-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_COMPSs_RO-Crate.py
1848 lines (1662 loc) · 78.1 KB
/
generate_COMPSs_RO-Crate.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
#!/usr/bin/python
#
# Copyright 2002-2023 Barcelona Supercomputing Center (www.bsc.es)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
The generate_COMPSs_RO-Crate.py module generates the resulting RO-Crate metadata from a COMPSs application run
following the Workflow Run Crate profile specification. Takes as parameters the ro-crate-info.yaml, and the
dataprovenance.log generated from the run.
"""
from pathlib import Path
from urllib.parse import urlsplit
import os
import uuid
import typing
import datetime as dt
import json
import socket
import subprocess
import yaml
import time
import sys
from rocrate.rocrate import ROCrate
from rocrate.model.person import Person
from rocrate.model.contextentity import ContextEntity
# from rocrate.model.entity import Entity
# from rocrate.model.file import File
from rocrate.utils import iso_now
PROFILES_BASE = "https://w3id.org/ro/wfrun"
PROFILES_VERSION = "0.1"
WROC_PROFILE_VERSION = "1.0"
def fix_dir_url(in_url: str) -> str:
"""
Fix dir:// URL returned by the runtime, change it to file:// and ensure it ends with '/'
:param in_url: URL that may need to be fixed
:returns: A file:// URL
"""
runtime_url = urlsplit(in_url)
if (
runtime_url.scheme == "dir"
): # Fix dir:// to file:// and ensure it ends with a slash
new_url = "file://" + runtime_url.netloc + runtime_url.path
if new_url[-1] != "/":
new_url += "/" # Add end slash if needed
return new_url
# else
return in_url # No changes required
def root_entity(compss_crate: ROCrate, yaml_content: dict) -> typing.Tuple[dict, list]:
"""
Generate the Root Entity in the RO-Crate generated for the COMPSs application
:param compss_crate: The COMPSs RO-Crate being generated
:param yaml_content: Content of the YAML file specified by the user
:returns: 'COMPSs Workflow Information' and 'Authors' sections, as defined in the YAML
"""
# Get Sections
compss_wf_info = yaml_content["COMPSs Workflow Information"]
authors_info = []
if "Authors" in yaml_content:
authors_info_yaml = yaml_content["Authors"] # Now a list of authors
if isinstance(authors_info_yaml, list):
authors_info = authors_info_yaml
else:
authors_info.append(authors_info_yaml)
# COMPSs Workflow RO Crate generation
# Root Entity
compss_crate.name = compss_wf_info[
"name"
] # SHOULD in RO-Crate 1.1. MUST in WorkflowHub
if "description" in compss_wf_info:
compss_crate.description = compss_wf_info[
"description"
] # SHOULD in Workflow Profile and WorkflowHub
if "license" in compss_wf_info:
# License details could be also added as a Contextual Entity. MUST in Workflow RO-Crate Profile, but WorkflowHub does not consider it a mandatory field
compss_crate.license = compss_wf_info["license"]
author_list = []
org_list = []
for author in authors_info:
properties_dict = {}
if author["orcid"] not in author_list:
# orcid is MANDATORY in RO-Crate 1.1
author_list.append(author["orcid"])
try:
properties_dict["name"] = author["name"] # MUST in WorkflowHub
except KeyError:
print(
f"PROVENANCE | ERROR in your ro-crate-info.yaml file. Both 'orcid' and 'name' must be defined together for an Author"
)
raise
if "ror" in author:
# ror is not mandatory on any profile
if author["ror"] not in org_list:
org_list.append(author["ror"])
properties_dict["affiliation"] = {"@id": author["ror"]}
# If ror defined, organisation_name becomes mandatory, if it is to be shown in WorkflowHub
try:
compss_crate.add(
ContextEntity(
compss_crate,
author["ror"],
{"@type": "Organization", "name": author["organisation_name"]},
)
)
except KeyError:
print(
f"PROVENANCE | ERROR in your ro-crate-info.yaml file. Both 'ror' and 'organisation_name' must be defined together for an Organisation"
)
raise
if "e-mail" in author:
properties_dict["contactPoint"] = {"@id": "mailto:" + author["e-mail"]}
compss_crate.add(
ContextEntity(
compss_crate,
"mailto:" + author["e-mail"],
{
"@type": "ContactPoint",
"contactType": "Author",
"email": author["e-mail"],
"identifier": author["e-mail"],
"url": author["orcid"],
},
)
)
compss_crate.add(Person(compss_crate, author["orcid"], properties_dict))
crate_author_list = []
crate_org_list = []
for author_orcid in author_list:
crate_author_list.append({"@id": author_orcid})
if crate_author_list:
compss_crate.creator = crate_author_list
for org_ror in org_list:
crate_org_list.append({"@id": org_ror})
# publisher is SHOULD in RO-Crate 1.1. Preferably an Organisation, but could be a Person
if not crate_org_list:
# Empty list of organisations, add authors as publishers
if crate_author_list:
compss_crate.publisher = crate_author_list
else:
compss_crate.publisher = crate_org_list
return compss_wf_info, crate_author_list
def get_main_entities(wf_info: dict) -> typing.Tuple[str, str, str]:
"""
Get COMPSs version and mainEntity from dataprovenance.log first lines
3 First lines expected format: compss_version_number\n main_entity\n output_profile_file\n
Next lines are for "accessed files" and "direction"
mainEntity can be directly obtained for Python, or defined by the user in the YAML (sources_main_file)
:param wf_info: YAML dict to extract info form the application, as specified by the user
:returns: COMPSs version, main COMPSs file name, COMPSs profile file name
"""
# Build the whole source files list in list_of_sources, and get a backup main entity, in case we can't find one
# automatically. The mainEntity must be an existing file, otherwise the RO-Crate won't have a ComputationalWorkflow
yaml_sources_list = [] # YAML sources list
list_of_sources = [] # Full list of source files, once directories are traversed
# Should contain absolute paths, for correct comparison (two files in different directories
# could be named the same)
main_entity = None
backup_main_entity = None
if "sources" in wf_info:
if isinstance(wf_info["sources"], list):
yaml_sources_list.extend(wf_info["sources"])
else:
yaml_sources_list.append(wf_info["sources"])
if "files" in wf_info:
# Backward compatibility: if old "sources_dir" and "files" have been used, merge in yaml_sources_list.
if isinstance(wf_info["files"], list):
yaml_sources_list.extend(wf_info["files"])
else:
yaml_sources_list.append(wf_info["files"])
if "sources_dir" in wf_info:
# Backward compatibility: if old "sources_dir" and "files" have been used, merge in yaml_sources_list.
# sources_list = list(tuple(wf_info["files"])) + list(tuple(wf_info["sources"]))
if isinstance(wf_info["sources_dir"], list):
yaml_sources_list.extend(wf_info["sources_dir"])
else:
yaml_sources_list.append(wf_info["sources_dir"])
keys = ["sources", "files", "sources_dir"]
if not any(key in wf_info for key in keys):
# If no sources are defined, define automatically the main_entity or return error
# We try directly to add the mainEntity identified in dataprovenance.log, if exists in the CWD
with open(DP_LOG, "r", encoding="UTF-8") as dp_file:
compss_v = next(dp_file).rstrip() # First line, COMPSs version number
second_line = next(dp_file).rstrip()
# Second, main_entity. Use better rstrip, just in case there is no '\n'
if second_line.endswith(".py"):
# Python. Line contains only the file name, need to locate it
detected_app = second_line
else: # Java app. Need to fix filename first
# Translate identified main entity matmul.files.Matmul to a comparable path
me_file_name = second_line.split(".")[-1]
detected_app = me_file_name + ".java"
# print(f"PROVENANCE DEBUG | Detected app when no 'sources' defined is: {detected_app}")
third_line = next(dp_file).rstrip()
out_profile_fn = Path(third_line)
if os.path.isfile(detected_app):
main_entity = detected_app
else:
print(
f"PROVENANCE | ERROR: No 'sources' defined at ro-crate-info.yaml, and detected mainEntity not found in Current Working Directory"
)
raise KeyError("No 'sources' key defined at ro-crate-info.yaml")
# Find a backup_main_entity while building the full list of source files
for source in yaml_sources_list:
path_source = Path(source).expanduser()
resolved_source = str(path_source.resolve())
if path_source.exists():
if os.path.isfile(resolved_source):
list_of_sources.append(resolved_source)
if backup_main_entity is None and path_source.suffix in {
".py",
".java",
".jar",
".class",
}:
backup_main_entity = resolved_source
# print(
# f"PROVENANCE DEBUG | FOUND SOURCE FILE AS BACKUP MAIN: {backup_main_entity}"
# )
elif os.path.isdir(resolved_source):
for root, _, files in os.walk(
resolved_source, topdown=True, followlinks=True
):
if "__pycache__" in root:
continue # We skip __pycache__ subdirectories
for f_name in files:
# print(f"PROVENANCE DEBUG | ADDING FILE to list_of_sources: {f_name}. root is: {root}")
if f_name.startswith("*"):
# Avoid dealing with symlinks with wildcards
continue
full_name = os.path.join(root, f_name)
list_of_sources.append(full_name)
if backup_main_entity is None and Path(f_name).suffix in {
".py",
".java",
".jar",
".class",
}:
backup_main_entity = full_name
# print(
# f"PROVENANCE DEBUG | FOUND SOURCE FILE IN A DIRECTORY AS BACKUP MAIN: {backup_main_entity}"
# )
else:
print(
f"PROVENANCE | WARNING: A defined source is neither a directory, nor a file ({resolved_source})"
)
else:
print(
f"PROVENANCE | WARNING: Specified file or directory in ro-crate-info.yaml 'sources' does not exist ({path_source})"
)
# Can't get backup_main_entity from sources_main_file, because we do not know if it really exists
if len(list_of_sources) == 0:
print(
"PROVENANCE | WARNING: Unable to find application source files. Please, review your "
"ro_crate_info.yaml definition ('sources' term)"
)
# raise FileNotFoundError
elif backup_main_entity is None:
# No source files found in list_of_sources, set any file as backup
backup_main_entity = list_of_sources[0]
# print(f"PROVENANCE DEBUG | backup_main_entity is: {backup_main_entity}")
with open(DP_LOG, "r", encoding="UTF-8") as dp_file:
compss_v = next(dp_file).rstrip() # First line, COMPSs version number
second_line = next(dp_file).rstrip()
# Second, main_entity. Use better rstrip, just in case there is no '\n'
if second_line.endswith(".py"):
# Python. Line contains only the file name, need to locate it
detected_app = second_line
else: # Java app. Need to fix filename first
# Translate identified main entity matmul.files.Matmul to a comparable path
me_sub_path = second_line.replace(".", "/")
detected_app = me_sub_path + ".java"
# print(f"PROVENANCE DEBUG | Detected app is: {detected_app}")
third_line = next(dp_file).rstrip()
out_profile_fn = Path(third_line)
for file in list_of_sources: # Try to find the identified mainEntity
if file.endswith(detected_app):
# print(
# f"PROVENANCE DEBUG | IDENTIFIED MAIN ENTITY FOUND IN LIST OF FILES: {file}"
# )
main_entity = file
break
# main_entity has a value if mainEntity has been automatically detected
if "sources_main_file" in wf_info:
# Check what the user has defined
# If it directly exists, we are done, no need to search in 'sources'
found = False
path_smf = Path(wf_info["sources_main_file"]).expanduser()
resolved_sources_main_file = str(path_smf.resolve())
if os.path.isfile(path_smf):
# Checks if exists
if main_entity is None:
# the detected_app was not found previously in the list of files
found = True
print(
f"PROVENANCE | WARNING: The file defined at sources_main_file is assigned as mainEntity: {resolved_sources_main_file}"
)
else:
print(
f"PROVENANCE | WARNING: The file defined at sources_main_file "
f"({resolved_sources_main_file}) in ro-crate-info.yaml does not match with the "
f"automatically identified mainEntity ({main_entity})"
)
main_entity = resolved_sources_main_file
found = True
else:
# If the file defined in sources_main_file is not directly found, try to find it in 'sources'
# if sources_main_file is an absolute path, the join has no effect
for source in yaml_sources_list: # Created at the beginning
path_sources = Path(source).expanduser()
if not path_sources.exists() or os.path.isfile(source):
continue
resolved_sources = str(path_sources.resolve())
resolved_sources_main_file = os.path.join(
resolved_sources, wf_info["sources_main_file"]
)
for file in list_of_sources:
if file == resolved_sources_main_file:
# The file exists
# print(
# f"PROVENANCE DEBUG | The file defined at sources_main_file exists: "
# f" {resolved_sources_main_file}"
# )
if resolved_sources_main_file != main_entity:
print(
f"PROVENANCE | WARNING: The file defined at sources_main_file "
f"({resolved_sources_main_file}) in ro-crate-info.yaml does not match with the "
f"automatically identified mainEntity ({main_entity})"
)
# else: the user has defined exactly the file we found
# In both cases: set file defined by user
main_entity = resolved_sources_main_file
# Can't use Path, file may not be in cwd
found = True
break
if file.endswith(wf_info["sources_main_file"]):
# The file exists
# print(
# f"PROVENANCE DEBUG | The file defined at sources_main_file exists: "
# f" {resolved_sources_main_file}"
# )
if file != main_entity:
print(
f"PROVENANCE | WARNING: The file defined at sources_main_file "
f"({file}) in ro-crate-info.yaml does not match with the "
f"automatically identified mainEntity ({main_entity})"
)
# else: the user has defined exactly the file we found
# In both cases: set file defined by user
main_entity = file
# Can't use Path, file may not be in cwd
found = True
break
if not found:
print(
f"PROVENANCE | WARNING: the defined 'sources_main_file' ({wf_info['sources_main_file']}) does "
f"not exist in the defined 'sources'. Check your ro-crate-info.yaml."
)
# If we identified the mainEntity automatically, we select it when the one defined
# by the user is not found
if main_entity is None:
# When neither identified, nor defined by user: get backup if exists
if backup_main_entity is None:
# We have a fatal problem
print(
f"PROVENANCE | ERROR: no mainEntity has been found. Check the definition of 'sources' and "
f"'sources_main_file' in ro-crate-info.yaml"
)
raise FileNotFoundError
main_entity = backup_main_entity
print(
f"PROVENANCE | WARNING: the detected mainEntity {detected_app} does not exist in the list "
f"of application files provided in ro-crate-info.yaml. Setting {main_entity} as mainEntity"
)
print(
f"PROVENANCE | COMPSs version: {compss_v}, out_profile: {out_profile_fn.name}, main_entity: {main_entity}"
)
return compss_v, main_entity, out_profile_fn.name
def process_accessed_files() -> typing.Tuple[list, list]:
"""
Process all the files the COMPSs workflow has accessed. They will be the overall inputs needed and outputs
generated of the whole workflow.
- If a task that is an INPUT, was previously an OUTPUT, it means it is an intermediate file, therefore we discard it
- Works fine with COLLECTION_FILE_IN, COLLECTION_FILE_OUT and COLLECTION_FILE_INOUT
:returns: List of Inputs and Outputs of the COMPSs workflow
"""
part_time = time.time()
inputs = set()
outputs = set()
with open(DP_LOG, "r", encoding="UTF-8") as dp_file:
for line in dp_file:
file_record = line.rstrip().split(" ")
if len(file_record) == 2:
if (
file_record[1] == "IN" or file_record[1] == "IN_DELETE"
): # Can we have an IN_DELETE that was not previously an OUTPUT?
if (
file_record[0] not in outputs
): # A true INPUT, not an intermediate file
inputs.add(file_record[0])
# Else, it is an intermediate file, not a true INPUT or OUTPUT. Not adding it as an input may
# be enough in most cases, since removing it as an output may be a bit radical
# outputs.remove(file_record[0])
elif file_record[1] == "OUT":
outputs.add(file_record[0])
else: # INOUT, COMMUTATIVE, CONCURRENT
if (
file_record[0] not in outputs
): # Not previously generated by another task (even a task using that same file), a true INPUT
inputs.add(file_record[0])
# else, we can't know for sure if it is an intermediate file, previous call using the INOUT may
# have inserted it at outputs, thus don't remove it from outputs
outputs.add(file_record[0])
# else dismiss the line
l_ins = list(inputs)
l_ins.sort() # Put directories first
l_outs = list(outputs)
l_outs.sort() # Put directories first
# Fix dir:// references, they don't end with slash '/' at dataprovenance.log
for data_list in [l_ins, l_outs]:
for item in data_list:
url_parts = urlsplit(item)
if url_parts.scheme == "dir":
data_list.append("dir://" + socket.gethostname() + url_parts.path + "/")
data_list.remove(item)
else:
break # File has been reached, all directories have been treated
data_list.sort()
print(f"PROVENANCE | COMPSs runtime detected inputs ({len(l_ins)})")
print(f"PROVENANCE | COMPSs runtime detected outputs ({len(l_outs)})")
print(
f"PROVENANCE | dataprovenance.log processing TIME: "
f"{time.time() - part_time} s"
)
return l_ins, l_outs
def add_file_to_crate(
compss_crate: ROCrate,
file_name: str,
compss_ver: str,
main_entity: str,
out_profile: str,
in_sources_dir: str,
) -> str:
"""
Get details of a file, and add it physically to the Crate. The file will be an application source file, so,
the destination directory should be 'application_sources/'
:param compss_crate: The COMPSs RO-Crate being generated
:param file_name: File to be added physically to the Crate, full path resolved
:param compss_ver: COMPSs version number
:param main_entity: COMPSs file with the main code, full path resolved
:param out_profile: COMPSs application profile output
:param in_sources_dir: Path to the defined sources_dir. May be passed empty, so there is no sub-folder structure
to be respected
:returns: Path where the file has been stored in the crate
"""
file_path = Path(file_name)
file_properties = {
"name": file_path.name,
"contentSize": os.path.getsize(file_name),
}
# main_entity has its absolute path, as well as file_name
if file_name == main_entity:
file_properties["description"] = "Main file of the COMPSs workflow source files"
if file_path.suffix == ".jar":
file_properties["encodingFormat"] = (
[
"application/java-archive",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/x-fmt/412"},
],
)
# Add JAR as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/x-fmt/412",
{"@type": "WebSite", "name": "Java Archive Format"},
)
)
elif file_path.suffix == ".class":
file_properties["encodingFormat"] = (
[
"application/java",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/x-fmt/415"},
],
)
# Add CLASS as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/x-fmt/415",
{"@type": "WebSite", "name": "Java Compiled Object Code"},
)
)
else: # .py, .java, .c, .cc, .cpp
file_properties["encodingFormat"] = "text/plain"
if complete_graph.exists():
file_properties["image"] = {
"@id": "complete_graph.svg"
} # Name as generated
# input and output properties not added to the workflow, since we do not comply with BioSchemas
# (i.e. no FormalParameters are defined)
else:
# Any other extra file needed
file_properties["description"] = "Auxiliary File"
if file_path.suffix in (".py", ".java"):
file_properties["encodingFormat"] = "text/plain"
file_properties["@type"] = ["File", "SoftwareSourceCode"]
elif file_path.suffix == ".json":
file_properties["encodingFormat"] = [
"application/json",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/817"},
]
elif file_path.suffix == ".pdf":
file_properties["encodingFormat"] = (
[
"application/pdf",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/276"},
],
)
elif file_path.suffix == ".svg":
file_properties["encodingFormat"] = (
[
"image/svg+xml",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/92"},
],
)
elif file_path.suffix == ".jar":
file_properties["encodingFormat"] = (
[
"application/java-archive",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/x-fmt/412"},
],
)
# Add JAR as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/x-fmt/412",
{"@type": "WebSite", "name": "Java Archive Format"},
)
)
elif file_path.suffix == ".class":
file_properties["encodingFormat"] = (
[
"Java .class",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/x-fmt/415"},
],
)
# Add CLASS as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/x-fmt/415",
{"@type": "WebSite", "name": "Java Compiled Object Code"},
)
)
# Build correct dest_path. If the file belongs to sources_dir, need to remove all "sources_dir" from file_name,
# respecting the sub_dir structure.
# If the file is defined individually, put in the root of application_sources
if in_sources_dir:
# /home/bsc/src/file.py must be translated to application_sources/src/file.py,
# but in_sources_dir is /home/bsc/src
new_root = str(Path(in_sources_dir).parents[0])
final_name = file_name[len(new_root) + 1 :]
path_in_crate = "application_sources/" + final_name
else:
path_in_crate = "application_sources/" + file_path.name
if file_name != main_entity:
# print(f"PROVENANCE DEBUG | Adding auxiliary source file: {file_name}")
compss_crate.add_file(
source=file_name, dest_path=path_in_crate, properties=file_properties
)
else:
# We get lang_version from dataprovenance.log
# print(f"PROVENANCE DEBUG | Adding main source file: {file_path.name}, file_name: {file_name}")
compss_crate.add_workflow(
source=file_name,
dest_path=path_in_crate,
main=True,
lang="COMPSs",
lang_version=compss_ver,
properties=file_properties,
gen_cwl=False,
)
# complete_graph.svg
if complete_graph.exists():
file_properties = {}
file_properties["name"] = "complete_graph.svg"
file_properties["contentSize"] = complete_graph.stat().st_size
file_properties["@type"] = ["File", "ImageObject", "WorkflowSketch"]
file_properties[
"description"
] = "The graph diagram of the workflow, automatically generated by COMPSs runtime"
# file_properties["encodingFormat"] = (
# [
# "application/pdf",
# {"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/276"},
# ],
# )
file_properties["encodingFormat"] = (
[
"image/svg+xml",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/92"},
],
)
file_properties["about"] = {
"@id": path_in_crate
} # Must be main_entity_location, not main_entity alone
# Add PDF as ContextEntity
# compss_crate.add(
# ContextEntity(
# compss_crate,
# "https://www.nationalarchives.gov.uk/PRONOM/fmt/276",
# {
# "@type": "WebSite",
# "name": "Acrobat PDF 1.7 - Portable Document Format",
# },
# )
# )
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/fmt/92",
{
"@type": "WebSite",
"name": "Scalable Vector Graphics",
},
)
)
compss_crate.add_file(complete_graph, properties=file_properties)
else:
print(
"PROVENANCE | WARNING: complete_graph.svg file not found. "
"Provenance will be generated without image property"
)
# out_profile
if os.path.exists(out_profile):
file_properties = {}
file_properties["name"] = out_profile
file_properties["contentSize"] = os.path.getsize(out_profile)
file_properties["description"] = "COMPSs application Tasks profile"
file_properties["encodingFormat"] = [
"application/json",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/817"},
]
# Fix COMPSs crappy format of JSON files
with open(out_profile, encoding="UTF-8") as op_file:
op_json = json.load(op_file)
with open(out_profile, "w", encoding="UTF-8") as op_file:
json.dump(op_json, op_file, indent=1)
# Add JSON as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/fmt/817",
{"@type": "WebSite", "name": "JSON Data Interchange Format"},
)
)
compss_crate.add_file(out_profile, properties=file_properties)
else:
print(
"PROVENANCE | WARNING: COMPSs application profile has not been generated. \
Make sure you use runcompss with --output_profile=file_name \
Provenance will be generated without profiling information"
)
# compss_submission_command_line.txt. Old compss_command_line_arguments.txt
file_properties = {}
file_properties["name"] = "compss_submission_command_line.txt"
file_properties["contentSize"] = os.path.getsize(
"compss_submission_command_line.txt"
)
file_properties[
"description"
] = "COMPSs submission command line (runcompss / enqueue_compss), including flags and parameters passed to the application"
file_properties["encodingFormat"] = "text/plain"
compss_crate.add_file(
"compss_submission_command_line.txt", properties=file_properties
)
# ro-crate-info.yaml
file_properties = {}
file_properties["name"] = "ro-crate-info.yaml"
file_properties["contentSize"] = os.path.getsize("ro-crate-info.yaml")
file_properties[
"description"
] = "COMPSs Workflow Provenance YAML configuration file"
file_properties["encodingFormat"] = [
"YAML",
{"@id": "https://www.nationalarchives.gov.uk/PRONOM/fmt/818"},
]
# Add YAML as ContextEntity
compss_crate.add(
ContextEntity(
compss_crate,
"https://www.nationalarchives.gov.uk/PRONOM/fmt/818",
{"@type": "WebSite", "name": "YAML"},
)
)
compss_crate.add_file("ro-crate-info.yaml", properties=file_properties)
return ""
# print(f"ADDED FILE: {file_name} as {path_in_crate}")
return path_in_crate
def add_application_source_files(
compss_crate: ROCrate,
compss_wf_info: dict,
compss_ver: str,
main_entity: str,
out_profile: str,
) -> None:
"""
Add all application source files as part of the crate. This means, to include them physically in the resulting
bundle
:param compss_crate: The COMPSs RO-Crate being generated
:param compss_wf_info: YAML dict to extract info form the application, as specified by the user
:param compss_ver: COMPSs version number
:param main_entity: COMPSs file with the main code, full path resolved
:param out_profile: COMPSs application profile output file
:returns: None
"""
part_time = time.time()
sources_list = []
if "sources" in compss_wf_info:
if isinstance(compss_wf_info["sources"], list):
sources_list.extend(compss_wf_info["sources"])
else:
sources_list.append(compss_wf_info["sources"])
if "files" in compss_wf_info:
# Backward compatibility: if old "sources_dir" and "files" have been used, merge in sources_list.
if isinstance(compss_wf_info["files"], list):
sources_list.extend(compss_wf_info["files"])
else:
sources_list.append(compss_wf_info["files"])
if "sources_dir" in compss_wf_info:
# Backward compatibility: if old "sources_dir" and "files" have been used, merge in sources_list.
# sources_list = list(tuple(wf_info["files"])) + list(tuple(wf_info["sources"]))
if isinstance(compss_wf_info["sources_dir"], list):
sources_list.extend(compss_wf_info["sources_dir"])
else:
sources_list.append(compss_wf_info["sources_dir"])
# else: Nothing defined, covered at the end
added_files = []
added_dirs = []
# TODO: before dealing with all files from all directories, update the list of sources, removing any sub-folders
# already included in other folders. Do it with source_list_copy, to avoid strange iterations
# This would avoid the issue of sources: [sources_empty/empty_dir_1/, sources_empty/] which adds empty_dir_1
# to the root of application_sources/.
for source in sources_list:
path_source = Path(source).expanduser()
if not path_source.exists():
print(
f"PROVENANCE | WARNING: A file or directory defined as 'sources' in ro-crate-info.yaml does not exist "
f"({source})"
)
continue
resolved_source = str(path_source.resolve())
if os.path.isdir(resolved_source):
# Adding files twice is not a drama, since add_file_to_crate won't add them twice, but we save traversing directories
if resolved_source in added_dirs:
print(
f"PROVENANCE | WARNING: A directory addition was attempted twice: {resolved_source}"
)
continue # Do not traverse the directory again
if any(resolved_source.startswith(dir_item) for dir_item in added_dirs):
print(
f"PROVENANCE | WARNING: A sub-directory addition was attempted twice: {resolved_source}"
)
continue
if any(dir_item.startswith(resolved_source) for dir_item in added_dirs):
print(
f"PROVENANCE | WARNING: A parent directory of a previously added sub-directory is being added. Some "
f"files will be traversed twice in: {resolved_source}"
)
# Can't continue, we need to traverse the parent directory. Luckily, files won't be added twice
added_dirs.append(resolved_source)
for root, dirs, files in os.walk(
resolved_source, topdown=True, followlinks=True
):
if "__pycache__" in root:
continue # We skip __pycache__ subdirectories
for f_name in files:
if f_name.startswith("*"):
# Avoid dealing with symlinks with wildcards
continue
resolved_file = os.path.join(root, f_name)
if resolved_file not in added_files:
add_file_to_crate(
compss_crate,
resolved_file,
compss_ver,
main_entity,
out_profile,
resolved_source,
)
added_files.append(resolved_file)
else:
print(
f"PROVENANCE | WARNING: A file addition was attempted twice: "
f"{resolved_file} in {resolved_source}"
)
for dir_name in dirs:
# Check if it's an empty directory, needs to be added by hand
full_dir_name = os.path.join(root, dir_name)
if not os.listdir(full_dir_name):
# print(f"PROVENANCE DEBUG | Adding an empty directory. root ({root}), full_dir_name ({full_dir_name}), resolved_source ({resolved_source})")
# Workaround to add empty directories in a git repository
git_keep = Path(full_dir_name + "/" + ".gitkeep")
Path.touch(git_keep)
add_file_to_crate(
compss_crate,
str(git_keep),
compss_ver,
main_entity,
out_profile,
resolved_source,
)
if not os.listdir(resolved_source):
# The root directory itself is empty
# print(f"PROVENANCE DEBUG | Adding an empty directory. resolved_source ({resolved_source})")
# Workaround to add empty directories in a git repository
git_keep = Path(resolved_source + "/" + ".gitkeep")
Path.touch(git_keep)
add_file_to_crate(
compss_crate,
str(git_keep),
compss_ver,
main_entity,
out_profile,
resolved_source,
)
elif os.path.isfile(resolved_source):
if resolved_source not in added_files:
add_file_to_crate(
compss_crate,
resolved_source,
compss_ver,
main_entity,
out_profile,
"",
)
added_files.append(resolved_source)
else:
print(
f"PROVENANCE | WARNING: A file addition was attempted twice: "
f"{resolved_source} in {added_dirs}"
)
else:
print(
f"PROVENANCE | WARNING: A defined source is neither a directory, nor a file ({resolved_source})"
)
if len(sources_list) == 0:
# No sources defined by the user, add the selected main_entity at least
add_file_to_crate(
compss_crate, main_entity, compss_ver, main_entity, out_profile, ""
)
added_files.append(main_entity)
# Add auxiliary files as hasPart to the ComputationalWorkflow main file
# Not working well when an application has several versions (ex: Java matmul files, objects, arrays)
# for e in compss_crate.data_entities:
# if 'ComputationalWorkflow' in e.type:
# for file in crate_paths:
# if file is not "":
# e.append_to("hasPart", {"@id": file})
print(f"PROVENANCE | Application source files detected ({len(added_files)})")
# print(f"PROVENANCE DEBUG | Source files detected: {added_files}")
print(
f"PROVENANCE | RO-Crate adding source files TIME: {time.time() - part_time} s"
)
def add_dataset_file_to_crate(
compss_crate: ROCrate, in_url: str, persist: bool, common_paths: list
) -> str:
"""
Add the file (or a reference to it) belonging to the dataset of the application (both input or output)
When adding local files that we don't want to be physically in the Crate, they must be added with a file:// URI
CAUTION: If the file has been already added (e.g. for INOUT files) add_file won't succeed in adding a second entity
with the same name
:param compss_crate: The COMPSs RO-Crate being generated
:param in_url: File added as input or output
:param persist: True to attach the file to the crate, False otherwise
:param common_paths: List of identified common paths among all dataset files, all finish with '/'
:returns: The original url if persist is false, the crate_path if persist is true
"""
# method_time = time.time()
url_parts = urlsplit(in_url)
# If in_url ends up with '/', os.path.basename will be empty, thus we need Pathlib
url_path = Path(url_parts.path)
final_item_name = url_path.name
file_properties = {
"name": final_item_name,
"sdDatePublished": iso_now(),
"dateModified": dt.datetime.utcfromtimestamp(os.path.getmtime(url_parts.path))
.replace(microsecond=0)
.isoformat(), # Schema.org
} # Register when the Data Entity was last accessible
if url_parts.scheme == "file": # Dealing with a local file
file_properties["contentSize"] = os.path.getsize(url_parts.path)
crate_path = ""
# add_file_time = time.time()
if persist: # Remove scheme so it is added as a regular file
for i, item in enumerate(common_paths): # All files must have a match
if url_parts.path.startswith(item):