-
Notifications
You must be signed in to change notification settings - Fork 12
/
vault.py
1698 lines (1317 loc) · 61 KB
/
vault.py
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Functions to copy packages to the vault and manage permissions of vault packages."""
__copyright__ = 'Copyright (c) 2019-2024, Utrecht University'
__license__ = 'GPLv3, see LICENSE'
import itertools
import os
import re
import subprocess
import time
from datetime import datetime
import genquery
import irods_types
from dateutil import parser
import folder
import groups
import meta
import meta_form
import policies_datamanager
import policies_datapackage_status
from util import *
__all__ = ['api_vault_submit',
'api_vault_approve',
'api_vault_cancel',
'api_vault_depublish',
'api_vault_republish',
'api_vault_preservable_formats_lists',
'api_vault_unpreservable_files',
'rule_vault_retry_copy_to_vault',
'rule_vault_copy_numthreads',
'rule_vault_copy_original_metadata_to_vault',
'rule_vault_write_license',
'rule_vault_enable_indexing',
'rule_vault_disable_indexing',
'rule_vault_process_status_transitions',
'rule_vault_grant_readers_vault_access',
'api_vault_system_metadata',
'api_vault_collection_details',
'api_vault_get_package_by_reference',
'api_vault_copy_to_research',
'api_vault_get_publication_terms',
'api_vault_get_landingpage_data',
'api_grant_read_access_research_group',
'api_revoke_read_access_research_group',
'api_vault_get_published_packages']
@api.make()
def api_vault_submit(ctx, coll, previous_version=None):
"""Submit data package for publication.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to submit
:param previous_version: Path to previous version of data package in the vault
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.SUBMITTED_FOR_PUBLICATION, previous_version)
if ret[0] == '':
log.write(ctx, 'api_vault_submit: iiAdminVaultActions')
ctx.iiAdminVaultActions()
return 'Success'
else:
return api.Error(ret[0], ret[1])
@api.make()
def api_vault_approve(ctx, coll):
"""Approve data package for publication.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to approve
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
# Check for previous version.
previous_version = get_previous_version(ctx, coll)
# Add related data package metadata for new and previous version.
if previous_version:
meta_add_new_version(ctx, coll, previous_version)
ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.APPROVED_FOR_PUBLICATION)
if ret[0] == '':
log.write(ctx, 'api_vault_approve: iiAdminVaultActions')
ctx.iiAdminVaultActions()
return 'Success'
else:
return api.Error(ret[0], ret[1])
@api.make()
def api_vault_cancel(ctx, coll):
"""Cancel submit of data package.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to cancel submit
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.UNPUBLISHED)
if ret[0] == '':
log.write(ctx, 'api_vault_submit: iiAdminVaultActions')
ctx.iiAdminVaultActions()
return 'Success'
else:
return api.Error(ret[0], ret[1])
@api.make()
def api_vault_depublish(ctx, coll):
"""Depublish data package.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to depublish
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.PENDING_DEPUBLICATION)
if ret[0] == '':
log.write(ctx, 'api_vault_submit: iiAdminVaultActions')
ctx.iiAdminVaultActions()
return 'Success'
else:
return api.Error(ret[0], ret[1])
@api.make()
def api_vault_republish(ctx, coll):
"""Republish data package.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to republish
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.PENDING_REPUBLICATION)
if ret[0] == '':
log.write(ctx, 'api_vault_submit: iiAdminVaultActions')
ctx.iiAdminVaultActions()
return 'Success'
else:
return api.Error(ret[0], ret[1])
@api.make()
def api_vault_copy_to_research(ctx, coll_origin, coll_target):
"""Copy data package from vault to research space.
:param ctx: Combined type of a callback and rei struct
:param coll_origin: Collection of data package to copy
:param coll_target: Collection to copy data package to
:returns: API status
"""
zone = user.zone(ctx)
# API error introduces post-error in requesting application.
if coll_target == "/" + zone + "/home":
return api.Error('HomeCollectionNotAllowed', 'Please select a specific research folder for your datapackage')
# Check if target is a research folder. I.e. none-vault folder.
parts = coll_target.split('/')
group_name = parts[3]
if group_name.startswith('vault-'):
return api.Error('RequiredIsResearchArea', 'Please select a specific research folder for your datapackage')
# Check whether datapackage folder already present in target folder.
# Get package name from origin path
parts = coll_origin.split('/')
new_package_collection = coll_target + '/' + parts[-1]
# Now check whether target collection already exist.
if collection.exists(ctx, new_package_collection):
return api.Error('PackageAlreadyPresentInTarget', 'This datapackage is already present at the specified place')
# Check if target path exists.
if not collection.exists(ctx, coll_target):
return api.Error('TargetPathNotExists', 'The target you specified does not exist')
# Check if user has READ ACCESS to specific vault package in collection coll_origin.
user_full_name = user.full_name(ctx)
category = groups.group_category(ctx, group_name)
is_datamanager = groups.user_is_datamanager(ctx, category, user.full_name(ctx))
if not is_datamanager:
# Check if research group has access by checking of research-group exists for this user.
research_group_access = collection.exists(ctx, coll_origin)
if not research_group_access:
return api.Error('NoPermissions', 'Insufficient rights to perform this action')
# Check for possible locks on target collection.
lock_count = meta_form.get_coll_lock_count(ctx, coll_target)
if lock_count:
return api.Error('TargetCollectionLocked', 'The folder you selected is locked.')
# Check if user has write access to research folder.
# Only normal user has write access.
if groups.user_role(ctx, user_full_name, group_name) not in ['normal', 'manager']:
return api.Error('NoWriteAccessTargetCollection', 'Not permitted to write in selected folder')
# Register to delayed rule queue.
delay = 10
ctx.delayExec(
"<PLUSET>%ds</PLUSET>" % delay,
"iiCopyFolderToResearch('%s', '%s')" % (coll_origin, coll_target),
"")
# TODO: response nog veranderen
return {"status": "ok",
"target": coll_target,
"origin": coll_origin}
@api.make()
def api_vault_preservable_formats_lists(ctx):
"""Retrieve lists of preservable file formats on the system.
:param ctx: Combined type of a callback and rei struct
:returns: dict -- Lists of preservable file formats {name => [ext...]}
"""
zone = user.zone(ctx)
# Retrieve all preservable file formats lists on the system.
files = [x for x in collection.data_objects(ctx, '/{}/yoda/file_formats'.format(zone))
if x.endswith('.json')]
# Return dict of list filename (without extension) -> JSON contents
return {os.path.splitext(pathutil.chop(x)[1])[0]:
jsonutil.read(ctx, x) for x in files}
@api.make()
def api_vault_unpreservable_files(ctx, coll, list_name):
"""Retrieve the set of unpreservable file formats in a collection.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of folder to check
:param list_name: Name of preservable file format list
:returns: Set of unpreservable file formats
"""
space, zone, _, _ = pathutil.info(coll)
if space not in [pathutil.Space.RESEARCH, pathutil.Space.VAULT]:
return api.Error('invalid_path', 'Invalid vault path.')
# Retrieve JSON list of preservable file formats.
list_data = jsonutil.read(ctx, '/{}/yoda/file_formats/{}.json'.format(zone, list_name))
preservable_formats = set(list_data['formats'])
# Get basenames of all data objects within this collection.
data_names = itertools.imap(lambda x: pathutil.chop(x)[1],
collection.data_objects(ctx, coll, recursive=True))
# Exclude Yoda metadata files
data_names = itertools.ifilter(lambda
x: not re.match(r"yoda\-metadata(\[\d+\])?\.(xml|json)", x),
data_names)
# Data names -> lowercase extensions, without the dot.
exts = set(list(itertools.imap(lambda x: os.path.splitext(x)[1][1:].lower(), data_names)))
exts -= set([''])
# Return any ext that is not in the preservable list.
return list(exts - preservable_formats)
def rule_vault_copy_original_metadata_to_vault(rule_args, callback, rei):
"""Copy the original metadata JSON into the root of the package.
:param rule_args: [0] Path of a new package in the vault
:param callback: Callback to rule Language
:param rei: The rei struct
"""
vault_package = rule_args[0]
vault_copy_original_metadata_to_vault(callback, vault_package)
def get_vault_copy_numthreads(ctx):
# numThreads should be 0 if want multithreading with no specified amount of threads
return 0 if config.vault_copy_multithread_enabled else 1
def vault_copy_original_metadata_to_vault(ctx, vault_package_path):
"""Copy original metadata to the vault package root.
:param ctx: Combined type of a callback and rei struct
:param vault_package_path: Path of a package in the vault
"""
original_metadata = vault_package_path + "/original/" + constants.IIJSONMETADATA
copied_metadata = vault_package_path + '/yoda-metadata[' + str(int(time.time())) + '].json'
# Copy original metadata JSON.
ctx.msiDataObjCopy(original_metadata, copied_metadata, 'destRescName={}++++numThreads={}++++verifyChksum='.format(config.resource_vault, get_vault_copy_numthreads(ctx)), 0)
# msi.data_obj_copy(ctx, original_metadata, copied_metadata, 'verifyChksum=', irods_types.BytesBuf())
def rule_vault_write_license(rule_args, callback, rei):
"""Write the license as a text file into the root of the vault package.
:param rule_args: [0] Path of a package in the vault
:param callback: Callback to rule Language
:param rei: The rei struct
"""
vault_pkg_coll = rule_args[0]
vault_write_license(callback, vault_pkg_coll)
def vault_write_license(ctx, vault_pkg_coll):
"""Write the license as a text file into the root of the vault package.
:param ctx: Combined type of a callback and rei struct
:param vault_pkg_coll: Path of a package in the vault
"""
zone = user.zone(ctx)
# Retrieve license.
license = ""
license_key = "License"
license_unit = "{}_%".format(constants.UUUSERMETADATAROOT)
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = '{}' AND META_COLL_ATTR_UNITS LIKE '{}'".format(vault_pkg_coll, license_key, license_unit),
genquery.AS_LIST, ctx)
for row in iter:
license = row[0]
if license == "":
# No license set in user metadata.
log.write(ctx, "rule_vault_write_license: No license found in user metadata <{}>".format(vault_pkg_coll))
elif license == "Custom":
# Custom license set in user metadata, no License.txt should exist in package.
license_file = vault_pkg_coll + "/License.txt"
if data_object.exists(ctx, license_file):
data_object.remove(ctx, license_file, force=True)
else:
# License set in user metadata, a License.txt should exist in package.
# Check if license text exists.
license_txt = "/{}{}/{}.txt".format(zone, constants.IILICENSECOLLECTION, license)
if data_object.exists(ctx, license_txt):
# Copy license file.
license_file = vault_pkg_coll + "/License.txt"
ctx.msiDataObjCopy(license_txt, license_file, 'destRescName={}++++forceFlag=++++numThreads={}++++verifyChksum='.format(config.resource_vault, get_vault_copy_numthreads(ctx)), 0)
# Fix ACLs.
try:
ctx.iiCopyACLsFromParent(license_file, 'default')
except Exception:
log.write(ctx, "rule_vault_write_license: Failed to set vault permissions on <{}>".format(license_file))
else:
log.write(ctx, "rule_vault_write_license: License text not available for <{}>".format(license))
# Check if license URI exists.
license_uri_file = "/{}{}/{}.uri".format(zone, constants.IILICENSECOLLECTION, license)
if data_object.exists(ctx, license_uri_file):
# Retrieve license URI.
license_uri = data_object.read(ctx, license_uri_file)
license_uri = license_uri.strip()
license_uri = license_uri.strip('\"')
# Set license URI.
avu.set_on_coll(ctx, vault_pkg_coll, "{}{}".format(constants.UUORGMETADATAPREFIX, "license_uri"), license_uri)
else:
log.write(ctx, "rule_vault_write_license: License URI not available for <{}>".format(license))
@rule.make(inputs=[0], outputs=[1])
def rule_vault_enable_indexing(ctx, coll):
vault_enable_indexing(ctx, coll)
return "Success"
def vault_enable_indexing(ctx, coll):
if config.enable_open_search:
if not collection.exists(ctx, coll + "/index"):
# index collection does not exist yet
path = meta.get_latest_vault_metadata_path(ctx, coll)
ctx.msi_rmw_avu('-d', path, '%', '%', constants.UUFLATINDEX)
meta.ingest_metadata_vault(ctx, path)
# add indexing attribute and update opensearch
subprocess.call(["imeta", "add", "-C", coll + "/index", "irods::indexing::index", "yoda::metadata", "elasticsearch"])
@rule.make(inputs=[0], outputs=[1])
def rule_vault_disable_indexing(ctx, coll):
vault_disable_indexing(ctx, coll)
return "Success"
def vault_disable_indexing(ctx, coll):
if config.enable_open_search:
if collection.exists(ctx, coll + "/index"):
coll = coll + "/index"
# tricky: remove indexing attribute without updating opensearch
try:
msi.mod_avu_metadata(ctx, "-C", coll, "rm", "irods::indexing::index", "yoda::metadata", "elasticsearch")
except Exception:
pass
@api.make()
def api_vault_system_metadata(ctx, coll):
"""Return system metadata of a vault collection.
:param ctx: Combined type of a callback and rei struct
:param coll: Path to data package
:returns: Dict system metadata of a vault collection
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
system_metadata = {}
# Package size.
data_count = collection.data_count(ctx, coll)
collection_count = collection.collection_count(ctx, coll)
size = collection.size(ctx, coll)
size_readable = misc.human_readable_size(size)
system_metadata["Data Package Size"] = "{} files, {} folders, total of {}".format(data_count, collection_count, size_readable)
# Modified date.
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_lastModifiedDateTime'" % (coll),
genquery.AS_LIST, ctx
)
for row in iter:
# Python 3: https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat
# modified_date = date.fromisoformat(row[0])
modified_date = parser.parse(row[0])
modified_date = modified_date.strftime('%Y-%m-%d %H:%M:%S%z')
system_metadata["Modified date"] = "{}".format(modified_date)
# Landingpage URL.
landinpage_url = ""
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_landingPageUrl'" % (coll),
genquery.AS_LIST, ctx
)
for row in iter:
landinpage_url = row[0]
system_metadata["Landingpage"] = "<a href=\"{}\">{}</a>".format(landinpage_url, landinpage_url)
# Data Package Reference.
data_package_reference = ""
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = '{}'".format(coll, constants.DATA_PACKAGE_REFERENCE),
genquery.AS_LIST, ctx
)
for row in iter:
data_package_reference = row[0]
system_metadata["Data Package Reference"] = "<a href=\"yoda/{}\">yoda/{}</a>".format(data_package_reference, data_package_reference)
# Persistent Identifier EPIC.
package_epic_pid = ""
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_epic_pid'" % (coll),
genquery.AS_LIST, ctx
)
for row in iter:
package_epic_pid = row[0]
package_epic_url = ""
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_epic_url'" % (coll),
genquery.AS_LIST, ctx
)
for row in iter:
package_epic_url = row[0]
if package_epic_pid:
if package_epic_url:
persistent_identifier_epic = "<a href=\"{}\">{}</a>".format(package_epic_url, package_epic_pid)
else:
persistent_identifier_epic = "{}".format(package_epic_pid)
system_metadata["EPIC Persistent Identifier"] = persistent_identifier_epic
return system_metadata
def get_coll_vault_status(ctx, path, org_metadata=None):
"""Get the status of a vault folder."""
if org_metadata is None:
org_metadata = folder.get_org_metadata(ctx, path)
# Don't care about duplicate attr names here.
org_metadata = dict(org_metadata)
if constants.IIVAULTSTATUSATTRNAME in org_metadata:
x = org_metadata[constants.IIVAULTSTATUSATTRNAME]
try:
return constants.vault_package_state(x)
except Exception:
log.write(ctx, 'Invalid vault folder status <{}>'.format(x))
return constants.vault_package_state.EMPTY
def get_all_published_versions(ctx, path):
"""Get all published versions of a data package."""
base_doi = get_doi(ctx, path, 'base')
package_doi = get_doi(ctx, path)
coll_parent_name = path.rsplit('/', 1)[0]
org_publ_info, data_packages, grouped_base_dois = get_all_doi_versions(ctx, coll_parent_name)
count = 0
all_versions = []
for data in data_packages:
if data[2] == package_doi:
count += 1
if count == 1: # Base DOI does not exist as it is first version of the publication
# Convert the date into two formats for display and tooltip (Jan 1, 1990 and 1990-01-01 00:00:00)
data_packages = [[x[0], datetime.strptime(x[1], "%Y-%m-%dT%H:%M:%S.%f").strftime("%b %d, %Y"), x[2],
datetime.strptime(x[1], "%Y-%m-%dT%H:%M:%S.%f").strftime('%Y-%m-%d %H:%M:%S%z'), x[3]] for x in data_packages]
for item in data_packages:
if item[2] == package_doi:
all_versions.append([item[1], item[2], item[3]])
else: # Base DOI exists
# Sort by publication date
sorted_publ = [sorted(x, key=lambda x: datetime.strptime(x[1], "%Y-%m-%dT%H:%M:%S.%f"), reverse=True) for x in grouped_base_dois]
sorted_publ = [element for innerList in sorted_publ for element in innerList]
# Convert the date into two formats for display and tooltip (Jan 1, 1990 and 1990-01-01 00:00:00)
sorted_publ = [[x[0], datetime.strptime(x[1], "%Y-%m-%dT%H:%M:%S.%f").strftime("%b %d, %Y"), x[2],
datetime.strptime(x[1], "%Y-%m-%dT%H:%M:%S.%f").strftime('%Y-%m-%d %H:%M:%S%z'), x[3]] for x in sorted_publ]
for item in sorted_publ:
if item[0] == base_doi:
all_versions.append([item[1], item[2], item[3]])
return base_doi, package_doi, all_versions
@api.make()
def api_vault_collection_details(ctx, path):
"""Return details of a vault collection.
:param ctx: Combined type of a callback and rei struct
:param path: Path to data package
:returns: Dict with collection details
"""
if not collection.exists(ctx, path):
return api.Error('nonexistent', 'The given path does not exist')
# Check if collection is in vault space.
space, _, group, subpath = pathutil.info(path)
if space is not pathutil.Space.VAULT:
return {}
basename = pathutil.basename(path)
# Find group name to retrieve member type
group_parts = group.split('-')
if subpath.startswith("deposit-"):
research_group_name = 'deposit-' + '-'.join(group_parts[1:])
else:
research_group_name = 'research-' + '-'.join(group_parts[1:])
member_type = groups.user_role(ctx, user.full_name(ctx), research_group_name)
# Retrieve vault folder status.
status = get_coll_vault_status(ctx, path).value
# Check if collection has datamanager.
has_datamanager = True
# Check if user is datamanager.
category = groups.group_category(ctx, group)
is_datamanager = groups.user_is_datamanager(ctx, category, user.full_name(ctx))
# Check if collection is vault package.
metadata_path = meta.get_latest_vault_metadata_path(ctx, path)
if metadata_path is None:
return {'member_type': member_type, 'is_datamanager': is_datamanager}
else:
metadata = True
# Retreive all published versions
base_doi, package_doi, all_versions = get_all_published_versions(ctx, path)
# Check if a vault action is pending.
vault_action_pending = False
coll_id = collection.id_from_name(ctx, path)
action_status = constants.UUORGMETADATAPREFIX + '"vault_status_action_' + coll_id
iter = genquery.row_iterator(
"COLL_ID",
"META_COLL_ATTR_NAME = '" + action_status + "' AND META_COLL_ATTR_VALUE = 'PENDING'",
genquery.AS_LIST, ctx
)
for _row in iter:
vault_action_pending = True
# Check if research group has access.
research_group_access = False
# Retrieve all access user IDs on collection.
iter = genquery.row_iterator(
"COLL_ACCESS_USER_ID",
"COLL_NAME = '{}'".format(path),
genquery.AS_LIST, ctx
)
for row in iter:
user_id = row[0]
# Retrieve all group names with this ID.
iter2 = genquery.row_iterator(
"USER_NAME",
"USER_ID = '{}'".format(user_id),
genquery.AS_LIST, ctx
)
for row2 in iter2:
user_name = row2[0]
# Check if group is a research or intake group.
if user_name.startswith(("research-", "deposit-")):
research_group_access = True
result = {
"basename": basename,
"status": status,
"metadata": metadata,
"member_type": member_type,
"has_datamanager": has_datamanager,
"is_datamanager": is_datamanager,
"vault_action_pending": vault_action_pending,
"research_group_access": research_group_access,
"all_versions": all_versions,
"base_doi": base_doi,
"package_doi": package_doi
}
if config.enable_data_package_archive:
import vault_archive
result["archive"] = {
"archivable": vault_archive.vault_archivable(ctx, path),
"status": vault_archive.vault_archival_status(ctx, path)
}
if config.enable_data_package_download:
import vault_download
result["downloadable"] = vault_download.vault_downloadable(ctx, path)
return result
@api.make()
def api_vault_get_package_by_reference(ctx, reference):
"""Return path to data package with provided reference (UUID4).
:param ctx: Combined type of a callback and rei struct
:param reference: Data Package Reference (UUID4)
:returns: Path to data package
"""
data_package = ""
iter = genquery.row_iterator(
"COLL_NAME",
"META_COLL_ATTR_NAME = '{}' and META_COLL_ATTR_VALUE = '{}'".format(constants.DATA_PACKAGE_REFERENCE, reference),
genquery.AS_LIST, ctx)
for row in iter:
data_package = row[0]
if data_package == "":
return api.Error('not_found', 'Could not find data package with provided reference.')
_, _, path, subpath = pathutil.info(data_package)
return "/{}/{}".format(path, subpath)
@api.make()
def api_vault_get_landingpage_data(ctx, coll):
"""Retrieve landingpage data of data package.
Landinpage data consists of metadata and system metadata.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection to retrieve landingpage data from
:returns: API status
"""
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return api.Error('invalid_path', 'Invalid vault path.')
meta_path = meta.get_latest_vault_metadata_path(ctx, coll)
# Try to load the metadata file.
try:
metadata = jsonutil.read(ctx, meta_path)
current_schema_id = meta.metadata_get_schema_id(metadata)
if current_schema_id is None:
return api.Error('no_schema_id', 'Please check the structure of this file.',
'schema id missing')
except jsonutil.ParseError:
return api.Error('bad_json', 'Please check the structure of this file.', 'JSON invalid')
except msi.Error as e:
return api.Error('internal', 'The metadata file could not be read.', e)
# Get deposit date and end preservation date based upon retention period
# "submitted for vault"
# deposit_date = '2016-02-29' # To be gotten from the action log
iter = genquery.row_iterator(
"order_desc(META_COLL_MODIFY_TIME), META_COLL_ATTR_VALUE",
"COLL_NAME = '" + coll + "' AND META_COLL_ATTR_NAME = '" + constants.UUORGMETADATAPREFIX + 'action_log' + "'",
genquery.AS_LIST, ctx
)
for row in iter:
# row contains json encoded [str(int(time.time())), action, actor]
log_item_list = jsonutil.parse(row[1])
if log_item_list[1] == "submitted for vault":
deposit_timestamp = datetime.fromtimestamp(int(log_item_list[0]))
deposit_date = deposit_timestamp.strftime('%Y-%m-%d')
break
return {'metadata': metadata, 'deposit_date': deposit_date}
@api.make()
def api_vault_get_publication_terms(ctx):
"""Retrieve the publication terms."""
zone = user.zone(ctx)
terms_collection = "/{}{}".format(zone, constants.IITERMSCOLLECTION)
terms = ""
iter = genquery.row_iterator(
"DATA_NAME, order_asc(DATA_MODIFY_TIME)",
"COLL_NAME = '{}'".format(terms_collection),
genquery.AS_LIST, ctx)
for row in iter:
terms = row[0]
if terms == "":
return api.Error('TermsNotFound', 'No Terms and Agreements found.')
try:
terms_file = "/{}{}/{}".format(zone, constants.IITERMSCOLLECTION, terms)
return data_object.read(ctx, terms_file)
except Exception:
return api.Error('TermsReadFailed', 'Could not open Terms and Agreements.')
def change_read_access_group(ctx, coll, actor, group, grant=True):
"""Grant/revoke research group read access to vault package.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to grant/remove read rights from
:param actor: User changing the permissions
:param group: Group to grant/revoke read access to vault package
:param grant: Whether to grant or revoke access
:returns: 2-Tuple of boolean successfully changed, API status if error
"""
try:
acl_kv = msi.kvpair(ctx, "actor", actor)
if grant:
msi.sudo_obj_acl_set(ctx, "recursive", "read", group, coll, acl_kv)
else:
msi.sudo_obj_acl_set(ctx, "recursive", "null", group, coll, acl_kv)
except Exception:
policy_error = policies_datamanager.can_datamanager_acl_set(ctx, coll, actor, group, "1", "read")
if bool(policy_error):
return False, api.Error('ErrorACLs', 'Could not acquire datamanager access to {}.'.format(coll))
else:
return False, api.Error('ErrorACLs', str(policy_error))
return True, ''
def check_change_read_access_research_group(ctx, coll, grant=True):
"""Initial checks when changing read rights of research group for datapackage in vault.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to revoke/grant read rights from
:param grant: Whether to grant or revoke read rights
:returns: 2-Tuple of boolean whether ok to continue and API status if error
"""
verb = "grant" if grant else "revoke"
if not collection.exists(ctx, coll):
return False, api.Error('nonexistent', 'The given path does not exist')
coll_parts = coll.split('/')
if len(coll_parts) != 5:
return False, api.Error('invalid_collection', 'The datamanager can only {} permissions to vault packages'.format(verb))
space, _, _, _ = pathutil.info(coll)
if space is not pathutil.Space.VAULT:
return False, api.Error('invalid_collection', 'The datamanager can only {} permissions to vault packages'.format(verb))
return True, ''
def change_read_access_research_group(ctx, coll, grant=True):
"""Grant/revoke read rights of members of research group to a
datapackage in vault. This operation also includes read only members.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to grant/remove read rights from
:param grant: Whether to grant or revoke access
:returns: API status
"""
verb = "granting" if grant else "revoking"
response, api_error = check_change_read_access_research_group(ctx, coll, True)
if not response:
return api_error
_, _, group, subpath = pathutil.info(coll)
# Find category
group_parts = group.split('-')
if subpath.startswith("deposit-"):
research_group_name = 'deposit-' + '-'.join(group_parts[1:])
else:
research_group_name = 'research-' + '-'.join(group_parts[1:])
category = groups.group_category(ctx, group)
read_group_name = 'read-' + '-'.join(group_parts[1:])
# Is datamanager?
actor = user.full_name(ctx)
if groups.user_role(ctx, actor, 'datamanager-' + category) in ['normal', 'manager']:
# Grant/revoke research group read access to vault package.
for group_name in (research_group_name, read_group_name):
response, api_error = change_read_access_group(ctx, coll, actor, group_name, grant)
if not response:
return api_error
else:
return api.Error('NoDatamanager', 'Actor must be a datamanager for {} access'.format(verb))
return {'status': 'Success', 'statusInfo': ''}
@api.make()
def api_grant_read_access_research_group(ctx, coll):
"""Grant read rights of research group for datapackage in vault.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to remove read rights from
:returns: API status
"""
return change_read_access_research_group(ctx, coll, True)
@api.make()
def api_revoke_read_access_research_group(ctx, coll):
"""Revoke read rights of research group for datapackage in vault.
:param ctx: Combined type of a callback and rei struct
:param coll: Collection of data package to remove read rights from
:returns: API status
"""
return change_read_access_research_group(ctx, coll, False)
@rule.make()
def rule_vault_retry_copy_to_vault(ctx):
copy_to_vault(ctx, constants.CRONJOB_STATE["PENDING"])
copy_to_vault(ctx, constants.CRONJOB_STATE["RETRY"])
def copy_to_vault(ctx, state):
""" Collect all folders with a given cronjob state
and try to copy them to the vault.
:param ctx: Combined type of a callback and rei struct
:param state: one of constants.CRONJOB_STATE
"""
iter = get_copy_to_vault_colls(ctx, state)
for row in iter:
coll = row[0]
log.write(ctx, "copy_to_vault {}: {}".format(state, coll))
if not folder.precheck_folder_secure(ctx, coll):
continue
# failed copy
if not folder.folder_secure(ctx, coll):
log.write(ctx, "copy_to_vault {} failed for collection <{}>".format(state, coll))
folder.folder_secure_set_retry(ctx, coll)
def get_copy_to_vault_colls(ctx, cronjob_state):
iter = list(genquery.Query(ctx,
['COLL_NAME'],
"META_COLL_ATTR_NAME = '{}' AND META_COLL_ATTR_VALUE = '{}'".format(
constants.UUORGMETADATAPREFIX + "cronjob_copy_to_vault",
cronjob_state),
output=genquery.AS_LIST))
return iter
def copy_folder_to_vault(ctx, coll, target):
"""Copy folder and all its contents to target in vault using irsync.
The data will reside under folder '/original' within the vault.
:param ctx: Combined type of a callback and rei struct
:param coll: Path of a folder in the research space
:param target: Path of a package in the vault space
:returns: True for successful copy
"""
returncode = 0
try:
returncode = subprocess.call(["irsync", "-rK", "i:{}/".format(coll), "i:{}/original".format(target)])
except Exception as e:
log.write(ctx, "irsync failure: " + e)
log.write(ctx, "irsync failure for coll <{}> and target <{}>".format(coll, target))
return False
if returncode != 0:
log.write(ctx, "irsync failure for coll <{}> and target <{}>".format(coll, target))
return False
return True
def treewalk_and_ingest(ctx, folder, target, origin, error):
"""Treewalk folder and ingest.
:param ctx: Combined type of a callback and rei struct
:param folder: Will change every time as it represents every folder that has to be copied to vault
:param target: Target of ingest
:param origin: Origin of treewalk
:param error: 0/1 indicating if treewalk or ingest failed
:returns: Error status (which should remain 0 for further processing in iterative manner)
"""
parent_coll, coll = pathutil.chop(folder)
# 1. Process this collection itself as a collection.
# INGEST
if error == 0:
# INGEST COLLECTION
error = ingest_object(ctx, parent_coll, coll, True, target, origin)
# 2. Process dataobjects located directly within the collection
if error == 0:
iter = genquery.row_iterator(
"DATA_NAME",
"COLL_NAME = '" + folder + "'",
genquery.AS_LIST, ctx