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

    
435
        // TODO: check credentials
436

    
437
        // get the referenced object
438
        Identifier pid = sysmeta.getIdentifier();
439

    
440
        // get from the membernode
441
        // TODO: switch credentials for the server retrieval?
442
        MNode mn = D1Client.getMN(sourceNode);
443
        CNode cn = D1Client.getCN();
444
        long serialVersion = sysmeta.getSerialVersion().longValue();
445
        InputStream object = null;
446
        Session thisNodeSession = null;
447
        
448
        try {
449
          // session should be null to use the default certificate location set in the Certificate manager
450
            object = mn.getReplica(thisNodeSession, pid);
451
            logMetacat.info("MNodeService.replicate() called for identifier " + pid.getValue());
452

    
453
        } catch (InvalidToken e) {
454
            e.printStackTrace();
455
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
456
        } catch (NotFound e) {
457
            e.printStackTrace();
458
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
459
        }
460

    
461
        // add it to local store
462
        Identifier retPid;
463
        try {
464
          // skip the MN.create -- this mutates the system metadata and we dont want it to
465
            retPid = super.create(session, pid, object, sysmeta);
466
            result = (retPid.getValue().equals(pid.getValue()));
467
        } catch (InvalidToken e) {
468
            e.printStackTrace();
469
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
470
        } catch (IdentifierNotUnique e) {
471
            e.printStackTrace();
472
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
473
        } catch (InvalidSystemMetadata e) {
474
            e.printStackTrace();
475
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
476
        }
477

    
478
        try {
479
          // call the CN as the MN to set the replication status
480
            cn.setReplicationStatus(thisNodeSession, pid, sourceNode, ReplicationStatus.COMPLETED, serialVersion);
481
            
482
        } catch (InvalidToken e) {
483
            // TODO Auto-generated catch block
484
            e.printStackTrace();
485
        } catch (NotFound e) {
486
            // TODO Auto-generated catch block
487
            e.printStackTrace();
488
        } catch (VersionMismatch e) {
489
			// TODO Auto-generated catch block
490
			e.printStackTrace();
491
		}
492
        return result;
493

    
494
    }
495

    
496
    /**
497
     * This method provides a lighter weight mechanism than 
498
     * MN_read.getSystemMetadata() for a client to determine basic 
499
     * properties of the referenced object.
500
     * 
501
     * @param session - the Session object containing the credentials for the Subject
502
     * @param pid - the identifier of the object to be described
503
     * 
504
     * @return describeResponse - A set of values providing a basic description 
505
     *                            of the object.
506
     * 
507
     * @throws InvalidToken
508
     * @throws ServiceFailure
509
     * @throws NotAuthorized
510
     * @throws NotFound
511
     * @throws NotImplemented
512
     * @throws InvalidRequest
513
     */
514
    @Override
515
    public DescribeResponse describe(Session session, Identifier pid) 
516
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
517

    
518
      // get system metadata and construct the describe response
519
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
520
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
521
                sysmeta.getChecksum());
522

    
523
        return describeResponse;
524

    
525
    }
526

    
527
    /**
528
     * Return the object identified by the given object identifier
529
     * 
530
     * @param session - the Session object containing the credentials for the Subject
531
     * @param pid - the object identifier for the given object
532
     * 
533
     * @return inputStream - the input stream of the given object
534
     * 
535
     * @throws InvalidToken
536
     * @throws ServiceFailure
537
     * @throws NotAuthorized
538
     * @throws InvalidRequest
539
     * @throws NotImplemented
540
     */
541
    @Override
542
    public InputStream get(Session session, Identifier pid) 
543
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
544

    
545
        return super.get(session, pid);
546

    
547
    }
548

    
549
    /**
550
     * Returns a Checksum for the specified object using an accepted hashing algorithm
551
     * 
552
     * @param session - the Session object containing the credentials for the Subject
553
     * @param pid - the object identifier for the given object
554
     * @param algorithm -  the name of an algorithm that will be used to compute 
555
     *                     a checksum of the bytes of the object
556
     * 
557
     * @return checksum - the checksum of the given object
558
     * 
559
     * @throws InvalidToken
560
     * @throws ServiceFailure
561
     * @throws NotAuthorized
562
     * @throws NotFound
563
     * @throws InvalidRequest
564
     * @throws NotImplemented
565
     */
566
    @Override
567
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
568
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
569
        InvalidRequest, NotImplemented {
570

    
571
        Checksum checksum = null;
572

    
573
        InputStream inputStream = get(session, pid);
574

    
575
        try {
576
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
577

    
578
        } catch (NoSuchAlgorithmException e) {
579
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
580
                    + e.getMessage());
581
        } catch (IOException e) {
582
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
583
                    + e.getMessage());
584
        }
585

    
586
        if (checksum == null) {
587
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
588
        }
589

    
590
        return checksum;
591
    }
592

    
593
    /**
594
     * Return the system metadata for a given object
595
     * 
596
     * @param session - the Session object containing the credentials for the Subject
597
     * @param pid - the object identifier for the given object
598
     * 
599
     * @return inputStream - the input stream of the given system metadata object
600
     * 
601
     * @throws InvalidToken
602
     * @throws ServiceFailure
603
     * @throws NotAuthorized
604
     * @throws NotFound
605
     * @throws InvalidRequest
606
     * @throws NotImplemented
607
     */
608
    @Override
609
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
610
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
611
        NotImplemented {
612

    
613
        return super.getSystemMetadata(session, pid);
614
    }
615

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

    
644
        ObjectList objectList = null;
645

    
646
        try {
647
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
648
        } catch (Exception e) {
649
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
650
        }
651

    
652
        return objectList;
653
    }
654

    
655
    /**
656
     * Return a description of the node's capabilities and services.
657
     * 
658
     * @return node - the technical capabilities of the Member Node
659
     * 
660
     * @throws ServiceFailure
661
     * @throws NotAuthorized
662
     * @throws InvalidRequest
663
     * @throws NotImplemented
664
     */
665
    @Override
666
    public Node getCapabilities() 
667
        throws NotImplemented, ServiceFailure {
668

    
669
        String nodeName = null;
670
        String nodeId = null;
671
        String subject = null;
672
        String nodeDesc = null;
673
        String nodeTypeString = null;
674
        NodeType nodeType = null;
675
        String mnCoreServiceVersion = null;
676
        String mnReadServiceVersion = null;
677
        String mnAuthorizationServiceVersion = null;
678
        String mnStorageServiceVersion = null;
679
        String mnReplicationServiceVersion = null;
680

    
681
        boolean nodeSynchronize = false;
682
        boolean nodeReplicate = false;
683
        boolean mnCoreServiceAvailable = false;
684
        boolean mnReadServiceAvailable = false;
685
        boolean mnAuthorizationServiceAvailable = false;
686
        boolean mnStorageServiceAvailable = false;
687
        boolean mnReplicationServiceAvailable = false;
688

    
689
        try {
690
            // get the properties of the node based on configuration information
691
            nodeName = PropertyService.getProperty("dataone.nodeName");
692
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
693
            subject = PropertyService.getProperty("dataone.subject");
694
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
695
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
696
            nodeType = NodeType.convert(nodeTypeString);
697
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
698
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
699

    
700
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
701
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
702
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
703
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
704
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
705

    
706
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
707
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
708
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
709
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
710
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
711

    
712
            // Set the properties of the node based on configuration information and
713
            // calls to current status methods
714
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
715
            Node node = new Node();
716
            node.setBaseURL(serviceName + "/" + nodeTypeString);
717
            node.setDescription(nodeDesc);
718

    
719
            // set the node's health information
720
            node.setState(NodeState.UP);
721
            
722
            // set the ping response to the current value
723
            Ping canPing = new Ping();
724
            canPing.setSuccess(false);
725
            try {
726
                canPing.setSuccess(ping());
727
            } catch (InsufficientResources e) {
728
                e.printStackTrace();
729
            }
730
            
731
            node.setPing(canPing);
732

    
733
            NodeReference identifier = new NodeReference();
734
            identifier.setValue(nodeId);
735
            node.setIdentifier(identifier);
736
            Subject s = new Subject();
737
            s.setValue(subject);
738
            node.addSubject(s);
739
            node.setName(nodeName);
740
            node.setReplicate(nodeReplicate);
741
            node.setSynchronize(nodeSynchronize);
742

    
743
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
744
            Services services = new Services();
745

    
746
            Service sMNCore = new Service();
747
            sMNCore.setName("MNCore");
748
            sMNCore.setVersion(mnCoreServiceVersion);
749
            sMNCore.setAvailable(mnCoreServiceAvailable);
750

    
751
            Service sMNRead = new Service();
752
            sMNRead.setName("MNRead");
753
            sMNRead.setVersion(mnReadServiceVersion);
754
            sMNRead.setAvailable(mnReadServiceAvailable);
755

    
756
            Service sMNAuthorization = new Service();
757
            sMNAuthorization.setName("MNAuthorization");
758
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
759
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
760

    
761
            Service sMNStorage = new Service();
762
            sMNStorage.setName("MNStorage");
763
            sMNStorage.setVersion(mnStorageServiceVersion);
764
            sMNStorage.setAvailable(mnStorageServiceAvailable);
765

    
766
            Service sMNReplication = new Service();
767
            sMNReplication.setName("MNReplication");
768
            sMNReplication.setVersion(mnReplicationServiceVersion);
769
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
770

    
771
            services.addService(sMNRead);
772
            services.addService(sMNCore);
773
            services.addService(sMNAuthorization);
774
            services.addService(sMNStorage);
775
            services.addService(sMNReplication);
776
            node.setServices(services);
777

    
778
            // TODO: Allow the metacat admin to determine the schedule
779
            // Set the schedule for synchronization
780
            Synchronization synchronization = new Synchronization();
781
            Schedule schedule = new Schedule();
782
            Date now = new Date();
783
            schedule.setYear("*");
784
            schedule.setMon("*");
785
            schedule.setMday("*");
786
            schedule.setWday("?");
787
            schedule.setHour("*");
788
            schedule.setMin("0/3");
789
            schedule.setSec("10");
790
            synchronization.setSchedule(schedule);
791
            synchronization.setLastHarvested(now);
792
            synchronization.setLastCompleteHarvest(now);
793
            node.setSynchronization(synchronization);
794

    
795
            node.setType(nodeType);
796
            return node;
797

    
798
        } catch (PropertyNotFoundException pnfe) {
799
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
800
            logMetacat.error(msg);
801
            throw new ServiceFailure("2162", msg);
802
        }
803
    }
804

    
805
    /**
806
     * Returns the number of operations that have been serviced by the node 
807
     * over time periods of one and 24 hours.
808
     * 
809
     * @param session - the Session object containing the credentials for the Subject
810
     * @param period - An ISO8601 compatible DateTime range specifying the time 
811
     *                 range for which to return operation statistics.
812
     * @param requestor - Limit to operations performed by given requestor identity.
813
     * @param event -  Enumerated value indicating the type of event being examined
814
     * @param format - Limit to events involving objects of the specified format
815
     * 
816
     * @return the desired log records
817
     * 
818
     * @throws InvalidToken
819
     * @throws ServiceFailure
820
     * @throws NotAuthorized
821
     * @throws InvalidRequest
822
     * @throws NotImplemented
823
     */
824
    public MonitorList getOperationStatistics(Session session, Date startTime, 
825
        Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
826
        throws NotImplemented, ServiceFailure, NotAuthorized, InsufficientResources, UnsupportedType {
827

    
828
        MonitorList monitorList = new MonitorList();
829

    
830
        try {
831

    
832
            // get log records first
833
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
834

    
835
            // TODO: aggregate by day or hour -- needs clarification
836
            int count = 1;
837
            for (LogEntry logEntry : logs.getLogEntryList()) {
838
                Identifier pid = logEntry.getIdentifier();
839
                Date logDate = logEntry.getDateLogged();
840
                // if we are filtering by format
841
                if (formatId != null) {
842
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
843
                    if (!sysmeta.getFormatId().getValue().equals(formatId.getValue())) {
844
                        // does not match
845
                        continue;
846
                    }
847
                }
848
                MonitorInfo item = new MonitorInfo();
849
                item.setCount(count);
850
                item.setDate(new java.sql.Date(logDate.getTime()));
851
                monitorList.addMonitorInfo(item);
852

    
853
            }
854
        } catch (Exception e) {
855
            e.printStackTrace();
856
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
857
        }
858

    
859
        return monitorList;
860

    
861
    }
862

    
863
    /**
864
     * Low level “are you alive” operation. A valid ping response is 
865
     * indicated by a HTTP status of 200.
866
     * 
867
     * @return true if the service is alive
868
     * 
869
     * @throws InvalidToken
870
     * @throws ServiceFailure
871
     * @throws NotImplemented
872
     */
873
    @Override
874
    public boolean ping() 
875
        throws NotImplemented, ServiceFailure, InsufficientResources {
876

    
877
        // test if we can get a database connection
878
        boolean alive = false;
879
        int serialNumber = -1;
880
        DBConnection dbConn = null;
881
        try {
882
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
883
            serialNumber = dbConn.getCheckOutSerialNumber();
884
            alive = true;
885
        } catch (SQLException e) {
886
            return alive;
887
        } finally {
888
            // Return the database connection
889
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
890
        }
891

    
892
        return alive;
893
    }
894

    
895
    /**
896
     * A callback method used by a CN to indicate to a MN that it cannot 
897
     * complete synchronization of the science metadata identified by pid.  Log
898
     * the event in the metacat event log.
899
     * 
900
     * @param session
901
     * @param syncFailed
902
     * 
903
     * @throws ServiceFailure
904
     * @throws NotAuthorized
905
     * @throws NotImplemented
906
     */
907
    @Override
908
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
909
        throws NotImplemented, ServiceFailure, NotAuthorized {
910

    
911
        String localId;
912

    
913
        try {
914
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
915
        } catch (McdbDocNotFoundException e) {
916
            throw new ServiceFailure("2161", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
917

    
918
        }
919
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
920
        // method is changed to include the URL as a parameter
921
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
922
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
923
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
924
        String principal = Constants.SUBJECT_PUBLIC;
925
        if (session != null && session.getSubject() != null) {
926
          principal = session.getSubject().getValue();
927
        }
928
        try {
929
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
930
        } catch (Exception e) {
931
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
932
    }
933
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
934
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
935

    
936
    }
937

    
938
    /**
939
     * Essentially a get() but with different logging behavior
940
     */
941
    @Override
942
    public InputStream getReplica(Session session, Identifier pid) 
943
        throws NotAuthorized, NotImplemented, ServiceFailure {
944

    
945
        logMetacat.info("MNodeService.getReplica() called.");
946

    
947
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
948
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
949
             "\tIdentifier           = " + pid.getValue());
950

    
951
        InputStream inputStream = null; // bytes to be returned
952
        handler = new MetacatHandler(new Timer());
953
        boolean allowed = false;
954
        String localId; // the metacat docid for the pid
955

    
956
        // get the local docid from Metacat
957
        try {
958
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
959
        } catch (McdbDocNotFoundException e) {
960
            throw new ServiceFailure("2181", "The object specified by " + 
961
                    pid.getValue() + " does not exist at this node.");
962
            
963
        }
964

    
965
        Subject targetNodeSubject = session.getSubject();
966

    
967
        // check for authorization to replicate, null session to act as this source MN
968
        try {
969
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid, Permission.REPLICATE);
970
        } catch (InvalidToken e1) {
971
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
972
                + e1.getMessage());
973
            
974
        } catch (NotFound e1) {
975
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
976
                    + e1.getMessage());
977

    
978
        } catch (InvalidRequest e1) {
979
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
980
                    + e1.getMessage());
981

    
982
        }
983

    
984
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
985
            " for identifier " + pid.getValue());
986

    
987
        // if the person is authorized, perform the read
988
        if (allowed) {
989
            try {
990
                inputStream = handler.read(localId);
991
            } catch (Exception e) {
992
                throw new ServiceFailure("1020", "The object specified by " + 
993
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
994
            }
995
        }
996

    
997
        // if we fail to set the input stream
998
        if (inputStream == null) {
999
            throw new ServiceFailure("2181", "The object specified by " + 
1000
                pid.getValue() + "does not exist at this node.");
1001
        }
1002

    
1003
        // log the replica event
1004
        String principal = null;
1005
        if (session.getSubject() != null) {
1006
            principal = session.getSubject().getValue();
1007
        }
1008
        EventLog.getInstance().log(request.getRemoteAddr(), 
1009
            request.getHeader("User-Agent"), principal, localId, "replicate");
1010

    
1011
        return inputStream;
1012
    }
1013

    
1014
    /**
1015
     * Set the access policy
1016
     */
1017
    @Deprecated
1018
    @Override
1019
    public boolean setAccessPolicy(Session session, Identifier pid,
1020
        AccessPolicy policy) 
1021
        throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
1022
        NotImplemented, InvalidRequest {
1023
        
1024
        throw new NotImplemented("4401", "This method is deprecated for Member Nodes.");
1025
        
1026
    }
1027

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