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