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