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
15 from cwltool.pack import pack
16 from cwltool.load_tool import fetch_document
17 from cwltool.process import shortname
18 from cwltool.workflow import Workflow, WorkflowException, WorkflowStep
19 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
20 from cwltool.context import LoadingContext
22 import ruamel.yaml as yaml
24 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
25 trim_anonymous_location, remove_redundant_fields, discover_secondary_files)
26 from .pathmapper import ArvPathMapper, trim_listing
27 from .arvtool import ArvadosCommandTool, set_cluster_target, make_builder
28 from .perf import Perf
30 logger = logging.getLogger('arvados.cwl-runner')
31 metrics = logging.getLogger('arvados.cwl-runner.metrics')
33 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
34 sum_res_pars = ("outdirMin", "outdirMax")
36 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
37 submit_runner_ram=0, name=None, merged_map=None):
39 packed = packed_workflow(arvRunner, tool, merged_map)
41 adjustDirObjs(job_order, trim_listing)
42 adjustFileObjs(job_order, trim_anonymous_location)
43 adjustDirObjs(job_order, trim_anonymous_location)
45 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
46 for inp in main["inputs"]:
47 sn = shortname(inp["id"])
49 inp["default"] = job_order[sn]
52 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
54 upload_dependencies(arvRunner, name, tool.doc_loader,
55 packed, tool.tool["id"], False)
58 hints = main.get("hints", [])
61 if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
62 h["ramMin"] = submit_runner_ram
66 hints.append({"class": "http://arvados.org/cwl#WorkflowRunnerResources",
67 "ramMin": submit_runner_ram})
73 "description": tool.tool.get("doc", ""),
74 "definition":json.dumps(packed, sort_keys=True, indent=4, separators=(',',': '))
77 body["workflow"]["owner_uuid"] = project_uuid
80 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
82 call = arvRunner.api.workflows().create(body=body)
83 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
87 for r in reversed(reqs):
88 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
90 return [dedup[r] for r in sorted(dedup.keys())]
92 def get_overall_res_req(res_reqs):
93 """Take the overall of a list of ResourceRequirement,
94 i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
95 and the sum of outdirMin, outdirMax."""
99 for a in max_res_pars + sum_res_pars:
101 for res_req in res_reqs:
103 if isinstance(res_req[a], int): # integer check
104 all_res_req[a].append(res_req[a])
106 msg = SourceLine(res_req, a).makeError(
107 "Non-top-level ResourceRequirement in single container cannot have expressions")
108 exception_msgs.append(msg)
110 raise WorkflowException("\n".join(exception_msgs))
113 for a in all_res_req:
115 if a in max_res_pars:
116 overall_res_req[a] = max(all_res_req[a])
117 elif a in sum_res_pars:
118 overall_res_req[a] = sum(all_res_req[a])
120 overall_res_req["class"] = "ResourceRequirement"
121 return cmap(overall_res_req)
123 class ArvadosWorkflowStep(WorkflowStep):
125 toolpath_object, # type: Dict[Text, Any]
127 loadingContext, # type: LoadingContext
131 ): # type: (...) -> None
133 super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
134 self.tool["class"] = "WorkflowStep"
135 self.arvrunner = arvrunner
137 def job(self, joborder, output_callback, runtimeContext):
138 runtimeContext = runtimeContext.copy()
139 runtimeContext.toplevel = True # Preserve behavior for #13365
141 builder = make_builder({shortname(k): v for k,v in viewitems(joborder)}, self.hints, self.requirements, runtimeContext)
142 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
143 return super(ArvadosWorkflowStep, self).job(joborder, output_callback, runtimeContext)
146 class ArvadosWorkflow(Workflow):
147 """Wrap cwltool Workflow to override selected methods."""
149 def __init__(self, arvrunner, toolpath_object, loadingContext):
150 self.arvrunner = arvrunner
152 self.dynamic_resource_req = []
153 self.static_resource_req = []
154 self.wf_reffiles = []
155 self.loadingContext = loadingContext
156 super(ArvadosWorkflow, self).__init__(toolpath_object, loadingContext)
157 self.cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
159 def job(self, joborder, output_callback, runtimeContext):
161 builder = make_builder(joborder, self.hints, self.requirements, runtimeContext)
162 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
164 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
166 return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
168 # RunInSingleContainer is true
170 with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
171 if "id" not in self.tool:
172 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
173 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
175 discover_secondary_files(self.tool["inputs"], joborder)
177 with Perf(metrics, "subworkflow upload_deps"):
178 upload_dependencies(self.arvrunner,
179 os.path.basename(joborder.get("id", "#")),
182 joborder.get("id", "#"),
185 if self.wf_pdh is None:
186 workflowobj["requirements"] = dedup_reqs(self.requirements)
187 workflowobj["hints"] = dedup_reqs(self.hints)
189 packed = pack(document_loader, workflowobj, uri, self.metadata)
192 for t in ("hints", "requirements"):
196 if req["class"] == "ResourceRequirement":
198 for k in max_res_pars + sum_res_pars:
200 if isinstance(req[k], basestring):
201 if item["id"] == "#main":
202 # only the top-level requirements/hints may contain expressions
203 self.dynamic_resource_req.append(req)
207 with SourceLine(req, k, WorkflowException):
208 raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
210 self.static_resource_req.append(req)
211 if req["class"] == "DockerRequirement":
212 if "http://arvados.org/cwl#dockerCollectionPDH" in req:
213 del req["http://arvados.org/cwl#dockerCollectionPDH"]
215 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
217 if self.static_resource_req:
218 self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
220 upload_dependencies(self.arvrunner,
227 # Discover files/directories referenced by the
228 # workflow (mainly "default" values)
229 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
232 if self.dynamic_resource_req:
233 # Evaluate dynamic resource requirements using current builder
234 rs = copy.copy(self.static_resource_req)
235 for dyn_rs in self.dynamic_resource_req:
236 eval_req = {"class": "ResourceRequirement"}
237 for a in max_res_pars + sum_res_pars:
239 eval_req[a] = builder.do_eval(dyn_rs[a])
241 job_res_reqs = [get_overall_res_req(rs)]
243 job_res_reqs = self.static_resource_req
245 with Perf(metrics, "subworkflow adjust"):
246 joborder_resolved = copy.deepcopy(joborder)
247 joborder_keepmount = copy.deepcopy(joborder)
250 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
252 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
256 # For containers API, we need to make sure any extra
257 # referenced files (ie referenced by the workflow but
258 # not in the inputs) are included in the mounts.
260 runtimeContext = runtimeContext.copy()
261 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
264 remove_redundant_fields(obj)
265 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
266 if "location" not in obj:
267 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
268 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
269 if obj["location"].startswith("keep:"):
270 obj["location"] = mapper.mapper(obj["location"]).target
273 elif obj["location"].startswith("_:"):
276 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
278 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
281 if obj["location"].startswith("keep:"):
282 obj["location"] = mapper.mapper(obj["location"]).resolved
284 visit_class(joborder_resolved, ("File", "Directory"), resolved)
286 if self.wf_pdh is None:
287 adjustFileObjs(packed, keepmount)
288 adjustDirObjs(packed, keepmount)
289 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
292 "class": "CommandLineTool",
293 "baseCommand": "cwltool",
294 "inputs": self.tool["inputs"],
295 "outputs": self.tool["outputs"],
296 "stdout": "cwl.output.json",
297 "requirements": self.requirements+job_res_reqs+[
298 {"class": "InlineJavascriptRequirement"},
300 "class": "InitialWorkDirRequirement",
302 "entryname": "workflow.cwl",
303 "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
305 "entryname": "cwl.input.yml",
306 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
310 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"],
313 return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
315 def make_workflow_step(self,
316 toolpath_object, # type: Dict[Text, Any]
318 loadingContext, # type: LoadingContext
322 # (...) -> WorkflowStep
323 return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)