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
18 import ruamel.yaml as yaml
20 from .runner import upload_dependencies, packed_workflow, upload_workflow_collection, trim_anonymous_location
21 from .pathmapper import trim_listing
22 from .arvtool import ArvadosCommandTool
23 from .perf import Perf
25 logger = logging.getLogger('arvados.cwl-runner')
26 metrics = logging.getLogger('arvados.cwl-runner.metrics')
28 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
29 submit_runner_ram=0, name=None):
31 packed = packed_workflow(arvRunner, tool)
33 adjustDirObjs(job_order, trim_listing)
34 adjustFileObjs(job_order, trim_anonymous_location)
35 adjustDirObjs(job_order, trim_anonymous_location)
37 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
38 for inp in main["inputs"]:
39 sn = shortname(inp["id"])
41 inp["default"] = job_order[sn]
44 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
46 upload_dependencies(arvRunner, name, tool.doc_loader,
47 packed, tool.tool["id"], False)
49 # TODO nowhere for submit_runner_ram to go.
54 "description": tool.tool.get("doc", ""),
55 "definition":yaml.round_trip_dump(packed)
58 body["workflow"]["owner_uuid"] = project_uuid
61 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
63 call = arvRunner.api.workflows().create(body=body)
64 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
68 for r in reversed(reqs):
69 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
71 return [dedup[r] for r in sorted(dedup.keys())]
73 class ArvadosWorkflow(Workflow):
74 """Wrap cwltool Workflow to override selected methods."""
76 def __init__(self, arvrunner, toolpath_object, **kwargs):
77 super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
78 self.arvrunner = arvrunner
79 self.work_api = kwargs["work_api"]
82 def job(self, joborder, output_callback, **kwargs):
83 kwargs["work_api"] = self.work_api
84 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
86 with SourceLine(self.tool, None, WorkflowException):
87 if "id" not in self.tool:
88 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
89 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
91 with Perf(metrics, "subworkflow upload_deps"):
92 upload_dependencies(self.arvrunner,
93 os.path.basename(joborder.get("id", "#")),
96 joborder.get("id", "#"),
99 if self.wf_pdh is None:
100 workflowobj["requirements"] = dedup_reqs(self.requirements)
101 workflowobj["hints"] = dedup_reqs(self.hints)
103 packed = pack(document_loader, workflowobj, uri, self.metadata)
105 upload_dependencies(self.arvrunner,
106 kwargs.get("name", ""),
112 with Perf(metrics, "subworkflow adjust"):
113 joborder_keepmount = copy.deepcopy(joborder)
116 with SourceLine(obj, None, WorkflowException):
117 if "location" not in obj:
118 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
119 with SourceLine(obj, "location", WorkflowException):
120 if obj["location"].startswith("keep:"):
121 obj["location"] = "/keep/" + obj["location"][5:]
124 elif obj["location"].startswith("_:"):
127 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
129 adjustFileObjs(joborder_keepmount, keepmount)
130 adjustDirObjs(joborder_keepmount, keepmount)
132 if self.wf_pdh is None:
133 adjustFileObjs(packed, keepmount)
134 adjustDirObjs(packed, keepmount)
135 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
138 "class": "CommandLineTool",
139 "baseCommand": "cwltool",
140 "inputs": self.tool["inputs"],
141 "outputs": self.tool["outputs"],
142 "stdout": "cwl.output.json",
143 "requirements": workflowobj["requirements"]+[
145 "class": "InitialWorkDirRequirement",
147 "entryname": "workflow.cwl",
150 "location": "keep:%s/workflow.cwl" % self.wf_pdh
153 "entryname": "cwl.input.yml",
154 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
157 "hints": workflowobj["hints"],
158 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"]
160 kwargs["loader"] = self.doc_loader
161 kwargs["avsc_names"] = self.doc_schema
162 return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder, output_callback, **kwargs)
164 return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)