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