1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
10 from schema_salad.sourceline import SourceLine, cmap
12 from cwltool.pack import pack
13 from cwltool.load_tool import fetch_document
14 from cwltool.process import shortname
15 from cwltool.workflow import Workflow, WorkflowException, WorkflowStep
16 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
17 from cwltool.builder import Builder
18 from cwltool.context import LoadingContext
20 import ruamel.yaml as yaml
22 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
23 trim_anonymous_location, remove_redundant_fields, discover_secondary_files)
24 from .pathmapper import ArvPathMapper, trim_listing
25 from .arvtool import ArvadosCommandTool, set_cluster_target
26 from .perf import Perf
28 logger = logging.getLogger('arvados.cwl-runner')
29 metrics = logging.getLogger('arvados.cwl-runner.metrics')
31 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
32 sum_res_pars = ("outdirMin", "outdirMax")
34 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
35 submit_runner_ram=0, name=None, merged_map=None):
37 packed = packed_workflow(arvRunner, tool, merged_map)
39 adjustDirObjs(job_order, trim_listing)
40 adjustFileObjs(job_order, trim_anonymous_location)
41 adjustDirObjs(job_order, trim_anonymous_location)
43 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
44 for inp in main["inputs"]:
45 sn = shortname(inp["id"])
47 inp["default"] = job_order[sn]
50 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
52 upload_dependencies(arvRunner, name, tool.doc_loader,
53 packed, tool.tool["id"], False)
56 hints = main.get("hints", [])
59 if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
60 h["ramMin"] = submit_runner_ram
64 hints.append({"class": "http://arvados.org/cwl#WorkflowRunnerResources",
65 "ramMin": submit_runner_ram})
71 "description": tool.tool.get("doc", ""),
72 "definition":json.dumps(packed, sort_keys=True, indent=4, separators=(',',': '))
75 body["workflow"]["owner_uuid"] = project_uuid
78 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
80 call = arvRunner.api.workflows().create(body=body)
81 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
85 for r in reversed(reqs):
86 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
88 return [dedup[r] for r in sorted(dedup.keys())]
90 def get_overall_res_req(res_reqs):
91 """Take the overall of a list of ResourceRequirement,
92 i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
93 and the sum of outdirMin, outdirMax."""
97 for a in max_res_pars + sum_res_pars:
99 for res_req in res_reqs:
101 if isinstance(res_req[a], int): # integer check
102 all_res_req[a].append(res_req[a])
104 msg = SourceLine(res_req, a).makeError(
105 "Non-top-level ResourceRequirement in single container cannot have expressions")
106 exception_msgs.append(msg)
108 raise WorkflowException("\n".join(exception_msgs))
111 for a in all_res_req:
113 if a in max_res_pars:
114 overall_res_req[a] = max(all_res_req[a])
115 elif a in sum_res_pars:
116 overall_res_req[a] = sum(all_res_req[a])
118 overall_res_req["class"] = "ResourceRequirement"
119 return cmap(overall_res_req)
121 class ArvadosWorkflowStep(WorkflowStep):
123 toolpath_object, # type: Dict[Text, Any]
125 loadingContext, # type: LoadingContext
129 ): # type: (...) -> None
131 super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
132 self.tool["class"] = "WorkflowStep"
133 self.arvrunner = arvrunner
135 def job(self, joborder, output_callback, runtimeContext):
136 runtimeContext = runtimeContext.copy()
137 runtimeContext.toplevel = True # Preserve behavior for #13365
139 builder = self._init_job({shortname(k): v for k,v in joborder.items()}, runtimeContext)
140 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
141 return super(ArvadosWorkflowStep, self).job(joborder, output_callback, runtimeContext)
144 class ArvadosWorkflow(Workflow):
145 """Wrap cwltool Workflow to override selected methods."""
147 def __init__(self, arvrunner, toolpath_object, loadingContext):
148 self.arvrunner = arvrunner
150 self.dynamic_resource_req = []
151 self.static_resource_req = []
152 self.wf_reffiles = []
153 self.loadingContext = loadingContext
154 super(ArvadosWorkflow, self).__init__(toolpath_object, loadingContext)
155 self.cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
157 def job(self, joborder, output_callback, runtimeContext):
159 builder = self._init_job(joborder, runtimeContext)
160 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
162 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
164 return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
166 # RunInSingleContainer is true
168 with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
169 if "id" not in self.tool:
170 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
171 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
173 discover_secondary_files(self.tool["inputs"], joborder)
175 with Perf(metrics, "subworkflow upload_deps"):
176 upload_dependencies(self.arvrunner,
177 os.path.basename(joborder.get("id", "#")),
180 joborder.get("id", "#"),
183 if self.wf_pdh is None:
184 workflowobj["requirements"] = dedup_reqs(self.requirements)
185 workflowobj["hints"] = dedup_reqs(self.hints)
187 packed = pack(document_loader, workflowobj, uri, self.metadata)
190 for t in ("hints", "requirements"):
194 if req["class"] == "ResourceRequirement":
196 for k in max_res_pars + sum_res_pars:
198 if isinstance(req[k], basestring):
199 if item["id"] == "#main":
200 # only the top-level requirements/hints may contain expressions
201 self.dynamic_resource_req.append(req)
205 with SourceLine(req, k, WorkflowException):
206 raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
208 self.static_resource_req.append(req)
210 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
212 if self.static_resource_req:
213 self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
215 upload_dependencies(self.arvrunner,
222 # Discover files/directories referenced by the
223 # workflow (mainly "default" values)
224 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
227 if self.dynamic_resource_req:
228 # Evaluate dynamic resource requirements using current builder
229 rs = copy.copy(self.static_resource_req)
230 for dyn_rs in self.dynamic_resource_req:
231 eval_req = {"class": "ResourceRequirement"}
232 for a in max_res_pars + sum_res_pars:
234 eval_req[a] = builder.do_eval(dyn_rs[a])
236 job_res_reqs = [get_overall_res_req(rs)]
238 job_res_reqs = self.static_resource_req
240 with Perf(metrics, "subworkflow adjust"):
241 joborder_resolved = copy.deepcopy(joborder)
242 joborder_keepmount = copy.deepcopy(joborder)
245 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
247 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
251 # For containers API, we need to make sure any extra
252 # referenced files (ie referenced by the workflow but
253 # not in the inputs) are included in the mounts.
255 runtimeContext = runtimeContext.copy()
256 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
259 remove_redundant_fields(obj)
260 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
261 if "location" not in obj:
262 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
263 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
264 if obj["location"].startswith("keep:"):
265 obj["location"] = mapper.mapper(obj["location"]).target
268 elif obj["location"].startswith("_:"):
271 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
273 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
276 if obj["location"].startswith("keep:"):
277 obj["location"] = mapper.mapper(obj["location"]).resolved
279 visit_class(joborder_resolved, ("File", "Directory"), resolved)
281 if self.wf_pdh is None:
282 adjustFileObjs(packed, keepmount)
283 adjustDirObjs(packed, keepmount)
284 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
287 "class": "CommandLineTool",
288 "baseCommand": "cwltool",
289 "inputs": self.tool["inputs"],
290 "outputs": self.tool["outputs"],
291 "stdout": "cwl.output.json",
292 "requirements": self.requirements+job_res_reqs+[
293 {"class": "InlineJavascriptRequirement"},
295 "class": "InitialWorkDirRequirement",
297 "entryname": "workflow.cwl",
298 "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
300 "entryname": "cwl.input.yml",
301 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
305 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"],
308 return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
310 def make_workflow_step(self,
311 toolpath_object, # type: Dict[Text, Any]
313 loadingContext, # type: LoadingContext
317 # (...) -> WorkflowStep
318 return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)