Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author:  $'
7
 *     '$Date:  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.IOException;
27
import java.io.InputStream;
28
import java.security.NoSuchAlgorithmException;
29
import java.sql.SQLException;
30
import java.util.ArrayList;
31
import java.util.Calendar;
32
import java.util.Date;
33
import java.util.List;
34
import java.util.Timer;
35

    
36
import javax.servlet.http.HttpServletRequest;
37

    
38
import org.apache.commons.io.IOUtils;
39
import org.apache.log4j.Logger;
40
import org.dataone.client.CNode;
41
import org.dataone.client.D1Client;
42
import org.dataone.client.MNode;
43
import org.dataone.client.auth.CertificateManager;
44
import org.dataone.configuration.Settings;
45
import org.dataone.service.exceptions.IdentifierNotUnique;
46
import org.dataone.service.exceptions.InsufficientResources;
47
import org.dataone.service.exceptions.InvalidRequest;
48
import org.dataone.service.exceptions.InvalidSystemMetadata;
49
import org.dataone.service.exceptions.InvalidToken;
50
import org.dataone.service.exceptions.NotAuthorized;
51
import org.dataone.service.exceptions.NotFound;
52
import org.dataone.service.exceptions.NotImplemented;
53
import org.dataone.service.exceptions.ServiceFailure;
54
import org.dataone.service.exceptions.SynchronizationFailed;
55
import org.dataone.service.exceptions.UnsupportedType;
56
import org.dataone.service.exceptions.VersionMismatch;
57
import org.dataone.service.mn.tier1.v1.MNCore;
58
import org.dataone.service.mn.tier1.v1.MNRead;
59
import org.dataone.service.mn.tier2.v1.MNAuthorization;
60
import org.dataone.service.mn.tier3.v1.MNStorage;
61
import org.dataone.service.mn.tier4.v1.MNReplication;
62
import org.dataone.service.types.v1.AccessPolicy;
63
import org.dataone.service.types.v1.Checksum;
64
import org.dataone.service.types.v1.DescribeResponse;
65
import org.dataone.service.types.v1.Event;
66
import org.dataone.service.types.v1.Group;
67
import org.dataone.service.types.v1.Identifier;
68
import org.dataone.service.types.v1.Log;
69
import org.dataone.service.types.v1.LogEntry;
70
import org.dataone.service.types.v1.MonitorInfo;
71
import org.dataone.service.types.v1.MonitorList;
72
import org.dataone.service.types.v1.Node;
73
import org.dataone.service.types.v1.NodeList;
74
import org.dataone.service.types.v1.NodeReference;
75
import org.dataone.service.types.v1.NodeState;
76
import org.dataone.service.types.v1.NodeType;
77
import org.dataone.service.types.v1.ObjectFormatIdentifier;
78
import org.dataone.service.types.v1.ObjectList;
79
import org.dataone.service.types.v1.Permission;
80
import org.dataone.service.types.v1.Ping;
81
import org.dataone.service.types.v1.ReplicationStatus;
82
import org.dataone.service.types.v1.Schedule;
83
import org.dataone.service.types.v1.Service;
84
import org.dataone.service.types.v1.Services;
85
import org.dataone.service.types.v1.Session;
86
import org.dataone.service.types.v1.Subject;
87
import org.dataone.service.types.v1.SubjectList;
88
import org.dataone.service.types.v1.Synchronization;
89
import org.dataone.service.types.v1.SystemMetadata;
90
import org.dataone.service.types.v1.util.ChecksumUtil;
91
import org.dataone.service.util.Constants;
92

    
93
import edu.ucsb.nceas.metacat.DocumentImpl;
94
import edu.ucsb.nceas.metacat.EventLog;
95
import edu.ucsb.nceas.metacat.IdentifierManager;
96
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
97
import edu.ucsb.nceas.metacat.MetacatHandler;
98
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
99
import edu.ucsb.nceas.metacat.database.DBConnection;
100
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
101
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
102
import edu.ucsb.nceas.metacat.properties.PropertyService;
103
import edu.ucsb.nceas.metacat.util.SystemUtil;
104
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
105

    
106
/**
107
 * Represents Metacat's implementation of the DataONE Member Node 
108
 * service API. Methods implement the various MN* interfaces, and methods common
109
 * to both Member Node and Coordinating Node interfaces are found in the
110
 * D1NodeService base class.
111
 * 
112
 * Implements:
113
 * MNCore.ping()
114
 * MNCore.getLogRecords()
115
 * MNCore.getObjectStatistics()
116
 * MNCore.getOperationStatistics()
117
 * MNCore.getStatus()
118
 * MNCore.getCapabilities()
119
 * MNRead.get()
120
 * MNRead.getSystemMetadata()
121
 * MNRead.describe()
122
 * MNRead.getChecksum()
123
 * MNRead.listObjects()
124
 * MNRead.synchronizationFailed()
125
 * MNAuthorization.isAuthorized()
126
 * MNAuthorization.setAccessPolicy()
127
 * MNStorage.create()
128
 * MNStorage.update()
129
 * MNStorage.delete()
130
 * MNReplication.replicate()
131
 * 
132
 */
133
public class MNodeService extends D1NodeService 
134
    implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage {
135

    
136
    /* the logger instance */
137
    private Logger logMetacat = null;
138

    
139
    /**
140
     * Singleton accessor to get an instance of MNodeService.
141
     * 
142
     * @return instance - the instance of MNodeService
143
     */
144
    public static MNodeService getInstance(HttpServletRequest request) {
145
        return new MNodeService(request);
146
    }
147

    
148
    /**
149
     * Constructor, private for singleton access
150
     */
151
    private MNodeService(HttpServletRequest request) {
152
        super(request);
153
        logMetacat = Logger.getLogger(MNodeService.class);
154
        
155
        // set the Member Node certificate file location
156
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
157
    }
158

    
159
    /**
160
     * Deletes an object from the Member Node, where the object is either a 
161
     * data object or a science metadata object.
162
     * 
163
     * @param session - the Session object containing the credentials for the Subject
164
     * @param pid - The object identifier to be deleted
165
     * 
166
     * @return pid - the identifier of the object used for the deletion
167
     * 
168
     * @throws InvalidToken
169
     * @throws ServiceFailure
170
     * @throws NotAuthorized
171
     * @throws NotFound
172
     * @throws NotImplemented
173
     * @throws InvalidRequest
174
     */
175
    @Override
176
    public Identifier delete(Session session, Identifier pid) 
177
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
178

    
179
        String localId = null;
180
        boolean allowed = false;
181
        String username = Constants.SUBJECT_PUBLIC;
182
        String[] groupnames = null;
183
        if (session == null) {
184
        	throw new InvalidToken("1330", "No session has been provided");
185
        } else {
186
            username = session.getSubject().getValue();
187
            if (session.getSubjectInfo() != null) {
188
                List<Group> groupList = session.getSubjectInfo().getGroupList();
189
                if (groupList != null) {
190
                    groupnames = new String[groupList.size()];
191
                    for (int i = 0; i > groupList.size(); i++) {
192
                        groupnames[i] = groupList.get(i).getGroupName();
193
                    }
194
                }
195
            }
196
        }
197

    
198
        // do we have a valid pid?
199
        if (pid == null || pid.getValue().trim().equals("")) {
200
            throw new ServiceFailure("1350", "The provided identifier was invalid.");
201
        }
202

    
203
        // check for the existing identifier
204
        try {
205
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
206
        } catch (McdbDocNotFoundException e) {
207
            throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
208
        }
209

    
210
        // does the subject have DELETE (a D1 CHANGE_PERMISSION level) priveleges on the pid?
211
        allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
212
            
213

    
214
        if (allowed) {
215
            try {
216
                // delete the document
217
                DocumentImpl.delete(localId, username, groupnames, null);
218
                EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
219

    
220
                // remove the system metadata for it
221
                HazelcastService.getInstance().getSystemMetadataMap().remove(pid);
222
                
223
            } catch (McdbDocNotFoundException e) {
224
                throw new NotFound("1340", "The provided identifier was invalid.");
225

    
226
            } catch (SQLException e) {
227
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
228

    
229
            } catch (InsufficientKarmaException e) {
230
                throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
231

    
232
            } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
233
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
234
            }
235

    
236
        } else {
237
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
238
        }
239

    
240
        return pid;
241
    }
242

    
243
    /**
244
     * Updates an existing object by creating a new object identified by 
245
     * newPid on the Member Node which explicitly obsoletes the object 
246
     * identified by pid through appropriate changes to the SystemMetadata 
247
     * of pid and newPid
248
     * 
249
     * @param session - the Session object containing the credentials for the Subject
250
     * @param pid - The identifier of the object to be updated
251
     * @param object - the new object bytes
252
     * @param sysmeta - the new system metadata describing the object
253
     * 
254
     * @return newPid - the identifier of the new object
255
     * 
256
     * @throws InvalidToken
257
     * @throws ServiceFailure
258
     * @throws NotAuthorized
259
     * @throws NotFound
260
     * @throws NotImplemented
261
     * @throws IdentifierNotUnique
262
     * @throws UnsupportedType
263
     * @throws InsufficientResources
264
     * @throws InvalidSystemMetadata
265
     * @throws InvalidRequest
266
     */
267
    @Override
268
    public Identifier update(Session session, Identifier pid, InputStream object, 
269
        Identifier newPid, SystemMetadata sysmeta) 
270
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
271
        UnsupportedType, InsufficientResources, NotFound, 
272
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
273

    
274
        String localId = null;
275
        boolean allowed = false;
276
        boolean isScienceMetadata = false;
277
        
278
        if (session == null) {
279
        	throw new InvalidToken("1210", "No session has been provided");
280
        }
281
        Subject subject = session.getSubject();
282

    
283
        // do we have a valid pid?
284
        if (pid == null || pid.getValue().trim().equals("")) {
285
            throw new InvalidRequest("1202", "The provided identifier was invalid.");
286
            
287
        }
288

    
289
        // check for the existing identifier
290
        try {
291
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
292
            
293
        } catch (McdbDocNotFoundException e) {
294
            throw new InvalidRequest("1202", "The object with the provided " + 
295
                "identifier was not found.");
296
            
297
        }
298
        
299
        // set the originating node
300
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
301
        sysmeta.setOriginMemberNode(originMemberNode);
302
        
303
        // set the submitter to match the certificate
304
        sysmeta.setSubmitter(subject);
305
        // set the dates
306
        Date now = Calendar.getInstance().getTime();
307
        sysmeta.setDateSysMetadataModified(now);
308
        sysmeta.setDateUploaded(now);
309

    
310
        // does the subject have WRITE ( == update) priveleges on the pid?
311
        allowed = isAuthorized(session, pid, Permission.WRITE);
312

    
313
        if (allowed) {
314
        	
315
        	// check quality of SM
316
        	if (sysmeta.getObsoletedBy() != null) {
317
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
318
        	}
319
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
320
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
321
        	}
322

    
323
            // get the existing system metadata for the object
324
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
325

    
326
            // add the newPid to the obsoletedBy list for the existing sysmeta
327
            existingSysMeta.setObsoletedBy(newPid);
328

    
329
            // then update the existing system metadata
330
            updateSystemMetadata(existingSysMeta);
331

    
332
            // prep the new system metadata, add pid to the affected lists
333
            sysmeta.setObsoletes(pid);
334
            //sysmeta.addDerivedFrom(pid);
335

    
336
            isScienceMetadata = isScienceMetadata(sysmeta);
337

    
338
            // do we have XML metadata or a data object?
339
            if (isScienceMetadata) {
340

    
341
                // update the science metadata XML document
342
                // TODO: handle non-XML metadata/data documents (like netCDF)
343
                // TODO: don't put objects into memory using stream to string
344
                String objectAsXML = "";
345
                try {
346
                    objectAsXML = IOUtils.toString(object, "UTF-8");
347
                    localId = insertOrUpdateDocument(objectAsXML, newPid, session, "update");
348
                    // register the newPid and the generated localId
349
                    if (newPid != null) {
350
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
351

    
352
                    }
353

    
354
                } catch (IOException e) {
355
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
356
                    logMetacat.info(msg);
357
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
358

    
359
                }
360

    
361
            } else {
362

    
363
                // update the data object
364
                localId = insertDataObject(object, newPid, session);
365

    
366
            }
367

    
368
            // and insert the new system metadata
369
            insertSystemMetadata(sysmeta);
370

    
371
            // log the update event
372
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
373

    
374
        } else {
375
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
376
                    + " on the Member Node.");
377
        }
378

    
379
        return newPid;
380
    }
381

    
382
    public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
383
            IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
384

    
385
      // check for null session
386
        if (session == null) {
387
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
388
        }
389
        // set the submitter to match the certificate
390
        sysmeta.setSubmitter(session.getSubject());
391
        // set the originating node
392
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
393
        sysmeta.setOriginMemberNode(originMemberNode);
394
        // set the dates
395
        Date now = Calendar.getInstance().getTime();
396
    sysmeta.setDateSysMetadataModified(now);
397
    sysmeta.setDateUploaded(now);
398
        // call the shared impl
399
        return super.create(session, pid, object, sysmeta);
400
    }
401

    
402
    /**
403
     * Called by a Coordinating Node to request that the Member Node create a 
404
     * copy of the specified object by retrieving it from another Member 
405
     * Node and storing it locally so that it can be made accessible to 
406
     * the DataONE system.
407
     * 
408
     * @param session - the Session object containing the credentials for the Subject
409
     * @param sysmeta - Copy of the CN held system metadata for the object
410
     * @param sourceNode - A reference to node from which the content should be 
411
     *                     retrieved. The reference should be resolved by 
412
     *                     checking the CN node registry.
413
     * 
414
     * @return true if the replication succeeds
415
     * 
416
     * @throws ServiceFailure
417
     * @throws NotAuthorized
418
     * @throws NotImplemented
419
     * @throws UnsupportedType
420
     * @throws InsufficientResources
421
     * @throws InvalidRequest
422
     */
423
    @Override
424
    public boolean replicate(Session session, SystemMetadata sysmeta, NodeReference sourceNode) 
425
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, 
426
        InsufficientResources, UnsupportedType {
427

    
428
        logMetacat.info("MNodeService.replicate() called with parameters: \n" +
429
            "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
430
            "\tSystemMetadata       = " + sysmeta.toString()              + "\n" +
431
            "\tSource NodeReference ="  + sourceNode.getValue());
432
        
433
        boolean result = false;
434
        String nodeIdStr  = null;
435
        NodeReference nodeId = null;
436
        
437
        // get the local node id
438
        try {
439
            nodeIdStr = PropertyService.getProperty("dataone.memberNodeId");
440
            nodeId = new NodeReference();
441
            nodeId.setValue(nodeIdStr);
442
            
443
        } catch (PropertyNotFoundException e1) {
444
            logMetacat.error("Couldn't get dataone.memberNodeId property: " + 
445
                e1.getMessage());
446
            
447
        }
448
        // TODO: check credentials
449

    
450
        // get the referenced object
451
        Identifier pid = sysmeta.getIdentifier();
452

    
453
        // get from the membernode
454
        // TODO: switch credentials for the server retrieval?
455
        MNode mn = D1Client.getMN(sourceNode);
456
        CNode cn = D1Client.getCN();
457
        long serialVersion = sysmeta.getSerialVersion().longValue();
458
        InputStream object = null;
459
        Session thisNodeSession = null;
460
        
461
        try {
462
          // session should be null to use the default certificate location set in the Certificate manager
463
            object = mn.getReplica(thisNodeSession, pid);
464
            logMetacat.info("MNodeService.replicate() called for identifier " + pid.getValue());
465

    
466
        } catch (InvalidToken e) {
467
            e.printStackTrace();
468
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
469
        } catch (NotFound e) {
470
            e.printStackTrace();
471
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
472
        }
473

    
474
        // add it to local store
475
        Identifier retPid;
476
        try {
477
          // skip the MN.create -- this mutates the system metadata and we dont want it to
478
            retPid = super.create(session, pid, object, sysmeta);
479
            result = (retPid.getValue().equals(pid.getValue()));
480
        } catch (InvalidToken e) {
481
            e.printStackTrace();
482
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
483
        } catch (IdentifierNotUnique e) {
484
            e.printStackTrace();
485
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
486
        } catch (InvalidSystemMetadata e) {
487
            e.printStackTrace();
488
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
489
        }
490

    
491
        try {
492
          // call the CN as the MN to set the replication status
493
            cn.setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, serialVersion);
494
            
495
        } catch (InvalidToken e) {
496
            // TODO Auto-generated catch block
497
            e.printStackTrace();
498
        } catch (NotFound e) {
499
            // TODO Auto-generated catch block
500
            e.printStackTrace();
501
        } catch (VersionMismatch e) {
502
			// TODO Auto-generated catch block
503
			e.printStackTrace();
504
		}
505
        return result;
506

    
507
    }
508

    
509
    /**
510
     * This method provides a lighter weight mechanism than 
511
     * MN_read.getSystemMetadata() for a client to determine basic 
512
     * properties of the referenced object.
513
     * 
514
     * @param session - the Session object containing the credentials for the Subject
515
     * @param pid - the identifier of the object to be described
516
     * 
517
     * @return describeResponse - A set of values providing a basic description 
518
     *                            of the object.
519
     * 
520
     * @throws InvalidToken
521
     * @throws ServiceFailure
522
     * @throws NotAuthorized
523
     * @throws NotFound
524
     * @throws NotImplemented
525
     * @throws InvalidRequest
526
     */
527
    @Override
528
    public DescribeResponse describe(Session session, Identifier pid) 
529
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
530

    
531
      // get system metadata and construct the describe response
532
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
533
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
534
                sysmeta.getChecksum());
535

    
536
        return describeResponse;
537

    
538
    }
539

    
540
    /**
541
     * Return the object identified by the given object identifier
542
     * 
543
     * @param session - the Session object containing the credentials for the Subject
544
     * @param pid - the object identifier for the given object
545
     * 
546
     * @return inputStream - the input stream of the given object
547
     * 
548
     * @throws InvalidToken
549
     * @throws ServiceFailure
550
     * @throws NotAuthorized
551
     * @throws InvalidRequest
552
     * @throws NotImplemented
553
     */
554
    @Override
555
    public InputStream get(Session session, Identifier pid) 
556
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
557

    
558
        return super.get(session, pid);
559

    
560
    }
561

    
562
    /**
563
     * Returns a Checksum for the specified object using an accepted hashing algorithm
564
     * 
565
     * @param session - the Session object containing the credentials for the Subject
566
     * @param pid - the object identifier for the given object
567
     * @param algorithm -  the name of an algorithm that will be used to compute 
568
     *                     a checksum of the bytes of the object
569
     * 
570
     * @return checksum - the checksum of the given object
571
     * 
572
     * @throws InvalidToken
573
     * @throws ServiceFailure
574
     * @throws NotAuthorized
575
     * @throws NotFound
576
     * @throws InvalidRequest
577
     * @throws NotImplemented
578
     */
579
    @Override
580
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
581
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
582
        InvalidRequest, NotImplemented {
583

    
584
        Checksum checksum = null;
585

    
586
        InputStream inputStream = get(session, pid);
587

    
588
        try {
589
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
590

    
591
        } catch (NoSuchAlgorithmException e) {
592
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
593
                    + e.getMessage());
594
        } catch (IOException e) {
595
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
596
                    + e.getMessage());
597
        }
598

    
599
        if (checksum == null) {
600
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
601
        }
602

    
603
        return checksum;
604
    }
605

    
606
    /**
607
     * Return the system metadata for a given object
608
     * 
609
     * @param session - the Session object containing the credentials for the Subject
610
     * @param pid - the object identifier for the given object
611
     * 
612
     * @return inputStream - the input stream of the given system metadata object
613
     * 
614
     * @throws InvalidToken
615
     * @throws ServiceFailure
616
     * @throws NotAuthorized
617
     * @throws NotFound
618
     * @throws InvalidRequest
619
     * @throws NotImplemented
620
     */
621
    @Override
622
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
623
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
624
        NotImplemented {
625

    
626
        return super.getSystemMetadata(session, pid);
627
    }
628

    
629
    /**
630
     * Retrieve the list of objects present on the MN that match the calling parameters
631
     * 
632
     * @param session - the Session object containing the credentials for the Subject
633
     * @param startTime - Specifies the beginning of the time range from which 
634
     *                    to return object (>=)
635
     * @param endTime - Specifies the beginning of the time range from which 
636
     *                  to return object (>=)
637
     * @param objectFormat - Restrict results to the specified object format
638
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
639
     * @param start - The zero-based index of the first value, relative to the 
640
     *                first record of the resultset that matches the parameters.
641
     * @param count - The maximum number of entries that should be returned in 
642
     *                the response. The Member Node may return less entries 
643
     *                than specified in this value.
644
     * 
645
     * @return objectList - the list of objects matching the criteria
646
     * 
647
     * @throws InvalidToken
648
     * @throws ServiceFailure
649
     * @throws NotAuthorized
650
     * @throws InvalidRequest
651
     * @throws NotImplemented
652
     */
653
    @Override
654
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
655
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
656

    
657
        ObjectList objectList = null;
658

    
659
        try {
660
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
661
        } catch (Exception e) {
662
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
663
        }
664

    
665
        return objectList;
666
    }
667

    
668
    /**
669
     * Return a description of the node's capabilities and services.
670
     * 
671
     * @return node - the technical capabilities of the Member Node
672
     * 
673
     * @throws ServiceFailure
674
     * @throws NotAuthorized
675
     * @throws InvalidRequest
676
     * @throws NotImplemented
677
     */
678
    @Override
679
    public Node getCapabilities() 
680
        throws NotImplemented, ServiceFailure {
681

    
682
        String nodeName = null;
683
        String nodeId = null;
684
        String subject = null;
685
        String nodeDesc = null;
686
        String nodeTypeString = null;
687
        NodeType nodeType = null;
688
        String mnCoreServiceVersion = null;
689
        String mnReadServiceVersion = null;
690
        String mnAuthorizationServiceVersion = null;
691
        String mnStorageServiceVersion = null;
692
        String mnReplicationServiceVersion = null;
693

    
694
        boolean nodeSynchronize = false;
695
        boolean nodeReplicate = false;
696
        boolean mnCoreServiceAvailable = false;
697
        boolean mnReadServiceAvailable = false;
698
        boolean mnAuthorizationServiceAvailable = false;
699
        boolean mnStorageServiceAvailable = false;
700
        boolean mnReplicationServiceAvailable = false;
701

    
702
        try {
703
            // get the properties of the node based on configuration information
704
            nodeName = PropertyService.getProperty("dataone.nodeName");
705
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
706
            subject = PropertyService.getProperty("dataone.subject");
707
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
708
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
709
            nodeType = NodeType.convert(nodeTypeString);
710
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
711
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
712

    
713
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
714
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
715
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
716
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
717
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
718

    
719
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
720
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
721
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
722
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
723
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
724

    
725
            // Set the properties of the node based on configuration information and
726
            // calls to current status methods
727
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
728
            Node node = new Node();
729
            node.setBaseURL(serviceName + "/" + nodeTypeString);
730
            node.setDescription(nodeDesc);
731

    
732
            // set the node's health information
733
            node.setState(NodeState.UP);
734
            
735
            // set the ping response to the current value
736
            Ping canPing = new Ping();
737
            canPing.setSuccess(false);
738
            try {
739
                canPing.setSuccess(ping());
740
            } catch (InsufficientResources e) {
741
                e.printStackTrace();
742
            }
743
            
744
            node.setPing(canPing);
745

    
746
            NodeReference identifier = new NodeReference();
747
            identifier.setValue(nodeId);
748
            node.setIdentifier(identifier);
749
            Subject s = new Subject();
750
            s.setValue(subject);
751
            node.addSubject(s);
752
            node.setName(nodeName);
753
            node.setReplicate(nodeReplicate);
754
            node.setSynchronize(nodeSynchronize);
755

    
756
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
757
            Services services = new Services();
758

    
759
            Service sMNCore = new Service();
760
            sMNCore.setName("MNCore");
761
            sMNCore.setVersion(mnCoreServiceVersion);
762
            sMNCore.setAvailable(mnCoreServiceAvailable);
763

    
764
            Service sMNRead = new Service();
765
            sMNRead.setName("MNRead");
766
            sMNRead.setVersion(mnReadServiceVersion);
767
            sMNRead.setAvailable(mnReadServiceAvailable);
768

    
769
            Service sMNAuthorization = new Service();
770
            sMNAuthorization.setName("MNAuthorization");
771
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
772
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
773

    
774
            Service sMNStorage = new Service();
775
            sMNStorage.setName("MNStorage");
776
            sMNStorage.setVersion(mnStorageServiceVersion);
777
            sMNStorage.setAvailable(mnStorageServiceAvailable);
778

    
779
            Service sMNReplication = new Service();
780
            sMNReplication.setName("MNReplication");
781
            sMNReplication.setVersion(mnReplicationServiceVersion);
782
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
783

    
784
            services.addService(sMNRead);
785
            services.addService(sMNCore);
786
            services.addService(sMNAuthorization);
787
            services.addService(sMNStorage);
788
            services.addService(sMNReplication);
789
            node.setServices(services);
790

    
791
            // TODO: Allow the metacat admin to determine the schedule
792
            // Set the schedule for synchronization
793
            Synchronization synchronization = new Synchronization();
794
            Schedule schedule = new Schedule();
795
            Date now = new Date();
796
            schedule.setYear("*");
797
            schedule.setMon("*");
798
            schedule.setMday("*");
799
            schedule.setWday("?");
800
            schedule.setHour("*");
801
            schedule.setMin("0/3");
802
            schedule.setSec("10");
803
            synchronization.setSchedule(schedule);
804
            synchronization.setLastHarvested(now);
805
            synchronization.setLastCompleteHarvest(now);
806
            node.setSynchronization(synchronization);
807

    
808
            node.setType(nodeType);
809
            return node;
810

    
811
        } catch (PropertyNotFoundException pnfe) {
812
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
813
            logMetacat.error(msg);
814
            throw new ServiceFailure("2162", msg);
815
        }
816
    }
817

    
818
    /**
819
     * Returns the number of operations that have been serviced by the node 
820
     * over time periods of one and 24 hours.
821
     * 
822
     * @param session - the Session object containing the credentials for the Subject
823
     * @param period - An ISO8601 compatible DateTime range specifying the time 
824
     *                 range for which to return operation statistics.
825
     * @param requestor - Limit to operations performed by given requestor identity.
826
     * @param event -  Enumerated value indicating the type of event being examined
827
     * @param format - Limit to events involving objects of the specified format
828
     * 
829
     * @return the desired log records
830
     * 
831
     * @throws InvalidToken
832
     * @throws ServiceFailure
833
     * @throws NotAuthorized
834
     * @throws InvalidRequest
835
     * @throws NotImplemented
836
     */
837
    public MonitorList getOperationStatistics(Session session, Date startTime, 
838
        Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
839
        throws NotImplemented, ServiceFailure, NotAuthorized, InsufficientResources, UnsupportedType {
840

    
841
        MonitorList monitorList = new MonitorList();
842

    
843
        try {
844

    
845
            // get log records first
846
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
847

    
848
            // TODO: aggregate by day or hour -- needs clarification
849
            int count = 1;
850
            for (LogEntry logEntry : logs.getLogEntryList()) {
851
                Identifier pid = logEntry.getIdentifier();
852
                Date logDate = logEntry.getDateLogged();
853
                // if we are filtering by format
854
                if (formatId != null) {
855
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
856
                    if (!sysmeta.getFormatId().getValue().equals(formatId.getValue())) {
857
                        // does not match
858
                        continue;
859
                    }
860
                }
861
                MonitorInfo item = new MonitorInfo();
862
                item.setCount(count);
863
                item.setDate(new java.sql.Date(logDate.getTime()));
864
                monitorList.addMonitorInfo(item);
865

    
866
            }
867
        } catch (Exception e) {
868
            e.printStackTrace();
869
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
870
        }
871

    
872
        return monitorList;
873

    
874
    }
875

    
876
    /**
877
     * Low level “are you alive” operation. A valid ping response is 
878
     * indicated by a HTTP status of 200.
879
     * 
880
     * @return true if the service is alive
881
     * 
882
     * @throws InvalidToken
883
     * @throws ServiceFailure
884
     * @throws NotImplemented
885
     */
886
    @Override
887
    public boolean ping() 
888
        throws NotImplemented, ServiceFailure, InsufficientResources {
889

    
890
        // test if we can get a database connection
891
        boolean alive = false;
892
        int serialNumber = -1;
893
        DBConnection dbConn = null;
894
        try {
895
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
896
            serialNumber = dbConn.getCheckOutSerialNumber();
897
            alive = true;
898
        } catch (SQLException e) {
899
            return alive;
900
        } finally {
901
            // Return the database connection
902
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
903
        }
904

    
905
        return alive;
906
    }
907

    
908
    /**
909
     * A callback method used by a CN to indicate to a MN that it cannot 
910
     * complete synchronization of the science metadata identified by pid.  Log
911
     * the event in the metacat event log.
912
     * 
913
     * @param session
914
     * @param syncFailed
915
     * 
916
     * @throws ServiceFailure
917
     * @throws NotAuthorized
918
     * @throws NotImplemented
919
     */
920
    @Override
921
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
922
        throws NotImplemented, ServiceFailure, NotAuthorized {
923

    
924
        String localId;
925

    
926
        try {
927
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
928
        } catch (McdbDocNotFoundException e) {
929
            throw new ServiceFailure("2161", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
930

    
931
        }
932
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
933
        // method is changed to include the URL as a parameter
934
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
935
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
936
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
937
        String principal = Constants.SUBJECT_PUBLIC;
938
        if (session != null && session.getSubject() != null) {
939
          principal = session.getSubject().getValue();
940
        }
941
        try {
942
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
943
        } catch (Exception e) {
944
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
945
    }
946
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
947
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
948

    
949
    }
950

    
951
    /**
952
     * Essentially a get() but with different logging behavior
953
     */
954
    @Override
955
    public InputStream getReplica(Session session, Identifier pid) 
956
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken {
957

    
958
        logMetacat.info("MNodeService.getReplica() called.");
959

    
960
        // cannot be called by public
961
        if (session == null) {
962
        	throw new InvalidToken("2183", "No session was provided.");
963
        }
964
        
965
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
966
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
967
             "\tIdentifier           = " + pid.getValue());
968

    
969
        InputStream inputStream = null; // bytes to be returned
970
        handler = new MetacatHandler(new Timer());
971
        boolean allowed = false;
972
        String localId; // the metacat docid for the pid
973

    
974
        // get the local docid from Metacat
975
        try {
976
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
977
        } catch (McdbDocNotFoundException e) {
978
            throw new ServiceFailure("2181", "The object specified by " + 
979
                    pid.getValue() + " does not exist at this node.");
980
            
981
        }
982

    
983
        Subject targetNodeSubject = session.getSubject();
984

    
985
        // check for authorization to replicate, null session to act as this source MN
986
        try {
987
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid, Permission.REPLICATE);
988
        } catch (InvalidToken e1) {
989
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
990
                + e1.getMessage());
991
            
992
        } catch (NotFound e1) {
993
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
994
                    + e1.getMessage());
995

    
996
        } catch (InvalidRequest e1) {
997
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
998
                    + e1.getMessage());
999

    
1000
        }
1001

    
1002
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1003
            " for identifier " + pid.getValue());
1004

    
1005
        // if the person is authorized, perform the read
1006
        if (allowed) {
1007
            try {
1008
                inputStream = handler.read(localId);
1009
            } catch (Exception e) {
1010
                throw new ServiceFailure("1020", "The object specified by " + 
1011
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1012
            }
1013
        }
1014

    
1015
        // if we fail to set the input stream
1016
        if (inputStream == null) {
1017
            throw new ServiceFailure("2181", "The object specified by " + 
1018
                pid.getValue() + "does not exist at this node.");
1019
        }
1020

    
1021
        // log the replica event
1022
        String principal = null;
1023
        if (session.getSubject() != null) {
1024
            principal = session.getSubject().getValue();
1025
        }
1026
        EventLog.getInstance().log(request.getRemoteAddr(), 
1027
            request.getHeader("User-Agent"), principal, localId, "replicate");
1028

    
1029
        return inputStream;
1030
    }
1031

    
1032
    /**
1033
     * Set the access policy
1034
     */
1035
    @Deprecated
1036
    @Override
1037
    public boolean setAccessPolicy(Session session, Identifier pid,
1038
        AccessPolicy policy) 
1039
        throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
1040
        NotImplemented, InvalidRequest {
1041
        
1042
        throw new NotImplemented("4401", "This method is deprecated for Member Nodes.");
1043
        
1044
    }
1045

    
1046
    /**
1047
     * A method to notify the Member Node that the authoritative copy of 
1048
     * system metadata on the Coordinating Nodes has changed.
1049
     * 
1050
     * @param session   Session information that contains the identity of the 
1051
     *                  calling user as retrieved from the X.509 certificate 
1052
     *                  which must be traceable to the CILogon service.
1053
     * @param serialVersion   The serialVersion of the system metadata
1054
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1055
     * @throws NotImplemented
1056
     * @throws ServiceFailure
1057
     * @throws NotAuthorized
1058
     * @throws InvalidRequest
1059
     * @throws InvalidToken
1060
     */
1061
    public void systemMetadataChanged(Session session, Identifier pid,
1062
        long serialVersion, Date dateSysMetaLastModified) 
1063
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1064
        InvalidToken {
1065
        
1066
        SystemMetadata currentLocalSysMeta = null;
1067
        SystemMetadata newSysMeta = null;
1068
        CNode cn = D1Client.getCN();
1069
        NodeList nodeList = null;
1070
        Subject callingSubject = null;
1071
        boolean allowed = false;
1072
        
1073
        // are we allowed to call this?
1074
        callingSubject = session.getSubject();
1075
        nodeList = cn.listNodes();
1076
        
1077
        for(Node node : nodeList.getNodeList()) {
1078
            // must be a CN
1079
            if ( node.getType().equals(NodeType.CN)) {
1080
               List<Subject> subjectList = node.getSubjectList();
1081
               // the calling subject must be in the subject list
1082
               if ( subjectList.contains(callingSubject)) {
1083
                   allowed = true;
1084
                   
1085
               }
1086
               
1087
            }
1088
        }
1089
        
1090
        if (!allowed ) {
1091
            String msg = "The subject identified by " + callingSubject.getValue() +
1092
              " is not authorized to call this service.";
1093
            throw new NotAuthorized("1331", msg);
1094
            
1095
        }
1096
        
1097
        // compare what we have locally to what is sent in the change notification
1098
        try {
1099
            currentLocalSysMeta = 
1100
                IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
1101
        
1102
        } catch (McdbDocNotFoundException e) {
1103
            String msg = "SystemMetadata for pid " + pid.getValue() +
1104
              " cpouldn't be updated because it couldn't be found locally: " +
1105
              e.getMessage();
1106
            logMetacat.warn(msg);
1107
            
1108
        }
1109
        
1110
        if (currentLocalSysMeta.getSerialVersion().longValue() < serialVersion ) {
1111
            try {
1112
                newSysMeta = cn.getSystemMetadata(null, pid);
1113
            } catch (NotFound e) {
1114
                // huh? you just said you had it
1115
                logMetacat.error("On updating the local copy of system metadata " + 
1116
                    "for pid " + pid.getValue() +", the CN reports it is not found." +
1117
                    " The error message was: " + e.getMessage());
1118
                
1119
            }
1120
            // update the local copy of system metadata for the pid
1121
            try {
1122
                IdentifierManager.getInstance().updateSystemMetadata(newSysMeta);
1123
                logMetacat.info("Updated local copy of system metadata for pid " +
1124
                    pid.getValue() + " after change notification from the CN.");
1125
                
1126
            } catch (McdbDocNotFoundException e) {
1127
                String msg = "SystemMetadata for pid " + pid.getValue() +
1128
                  " cpouldn't be updated because it couldn't be found: " +
1129
                  e.getMessage();
1130
                logMetacat.warn(msg);
1131
                
1132
            }
1133
        }
1134
        
1135
    }
1136
    
1137
}
(3-3/4)