This repository has been archived by the owner on Dec 1, 2022. It is now read-only.
/
intellectual_object.go
550 lines (484 loc) · 20.6 KB
/
intellectual_object.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package models
import (
"encoding/json"
"github.com/APTrust/exchange/constants"
"strings"
"time"
)
// IntellectualObject represents a single object (ingested bag) in APTrust.
// An object can include any number of files and events.
//
// Properties are described below, but note that all of the "Ingest-"
// fields populated and used by the Exchange ingest code on ingest only.
// These fields are not stored in Pharos, and will not be populated on
// any IntellectualObject retrieved from Pharos.
//
// Ingest services do save a JSON representation of IntellectualObjects,
// including all of the "Ingest-" fields in the WorkItemState record
// associated with the ingest WorkItem. That JSON record can be useful
// for forensics, debugging, troubleshooting, and data reconstruction.
type IntellectualObject struct {
// Id is the primary key id of this bag in Pharos.
// If Id is non-zero, this has been recorded in Pharos.
Id int `json:"id,omitempty"`
// Identifier is the unique bag identifier, which is a
// string in the format "institution_identifier/bag_name".
// Example: "virginia.edu/bag1234"
Identifier string `json:"identifier,omitempty"`
// BagName is the name of the bag, without the institution
// identifier prefix. Example: "bag1234"
BagName string `json:"bag_name,omitempty"`
// BagGroupIdentifier (from the BagIt spec) describes a logical
// collection or group to which a bag belongs. This will be empty
// in many cases.
BagGroupIdentifier string `json:"bag_group_identifier,omitempty"`
// Institution is the institution identifier (the domain name)
// of the institution that owns this bag.
Institution string `json:"institution,omitempty"`
// InstitutionId is the Id (in Pharos) of the institution
// that owns this bag.
InstitutionId int `json:"institution_id,omitempty"`
// Title is the title of the IntellectualObject. For example,
// "Architectural Plans for Alderman Library, 1933"
Title string `json:"title,omitempty"`
// Description is a description of the IntellectualObject.
// This comes from the Internal-Sender-Description field of the
// bag-info.txt file.
Description string `json:"description,omitempty"`
// Access describes who can see this intellectual object.
// This is specified in the aptrust-info.txt file. See
// https://sites.google.com/a/aptrust.org/member-wiki/basic-operations/bagging
// for a description of access policies.
Access string `json:"access,omitempty"`
// AltIdentifier is an alternate identifier for this bag. It comes from
// the Internal-Sender-Identifier field in the bag-info.txt file.
AltIdentifier string `json:"alt_identifier,omitempty"`
// DPNUUID is the DPN identifier for this bag, which is a UUID.
// This field will be empty if the bag has not been pushed to DPN.
DPNUUID string `json:"dpn_uuid,omitempty"`
// ETag is the AWS S3 etag from the depositor's receiving bucket
// for the bag that became this IntellectualObject.
ETag string `json:"etag,omitempty"`
// GenericFiles is a list of the files that make up this bag.
GenericFiles []*GenericFile `json:"generic_files,omitempty"`
// PremisEvents is a list of PREMIS events associated with this
// IntellectualObject. That includes events such as ingest and
// identifier assignment. Note that most PREMIS events are associated
// with GenericFiles, so see GenericFile.PremisEvents as well.
PremisEvents []*PremisEvent `json:"premis_events,omitempty"`
// State of the object. A = active, D = deleted.
State string `json:"state"`
// Storage option: Standard, Glacier-OH, Glacier-OR, Glacier-VA,
// "Glacier-Deep-OH", "Glacier-Deep-OR", "Glacier-Deep-VA"
StorageOption string `json:"storage_option"`
// CreatedAt is the Pharos timestamp describing when this
// IntellectualObject was first recorded in our database.
// This is usually within minutes of the ingest event, after
// all files have been copied to long-term storage.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt describes when this object was last updated in Pharos.
// If this timestamp differs from CreatedAt, it usually means the
// bag (or some part of it) was ingested a second time.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// FileCount is the number of files this object includes. We do not
// set this ever, and it will always be zero during the ingest process.
// This is a calculated field returned by Pharos. Consider it read-only.
// It will only ever be populated by Pharos, when retrieving records
// through the Admin REST API. Added for Restoration spot tests.
FileCount int `json:"file_count,omitempty"`
// FileSize is the total size (in bytes) of the files that make up this
// object. We do not set this ever, and it will always be zero during
// the ingest process. This is a calculated field returned by Pharos.
// Consider it read-only. It will only ever be populated by Pharos,
// when retrieving records through the Admin REST API. Added for
// Restoration spot tests.
FileSize int64 `json:"file_size,omitempty"`
// IngestS3Bucket is the bucket to which the depositor uploaded
// this bag. We fetch it from there to a local staging area for
// processing.
IngestS3Bucket string `json:"ingest_s3_bucket,omitempty"`
// IngestS3Key is the file name in the S3 receiving bucket. It
// should be the bag name plus a ".tar" extension.
IngestS3Key string `json:"ingest_s3_key,omitempty"`
// IngestTarFilePath is the absolute path to the tarred bag in
// our local staging area. We download the bag (as a tar file) from
// the receiving bucket to this local file.
IngestTarFilePath string `json:"ingest_tar_file_path,omitempty"`
// IngestUntarredPath is the path to the untarred bag in our local
// staging area. This may be an empty string if we did not untar the bag.
// As of APTrust 2.0, we generally validate bags and send their files
// to long-term storage without ever untarring them.
IngestUntarredPath string `json:"ingest_untarred_path,omitempty"`
// IngestSize is the size of the tarred bag we're trying to ingest.
IngestSize int64 `json:"ingest_size,omitempty"`
// IngestRemoteMd5 is the etag of this bag as reported by the
// depositor's S3 receiving bucket. We use this to verify the download,
// if possible. For smaller bags (< 5GB), the etag is an md5 checksum.
// Large bags that the depositor sent to S3 via multipart
// upload have an etag that is calculated differently from a normal
// md5 checksum and includes a dash, followed by the number of parts
// in the original multipart upload. We cannot use those multipart
// etags for md5 validation.
IngestRemoteMd5 string `json:"ingest_remote_md5,omitempty"`
// IngestLocalMd5 is the md5 digest of the tarred bag that we calculated
// locally upon downloading the file.
IngestLocalMd5 string `json:"ingest_local_md5,omitempty"`
// IngestMd5Verified indicates whether or not we were able to verify
// the md5 digest of the entire bag upon download to our staging area.
IngestMd5Verified bool `json:"ingest_md5_verified,omitempty"`
// IngestMd5Verifiable indicates whether we can verify our local md5
// digest against the S3 etag for this tarred bag. We cannot verify
// the checksum of large bags. See the comments on IngestRemoteMd5
// above.
IngestMd5Verifiable bool `json:"ingest_md5_verifiable,omitempty"`
// IngestManifests is list of manifest files found inside this bag
// when we downloaded it.
IngestManifests []string `json:"ingest_manifests,omitempty"`
// IngestTagManifests is a list of tag manifests found inside this
// bag when we downloaded it.
IngestTagManifests []string `json:"ingest_tag_manifests,omitempty"`
// IngestFilesIgnored is a list of files found in the bag that are
// neither manifests, tag files, or data files. This includes files
// beginning with a dot (.) or dash (-). We do not save these files
// to long-term storage.
IngestFilesIgnored []string `json:"ingest_files_ignored,omitempty"`
// IngestTags is a list of tags found in all of the tag files that
// we parsed when ingesting this bag. We parse only those tag files
// listed with the ParseAsTagFile option in
// config/aptrust_bag_validation_config.json. While Pharos itself
// only keeps and exposes the Title, Description, and Access tags,
// the JSON ingest data preserved in the WorkItemState record for
// each ingest includes a record of all tags parsed on ingest for
// items ingested in APTrust 2.0.
IngestTags []*Tag `json:"ingest_tags,omitempty"`
// IngestMissingFiles is a list of files that appear in the bag's
// manifest(s) but were not found inside the tarred bag. This list
// should be empty for valid bags. This field is for reporting
// bag validation errors.
IngestMissingFiles []*MissingFile `json:"ingest_missing_files,omitempty"`
// IngestTopLevelDirNames is a list of directory names found at
// the top of the directory hierarchy inside the tarred bag. The
// APTrust spec says there should be only one directory at the top
// level of the tar file contents, and that directory should have
// the same name as the bag, minus the ".tar" extension. This field
// is used for reporting bag validation errors.
IngestTopLevelDirNames []string `json:"ingest_top_level_dir_names,omitempty"`
// IngestErrorMessage contains information about why ingest failed
// for this bag. On successful ingest, this field will be empty.
IngestErrorMessage string `json:"ingest_error_message,omitempty"`
// IngestDeletedFromReceivingAt is a timestamp describing when the
// original tar file was deleted from the receiving bucket. After
// successful ingest, the workers/apt_recorder process should
// delete the tar file. If this timestamp is empty, it means the
// cleanup didn't happen, and we may be accumulating unneeded bags
// and incurring unnecessary costs in the receiving buckets.
IngestDeletedFromReceivingAt time.Time `json:"ingest_deleted_from_receiving_at,omitempty"`
// genericFileMap is used internally to quickly find GenericFiles by
// their path within the bag. E.g. "data/photos/image1.jpg".
genericFileMap map[string]*GenericFile
// tagMap is used internally to find tags by name.
tagMap map[string][]*Tag
}
func NewIntellectualObject() *IntellectualObject {
return &IntellectualObject{
GenericFiles: make([]*GenericFile, 0),
PremisEvents: make([]*PremisEvent, 0),
IngestManifests: make([]string, 0),
IngestTagManifests: make([]string, 0),
IngestFilesIgnored: make([]string, 0),
IngestTags: make([]*Tag, 0),
State: "A",
StorageOption: constants.StorageStandard,
}
}
// MissingFile defines a file that is not in the bag, despite the
// fact that its checksum was found in a manifest. We keep track
// of these during bag validation, so we can report which files
// were not found.
type MissingFile struct {
Manifest string
LineNumber int
FilePath string
Digest string
}
// NewMissingFile creates a new missing file record.
func NewMissingFile(manifest string, lineNumber int, filePath, digest string) *MissingFile {
return &MissingFile{
Manifest: manifest,
LineNumber: lineNumber,
FilePath: filePath,
Digest: digest,
}
}
// This Tag struct is essentially the same as the bagins
// TagField struct, but its properties are public and can
// be easily serialized to / deserialized from JSON.
type Tag struct {
SourceFile string
Label string
Value string
}
func NewTag(sourceFile, label, value string) *Tag {
return &Tag{
SourceFile: sourceFile,
Label: label,
Value: value,
}
}
// Returns the total number of bytes of all of the generic
// files in this object, including tag files. The object's bag
// size will be slightly larger than this, because it will
// include manifests, and a tar header.
//
// If you're looking for the number of bytes the payload only,
// See PayloadBytesAndFiles
func (obj *IntellectualObject) TotalFileSize() int64 {
total := int64(0)
for _, genericFile := range obj.GenericFiles {
total += genericFile.Size
}
return total
}
// PayloadBytesAndFiles returns the total number of bytes
// and files in the object's payload directory. Use this method
// to calculate the Payload-Oxum value of a BagIt bag.
//
// Return values byteCount and fileCount correspond to the BagIt
// spec's _OctetCount_ and _StreamCount_. See the Payload-Oxum
// tag documentation under
// https://tools.ietf.org/html/draft-kunze-bagit-17#section-2.2.2
func (obj *IntellectualObject) PayloadBytesAndFiles() (byteCount int64, fileCount int) {
for _, genericFile := range obj.GenericFiles {
if strings.HasPrefix(genericFile.OriginalPath(), "data/") {
byteCount += genericFile.Size
fileCount += 1
}
}
return byteCount, fileCount
}
// AccessValid returns true or false to indicate whether the
// structure's Access property contains a valid value.
func (obj *IntellectualObject) AccessValid() bool {
lcAccess := strings.ToLower(obj.Access)
for _, value := range constants.AccessRights {
if value == lcAccess {
return true
}
}
return false
}
// Returns the GenericFile record for the specified path, or nil.
// Param filePath should be the relative path of the file within
// the bag. E.g. "data/images/myphoto.jpg"
func (obj *IntellectualObject) FindGenericFile(filePath string) *GenericFile {
if obj.genericFileMap == nil || len(obj.genericFileMap) != len(obj.GenericFiles) {
obj.genericFileMap = make(map[string]*GenericFile, len(obj.GenericFiles))
for i := range obj.GenericFiles {
gf := obj.GenericFiles[i]
obj.genericFileMap[gf.OriginalPath()] = gf
}
}
return obj.genericFileMap[filePath]
}
// Returns the tag with the specified name, or nil. The bag spec at
// https://tools.ietf.org/html/draft-kunze-bagit-13#section-2.2.2
// says tags may be repeated, and their order must be preserved,
// so this returns a slice of tags if the tag is found. In most
// cases, the slice will contain one element.
func (obj *IntellectualObject) FindTag(tagName string) []*Tag {
if obj.tagMap == nil {
obj.tagMap = make(map[string][]*Tag)
for i := range obj.IngestTags {
tag := obj.IngestTags[i]
if obj.tagMap[tag.Label] == nil {
obj.tagMap[tag.Label] = make([]*Tag, 0)
}
obj.tagMap[tag.Label] = append(obj.tagMap[tag.Label], tag)
}
}
return obj.tagMap[tagName]
}
// Returns true if all the GenericFiles that needed to be saved
// were successfully saved to both primary and secondary storage.
// Note that GenericFiles marked as IngestNeedsSave = false do
// not need to be saved.
func (obj *IntellectualObject) AllFilesSaved() bool {
allSaved := true
for _, gf := range obj.GenericFiles {
if gf.IngestNeedsSave {
if gf.IngestStorageURL == "" ||
gf.IngestReplicationURL == "" ||
gf.IngestStoredAt.IsZero() ||
gf.IngestReplicatedAt.IsZero() {
allSaved = false
break
}
}
}
return allSaved
}
// Serialize the subset of IntellectualObject data that Pharos
// will accept. This is for post/put, where essential info, such
// as institution id and/or object id will be in the URL.
// This sets obj.Access to all lower case when it serializes,
// because Pharos requires access values to be normalized that way.
func (obj *IntellectualObject) SerializeForPharos() ([]byte, error) {
pharosObj := NewIntellectualObjectForPharos(obj)
dataStruct := make(map[string]interface{})
dataStruct["intellectual_object"] = pharosObj
return json.Marshal(dataStruct)
}
// Returns events of the specified type
func (obj *IntellectualObject) FindEventsByType(eventType string) []PremisEvent {
events := make([]PremisEvent, 0)
for _, event := range obj.PremisEvents {
if event != nil && event.EventType == eventType {
events = append(events, *event)
}
}
return events
}
// BuildIngestEvents creates all of the PremisEvents required
// for ingest for this IntellectualObject and all of its
// GenericFiles. This call works only when the Ingest data fields
// on the IntellectualObject are populated, which means it will
// not work on the barebones IntellectualObject we get back from
// Pharos. It will work on the IntellectualObject we build during
// the ingest process, the one that apt_fetch builds and passes
// along to apt_store and apt_record. That fully-fleshed object
// is preserved in JSON format in WorkItemState.State.
//
// Param numberOfFiles is the number of GenericFiles received
// in the ingested tar file. Not all of these will be saved to
// long-term storage (e.g. bagit.txt and any files that have not
// changed since the last ingest).
//
// We want to build all of the ingest PremisEvents before saving
// them to avoid a problem that showed up in the old system. In
// that system, we created PremisEvents when we were ready to
// save them. Ingest often took 2 or 3 attempts in the old system
// due to problems with Fluctus/Fedora. That resulted in 2 or 3
// ingest events for each object and file. Generating the events
// beforehand, with uuids, allows us to check with Pharos first
// to see if the event with the specific uuid is already in the
// system. We can add it if it's not, and we won't duplicate it
// if it is. This takes care of PT #113562325.
//
// This call is idempotent, so calling it multiple times will
// not mess up our data.
func (obj *IntellectualObject) BuildIngestEvents(numberOfFiles int) error {
err := obj.buildEventCreation()
if err != nil {
return err
}
err = obj.buildEventIdentifierAssignment()
if err != nil {
return err
}
err = obj.buildEventAccessAssignment()
if err != nil {
return err
}
err = obj.buildEventIngest(numberOfFiles)
if err != nil {
return err
}
for _, gf := range obj.GenericFiles {
if gf.IngestNeedsSave {
err = gf.BuildIngestEvents()
if err != nil {
return err
}
}
}
return nil
}
// Builds the event (if it doesn't already exist) describing when
// this object was created. There will be some lag time between
// when the object is created and when all of its ingest metadata
// is recorded.
func (obj *IntellectualObject) buildEventCreation() error {
events := obj.FindEventsByType(constants.EventCreation)
if len(events) == 0 {
event := NewEventObjectCreation()
event.IntellectualObjectId = obj.Id
event.IntellectualObjectIdentifier = obj.Identifier
obj.PremisEvents = append(obj.PremisEvents, event)
}
return nil
}
// Builds the event (if it doesn't already exist) describing when
// this object was assigned an identifier, and what that identifier is.
func (obj *IntellectualObject) buildEventIdentifierAssignment() error {
events := obj.FindEventsByType(constants.EventIdentifierAssignment)
if len(events) == 0 {
event, err := NewEventObjectIdentifierAssignment(obj.Identifier)
if err != nil {
return err
}
event.IntellectualObjectId = obj.Id
event.IntellectualObjectIdentifier = obj.Identifier
obj.PremisEvents = append(obj.PremisEvents, event)
}
return nil
}
// Builds the event (if it doesn't already exist) describing when
// access permissions were set on this object.
func (obj *IntellectualObject) buildEventAccessAssignment() error {
events := obj.FindEventsByType(constants.EventAccessAssignment)
if len(events) == 0 {
event, err := NewEventObjectRights(obj.Access)
if err != nil {
return err
}
event.IntellectualObjectId = obj.Id
event.IntellectualObjectIdentifier = obj.Identifier
obj.PremisEvents = append(obj.PremisEvents, event)
}
return nil
}
// Builds the event (if it doesn't already exist) describing when
// this object was fully ingested.
func (obj *IntellectualObject) buildEventIngest(numberOfFiles int) error {
events := obj.FindEventsByType(constants.EventIngestion)
if len(events) == 0 {
event, err := NewEventObjectIngest(numberOfFiles)
if err != nil {
return err
}
event.IntellectualObjectId = obj.Id
event.IntellectualObjectIdentifier = obj.Identifier
obj.PremisEvents = append(obj.PremisEvents, event)
}
return nil
}
// BuildIngestChecksums creates all of the ingest checksums for
// this object's GenericFiles. See the notes for BuildIngestEvents
// above, as they all apply here. This call is idempotent, so
// calling it multiple times will not mess up our data.
func (obj *IntellectualObject) BuildIngestChecksums() error {
for _, gf := range obj.GenericFiles {
err := gf.BuildIngestChecksums()
if err != nil {
return err
}
}
return nil
}
// Copy this IntellectualObject's Id and Identifier to the
// IntellectualObjectId and IntellectualObjectIdentifier
// properties of all child objects. Also propagates GenericFile
// Ids and Identifiers to sub-objects, if they are avialable.
// This call exists because objects don't have Ids until after
// they're saved in Pharos
func (obj *IntellectualObject) PropagateIdsToChildren() {
for _, event := range obj.PremisEvents {
event.IntellectualObjectId = obj.Id
event.IntellectualObjectIdentifier = obj.Identifier
}
for _, gf := range obj.GenericFiles {
gf.IntellectualObjectId = obj.Id
gf.IntellectualObjectIdentifier = obj.Identifier
gf.PropagateIdsToChildren()
}
}