10793: Move output_callback to finally block to ensure it is always called.
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 import logging
2 import json
3 import os
4
5 import ruamel.yaml as yaml
6
7 from cwltool.errors import WorkflowException
8 from cwltool.process import get_feature, UnsupportedRequirement, shortname
9 from cwltool.pathmapper import adjustFiles
10 from cwltool.utils import aslist
11
12 import arvados.collection
13
14 from .arvdocker import arv_docker_get_image
15 from . import done
16 from .runner import Runner, arvados_jobs_image
17 from .fsaccess import CollectionFetcher
18
19 logger = logging.getLogger('arvados.cwl-runner')
20
21 class ArvadosContainer(object):
22     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
23
24     def __init__(self, runner):
25         self.arvrunner = runner
26         self.running = False
27         self.uuid = None
28
29     def update_pipeline_component(self, r):
30         pass
31
32     def run(self, dry_run=False, pull_image=True, **kwargs):
33         container_request = {
34             "command": self.command_line,
35             "owner_uuid": self.arvrunner.project_uuid,
36             "name": self.name,
37             "output_path": self.outdir,
38             "cwd": self.outdir,
39             "priority": 1,
40             "state": "Committed",
41             "properties": {}
42         }
43         runtime_constraints = {}
44         mounts = {
45             self.outdir: {
46                 "kind": "tmp"
47             }
48         }
49         scheduling_parameters = {}
50
51         dirs = set()
52         for f in self.pathmapper.files():
53             _, p, tp = self.pathmapper.mapper(f)
54             if tp == "Directory" and '/' not in p[6:]:
55                 mounts[p] = {
56                     "kind": "collection",
57                     "portable_data_hash": p[6:]
58                 }
59                 dirs.add(p[6:])
60         for f in self.pathmapper.files():
61             _, p, tp = self.pathmapper.mapper(f)
62             if p[6:].split("/")[0] not in dirs:
63                 mounts[p] = {
64                     "kind": "collection",
65                     "portable_data_hash": p[6:]
66                 }
67
68         if self.generatefiles["listing"]:
69             raise UnsupportedRequirement("InitialWorkDirRequirement not supported with --api=containers")
70
71         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
72         if self.environment:
73             container_request["environment"].update(self.environment)
74
75         if self.stdin:
76             raise UnsupportedRequirement("Stdin redirection currently not suppported")
77
78         if self.stderr:
79             raise UnsupportedRequirement("Stderr redirection currently not suppported")
80
81         if self.stdout:
82             mounts["stdout"] = {"kind": "file",
83                                 "path": "%s/%s" % (self.outdir, self.stdout)}
84
85         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
86         if not docker_req:
87             docker_req = {"dockerImageId": arvados_jobs_image(self.arvrunner)}
88
89         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
90                                                                      docker_req,
91                                                                      pull_image,
92                                                                      self.arvrunner.project_uuid)
93
94         resources = self.builder.resources
95         if resources is not None:
96             runtime_constraints["vcpus"] = resources.get("cores", 1)
97             runtime_constraints["ram"] = resources.get("ram") * 2**20
98
99         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
100         if api_req:
101             runtime_constraints["API"] = True
102
103         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
104         if runtime_req:
105             if "keep_cache" in runtime_req:
106                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"]
107
108         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
109         if partition_req:
110             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
111
112         container_request["mounts"] = mounts
113         container_request["runtime_constraints"] = runtime_constraints
114         container_request["use_existing"] = kwargs.get("enable_reuse", True)
115         container_request["scheduling_parameters"] = scheduling_parameters
116
117         if kwargs.get("runnerjob", "").startswith("arvwf:"):
118             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
119             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
120             if container_request["name"] == "main":
121                 container_request["name"] = wfrecord["name"]
122             container_request["properties"]["template_uuid"] = wfuuid
123
124         try:
125             response = self.arvrunner.api.container_requests().create(
126                 body=container_request
127             ).execute(num_retries=self.arvrunner.num_retries)
128
129             self.uuid = response["uuid"]
130             self.arvrunner.processes[self.uuid] = self
131
132             logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
133
134             if response["state"] == "Final":
135                 self.done(response)
136         except Exception as e:
137             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
138             self.output_callback({}, "permanentFail")
139
140     def done(self, record):
141         try:
142             container = self.arvrunner.api.containers().get(
143                 uuid=record["container_uuid"]
144             ).execute(num_retries=self.arvrunner.num_retries)
145             if container["state"] == "Complete":
146                 rcode = container["exit_code"]
147                 if self.successCodes and rcode in self.successCodes:
148                     processStatus = "success"
149                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
150                     processStatus = "temporaryFail"
151                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
152                     processStatus = "permanentFail"
153                 elif rcode == 0:
154                     processStatus = "success"
155                 else:
156                     processStatus = "permanentFail"
157             else:
158                 processStatus = "permanentFail"
159
160             if processStatus == "permanentFail":
161                 logc = arvados.collection.CollectionReader(container["log"],
162                                                            api_client=self.arvrunner.api,
163                                                            keep_client=self.arvrunner.keep_client,
164                                                            num_retries=self.arvrunner.num_retries)
165                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
166
167             outputs = {}
168             if container["output"]:
169                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
170         except WorkflowException as e:
171             logger.error("%s unable to collect output from %s:\n%s",
172                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
173             processStatus = "permanentFail"
174         except Exception as e:
175             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
176             processStatus = "permanentFail"
177         finally:
178             self.output_callback(outputs, processStatus)
179             if record["uuid"] in self.arvrunner.processes:
180                 del self.arvrunner.processes[record["uuid"]]
181
182
183 class RunnerContainer(Runner):
184     """Submit and manage a container that runs arvados-cwl-runner."""
185
186     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
187         """Create an Arvados container request for this workflow.
188
189         The returned dict can be used to create a container passed as
190         the +body+ argument to container_requests().create().
191         """
192
193         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
194
195         container_req = {
196             "owner_uuid": self.arvrunner.project_uuid,
197             "name": self.name,
198             "output_path": "/var/spool/cwl",
199             "cwd": "/var/spool/cwl",
200             "priority": 1,
201             "state": "Committed",
202             "container_image": arvados_jobs_image(self.arvrunner),
203             "mounts": {
204                 "/var/lib/cwl/cwl.input.json": {
205                     "kind": "json",
206                     "content": self.job_order
207                 },
208                 "stdout": {
209                     "kind": "file",
210                     "path": "/var/spool/cwl/cwl.output.json"
211                 },
212                 "/var/spool/cwl": {
213                     "kind": "collection",
214                     "writable": True
215                 }
216             },
217             "runtime_constraints": {
218                 "vcpus": 1,
219                 "ram": 1024*1024 * self.submit_runner_ram,
220                 "API": True
221             },
222             "properties": {}
223         }
224
225         workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
226         if workflowcollection.startswith("keep:"):
227             workflowcollection = workflowcollection[5:workflowcollection.index('/')]
228             workflowname = os.path.basename(self.tool.tool["id"])
229             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
230             container_req["mounts"]["/var/lib/cwl/workflow"] = {
231                 "kind": "collection",
232                 "portable_data_hash": "%s" % workflowcollection
233                 }
234         elif workflowcollection.startswith("arvwf:"):
235             workflowpath = "/var/lib/cwl/workflow.json#main"
236             wfuuid = workflowcollection[6:workflowcollection.index("#")]
237             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
238             wfobj = yaml.safe_load(wfrecord["definition"])
239             if container_req["name"].startswith("arvwf:"):
240                 container_req["name"] = wfrecord["name"]
241             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
242                 "kind": "json",
243                 "json": wfobj
244             }
245             container_req["properties"]["template_uuid"] = wfuuid
246
247         command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
248         if self.output_name:
249             command.append("--output-name=" + self.output_name)
250
251         if self.output_tags:
252             command.append("--output-tags=" + self.output_tags)
253
254         if kwargs.get("debug"):
255             command.append("--debug")
256
257         if self.enable_reuse:
258             command.append("--enable-reuse")
259         else:
260             command.append("--disable-reuse")
261
262         if self.on_error:
263             command.append("--on-error=" + self.on_error)
264
265         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
266
267         container_req["command"] = command
268
269         return container_req
270
271
272     def run(self, *args, **kwargs):
273         kwargs["keepprefix"] = "keep:"
274         job_spec = self.arvados_job_spec(*args, **kwargs)
275         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
276
277         response = self.arvrunner.api.container_requests().create(
278             body=job_spec
279         ).execute(num_retries=self.arvrunner.num_retries)
280
281         self.uuid = response["uuid"]
282         self.arvrunner.processes[self.uuid] = self
283
284         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
285
286         if response["state"] == "Final":
287             self.done(response)
288
289     def done(self, record):
290         try:
291             container = self.arvrunner.api.containers().get(
292                 uuid=record["container_uuid"]
293             ).execute(num_retries=self.arvrunner.num_retries)
294         except Exception as e:
295             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
296             self.arvrunner.output_callback({}, "permanentFail")
297         else:
298             super(RunnerContainer, self).done(container)
299         finally:
300             if record["uuid"] in self.arvrunner.processes:
301                 del self.arvrunner.processes[record["uuid"]]