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