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