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