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