18238: Make sure to pull default image
[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 from cwltool.pack import pack
17 from cwltool.load_tool import fetch_document, resolve_and_validate_document
18 from cwltool.process import shortname
19 from cwltool.workflow import Workflow, WorkflowException, WorkflowStep
20 from cwltool.utils import adjustFileObjs, adjustDirObjs, visit_class, normalizeFilesDirs
21 from cwltool.context import LoadingContext
22
23 import ruamel.yaml as yaml
24
25 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
26                      trim_anonymous_location, remove_redundant_fields, discover_secondary_files,
27                      make_builder, arvados_jobs_image)
28 from .pathmapper import ArvPathMapper, trim_listing
29 from .arvtool import ArvadosCommandTool, set_cluster_target
30 from ._version import __version__
31
32 from .perf import Perf
33
34 logger = logging.getLogger('arvados.cwl-runner')
35 metrics = logging.getLogger('arvados.cwl-runner.metrics')
36
37 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
38 sum_res_pars = ("outdirMin", "outdirMax")
39
40 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
41                     submit_runner_ram=0, name=None, merged_map=None,
42                     submit_runner_image=None):
43
44     packed = packed_workflow(arvRunner, tool, merged_map)
45
46     adjustDirObjs(job_order, trim_listing)
47     adjustFileObjs(job_order, trim_anonymous_location)
48     adjustDirObjs(job_order, trim_anonymous_location)
49
50     main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
51     for inp in main["inputs"]:
52         sn = shortname(inp["id"])
53         if sn in job_order:
54             inp["default"] = job_order[sn]
55
56     if not name:
57         name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
58
59     upload_dependencies(arvRunner, name, tool.doc_loader,
60                         packed, tool.tool["id"], False)
61
62     wf_runner_resources = None
63
64     hints = main.get("hints", [])
65     found = False
66     for h in hints:
67         if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
68             wf_runner_resources = h
69             found = True
70             break
71     if not found:
72         wf_runner_resources = {"class": "http://arvados.org/cwl#WorkflowRunnerResources"}
73         hints.append(wf_runner_resources)
74
75     wf_runner_resources["acrContainerImage"] = arvados_jobs_image(arvRunner, submit_runner_image or "arvados/jobs:"+__version__)
76
77     if submit_runner_ram:
78         wf_runner_resources["ramMin"] = submit_runner_ram
79
80     main["hints"] = hints
81
82     body = {
83         "workflow": {
84             "name": name,
85             "description": tool.tool.get("doc", ""),
86             "definition":json.dumps(packed, sort_keys=True, indent=4, separators=(',',': '))
87         }}
88     if project_uuid:
89         body["workflow"]["owner_uuid"] = project_uuid
90
91     if uuid:
92         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
93     else:
94         call = arvRunner.api.workflows().create(body=body)
95     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
96
97 def dedup_reqs(reqs):
98     dedup = {}
99     for r in reversed(reqs):
100         if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
101             dedup[r["class"]] = r
102     return [dedup[r] for r in sorted(dedup.keys())]
103
104 def get_overall_res_req(res_reqs):
105     """Take the overall of a list of ResourceRequirement,
106     i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
107     and the sum of outdirMin, outdirMax."""
108
109     all_res_req = {}
110     exception_msgs = []
111     for a in max_res_pars + sum_res_pars:
112         all_res_req[a] = []
113         for res_req in res_reqs:
114             if a in res_req:
115                 if isinstance(res_req[a], int): # integer check
116                     all_res_req[a].append(res_req[a])
117                 else:
118                     msg = SourceLine(res_req, a).makeError(
119                     "Non-top-level ResourceRequirement in single container cannot have expressions")
120                     exception_msgs.append(msg)
121     if exception_msgs:
122         raise WorkflowException("\n".join(exception_msgs))
123     else:
124         overall_res_req = {}
125         for a in all_res_req:
126             if all_res_req[a]:
127                 if a in max_res_pars:
128                     overall_res_req[a] = max(all_res_req[a])
129                 elif a in sum_res_pars:
130                     overall_res_req[a] = sum(all_res_req[a])
131         if overall_res_req:
132             overall_res_req["class"] = "ResourceRequirement"
133         return cmap(overall_res_req)
134
135 class ArvadosWorkflowStep(WorkflowStep):
136     def __init__(self,
137                  toolpath_object,      # type: Dict[Text, Any]
138                  pos,                  # type: int
139                  loadingContext,       # type: LoadingContext
140                  arvrunner,
141                  *argc,
142                  **argv
143                 ):  # type: (...) -> None
144
145         super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
146         self.tool["class"] = "WorkflowStep"
147         self.arvrunner = arvrunner
148
149     def job(self, joborder, output_callback, runtimeContext):
150         runtimeContext = runtimeContext.copy()
151         runtimeContext.toplevel = True  # Preserve behavior for #13365
152
153         builder = make_builder({shortname(k): v for k,v in viewitems(joborder)}, self.hints, self.requirements,
154                                runtimeContext, self.metadata)
155         runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
156         return super(ArvadosWorkflowStep, self).job(joborder, output_callback, runtimeContext)
157
158
159 class ArvadosWorkflow(Workflow):
160     """Wrap cwltool Workflow to override selected methods."""
161
162     def __init__(self, arvrunner, toolpath_object, loadingContext):
163         self.arvrunner = arvrunner
164         self.wf_pdh = None
165         self.dynamic_resource_req = []
166         self.static_resource_req = []
167         self.wf_reffiles = []
168         self.loadingContext = loadingContext
169         super(ArvadosWorkflow, self).__init__(toolpath_object, loadingContext)
170         self.cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
171
172     def job(self, joborder, output_callback, runtimeContext):
173
174         builder = make_builder(joborder, self.hints, self.requirements, runtimeContext, self.metadata)
175         runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
176
177         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
178         if not req:
179             return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
180
181         # RunInSingleContainer is true
182
183         with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
184             if "id" not in self.tool:
185                 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
186
187         discover_secondary_files(self.arvrunner.fs_access, builder,
188                                  self.tool["inputs"], joborder)
189         normalizeFilesDirs(joborder)
190
191         with Perf(metrics, "subworkflow upload_deps"):
192             upload_dependencies(self.arvrunner,
193                                 os.path.basename(joborder.get("id", "#")),
194                                 self.doc_loader,
195                                 joborder,
196                                 joborder.get("id", "#"),
197                                 False)
198
199             if self.wf_pdh is None:
200                 packed = pack(self.loadingContext, self.tool["id"], loader=self.doc_loader)
201
202                 for p in packed["$graph"]:
203                     if p["id"] == "#main":
204                         p["requirements"] = dedup_reqs(self.requirements)
205                         p["hints"] = dedup_reqs(self.hints)
206
207                 def visit(item):
208                     if "requirements" in item:
209                         item["requirements"] = [i for i in item["requirements"] if i["class"] != "DockerRequirement"]
210                     for t in ("hints", "requirements"):
211                         if t not in item:
212                             continue
213                         for req in item[t]:
214                             if req["class"] == "ResourceRequirement":
215                                 dyn = False
216                                 for k in max_res_pars + sum_res_pars:
217                                     if k in req:
218                                         if isinstance(req[k], basestring):
219                                             if item["id"] == "#main":
220                                                 # only the top-level requirements/hints may contain expressions
221                                                 self.dynamic_resource_req.append(req)
222                                                 dyn = True
223                                                 break
224                                             else:
225                                                 with SourceLine(req, k, WorkflowException):
226                                                     raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
227                                 if not dyn:
228                                     self.static_resource_req.append(req)
229
230                 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
231
232                 if self.static_resource_req:
233                     self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
234
235                 upload_dependencies(self.arvrunner,
236                                     runtimeContext.name,
237                                     self.doc_loader,
238                                     packed,
239                                     self.tool["id"],
240                                     False)
241
242                 # Discover files/directories referenced by the
243                 # workflow (mainly "default" values)
244                 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
245
246
247         if self.dynamic_resource_req:
248             # Evaluate dynamic resource requirements using current builder
249             rs = copy.copy(self.static_resource_req)
250             for dyn_rs in self.dynamic_resource_req:
251                 eval_req = {"class": "ResourceRequirement"}
252                 for a in max_res_pars + sum_res_pars:
253                     if a in dyn_rs:
254                         eval_req[a] = builder.do_eval(dyn_rs[a])
255                 rs.append(eval_req)
256             job_res_reqs = [get_overall_res_req(rs)]
257         else:
258             job_res_reqs = self.static_resource_req
259
260         with Perf(metrics, "subworkflow adjust"):
261             joborder_resolved = copy.deepcopy(joborder)
262             joborder_keepmount = copy.deepcopy(joborder)
263
264             reffiles = []
265             visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
266
267             mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
268                                    "/keep/%s",
269                                    "/keep/%s/%s")
270
271             # For containers API, we need to make sure any extra
272             # referenced files (ie referenced by the workflow but
273             # not in the inputs) are included in the mounts.
274             if self.wf_reffiles:
275                 runtimeContext = runtimeContext.copy()
276                 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
277
278             def keepmount(obj):
279                 remove_redundant_fields(obj)
280                 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
281                     if "location" not in obj:
282                         raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
283                 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
284                     if obj["location"].startswith("keep:"):
285                         obj["location"] = mapper.mapper(obj["location"]).target
286                         if "listing" in obj:
287                             del obj["listing"]
288                     elif obj["location"].startswith("_:"):
289                         del obj["location"]
290                     else:
291                         raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
292
293             visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
294
295             def resolved(obj):
296                 if obj["location"].startswith("keep:"):
297                     obj["location"] = mapper.mapper(obj["location"]).resolved
298
299             visit_class(joborder_resolved, ("File", "Directory"), resolved)
300
301             if self.wf_pdh is None:
302                 adjustFileObjs(packed, keepmount)
303                 adjustDirObjs(packed, keepmount)
304                 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
305
306         self.loadingContext = self.loadingContext.copy()
307         self.loadingContext.metadata = self.loadingContext.metadata.copy()
308         self.loadingContext.metadata["http://commonwl.org/cwltool#original_cwlVersion"] = "v1.0"
309
310         if len(job_res_reqs) == 1:
311             # RAM request needs to be at least 128 MiB or the workflow
312             # runner itself won't run reliably.
313             if job_res_reqs[0].get("ramMin", 1024) < 128:
314                 job_res_reqs[0]["ramMin"] = 128
315
316         arguments = ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl", "cwl.input.yml"]
317         if runtimeContext.debug:
318             arguments.insert(0, '--debug')
319
320         wf_runner = cmap({
321             "class": "CommandLineTool",
322             "baseCommand": "cwltool",
323             "inputs": self.tool["inputs"],
324             "outputs": self.tool["outputs"],
325             "stdout": "cwl.output.json",
326             "requirements": self.requirements+job_res_reqs+[
327                 {"class": "InlineJavascriptRequirement"},
328                 {
329                 "class": "InitialWorkDirRequirement",
330                 "listing": [{
331                         "entryname": "workflow.cwl",
332                         "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
333                     }, {
334                         "entryname": "cwl.input.yml",
335                         "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
336                     }]
337             }],
338             "hints": self.hints,
339             "arguments": arguments,
340             "id": "#"
341         })
342         return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
343
344     def make_workflow_step(self,
345                            toolpath_object,      # type: Dict[Text, Any]
346                            pos,                  # type: int
347                            loadingContext,       # type: LoadingContext
348                            *argc,
349                            **argv
350     ):
351         # (...) -> WorkflowStep
352         return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)