Merge branch '10499-cwl-crunch2-docs' refs #10499
[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):
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     body = {
41         "workflow": {
42             "name": tool.tool.get("label", name),
43             "description": tool.tool.get("doc", ""),
44             "definition":yaml.safe_dump(packed)
45         }}
46     if project_uuid:
47         body["workflow"]["owner_uuid"] = project_uuid
48
49     if uuid:
50         call = arvRunner.api.workflows().update(uuid=uuid, body=body)
51     else:
52         call = arvRunner.api.workflows().create(body=body)
53     return call.execute(num_retries=arvRunner.num_retries)["uuid"]
54
55 class ArvadosWorkflow(Workflow):
56     """Wrap cwltool Workflow to override selected methods."""
57
58     def __init__(self, arvrunner, toolpath_object, **kwargs):
59         super(ArvadosWorkflow, self).__init__(toolpath_object, **kwargs)
60         self.arvrunner = arvrunner
61         self.work_api = kwargs["work_api"]
62
63     def job(self, joborder, output_callback, **kwargs):
64         kwargs["work_api"] = self.work_api
65         req, _ = self.get_requirement("http://arvados.org/cwl#RunInSingleContainer")
66         if req:
67             document_loader, workflowobj, uri = (self.doc_loader, self.doc_loader.fetch(self.tool["id"]), self.tool["id"])
68
69             with Perf(metrics, "subworkflow upload_deps"):
70                 workflowobj["requirements"] = self.requirements + workflowobj.get("requirements", [])
71                 workflowobj["hints"] = self.hints + workflowobj.get("hints", [])
72                 packed = pack(document_loader, workflowobj, uri, self.metadata)
73
74                 upload_dependencies(self.arvrunner,
75                                     kwargs.get("name", ""),
76                                     document_loader,
77                                     packed,
78                                     uri,
79                                     False)
80
81                 upload_dependencies(self.arvrunner,
82                                     os.path.basename(joborder.get("id", "#")),
83                                     document_loader,
84                                     joborder,
85                                     joborder.get("id", "#"),
86                                     False)
87
88             with Perf(metrics, "subworkflow adjust"):
89                 joborder_keepmount = copy.deepcopy(joborder)
90
91                 def keepmount(obj):
92                     if "location" not in obj:
93                         raise WorkflowException("%s object is missing required 'location' field: %s" % (obj["class"], obj))
94                     if obj["location"].startswith("keep:"):
95                         obj["location"] = "/keep/" + obj["location"][5:]
96                         if "listing" in obj:
97                             del obj["listing"]
98                     elif obj["location"].startswith("_:"):
99                         del obj["location"]
100                     else:
101                         raise WorkflowException("Location is not a keep reference or a literal: '%s'" % obj["location"])
102
103                 adjustFileObjs(joborder_keepmount, keepmount)
104                 adjustDirObjs(joborder_keepmount, keepmount)
105                 adjustFileObjs(packed, keepmount)
106                 adjustDirObjs(packed, keepmount)
107
108             wf_runner = {
109                 "class": "CommandLineTool",
110                 "baseCommand": "cwltool",
111                 "inputs": self.tool["inputs"],
112                 "outputs": self.tool["outputs"],
113                 "stdout": "cwl.output.json",
114                 "requirements": workflowobj["requirements"]+[
115                     {
116                     "class": "InitialWorkDirRequirement",
117                     "listing": [{
118                             "entryname": "workflow.cwl",
119                             "entry": yaml.safe_dump(packed).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
120                         }, {
121                             "entryname": "cwl.input.yml",
122                             "entry": yaml.safe_dump(joborder_keepmount).replace("\\", "\\\\").replace('$(', '\$(').replace('${', '\${')
123                         }]
124                 }],
125                 "hints": workflowobj["hints"],
126                 "arguments": ["--no-container", "--move-outputs", "--preserve-entire-environment", "workflow.cwl#main", "cwl.input.yml"]
127             }
128             kwargs["loader"] = self.doc_loader
129             kwargs["avsc_names"] = self.doc_schema
130             return ArvadosCommandTool(self.arvrunner, wf_runner, **kwargs).job(joborder, output_callback, **kwargs)
131         else:
132             return super(ArvadosWorkflow, self).job(joborder, output_callback, **kwargs)