1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 from past.builtins import basestring
6 from future.utils import viewitems
13 from schema_salad.sourceline import SourceLine, cmap
14 import schema_salad.ref_resolver
16 import arvados.collection
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
25 import ruamel.yaml as yaml
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__
34 from .perf import Perf
36 logger = logging.getLogger('arvados.cwl-runner')
37 metrics = logging.getLogger('arvados.cwl-runner.metrics')
39 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
40 sum_res_pars = ("outdirMin", "outdirMax")
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)
46 with col.open("workflow.json", "wt") as f:
47 json.dump(packed, f, sort_keys=True, indent=4, separators=(',',': '))
49 pdh = col.portable_data_hash()
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"))
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)
59 # now construct the wrapper
62 "id": "#main/" + toolname,
65 "run": "keep:%s/workflow.json#main" % pdh,
70 for i in main["inputs"]:
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
78 for f in ("type", "label", "secondaryFiles", "streamable",
79 "doc", "id", "format", "loadContents",
80 "loadListing", "default"):
93 for i in main["inputs"]:
95 "id": "#main/step/%s" % shortname(i["id"]),
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"]),
105 wrapper["requirements"] = [{"class": "SubworkflowFeatureRequirement"}]
107 if main.get("requirements"):
108 wrapper["requirements"].extend(main["requirements"])
109 if main.get("hints"):
110 wrapper["hints"] = main["hints"]
112 doc = {"cwlVersion": "v1.2", "$graph": [wrapper]}
118 return json.dumps(doc, sort_keys=True, indent=4, separators=(',',': '))
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,
126 packed = packed_workflow(arvRunner, tool, merged_map, runtimeContext, git_info)
128 adjustDirObjs(job_order, trim_listing)
129 adjustFileObjs(job_order, trim_anonymous_location)
130 adjustDirObjs(job_order, trim_anonymous_location)
132 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
133 for inp in main["inputs"]:
134 sn = shortname(inp["id"])
136 inp["default"] = job_order[sn]
139 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
141 upload_dependencies(arvRunner, name, tool.doc_loader,
142 packed, tool.tool["id"], False,
145 wf_runner_resources = None
147 hints = main.get("hints", [])
150 if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
151 wf_runner_resources = h
155 wf_runner_resources = {"class": "http://arvados.org/cwl#WorkflowRunnerResources"}
156 hints.append(wf_runner_resources)
158 wf_runner_resources["acrContainerImage"] = arvados_jobs_image(arvRunner,
159 submit_runner_image or "arvados/jobs:"+__version__,
162 if submit_runner_ram:
163 wf_runner_resources["ramMin"] = submit_runner_ram
165 main["hints"] = hints
167 wrapper = make_wrapper_workflow(arvRunner, main, packed, project_uuid, name, git_info, tool)
172 "description": tool.tool.get("doc", ""),
173 "definition": wrapper
176 body["workflow"]["owner_uuid"] = project_uuid
179 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
181 call = arvRunner.api.workflows().create(body=body)
182 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
184 def dedup_reqs(reqs):
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())]
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."""
198 for a in max_res_pars + sum_res_pars:
200 for res_req in res_reqs:
202 if isinstance(res_req[a], int): # integer check
203 all_res_req[a].append(res_req[a])
205 msg = SourceLine(res_req, a).makeError(
206 "Non-top-level ResourceRequirement in single container cannot have expressions")
207 exception_msgs.append(msg)
209 raise WorkflowException("\n".join(exception_msgs))
212 for a in all_res_req:
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])
219 overall_res_req["class"] = "ResourceRequirement"
220 return cmap(overall_res_req)
222 class ArvadosWorkflowStep(WorkflowStep):
224 toolpath_object, # type: Dict[Text, Any]
226 loadingContext, # type: LoadingContext
230 ): # type: (...) -> None
232 if arvrunner.fast_submit:
233 self.tool = toolpath_object
234 self.tool["inputs"] = []
235 self.tool["outputs"] = []
237 super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
238 self.tool["class"] = "WorkflowStep"
239 self.arvrunner = arvrunner
241 def job(self, joborder, output_callback, runtimeContext):
242 runtimeContext = runtimeContext.copy()
243 runtimeContext.toplevel = True # Preserve behavior for #13365
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)
251 class ArvadosWorkflow(Workflow):
252 """Wrap cwltool Workflow to override selected methods."""
254 def __init__(self, arvrunner, toolpath_object, loadingContext):
255 self.arvrunner = arvrunner
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")
264 def job(self, joborder, output_callback, runtimeContext):
266 builder = make_builder(joborder, self.hints, self.requirements, runtimeContext, self.metadata)
267 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
269 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
271 return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
273 # RunInSingleContainer is true
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"]))
279 discover_secondary_files(self.arvrunner.fs_access, builder,
280 self.tool["inputs"], joborder)
281 normalizeFilesDirs(joborder)
283 with Perf(metrics, "subworkflow upload_deps"):
284 upload_dependencies(self.arvrunner,
285 os.path.basename(joborder.get("id", "#")),
288 joborder.get("id", "#"),
292 if self.wf_pdh is None:
293 packed = pack(self.loadingContext, self.tool["id"], loader=self.doc_loader)
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)
301 if "requirements" in item:
302 item["requirements"] = [i for i in item["requirements"] if i["class"] != "DockerRequirement"]
303 for t in ("hints", "requirements"):
307 if req["class"] == "ResourceRequirement":
309 for k in max_res_pars + sum_res_pars:
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)
318 with SourceLine(req, k, WorkflowException):
319 raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
321 self.static_resource_req.append(req)
323 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
325 if self.static_resource_req:
326 self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
328 upload_dependencies(self.arvrunner,
336 # Discover files/directories referenced by the
337 # workflow (mainly "default" values)
338 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
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:
348 eval_req[a] = builder.do_eval(dyn_rs[a])
350 job_res_reqs = [get_overall_res_req(rs)]
352 job_res_reqs = self.static_resource_req
354 with Perf(metrics, "subworkflow adjust"):
355 joborder_resolved = copy.deepcopy(joborder)
356 joborder_keepmount = copy.deepcopy(joborder)
359 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
361 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
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.
369 runtimeContext = runtimeContext.copy()
370 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
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
382 elif obj["location"].startswith("_:"):
385 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
387 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
390 if obj["location"].startswith("keep:"):
391 obj["location"] = mapper.mapper(obj["location"]).resolved
393 visit_class(joborder_resolved, ("File", "Directory"), resolved)
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)
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"
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
410 arguments = ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl", "cwl.input.yml"]
411 if runtimeContext.debug:
412 arguments.insert(0, '--debug')
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"},
423 "class": "InitialWorkDirRequirement",
425 "entryname": "workflow.cwl",
426 "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
428 "entryname": "cwl.input.yml",
429 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
433 "arguments": arguments,
436 return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
438 def make_workflow_step(self,
439 toolpath_object, # type: Dict[Text, Any]
441 loadingContext, # type: LoadingContext
445 # (...) -> WorkflowStep
446 return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)