Merge branch '19840-docker-port-number'
[arvados.git] / sdk / cwl / arvados_cwl / arvworkflow.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 from past.builtins import basestring
6 from future.utils import viewitems
7
8 import os
9 import json
10 import copy
11 import logging
12
13 from schema_salad.sourceline import SourceLine, cmap
14 import schema_salad.ref_resolver
15
16 import arvados.collection
17
18 from cwltool.pack import pack
19 from cwltool.load_tool import fetch_document, resolve_and_validate_document
20 from cwltool.process import shortname
21 from cwltool.workflow import Workflow, WorkflowException, WorkflowStep
22 from cwltool.utils import adjustFileObjs, adjustDirObjs, visit_class, normalizeFilesDirs
23 from cwltool.context import LoadingContext
24
25 import ruamel.yaml as yaml
26
27 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
28                      trim_anonymous_location, remove_redundant_fields, discover_secondary_files,
29                      make_builder, arvados_jobs_image)
30 from .pathmapper import ArvPathMapper, trim_listing
31 from .arvtool import ArvadosCommandTool, set_cluster_target
32 from ._version import __version__
33
34 from .perf import Perf
35
36 logger = logging.getLogger('arvados.cwl-runner')
37 metrics = logging.getLogger('arvados.cwl-runner.metrics')
38
39 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
40 sum_res_pars = ("outdirMin", "outdirMax")
41
42 def make_wrapper_workflow(arvRunner, main, packed, project_uuid, name, git_info, tool):
43     col = arvados.collection.Collection(api_client=arvRunner.api,
44                                         keep_client=arvRunner.keep_client)
45
46     with col.open("workflow.json", "wt") as f:
47         json.dump(packed, f, sort_keys=True, indent=4, separators=(',',': '))
48
49     pdh = col.portable_data_hash()
50
51     toolname = tool.tool.get("label") or tool.metadata.get("label") or os.path.basename(tool.tool["id"])
52     if git_info and git_info.get("http://arvados.org/cwl#gitDescribe"):
53         toolname = "%s (%s)" % (toolname, git_info.get("http://arvados.org/cwl#gitDescribe"))
54
55     existing = arvRunner.api.collections().list(filters=[["portable_data_hash", "=", pdh], ["owner_uuid", "=", project_uuid]]).execute(num_retries=arvRunner.num_retries)
56     if len(existing["items"]) == 0:
57         col.save_new(name=toolname, owner_uuid=project_uuid, ensure_unique_name=True)
58
59     # now construct the wrapper
60
61     step = {
62         "id": "#main/" + toolname,
63         "in": [],
64         "out": [],
65         "run": "keep:%s/workflow.json#main" % pdh,
66         "label": name
67     }
68
69     newinputs = []
70     for i in main["inputs"]:
71         inp = {}
72         # Make sure to only copy known fields that are meaningful at
73         # the workflow level. In practice this ensures that if we're
74         # wrapping a CommandLineTool we don't grab inputBinding.
75         # Right now also excludes extension fields, which is fine,
76         # Arvados doesn't currently look for any extension fields on
77         # input parameters.
78         for f in ("type", "label", "secondaryFiles", "streamable",
79                   "doc", "id", "format", "loadContents",
80                   "loadListing", "default"):
81             if f in i:
82                 inp[f] = i[f]
83         newinputs.append(inp)
84
85     wrapper = {
86         "class": "Workflow",
87         "id": "#main",
88         "inputs": newinputs,
89         "outputs": [],
90         "steps": [step]
91     }
92
93     for i in main["inputs"]:
94         step["in"].append({
95             "id": "#main/step/%s" % shortname(i["id"]),
96             "source": i["id"]
97         })
98
99     for i in main["outputs"]:
100         step["out"].append({"id": "#main/step/%s" % shortname(i["id"])})
101         wrapper["outputs"].append({"outputSource": "#main/step/%s" % shortname(i["id"]),
102                                    "type": i["type"],
103                                    "id": i["id"]})
104
105     wrapper["requirements"] = [{"class": "SubworkflowFeatureRequirement"}]
106
107     if main.get("requirements"):
108         wrapper["requirements"].extend(main["requirements"])
109     if main.get("hints"):
110         wrapper["hints"] = main["hints"]
111
112     doc = {"cwlVersion": "v1.2", "$graph": [wrapper]}
113
114     if git_info:
115         for g in git_info:
116             doc[g] = git_info[g]
117
118     return json.dumps(doc, sort_keys=True, indent=4, separators=(',',': '))
119
120 def upload_workflow(arvRunner, tool, job_order, project_uuid,
121                     runtimeContext, uuid=None,
122                     submit_runner_ram=0, name=None, merged_map=None,
123                     submit_runner_image=None,
124                     git_info=None):
125
126     packed = packed_workflow(arvRunner, tool, merged_map, runtimeContext, git_info)
127
128     adjustDirObjs(job_order, trim_listing)
129     adjustFileObjs(job_order, trim_anonymous_location)
130     adjustDirObjs(job_order, trim_anonymous_location)
131
132     main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
133     for inp in main["inputs"]:
134         sn = shortname(inp["id"])
135         if sn in job_order:
136             inp["default"] = job_order[sn]
137
138     if not name:
139         name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
140
141     upload_dependencies(arvRunner, name, tool.doc_loader,
142                         packed, tool.tool["id"], False,
143                         runtimeContext)
144
145     wf_runner_resources = None
146
147     hints = main.get("hints", [])
148     found = False
149     for h in hints:
150         if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
151             wf_runner_resources = h
152             found = True
153             break
154     if not found:
155         wf_runner_resources = {"class": "http://arvados.org/cwl#WorkflowRunnerResources"}
156         hints.append(wf_runner_resources)
157
158     wf_runner_resources["acrContainerImage"] = arvados_jobs_image(arvRunner,
159                                                                   submit_runner_image or "arvados/jobs:"+__version__,
160                                                                   runtimeContext)
161
162     if submit_runner_ram:
163         wf_runner_resources["ramMin"] = submit_runner_ram
164
165     main["hints"] = hints
166
167     wrapper = make_wrapper_workflow(arvRunner, main, packed, project_uuid, name, git_info, tool)
168
169     body = {
170         "workflow": {
171             "name": name,
172             "description": tool.tool.get("doc", ""),
173             "definition": wrapper
174         }}
175     if project_uuid:
176         body["workflow"]["owner_uuid"] = project_uuid
177
178     if uuid:
179         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
180     else:
181         call = arvRunner.api.workflows().create(body=body)
182     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
183
184 def dedup_reqs(reqs):
185     dedup = {}
186     for r in reversed(reqs):
187         if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
188             dedup[r["class"]] = r
189     return [dedup[r] for r in sorted(dedup.keys())]
190
191 def get_overall_res_req(res_reqs):
192     """Take the overall of a list of ResourceRequirement,
193     i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
194     and the sum of outdirMin, outdirMax."""
195
196     all_res_req = {}
197     exception_msgs = []
198     for a in max_res_pars + sum_res_pars:
199         all_res_req[a] = []
200         for res_req in res_reqs:
201             if a in res_req:
202                 if isinstance(res_req[a], int): # integer check
203                     all_res_req[a].append(res_req[a])
204                 else:
205                     msg = SourceLine(res_req, a).makeError(
206                     "Non-top-level ResourceRequirement in single container cannot have expressions")
207                     exception_msgs.append(msg)
208     if exception_msgs:
209         raise WorkflowException("\n".join(exception_msgs))
210     else:
211         overall_res_req = {}
212         for a in all_res_req:
213             if all_res_req[a]:
214                 if a in max_res_pars:
215                     overall_res_req[a] = max(all_res_req[a])
216                 elif a in sum_res_pars:
217                     overall_res_req[a] = sum(all_res_req[a])
218         if overall_res_req:
219             overall_res_req["class"] = "ResourceRequirement"
220         return cmap(overall_res_req)
221
222 class ArvadosWorkflowStep(WorkflowStep):
223     def __init__(self,
224                  toolpath_object,      # type: Dict[Text, Any]
225                  pos,                  # type: int
226                  loadingContext,       # type: LoadingContext
227                  arvrunner,
228                  *argc,
229                  **argv
230                 ):  # type: (...) -> None
231
232         if arvrunner.fast_submit:
233             self.tool = toolpath_object
234             self.tool["inputs"] = []
235             self.tool["outputs"] = []
236         else:
237             super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
238             self.tool["class"] = "WorkflowStep"
239         self.arvrunner = arvrunner
240
241     def job(self, joborder, output_callback, runtimeContext):
242         runtimeContext = runtimeContext.copy()
243         runtimeContext.toplevel = True  # Preserve behavior for #13365
244
245         builder = make_builder({shortname(k): v for k,v in viewitems(joborder)}, self.hints, self.requirements,
246                                runtimeContext, self.metadata)
247         runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
248         return super(ArvadosWorkflowStep, self).job(joborder, output_callback, runtimeContext)
249
250
251 class ArvadosWorkflow(Workflow):
252     """Wrap cwltool Workflow to override selected methods."""
253
254     def __init__(self, arvrunner, toolpath_object, loadingContext):
255         self.arvrunner = arvrunner
256         self.wf_pdh = None
257         self.dynamic_resource_req = []
258         self.static_resource_req = []
259         self.wf_reffiles = []
260         self.loadingContext = loadingContext
261         super(ArvadosWorkflow, self).__init__(toolpath_object, loadingContext)
262         self.cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
263
264     def job(self, joborder, output_callback, runtimeContext):
265
266         builder = make_builder(joborder, self.hints, self.requirements, runtimeContext, self.metadata)
267         runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
268
269         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
270         if not req:
271             return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
272
273         # RunInSingleContainer is true
274
275         with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
276             if "id" not in self.tool:
277                 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
278
279         discover_secondary_files(self.arvrunner.fs_access, builder,
280                                  self.tool["inputs"], joborder)
281         normalizeFilesDirs(joborder)
282
283         with Perf(metrics, "subworkflow upload_deps"):
284             upload_dependencies(self.arvrunner,
285                                 os.path.basename(joborder.get("id", "#")),
286                                 self.doc_loader,
287                                 joborder,
288                                 joborder.get("id", "#"),
289                                 False,
290                                 runtimeContext)
291
292             if self.wf_pdh is None:
293                 packed = pack(self.loadingContext, self.tool["id"], loader=self.doc_loader)
294
295                 for p in packed["$graph"]:
296                     if p["id"] == "#main":
297                         p["requirements"] = dedup_reqs(self.requirements)
298                         p["hints"] = dedup_reqs(self.hints)
299
300                 def visit(item):
301                     if "requirements" in item:
302                         item["requirements"] = [i for i in item["requirements"] if i["class"] != "DockerRequirement"]
303                     for t in ("hints", "requirements"):
304                         if t not in item:
305                             continue
306                         for req in item[t]:
307                             if req["class"] == "ResourceRequirement":
308                                 dyn = False
309                                 for k in max_res_pars + sum_res_pars:
310                                     if k in req:
311                                         if isinstance(req[k], basestring):
312                                             if item["id"] == "#main":
313                                                 # only the top-level requirements/hints may contain expressions
314                                                 self.dynamic_resource_req.append(req)
315                                                 dyn = True
316                                                 break
317                                             else:
318                                                 with SourceLine(req, k, WorkflowException):
319                                                     raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
320                                 if not dyn:
321                                     self.static_resource_req.append(req)
322
323                 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
324
325                 if self.static_resource_req:
326                     self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
327
328                 upload_dependencies(self.arvrunner,
329                                     runtimeContext.name,
330                                     self.doc_loader,
331                                     packed,
332                                     self.tool["id"],
333                                     False,
334                                     runtimeContext)
335
336                 # Discover files/directories referenced by the
337                 # workflow (mainly "default" values)
338                 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
339
340
341         if self.dynamic_resource_req:
342             # Evaluate dynamic resource requirements using current builder
343             rs = copy.copy(self.static_resource_req)
344             for dyn_rs in self.dynamic_resource_req:
345                 eval_req = {"class": "ResourceRequirement"}
346                 for a in max_res_pars + sum_res_pars:
347                     if a in dyn_rs:
348                         eval_req[a] = builder.do_eval(dyn_rs[a])
349                 rs.append(eval_req)
350             job_res_reqs = [get_overall_res_req(rs)]
351         else:
352             job_res_reqs = self.static_resource_req
353
354         with Perf(metrics, "subworkflow adjust"):
355             joborder_resolved = copy.deepcopy(joborder)
356             joborder_keepmount = copy.deepcopy(joborder)
357
358             reffiles = []
359             visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
360
361             mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
362                                    "/keep/%s",
363                                    "/keep/%s/%s")
364
365             # For containers API, we need to make sure any extra
366             # referenced files (ie referenced by the workflow but
367             # not in the inputs) are included in the mounts.
368             if self.wf_reffiles:
369                 runtimeContext = runtimeContext.copy()
370                 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
371
372             def keepmount(obj):
373                 remove_redundant_fields(obj)
374                 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
375                     if "location" not in obj:
376                         raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
377                 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
378                     if obj["location"].startswith("keep:"):
379                         obj["location"] = mapper.mapper(obj["location"]).target
380                         if "listing" in obj:
381                             del obj["listing"]
382                     elif obj["location"].startswith("_:"):
383                         del obj["location"]
384                     else:
385                         raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
386
387             visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
388
389             def resolved(obj):
390                 if obj["location"].startswith("keep:"):
391                     obj["location"] = mapper.mapper(obj["location"]).resolved
392
393             visit_class(joborder_resolved, ("File", "Directory"), resolved)
394
395             if self.wf_pdh is None:
396                 adjustFileObjs(packed, keepmount)
397                 adjustDirObjs(packed, keepmount)
398                 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed, runtimeContext)
399
400         self.loadingContext = self.loadingContext.copy()
401         self.loadingContext.metadata = self.loadingContext.metadata.copy()
402         self.loadingContext.metadata["http://commonwl.org/cwltool#original_cwlVersion"] = "v1.0"
403
404         if len(job_res_reqs) == 1:
405             # RAM request needs to be at least 128 MiB or the workflow
406             # runner itself won't run reliably.
407             if job_res_reqs[0].get("ramMin", 1024) < 128:
408                 job_res_reqs[0]["ramMin"] = 128
409
410         arguments = ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl", "cwl.input.yml"]
411         if runtimeContext.debug:
412             arguments.insert(0, '--debug')
413
414         wf_runner = cmap({
415             "class": "CommandLineTool",
416             "baseCommand": "cwltool",
417             "inputs": self.tool["inputs"],
418             "outputs": self.tool["outputs"],
419             "stdout": "cwl.output.json",
420             "requirements": self.requirements+job_res_reqs+[
421                 {"class": "InlineJavascriptRequirement"},
422                 {
423                 "class": "InitialWorkDirRequirement",
424                 "listing": [{
425                         "entryname": "workflow.cwl",
426                         "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
427                     }, {
428                         "entryname": "cwl.input.yml",
429                         "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
430                     }]
431             }],
432             "hints": self.hints,
433             "arguments": arguments,
434             "id": "#"
435         })
436         return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
437
438     def make_workflow_step(self,
439                            toolpath_object,      # type: Dict[Text, Any]
440                            pos,                  # type: int
441                            loadingContext,       # type: LoadingContext
442                            *argc,
443                            **argv
444     ):
445         # (...) -> WorkflowStep
446         return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)