Merge branch 'master' into 10604-crunch2-user-guide
[arvados.git] / sdk / cwl / arvados_cwl / arvworkflow.py
1 import os
2 import json
3 import copy
4 import logging
5
6 from cwltool.pack import pack
7 from cwltool.load_tool import fetch_document
8 from cwltool.process import shortname
9 from cwltool.workflow import Workflow, WorkflowException
10 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs
11
12 import ruamel.yaml as yaml
13
14 from .runner import upload_docker, upload_dependencies, trim_listing
15 from .arvtool import ArvadosCommandTool
16 from .perf import Perf
17
18 logger = logging.getLogger('arvados.cwl-runner')
19 metrics = logging.getLogger('arvados.cwl-runner.metrics')
20
21 def upload_workflow(arvRunner, tool, job_order, project_uuid, uuid=None, submit_runner_ram=0):
22     upload_docker(arvRunner, tool)
23
24     document_loader, workflowobj, uri = (tool.doc_loader, tool.doc_loader.fetch(tool.tool["id"]), tool.tool["id"])
25
26     packed = pack(document_loader, workflowobj, uri, tool.metadata)
27
28     adjustDirObjs(job_order, trim_listing)
29
30     main = [p for p in packed["$graph"] if p["id"] == "#main"][0]
31     for inp in main["inputs"]:
32         sn = shortname(inp["id"])
33         if sn in job_order:
34             inp["default"] = job_order[sn]
35
36     name = os.path.basename(tool.tool["id"])
37     upload_dependencies(arvRunner, name, document_loader,
38                         packed, uri, False)
39
40     # TODO nowhere for submit_runner_ram to go.
41
42     body = {
43         "workflow": {
44             "name": tool.tool.get("label", name),
45             "description": tool.tool.get("doc", ""),
46             "definition":yaml.safe_dump(packed)
47         }}
48     if project_uuid:
49         body["workflow"]["owner_uuid"] = project_uuid
50
51     if uuid:
52         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
53     else:
54         call = arvRunner.api.workflows().create(body=body)
55     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
56
57 class ArvadosWorkflow(Workflow):
58     """Wrap cwltool Workflow to override selected methods."""
59
60     def __init__(self, arvrunner, toolpath_object, **kwargs):
61         super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
62         self.arvrunner = arvrunner
63         self.work_api = kwargs["work_api"]
64
65     def job(self, joborder, output_callback, **kwargs):
66         kwargs["work_api"] = self.work_api
67         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
68         if req:
69             document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
70
71             with Perf(metrics, "subworkflow upload_deps"):
72                 workflowobj["requirements"] = self.requirements + workflowobj.get("requirements", [])
73                 workflowobj["hints"] = self.hints + workflowobj.get("hints", [])
74                 packed = pack(document_loader, workflowobj, uri, self.metadata)
75
76                 upload_dependencies(self.arvrunner,
77                                     kwargs.get("name", ""),
78                                     document_loader,
79                                     packed,
80                                     uri,
81                                     False)
82
83                 upload_dependencies(self.arvrunner,
84                                     os.path.basename(joborder.get("id", "#")),
85                                     document_loader,
86                                     joborder,
87                                     joborder.get("id", "#"),
88                                     False)
89
90             with Perf(metrics, "subworkflow adjust"):
91                 joborder_keepmount = copy.deepcopy(joborder)
92
93                 def keepmount(obj):
94                     if "location" not in obj:
95                         raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
96                     if obj["location"].startswith("keep:"):
97                         obj["location"] = "/keep/" + obj["location"][5:]
98                         if "listing" in obj:
99                             del obj["listing"]
100                     elif obj["location"].startswith("_:"):
101                         del obj["location"]
102                     else:
103                         raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
104
105                 adjustFileObjs(joborder_keepmount, keepmount)
106                 adjustDirObjs(joborder_keepmount, keepmount)
107                 adjustFileObjs(packed, keepmount)
108                 adjustDirObjs(packed, keepmount)
109
110             wf_runner = {
111                 "class": "CommandLineTool",
112                 "baseCommand": "cwltool",
113                 "inputs": self.tool["inputs"],
114                 "outputs": self.tool["outputs"],
115                 "stdout": "cwl.output.json",
116                 "requirements": workflowobj["requirements"]+[
117                     {
118                     "class": "InitialWorkDirRequirement",
119                     "listing": [{
120                             "entryname": "workflow.cwl",
121                             "entry": yaml.safe_dump(packed).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
122                         }, {
123                             "entryname": "cwl.input.yml",
124                             "entry": yaml.safe_dump(joborder_keepmount).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
125                         }]
126                 }],
127                 "hints": workflowobj["hints"],
128                 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"]
129             }
130             kwargs["loader"] = self.doc_loader
131             kwargs["avsc_names"] = self.doc_schema
132             return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder, output_callback, **kwargs)
133         else:
134             return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)