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