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 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
23 import ruamel.yaml as yaml
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__
32 from .perf import Perf
34 logger = logging.getLogger('arvados.cwl-runner')
35 metrics = logging.getLogger('arvados.cwl-runner.metrics')
37 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
38 sum_res_pars = ("outdirMin", "outdirMax")
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):
44 packed = packed_workflow(arvRunner, tool, merged_map)
46 adjustDirObjs(job_order, trim_listing)
47 adjustFileObjs(job_order, trim_anonymous_location)
48 adjustDirObjs(job_order, trim_anonymous_location)
50 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
51 for inp in main["inputs"]:
52 sn = shortname(inp["id"])
54 inp["default"] = job_order[sn]
57 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
59 upload_dependencies(arvRunner, name, tool.doc_loader,
60 packed, tool.tool["id"], False)
62 wf_runner_resources = None
64 hints = main.get("hints", [])
67 if h["class"] == "http://arvados.org/cwl#WorkflowRunnerResources":
68 wf_runner_resources = h
72 wf_runner_resources = {"class": "http://arvados.org/cwl#WorkflowRunnerResources"}
73 hints.append(wf_runner_resources)
75 wf_runner_resources["acrContainerImage"] = arvados_jobs_image(arvRunner, submit_runner_image or "arvados/jobs:"+__version__)
78 wf_runner_resources["ramMin"] = submit_runner_ram
85 "description": tool.tool.get("doc", ""),
86 "definition":json.dumps(packed, sort_keys=True, indent=4, separators=(',',': '))
89 body["workflow"]["owner_uuid"] = project_uuid
92 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
94 call = arvRunner.api.workflows().create(body=body)
95 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
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())]
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."""
111 for a in max_res_pars + sum_res_pars:
113 for res_req in res_reqs:
115 if isinstance(res_req[a], int): # integer check
116 all_res_req[a].append(res_req[a])
118 msg = SourceLine(res_req, a).makeError(
119 "Non-top-level ResourceRequirement in single container cannot have expressions")
120 exception_msgs.append(msg)
122 raise WorkflowException("\n".join(exception_msgs))
125 for a in all_res_req:
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])
132 overall_res_req["class"] = "ResourceRequirement"
133 return cmap(overall_res_req)
135 class ArvadosWorkflowStep(WorkflowStep):
137 toolpath_object, # type: Dict[Text, Any]
139 loadingContext, # type: LoadingContext
143 ): # type: (...) -> None
145 super(ArvadosWorkflowStep, self).__init__(toolpath_object, pos, loadingContext, *argc, **argv)
146 self.tool["class"] = "WorkflowStep"
147 self.arvrunner = arvrunner
149 def job(self, joborder, output_callback, runtimeContext):
150 runtimeContext = runtimeContext.copy()
151 runtimeContext.toplevel = True # Preserve behavior for #13365
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)
159 class ArvadosWorkflow(Workflow):
160 """Wrap cwltool Workflow to override selected methods."""
162 def __init__(self, arvrunner, toolpath_object, loadingContext):
163 self.arvrunner = arvrunner
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")
172 def job(self, joborder, output_callback, runtimeContext):
174 builder = make_builder(joborder, self.hints, self.requirements, runtimeContext, self.metadata)
175 runtimeContext = set_cluster_target(self.tool, self.arvrunner, builder, runtimeContext)
177 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
179 return super(ArvadosWorkflow, self).job(joborder, output_callback, runtimeContext)
181 # RunInSingleContainer is true
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"]))
187 discover_secondary_files(self.arvrunner.fs_access, builder,
188 self.tool["inputs"], joborder)
189 normalizeFilesDirs(joborder)
191 with Perf(metrics, "subworkflow upload_deps"):
192 upload_dependencies(self.arvrunner,
193 os.path.basename(joborder.get("id", "#")),
196 joborder.get("id", "#"),
199 if self.wf_pdh is None:
200 packed = pack(self.loadingContext, self.tool["id"], loader=self.doc_loader)
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)
208 if "requirements" in item:
209 item["requirements"] = [i for i in item["requirements"] if i["class"] != "DockerRequirement"]
210 for t in ("hints", "requirements"):
214 if req["class"] == "ResourceRequirement":
216 for k in max_res_pars + sum_res_pars:
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)
225 with SourceLine(req, k, WorkflowException):
226 raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
228 self.static_resource_req.append(req)
230 visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
232 if self.static_resource_req:
233 self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
235 upload_dependencies(self.arvrunner,
242 # Discover files/directories referenced by the
243 # workflow (mainly "default" values)
244 visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
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:
254 eval_req[a] = builder.do_eval(dyn_rs[a])
256 job_res_reqs = [get_overall_res_req(rs)]
258 job_res_reqs = self.static_resource_req
260 with Perf(metrics, "subworkflow adjust"):
261 joborder_resolved = copy.deepcopy(joborder)
262 joborder_keepmount = copy.deepcopy(joborder)
265 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
267 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, runtimeContext.basedir,
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.
275 runtimeContext = runtimeContext.copy()
276 runtimeContext.extra_reffiles = copy.deepcopy(self.wf_reffiles)
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
288 elif obj["location"].startswith("_:"):
291 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
293 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
296 if obj["location"].startswith("keep:"):
297 obj["location"] = mapper.mapper(obj["location"]).resolved
299 visit_class(joborder_resolved, ("File", "Directory"), resolved)
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)
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"
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
316 arguments = ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl", "cwl.input.yml"]
317 if runtimeContext.debug:
318 arguments.insert(0, '--debug')
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"},
329 "class": "InitialWorkDirRequirement",
331 "entryname": "workflow.cwl",
332 "entry": '$({"class": "File", "location": "keep:%s/workflow.cwl"})' % self.wf_pdh
334 "entryname": "cwl.input.yml",
335 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
339 "arguments": arguments,
342 return ArvadosCommandTool(self.arvrunner, wf_runner, self.loadingContext).job(joborder_resolved, output_callback, runtimeContext)
344 def make_workflow_step(self,
345 toolpath_object, # type: Dict[Text, Any]
347 loadingContext, # type: LoadingContext
351 # (...) -> WorkflowStep
352 return ArvadosWorkflowStep(toolpath_object, pos, loadingContext, self.arvrunner, *argc, **argv)