/
m_0005__2_cwl.py
504 lines (385 loc) · 17 KB
/
m_0005__2_cwl.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
# -*- coding: utf-8 -*-
#
# Copyright 2020 - 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.
"""Initial migrations."""
import glob
import os
import uuid
from collections import defaultdict
from functools import cmp_to_key
from hashlib import sha1
from pathlib import Path
from cwlgen import CommandLineTool, parse_cwl
from cwlgen.requirements import InitialWorkDirRequirement
from werkzeug.utils import secure_filename
from renku.core import errors
from renku.core.management.migrations.models.v3 import Dataset
from renku.core.management.migrations.models.v9 import (
Collection,
CommandArgument,
CommandInput,
CommandOutput,
Entity,
MappedIOStream,
Person,
ProcessRun,
Run,
SoftwareAgent,
WorkflowRun,
)
from renku.core.management.migrations.utils import OLD_DATASETS_PATH, OLD_WORKFLOW_PATH, MigrationType
from renku.core.metadata.repository import Actor, Commit, git_unicode_unescape
from renku.core.utils import communication
from renku.version import __version__, version_url
default_missing_software_agent = SoftwareAgent(
label="renku pre 0.11.0", id="https://github.com/swissdatasciencecenter/renku-python/tree/pre-0.11.0"
)
def migrate(migration_context):
"""Migration function."""
if MigrationType.WORKFLOWS not in migration_context.options.type:
return
_migrate_old_workflows(migration_context.client)
def _migrate_old_workflows(client):
"""Migrates old cwl workflows to new jsonld format."""
def sort_cwl_commits(e1, e2):
"""Sorts cwl commits in order of their creation."""
commit1 = e1[1]
commit2 = e2[1]
return commit1.compare_to(commit2)
cache = RepositoryCache.from_client(client)
client.cache = cache
wf_path = f"{client.renku_path}/workflow/*.cwl"
for path in glob.glob(wf_path):
if path not in cache.cwl_files_commits:
raise ValueError(f"Couldn't find a previous commit for path `{path}`")
cwl_paths = list(cache.cwl_files_commits.items())
cwl_paths = sorted(cwl_paths, key=cmp_to_key(sort_cwl_commits))
for n, element in enumerate(cwl_paths, start=1):
communication.echo(f"Processing commit {n}/{len(cwl_paths)}", end="\r")
cwl_file, commit = element
if not Path(cwl_file).exists():
continue
path = _migrate_cwl(client, cwl_file, commit)
os.remove(cwl_file)
client.repository.add(cwl_file, path)
if client.repository.is_dirty():
commit_msg = "renku migrate: committing migrated workflow"
committer = Actor(name=f"renku {__version__}", email=version_url)
client.repository.commit(commit_msg, committer=committer, no_verify=True)
def _migrate_cwl(client, path, commit):
"""Migrate a cwl file."""
workflow = parse_cwl_cached(str(path))
if isinstance(workflow, CommandLineTool):
_, path = _migrate_single_step(client, workflow, path, commit=commit, persist=True)
else:
_, path = _migrate_composite_step(client, workflow, path, commit=commit)
return path
def _migrate_single_step(client, cmd_line_tool, path, commit=None, parent_commit=None, persist=False):
"""Migrate a single step workflow."""
if not commit:
commit = client.cache.find_previous_commit(path, revision=parent_commit if parent_commit else "HEAD")
run = Run(client=client, path=path, commit=commit)
run.command = " ".join(cmd_line_tool.baseCommand)
run.successcodes = cmd_line_tool.successCodes
inputs = list(cmd_line_tool.inputs)
outputs = list(cmd_line_tool.outputs)
# NOTE: Make run ids deterministic to prevent duplication.
rel_path = Path(path).relative_to(client.path)
if parent_commit:
label = f"{rel_path}@{parent_commit.hexsha}"
else:
label = f"{rel_path}@{commit.hexsha}"
identifier = sha1(label.encode("utf-8")).hexdigest()
base_id = Run.generate_id(client, identifier=identifier)
run._id = base_id
if cmd_line_tool.stdin:
name = cmd_line_tool.stdin.split(".")[1]
if name.endswith(")"):
name = name[:-1]
matched_input = next(i for i in inputs if i.id == name)
inputs.remove(matched_input)
path = client.renku_path / OLD_WORKFLOW_PATH / Path(matched_input.default["path"])
stdin = path.resolve().relative_to(client.path)
id_ = CommandInput.generate_id(base_id, "stdin")
run.inputs.append(
CommandInput(
id=id_,
consumes=_entity_from_path(client, stdin, commit),
mapped_to=MappedIOStream(client=client, stream_type="stdin"),
)
)
if cmd_line_tool.stdout:
run.outputs.append(
CommandOutput(
id=CommandOutput.generate_id(base_id, "stdout"),
produces=_entity_from_path(client, cmd_line_tool.stdout, commit),
mapped_to=MappedIOStream(client=client, stream_type="stdout"),
create_folder=False,
)
)
matched_output = next(o for o in outputs if o.id == "output_stdout")
if matched_output:
outputs.remove(matched_output)
if cmd_line_tool.stderr:
run.outputs.append(
CommandOutput(
id=CommandOutput.generate_id(base_id, "stderr"),
produces=_entity_from_path(client, cmd_line_tool.stderr, commit),
mapped_to=MappedIOStream(client=client, stream_type="stderr"),
create_folder=False,
)
)
matched_output = next(o for o in outputs if o.id == "output_stderr")
if matched_output:
outputs.remove(matched_output)
created_outputs = []
workdir_requirements = [r for r in cmd_line_tool.requirements if isinstance(r, InitialWorkDirRequirement)]
for r in workdir_requirements:
for listing in r.listing:
if listing.entry == '$({"listing": [], "class": "Directory"})':
created_outputs.append(listing.entryname)
# NOTE: multiple outputs might bind to the same input; we use this copy to find output bindings
all_inputs = inputs.copy()
for o in outputs:
prefix = None
position = None
if o.outputBinding.glob.startswith("$(inputs."):
name = o.outputBinding.glob.split(".")[1]
if name.endswith(")"):
name = name[:-1]
matched_input = next(i for i in all_inputs if i.id == name)
try:
inputs.remove(matched_input)
except ValueError:
pass
if isinstance(matched_input.default, dict):
path = client.renku_path / OLD_WORKFLOW_PATH / Path(matched_input.default["path"])
else:
path = Path(matched_input.default)
path = Path(os.path.realpath(client.path / path)).relative_to(client.path)
if matched_input.inputBinding:
prefix = matched_input.inputBinding.prefix
position = matched_input.inputBinding.position
if prefix and matched_input.inputBinding.separate:
prefix += " "
else:
path = Path(o.outputBinding.glob)
create_folder = False
check_path = path
if not (client.path / path).is_dir():
check_path = path.parent
if check_path != "." and str(check_path) in created_outputs:
create_folder = True
run.outputs.append(
CommandOutput(
id=CommandOutput.generate_id(base_id, position),
position=position,
prefix=prefix,
produces=_entity_from_path(client, path, commit),
create_folder=create_folder,
)
)
for i in inputs:
prefix = None
position = None
if i.inputBinding:
prefix = i.inputBinding.prefix
position = i.inputBinding.position
if prefix and i.inputBinding.separate:
prefix += " "
if isinstance(i.default, dict) and "class" in i.default and i.default["class"] in ["File", "Directory"]:
path = client.renku_path / OLD_WORKFLOW_PATH / Path(i.default["path"])
path = Path(os.path.realpath(path)).relative_to(client.path)
run.inputs.append(
CommandInput(
id=CommandInput.generate_id(base_id, position),
position=position,
prefix=prefix,
consumes=_entity_from_path(client, path, commit),
)
)
else:
run.arguments.append(
CommandArgument(
id=CommandArgument.generate_id(base_id, position),
position=position,
prefix=prefix,
value=str(i.default),
)
)
for a in cmd_line_tool.arguments:
id_ = CommandArgument.generate_id(base_id, a["position"])
run.arguments.append(CommandArgument(id=id_, position=a["position"], value=a["valueFrom"]))
if not persist:
return run, None
step_name = "{0}_{1}.yaml".format(uuid.uuid4().hex, secure_filename("_".join(cmd_line_tool.baseCommand)))
absolute_path = client.renku_path / OLD_WORKFLOW_PATH / step_name
path = absolute_path.relative_to(client.path)
run.path = path
process_run = ProcessRun.from_run(run, client, path, commit=commit)
process_run.invalidated = _invalidations_from_commit(client, commit)
# HACK: This fixes broken SoftwareAgent due to rebases done by users
if isinstance(process_run.association.agent, Person) or not process_run.association.agent.label.startswith(
"renku "
):
process_run.association.agent = default_missing_software_agent
process_run.to_yaml(path=absolute_path)
return process_run, absolute_path
def _migrate_composite_step(client, workflow, path, commit=None):
"""Migrate a composite workflow."""
if not commit:
commit = client.cache.find_previous_commit(path)
run = Run(client=client, path=path, commit=commit)
rel_path = Path(path).relative_to(client.path)
label = f"{rel_path}@{commit.hexsha}"
identifier = sha1(label.encode("utf-8")).hexdigest()
run._id = Run.generate_id(client, identifier=identifier)
name = "{0}_migrated.yaml".format(uuid.uuid4().hex)
wf_path = client.renku_path / OLD_WORKFLOW_PATH
run.path = (wf_path / name).relative_to(client.path)
for step in workflow.steps:
if isinstance(step.run, dict):
continue
else:
path = wf_path / step.run
subrun = parse_cwl_cached(str(path))
subprocess, _ = _migrate_single_step(client, subrun, path, parent_commit=commit)
run.add_subprocess(subprocess)
wf = WorkflowRun.from_run(run, client, run.path, commit=commit)
# HACK: This fixes broken SoftwareAgent due to rebases done by users
if isinstance(wf.association.agent, Person) or not wf.association.agent.label.startswith("renku "):
wf.association.agent = default_missing_software_agent
for p in wf._processes:
if isinstance(p.association.agent, Person) or not p.association.agent.label.startswith("renku "):
p.association.agent = default_missing_software_agent
wf.to_yaml(run.path)
return wf, run.path
def _entity_from_path(client, path, commit):
"""Gets the entity associated with a path."""
client, commit, path = client.get_in_submodules(client.cache.find_previous_commit(path, revision=commit), path)
entity_cls = Entity
if (client.path / path).is_dir():
entity_cls = Collection
if str(path).startswith(os.path.join(client.renku_home, OLD_DATASETS_PATH)):
return Dataset.from_yaml(path=client.path / path, client=client, commit=commit)
else:
return entity_cls(commit=commit, client=client, path=str(path))
def _invalidations_from_commit(client, commit: Commit):
"""Gets invalidated files from a commit."""
results = []
collections = dict()
for file in commit.get_changes():
# NOTE: only process deleted files
if not file.deleted:
continue
path = Path(file.a_path)
entity = _get_activity_entity(client, commit, path, collections, deleted=True)
results.append(entity)
return results
def _get_activity_entity(client, commit, path, collections, deleted=False):
"""Gets the entity associated with this Activity and path."""
client, commit, path = client.get_in_submodules(commit, path)
output_path = client.path / path
parents = list(output_path.relative_to(client.path).parents)
collection = None
members = []
for parent in reversed(parents[:-1]):
if str(parent) in collections:
collection = collections[str(parent)]
else:
collection = Collection(client=client, commit=commit, path=str(parent), members=[], parent=collection)
members.append(collection)
collections[str(parent)] = collection
members = collection.members
entity_cls = Entity
if (client.path / path).is_dir():
entity_cls = Collection
if str(path).startswith(os.path.join(client.renku_home, OLD_DATASETS_PATH)) and not deleted:
entity = Dataset.from_yaml(path=client.path / path, client=client, commit=commit)
else:
entity = entity_cls(commit=commit, client=client, path=str(path), parent=collection)
if collection:
collection.members.append(entity)
return entity
_cwl_cache = {}
def parse_cwl_cached(path):
"""Parse cwl and remember the result for future execution."""
if path in _cwl_cache:
return _cwl_cache[path]
cwl = parse_cwl(path)
_cwl_cache[path] = cwl
return cwl
class RepositoryCache:
"""Cache for a git repository."""
def __init__(self, client, cache, cwl_files_commits):
self.client = client
self.cache = cache
self.cwl_files_commits = cwl_files_commits
@classmethod
def from_client(cls, client):
"""Return a cached repository."""
cache = defaultdict(list)
cwl_files_commits_map = {}
for n, commit in enumerate(client.repository.iterate_commits(full_history=True), start=1):
communication.echo(f"Caching commit {n}", end="\r")
cwl_files = []
for file in commit.get_changes():
# Ignore deleted files
if file.deleted:
continue
path = file.a_path
cache[path].append(commit)
if path.startswith(f"{client.renku_home}/workflow/") and path.endswith(".cwl"):
cwl_files.append(os.path.realpath(client.path / path))
cls._update_cwl_files_and_commits(commit, cwl_files_commits_map, cwl_files)
communication.echo(40 * " ", end="\r")
return RepositoryCache(client, cache, cwl_files_commits_map)
@staticmethod
def _update_cwl_files_and_commits(commit, cwl_files_commits_map, cwl_files):
if len(cwl_files) != 1:
return
path = cwl_files[0]
existing_commit = cwl_files_commits_map.get(path)
if existing_commit is None:
cwl_files_commits_map[path] = commit
elif existing_commit.compare_to(commit) < 0: # existing commit is older
cwl_files_commits_map[path] = commit
def find_previous_commit(self, path, revision="HEAD"):
"""Return a previous commit for a given path starting from 'revision'."""
def find_from_client(path, revision):
try:
return self.client.repository.get_previous_commit(path=path, revision=revision, full_history=True)
except errors.GitCommitNotFoundError:
communication.warn(f"Cannot find previous commit for {path} from {str(revision)}")
return revision
try:
path = (self.client.path / path).relative_to(self.client.path)
except ValueError:
pass
path = str(path)
if revision == "HEAD":
revision = self.client.repository.head.commit
commits = self.cache.get(git_unicode_unescape(path))
if not commits:
return find_from_client(path, revision)
if revision in commits:
return revision
for commit in commits:
if commit.compare_to(revision) <= 0:
return commit
# No commit was found
return find_from_client(path, revision)