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
18 import ruamel.yaml as yaml
20 from .runner import (upload_dependencies, packed_workflow, upload_workflow_collection,
21 trim_anonymous_location, remove_redundant_fields, discover_secondary_files)
22 from .pathmapper import ArvPathMapper, trim_listing
23 from .arvtool import ArvadosCommandTool
24 from .perf import Perf
26 logger = logging.getLogger('arvados.cwl-runner')
27 metrics = logging.getLogger('arvados.cwl-runner.metrics')
29 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
30 submit_runner_ram=0, name=None):
32 packed = packed_workflow(arvRunner, tool)
34 adjustDirObjs(job_order, trim_listing)
35 adjustFileObjs(job_order, trim_anonymous_location)
36 adjustDirObjs(job_order, trim_anonymous_location)
38 main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
39 for inp in main["inputs"]:
40 sn = shortname(inp["id"])
42 inp["default"] = job_order[sn]
45 name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
47 upload_dependencies(arvRunner, name, tool.doc_loader,
48 packed, tool.tool["id"], False)
50 # TODO nowhere for submit_runner_ram to go.
55 "description": tool.tool.get("doc", ""),
56 "definition":yaml.round_trip_dump(packed)
59 body["workflow"]["owner_uuid"] = project_uuid
62 call = arvRunner.api.workflows().update(uuid=uuid, body=body)
64 call = arvRunner.api.workflows().create(body=body)
65 return call.execute(num_retries=arvRunner.num_retries)["uuid"]
69 for r in reversed(reqs):
70 if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
72 return [dedup[r] for r in sorted(dedup.keys())]
74 class ArvadosWorkflow(Workflow):
75 """Wrap cwltool Workflow to override selected methods."""
77 def __init__(self, arvrunner, toolpath_object, **kwargs):
78 super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
79 self.arvrunner = arvrunner
80 self.work_api = kwargs["work_api"]
83 def job(self, joborder, output_callback, **kwargs):
84 kwargs["work_api"] = self.work_api
85 req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
87 with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
88 if "id" not in self.tool:
89 raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
90 document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
92 discover_secondary_files(self.tool["inputs"], joborder)
94 with Perf(metrics, "subworkflow upload_deps"):
95 upload_dependencies(self.arvrunner,
96 os.path.basename(joborder.get("id", "#")),
99 joborder.get("id", "#"),
102 if self.wf_pdh is None:
103 workflowobj["requirements"] = dedup_reqs(self.requirements)
104 workflowobj["hints"] = dedup_reqs(self.hints)
106 packed = pack(document_loader, workflowobj, uri, self.metadata)
108 upload_dependencies(self.arvrunner,
109 kwargs.get("name", ""),
115 with Perf(metrics, "subworkflow adjust"):
116 joborder_resolved = copy.deepcopy(joborder)
117 joborder_keepmount = copy.deepcopy(joborder)
120 visit_class(joborder_keepmount, ("File", "Directory"), lambda x: reffiles.append(x))
122 mapper = ArvPathMapper(self.arvrunner, reffiles, kwargs["basedir"],
128 remove_redundant_fields(obj)
129 with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
130 if "location" not in obj:
131 raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
132 with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
133 if obj["location"].startswith("keep:"):
134 obj["location"] = mapper.mapper(obj["location"]).target
137 elif obj["location"].startswith("_:"):
140 raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
142 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
145 if obj["location"].startswith("keep:"):
146 obj["location"] = mapper.mapper(obj["location"]).resolved
148 visit_class(joborder_resolved, ("File", "Directory"), resolved)
150 if self.wf_pdh is None:
151 adjustFileObjs(packed, keepmount)
152 adjustDirObjs(packed, keepmount)
153 self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
156 "class": "CommandLineTool",
157 "baseCommand": "cwltool",
158 "inputs": self.tool["inputs"],
159 "outputs": self.tool["outputs"],
160 "stdout": "cwl.output.json",
161 "requirements": workflowobj["requirements"]+[
163 "class": "InitialWorkDirRequirement",
165 "entryname": "workflow.cwl",
168 "location": "keep:%s/workflow.cwl" % self.wf_pdh
171 "entryname": "cwl.input.yml",
172 "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
175 "hints": workflowobj["hints"],
176 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"]
178 kwargs["loader"] = self.doc_loader
179 kwargs["avsc_names"] = self.doc_schema
180 return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder_resolved, output_callback, **kwargs)
182 return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)