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.Date;
31
import java.util.List;
32
import java.util.Timer;
33

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

    
81
import edu.ucsb.nceas.metacat.DocumentImpl;
82
import edu.ucsb.nceas.metacat.EventLog;
83
import edu.ucsb.nceas.metacat.IdentifierManager;
84
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
85
import edu.ucsb.nceas.metacat.MetacatHandler;
86
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
87
import edu.ucsb.nceas.metacat.database.DBConnection;
88
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
89
import edu.ucsb.nceas.metacat.properties.PropertyService;
90
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
91

    
92
/**
93
 * Represents Metacat's implementation of the DataONE Member Node 
94
 * service API. Methods implement the various MN* interfaces, and methods common
95
 * to both Member Node and Coordinating Node interfaces are found in the
96
 * D1NodeService base class.
97
 * 
98
 * Implements:
99
 * MNCore.ping()
100
 * MNCore.getLogRecords()
101
 * MNCore.getObjectStatistics()
102
 * MNCore.getOperationStatistics()
103
 * MNCore.getStatus()
104
 * MNCore.getCapabilities()
105
 * MNRead.get()
106
 * MNRead.getSystemMetadata()
107
 * MNRead.describe()
108
 * MNRead.getChecksum()
109
 * MNRead.listObjects()
110
 * MNRead.synchronizationFailed()
111
 * MNAuthorization.isAuthorized()
112
 * MNAuthorization.setAccessPolicy()
113
 * MNStorage.create()
114
 * MNStorage.update()
115
 * MNStorage.delete()
116
 * MNReplication.replicate()
117
 * 
118
 */
119
public class MNodeService extends D1NodeService implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage {
120

    
121
    /* the instance of the MNodeService object */
122
    private static MNodeService instance = null;
123

    
124
    /* the logger instance */
125
    private Logger logMetacat = null;
126

    
127
    /**
128
     * Singleton accessor to get an instance of MNodeService.
129
     * 
130
     * @return instance - the instance of MNodeService
131
     */
132
    public static MNodeService getInstance() {
133
        if (instance == null) {
134
            instance = new MNodeService();
135
        }
136
        return instance;
137
    }
138

    
139
    /**
140
     * Constructor, private for singleton access
141
     */
142
    private MNodeService() {
143
        super();
144
        logMetacat = Logger.getLogger(MNodeService.class);
145
    }
146

    
147
    /**
148
     * Deletes an object from the Member Node, where the object is either a 
149
     * data object or a science metadata object.
150
     * 
151
     * @param session - the Session object containing the credentials for the Subject
152
     * @param pid - The object identifier to be deleted
153
     * 
154
     * @return pid - the identifier of the object used for the deletion
155
     * 
156
     * @throws InvalidToken
157
     * @throws ServiceFailure
158
     * @throws NotAuthorized
159
     * @throws NotFound
160
     * @throws NotImplemented
161
     * @throws InvalidRequest
162
     */
163
    @Override
164
    public Identifier delete(Session session, Identifier pid) 
165
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
166

    
167
        String localId = null;
168
        boolean allowed = false;
169
        String username = Constants.PUBLIC_SUBJECT;
170
        String[] groupnames = null;
171
        if (session != null) {
172
            username = session.getSubject().getValue();
173
            if (session.getSubjectList() != null) {
174
                List<Group> groupList = session.getSubjectList().getGroupList();
175
                if (groupList != null) {
176
                    groupnames = new String[groupList.size()];
177
                    for (int i = 0; i > groupList.size(); i++) {
178
                        groupnames[i] = groupList.get(i).getGroupName();
179
                    }
180
                }
181
            }
182
        }
183

    
184
        // do we have a valid pid?
185
        if (pid == null || pid.getValue().trim().equals("")) {
186
            throw new InvalidRequest("1322", "The provided identifier was invalid.");
187
        }
188

    
189
        // check for the existing identifier
190
        try {
191
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
192
        } catch (McdbDocNotFoundException e) {
193
            throw new InvalidRequest("1322", "The object with the provided " + "identifier was not found.");
194
        }
195

    
196
        // does the subject have DELETE (a D1 CHANGE_PERMISSION level) priveleges on the pid?
197
        allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
198

    
199
        if (allowed) {
200
            try {
201
                // delete the document
202
                DocumentImpl.delete(localId, username, groupnames, null);
203
                EventLog.getInstance().log(metacatUrl, username, localId, Event.DELETE.xmlValue());
204

    
205
            } catch (McdbDocNotFoundException e) {
206
                throw new InvalidRequest("1322", "The provided identifier was invalid.");
207

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

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

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

    
218
        } else {
219
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
220
        }
221

    
222
        return pid;
223
    }
224

    
225
    /**
226
     * Updates an existing object by creating a new object identified by 
227
     * newPid on the Member Node which explicitly obsoletes the object 
228
     * identified by pid through appropriate changes to the SystemMetadata 
229
     * of pid and newPid
230
     * 
231
     * @param session - the Session object containing the credentials for the Subject
232
     * @param pid - The identifier of the object to be updated
233
     * @param object - the new object bytes
234
     * @param sysmeta - the new system metadata describing the object
235
     * 
236
     * @return newPid - the identifier of the new object
237
     * 
238
     * @throws InvalidToken
239
     * @throws ServiceFailure
240
     * @throws NotAuthorized
241
     * @throws NotFound
242
     * @throws NotImplemented
243
     * @throws IdentifierNotUnique
244
     * @throws UnsupportedType
245
     * @throws InsufficientResources
246
     * @throws InvalidSystemMetadata
247
     * @throws InvalidRequest
248
     */
249
    @Override
250
    public Identifier update(Session session, Identifier pid, InputStream object, Identifier newPid, SystemMetadata sysmeta) throws InvalidToken,
251
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, NotImplemented,
252
            InvalidRequest {
253

    
254
        // check if the pid has been reserved
255
        try {
256
            boolean hasReservation = D1Client.getCN().hasReservation(session, pid);
257
            if (!hasReservation) {
258
                throw new NotAuthorized("", "No reservation for pid: " + pid.getValue());
259
            }
260
        } catch (NotFound e) {
261
            // okay to continue
262
        }
263

    
264
        String localId = null;
265
        boolean allowed = false;
266
        boolean isScienceMetadata = false;
267
        Subject subject = session.getSubject();
268

    
269
        // do we have a valid pid?
270
        if (pid == null || pid.getValue().trim().equals("")) {
271
            throw new InvalidRequest("1202", "The provided identifier was invalid.");
272
        }
273

    
274
        // check for the existing identifier
275
        try {
276
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
277
        } catch (McdbDocNotFoundException e) {
278
            throw new InvalidRequest("1202", "The object with the provided " + "identifier was not found.");
279
        }
280

    
281
        // does the subject have WRITE ( == update) priveleges on the pid?
282
        allowed = isAuthorized(session, pid, Permission.WRITE);
283

    
284
        if (allowed) {
285

    
286
            // get the existing system metadata for the object
287
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
288

    
289
            // add the newPid to the obsoletedBy list for the existing sysmeta
290
            existingSysMeta.setObsoletedBy(newPid);
291

    
292
            // then update the existing system metadata
293
            updateSystemMetadata(existingSysMeta);
294

    
295
            // prep the new system metadata, add pid to the affected lists
296
            sysmeta.setObsoletes(pid);
297
            //sysmeta.addDerivedFrom(pid);
298

    
299
            isScienceMetadata = isScienceMetadata(sysmeta);
300

    
301
            // do we have XML metadata or a data object?
302
            if (isScienceMetadata) {
303

    
304
                // update the science metadata XML document
305
                // TODO: handle non-XML metadata/data documents (like netCDF)
306
                // TODO: don't put objects into memory using stream to string
307
                String objectAsXML = "";
308
                try {
309
                    objectAsXML = IOUtils.toString(object, "UTF-8");
310
                    localId = insertOrUpdateDocument(objectAsXML, newPid, session, "update");
311
                    // register the newPid and the generated localId
312
                    if (newPid != null) {
313
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
314

    
315
                    }
316

    
317
                } catch (IOException e) {
318
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
319
                    logMetacat.info(msg);
320
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
321

    
322
                }
323

    
324
            } else {
325

    
326
                // update the data object
327
                localId = insertDataObject(object, newPid, session);
328

    
329
            }
330

    
331
            // and insert the new system metadata
332
            insertSystemMetadata(sysmeta);
333

    
334
            // log the update event
335
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
336

    
337
        } else {
338
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
339
                    + " on the Member Node.");
340
        }
341

    
342
        return newPid;
343
    }
344

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

    
348
        // check if the pid has been reserved
349
        try {
350
            boolean hasReservation = D1Client.getCN().hasReservation(session, pid);
351
            if (!hasReservation) {
352
                throw new NotAuthorized("", "No reservation for pid: " + pid.getValue());
353
            }
354
        } catch (NotFound e) {
355
            // okay to continue
356
        }
357

    
358
        return super.create(session, pid, object, sysmeta);
359
    }
360

    
361
    /**
362
     * Called by a Coordinating Node to request that the Member Node create a 
363
     * copy of the specified object by retrieving it from another Member 
364
     * Node and storing it locally so that it can be made accessible to 
365
     * the DataONE system.
366
     * 
367
     * @param session - the Session object containing the credentials for the Subject
368
     * @param sysmeta - Copy of the CN held system metadata for the object
369
     * @param sourceNode - A reference to node from which the content should be 
370
     *                     retrieved. The reference should be resolved by 
371
     *                     checking the CN node registry.
372
     * 
373
     * @return true if the replication succeeds
374
     * 
375
     * @throws ServiceFailure
376
     * @throws NotAuthorized
377
     * @throws NotImplemented
378
     * @throws UnsupportedType
379
     * @throws InsufficientResources
380
     * @throws InvalidRequest
381
     */
382
    @Override
383
    public boolean replicate(Session session, SystemMetadata sysmeta, NodeReference sourceNode) throws NotImplemented, ServiceFailure, NotAuthorized,
384
            InvalidRequest, InsufficientResources, UnsupportedType {
385

    
386
        boolean result = false;
387

    
388
        // TODO: check credentials
389

    
390
        // get the referenced object
391
        Identifier pid = sysmeta.getIdentifier();
392

    
393
        // get from the membernode
394
        // TODO: switch credentials for the server retrieval?
395
        MNode mn = D1Client.getMN(sourceNode);
396
        InputStream object = null;
397

    
398
        try {
399
            object = mn.get(session, pid);
400
        } catch (InvalidToken e) {
401
            e.printStackTrace();
402
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
403
        } catch (NotFound e) {
404
            e.printStackTrace();
405
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
406
        }
407

    
408
        // add it to local store
409
        Identifier retPid;
410
        try {
411
            retPid = create(session, pid, object, sysmeta);
412
            result = (retPid.getValue().equals(pid.getValue()));
413
        } catch (InvalidToken e) {
414
            e.printStackTrace();
415
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
416
        } catch (IdentifierNotUnique e) {
417
            e.printStackTrace();
418
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
419
        } catch (InvalidSystemMetadata e) {
420
            e.printStackTrace();
421
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
422
        }
423

    
424
        return result;
425

    
426
    }
427

    
428
    /**
429
     * This method provides a lighter weight mechanism than 
430
     * MN_read.getSystemMetadata() for a client to determine basic 
431
     * properties of the referenced object.
432
     * 
433
     * @param session - the Session object containing the credentials for the Subject
434
     * @param pid - the identifier of the object to be described
435
     * 
436
     * @return describeResponse - A set of values providing a basic description 
437
     *                            of the object.
438
     * 
439
     * @throws InvalidToken
440
     * @throws ServiceFailure
441
     * @throws NotAuthorized
442
     * @throws NotFound
443
     * @throws NotImplemented
444
     * @throws InvalidRequest
445
     */
446
    @Override
447
    public DescribeResponse describe(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented,
448
            InvalidRequest {
449

    
450
        if (session == null) {
451
            throw new InvalidToken("1370", "The session object is null");
452
        }
453

    
454
        if (pid == null || pid.getValue().trim().equals("")) {
455
            throw new InvalidRequest("1362", "The object identifier is null. " + "A valid identifier is required.");
456
        }
457

    
458
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
459
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
460
                sysmeta.getChecksum());
461

    
462
        return describeResponse;
463

    
464
    }
465

    
466
    /**
467
     * Return the object identified by the given object identifier
468
     * 
469
     * @param session - the Session object containing the credentials for the Subject
470
     * @param pid - the object identifier for the given object
471
     * 
472
     * @return inputStream - the input stream of the given object
473
     * 
474
     * @throws InvalidToken
475
     * @throws ServiceFailure
476
     * @throws NotAuthorized
477
     * @throws InvalidRequest
478
     * @throws NotImplemented
479
     */
480
    @Override
481
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
482

    
483
        return super.get(session, pid);
484

    
485
    }
486

    
487
    /**
488
     * Returns a Checksum for the specified object using an accepted hashing algorithm
489
     * 
490
     * @param session - the Session object containing the credentials for the Subject
491
     * @param pid - the object identifier for the given object
492
     * @param algorithm -  the name of an algorithm that will be used to compute 
493
     *                     a checksum of the bytes of the object
494
     * 
495
     * @return checksum - the checksum of the given object
496
     * 
497
     * @throws InvalidToken
498
     * @throws ServiceFailure
499
     * @throws NotAuthorized
500
     * @throws NotFound
501
     * @throws InvalidRequest
502
     * @throws NotImplemented
503
     */
504
    @Override
505
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
506
            InvalidRequest, NotImplemented {
507

    
508
        Checksum checksum = null;
509

    
510
        InputStream inputStream = get(session, pid);
511

    
512
        try {
513
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
514

    
515
        } catch (NoSuchAlgorithmException e) {
516
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
517
                    + e.getMessage());
518
        } catch (IOException e) {
519
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
520
                    + e.getMessage());
521
        }
522

    
523
        if (checksum == null) {
524
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
525
        }
526

    
527
        return checksum;
528
    }
529

    
530
    /**
531
     * Return the system metadata for a given object
532
     * 
533
     * @param session - the Session object containing the credentials for the Subject
534
     * @param pid - the object identifier for the given object
535
     * 
536
     * @return inputStream - the input stream of the given system metadata object
537
     * 
538
     * @throws InvalidToken
539
     * @throws ServiceFailure
540
     * @throws NotAuthorized
541
     * @throws NotFound
542
     * @throws InvalidRequest
543
     * @throws NotImplemented
544
     */
545
    @Override
546
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
547
            NotImplemented {
548

    
549
        return super.getSystemMetadata(session, pid);
550
    }
551

    
552
    /**
553
     * Retrieve the list of objects present on the MN that match the calling parameters
554
     * 
555
     * @param session - the Session object containing the credentials for the Subject
556
     * @param startTime - Specifies the beginning of the time range from which 
557
     *                    to return object (>=)
558
     * @param endTime - Specifies the beginning of the time range from which 
559
     *                  to return object (>=)
560
     * @param objectFormat - Restrict results to the specified object format
561
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
562
     * @param start - The zero-based index of the first value, relative to the 
563
     *                first record of the resultset that matches the parameters.
564
     * @param count - The maximum number of entries that should be returned in 
565
     *                the response. The Member Node may return less entries 
566
     *                than specified in this value.
567
     * 
568
     * @return objectList - the list of objects matching the criteria
569
     * 
570
     * @throws InvalidToken
571
     * @throws ServiceFailure
572
     * @throws NotAuthorized
573
     * @throws InvalidRequest
574
     * @throws NotImplemented
575
     */
576
    @Override
577
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
578
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
579

    
580
        ObjectList objectList = null;
581

    
582
        try {
583
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
584
        } catch (Exception e) {
585
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
586
        }
587

    
588
        return objectList;
589
    }
590

    
591
    /**
592
     * Return a description of the node's capabilities and services.
593
     * 
594
     * @return node - the technical capabilities of the Member Node
595
     * 
596
     * @throws ServiceFailure
597
     * @throws NotAuthorized
598
     * @throws InvalidRequest
599
     * @throws NotImplemented
600
     */
601
    @Override
602
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
603

    
604
        String nodeName = null;
605
        String nodeId = null;
606
        String nodeDesc = null;
607
        String nodeTypeString = null;
608
        NodeType nodeType = null;
609
        String mnCoreServiceVersion = null;
610
        String mnReadServiceVersion = null;
611
        String mnAuthorizationServiceVersion = null;
612
        String mnStorageServiceVersion = null;
613
        String mnReplicationServiceVersion = null;
614

    
615
        boolean nodeSynchronize = false;
616
        boolean nodeReplicate = false;
617
        boolean mnCoreServiceAvailable = false;
618
        boolean mnReadServiceAvailable = false;
619
        boolean mnAuthorizationServiceAvailable = false;
620
        boolean mnStorageServiceAvailable = false;
621
        boolean mnReplicationServiceAvailable = false;
622

    
623
        try {
624
            // get the properties of the node based on configuration information
625
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
626
            nodeName = PropertyService.getProperty("dataone.nodeName");
627
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
628
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
629
            nodeType = NodeType.convert(nodeTypeString);
630
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
631
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
632

    
633
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
634
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
635
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
636
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
637
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
638

    
639
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
640
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
641
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
642
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
643
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
644

    
645
            // Set the properties of the node based on configuration information and
646
            // calls to current status methods
647
            Node node = new Node();
648
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
649
            node.setDescription(nodeDesc);
650

    
651
            // set the node's health information
652
            node.setState(NodeState.UP);
653
            
654
            // set the ping response to the current value
655
            Ping canPing = new Ping();
656
            canPing.setSuccess(false);
657
            try {
658
                canPing.setSuccess(ping());
659
            } catch (InsufficientResources e) {
660
                e.printStackTrace();
661
            } catch (UnsupportedType e) {
662
                e.printStackTrace();
663
            }
664
            node.setPing(canPing);
665

    
666
            NodeReference identifier = new NodeReference();
667
            identifier.setValue(nodeId);
668
            node.setIdentifier(identifier);
669
            node.setName(nodeName);
670
            node.setReplicate(nodeReplicate);
671
            node.setSynchronize(nodeSynchronize);
672

    
673
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
674
            Services services = new Services();
675

    
676
            Service sMNCore = new Service();
677
            sMNCore.setName("MNCore");
678
            sMNCore.setVersion(mnCoreServiceVersion);
679
            sMNCore.setAvailable(mnCoreServiceAvailable);
680

    
681
            Service sMNRead = new Service();
682
            sMNRead.setName("MNRead");
683
            sMNRead.setVersion(mnReadServiceVersion);
684
            sMNRead.setAvailable(mnReadServiceAvailable);
685

    
686
            Service sMNAuthorization = new Service();
687
            sMNAuthorization.setName("MNAuthorization");
688
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
689
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
690

    
691
            Service sMNStorage = new Service();
692
            sMNStorage.setName("MNStorage");
693
            sMNStorage.setVersion(mnStorageServiceVersion);
694
            sMNStorage.setAvailable(mnStorageServiceAvailable);
695

    
696
            Service sMNReplication = new Service();
697
            sMNReplication.setName("MNReplication");
698
            sMNReplication.setVersion(mnReplicationServiceVersion);
699
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
700

    
701
            services.addService(sMNRead);
702
            services.addService(sMNCore);
703
            services.addService(sMNAuthorization);
704
            services.addService(sMNStorage);
705
            services.addService(sMNReplication);
706
            node.setServices(services);
707

    
708
            // TODO: Allow the metacat admin to determine the schedule
709
            // Set the schedule for synchronization
710
            Synchronization synchronization = new Synchronization();
711
            Schedule schedule = new Schedule();
712
            Date now = new Date();
713
            schedule.setYear("*");
714
            schedule.setMon("*");
715
            schedule.setMday("*");
716
            schedule.setWday("*");
717
            schedule.setHour("*");
718
            schedule.setMin("0,5,10,15,20,25,30,35,40,45,50,55");
719
            schedule.setSec("*");
720
            synchronization.setSchedule(schedule);
721
            synchronization.setLastHarvested(now);
722
            synchronization.setLastCompleteHarvest(now);
723
            node.setSynchronization(synchronization);
724

    
725
            node.setType(nodeType);
726
            return node;
727

    
728
        } catch (PropertyNotFoundException pnfe) {
729
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
730
            logMetacat.error(msg);
731
            throw new ServiceFailure("2162", msg);
732
        }
733
    }
734

    
735
    /**
736
     * Returns the number of operations that have been serviced by the node 
737
     * over time periods of one and 24 hours.
738
     * 
739
     * @param session - the Session object containing the credentials for the Subject
740
     * @param period - An ISO8601 compatible DateTime range specifying the time 
741
     *                 range for which to return operation statistics.
742
     * @param requestor - Limit to operations performed by given requestor identity.
743
     * @param event -  Enumerated value indicating the type of event being examined
744
     * @param format - Limit to events involving objects of the specified format
745
     * 
746
     * @return the desired log records
747
     * 
748
     * @throws InvalidToken
749
     * @throws ServiceFailure
750
     * @throws NotAuthorized
751
     * @throws InvalidRequest
752
     * @throws NotImplemented
753
     */
754
    @Override
755
    public MonitorList getOperationStatistics(Session session, Date startTime, Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
756
            throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
757

    
758
        MonitorList monitorList = new MonitorList();
759

    
760
        try {
761

    
762
            // get log records first
763
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
764

    
765
            // TODO: aggregate by day or hour -- needs clarification
766
            int count = 1;
767
            for (LogEntry logEntry : logs.getLogEntryList()) {
768
                Identifier pid = logEntry.getIdentifier();
769
                Date logDate = logEntry.getDateLogged();
770
                // if we are filtering by format
771
                if (formatId != null) {
772
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
773
                    if (!sysmeta.getFmtid().getValue().equals(formatId.getValue())) {
774
                        // does not match
775
                        continue;
776
                    }
777
                }
778
                MonitorInfo item = new MonitorInfo();
779
                item.setCount(count);
780
                item.setDate(new java.sql.Date(logDate.getTime()));
781
                monitorList.addMonitorInfo(item);
782

    
783
            }
784
        } catch (Exception e) {
785
            e.printStackTrace();
786
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
787
        }
788

    
789
        return monitorList;
790

    
791
    }
792

    
793
    /**
794
     * Low level “are you alive” operation. A valid ping response is 
795
     * indicated by a HTTP status of 200.
796
     * 
797
     * @return true if the service is alive
798
     * 
799
     * @throws InvalidToken
800
     * @throws ServiceFailure
801
     * @throws NotAuthorized
802
     * @throws InvalidRequest
803
     * @throws NotImplemented
804
     */
805
    @Override
806
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
807

    
808
        // test if we can get a database connection
809
        boolean alive = false;
810
        int serialNumber = -1;
811
        DBConnection dbConn = null;
812
        try {
813
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
814
            serialNumber = dbConn.getCheckOutSerialNumber();
815
            alive = true;
816
        } catch (SQLException e) {
817
            return alive;
818
        } finally {
819
            // Return the database connection
820
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
821
        }
822

    
823
        return alive;
824
    }
825

    
826
    /**
827
     * A callback method used by a CN to indicate to a MN that it cannot 
828
     * complete synchronization of the science metadata identified by pid.  Log
829
     * the event in the metacat event log.
830
     * 
831
     * @param session
832
     * @param syncFailed
833
     * 
834
     * @throws ServiceFailure
835
     * @throws NotAuthorized
836
     * @throws InvalidRequest
837
     * @throws NotImplemented
838
     */
839
    @Override
840
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
841

    
842
        String localId;
843

    
844
        try {
845
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
846
        } catch (McdbDocNotFoundException e) {
847
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
848

    
849
        }
850
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
851
        // method is changed to include the URL as a parameter
852
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
853
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
854
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
855
        EventLog.getInstance().log(syncFailed.getNodeId(), session.getSubject().getValue(), localId, "synchronization_failed");
856
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
857
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
858

    
859
    }
860

    
861
    /**
862
     * Essentially a get() but with different logging behavior
863
     */
864
    @Override
865
    public InputStream getReplica(Session session, Identifier pid) throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound {
866

    
867
        InputStream inputStream = null; // bytes to be returned
868
        handler = new MetacatHandler(new Timer());
869
        boolean allowed = false;
870
        String localId; // the metacat docid for the pid
871

    
872
        // get the local docid from Metacat
873
        try {
874
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
875
        } catch (McdbDocNotFoundException e) {
876
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
877
        }
878

    
879
        Node node = this.getCapabilities();
880
        Subject targetNodeSubject = node.getSubject(0);
881

    
882
        // check for authorization to replicate
883
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
884

    
885
        // if the person is authorized, perform the read
886
        if (allowed) {
887
            try {
888
                inputStream = handler.read(localId);
889
            } catch (Exception e) {
890
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
891
            }
892
        }
893

    
894
        // if we fail to set the input stream
895
        if (inputStream == null) {
896
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
897
        }
898

    
899
        // log the replica event
900
        String principal = null;
901
        if (session.getSubject() != null) {
902
            principal = session.getSubject().getValue();
903
        }
904
        EventLog.getInstance().log(null, principal, localId, "getreplica");
905

    
906
        return inputStream;
907
    }
908

    
909
}
(3-3/6)