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