8937: Merge branch 'master' into 8937-arvput-cached-tokens
[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
17
18 import ruamel.yaml as yaml
19
20 from .runner import upload_dependencies, packed_workflow, upload_workflow_collection, trim_anonymous_location
21 from .pathmapper import trim_listing
22 from .arvtool import ArvadosCommandTool
23 from .perf import Perf
24
25 logger = logging.getLogger('arvados.cwl-runner')
26 metrics = logging.getLogger('arvados.cwl-runner.metrics')
27
28 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None,
29                     submit_runner_ram=0, name=None):
30
31     packed = packed_workflow(arvRunner, tool)
32
33     adjustDirObjs(job_order, trim_listing)
34     adjustFileObjs(job_order, trim_anonymous_location)
35     adjustDirObjs(job_order, trim_anonymous_location)
36
37     main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
38     for inp in main["inputs"]:
39         sn = shortname(inp["id"])
40         if sn in job_order:
41             inp["default"] = job_order[sn]
42
43     if not name:
44         name = tool.tool.get("label", os.path.basename(tool.tool["id"]))
45
46     upload_dependencies(arvRunner, name, tool.doc_loader,
47                         packed, tool.tool["id"], False)
48
49     # TODO nowhere for submit_runner_ram to go.
50
51     body = {
52         "workflow": {
53             "name": name,
54             "description": tool.tool.get("doc", ""),
55             "definition":yaml.round_trip_dump(packed)
56         }}
57     if project_uuid:
58         body["workflow"]["owner_uuid"] = project_uuid
59
60     if uuid:
61         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
62     else:
63         call = arvRunner.api.workflows().create(body=body)
64     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
65
66 def dedup_reqs(reqs):
67     dedup = {}
68     for r in reversed(reqs):
69         if r["class"] not in dedup and not r["class"].startswith("http://arvados.org/cwl#"):
70             dedup[r["class"]] = r
71     return [dedup[r] for r in sorted(dedup.keys())]
72
73 class ArvadosWorkflow(Workflow):
74     """Wrap cwltool Workflow to override selected methods."""
75
76     def __init__(self, arvrunner, toolpath_object, **kwargs):
77         super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
78         self.arvrunner = arvrunner
79         self.work_api = kwargs["work_api"]
80         self.wf_pdh = None
81
82     def job(self, joborder, output_callback, **kwargs):
83         kwargs["work_api"] = self.work_api
84         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
85         if req:
86             with SourceLine(self.tool, None, WorkflowException):
87                 if "id" not in self.tool:
88                     raise WorkflowException("%s object must have 'id'" % (self.tool["class"]))
89             document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
90
91             with Perf(metrics, "subworkflow upload_deps"):
92                 upload_dependencies(self.arvrunner,
93                                     os.path.basename(joborder.get("id", "#")),
94                                     document_loader,
95                                     joborder,
96                                     joborder.get("id", "#"),
97                                     False)
98
99                 if self.wf_pdh is None:
100                     workflowobj["requirements"] = dedup_reqs(self.requirements)
101                     workflowobj["hints"] = dedup_reqs(self.hints)
102
103                     packed = pack(document_loader, workflowobj, uri, self.metadata)
104
105                     upload_dependencies(self.arvrunner,
106                                         kwargs.get("name", ""),
107                                         document_loader,
108                                         packed,
109                                         uri,
110                                         False)
111
112             with Perf(metrics, "subworkflow adjust"):
113                 joborder_keepmount = copy.deepcopy(joborder)
114
115                 def keepmount(obj):
116                     with SourceLine(obj, None, WorkflowException):
117                         if "location" not in obj:
118                             raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
119                     with SourceLine(obj, "location", WorkflowException):
120                         if obj["location"].startswith("keep:"):
121                             obj["location"] = "/keep/" + obj["location"][5:]
122                             if "listing" in obj:
123                                 del obj["listing"]
124                         elif obj["location"].startswith("_:"):
125                             del obj["location"]
126                         else:
127                             raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
128
129                 adjustFileObjs(joborder_keepmount, keepmount)
130                 adjustDirObjs(joborder_keepmount, keepmount)
131
132                 if self.wf_pdh is None:
133                     adjustFileObjs(packed, keepmount)
134                     adjustDirObjs(packed, keepmount)
135                     self.wf_pdh = upload_workflow_collection(self.arvrunner, shortname(self.tool["id"]), packed)
136
137             wf_runner = cmap({
138                 "class": "CommandLineTool",
139                 "baseCommand": "cwltool",
140                 "inputs": self.tool["inputs"],
141                 "outputs": self.tool["outputs"],
142                 "stdout": "cwl.output.json",
143                 "requirements": workflowobj["requirements"]+[
144                     {
145                     "class": "InitialWorkDirRequirement",
146                     "listing": [{
147                             "entryname": "workflow.cwl",
148                             "entry": {
149                                 "class": "File",
150                                 "location": "keep:%s/workflow.cwl" % self.wf_pdh
151                             }
152                         }, {
153                             "entryname": "cwl.input.yml",
154                             "entry": json.dumps(joborder_keepmount, indent=2, sort_keys=True, separators=(',',': ')).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
155                         }]
156                 }],
157                 "hints": workflowobj["hints"],
158                 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"]
159             })
160             kwargs["loader"] = self.doc_loader
161             kwargs["avsc_names"] = self.doc_schema
162             return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder, output_callback, **kwargs)
163         else:
164             return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)