Project

General

Profile

1 6179 cjones
/**
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 6228 cjones
import java.io.IOException;
27 6179 cjones
import java.io.InputStream;
28 6228 cjones
import java.security.NoSuchAlgorithmException;
29 6250 cjones
import java.sql.SQLException;
30 6525 leinfelder
import java.util.Calendar;
31 6179 cjones
import java.util.Date;
32 6250 cjones
import java.util.List;
33 6389 leinfelder
import java.util.Timer;
34 6179 cjones
35 6258 cjones
import org.apache.commons.io.IOUtils;
36 6179 cjones
import org.apache.log4j.Logger;
37 6528 cjones
import org.dataone.client.CNode;
38 6332 leinfelder
import org.dataone.client.D1Client;
39
import org.dataone.client.MNode;
40 6179 cjones
import org.dataone.service.exceptions.IdentifierNotUnique;
41
import org.dataone.service.exceptions.InsufficientResources;
42
import org.dataone.service.exceptions.InvalidRequest;
43
import org.dataone.service.exceptions.InvalidSystemMetadata;
44
import org.dataone.service.exceptions.InvalidToken;
45
import org.dataone.service.exceptions.NotAuthorized;
46
import org.dataone.service.exceptions.NotFound;
47
import org.dataone.service.exceptions.NotImplemented;
48
import org.dataone.service.exceptions.ServiceFailure;
49 6185 leinfelder
import org.dataone.service.exceptions.SynchronizationFailed;
50 6179 cjones
import org.dataone.service.exceptions.UnsupportedType;
51 6366 leinfelder
import org.dataone.service.mn.tier1.v1.MNCore;
52
import org.dataone.service.mn.tier1.v1.MNRead;
53
import org.dataone.service.mn.tier2.v1.MNAuthorization;
54
import org.dataone.service.mn.tier3.v1.MNStorage;
55
import org.dataone.service.mn.tier4.v1.MNReplication;
56
import org.dataone.service.types.v1.Checksum;
57
import org.dataone.service.types.v1.DescribeResponse;
58
import org.dataone.service.types.v1.Event;
59
import org.dataone.service.types.v1.Group;
60
import org.dataone.service.types.v1.Identifier;
61
import org.dataone.service.types.v1.Log;
62
import org.dataone.service.types.v1.LogEntry;
63
import org.dataone.service.types.v1.MonitorInfo;
64
import org.dataone.service.types.v1.MonitorList;
65
import org.dataone.service.types.v1.Node;
66
import org.dataone.service.types.v1.NodeReference;
67
import org.dataone.service.types.v1.NodeState;
68
import org.dataone.service.types.v1.NodeType;
69
import org.dataone.service.types.v1.ObjectFormatIdentifier;
70
import org.dataone.service.types.v1.ObjectList;
71
import org.dataone.service.types.v1.Permission;
72
import org.dataone.service.types.v1.Ping;
73 6528 cjones
import org.dataone.service.types.v1.ReplicationStatus;
74 6366 leinfelder
import org.dataone.service.types.v1.Schedule;
75
import org.dataone.service.types.v1.Service;
76
import org.dataone.service.types.v1.Services;
77
import org.dataone.service.types.v1.Session;
78
import org.dataone.service.types.v1.Subject;
79
import org.dataone.service.types.v1.Synchronization;
80
import org.dataone.service.types.v1.SystemMetadata;
81
import org.dataone.service.types.v1.util.ChecksumUtil;
82 6476 jones
import org.dataone.service.util.Constants;
83 6179 cjones
84 6250 cjones
import edu.ucsb.nceas.metacat.DocumentImpl;
85 6234 cjones
import edu.ucsb.nceas.metacat.EventLog;
86 6230 cjones
import edu.ucsb.nceas.metacat.IdentifierManager;
87 6234 cjones
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
88 6389 leinfelder
import edu.ucsb.nceas.metacat.MetacatHandler;
89 6250 cjones
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
90 6260 cjones
import edu.ucsb.nceas.metacat.database.DBConnection;
91
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
92 6340 cjones
import edu.ucsb.nceas.metacat.properties.PropertyService;
93
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
94 6230 cjones
95 6179 cjones
/**
96
 * Represents Metacat's implementation of the DataONE Member Node
97
 * service API. Methods implement the various MN* interfaces, and methods common
98
 * to both Member Node and Coordinating Node interfaces are found in the
99
 * D1NodeService base class.
100 6288 cjones
 *
101
 * Implements:
102
 * MNCore.ping()
103
 * MNCore.getLogRecords()
104
 * MNCore.getObjectStatistics()
105
 * MNCore.getOperationStatistics()
106
 * MNCore.getStatus()
107
 * MNCore.getCapabilities()
108
 * MNRead.get()
109
 * MNRead.getSystemMetadata()
110
 * MNRead.describe()
111
 * MNRead.getChecksum()
112
 * MNRead.listObjects()
113
 * MNRead.synchronizationFailed()
114
 * MNAuthorization.isAuthorized()
115
 * MNAuthorization.setAccessPolicy()
116
 * MNStorage.create()
117
 * MNStorage.update()
118
 * MNStorage.delete()
119
 * MNReplication.replicate()
120
 *
121 6179 cjones
 */
122 6475 jones
public class MNodeService extends D1NodeService implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage {
123 6179 cjones
124 6475 jones
    /* the instance of the MNodeService object */
125
    private static MNodeService instance = null;
126 6179 cjones
127 6475 jones
    /* the logger instance */
128
    private Logger logMetacat = null;
129 6241 cjones
130 6475 jones
    /**
131
     * Singleton accessor to get an instance of MNodeService.
132
     *
133
     * @return instance - the instance of MNodeService
134
     */
135
    public static MNodeService getInstance() {
136
        if (instance == null) {
137
            instance = new MNodeService();
138
        }
139
        return instance;
140 6179 cjones
    }
141
142 6475 jones
    /**
143
     * Constructor, private for singleton access
144
     */
145
    private MNodeService() {
146
        super();
147
        logMetacat = Logger.getLogger(MNodeService.class);
148 6310 cjones
    }
149 6475 jones
150
    /**
151
     * Deletes an object from the Member Node, where the object is either a
152
     * data object or a science metadata object.
153
     *
154
     * @param session - the Session object containing the credentials for the Subject
155
     * @param pid - The object identifier to be deleted
156
     *
157
     * @return pid - the identifier of the object used for the deletion
158
     *
159
     * @throws InvalidToken
160
     * @throws ServiceFailure
161
     * @throws NotAuthorized
162
     * @throws NotFound
163
     * @throws NotImplemented
164
     * @throws InvalidRequest
165
     */
166
    @Override
167
    public Identifier delete(Session session, Identifier pid)
168
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
169
170
        String localId = null;
171
        boolean allowed = false;
172
        String username = Constants.PUBLIC_SUBJECT;
173
        String[] groupnames = null;
174
        if (session != null) {
175
            username = session.getSubject().getValue();
176
            if (session.getSubjectList() != null) {
177
                List<Group> groupList = session.getSubjectList().getGroupList();
178
                if (groupList != null) {
179
                    groupnames = new String[groupList.size()];
180
                    for (int i = 0; i > groupList.size(); i++) {
181
                        groupnames[i] = groupList.get(i).getGroupName();
182
                    }
183
                }
184
            }
185
        }
186
187
        // do we have a valid pid?
188
        if (pid == null || pid.getValue().trim().equals("")) {
189
            throw new InvalidRequest("1322", "The provided identifier was invalid.");
190
        }
191
192
        // check for the existing identifier
193
        try {
194
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
195
        } catch (McdbDocNotFoundException e) {
196
            throw new InvalidRequest("1322", "The object with the provided " + "identifier was not found.");
197
        }
198
199
        // does the subject have DELETE (a D1 CHANGE_PERMISSION level) priveleges on the pid?
200
        allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
201
202
        if (allowed) {
203
            try {
204
                // delete the document
205
                DocumentImpl.delete(localId, username, groupnames, null);
206
                EventLog.getInstance().log(metacatUrl, username, localId, Event.DELETE.xmlValue());
207
208
            } catch (McdbDocNotFoundException e) {
209
                throw new InvalidRequest("1322", "The provided identifier was invalid.");
210
211
            } catch (SQLException e) {
212
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
213
214
            } catch (InsufficientKarmaException e) {
215
                throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
216
217
            } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
218
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
219
            }
220
221
        } else {
222
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
223
        }
224
225
        return pid;
226 6250 cjones
    }
227
228 6475 jones
    /**
229
     * Updates an existing object by creating a new object identified by
230
     * newPid on the Member Node which explicitly obsoletes the object
231
     * identified by pid through appropriate changes to the SystemMetadata
232
     * of pid and newPid
233
     *
234
     * @param session - the Session object containing the credentials for the Subject
235
     * @param pid - The identifier of the object to be updated
236
     * @param object - the new object bytes
237
     * @param sysmeta - the new system metadata describing the object
238
     *
239
     * @return newPid - the identifier of the new object
240
     *
241
     * @throws InvalidToken
242
     * @throws ServiceFailure
243
     * @throws NotAuthorized
244
     * @throws NotFound
245
     * @throws NotImplemented
246
     * @throws IdentifierNotUnique
247
     * @throws UnsupportedType
248
     * @throws InsufficientResources
249
     * @throws InvalidSystemMetadata
250
     * @throws InvalidRequest
251
     */
252
    @Override
253
    public Identifier update(Session session, Identifier pid, InputStream object, Identifier newPid, SystemMetadata sysmeta) throws InvalidToken,
254
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, NotImplemented,
255
            InvalidRequest {
256 6250 cjones
257 6475 jones
        String localId = null;
258
        boolean allowed = false;
259
        boolean isScienceMetadata = false;
260
        Subject subject = session.getSubject();
261
262
        // do we have a valid pid?
263
        if (pid == null || pid.getValue().trim().equals("")) {
264
            throw new InvalidRequest("1202", "The provided identifier was invalid.");
265
        }
266
267
        // check for the existing identifier
268
        try {
269
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
270
        } catch (McdbDocNotFoundException e) {
271
            throw new InvalidRequest("1202", "The object with the provided " + "identifier was not found.");
272
        }
273 6518 leinfelder
274 6521 leinfelder
        // set the originating node
275
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
276
        sysmeta.setOriginMemberNode(originMemberNode);
277
278 6518 leinfelder
        // set the submitter to match the certificate
279
        sysmeta.setSubmitter(subject);
280 6525 leinfelder
        // set the dates
281
        Date now = Calendar.getInstance().getTime();
282
		sysmeta.setDateSysMetadataModified(now);
283
		sysmeta.setDateUploaded(now);
284 6475 jones
285
        // does the subject have WRITE ( == update) priveleges on the pid?
286
        allowed = isAuthorized(session, pid, Permission.WRITE);
287
288
        if (allowed) {
289
290
            // get the existing system metadata for the object
291
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
292
293
            // add the newPid to the obsoletedBy list for the existing sysmeta
294
            existingSysMeta.setObsoletedBy(newPid);
295
296
            // then update the existing system metadata
297
            updateSystemMetadata(existingSysMeta);
298
299
            // prep the new system metadata, add pid to the affected lists
300
            sysmeta.setObsoletes(pid);
301
            //sysmeta.addDerivedFrom(pid);
302
303
            isScienceMetadata = isScienceMetadata(sysmeta);
304
305
            // do we have XML metadata or a data object?
306
            if (isScienceMetadata) {
307
308
                // update the science metadata XML document
309
                // TODO: handle non-XML metadata/data documents (like netCDF)
310
                // TODO: don't put objects into memory using stream to string
311
                String objectAsXML = "";
312
                try {
313
                    objectAsXML = IOUtils.toString(object, "UTF-8");
314
                    localId = insertOrUpdateDocument(objectAsXML, newPid, session, "update");
315
                    // register the newPid and the generated localId
316
                    if (newPid != null) {
317
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
318
319
                    }
320
321
                } catch (IOException e) {
322
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
323
                    logMetacat.info(msg);
324
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
325
326
                }
327
328
            } else {
329
330
                // update the data object
331
                localId = insertDataObject(object, newPid, session);
332
333
            }
334
335
            // and insert the new system metadata
336
            insertSystemMetadata(sysmeta);
337
338
            // log the update event
339
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
340
341
        } else {
342
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
343
                    + " on the Member Node.");
344
        }
345
346
        return newPid;
347 6250 cjones
    }
348 6254 cjones
349 6475 jones
    public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
350
            IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
351 6250 cjones
352 6530 leinfelder
    	// check for null session
353
        if (session == null) {
354
        	throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
355
        }
356 6518 leinfelder
        // set the submitter to match the certificate
357
        sysmeta.setSubmitter(session.getSubject());
358 6520 leinfelder
        // set the originating node
359
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
360
        sysmeta.setOriginMemberNode(originMemberNode);
361 6525 leinfelder
        // set the dates
362
        Date now = Calendar.getInstance().getTime();
363
		sysmeta.setDateSysMetadataModified(now);
364
		sysmeta.setDateUploaded(now);
365 6518 leinfelder
        // call the shared impl
366 6475 jones
        return super.create(session, pid, object, sysmeta);
367
    }
368 6250 cjones
369 6475 jones
    /**
370
     * Called by a Coordinating Node to request that the Member Node create a
371
     * copy of the specified object by retrieving it from another Member
372
     * Node and storing it locally so that it can be made accessible to
373
     * the DataONE system.
374
     *
375
     * @param session - the Session object containing the credentials for the Subject
376
     * @param sysmeta - Copy of the CN held system metadata for the object
377
     * @param sourceNode - A reference to node from which the content should be
378
     *                     retrieved. The reference should be resolved by
379
     *                     checking the CN node registry.
380
     *
381
     * @return true if the replication succeeds
382
     *
383
     * @throws ServiceFailure
384
     * @throws NotAuthorized
385
     * @throws NotImplemented
386
     * @throws UnsupportedType
387
     * @throws InsufficientResources
388
     * @throws InvalidRequest
389
     */
390
    @Override
391 6528 cjones
    public boolean replicate(Session session, SystemMetadata sysmeta, NodeReference sourceNode)
392
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
393
        InsufficientResources, UnsupportedType {
394 6250 cjones
395 6475 jones
        boolean result = false;
396
397
        // TODO: check credentials
398
399
        // get the referenced object
400
        Identifier pid = sysmeta.getIdentifier();
401
402
        // get from the membernode
403
        // TODO: switch credentials for the server retrieval?
404
        MNode mn = D1Client.getMN(sourceNode);
405 6528 cjones
        CNode cn = D1Client.getCN();
406
407 6475 jones
        InputStream object = null;
408
409
        try {
410 6528 cjones
            object = mn.getReplica(session, pid);
411 6475 jones
        } catch (InvalidToken e) {
412
            e.printStackTrace();
413
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
414
        } catch (NotFound e) {
415
            e.printStackTrace();
416
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
417
        }
418
419
        // add it to local store
420
        Identifier retPid;
421
        try {
422
            retPid = create(session, pid, object, sysmeta);
423
            result = (retPid.getValue().equals(pid.getValue()));
424
        } catch (InvalidToken e) {
425
            e.printStackTrace();
426
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
427
        } catch (IdentifierNotUnique e) {
428
            e.printStackTrace();
429
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
430
        } catch (InvalidSystemMetadata e) {
431
            e.printStackTrace();
432
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
433
        }
434
435 6528 cjones
        try {
436
            session = null;
437
            cn.setReplicationStatus(session, pid, sourceNode, ReplicationStatus.COMPLETED);
438
439
        } catch (InvalidToken e) {
440
            // TODO Auto-generated catch block
441
            e.printStackTrace();
442
        } catch (NotFound e) {
443
            // TODO Auto-generated catch block
444
            e.printStackTrace();
445
        }
446 6475 jones
        return result;
447
448 6250 cjones
    }
449 6179 cjones
450 6475 jones
    /**
451
     * This method provides a lighter weight mechanism than
452
     * MN_read.getSystemMetadata() for a client to determine basic
453
     * properties of the referenced object.
454
     *
455
     * @param session - the Session object containing the credentials for the Subject
456
     * @param pid - the identifier of the object to be described
457
     *
458
     * @return describeResponse - A set of values providing a basic description
459
     *                            of the object.
460
     *
461
     * @throws InvalidToken
462
     * @throws ServiceFailure
463
     * @throws NotAuthorized
464
     * @throws NotFound
465
     * @throws NotImplemented
466
     * @throws InvalidRequest
467
     */
468
    @Override
469
    public DescribeResponse describe(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented,
470
            InvalidRequest {
471 6251 cjones
472 6502 leinfelder
    	// get system metadata and construct the describe response
473 6475 jones
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
474
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
475
                sysmeta.getChecksum());
476
477
        return describeResponse;
478
479 6259 cjones
    }
480 6258 cjones
481 6475 jones
    /**
482
     * Return the object identified by the given object identifier
483
     *
484
     * @param session - the Session object containing the credentials for the Subject
485
     * @param pid - the object identifier for the given object
486
     *
487
     * @return inputStream - the input stream of the given object
488
     *
489
     * @throws InvalidToken
490
     * @throws ServiceFailure
491
     * @throws NotAuthorized
492
     * @throws InvalidRequest
493
     * @throws NotImplemented
494
     */
495
    @Override
496
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
497 6258 cjones
498 6475 jones
        return super.get(session, pid);
499 6258 cjones
500 6259 cjones
    }
501 6258 cjones
502 6475 jones
    /**
503
     * Returns a Checksum for the specified object using an accepted hashing algorithm
504
     *
505
     * @param session - the Session object containing the credentials for the Subject
506
     * @param pid - the object identifier for the given object
507
     * @param algorithm -  the name of an algorithm that will be used to compute
508
     *                     a checksum of the bytes of the object
509
     *
510
     * @return checksum - the checksum of the given object
511
     *
512
     * @throws InvalidToken
513
     * @throws ServiceFailure
514
     * @throws NotAuthorized
515
     * @throws NotFound
516
     * @throws InvalidRequest
517
     * @throws NotImplemented
518
     */
519
    @Override
520
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
521
            InvalidRequest, NotImplemented {
522 6258 cjones
523 6475 jones
        Checksum checksum = null;
524
525
        InputStream inputStream = get(session, pid);
526
527 6259 cjones
        try {
528 6475 jones
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
529
530
        } catch (NoSuchAlgorithmException e) {
531
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
532
                    + e.getMessage());
533 6259 cjones
        } catch (IOException e) {
534 6475 jones
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
535
                    + e.getMessage());
536 6259 cjones
        }
537 6382 cjones
538 6475 jones
        if (checksum == null) {
539
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
540
        }
541 6258 cjones
542 6475 jones
        return checksum;
543 6259 cjones
    }
544 6179 cjones
545 6475 jones
    /**
546
     * Return the system metadata for a given object
547
     *
548
     * @param session - the Session object containing the credentials for the Subject
549
     * @param pid - the object identifier for the given object
550
     *
551
     * @return inputStream - the input stream of the given system metadata object
552
     *
553
     * @throws InvalidToken
554
     * @throws ServiceFailure
555
     * @throws NotAuthorized
556
     * @throws NotFound
557
     * @throws InvalidRequest
558
     * @throws NotImplemented
559
     */
560
    @Override
561
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
562
            NotImplemented {
563 6341 leinfelder
564 6475 jones
        return super.getSystemMetadata(session, pid);
565
    }
566 6341 leinfelder
567 6475 jones
    /**
568
     * Retrieve the list of objects present on the MN that match the calling parameters
569
     *
570
     * @param session - the Session object containing the credentials for the Subject
571
     * @param startTime - Specifies the beginning of the time range from which
572
     *                    to return object (>=)
573
     * @param endTime - Specifies the beginning of the time range from which
574
     *                  to return object (>=)
575
     * @param objectFormat - Restrict results to the specified object format
576
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
577
     * @param start - The zero-based index of the first value, relative to the
578
     *                first record of the resultset that matches the parameters.
579
     * @param count - The maximum number of entries that should be returned in
580
     *                the response. The Member Node may return less entries
581
     *                than specified in this value.
582
     *
583
     * @return objectList - the list of objects matching the criteria
584
     *
585
     * @throws InvalidToken
586
     * @throws ServiceFailure
587
     * @throws NotAuthorized
588
     * @throws InvalidRequest
589
     * @throws NotImplemented
590
     */
591
    @Override
592
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
593
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
594 6179 cjones
595 6475 jones
        ObjectList objectList = null;
596 6332 leinfelder
597 6475 jones
        try {
598
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
599
        } catch (Exception e) {
600
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
601
        }
602 6332 leinfelder
603 6475 jones
        return objectList;
604 6229 cjones
    }
605 6179 cjones
606 6475 jones
    /**
607 6476 jones
     * Return a description of the node's capabilities and services.
608 6475 jones
     *
609
     * @return node - the technical capabilities of the Member Node
610
     *
611
     * @throws ServiceFailure
612
     * @throws NotAuthorized
613
     * @throws InvalidRequest
614
     * @throws NotImplemented
615
     */
616
    @Override
617
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
618 6179 cjones
619 6475 jones
        String nodeName = null;
620
        String nodeId = null;
621 6492 jones
        String subject = null;
622 6475 jones
        String nodeDesc = null;
623 6476 jones
        String nodeTypeString = null;
624
        NodeType nodeType = null;
625 6475 jones
        String mnCoreServiceVersion = null;
626
        String mnReadServiceVersion = null;
627
        String mnAuthorizationServiceVersion = null;
628
        String mnStorageServiceVersion = null;
629
        String mnReplicationServiceVersion = null;
630 6179 cjones
631 6475 jones
        boolean nodeSynchronize = false;
632
        boolean nodeReplicate = false;
633
        boolean mnCoreServiceAvailable = false;
634
        boolean mnReadServiceAvailable = false;
635
        boolean mnAuthorizationServiceAvailable = false;
636
        boolean mnStorageServiceAvailable = false;
637
        boolean mnReplicationServiceAvailable = false;
638 6179 cjones
639 6475 jones
        try {
640
            // get the properties of the node based on configuration information
641 6492 jones
            nodeName = PropertyService.getProperty("dataone.nodeName");
642 6475 jones
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
643 6492 jones
            subject = PropertyService.getProperty("dataone.subject");
644 6475 jones
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
645 6476 jones
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
646
            nodeType = NodeType.convert(nodeTypeString);
647 6475 jones
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
648
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
649
650
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
651
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
652
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
653
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
654
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
655
656
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
657
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
658
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
659
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
660
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
661
662 6476 jones
            // Set the properties of the node based on configuration information and
663
            // calls to current status methods
664
            Node node = new Node();
665
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
666
            node.setDescription(nodeDesc);
667 6475 jones
668 6476 jones
            // set the node's health information
669
            node.setState(NodeState.UP);
670
671
            // set the ping response to the current value
672
            Ping canPing = new Ping();
673
            canPing.setSuccess(false);
674
            try {
675
                canPing.setSuccess(ping());
676
            } catch (InsufficientResources e) {
677
                e.printStackTrace();
678
            } catch (UnsupportedType e) {
679
                e.printStackTrace();
680
            }
681
            node.setPing(canPing);
682 6475 jones
683 6476 jones
            NodeReference identifier = new NodeReference();
684
            identifier.setValue(nodeId);
685
            node.setIdentifier(identifier);
686 6492 jones
            Subject s = new Subject();
687
            s.setValue(subject);
688
            node.addSubject(s);
689 6476 jones
            node.setName(nodeName);
690
            node.setReplicate(nodeReplicate);
691
            node.setSynchronize(nodeSynchronize);
692 6475 jones
693 6476 jones
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
694
            Services services = new Services();
695 6475 jones
696 6476 jones
            Service sMNCore = new Service();
697
            sMNCore.setName("MNCore");
698
            sMNCore.setVersion(mnCoreServiceVersion);
699
            sMNCore.setAvailable(mnCoreServiceAvailable);
700 6475 jones
701 6476 jones
            Service sMNRead = new Service();
702
            sMNRead.setName("MNRead");
703
            sMNRead.setVersion(mnReadServiceVersion);
704
            sMNRead.setAvailable(mnReadServiceAvailable);
705 6475 jones
706 6476 jones
            Service sMNAuthorization = new Service();
707
            sMNAuthorization.setName("MNAuthorization");
708
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
709
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
710 6475 jones
711 6476 jones
            Service sMNStorage = new Service();
712
            sMNStorage.setName("MNStorage");
713
            sMNStorage.setVersion(mnStorageServiceVersion);
714
            sMNStorage.setAvailable(mnStorageServiceAvailable);
715 6475 jones
716 6476 jones
            Service sMNReplication = new Service();
717
            sMNReplication.setName("MNReplication");
718
            sMNReplication.setVersion(mnReplicationServiceVersion);
719
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
720 6475 jones
721 6476 jones
            services.addService(sMNRead);
722
            services.addService(sMNCore);
723
            services.addService(sMNAuthorization);
724
            services.addService(sMNStorage);
725
            services.addService(sMNReplication);
726
            node.setServices(services);
727 6475 jones
728 6476 jones
            // TODO: Allow the metacat admin to determine the schedule
729
            // Set the schedule for synchronization
730
            Synchronization synchronization = new Synchronization();
731
            Schedule schedule = new Schedule();
732
            Date now = new Date();
733
            schedule.setYear("*");
734
            schedule.setMon("*");
735
            schedule.setMday("*");
736 6512 jones
            schedule.setWday("?");
737 6476 jones
            schedule.setHour("*");
738 6512 jones
            schedule.setMin("0/3");
739
            schedule.setSec("10");
740 6476 jones
            synchronization.setSchedule(schedule);
741
            synchronization.setLastHarvested(now);
742
            synchronization.setLastCompleteHarvest(now);
743
            node.setSynchronization(synchronization);
744 6475 jones
745 6476 jones
            node.setType(nodeType);
746
            return node;
747 6475 jones
748 6476 jones
        } catch (PropertyNotFoundException pnfe) {
749
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
750
            logMetacat.error(msg);
751
            throw new ServiceFailure("2162", msg);
752
        }
753 6228 cjones
    }
754 6179 cjones
755 6475 jones
    /**
756
     * Returns the number of operations that have been serviced by the node
757
     * over time periods of one and 24 hours.
758
     *
759
     * @param session - the Session object containing the credentials for the Subject
760
     * @param period - An ISO8601 compatible DateTime range specifying the time
761
     *                 range for which to return operation statistics.
762
     * @param requestor - Limit to operations performed by given requestor identity.
763
     * @param event -  Enumerated value indicating the type of event being examined
764
     * @param format - Limit to events involving objects of the specified format
765
     *
766
     * @return the desired log records
767
     *
768
     * @throws InvalidToken
769
     * @throws ServiceFailure
770
     * @throws NotAuthorized
771
     * @throws InvalidRequest
772
     * @throws NotImplemented
773
     */
774
    @Override
775
    public MonitorList getOperationStatistics(Session session, Date startTime, Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
776
            throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
777 6179 cjones
778 6475 jones
        MonitorList monitorList = new MonitorList();
779 6179 cjones
780 6475 jones
        try {
781 6179 cjones
782 6475 jones
            // get log records first
783
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
784 6179 cjones
785 6475 jones
            // TODO: aggregate by day or hour -- needs clarification
786
            int count = 1;
787
            for (LogEntry logEntry : logs.getLogEntryList()) {
788
                Identifier pid = logEntry.getIdentifier();
789
                Date logDate = logEntry.getDateLogged();
790
                // if we are filtering by format
791
                if (formatId != null) {
792
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
793
                    if (!sysmeta.getFmtid().getValue().equals(formatId.getValue())) {
794
                        // does not match
795
                        continue;
796
                    }
797
                }
798
                MonitorInfo item = new MonitorInfo();
799
                item.setCount(count);
800
                item.setDate(new java.sql.Date(logDate.getTime()));
801
                monitorList.addMonitorInfo(item);
802 6179 cjones
803 6475 jones
            }
804
        } catch (Exception e) {
805
            e.printStackTrace();
806
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
807
        }
808 6345 cjones
809 6475 jones
        return monitorList;
810 6345 cjones
811 6340 cjones
    }
812
813 6475 jones
    /**
814
     * Low level “are you alive” operation. A valid ping response is
815
     * indicated by a HTTP status of 200.
816
     *
817
     * @return true if the service is alive
818
     *
819
     * @throws InvalidToken
820
     * @throws ServiceFailure
821
     * @throws NotAuthorized
822
     * @throws InvalidRequest
823
     * @throws NotImplemented
824
     */
825
    @Override
826
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
827
828
        // test if we can get a database connection
829
        boolean alive = false;
830
        int serialNumber = -1;
831
        DBConnection dbConn = null;
832
        try {
833
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
834
            serialNumber = dbConn.getCheckOutSerialNumber();
835
            alive = true;
836
        } catch (SQLException e) {
837
            return alive;
838
        } finally {
839
            // Return the database connection
840
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
841
        }
842
843
        return alive;
844 6351 cjones
    }
845
846 6475 jones
    /**
847
     * A callback method used by a CN to indicate to a MN that it cannot
848
     * complete synchronization of the science metadata identified by pid.  Log
849
     * the event in the metacat event log.
850
     *
851
     * @param session
852
     * @param syncFailed
853
     *
854
     * @throws ServiceFailure
855
     * @throws NotAuthorized
856
     * @throws InvalidRequest
857
     * @throws NotImplemented
858
     */
859
    @Override
860
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
861 6179 cjones
862 6475 jones
        String localId;
863 6331 leinfelder
864 6475 jones
        try {
865
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
866
        } catch (McdbDocNotFoundException e) {
867
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
868 6179 cjones
869 6475 jones
        }
870
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
871
        // method is changed to include the URL as a parameter
872
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
873
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
874
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
875 6506 leinfelder
        String principal = Constants.PUBLIC_SUBJECT;
876
        if (session != null && session.getSubject() != null) {
877
        	principal = session.getSubject().getValue();
878
        }
879
        try {
880
        	EventLog.getInstance().log(syncFailed.getNodeId(), principal, localId, "synchronization_failed");
881
        } catch (Exception e) {
882
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
883
		}
884 6475 jones
        //EventLog.getInstance().log("CN URL WILL GO HERE",
885
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
886 6179 cjones
887 6260 cjones
    }
888
889 6475 jones
    /**
890
     * Essentially a get() but with different logging behavior
891
     */
892
    @Override
893
    public InputStream getReplica(Session session, Identifier pid) throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound {
894 6179 cjones
895 6475 jones
        InputStream inputStream = null; // bytes to be returned
896
        handler = new MetacatHandler(new Timer());
897
        boolean allowed = false;
898
        String localId; // the metacat docid for the pid
899 6179 cjones
900 6475 jones
        // get the local docid from Metacat
901
        try {
902
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
903
        } catch (McdbDocNotFoundException e) {
904
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
905
        }
906 6234 cjones
907 6475 jones
        Node node = this.getCapabilities();
908
        Subject targetNodeSubject = node.getSubject(0);
909 6185 leinfelder
910 6475 jones
        // check for authorization to replicate
911
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
912 6384 cjones
913 6475 jones
        // if the person is authorized, perform the read
914
        if (allowed) {
915
            try {
916
                inputStream = handler.read(localId);
917
            } catch (Exception e) {
918
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
919
            }
920
        }
921 6384 cjones
922 6475 jones
        // if we fail to set the input stream
923
        if (inputStream == null) {
924
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
925
        }
926
927
        // log the replica event
928
        String principal = null;
929
        if (session.getSubject() != null) {
930
            principal = session.getSubject().getValue();
931
        }
932
        EventLog.getInstance().log(null, principal, localId, "getreplica");
933
934
        return inputStream;
935
    }
936
937 6179 cjones
}