Merge branch '13330-collection-save'
[arvados.git] / sdk / cwl / arvados_cwl / arvworkflow.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import os
6 import json
7 import copy
8 import logging
9
10 from schema_salad.sourceline import SourceLine, cmap
11
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
18
19 import ruamel.yaml as yaml
20
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
26
27 logger = logging.getLogger('arvados.cwl-runner')
28 metrics = logging.getLogger('arvados.cwl-runner.metrics')
29
30 max_res_pars = ("coresMin", "coresMax", "ramMin", "ramMax", "tmpdirMin", "tmpdirMax")
31 sum_res_pars = ("outdirMin", "outdirMax")
32
33 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
34                     submit_runner_ram=0, name=None, merged_map=None):
35
36     packed = packed_workflow(arvRunner, tool, merged_map)
37
38     adjustDirObjs(job_order, trim_listing)
39     adjustFileObjs(job_order, trim_anonymous_location)
40     adjustDirObjs(job_order, trim_anonymous_location)
41
42     main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
43     for inp in main["inputs"]:
44         sn = shortname(inp["id"])
45         if sn in job_order:
46             inp["default"] = job_order[sn]
47
48     if not name:
49         name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
50
51     upload_dependencies(arvRunner, name, tool.doc_loader,
52                         packed, tool.tool["id"], False)
53
54     # TODO nowhere for submit_runner_ram to go.
55
56     body = {
57         "workflow": {
58             "name": name,
59             "description": tool.tool.get("doc", ""),
60             "definition":yaml.round_trip_dump(packed)
61         }}
62     if project_uuid:
63         body["workflow"]["owner_uuid"] = project_uuid
64
65     if uuid:
66         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
67     else:
68         call = arvRunner.api.workflows().create(body=body)
69     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
70
71 def dedup_reqs(reqs):
72     dedup = {}
73     for r in reversed(reqs):
74         if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
75             dedup[r["class"]] = r
76     return [dedup[r] for r in sorted(dedup.keys())]
77
78 def get_overall_res_req(res_reqs):
79     """Take the overall of a list of ResourceRequirement,
80     i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax
81     and the sum of outdirMin, outdirMax."""
82
83     all_res_req = {}
84     exception_msgs = []
85     for a in max_res_pars + sum_res_pars:
86         all_res_req[a] = []
87         for res_req in res_reqs:
88             if a in res_req:
89                 if isinstance(res_req[a], int): # integer check
90                     all_res_req[a].append(res_req[a])
91                 else:
92                     msg = SourceLine(res_req, a).makeError(
93                     "Non-top-level ResourceRequirement in single container cannot have expressions")
94                     exception_msgs.append(msg)
95     if exception_msgs:
96         raise WorkflowException("\n".join(exception_msgs))
97     else:
98         overall_res_req = {}
99         for a in all_res_req:
100             if all_res_req[a]:
101                 if a in max_res_pars:
102                     overall_res_req[a] = max(all_res_req[a])
103                 elif a in sum_res_pars:
104                     overall_res_req[a] = sum(all_res_req[a])
105         if overall_res_req:
106             overall_res_req["class"] = "ResourceRequirement"
107         return cmap(overall_res_req)
108
109 class ArvadosWorkflow(Workflow):
110     """Wrap cwltool Workflow to override selected methods."""
111
112     def __init__(self, arvrunner, toolpath_object, **kwargs):
113         super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
114         self.arvrunner = arvrunner
115         self.work_api = kwargs["work_api"]
116         self.wf_pdh = None
117         self.dynamic_resource_req = []
118         self.static_resource_req = []
119         self.wf_reffiles = []
120
121     def job(self, joborder, output_callback, **kwargs):
122         kwargs["work_api"] = self.work_api
123         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
124         if req:
125             with SourceLine(self.tool, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
126                 if "id" not in self.tool:
127                     raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
128             document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
129
130             discover_secondary_files(self.tool["inputs"], joborder)
131
132             with Perf(metrics, "subworkflow upload_deps"):
133                 upload_dependencies(self.arvrunner,
134                                     os.path.basename(joborder.get("id", "#")),
135                                     document_loader,
136                                     joborder,
137                                     joborder.get("id", "#"),
138                                     False)
139
140                 if self.wf_pdh is None:
141                     workflowobj["requirements"] = dedup_reqs(self.requirements)
142                     workflowobj["hints"] = dedup_reqs(self.hints)
143
144                     packed = pack(document_loader, workflowobj, uri, self.metadata)
145
146                     builder = Builder()
147                     builder.job = joborder
148                     builder.requirements = workflowobj["requirements"]
149                     builder.hints = workflowobj["hints"]
150                     builder.resources = {}
151
152                     def visit(item):
153                         for t in ("hints", "requirements"):
154                             if t not in item:
155                                 continue
156                             for req in item[t]:
157                                 if req["class"] == "ResourceRequirement":
158                                     dyn = False
159                                     for k in max_res_pars + sum_res_pars:
160                                         if k in req:
161                                             if isinstance(req[k], basestring):
162                                                 if item["id"] == "#main":
163                                                     # only the top-level requirements/hints may contain expressions
164                                                     self.dynamic_resource_req.append(req)
165                                                     dyn = True
166                                                     break
167                                                 else:
168                                                     with SourceLine(req, k, WorkflowException):
169                                                         raise WorkflowException("Non-top-level ResourceRequirement in single container cannot have expressions")
170                                     if not dyn:
171                                         self.static_resource_req.append(req)
172
173                     visit_class(packed["$graph"], ("Workflow", "CommandLineTool"), visit)
174
175                     if self.static_resource_req:
176                         self.static_resource_req = [get_overall_res_req(self.static_resource_req)]
177
178                     upload_dependencies(self.arvrunner,
179                                         kwargs.get("name", ""),
180                                         document_loader,
181                                         packed,
182                                         uri,
183                                         False)
184
185                     # Discover files/directories referenced by the
186                     # workflow (mainly "default" values)
187                     visit_class(packed, ("File", "Directory"), self.wf_reffiles.append)
188
189
190             if self.dynamic_resource_req:
191                 builder = Builder()
192                 builder.job = joborder
193                 builder.requirements = self.requirements
194                 builder.hints = self.hints
195                 builder.resources = {}
196
197                 # Evaluate dynamic resource requirements using current builder
198                 rs = copy.copy(self.static_resource_req)
199                 for dyn_rs in self.dynamic_resource_req:
200                     eval_req = {"class": "ResourceRequirement"}
201                     for a in max_res_pars + sum_res_pars:
202                         if a in dyn_rs:
203                             eval_req[a] = builder.do_eval(dyn_rs[a])
204                     rs.append(eval_req)
205                 job_res_reqs = [get_overall_res_req(rs)]
206             else:
207                 job_res_reqs = self.static_resource_req
208
209             with Perf(metrics, "subworkflow adjust"):
210                 joborder_resolved = copy.deepcopy(joborder)
211                 joborder_keepmount = copy.deepcopy(joborder)
212
213                 reffiles = []
214                 visit_class(joborder_keepmount, ("File", "Directory"), reffiles.append)
215
216                 mapper = ArvPathMapper(self.arvrunner, reffiles+self.wf_reffiles, kwargs["basedir"],
217                                  "/keep/%s",
218                                  "/keep/%s/%s",
219                                  **kwargs)
220
221                 # For containers API, we need to make sure any extra
222                 # referenced files (ie referenced by the workflow but
223                 # not in the inputs) are included in the mounts.
224                 kwargs["extra_reffiles"] = copy.deepcopy(self.wf_reffiles)
225
226                 def keepmount(obj):
227                     remove_redundant_fields(obj)
228                     with SourceLine(obj, None, WorkflowException, logger.isEnabledFor(logging.DEBUG)):
229                         if "location" not in obj:
230                             raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
231                     with SourceLine(obj, "location", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
232                         if obj["location"].startswith("keep:"):
233                             obj["location"] = mapper.mapper(obj["location"]).target
234                             if "listing" in obj:
235                                 del obj["listing"]
236                         elif obj["location"].startswith("_:"):
237                             del obj["location"]
238                         else:
239                             raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
240
241                 visit_class(joborder_keepmount, ("File", "Directory"), keepmount)
242
243                 def resolved(obj):
244                     if obj["location"].startswith("keep:"):
245                         obj["location"] = mapper.mapper(obj["location"]).resolved
246
247                 visit_class(joborder_resolved, ("File", "Directory"), resolved)
248
249                 if self.wf_pdh is None:
250                     adjustFileObjs(packed, keepmount)
251                     adjustDirObjs(packed, keepmount)
252                     self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
253
254             wf_runner = cmap({
255                 "class": "CommandLineTool",
256                 "baseCommand": "cwltool",
257                 "inputs": self.tool["inputs"],
258                 "outputs": self.tool["outputs"],
259                 "stdout": "cwl.output.json",
260                 "requirements": self.requirements+job_res_reqs+[
261                     {
262                     "class": "InitialWorkDirRequirement",
263                     "listing": [{
264                             "entryname": "workflow.cwl",
265                             "entry": {
266                                 "class": "File",
267                                 "location": "keep:%s/workflow.cwl" % self.wf_pdh
268                             }
269                         }, {
270                             "entryname": "cwl.input.yml",
271                             "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
272                         }]
273                 }],
274                 "hints": self.hints,
275                 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"],
276                 "id": "#"
277             })
278             kwargs["loader"] = self.doc_loader
279             kwargs["avsc_names"] = self.doc_schema
280             kwargs["metadata"]  = self.metadata
281             return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder_resolved, output_callback, **kwargs)
282         else:
283             return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)