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