1
|
/**
|
2
|
* '$RCSfile$'
|
3
|
* Copyright: 2000-2011 Regents of the University of California and the
|
4
|
* National Center for Ecological Analysis and Synthesis
|
5
|
*
|
6
|
* '$Author: leinfelder $'
|
7
|
* '$Date: 2014-08-06 13:09:47 -0700 (Wed, 06 Aug 2014) $'
|
8
|
*
|
9
|
* This program is free software; you can redistribute it and/or modify
|
10
|
* it under the terms of the GNU General Public License as published by
|
11
|
* the Free Software Foundation; either version 2 of the License, or
|
12
|
* (at your option) any later version.
|
13
|
*
|
14
|
* This program is distributed in the hope that it will be useful,
|
15
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
16
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
17
|
* GNU General Public License for more details.
|
18
|
*
|
19
|
* You should have received a copy of the GNU General Public License
|
20
|
* along with this program; if not, write to the Free Software
|
21
|
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
22
|
*/
|
23
|
|
24
|
package edu.ucsb.nceas.metacat.dataone;
|
25
|
|
26
|
import java.io.File;
|
27
|
import java.io.FileNotFoundException;
|
28
|
import java.io.FileOutputStream;
|
29
|
import java.io.IOException;
|
30
|
import java.io.InputStream;
|
31
|
import java.io.OutputStream;
|
32
|
import java.sql.SQLException;
|
33
|
import java.util.ArrayList;
|
34
|
import java.util.Calendar;
|
35
|
import java.util.Date;
|
36
|
import java.util.Hashtable;
|
37
|
import java.util.List;
|
38
|
import java.util.Set;
|
39
|
import java.util.Timer;
|
40
|
import java.util.concurrent.locks.Lock;
|
41
|
|
42
|
import javax.servlet.http.HttpServletRequest;
|
43
|
|
44
|
import org.apache.commons.io.IOUtils;
|
45
|
import org.apache.log4j.Logger;
|
46
|
import org.dataone.client.v2.CNode;
|
47
|
import org.dataone.client.v2.itk.D1Client;
|
48
|
import org.dataone.client.v2.formats.ObjectFormatCache;
|
49
|
import org.dataone.service.exceptions.BaseException;
|
50
|
import org.dataone.service.exceptions.IdentifierNotUnique;
|
51
|
import org.dataone.service.exceptions.InsufficientResources;
|
52
|
import org.dataone.service.exceptions.InvalidRequest;
|
53
|
import org.dataone.service.exceptions.InvalidSystemMetadata;
|
54
|
import org.dataone.service.exceptions.InvalidToken;
|
55
|
import org.dataone.service.exceptions.NotAuthorized;
|
56
|
import org.dataone.service.exceptions.NotFound;
|
57
|
import org.dataone.service.exceptions.NotImplemented;
|
58
|
import org.dataone.service.exceptions.ServiceFailure;
|
59
|
import org.dataone.service.exceptions.UnsupportedType;
|
60
|
import org.dataone.service.types.v1.AccessRule;
|
61
|
import org.dataone.service.types.v1.DescribeResponse;
|
62
|
import org.dataone.service.types.v1.Group;
|
63
|
import org.dataone.service.types.v1.Identifier;
|
64
|
import org.dataone.service.types.v2.Log;
|
65
|
import org.dataone.service.types.v2.Node;
|
66
|
import org.dataone.service.types.v1.Event;
|
67
|
import org.dataone.service.types.v1.NodeReference;
|
68
|
import org.dataone.service.types.v1.NodeType;
|
69
|
import org.dataone.service.types.v2.ObjectFormat;
|
70
|
import org.dataone.service.types.v1.Permission;
|
71
|
import org.dataone.service.types.v1.Replica;
|
72
|
import org.dataone.service.types.v1.Session;
|
73
|
import org.dataone.service.types.v1.Subject;
|
74
|
import org.dataone.service.types.v2.SystemMetadata;
|
75
|
import org.dataone.service.types.v1.util.AuthUtils;
|
76
|
import org.dataone.service.types.v1.util.ChecksumUtil;
|
77
|
import org.dataone.service.util.Constants;
|
78
|
|
79
|
import edu.ucsb.nceas.metacat.AccessionNumberException;
|
80
|
import edu.ucsb.nceas.metacat.DocumentImpl;
|
81
|
import edu.ucsb.nceas.metacat.EventLog;
|
82
|
import edu.ucsb.nceas.metacat.IdentifierManager;
|
83
|
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
|
84
|
import edu.ucsb.nceas.metacat.MetacatHandler;
|
85
|
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
|
86
|
import edu.ucsb.nceas.metacat.database.DBConnection;
|
87
|
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
|
88
|
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
|
89
|
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
|
90
|
import edu.ucsb.nceas.metacat.properties.PropertyService;
|
91
|
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
|
92
|
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
|
93
|
|
94
|
public abstract class D1NodeService {
|
95
|
|
96
|
private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
|
97
|
|
98
|
/** For logging the operations */
|
99
|
protected HttpServletRequest request;
|
100
|
|
101
|
/* reference to the metacat handler */
|
102
|
protected MetacatHandler handler;
|
103
|
|
104
|
/* parameters set in the incoming request */
|
105
|
private Hashtable<String, String[]> params;
|
106
|
|
107
|
/**
|
108
|
* limit paged results sets to a configured maximum
|
109
|
*/
|
110
|
protected static int MAXIMUM_DB_RECORD_COUNT = 7000;
|
111
|
|
112
|
static {
|
113
|
try {
|
114
|
MAXIMUM_DB_RECORD_COUNT = Integer.valueOf(PropertyService.getProperty("database.webResultsetSize"));
|
115
|
} catch (Exception e) {
|
116
|
logMetacat.warn("Could not set MAXIMUM_DB_RECORD_COUNT", e);
|
117
|
}
|
118
|
}
|
119
|
|
120
|
/**
|
121
|
* out-of-band session object to be used when not passed in as a method parameter
|
122
|
*/
|
123
|
protected Session session;
|
124
|
|
125
|
/**
|
126
|
* Constructor - used to set the metacatUrl from a subclass extending D1NodeService
|
127
|
*
|
128
|
* @param metacatUrl - the URL of the metacat service, including the ending /d1
|
129
|
*/
|
130
|
public D1NodeService(HttpServletRequest request) {
|
131
|
this.request = request;
|
132
|
}
|
133
|
|
134
|
/**
|
135
|
* retrieve the out-of-band session
|
136
|
* @return
|
137
|
*/
|
138
|
public Session getSession() {
|
139
|
return session;
|
140
|
}
|
141
|
|
142
|
/**
|
143
|
* Set the out-of-band session
|
144
|
* @param session
|
145
|
*/
|
146
|
public void setSession(Session session) {
|
147
|
this.session = session;
|
148
|
}
|
149
|
|
150
|
/**
|
151
|
* This method provides a lighter weight mechanism than
|
152
|
* getSystemMetadata() for a client to determine basic
|
153
|
* properties of the referenced object.
|
154
|
*
|
155
|
* @param session - the Session object containing the credentials for the Subject
|
156
|
* @param pid - the identifier of the object to be described
|
157
|
*
|
158
|
* @return describeResponse - A set of values providing a basic description
|
159
|
* of the object.
|
160
|
*
|
161
|
* @throws InvalidToken
|
162
|
* @throws ServiceFailure
|
163
|
* @throws NotAuthorized
|
164
|
* @throws NotFound
|
165
|
* @throws NotImplemented
|
166
|
* @throws InvalidRequest
|
167
|
*/
|
168
|
public DescribeResponse describe(Session session, Identifier pid)
|
169
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
|
170
|
|
171
|
// get system metadata and construct the describe response
|
172
|
SystemMetadata sysmeta = getSystemMetadata(session, pid);
|
173
|
DescribeResponse describeResponse =
|
174
|
new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(),
|
175
|
sysmeta.getDateSysMetadataModified(),
|
176
|
sysmeta.getChecksum(), sysmeta.getSerialVersion());
|
177
|
|
178
|
return describeResponse;
|
179
|
|
180
|
}
|
181
|
|
182
|
/**
|
183
|
* Deletes an object from the Member Node, where the object is either a
|
184
|
* data object or a science metadata object.
|
185
|
*
|
186
|
* @param session - the Session object containing the credentials for the Subject
|
187
|
* @param pid - The object identifier to be deleted
|
188
|
*
|
189
|
* @return pid - the identifier of the object used for the deletion
|
190
|
*
|
191
|
* @throws InvalidToken
|
192
|
* @throws ServiceFailure
|
193
|
* @throws NotAuthorized
|
194
|
* @throws NotFound
|
195
|
* @throws NotImplemented
|
196
|
* @throws InvalidRequest
|
197
|
*/
|
198
|
public Identifier delete(Session session, Identifier pid)
|
199
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
|
200
|
|
201
|
String localId = null;
|
202
|
if (session == null) {
|
203
|
throw new InvalidToken("1330", "No session has been provided");
|
204
|
}
|
205
|
// just for logging purposes
|
206
|
String username = session.getSubject().getValue();
|
207
|
|
208
|
// do we have a valid pid?
|
209
|
if (pid == null || pid.getValue().trim().equals("")) {
|
210
|
throw new ServiceFailure("1350", "The provided identifier was invalid.");
|
211
|
}
|
212
|
|
213
|
// check for the existing identifier
|
214
|
try {
|
215
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
216
|
} catch (McdbDocNotFoundException e) {
|
217
|
throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
|
218
|
}
|
219
|
|
220
|
try {
|
221
|
// delete the document, as admin
|
222
|
DocumentImpl.delete(localId, null, null, null, true);
|
223
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
|
224
|
|
225
|
// archive it
|
226
|
// DocumentImpl.delete() now sets this
|
227
|
// see https://redmine.dataone.org/issues/3406
|
228
|
// SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
229
|
// sysMeta.setArchived(true);
|
230
|
// sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
|
231
|
// HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
|
232
|
|
233
|
} catch (McdbDocNotFoundException e) {
|
234
|
throw new NotFound("1340", "The provided identifier was invalid.");
|
235
|
|
236
|
} catch (SQLException e) {
|
237
|
throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
|
238
|
|
239
|
} catch (InsufficientKarmaException e) {
|
240
|
if ( logMetacat.isDebugEnabled() ) {
|
241
|
e.printStackTrace();
|
242
|
}
|
243
|
throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
|
244
|
|
245
|
} catch (Exception e) { // for some reason DocumentImpl throws a general Exception
|
246
|
throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
|
247
|
}
|
248
|
|
249
|
return pid;
|
250
|
}
|
251
|
|
252
|
/**
|
253
|
* Low level, "are you alive" operation. A valid ping response is
|
254
|
* indicated by a HTTP status of 200.
|
255
|
*
|
256
|
* @return true if the service is alive
|
257
|
*
|
258
|
* @throws NotImplemented
|
259
|
* @throws ServiceFailure
|
260
|
* @throws InsufficientResources
|
261
|
*/
|
262
|
public Date ping()
|
263
|
throws NotImplemented, ServiceFailure, InsufficientResources {
|
264
|
|
265
|
// test if we can get a database connection
|
266
|
int serialNumber = -1;
|
267
|
DBConnection dbConn = null;
|
268
|
try {
|
269
|
dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
|
270
|
serialNumber = dbConn.getCheckOutSerialNumber();
|
271
|
} catch (SQLException e) {
|
272
|
ServiceFailure sf = new ServiceFailure("", e.getMessage());
|
273
|
sf.initCause(e);
|
274
|
throw sf;
|
275
|
} finally {
|
276
|
// Return the database connection
|
277
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
278
|
}
|
279
|
|
280
|
return Calendar.getInstance().getTime();
|
281
|
}
|
282
|
|
283
|
/**
|
284
|
* Adds a new object to the Node, where the object is either a data
|
285
|
* object or a science metadata object. This method is called by clients
|
286
|
* to create new data objects on Member Nodes or internally for Coordinating
|
287
|
* Nodes
|
288
|
*
|
289
|
* @param session - the Session object containing the credentials for the Subject
|
290
|
* @param pid - The object identifier to be created
|
291
|
* @param object - the object bytes
|
292
|
* @param sysmeta - the system metadata that describes the object
|
293
|
*
|
294
|
* @return pid - the object identifier created
|
295
|
*
|
296
|
* @throws InvalidToken
|
297
|
* @throws ServiceFailure
|
298
|
* @throws NotAuthorized
|
299
|
* @throws IdentifierNotUnique
|
300
|
* @throws UnsupportedType
|
301
|
* @throws InsufficientResources
|
302
|
* @throws InvalidSystemMetadata
|
303
|
* @throws NotImplemented
|
304
|
* @throws InvalidRequest
|
305
|
*/
|
306
|
public Identifier create(Session session, Identifier pid, InputStream object,
|
307
|
SystemMetadata sysmeta)
|
308
|
throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
|
309
|
UnsupportedType, InsufficientResources, InvalidSystemMetadata,
|
310
|
NotImplemented, InvalidRequest {
|
311
|
|
312
|
Identifier resultPid = null;
|
313
|
String localId = null;
|
314
|
boolean allowed = false;
|
315
|
|
316
|
// check for null session
|
317
|
if (session == null) {
|
318
|
throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
|
319
|
}
|
320
|
Subject subject = session.getSubject();
|
321
|
|
322
|
Subject publicSubject = new Subject();
|
323
|
publicSubject.setValue(Constants.SUBJECT_PUBLIC);
|
324
|
// be sure the user is authenticated for create()
|
325
|
if (subject == null || subject.getValue() == null ||
|
326
|
subject.equals(publicSubject) ) {
|
327
|
throw new NotAuthorized("1100", "The provided identity does not have " +
|
328
|
"permission to WRITE to the Node.");
|
329
|
|
330
|
}
|
331
|
|
332
|
// verify the pid is valid format
|
333
|
if (!isValidIdentifier(pid)) {
|
334
|
throw new InvalidRequest("1202", "The provided identifier is invalid.");
|
335
|
}
|
336
|
|
337
|
// verify that pid == SystemMetadata.getIdentifier()
|
338
|
logMetacat.debug("Comparing pid|sysmeta_pid: " +
|
339
|
pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
|
340
|
if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
341
|
throw new InvalidSystemMetadata("1180",
|
342
|
"The supplied system metadata is invalid. " +
|
343
|
"The identifier " + pid.getValue() + " does not match identifier" +
|
344
|
"in the system metadata identified by " +
|
345
|
sysmeta.getIdentifier().getValue() + ".");
|
346
|
|
347
|
}
|
348
|
|
349
|
logMetacat.debug("Checking if identifier exists: " + pid.getValue());
|
350
|
// Check that the identifier does not already exist
|
351
|
if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
|
352
|
throw new IdentifierNotUnique("1120",
|
353
|
"The requested identifier " + pid.getValue() +
|
354
|
" is already used by another object and" +
|
355
|
"therefore can not be used for this object. Clients should choose" +
|
356
|
"a new identifier that is unique and retry the operation or " +
|
357
|
"use CN.reserveIdentifier() to reserve one.");
|
358
|
|
359
|
}
|
360
|
|
361
|
// TODO: this probably needs to be refined more
|
362
|
try {
|
363
|
allowed = isAuthorized(session, pid, Permission.WRITE);
|
364
|
|
365
|
} catch (NotFound e) {
|
366
|
// The identifier doesn't exist, writing should be fine.
|
367
|
allowed = true;
|
368
|
}
|
369
|
|
370
|
// verify checksum, only if we can reset the inputstream
|
371
|
if (object.markSupported()) {
|
372
|
logMetacat.debug("Checking checksum for: " + pid.getValue());
|
373
|
String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
|
374
|
String checksumValue = sysmeta.getChecksum().getValue();
|
375
|
try {
|
376
|
String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
|
377
|
// it's very important that we don't consume the stream
|
378
|
object.reset();
|
379
|
if (!computedChecksumValue.equals(checksumValue)) {
|
380
|
logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
|
381
|
throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
|
382
|
}
|
383
|
} catch (Exception e) {
|
384
|
String msg = "Error verifying checksum values";
|
385
|
logMetacat.error(msg, e);
|
386
|
throw new ServiceFailure("1190", msg + ": " + e.getMessage());
|
387
|
}
|
388
|
} else {
|
389
|
logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
|
390
|
}
|
391
|
|
392
|
// we have the go ahead
|
393
|
if ( allowed ) {
|
394
|
|
395
|
logMetacat.debug("Allowed to insert: " + pid.getValue());
|
396
|
|
397
|
// Science metadata (XML) or science data object?
|
398
|
// TODO: there are cases where certain object formats are science metadata
|
399
|
// but are not XML (netCDF ...). Handle this.
|
400
|
if ( isScienceMetadata(sysmeta) ) {
|
401
|
|
402
|
// CASE METADATA:
|
403
|
String objectAsXML = "";
|
404
|
try {
|
405
|
objectAsXML = IOUtils.toString(object, "UTF-8");
|
406
|
localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
|
407
|
//localId = im.getLocalId(pid.getValue());
|
408
|
|
409
|
} catch (IOException e) {
|
410
|
String msg = "The Node is unable to create the object. " +
|
411
|
"There was a problem converting the object to XML";
|
412
|
logMetacat.info(msg);
|
413
|
throw new ServiceFailure("1190", msg + ": " + e.getMessage());
|
414
|
|
415
|
}
|
416
|
|
417
|
} else {
|
418
|
|
419
|
// DEFAULT CASE: DATA (needs to be checked and completed)
|
420
|
localId = insertDataObject(object, pid, session);
|
421
|
}
|
422
|
|
423
|
}
|
424
|
|
425
|
logMetacat.debug("Done inserting new object: " + pid.getValue());
|
426
|
|
427
|
// save the sysmeta
|
428
|
try {
|
429
|
// lock and unlock of the pid happens in the subclass
|
430
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
|
431
|
// submit for indexing
|
432
|
MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
|
433
|
|
434
|
} catch (Exception e) {
|
435
|
logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
|
436
|
throw new ServiceFailure("1190", e.getMessage());
|
437
|
}
|
438
|
|
439
|
// setting the resulting identifier failed
|
440
|
if (localId == null ) {
|
441
|
throw new ServiceFailure("1190", "The Node is unable to create the object. ");
|
442
|
}
|
443
|
|
444
|
resultPid = pid;
|
445
|
|
446
|
logMetacat.debug("create() complete for object: " + pid.getValue());
|
447
|
|
448
|
return resultPid;
|
449
|
}
|
450
|
|
451
|
/**
|
452
|
* Return the log records associated with a given event between the start and
|
453
|
* end dates listed given a particular Subject listed in the Session
|
454
|
*
|
455
|
* @param session - the Session object containing the credentials for the Subject
|
456
|
* @param fromDate - the start date of the desired log records
|
457
|
* @param toDate - the end date of the desired log records
|
458
|
* @param event - restrict log records of a specific event type
|
459
|
* @param start - zero based offset from the first record in the
|
460
|
* set of matching log records. Used to assist with
|
461
|
* paging the response.
|
462
|
* @param count - maximum number of log records to return in the response.
|
463
|
* Used to assist with paging the response.
|
464
|
*
|
465
|
* @return the desired log records
|
466
|
*
|
467
|
* @throws InvalidToken
|
468
|
* @throws ServiceFailure
|
469
|
* @throws NotAuthorized
|
470
|
* @throws InvalidRequest
|
471
|
* @throws NotImplemented
|
472
|
*/
|
473
|
public Log getLogRecords(Session session, Date fromDate, Date toDate,
|
474
|
String event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
|
475
|
NotAuthorized, InvalidRequest, NotImplemented {
|
476
|
|
477
|
// only admin access to this method
|
478
|
// see https://redmine.dataone.org/issues/2855
|
479
|
if (!isAdminAuthorized(session)) {
|
480
|
throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
|
481
|
}
|
482
|
|
483
|
IdentifierManager im = IdentifierManager.getInstance();
|
484
|
EventLog el = EventLog.getInstance();
|
485
|
if ( fromDate == null ) {
|
486
|
logMetacat.debug("setting fromdate from null");
|
487
|
fromDate = new Date(1);
|
488
|
}
|
489
|
if ( toDate == null ) {
|
490
|
logMetacat.debug("setting todate from null");
|
491
|
toDate = new Date();
|
492
|
}
|
493
|
|
494
|
if ( start == null ) {
|
495
|
start = 0;
|
496
|
}
|
497
|
|
498
|
if ( count == null ) {
|
499
|
count = 1000;
|
500
|
}
|
501
|
|
502
|
// safeguard against large requests
|
503
|
if (count > MAXIMUM_DB_RECORD_COUNT) {
|
504
|
count = MAXIMUM_DB_RECORD_COUNT;
|
505
|
}
|
506
|
|
507
|
String[] filterDocid = null;
|
508
|
if (pidFilter != null) {
|
509
|
try {
|
510
|
String localId = im.getLocalId(pidFilter);
|
511
|
filterDocid = new String[] {localId};
|
512
|
} catch (Exception ex) {
|
513
|
String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
|
514
|
logMetacat.warn(msg, ex);
|
515
|
//throw new InvalidRequest("1480", msg);
|
516
|
}
|
517
|
}
|
518
|
|
519
|
logMetacat.debug("fromDate: " + fromDate);
|
520
|
logMetacat.debug("toDate: " + toDate);
|
521
|
|
522
|
Log log = el.getD1Report(null, null, filterDocid, event,
|
523
|
new java.sql.Timestamp(fromDate.getTime()),
|
524
|
new java.sql.Timestamp(toDate.getTime()), false, start, count);
|
525
|
|
526
|
logMetacat.info("getLogRecords");
|
527
|
return log;
|
528
|
}
|
529
|
|
530
|
/**
|
531
|
* Return the object identified by the given object identifier
|
532
|
*
|
533
|
* @param session - the Session object containing the credentials for the Subject
|
534
|
* @param pid - the object identifier for the given object
|
535
|
*
|
536
|
* TODO: The D1 Authorization API doesn't provide information on which
|
537
|
* authentication system the Subject belongs to, and so it's not possible to
|
538
|
* discern which Person or Group is a valid KNB LDAP DN. Fix this.
|
539
|
*
|
540
|
* @return inputStream - the input stream of the given object
|
541
|
*
|
542
|
* @throws InvalidToken
|
543
|
* @throws ServiceFailure
|
544
|
* @throws NotAuthorized
|
545
|
* @throws InvalidRequest
|
546
|
* @throws NotImplemented
|
547
|
*/
|
548
|
public InputStream get(Session session, Identifier pid)
|
549
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
550
|
NotImplemented {
|
551
|
|
552
|
InputStream inputStream = null; // bytes to be returned
|
553
|
handler = new MetacatHandler(new Timer());
|
554
|
boolean allowed = false;
|
555
|
String localId; // the metacat docid for the pid
|
556
|
|
557
|
// get the local docid from Metacat
|
558
|
try {
|
559
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
560
|
|
561
|
} catch (McdbDocNotFoundException e) {
|
562
|
throw new NotFound("1020", "The object specified by " +
|
563
|
pid.getValue() +
|
564
|
" does not exist at this node.");
|
565
|
}
|
566
|
|
567
|
// check for authorization
|
568
|
try {
|
569
|
allowed = isAuthorized(session, pid, Permission.READ);
|
570
|
} catch (InvalidRequest e) {
|
571
|
throw new ServiceFailure("1030", e.getDescription());
|
572
|
}
|
573
|
|
574
|
// if the person is authorized, perform the read
|
575
|
if (allowed) {
|
576
|
try {
|
577
|
inputStream = handler.read(localId);
|
578
|
} catch (Exception e) {
|
579
|
throw new NotFound("1020", "The object specified by " +
|
580
|
pid.getValue() +
|
581
|
"could not be returned due to error: " +
|
582
|
e.getMessage());
|
583
|
}
|
584
|
}
|
585
|
|
586
|
// if we fail to set the input stream
|
587
|
if ( inputStream == null ) {
|
588
|
throw new NotFound("1020", "The object specified by " +
|
589
|
pid.getValue() +
|
590
|
"does not exist at this node.");
|
591
|
}
|
592
|
|
593
|
// log the read event
|
594
|
String principal = Constants.SUBJECT_PUBLIC;
|
595
|
if (session != null && session.getSubject() != null) {
|
596
|
principal = session.getSubject().getValue();
|
597
|
}
|
598
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
|
599
|
|
600
|
return inputStream;
|
601
|
}
|
602
|
|
603
|
/**
|
604
|
* Return the system metadata for a given object
|
605
|
*
|
606
|
* @param session - the Session object containing the credentials for the Subject
|
607
|
* @param pid - the object identifier for the given object
|
608
|
*
|
609
|
* @return inputStream - the input stream of the given system metadata object
|
610
|
*
|
611
|
* @throws InvalidToken
|
612
|
* @throws ServiceFailure
|
613
|
* @throws NotAuthorized
|
614
|
* @throws NotFound
|
615
|
* @throws InvalidRequest
|
616
|
* @throws NotImplemented
|
617
|
*/
|
618
|
public SystemMetadata getSystemMetadata(Session session, Identifier pid)
|
619
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
|
620
|
NotImplemented {
|
621
|
|
622
|
boolean isAuthorized = false;
|
623
|
SystemMetadata systemMetadata = null;
|
624
|
List<Replica> replicaList = null;
|
625
|
NodeReference replicaNodeRef = null;
|
626
|
List<Node> nodeListBySubject = null;
|
627
|
Subject subject = null;
|
628
|
|
629
|
if (session != null ) {
|
630
|
subject = session.getSubject();
|
631
|
}
|
632
|
|
633
|
// check normal authorization
|
634
|
BaseException originalAuthorizationException = null;
|
635
|
if (!isAuthorized) {
|
636
|
try {
|
637
|
isAuthorized = isAuthorized(session, pid, Permission.READ);
|
638
|
|
639
|
} catch (InvalidRequest e) {
|
640
|
throw new ServiceFailure("1090", e.getDescription());
|
641
|
} catch (NotAuthorized nae) {
|
642
|
// catch this for later
|
643
|
originalAuthorizationException = nae;
|
644
|
}
|
645
|
}
|
646
|
|
647
|
// get the system metadata first because we need the replica list for auth
|
648
|
systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
649
|
|
650
|
// check the replica information to expand access to MNs that might need it
|
651
|
if (!isAuthorized) {
|
652
|
|
653
|
try {
|
654
|
|
655
|
// if MNs are listed as replicas, allow access
|
656
|
if ( systemMetadata != null ) {
|
657
|
replicaList = systemMetadata.getReplicaList();
|
658
|
// only check if there are in fact replicas listed
|
659
|
if ( replicaList != null ) {
|
660
|
|
661
|
if ( subject != null ) {
|
662
|
// get the list of nodes with a matching node subject
|
663
|
try {
|
664
|
nodeListBySubject = listNodesBySubject(session.getSubject());
|
665
|
|
666
|
} catch (BaseException e) {
|
667
|
// Unexpected error contacting the CN via D1Client
|
668
|
String msg = "Caught an unexpected error while trying "
|
669
|
+ "to potentially authorize system metadata access "
|
670
|
+ "based on the session subject. The error was "
|
671
|
+ e.getMessage();
|
672
|
logMetacat.error(msg);
|
673
|
if (logMetacat.isDebugEnabled()) {
|
674
|
e.printStackTrace();
|
675
|
|
676
|
}
|
677
|
// isAuthorized is still false
|
678
|
}
|
679
|
|
680
|
}
|
681
|
if (nodeListBySubject != null) {
|
682
|
// compare node ids to replica node ids
|
683
|
outer: for (Replica replica : replicaList) {
|
684
|
replicaNodeRef = replica.getReplicaMemberNode();
|
685
|
|
686
|
for (Node node : nodeListBySubject) {
|
687
|
if (node.getIdentifier().equals(replicaNodeRef)) {
|
688
|
// node id via session subject matches a replica node
|
689
|
isAuthorized = true;
|
690
|
break outer;
|
691
|
}
|
692
|
}
|
693
|
}
|
694
|
}
|
695
|
}
|
696
|
}
|
697
|
|
698
|
// if we still aren't authorized, then we are done
|
699
|
if (!isAuthorized) {
|
700
|
throw new NotAuthorized("1400", Permission.READ
|
701
|
+ " not allowed on " + pid.getValue());
|
702
|
}
|
703
|
|
704
|
} catch (RuntimeException e) {
|
705
|
e.printStackTrace();
|
706
|
// convert hazelcast RuntimeException to ServiceFailure
|
707
|
throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " +
|
708
|
pid.getValue());
|
709
|
}
|
710
|
|
711
|
}
|
712
|
|
713
|
// It wasn't in the map
|
714
|
if ( systemMetadata == null ) {
|
715
|
throw new NotFound("1420", "No record found for: " + pid.getValue());
|
716
|
}
|
717
|
|
718
|
return systemMetadata;
|
719
|
}
|
720
|
|
721
|
|
722
|
/**
|
723
|
* Test if the specified session represents the authoritative member node for the
|
724
|
* given object specified by the identifier. According the the DataONE documentation,
|
725
|
* the authoritative member node has all the rights of the *rightsHolder*.
|
726
|
* @param session - the Session object containing the credentials for the Subject
|
727
|
* @param pid - the Identifier of the data object
|
728
|
* @return true if the session represents the authoritative mn.
|
729
|
* @throws ServiceFailure
|
730
|
* @throws NotImplemented
|
731
|
*/
|
732
|
public boolean isAuthoritativeMNodeAdmin(Session session, Identifier pid) {
|
733
|
boolean allowed = false;
|
734
|
//check the parameters
|
735
|
if(session == null) {
|
736
|
logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the session object is null and return false.");
|
737
|
return allowed;
|
738
|
} else if (pid == null || pid.getValue() == null || pid.getValue().trim().equals("")) {
|
739
|
logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the Identifier object is null (not being specified) and return false.");
|
740
|
return allowed;
|
741
|
}
|
742
|
|
743
|
//Get the subject from the session
|
744
|
Subject subject = session.getSubject();
|
745
|
if(subject != null) {
|
746
|
//Get the authoritative member node info from the system metadata
|
747
|
SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
748
|
if(sysMeta != null) {
|
749
|
NodeReference authoritativeMNode = sysMeta.getAuthoritativeMemberNode();
|
750
|
if(authoritativeMNode != null) {
|
751
|
CNode cn = null;
|
752
|
try {
|
753
|
cn = D1Client.getCN();
|
754
|
} catch (BaseException e) {
|
755
|
logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't connect to the CN since "+
|
756
|
e.getDescription()+ ". The false value will be returned for the AuthoritativeMNodeAdmin.");
|
757
|
return allowed;
|
758
|
}
|
759
|
|
760
|
if(cn != null) {
|
761
|
List<Node> nodes = null;
|
762
|
try {
|
763
|
nodes = cn.listNodes().getNodeList();
|
764
|
} catch (NotImplemented e) {
|
765
|
logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+e.getDescription()+
|
766
|
". The false value will be returned for the AuthoritativeMNodeAdmin.");
|
767
|
return allowed;
|
768
|
} catch (ServiceFailure ee) {
|
769
|
logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+ee.getDescription()+
|
770
|
". The false value will be returned for the AuthoritativeMNodeAdmin.");
|
771
|
return allowed;
|
772
|
}
|
773
|
if(nodes != null) {
|
774
|
for(Node node : nodes) {
|
775
|
//find the authoritative node and get its subjects
|
776
|
if (node.getType() == NodeType.MN && node.getIdentifier() != null && node.getIdentifier().equals(authoritativeMNode)) {
|
777
|
List<Subject> nodeSubjects = node.getSubjectList();
|
778
|
if(nodeSubjects != null) {
|
779
|
// check if the session subject is in the node subject list
|
780
|
for (Subject nodeSubject : nodeSubjects) {
|
781
|
logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin(), comparing subjects: " +
|
782
|
nodeSubject.getValue() + " and " + subject.getValue());
|
783
|
if ( nodeSubject != null && nodeSubject.equals(subject) ) {
|
784
|
allowed = true; // subject of session == target node subject
|
785
|
break;
|
786
|
}
|
787
|
}
|
788
|
}
|
789
|
|
790
|
}
|
791
|
}
|
792
|
}
|
793
|
}
|
794
|
}
|
795
|
}
|
796
|
}
|
797
|
return allowed;
|
798
|
}
|
799
|
|
800
|
|
801
|
/**
|
802
|
* Test if the user identified by the provided token has administrative authorization
|
803
|
*
|
804
|
* @param session - the Session object containing the credentials for the Subject
|
805
|
*
|
806
|
* @return true if the user is admin
|
807
|
*
|
808
|
* @throws ServiceFailure
|
809
|
* @throws InvalidToken
|
810
|
* @throws NotFound
|
811
|
* @throws NotAuthorized
|
812
|
* @throws NotImplemented
|
813
|
*/
|
814
|
public boolean isAdminAuthorized(Session session)
|
815
|
throws ServiceFailure, InvalidToken, NotAuthorized,
|
816
|
NotImplemented {
|
817
|
|
818
|
boolean allowed = false;
|
819
|
|
820
|
// must have a session in order to check admin
|
821
|
if (session == null) {
|
822
|
logMetacat.debug("In isAdminAuthorized(), session is null ");
|
823
|
return false;
|
824
|
}
|
825
|
|
826
|
logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
|
827
|
session.getSubject().getValue());
|
828
|
|
829
|
// check if this is the node calling itself (MN)
|
830
|
allowed = isNodeAdmin(session);
|
831
|
|
832
|
// check the CN list
|
833
|
if (!allowed) {
|
834
|
List<Node> nodes = null;
|
835
|
|
836
|
try {
|
837
|
// are we allowed to do this? only CNs are allowed
|
838
|
CNode cn = D1Client.getCN();
|
839
|
nodes = cn.listNodes().getNodeList();
|
840
|
}
|
841
|
catch (Throwable e) {
|
842
|
logMetacat.warn(e.getMessage());
|
843
|
return false;
|
844
|
}
|
845
|
|
846
|
if ( nodes == null ) {
|
847
|
return false;
|
848
|
//throw new ServiceFailure("4852", "Couldn't get node list.");
|
849
|
}
|
850
|
|
851
|
// find the node in the node list
|
852
|
for ( Node node : nodes ) {
|
853
|
|
854
|
NodeReference nodeReference = node.getIdentifier();
|
855
|
logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
|
856
|
|
857
|
Subject subject = session.getSubject();
|
858
|
|
859
|
if (node.getType() == NodeType.CN) {
|
860
|
List<Subject> nodeSubjects = node.getSubjectList();
|
861
|
|
862
|
// check if the session subject is in the node subject list
|
863
|
for (Subject nodeSubject : nodeSubjects) {
|
864
|
logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
|
865
|
nodeSubject.getValue() + " and " + subject.getValue());
|
866
|
if ( nodeSubject.equals(subject) ) {
|
867
|
allowed = true; // subject of session == target node subject
|
868
|
break;
|
869
|
|
870
|
}
|
871
|
}
|
872
|
}
|
873
|
}
|
874
|
}
|
875
|
|
876
|
return allowed;
|
877
|
}
|
878
|
|
879
|
/**
|
880
|
* Test if the user identified by the provided token has administrative authorization
|
881
|
* on this node because they are calling themselves
|
882
|
*
|
883
|
* @param session - the Session object containing the credentials for the Subject
|
884
|
*
|
885
|
* @return true if the user is this node
|
886
|
* @throws ServiceFailure
|
887
|
* @throws NotImplemented
|
888
|
*/
|
889
|
public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
|
890
|
|
891
|
boolean allowed = false;
|
892
|
|
893
|
// must have a session in order to check admin
|
894
|
if (session == null) {
|
895
|
logMetacat.debug("In isNodeAdmin(), session is null ");
|
896
|
return false;
|
897
|
}
|
898
|
|
899
|
logMetacat.debug("In isNodeAdmin(), MN authorization for " +
|
900
|
session.getSubject().getValue());
|
901
|
|
902
|
Node node = MNodeService.getInstance(request).getCapabilities();
|
903
|
NodeReference nodeReference = node.getIdentifier();
|
904
|
logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
|
905
|
|
906
|
Subject subject = session.getSubject();
|
907
|
|
908
|
if (node.getType() == NodeType.MN) {
|
909
|
List<Subject> nodeSubjects = node.getSubjectList();
|
910
|
|
911
|
// check if the session subject is in the node subject list
|
912
|
for (Subject nodeSubject : nodeSubjects) {
|
913
|
logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
|
914
|
nodeSubject.getValue() + " and " + subject.getValue());
|
915
|
if ( nodeSubject.equals(subject) ) {
|
916
|
allowed = true; // subject of session == this node's subect
|
917
|
break;
|
918
|
}
|
919
|
}
|
920
|
}
|
921
|
|
922
|
return allowed;
|
923
|
}
|
924
|
|
925
|
/**
|
926
|
* Test if the user identified by the provided token has authorization
|
927
|
* for the operation on the specified object.
|
928
|
*
|
929
|
* @param session - the Session object containing the credentials for the Subject
|
930
|
* @param pid - The identifer of the resource for which access is being checked
|
931
|
* @param operation - The type of operation which is being requested for the given pid
|
932
|
*
|
933
|
* @return true if the operation is allowed
|
934
|
*
|
935
|
* @throws ServiceFailure
|
936
|
* @throws InvalidToken
|
937
|
* @throws NotFound
|
938
|
* @throws NotAuthorized
|
939
|
* @throws NotImplemented
|
940
|
* @throws InvalidRequest
|
941
|
*/
|
942
|
public boolean isAuthorized(Session session, Identifier pid, Permission permission)
|
943
|
throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
|
944
|
NotImplemented, InvalidRequest {
|
945
|
|
946
|
boolean allowed = false;
|
947
|
|
948
|
if (permission == null) {
|
949
|
throw new InvalidRequest("1761", "Permission was not provided or is invalid");
|
950
|
}
|
951
|
|
952
|
// permissions are hierarchical
|
953
|
List<Permission> expandedPermissions = null;
|
954
|
|
955
|
// always allow CN access
|
956
|
if ( isAdminAuthorized(session) ) {
|
957
|
allowed = true;
|
958
|
return allowed;
|
959
|
|
960
|
}
|
961
|
|
962
|
// the authoritative member node of the pid always has the access as well.
|
963
|
if (isAuthoritativeMNodeAdmin(session, pid)) {
|
964
|
allowed = true;
|
965
|
return allowed;
|
966
|
}
|
967
|
|
968
|
// get the subject[s] from the session
|
969
|
//defer to the shared util for recursively compiling the subjects
|
970
|
Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
|
971
|
|
972
|
// track the identities we have checked against
|
973
|
StringBuffer includedSubjects = new StringBuffer();
|
974
|
|
975
|
// get the system metadata
|
976
|
String pidStr = pid.getValue();
|
977
|
SystemMetadata systemMetadata = null;
|
978
|
try {
|
979
|
systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
980
|
|
981
|
} catch (Exception e) {
|
982
|
// convert Hazelcast RuntimeException to NotFound
|
983
|
logMetacat.error("An error occurred while getting system metadata for identifier " +
|
984
|
pid.getValue() + ". The error message was: " + e.getMessage());
|
985
|
throw new NotFound("1800", "No record found for " + pidStr);
|
986
|
|
987
|
}
|
988
|
|
989
|
// throw not found if it was not found
|
990
|
if (systemMetadata == null) {
|
991
|
throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
|
992
|
}
|
993
|
|
994
|
// do we own it?
|
995
|
for (Subject s: subjects) {
|
996
|
logMetacat.debug("Comparing \t" +
|
997
|
systemMetadata.getRightsHolder().getValue() +
|
998
|
" \tagainst \t" + s.getValue());
|
999
|
includedSubjects.append(s.getValue() + "; ");
|
1000
|
allowed = systemMetadata.getRightsHolder().equals(s);
|
1001
|
if (allowed) {
|
1002
|
return allowed;
|
1003
|
}
|
1004
|
}
|
1005
|
|
1006
|
// otherwise check the access rules
|
1007
|
try {
|
1008
|
List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
|
1009
|
search: // label break
|
1010
|
for (AccessRule accessRule: allows) {
|
1011
|
for (Subject s: subjects) {
|
1012
|
logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
|
1013
|
if (accessRule.getSubjectList().contains(s)) {
|
1014
|
logMetacat.debug("Access rule contains subject: " + s.getValue());
|
1015
|
for (Permission p: accessRule.getPermissionList()) {
|
1016
|
logMetacat.debug("Checking permission: " + p.xmlValue());
|
1017
|
expandedPermissions = expandPermissions(p);
|
1018
|
allowed = expandedPermissions.contains(permission);
|
1019
|
if (allowed) {
|
1020
|
logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
|
1021
|
break search; //label break
|
1022
|
}
|
1023
|
}
|
1024
|
|
1025
|
}
|
1026
|
}
|
1027
|
}
|
1028
|
} catch (Exception e) {
|
1029
|
// catch all for errors - safe side should be to deny the access
|
1030
|
logMetacat.error("Problem checking authorization - defaulting to deny", e);
|
1031
|
allowed = false;
|
1032
|
|
1033
|
}
|
1034
|
|
1035
|
// throw or return?
|
1036
|
if (!allowed) {
|
1037
|
throw new NotAuthorized("1820", permission + " not allowed on " + pidStr + " for subject[s]: " + includedSubjects.toString() );
|
1038
|
}
|
1039
|
|
1040
|
return allowed;
|
1041
|
|
1042
|
}
|
1043
|
|
1044
|
/*
|
1045
|
* parse a logEntry and get the relevant field from it
|
1046
|
*
|
1047
|
* @param fieldname
|
1048
|
* @param entry
|
1049
|
* @return
|
1050
|
*/
|
1051
|
private String getLogEntryField(String fieldname, String entry) {
|
1052
|
String begin = "<" + fieldname + ">";
|
1053
|
String end = "</" + fieldname + ">";
|
1054
|
// logMetacat.debug("looking for " + begin + " and " + end +
|
1055
|
// " in entry " + entry);
|
1056
|
String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
|
1057
|
.indexOf(end));
|
1058
|
logMetacat.debug("entry " + fieldname + " : " + s);
|
1059
|
return s;
|
1060
|
}
|
1061
|
|
1062
|
/**
|
1063
|
* Determine if a given object should be treated as an XML science metadata
|
1064
|
* object.
|
1065
|
*
|
1066
|
* @param sysmeta - the SystemMetadata describing the object
|
1067
|
* @return true if the object should be treated as science metadata
|
1068
|
*/
|
1069
|
public static boolean isScienceMetadata(SystemMetadata sysmeta) {
|
1070
|
|
1071
|
ObjectFormat objectFormat = null;
|
1072
|
boolean isScienceMetadata = false;
|
1073
|
|
1074
|
try {
|
1075
|
objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
|
1076
|
if ( objectFormat.getFormatType().equals("METADATA") ) {
|
1077
|
isScienceMetadata = true;
|
1078
|
|
1079
|
}
|
1080
|
|
1081
|
|
1082
|
} catch (ServiceFailure e) {
|
1083
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
1084
|
sysmeta.getIdentifier().getValue() +
|
1085
|
" is science metadata: " + e.getMessage());
|
1086
|
|
1087
|
} catch (NotFound e) {
|
1088
|
logMetacat.debug("There was a problem determining if the object identified by" +
|
1089
|
sysmeta.getIdentifier().getValue() +
|
1090
|
" is science metadata: " + e.getMessage());
|
1091
|
|
1092
|
}
|
1093
|
|
1094
|
return isScienceMetadata;
|
1095
|
|
1096
|
}
|
1097
|
|
1098
|
/**
|
1099
|
* Check fro whitespace in the given pid.
|
1100
|
* null pids are also invalid by default
|
1101
|
* @param pid
|
1102
|
* @return
|
1103
|
*/
|
1104
|
public static boolean isValidIdentifier(Identifier pid) {
|
1105
|
if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
|
1106
|
return !pid.getValue().matches(".*\\s+.*");
|
1107
|
}
|
1108
|
return false;
|
1109
|
}
|
1110
|
|
1111
|
|
1112
|
/**
|
1113
|
* Insert or update an XML document into Metacat
|
1114
|
*
|
1115
|
* @param xml - the XML document to insert or update
|
1116
|
* @param pid - the identifier to be used for the resulting object
|
1117
|
*
|
1118
|
* @return localId - the resulting docid of the document created or updated
|
1119
|
*
|
1120
|
*/
|
1121
|
public String insertOrUpdateDocument(String xml, Identifier pid,
|
1122
|
Session session, String insertOrUpdate)
|
1123
|
throws ServiceFailure {
|
1124
|
|
1125
|
logMetacat.debug("Starting to insert xml document...");
|
1126
|
IdentifierManager im = IdentifierManager.getInstance();
|
1127
|
|
1128
|
// generate pid/localId pair for sysmeta
|
1129
|
String localId = null;
|
1130
|
|
1131
|
if(insertOrUpdate.equals("insert")) {
|
1132
|
localId = im.generateLocalId(pid.getValue(), 1);
|
1133
|
|
1134
|
} else {
|
1135
|
//localid should already exist in the identifier table, so just find it
|
1136
|
try {
|
1137
|
logMetacat.debug("Updating pid " + pid.getValue());
|
1138
|
logMetacat.debug("looking in identifier table for pid " + pid.getValue());
|
1139
|
|
1140
|
localId = im.getLocalId(pid.getValue());
|
1141
|
|
1142
|
logMetacat.debug("localId: " + localId);
|
1143
|
//increment the revision
|
1144
|
String docid = localId.substring(0, localId.lastIndexOf("."));
|
1145
|
String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
|
1146
|
int rev = new Integer(revS).intValue();
|
1147
|
rev++;
|
1148
|
docid = docid + "." + rev;
|
1149
|
localId = docid;
|
1150
|
logMetacat.debug("incremented localId: " + localId);
|
1151
|
|
1152
|
} catch(McdbDocNotFoundException e) {
|
1153
|
throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
|
1154
|
"pid " + pid.getValue() +
|
1155
|
" should have been in the identifier table, but it wasn't: " +
|
1156
|
e.getMessage());
|
1157
|
|
1158
|
}
|
1159
|
|
1160
|
}
|
1161
|
|
1162
|
params = new Hashtable<String, String[]>();
|
1163
|
String[] action = new String[1];
|
1164
|
action[0] = insertOrUpdate;
|
1165
|
params.put("action", action);
|
1166
|
String[] docid = new String[1];
|
1167
|
docid[0] = localId;
|
1168
|
params.put("docid", docid);
|
1169
|
String[] doctext = new String[1];
|
1170
|
doctext[0] = xml;
|
1171
|
params.put("doctext", doctext);
|
1172
|
|
1173
|
String username = Constants.SUBJECT_PUBLIC;
|
1174
|
String[] groupnames = null;
|
1175
|
if (session != null ) {
|
1176
|
username = session.getSubject().getValue();
|
1177
|
if (session.getSubjectInfo() != null) {
|
1178
|
List<Group> groupList = session.getSubjectInfo().getGroupList();
|
1179
|
if (groupList != null) {
|
1180
|
groupnames = new String[groupList.size()];
|
1181
|
for (int i = 0; i < groupList.size(); i++ ) {
|
1182
|
groupnames[i] = groupList.get(i).getGroupName();
|
1183
|
}
|
1184
|
}
|
1185
|
}
|
1186
|
}
|
1187
|
|
1188
|
// do the insert or update action
|
1189
|
handler = new MetacatHandler(new Timer());
|
1190
|
String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null,
|
1191
|
null, params, username, groupnames, false, false);
|
1192
|
|
1193
|
if(result.indexOf("<error>") != -1) {
|
1194
|
String detailCode = "";
|
1195
|
if ( insertOrUpdate.equals("insert") ) {
|
1196
|
// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
|
1197
|
im.removeMapping(pid.getValue(), localId);
|
1198
|
detailCode = "1190";
|
1199
|
|
1200
|
} else if ( insertOrUpdate.equals("update") ) {
|
1201
|
detailCode = "1310";
|
1202
|
|
1203
|
}
|
1204
|
throw new ServiceFailure(detailCode,
|
1205
|
"Error inserting or updating document: " + result);
|
1206
|
}
|
1207
|
logMetacat.debug("Finsished inserting xml document with id " + localId);
|
1208
|
|
1209
|
return localId;
|
1210
|
}
|
1211
|
|
1212
|
/**
|
1213
|
* Insert a data document
|
1214
|
*
|
1215
|
* @param object
|
1216
|
* @param pid
|
1217
|
* @param sessionData
|
1218
|
* @throws ServiceFailure
|
1219
|
* @returns localId of the data object inserted
|
1220
|
*/
|
1221
|
public String insertDataObject(InputStream object, Identifier pid,
|
1222
|
Session session) throws ServiceFailure {
|
1223
|
|
1224
|
String username = Constants.SUBJECT_PUBLIC;
|
1225
|
String[] groupnames = null;
|
1226
|
if (session != null ) {
|
1227
|
username = session.getSubject().getValue();
|
1228
|
if (session.getSubjectInfo() != null) {
|
1229
|
List<Group> groupList = session.getSubjectInfo().getGroupList();
|
1230
|
if (groupList != null) {
|
1231
|
groupnames = new String[groupList.size()];
|
1232
|
for (int i = 0; i < groupList.size(); i++ ) {
|
1233
|
groupnames[i] = groupList.get(i).getGroupName();
|
1234
|
}
|
1235
|
}
|
1236
|
}
|
1237
|
}
|
1238
|
|
1239
|
// generate pid/localId pair for object
|
1240
|
logMetacat.debug("Generating a pid/localId mapping");
|
1241
|
IdentifierManager im = IdentifierManager.getInstance();
|
1242
|
String localId = im.generateLocalId(pid.getValue(), 1);
|
1243
|
|
1244
|
// Save the data file to disk using "localId" as the name
|
1245
|
String datafilepath = null;
|
1246
|
try {
|
1247
|
datafilepath = PropertyService.getProperty("application.datafilepath");
|
1248
|
} catch (PropertyNotFoundException e) {
|
1249
|
ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
|
1250
|
sf.initCause(e);
|
1251
|
throw sf;
|
1252
|
}
|
1253
|
boolean locked = false;
|
1254
|
try {
|
1255
|
locked = DocumentImpl.getDataFileLockGrant(localId);
|
1256
|
} catch (Exception e) {
|
1257
|
ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
|
1258
|
sf.initCause(e);
|
1259
|
throw sf;
|
1260
|
}
|
1261
|
|
1262
|
logMetacat.debug("Case DATA: starting to write to disk.");
|
1263
|
if (locked) {
|
1264
|
|
1265
|
File dataDirectory = new File(datafilepath);
|
1266
|
dataDirectory.mkdirs();
|
1267
|
|
1268
|
File newFile = writeStreamToFile(dataDirectory, localId, object);
|
1269
|
|
1270
|
// TODO: Check that the file size matches SystemMetadata
|
1271
|
// long size = newFile.length();
|
1272
|
// if (size == 0) {
|
1273
|
// throw new IOException("Uploaded file is 0 bytes!");
|
1274
|
// }
|
1275
|
|
1276
|
// Register the file in the database (which generates an exception
|
1277
|
// if the localId is not acceptable or other untoward things happen
|
1278
|
try {
|
1279
|
logMetacat.debug("Registering document...");
|
1280
|
DocumentImpl.registerDocument(localId, "BIN", localId,
|
1281
|
username, groupnames);
|
1282
|
logMetacat.debug("Registration step completed.");
|
1283
|
|
1284
|
} catch (SQLException e) {
|
1285
|
//newFile.delete();
|
1286
|
logMetacat.debug("SQLE: " + e.getMessage());
|
1287
|
e.printStackTrace(System.out);
|
1288
|
throw new ServiceFailure("1190", "Registration failed: " +
|
1289
|
e.getMessage());
|
1290
|
|
1291
|
} catch (AccessionNumberException e) {
|
1292
|
//newFile.delete();
|
1293
|
logMetacat.debug("ANE: " + e.getMessage());
|
1294
|
e.printStackTrace(System.out);
|
1295
|
throw new ServiceFailure("1190", "Registration failed: " +
|
1296
|
e.getMessage());
|
1297
|
|
1298
|
} catch (Exception e) {
|
1299
|
//newFile.delete();
|
1300
|
logMetacat.debug("Exception: " + e.getMessage());
|
1301
|
e.printStackTrace(System.out);
|
1302
|
throw new ServiceFailure("1190", "Registration failed: " +
|
1303
|
e.getMessage());
|
1304
|
}
|
1305
|
|
1306
|
logMetacat.debug("Logging the creation event.");
|
1307
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
|
1308
|
|
1309
|
// Schedule replication for this data file, the "insert" action is important here!
|
1310
|
logMetacat.debug("Scheduling replication.");
|
1311
|
ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
|
1312
|
}
|
1313
|
|
1314
|
return localId;
|
1315
|
|
1316
|
}
|
1317
|
|
1318
|
/**
|
1319
|
* Insert a systemMetadata document and return its localId
|
1320
|
*/
|
1321
|
public void insertSystemMetadata(SystemMetadata sysmeta)
|
1322
|
throws ServiceFailure {
|
1323
|
|
1324
|
logMetacat.debug("Starting to insert SystemMetadata...");
|
1325
|
sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
|
1326
|
logMetacat.debug("Inserting new system metadata with modified date " +
|
1327
|
sysmeta.getDateSysMetadataModified());
|
1328
|
|
1329
|
//insert the system metadata
|
1330
|
try {
|
1331
|
// note: the calling subclass handles the map hazelcast lock/unlock
|
1332
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
|
1333
|
// submit for indexing
|
1334
|
MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
|
1335
|
} catch (Exception e) {
|
1336
|
throw new ServiceFailure("1190", e.getMessage());
|
1337
|
|
1338
|
}
|
1339
|
}
|
1340
|
|
1341
|
/**
|
1342
|
* Update a systemMetadata document
|
1343
|
*
|
1344
|
* @param sysMeta - the system metadata object in the system to update
|
1345
|
*/
|
1346
|
protected void updateSystemMetadata(SystemMetadata sysMeta)
|
1347
|
throws ServiceFailure {
|
1348
|
|
1349
|
logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
|
1350
|
sysMeta.setDateSysMetadataModified(new Date());
|
1351
|
try {
|
1352
|
HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
|
1353
|
HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
|
1354
|
// submit for indexing
|
1355
|
MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
|
1356
|
} catch (Exception e) {
|
1357
|
throw new ServiceFailure("4862", e.getMessage());
|
1358
|
|
1359
|
} finally {
|
1360
|
HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
|
1361
|
|
1362
|
}
|
1363
|
|
1364
|
}
|
1365
|
|
1366
|
public boolean updateSystemMetadata(Session session, Identifier pid,
|
1367
|
SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
|
1368
|
ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
|
1369
|
|
1370
|
// The lock to be used for this identifier
|
1371
|
Lock lock = null;
|
1372
|
|
1373
|
// TODO: control who can call this?
|
1374
|
if (session == null) {
|
1375
|
//TODO: many of the thrown exceptions do not use the correct error codes
|
1376
|
//check these against the docs and correct them
|
1377
|
throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
|
1378
|
" If you are not logged in, please do so and retry the request.");
|
1379
|
}
|
1380
|
|
1381
|
// verify that guid == SystemMetadata.getIdentifier()
|
1382
|
logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() +
|
1383
|
"|" + sysmeta.getIdentifier().getValue());
|
1384
|
|
1385
|
if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
|
1386
|
throw new InvalidRequest("4863",
|
1387
|
"The identifier in method call (" + pid.getValue() +
|
1388
|
") does not match identifier in system metadata (" +
|
1389
|
sysmeta.getIdentifier().getValue() + ").");
|
1390
|
}
|
1391
|
|
1392
|
// do the actual update
|
1393
|
this.updateSystemMetadata(sysmeta);
|
1394
|
|
1395
|
try {
|
1396
|
String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
1397
|
EventLog.getInstance().log(request.getRemoteAddr(),
|
1398
|
request.getHeader("User-Agent"), session.getSubject().getValue(),
|
1399
|
localId, "updateSystemMetadata");
|
1400
|
} catch (McdbDocNotFoundException e) {
|
1401
|
// do nothing, no localId to log with
|
1402
|
logMetacat.warn("Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
|
1403
|
}
|
1404
|
|
1405
|
return true;
|
1406
|
}
|
1407
|
|
1408
|
/**
|
1409
|
* Given a Permission, returns a list of all permissions that it encompasses
|
1410
|
* Permissions are hierarchical so that WRITE also allows READ.
|
1411
|
* @param permission
|
1412
|
* @return list of included Permissions for the given permission
|
1413
|
*/
|
1414
|
protected List<Permission> expandPermissions(Permission permission) {
|
1415
|
List<Permission> expandedPermissions = new ArrayList<Permission>();
|
1416
|
if (permission.equals(Permission.READ)) {
|
1417
|
expandedPermissions.add(Permission.READ);
|
1418
|
}
|
1419
|
if (permission.equals(Permission.WRITE)) {
|
1420
|
expandedPermissions.add(Permission.READ);
|
1421
|
expandedPermissions.add(Permission.WRITE);
|
1422
|
}
|
1423
|
if (permission.equals(Permission.CHANGE_PERMISSION)) {
|
1424
|
expandedPermissions.add(Permission.READ);
|
1425
|
expandedPermissions.add(Permission.WRITE);
|
1426
|
expandedPermissions.add(Permission.CHANGE_PERMISSION);
|
1427
|
}
|
1428
|
return expandedPermissions;
|
1429
|
}
|
1430
|
|
1431
|
/*
|
1432
|
* Write a stream to a file
|
1433
|
*
|
1434
|
* @param dir - the directory to write to
|
1435
|
* @param fileName - the file name to write to
|
1436
|
* @param data - the object bytes as an input stream
|
1437
|
*
|
1438
|
* @return newFile - the new file created
|
1439
|
*
|
1440
|
* @throws ServiceFailure
|
1441
|
*/
|
1442
|
private File writeStreamToFile(File dir, String fileName, InputStream data)
|
1443
|
throws ServiceFailure {
|
1444
|
|
1445
|
File newFile = new File(dir, fileName);
|
1446
|
logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
|
1447
|
|
1448
|
try {
|
1449
|
if (newFile.createNewFile()) {
|
1450
|
// write data stream to desired file
|
1451
|
OutputStream os = new FileOutputStream(newFile);
|
1452
|
long length = IOUtils.copyLarge(data, os);
|
1453
|
os.flush();
|
1454
|
os.close();
|
1455
|
} else {
|
1456
|
logMetacat.debug("File creation failed, or file already exists.");
|
1457
|
throw new ServiceFailure("1190", "File already exists: " + fileName);
|
1458
|
}
|
1459
|
} catch (FileNotFoundException e) {
|
1460
|
logMetacat.debug("FNF: " + e.getMessage());
|
1461
|
throw new ServiceFailure("1190", "File not found: " + fileName + " "
|
1462
|
+ e.getMessage());
|
1463
|
} catch (IOException e) {
|
1464
|
logMetacat.debug("IOE: " + e.getMessage());
|
1465
|
throw new ServiceFailure("1190", "File was not written: " + fileName
|
1466
|
+ " " + e.getMessage());
|
1467
|
}
|
1468
|
|
1469
|
return newFile;
|
1470
|
}
|
1471
|
|
1472
|
/*
|
1473
|
* Returns a list of nodes that have been registered with the DataONE infrastructure
|
1474
|
* that match the given session subject
|
1475
|
* @return nodes - List of nodes from the registry with a matching session subject
|
1476
|
*
|
1477
|
* @throws ServiceFailure
|
1478
|
* @throws NotImplemented
|
1479
|
*/
|
1480
|
protected List<Node> listNodesBySubject(Subject subject)
|
1481
|
throws ServiceFailure, NotImplemented {
|
1482
|
List<Node> nodeList = new ArrayList<Node>();
|
1483
|
|
1484
|
CNode cn = D1Client.getCN();
|
1485
|
List<Node> nodes = cn.listNodes().getNodeList();
|
1486
|
|
1487
|
// find the node in the node list
|
1488
|
for ( Node node : nodes ) {
|
1489
|
|
1490
|
List<Subject> nodeSubjects = node.getSubjectList();
|
1491
|
if (nodeSubjects != null) {
|
1492
|
// check if the session subject is in the node subject list
|
1493
|
for (Subject nodeSubject : nodeSubjects) {
|
1494
|
if ( nodeSubject.equals(subject) ) { // subject of session == node subject
|
1495
|
nodeList.add(node);
|
1496
|
}
|
1497
|
}
|
1498
|
}
|
1499
|
}
|
1500
|
|
1501
|
return nodeList;
|
1502
|
|
1503
|
}
|
1504
|
|
1505
|
/**
|
1506
|
* Archives an object, where the object is either a
|
1507
|
* data object or a science metadata object.
|
1508
|
*
|
1509
|
* @param session - the Session object containing the credentials for the Subject
|
1510
|
* @param pid - The object identifier to be archived
|
1511
|
*
|
1512
|
* @return pid - the identifier of the object used for the archiving
|
1513
|
*
|
1514
|
* @throws InvalidToken
|
1515
|
* @throws ServiceFailure
|
1516
|
* @throws NotAuthorized
|
1517
|
* @throws NotFound
|
1518
|
* @throws NotImplemented
|
1519
|
* @throws InvalidRequest
|
1520
|
*/
|
1521
|
public Identifier archive(Session session, Identifier pid)
|
1522
|
throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
|
1523
|
|
1524
|
String localId = null;
|
1525
|
boolean allowed = false;
|
1526
|
String username = Constants.SUBJECT_PUBLIC;
|
1527
|
String[] groupnames = null;
|
1528
|
if (session == null) {
|
1529
|
throw new InvalidToken("1330", "No session has been provided");
|
1530
|
} else {
|
1531
|
username = session.getSubject().getValue();
|
1532
|
if (session.getSubjectInfo() != null) {
|
1533
|
List<Group> groupList = session.getSubjectInfo().getGroupList();
|
1534
|
if (groupList != null) {
|
1535
|
groupnames = new String[groupList.size()];
|
1536
|
for (int i = 0; i < groupList.size(); i++) {
|
1537
|
groupnames[i] = groupList.get(i).getGroupName();
|
1538
|
}
|
1539
|
}
|
1540
|
}
|
1541
|
}
|
1542
|
|
1543
|
// do we have a valid pid?
|
1544
|
if (pid == null || pid.getValue().trim().equals("")) {
|
1545
|
throw new ServiceFailure("1350", "The provided identifier was invalid.");
|
1546
|
}
|
1547
|
|
1548
|
// check for the existing identifier
|
1549
|
try {
|
1550
|
localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
|
1551
|
} catch (McdbDocNotFoundException e) {
|
1552
|
throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
|
1553
|
}
|
1554
|
|
1555
|
// does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
|
1556
|
try {
|
1557
|
allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
|
1558
|
} catch (InvalidRequest e) {
|
1559
|
throw new ServiceFailure("1350", e.getDescription());
|
1560
|
}
|
1561
|
|
1562
|
|
1563
|
if (allowed) {
|
1564
|
try {
|
1565
|
// archive the document
|
1566
|
DocumentImpl.delete(localId, null, null, null, false);
|
1567
|
EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
|
1568
|
|
1569
|
// archive it
|
1570
|
SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
|
1571
|
sysMeta.setArchived(true);
|
1572
|
sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
|
1573
|
HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
|
1574
|
// submit for indexing
|
1575
|
// DocumentImpl call above should do this.
|
1576
|
// see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
|
1577
|
//HazelcastService.getInstance().getIndexQueue().add(sysMeta);
|
1578
|
|
1579
|
} catch (McdbDocNotFoundException e) {
|
1580
|
throw new NotFound("1340", "The provided identifier was invalid.");
|
1581
|
|
1582
|
} catch (SQLException e) {
|
1583
|
throw new ServiceFailure("1350", "There was a problem archiving the object." + "The error message was: " + e.getMessage());
|
1584
|
|
1585
|
} catch (InsufficientKarmaException e) {
|
1586
|
throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive this object.");
|
1587
|
|
1588
|
} catch (Exception e) { // for some reason DocumentImpl throws a general Exception
|
1589
|
throw new ServiceFailure("1350", "There was a problem archiving the object." + "The error message was: " + e.getMessage());
|
1590
|
}
|
1591
|
|
1592
|
} else {
|
1593
|
throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
|
1594
|
}
|
1595
|
|
1596
|
return pid;
|
1597
|
}
|
1598
|
|
1599
|
|
1600
|
}
|