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