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,
27 from .pathmapper import ArvPathMapper, trim_listing
28 from .arvtool import ArvadosCommandTool, set_cluster_target
30 from .perf import Perf
32 logger = logging.getLogger('arvados.cwl-runner')
33 metrics = logging.getLogger('arvados.cwl-runner.metrics')
35 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
36 sum_res_pars = ("outdirMin", "outdirMax")
38 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
39 submit_runner_ram=0, name=None, merged_map=None):
41 packed = packed_workflow(arvRunner, tool, merged_map)
43 adjustDirObjs(job_order, trim_listing)
44 adjustFileObjs(job_order, trim_anonymous_location)
45 adjustDirObjs(job_order, trim_anonymous_location)
47 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
48 for inp in main["inputs"]:
49 sn = shortname(inp["id"])
51 inp["default"] = job_order[sn]
54 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
56 upload_dependencies(arvRunner, name, tool.doc_loader,
57 packed, tool.tool["id"], False)
60 hints = main.get("hints", [])
63 if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
64 h["ramMin"] = submit_runner_ram
68 hints.append({"class": "http://arvados.org/cwl#WorkflowRunnerResources",
69 "ramMin": submit_runner_ram})
75 "description": tool.tool.get("doc", ""),
76 "definition":json.dumps(packed, sort_keys=True, indent=4, separators=(',',': '))
79 body["workflow"]["owner_uuid"] = project_uuid
82 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
84 call = arvRunner.api.workflows().create(body=body)
85 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
89 for r in reversed(reqs):
90 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
92 return [dedup[r] for r in sorted(dedup.keys())]
94 def get_overall_res_req(res_reqs):
95 """Take the overall of a list of ResourceRequirement,
96 i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
97 and the sum of outdirMin, outdirMax."""
101 for a in max_res_pars + sum_res_pars:
103 for res_req in res_reqs:
105 if isinstance(res_req[a], int): # integer check
106 all_res_req[a].append(res_req[a])
108 msg = SourceLine(res_req, a).makeError(
109 "Non-top-level ResourceRequirement in single container cannot have expressions")
110 exception_msgs.append(msg)
112 raise WorkflowException("\n".join(exception_msgs))
115 for a in all_res_req:
117 if a in max_res_pars:
118 overall_res_req[a] = max(all_res_req[a])
119 elif a in sum_res_pars:
120 overall_res_req[a] = sum(all_res_req[a])
122 overall_res_req["class"] = "ResourceRequirement"
123 return cmap(overall_res_req)
125 class ArvadosWorkflowStep(WorkflowStep):
127 toolpath_object, # type: Dict[Text, Any]
129 loadingContext, # type: LoadingContext
133 ): # type: (...) -> None
135 super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
136 self.tool["class"] = "WorkflowStep"
137 self.arvrunner = arvrunner
139 def job(self, joborder, output_callback, runtimeContext):
140 runtimeContext = runtimeContext.copy()
141 runtimeContext.toplevel = True # Preserve behavior for #13365
143 builder = make_builder({shortname(k): v for k,v in viewitems(joborder)}, self.hints, self.requirements, runtimeContext)
144 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
145 return super(ArvadosWorkflowStep, self).job(joborder, output_callback, runtimeContext)
148 class ArvadosWorkflow(Workflow):
149 """Wrap cwltool Workflow to override selected methods."""
151 def __init__(self, arvrunner, toolpath_object, loadingContext):
152 self.arvrunner = arvrunner
154 self.dynamic_resource_req = []
155 self.static_resource_req = []
156 self.wf_reffiles = []
157 self.loadingContext = loadingContext
158 super(ArvadosWorkflow, self).__init__(toolpath_object, loadingContext)
159 self.cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
161 def job(self, joborder, output_callback, runtimeContext):
163 builder = make_builder(joborder, self.hints, self.requirements, runtimeContext)
164 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
166 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
168 return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
170 # RunInSingleContainer is true
172 with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
173 if "id" not in self.tool:
174 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
175 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
177 discover_secondary_files(self.arvrunner.fs_access, builder,
178 self.tool["inputs"], joborder)
180 with Perf(metrics, "subworkflow upload_deps"):
181 upload_dependencies(self.arvrunner,
182 os.path.basename(joborder.get("id", "#")),
185 joborder.get("id", "#"),
188 if self.wf_pdh is None:
189 workflowobj["requirements"] = dedup_reqs(self.requirements)
190 workflowobj["hints"] = dedup_reqs(self.hints)
192 packed = pack(document_loader, workflowobj, uri, self.metadata)
195 for t in ("hints", "requirements"):
199 if req["class"] == "ResourceRequirement":
201 for k in max_res_pars + sum_res_pars:
203 if isinstance(req[k], basestring):
204 if item["id"] == "#main":
205 # only the top-level requirements/hints may contain expressions
206 self.dynamic_resource_req.append(req)
210 with SourceLine(req, k, WorkflowException):
211 raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
213 self.static_resource_req.append(req)
214 if req["class"] == "DockerRequirement":
215 if "http://arvados.org/cwl#dockerCollectionPDH" in req:
216 del req["http://arvados.org/cwl#dockerCollectionPDH"]
218 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
220 if self.static_resource_req:
221 self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
223 upload_dependencies(self.arvrunner,
230 # Discover files/directories referenced by the
231 # workflow (mainly "default" values)
232 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
235 if self.dynamic_resource_req:
236 # Evaluate dynamic resource requirements using current builder
237 rs = copy.copy(self.static_resource_req)
238 for dyn_rs in self.dynamic_resource_req:
239 eval_req = {"class": "ResourceRequirement"}
240 for a in max_res_pars + sum_res_pars:
242 eval_req[a] = builder.do_eval(dyn_rs[a])
244 job_res_reqs = [get_overall_res_req(rs)]
246 job_res_reqs = self.static_resource_req
248 with Perf(metrics, "subworkflow adjust"):
249 joborder_resolved = copy.deepcopy(joborder)
250 joborder_keepmount = copy.deepcopy(joborder)
253 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
255 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
259 # For containers API, we need to make sure any extra
260 # referenced files (ie referenced by the workflow but
261 # not in the inputs) are included in the mounts.
263 runtimeContext = runtimeContext.copy()
264 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
267 remove_redundant_fields(obj)
268 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
269 if "location" not in obj:
270 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
271 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
272 if obj["location"].startswith("keep:"):
273 obj["location"] = mapper.mapper(obj["location"]).target
276 elif obj["location"].startswith("_:"):
279 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
281 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
284 if obj["location"].startswith("keep:"):
285 obj["location"] = mapper.mapper(obj["location"]).resolved
287 visit_class(joborder_resolved, ("File", "Directory"), resolved)
289 if self.wf_pdh is None:
290 adjustFileObjs(packed, keepmount)
291 adjustDirObjs(packed, keepmount)
292 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
294 self.loadingContext = self.loadingContext.copy()
295 self.loadingContext.metadata = self.loadingContext.metadata.copy()
296 self.loadingContext.metadata["http://commonwl.org/cwltool#original_cwlVersion"] = "v1.0"
299 "class": "CommandLineTool",
300 "baseCommand": "cwltool",
301 "inputs": self.tool["inputs"],
302 "outputs": self.tool["outputs"],
303 "stdout": "cwl.output.json",
304 "requirements": self.requirements+job_res_reqs+[
305 {"class": "InlineJavascriptRequirement"},
307 "class": "InitialWorkDirRequirement",
309 "entryname": "workflow.cwl",
310 "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
312 "entryname": "cwl.input.yml",
313 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
317 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"],
320 return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
322 def make_workflow_step(self,
323 toolpath_object, # type: Dict[Text, Any]
325 loadingContext, # type: LoadingContext
329 # (...) -> WorkflowStep
330 return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)