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