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