10081: Rename cwl.input.json to cwl.input.yml, fix test.
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 import logging
2 import json
3 import os
4
5 from cwltool.errors import WorkflowException
6 from cwltool.process import get_feature, UnsupportedRequirement, shortname
7 from cwltool.pathmapper import adjustFiles
8
9 import arvados.collection
10
11 from .arvdocker import arv_docker_get_image
12 from . import done
13 from .runner import Runner
14
15 logger = logging.getLogger('arvados.cwl-runner')
16
17 class ArvadosContainer(object):
18     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
19
20     def __init__(self, runner):
21         self.arvrunner = runner
22         self.running = False
23         self.uuid = None
24
25     def update_pipeline_component(self, r):
26         pass
27
28     def run(self, dry_run=False, pull_image=True, **kwargs):
29         container_request = {
30             "command": self.command_line,
31             "owner_uuid": self.arvrunner.project_uuid,
32             "name": self.name,
33             "output_path": self.outdir,
34             "cwd": self.outdir,
35             "priority": 1,
36             "state": "Committed"
37         }
38         runtime_constraints = {}
39         mounts = {
40             self.outdir: {
41                 "kind": "tmp"
42             }
43         }
44
45         dirs = set()
46         for f in self.pathmapper.files():
47             _, p, tp = self.pathmapper.mapper(f)
48             if tp == "Directory" and '/' not in p[6:]:
49                 mounts[p] = {
50                     "kind": "collection",
51                     "portable_data_hash": p[6:]
52                 }
53                 dirs.add(p[6:])
54         for f in self.pathmapper.files():
55             _, p, tp = self.pathmapper.mapper(f)
56             if p[6:].split("/")[0] not in dirs:
57                 mounts[p] = {
58                     "kind": "collection",
59                     "portable_data_hash": p[6:]
60                 }
61
62         if self.generatefiles["listing"]:
63             raise UnsupportedRequirement("Generate files not supported")
64
65         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
66         if self.environment:
67             container_request["environment"].update(self.environment)
68
69         if self.stdin:
70             raise UnsupportedRequirement("Stdin redirection currently not suppported")
71
72         if self.stderr:
73             raise UnsupportedRequirement("Stderr redirection currently not suppported")
74
75         if self.stdout:
76             mounts["stdout"] = {"kind": "file",
77                                 "path": "%s/%s" % (self.outdir, self.stdout)}
78
79         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
80         if not docker_req:
81             docker_req = {"dockerImageId": "arvados/jobs"}
82
83         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
84                                                                      docker_req,
85                                                                      pull_image,
86                                                                      self.arvrunner.project_uuid)
87
88         resources = self.builder.resources
89         if resources is not None:
90             runtime_constraints["vcpus"] = resources.get("cores", 1)
91             runtime_constraints["ram"] = resources.get("ram") * 2**20
92
93         container_request["mounts"] = mounts
94         container_request["runtime_constraints"] = runtime_constraints
95
96         try:
97             response = self.arvrunner.api.container_requests().create(
98                 body=container_request
99             ).execute(num_retries=self.arvrunner.num_retries)
100
101             self.arvrunner.processes[response["container_uuid"]] = self
102
103             logger.info("Container %s (%s) request state is %s", self.name, response["uuid"], response["state"])
104
105             if response["state"] == "Final":
106                 self.done(response)
107         except Exception as e:
108             logger.error("Got error %s" % str(e))
109             self.output_callback({}, "permanentFail")
110
111     def done(self, record):
112         try:
113             if record["state"] == "Complete":
114                 rcode = record["exit_code"]
115                 if self.successCodes and rcode in self.successCodes:
116                     processStatus = "success"
117                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
118                     processStatus = "temporaryFail"
119                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
120                     processStatus = "permanentFail"
121                 elif rcode == 0:
122                     processStatus = "success"
123                 else:
124                     processStatus = "permanentFail"
125             else:
126                 processStatus = "permanentFail"
127
128             try:
129                 outputs = {}
130                 if record["output"]:
131                     outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
132             except WorkflowException as e:
133                 logger.error("Error while collecting container outputs:\n%s", e, exc_info=(e if self.arvrunner.debug else False))
134                 processStatus = "permanentFail"
135             except Exception as e:
136                 logger.exception("Got unknown exception while collecting job outputs:")
137                 processStatus = "permanentFail"
138
139             self.output_callback(outputs, processStatus)
140         finally:
141             del self.arvrunner.processes[record["uuid"]]
142
143
144 class RunnerContainer(Runner):
145     """Submit and manage a container that runs arvados-cwl-runner."""
146
147     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
148         """Create an Arvados container request for this workflow.
149
150         The returned dict can be used to create a container passed as
151         the +body+ argument to container_requests().create().
152         """
153
154         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
155
156         with arvados.collection.Collection(api_client=self.arvrunner.api) as jobobj:
157             with jobobj.open("cwl.input.json", "w") as f:
158                 json.dump(self.job_order, f, sort_keys=True, indent=4)
159             jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
160
161         workflowname = os.path.basename(self.tool.tool["id"])
162         workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
163         workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
164         workflowcollection = workflowcollection[5:workflowcollection.index('/')]
165         jobpath = "/var/lib/cwl/job/cwl.input.json"
166
167         container_image = arv_docker_get_image(self.arvrunner.api,
168                                                {"dockerImageId": "arvados/jobs"},
169                                                pull_image,
170                                                self.arvrunner.project_uuid)
171
172         return {
173             "command": ["arvados-cwl-runner", "--local", "--api=containers", workflowpath, jobpath],
174             "owner_uuid": self.arvrunner.project_uuid,
175             "name": self.name,
176             "output_path": "/var/spool/cwl",
177             "cwd": "/var/spool/cwl",
178             "priority": 1,
179             "state": "Committed",
180             "container_image": container_image,
181             "mounts": {
182                 "/var/lib/cwl/workflow": {
183                     "kind": "collection",
184                     "portable_data_hash": "%s" % workflowcollection
185                 },
186                 jobpath: {
187                     "kind": "collection",
188                     "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
189                 },
190                 "stdout": {
191                     "kind": "file",
192                     "path": "/var/spool/cwl/cwl.output.json"
193                 },
194                 "/var/spool/cwl": {
195                     "kind": "collection",
196                     "writable": True
197                 }
198             },
199             "runtime_constraints": {
200                 "vcpus": 1,
201                 "ram": 1024*1024*256,
202                 "API": True
203             }
204         }
205
206     def run(self, *args, **kwargs):
207         kwargs["keepprefix"] = "keep:"
208         job_spec = self.arvados_job_spec(*args, **kwargs)
209         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
210
211         response = self.arvrunner.api.container_requests().create(
212             body=job_spec
213         ).execute(num_retries=self.arvrunner.num_retries)
214
215         self.uuid = response["uuid"]
216         self.arvrunner.processes[response["container_uuid"]] = self
217
218         logger.info("Submitted container %s", response["uuid"])
219
220         if response["state"] in ("Complete", "Failed", "Cancelled"):
221             self.done(response)