-
Notifications
You must be signed in to change notification settings - Fork 29
/
v9.py
2348 lines (1734 loc) · 72.4 KB
/
v9.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 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# 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.
"""Migration models V9."""
import datetime
import os
import pathlib
import re
import uuid
import weakref
from bisect import bisect
from collections import OrderedDict
from copy import copy
from functools import total_ordering
from pathlib import Path
from urllib.parse import quote, urljoin, urlparse
import attr
from attr.validators import instance_of
from marshmallow import EXCLUDE, pre_dump
from renku.core import errors
from renku.core.management.migrate import SUPPORTED_PROJECT_VERSION
from renku.core.management.migrations.utils import (
OLD_METADATA_PATH,
generate_dataset_file_url,
generate_dataset_id,
generate_dataset_tag_id,
generate_url_id,
get_datasets_path,
)
from renku.core.metadata.repository import Commit
from renku.core.models import jsonld as jsonld
from renku.core.models import project as new_project
from renku.core.models.calamus import (
DateTimeList,
JsonLDSchema,
Nested,
StringList,
Uri,
fields,
oa,
prov,
rdfs,
renku,
schema,
)
from renku.core.models.dataset import generate_default_name, is_dataset_name_valid
from renku.core.models.provenance.annotation import AnnotationSchema
from renku.core.models.refs import LinkReference
from renku.core.utils.datetime8601 import fix_datetime, parse_date
from renku.core.utils.doi import extract_doi, is_doi
from renku.core.utils.urls import get_host, get_slug
from renku.version import __version__, version_url
wfprov = fields.Namespace("http://purl.org/wf4ever/wfprov#")
PROJECT_URL_PATH = "projects"
RANDOM_ID_LENGTH = 4
def _set_entity_client_commit(entity, client, commit):
"""Set the client and commit of an entity."""
if client and not entity.client:
entity.client = client
if not entity.commit:
revision = "UNCOMMITTED"
if entity._label:
revision = entity._label.rsplit("@", maxsplit=1)[-1]
if revision == "UNCOMMITTED":
commit = commit
elif client:
commit = client.repository.get_commit(revision)
entity.commit = commit
def _str_or_none(data):
"""Return str representation or None."""
return str(data) if data is not None else data
def generate_project_id(client, name, creator):
"""Return the id for the project based on the repository origin remote."""
# Determine the hostname for the resource URIs.
# If RENKU_DOMAIN is set, it overrides the host from remote.
# Default is localhost.
host = "localhost"
if not creator:
raise ValueError("Project Creator not set")
owner = creator.email.split("@")[0]
if client:
remote = client.remote
host = client.remote.get("host") or host
owner = remote.get("owner") or owner
name = remote.get("name") or name
host = os.environ.get("RENKU_DOMAIN") or host
if name:
name = quote(name, safe="")
else:
raise ValueError("Project name not set")
project_url = urljoin(f"https://{host}", pathlib.posixpath.join(PROJECT_URL_PATH, owner, name))
return project_url
@attr.s(slots=True)
class Project:
"""Represent a project."""
name = attr.ib(default=None)
created = attr.ib(converter=parse_date)
version = attr.ib(converter=str, default=str(SUPPORTED_PROJECT_VERSION))
agent_version = attr.ib(converter=str, default="pre-0.11.0")
template_source = attr.ib(type=str, default=None)
template_ref = attr.ib(type=str, default=None)
template_id = attr.ib(type=str, default=None)
template_version = attr.ib(type=str, default=None)
template_metadata = attr.ib(type=str, default="{}")
immutable_template_files = attr.ib(factory=list)
automated_update = attr.ib(converter=bool, default=False)
client = attr.ib(default=None)
creator = attr.ib(default=None, kw_only=True)
_id = attr.ib(kw_only=True, default=None)
_metadata_path = attr.ib(default=None, init=False)
@created.default
def _now(self):
"""Define default value for datetime fields."""
return datetime.datetime.now(datetime.timezone.utc)
def __attrs_post_init__(self):
"""Initialize computed attributes."""
if not self.creator and self.client:
old_metadata_path = self.client.renku_path.joinpath(OLD_METADATA_PATH)
if old_metadata_path.exists():
self.creator = Person.from_commit(
self.client.repository.get_previous_commit(old_metadata_path, first=True)
)
else:
# this assumes the project is being newly created
self.creator = Person.from_repository(self.client.repository)
try:
self._id = self.project_id
except ValueError:
"""Fallback to old behaviour."""
if self._id:
pass
elif self.client and self.client.is_project_set():
self._id = self.client.project._id
else:
raise
@property
def project_id(self):
"""Return the id for the project."""
return generate_project_id(client=self.client, name=self.name, creator=self.creator)
@classmethod
def from_yaml(cls, path, client=None):
"""Return an instance from a YAML file."""
data = jsonld.read_yaml(path)
self = cls.from_jsonld(data=data, client=client)
self._metadata_path = path
return self
@classmethod
def from_jsonld(cls, data, client=None):
"""Create an instance from JSON-LD data."""
if isinstance(data, cls):
return data
if not isinstance(data, dict):
raise ValueError(data)
return ProjectSchema(client=client).load(data)
def to_yaml(self, path=None):
"""Write an instance to the referenced YAML file."""
from renku import __version__
self.agent_version = __version__
self._metadata_path = path or self._metadata_path
data = ProjectSchema().dump(self)
jsonld.write_yaml(path=self._metadata_path, data=data)
@attr.s(eq=False, order=False)
class CommitMixin:
"""Represent a commit mixin."""
commit = attr.ib(default=None, kw_only=True)
client = attr.ib(default=None, kw_only=True)
path = attr.ib(default=None, kw_only=True, converter=_str_or_none)
_id = attr.ib(default=None, kw_only=True)
_label = attr.ib(kw_only=True)
_project = attr.ib(type=Project, kw_only=True, default=None)
def default_id(self):
"""Configure calculated ID."""
hexsha = self.commit.hexsha if self.commit else "UNCOMMITTED"
return generate_file_id(client=self.client, hexsha=hexsha, path=self.path)
@_label.default
def default_label(self):
"""Generate a default label."""
if self.commit:
hexsha = self.commit.hexsha
else:
hexsha = "UNCOMMITTED"
if self.path:
path = self.path
if self.client and os.path.isabs(path):
path = pathlib.Path(path).relative_to(self.client.path)
return generate_label(path, hexsha)
return hexsha
def __attrs_post_init__(self):
"""Post-init hook."""
if self.path and self.client:
path = pathlib.Path(self.path)
if path.is_absolute():
self.path = str(path.relative_to(self.client.path))
# always force "project" to be the current project
if self.client:
try:
self._project = self.client.project
except ValueError:
metadata_path = self.client.renku_path.joinpath(OLD_METADATA_PATH)
self._project = Project.from_yaml(metadata_path, client=self.client)
if not self._id:
self._id = self.default_id()
@attr.s(eq=False, order=False)
class Entity(CommitMixin):
"""Represent a data value or item."""
_parent = attr.ib(
default=None, kw_only=True, converter=lambda value: weakref.ref(value) if value is not None else None
)
checksum = attr.ib(default=None, kw_only=True, type=str)
@classmethod
def from_revision(cls, client, path, revision="HEAD", parent=None, find_previous=True, **kwargs):
"""Return dependency from given path and revision."""
if find_previous:
revision = client.repository.get_previous_commit(path, revision=revision)
elif revision == "HEAD":
revision = client.repository.head.commit
else:
assert isinstance(revision, Commit)
client, commit, path = client.get_in_submodules(revision, path)
path_ = client.path / path
if path != "." and path_.is_dir():
entity = Collection(client=client, commit=commit, path=path, members=[], parent=parent)
files_in_commit = [c.b_path for c in commit.get_changes() if not c.deleted]
# update members with commits
for member in path_.iterdir():
if member.name == ".gitkeep":
continue
member_path = str(member.relative_to(client.path))
find_previous = True
if member_path in files_in_commit:
# we already know the newest commit, no need to look it up
find_previous = False
try:
assert all(member_path != m.path for m in entity.members)
entity.members.append(
cls.from_revision(
client, member_path, commit, parent=entity, find_previous=find_previous, **kwargs
)
)
except errors.GitCommitNotFoundError:
pass
else:
entity = cls(client=client, commit=commit, path=str(path), parent=parent, **kwargs)
return entity
@property
def parent(self): # pragma: no cover
"""Return the parent object."""
return self._parent() if self._parent is not None else None
@property
def entities(self):
"""Yield itself."""
if self.client and not self.commit and self._label and "@UNCOMMITTED" not in self._label:
self.commit = self.client.repository.get_commit(self._label.rsplit("@", maxsplit=1)[-1])
yield self
@attr.s(eq=False, order=False)
class Collection(Entity):
"""Represent a directory with files."""
members = attr.ib(kw_only=True, default=None)
def __attrs_post_init__(self):
"""Init members."""
super().__attrs_post_init__()
if self.members is None:
self.members = self.default_members()
for member in self.members:
member._parent = weakref.ref(self)
def default_members(self):
"""Generate default members as entities from current path."""
if not self.client:
return []
dir_path = self.client.path / self.path
if not dir_path.exists():
# likely a directory deleted in a previous commit
return []
assert dir_path.is_dir()
members = []
for path in dir_path.iterdir():
if path.name == ".gitkeep":
continue # ignore empty directories in Git repository
cls = Collection if path.is_dir() else Entity
members.append(
cls(commit=self.commit, client=self.client, path=str(path.relative_to(self.client.path)), parent=self)
)
return members
@property
def entities(self):
"""Recursively return all files."""
for member in self.members:
if not member.client and self.client:
member.client = self.client
yield from member.entities
if self.client and not self.commit and self._label and "@UNCOMMITTED" not in self._label:
self.commit = self.client.repository.get_commit(self._label.rsplit("@", maxsplit=1)[-1])
yield self
@attr.s(eq=False, order=False)
class MappedIOStream(object):
"""Represents an IO stream (``stdin``, ``stdout``, ``stderr``)."""
client = attr.ib(default=None, kw_only=True)
_id = attr.ib(default=None, kw_only=True)
_label = attr.ib(default=None, kw_only=True)
STREAMS = ["stdin", "stdout", "stderr"]
stream_type = attr.ib(type=str, kw_only=True)
def default_id(self):
"""Generate an id for a mapped stream."""
host = "localhost"
if self.client:
host = self.client.remote.get("host") or host
host = os.environ.get("RENKU_DOMAIN") or host
return urljoin("https://{host}".format(host=host), pathlib.posixpath.join("/iostreams", self.stream_type))
def default_label(self):
"""Set default label."""
return 'Stream mapping for stream "{}"'.format(self.stream_type)
def __attrs_post_init__(self):
"""Post-init hook."""
if not self._id:
self._id = self.default_id()
if not self._label:
self._label = self.default_label()
@attr.s(eq=False, order=False)
class CommandParameter:
"""Represents a parameter for an execution template."""
_id = attr.ib(default=None, kw_only=True)
_label = attr.ib(default=None, kw_only=True)
default_value = attr.ib(default=None, kw_only=True)
description = attr.ib(default=None, kw_only=True)
name: str = attr.ib(default=None, kw_only=True)
position = attr.ib(default=None, type=int, kw_only=True)
prefix = attr.ib(default=None, type=str, kw_only=True)
@property
def sanitized_id(self):
"""Return ``_id`` sanitized for use in non-jsonld contexts."""
if "/steps/" in self._id:
return "/".join(self._id.split("/")[-4:])
return "/".join(self._id.split("/")[-2:])
def default_label(self):
"""Set default label."""
raise NotImplementedError
def default_name(self):
"""Create a default name."""
raise NotImplementedError
def __attrs_post_init__(self):
"""Post-init hook."""
if not self._label:
self._label = self.default_label()
if not self.name:
self.name = self.default_name()
def _generate_name(base, prefix, position):
name = get_slug(prefix.strip(" -=")) if prefix else base
position = position or uuid.uuid4().hex[:RANDOM_ID_LENGTH]
return f"{name}-{position}"
@attr.s(eq=False, order=False)
class CommandArgument(CommandParameter):
"""An argument to a command that is neither input nor output."""
value = attr.ib(default=None, type=str, kw_only=True)
@staticmethod
def generate_id(run_id, position=None):
"""Generate an id for an argument."""
if position:
id_ = str(position)
else:
id_ = uuid.uuid4().hex
return "{}/arguments/{}".format(run_id, id_)
def default_label(self):
"""Set default label."""
return 'Command Argument "{}"'.format(self.default_value)
def default_name(self):
"""Create a default name."""
return _generate_name(base="param", prefix=self.prefix, position=self.position)
def __attrs_post_init__(self):
"""Post-init hook."""
super().__attrs_post_init__()
if not self.default_value:
self.default_value = self.value
@attr.s(eq=False, order=False)
class CommandInput(CommandParameter):
"""An input to a command."""
consumes = attr.ib(kw_only=True)
mapped_to = attr.ib(default=None, kw_only=True)
@staticmethod
def generate_id(run_id, position=None):
"""Generate an id for an argument."""
if position:
id_ = str(position)
else:
id_ = uuid.uuid4().hex
return "{}/inputs/{}".format(run_id, id_)
def default_label(self):
"""Set default label."""
return 'Command Input "{}"'.format(self.default_value)
def default_name(self):
"""Create a default name."""
return _generate_name(base="input", prefix=self.prefix, position=self.position)
def __attrs_post_init__(self):
"""Post-init hook."""
super().__attrs_post_init__()
if not self.default_value:
self.default_value = self.consumes.path
@attr.s(eq=False, order=False)
class CommandOutput(CommandParameter):
"""An output of a command."""
create_folder = attr.ib(default=False, kw_only=True, type=bool)
produces = attr.ib(kw_only=True)
mapped_to = attr.ib(default=None, kw_only=True)
@staticmethod
def generate_id(run_id, position=None):
"""Generate an id for an argument."""
if position:
id_ = str(position)
else:
id_ = uuid.uuid4().hex
return "{}/outputs/{}".format(run_id, id_)
def default_label(self):
"""Set default label."""
return 'Command Output "{}"'.format(self.default_value)
def default_name(self):
"""Create a default name."""
return _generate_name(base="output", prefix=self.prefix, position=self.position)
def __attrs_post_init__(self):
"""Post-init hook."""
super().__attrs_post_init__()
if not self.default_value:
self.default_value = self.produces.path
@attr.s(eq=False, order=False)
class RunParameter:
"""A run parameter that is set inside the script."""
_id = attr.ib(default=None, kw_only=True)
_label = attr.ib(default=None, kw_only=True)
name = attr.ib(default=None, type=str, kw_only=True)
value = attr.ib(default=None, type=str, kw_only=True)
type = attr.ib(default=None, type=str, kw_only=True)
@total_ordering
@attr.s(eq=False, order=False)
class Run(CommitMixin):
"""Represents a `renku run` execution template."""
command = attr.ib(default=None, type=str, kw_only=True)
successcodes = attr.ib(kw_only=True, type=list, factory=list)
subprocesses = attr.ib(kw_only=True, factory=list)
arguments = attr.ib(kw_only=True, factory=list)
inputs = attr.ib(kw_only=True, factory=list)
outputs = attr.ib(kw_only=True, factory=list)
run_parameters = attr.ib(kw_only=True, factory=list)
name = attr.ib(default=None, kw_only=True, type=str)
description = attr.ib(default=None, kw_only=True, type=str)
keywords = attr.ib(kw_only=True, factory=list)
_activity = attr.ib(kw_only=True, default=None)
@staticmethod
def generate_id(client, identifier=None):
"""Generate an id for an argument."""
host = "localhost"
if client:
host = client.remote.get("host") or host
host = os.environ.get("RENKU_DOMAIN") or host
if not identifier:
identifier = str(uuid.uuid4())
return urljoin("https://{host}".format(host=host), pathlib.posixpath.join("/runs", quote(identifier, safe="")))
def __lt__(self, other):
"""Compares two subprocesses order based on their dependencies."""
a_inputs = set()
b_outputs = set()
for i in other.inputs:
entity = i.consumes
for subentity in entity.entities:
a_inputs.add(subentity.path)
for i in self.outputs:
entity = i.produces
for subentity in entity.entities:
b_outputs.add(subentity.path)
return a_inputs & b_outputs
def add_subprocess(self, subprocess):
"""Adds a subprocess to this run."""
process_order = 0
if self.subprocesses:
processes = [o.process for o in self.subprocesses]
# Get position to insert based on dependencies
process_order = bisect(processes, subprocess)
if process_order < len(processes):
# adjust ids of inputs inherited from latter subprocesses
for i in range(len(processes), process_order, -1):
sp = self.subprocesses[i - 1]
sp._id = sp._id.replace(f"subprocess/{i}", f"subprocess/{i+1}")
sp.index += 1
for inp in self.inputs:
inp._id = inp._id.replace(f"/steps/step_{i}/", f"/steps/step_{i+1}/")
for outp in self.outputs:
outp._id = outp._id.replace(f"/steps/step_{i}/", f"/steps/step_{i+1}/")
input_paths = [i.consumes.path for i in self.inputs]
output_paths = [o.produces.path for o in self.outputs]
for input_ in subprocess.inputs:
if input_.consumes.path not in input_paths and input_.consumes.path not in output_paths:
new_input = copy(input_)
new_input._id = f"{self._id}/steps/step_{process_order + 1}/" f"{new_input.sanitized_id}"
new_input.mapped_to = None
matching_output = next((o for o in self.outputs if o.produces.path == new_input.consumes.path), None)
if not matching_output:
self.inputs.append(new_input)
input_paths.append(new_input.consumes.path)
for output in subprocess.outputs:
if output.produces.path not in output_paths:
new_output = copy(output)
new_output._id = f"{self._id}/steps/step_{process_order + 1}/" f"{new_output.sanitized_id}"
new_output.mapped_to = None
self.outputs.append(new_output)
output_paths.append(new_output.produces.path)
matching_input = next((i for i in self.inputs if i.consumes.path == new_output.produces.path), None)
if matching_input:
self.inputs.remove(matching_input)
input_paths.remove(matching_input.consumes.path)
ordered_process = OrderedSubprocess(
id=OrderedSubprocess.generate_id(self._id, process_order + 1), index=process_order + 1, process=subprocess
)
self.subprocesses.insert(process_order, ordered_process)
@total_ordering
@attr.s(eq=False, order=False)
class OrderedSubprocess:
"""A subprocess with ordering."""
_id = attr.ib(kw_only=True)
index = attr.ib(kw_only=True, type=int)
process = attr.ib(kw_only=True)
@staticmethod
def generate_id(parent_id, index):
"""Generate an id for an ``OrderedSubprocess``."""
return f"{parent_id}/subprocess/{index}"
def __lt__(self, other):
"""Compares two ordered subprocesses."""
return self.index < other.index
@attr.s
class Association:
"""Assign responsibility to an agent for an activity."""
plan = attr.ib()
agent = attr.ib(default=None)
_id = attr.ib(kw_only=True)
class EntityProxyMixin:
"""Implement proxy to entity attribute."""
def __getattribute__(self, name):
"""Proxy entity attributes."""
cls = object.__getattribute__(self, "__class__")
names = {field.name for field in attr.fields(cls)}
names |= set(dir(cls))
if name in names:
return object.__getattribute__(self, name)
entity = object.__getattribute__(self, "entity")
return getattr(entity, name)
@attr.s(eq=False, order=False)
class Usage(EntityProxyMixin):
"""Represent a dependent path."""
entity = attr.ib(kw_only=True)
role = attr.ib(default=None, kw_only=True)
_id = attr.ib(default=None, kw_only=True)
@attr.s(eq=False, order=False)
class Generation(EntityProxyMixin):
"""Represent an act of generating a file."""
entity = attr.ib()
role = attr.ib(default=None)
_activity = attr.ib(
default=None, kw_only=True, converter=lambda value: weakref.ref(value) if value is not None else None
)
_id = attr.ib(kw_only=True)
@property
def activity(self):
"""Return the activity object."""
return self._activity() if self._activity is not None else None
@_id.default
def default_id(self):
"""Configure calculated ID."""
if self.role:
return f"{self.activity._id}/{self.role}"
return f"{self.activity._id}/tree/{quote(str(self.entity.path))}"
@attr.s(eq=False, order=False)
class Activity(CommitMixin):
"""Represent an activity in the repository."""
_id = attr.ib(default=None, kw_only=True)
_message = attr.ib(kw_only=True)
_was_informed_by = attr.ib(kw_only=True)
part_of = attr.ib(default=None, kw_only=True)
_collections = attr.ib(default=attr.Factory(OrderedDict), init=False, kw_only=True)
generated = attr.ib(kw_only=True, default=None)
invalidated = attr.ib(kw_only=True, default=None)
influenced = attr.ib(kw_only=True)
started_at_time = attr.ib(kw_only=True)
ended_at_time = attr.ib(kw_only=True)
agents = attr.ib(kw_only=True)
_metadata_path = attr.ib(default=None, init=False)
@classmethod
def from_yaml(cls, path, client=None, commit=None):
"""Return an instance from a YAML file."""
data = jsonld.read_yaml(path)
self = cls.from_jsonld(data=data, client=client, commit=commit)
self._metadata_path = path
return self
@classmethod
def from_jsonld(cls, data, client=None, commit=None):
"""Create an instance from JSON-LD data."""
if isinstance(data, cls):
return data
if not isinstance(data, list):
raise ValueError(data)
schema = ActivitySchema
if any(str(wfprov.WorkflowRun) in d["@type"] for d in data):
schema = WorkflowRunSchema
elif any(str(wfprov.ProcessRun) in d["@type"] for d in data):
schema = ProcessRunSchema
return schema(client=client, commit=commit, flattened=True).load(data)
@_message.default
def default_message(self):
"""Generate a default message."""
if self.commit:
return self.commit.message
@_was_informed_by.default
def default_was_informed_by(self):
"""List parent actions."""
if self.commit:
return [self.generate_id(parent) for parent in self.commit.parents]
@started_at_time.default
def default_started_at_time(self):
"""Configure calculated properties."""
if self.commit:
return self.commit.authored_datetime
@ended_at_time.default
def default_ended_at_time(self):
"""Configure calculated properties."""
if self.commit:
return self.commit.committed_datetime
@agents.default
def default_agents(self):
"""Set person agent to be the author of the commit."""
renku_agent = SoftwareAgent(label="renku {0}".format(__version__), id=version_url)
if self.commit:
return [Person.from_commit(self.commit), renku_agent]
return [renku_agent]
@influenced.default
def default_influenced(self):
"""Calculate default values."""
return list(self._collections.values())
@attr.s(eq=False, order=False)
class ProcessRun(Activity):
"""A process run is a particular execution of a Process description."""
__association_cls__ = Run
generated = attr.ib(kw_only=True, default=None)
association = attr.ib(default=None, kw_only=True)
annotations = attr.ib(kw_only=True, default=None)
qualified_usage = attr.ib(kw_only=True, default=None)
run_parameter = attr.ib(kw_only=True, default=None)
def __attrs_post_init__(self):
"""Calculate properties."""
super().__attrs_post_init__()
commit_not_set = not self.commit or self.commit.hexsha in self._id
if commit_not_set and self.client and Path(self.path).exists():
self.commit = self.client.repository.get_previous_commit(self.path)
if self.association:
self.association.plan._activity = weakref.ref(self)
plan = self.association.plan
if not plan.commit:
if self.client:
plan.client = self.client
if self.commit:
plan.commit = self.commit
if plan.inputs:
for i in plan.inputs:
_set_entity_client_commit(i.consumes, self.client, self.commit)
if plan.outputs:
for o in plan.outputs:
_set_entity_client_commit(o.produces, self.client, self.commit)
if self.qualified_usage and self.client and self.commit:
usages = []
revision = self.commit.hexsha
for usage in self.qualified_usage:
if not usage.commit and "@UNCOMMITTED" in usage._label:
usages.append(
Usage.from_revision(
client=self.client, path=usage.path, role=usage.role, revision=revision, id=usage._id
)
)
else:
if not usage.client:
usage.entity.set_client(self.client)
if not usage.commit:
revision = usage._label.rsplit("@", maxsplit=1)[-1]
usage.entity.commit = self.client.repository.get_commit(revision)
usages.append(usage)
self.qualified_usage = usages
@classmethod
def generate_id(cls, commit_hexsha):
"""Calculate action ID."""
host = "localhost"
if hasattr(cls, "client"):
host = cls.client.remote.get("host") or host
host = os.environ.get("RENKU_DOMAIN") or host
return urljoin(
"https://{host}".format(host=host),
pathlib.posixpath.join("/activities", f"commit/{commit_hexsha}"),
)
@classmethod
def from_run(cls, run, client, path, commit=None, subprocess_index=None, update_commits=False):
"""Convert a ``Run`` to a ``ProcessRun``."""
if not commit:
commit = client.repository.head.commit
usages = []
id_ = ProcessRun.generate_id(commit.hexsha)
if subprocess_index is not None:
id_ = f"{id_}/steps/step_{subprocess_index}"
for input_ in run.inputs:
usage_id = f"{id_}/{input_.sanitized_id}"
input_path = input_.consumes.path
entity = input_.consumes
if update_commits:
commit = client.repository.get_previous_commit(input_path, revision=commit.hexsha)
entity = Entity.from_revision(client, input_path, commit)
dependency = Usage(entity=entity, role=input_.sanitized_id, id=usage_id)
usages.append(dependency)
agent = SoftwareAgent.from_commit(commit)
association = Association(agent=agent, id=id_ + "/association", plan=run)
run_parameter = []
for parameter in run.run_parameters:
parameter_id = f"{id_}/{parameter.name}"
run_parameter.append(RunParameter(name=parameter.name, value=parameter.value, id=parameter_id))
process_run = cls(
id=id_,
qualified_usage=usages,
association=association,
client=client,
commit=commit,
path=path,
run_parameter=run_parameter,
)
generated = []
for output in run.outputs:
entity = Entity.from_revision(client, output.produces.path, revision=commit, parent=output.produces.parent)
generation = Generation(activity=process_run, role=output.sanitized_id, entity=entity)
generated.append(generation)
process_run.generated = generated
return process_run
def to_yaml(self, path=None):
"""Write an instance to the referenced YAML file."""