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
16 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
17 from cwltool.builder import Builder
19 import ruamel.yaml as yaml
21 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
22 trim_anonymous_location, remove_redundant_fields, discover_secondary_files)
23 from .pathmapper import ArvPathMapper, trim_listing
24 from .arvtool import ArvadosCommandTool
25 from .perf import Perf
27 logger = logging.getLogger('arvados.cwl-runner')
28 metrics = logging.getLogger('arvados.cwl-runner.metrics')
30 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
31 submit_runner_ram=0, name=None, merged_map=None):
33 packed = packed_workflow(arvRunner, tool, merged_map)
35 adjustDirObjs(job_order, trim_listing)
36 adjustFileObjs(job_order, trim_anonymous_location)
37 adjustDirObjs(job_order, trim_anonymous_location)
39 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
40 for inp in main["inputs"]:
41 sn = shortname(inp["id"])
43 inp["default"] = job_order[sn]
46 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
48 upload_dependencies(arvRunner, name, tool.doc_loader,
49 packed, tool.tool["id"], False)
51 # TODO nowhere for submit_runner_ram to go.
56 "description": tool.tool.get("doc", ""),
57 "definition":yaml.round_trip_dump(packed)
60 body["workflow"]["owner_uuid"] = project_uuid
63 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
65 call = arvRunner.api.workflows().create(body=body)
66 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
70 for r in reversed(reqs):
71 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
73 return [dedup[r] for r in sorted(dedup.keys())]
75 def get_max_res_req(res_reqs):
76 """Take the max of a list of ResourceRequirement."""
80 for a in ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax", "outdirMin", "outdirMax"):
82 for res_req in res_reqs:
84 if isinstance(res_req[a], int): # integer check
85 total_res_req[a].append(res_req[a])
87 msg = SourceLine(res_req).makeError(
88 "Non-top-level ResourceRequirement in single container cannot have expressions")
89 exception_msgs.append(msg)
91 raise WorkflowException("\n".join(exception_msgs))
94 for a in total_res_req:
96 max_res_req[a] = max(total_res_req[a])
98 max_res_req["class"] = "ResourceRequirement"
99 return cmap(max_res_req)
101 class ArvadosWorkflow(Workflow):
102 """Wrap cwltool Workflow to override selected methods."""
104 def __init__(self, arvrunner, toolpath_object, **kwargs):
105 super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
106 self.arvrunner = arvrunner
107 self.work_api = kwargs["work_api"]
110 def job(self, joborder, output_callback, **kwargs):
111 kwargs["work_api"] = self.work_api
112 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
114 with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
115 if "id" not in self.tool:
116 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
117 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
119 discover_secondary_files(self.tool["inputs"], joborder)
121 with Perf(metrics, "subworkflow upload_deps"):
122 upload_dependencies(self.arvrunner,
123 os.path.basename(joborder.get("id", "#")),
126 joborder.get("id", "#"),
129 if self.wf_pdh is None:
130 workflowobj["requirements"] = dedup_reqs(self.requirements)
131 workflowobj["hints"] = dedup_reqs(self.hints)
133 packed = pack(document_loader, workflowobj, uri, self.metadata)
136 builder.job = joborder
137 builder.requirements = self.requirements
138 builder.hints = self.hints
139 builder.resources = {}
141 res_reqs = {"requirements": [], "hints": []}
142 for t in ("requirements", "hints"):
143 for item in packed["$graph"]:
145 if item["id"] == "#main": # evaluate potential expressions in the top-level requirements/hints
147 if req["class"] == "ResourceRequirement":
148 eval_req = {"class": "ResourceRequirement"}
149 for a in ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax", "outdirMin", "outdirMax"):
151 eval_req[a] = builder.do_eval(req[a])
152 res_reqs[t].append(eval_req)
155 if req["class"] == "ResourceRequirement":
156 res_reqs[t].append(req)
157 max_res_req = {"requirements": get_max_res_req(res_reqs["requirements"]),
158 "hints": get_max_res_req(res_reqs["hints"])}
160 new_spec = {"requirements": self.requirements, "hints": self.hints}
161 for t in ("requirements", "hints"):
162 for req in new_spec[t]:
163 if req["class"] == "ResourceRequirement":
164 new_spec[t].remove(req)
166 new_spec[t].append(max_res_req[t])
168 upload_dependencies(self.arvrunner,
169 kwargs.get("name", ""),
175 with Perf(metrics, "subworkflow adjust"):
176 joborder_resolved = copy.deepcopy(joborder)
177 joborder_keepmount = copy.deepcopy(joborder)
180 visit_class(joborder_keepmount, ("File", "Directory"), lambda x: reffiles.append(x))
182 mapper = ArvPathMapper(self.arvrunner, reffiles, kwargs["basedir"],
188 remove_redundant_fields(obj)
189 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
190 if "location" not in obj:
191 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
192 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
193 if obj["location"].startswith("keep:"):
194 obj["location"] = mapper.mapper(obj["location"]).target
197 elif obj["location"].startswith("_:"):
200 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
202 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
205 if obj["location"].startswith("keep:"):
206 obj["location"] = mapper.mapper(obj["location"]).resolved
208 visit_class(joborder_resolved, ("File", "Directory"), resolved)
210 if self.wf_pdh is None:
211 adjustFileObjs(packed, keepmount)
212 adjustDirObjs(packed, keepmount)
213 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
216 "class": "CommandLineTool",
217 "baseCommand": "cwltool",
218 "inputs": self.tool["inputs"],
219 "outputs": self.tool["outputs"],
220 "stdout": "cwl.output.json",
221 "requirements": new_spec["requirements"]+[
223 "class": "InitialWorkDirRequirement",
225 "entryname": "workflow.cwl",
228 "location": "keep:%s/workflow.cwl" % self.wf_pdh
231 "entryname": "cwl.input.yml",
232 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
235 "hints": new_spec["hints"],
236 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"],
239 kwargs["loader"] = self.doc_loader
240 kwargs["avsc_names"] = self.doc_schema
241 return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder_resolved, output_callback, **kwargs)
243 return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)