Merge branch 'master' into 10401-limit-dir-expansion
[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, stg = 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, stg = 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             raise UnsupportedRequirement("Stdin redirection currently not suppported")
119
120         if self.stderr:
121             raise UnsupportedRequirement("Stderr redirection currently not suppported")
122
123         if self.stdout:
124             mounts["stdout"] = {"kind": "file",
125                                 "path": "%s/%s" % (self.outdir, self.stdout)}
126
127         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
128         if not docker_req:
129             docker_req = {"dockerImageId": "arvados/jobs"}
130
131         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
132                                                                      docker_req,
133                                                                      pull_image,
134                                                                      self.arvrunner.project_uuid)
135
136         resources = self.builder.resources
137         if resources is not None:
138             runtime_constraints["vcpus"] = resources.get("cores", 1)
139             runtime_constraints["ram"] = resources.get("ram") * 2**20
140
141         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
142         if api_req:
143             runtime_constraints["API"] = True
144
145         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
146         if runtime_req:
147             if "keep_cache" in runtime_req:
148                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
149
150         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
151         if partition_req:
152             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
153
154         container_request["mounts"] = mounts
155         container_request["runtime_constraints"] = runtime_constraints
156         container_request["use_existing"] = kwargs.get("enable_reuse", True)
157         container_request["scheduling_parameters"] = scheduling_parameters
158
159         if kwargs.get("runnerjob", "").startswith("arvwf:"):
160             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
161             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
162             if container_request["name"] == "main":
163                 container_request["name"] = wfrecord["name"]
164             container_request["properties"]["template_uuid"] = wfuuid
165
166         try:
167             response = self.arvrunner.api.container_requests().create(
168                 body=container_request
169             ).execute(num_retries=self.arvrunner.num_retries)
170
171             self.uuid = response["uuid"]
172             self.arvrunner.processes[self.uuid] = self
173
174             if response["state"] == "Final":
175                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
176                 self.done(response)
177             else:
178                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
179         except Exception as e:
180             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
181             self.output_callback({}, "permanentFail")
182
183     def done(self, record):
184         try:
185             container = self.arvrunner.api.containers().get(
186                 uuid=record["container_uuid"]
187             ).execute(num_retries=self.arvrunner.num_retries)
188             if container["state"] == "Complete":
189                 rcode = container["exit_code"]
190                 if self.successCodes and rcode in self.successCodes:
191                     processStatus = "success"
192                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
193                     processStatus = "temporaryFail"
194                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
195                     processStatus = "permanentFail"
196                 elif rcode == 0:
197                     processStatus = "success"
198                 else:
199                     processStatus = "permanentFail"
200             else:
201                 processStatus = "permanentFail"
202
203             if processStatus == "permanentFail":
204                 logc = arvados.collection.CollectionReader(container["log"],
205                                                            api_client=self.arvrunner.api,
206                                                            keep_client=self.arvrunner.keep_client,
207                                                            num_retries=self.arvrunner.num_retries)
208                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
209
210             outputs = {}
211             if container["output"]:
212                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
213         except WorkflowException as e:
214             logger.error("%s unable to collect output from %s:\n%s",
215                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
216             processStatus = "permanentFail"
217         except Exception as e:
218             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
219             processStatus = "permanentFail"
220         finally:
221             self.output_callback(outputs, processStatus)
222             if record["uuid"] in self.arvrunner.processes:
223                 del self.arvrunner.processes[record["uuid"]]
224
225
226 class RunnerContainer(Runner):
227     """Submit and manage a container that runs arvados-cwl-runner."""
228
229     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
230         """Create an Arvados container request for this workflow.
231
232         The returned dict can be used to create a container passed as
233         the +body+ argument to container_requests().create().
234         """
235
236         adjustDirObjs(self.job_order, trim_listing)
237
238         container_req = {
239             "owner_uuid": self.arvrunner.project_uuid,
240             "name": self.name,
241             "output_path": "/var/spool/cwl",
242             "cwd": "/var/spool/cwl",
243             "priority": 1,
244             "state": "Committed",
245             "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
246             "mounts": {
247                 "/var/lib/cwl/cwl.input.json": {
248                     "kind": "json",
249                     "content": self.job_order
250                 },
251                 "stdout": {
252                     "kind": "file",
253                     "path": "/var/spool/cwl/cwl.output.json"
254                 },
255                 "/var/spool/cwl": {
256                     "kind": "collection",
257                     "writable": True
258                 }
259             },
260             "runtime_constraints": {
261                 "vcpus": 1,
262                 "ram": 1024*1024 * self.submit_runner_ram,
263                 "API": True
264             },
265             "properties": {}
266         }
267
268         if self.tool.tool.get("id", "").startswith("keep:"):
269             sp = self.tool.tool["id"].split('/')
270             workflowcollection = sp[0][5:]
271             workflowname = "/".join(sp[1:])
272             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
273             container_req["mounts"]["/var/lib/cwl/workflow"] = {
274                 "kind": "collection",
275                 "portable_data_hash": "%s" % workflowcollection
276             }
277         else:
278             packed = packed_workflow(self.arvrunner, self.tool)
279             workflowpath = "/var/lib/cwl/workflow.json#main"
280             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
281                 "kind": "json",
282                 "content": packed
283             }
284             if self.tool.tool.get("id", "").startswith("arvwf:"):
285                 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
286
287         command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
288         if self.output_name:
289             command.append("--output-name=" + self.output_name)
290             container_req["output_name"] = self.output_name
291
292         if self.output_tags:
293             command.append("--output-tags=" + self.output_tags)
294
295         if kwargs.get("debug"):
296             command.append("--debug")
297
298         if self.enable_reuse:
299             command.append("--enable-reuse")
300         else:
301             command.append("--disable-reuse")
302
303         if self.on_error:
304             command.append("--on-error=" + self.on_error)
305
306         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
307
308         container_req["command"] = command
309
310         return container_req
311
312
313     def run(self, *args, **kwargs):
314         kwargs["keepprefix"] = "keep:"
315         job_spec = self.arvados_job_spec(*args, **kwargs)
316         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
317
318         response = self.arvrunner.api.container_requests().create(
319             body=job_spec
320         ).execute(num_retries=self.arvrunner.num_retries)
321
322         self.uuid = response["uuid"]
323         self.arvrunner.processes[self.uuid] = self
324
325         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
326
327         if response["state"] == "Final":
328             self.done(response)
329
330     def done(self, record):
331         try:
332             container = self.arvrunner.api.containers().get(
333                 uuid=record["container_uuid"]
334             ).execute(num_retries=self.arvrunner.num_retries)
335         except Exception as e:
336             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
337             self.arvrunner.output_callback({}, "permanentFail")
338         else:
339             super(RunnerContainer, self).done(container)
340         finally:
341             if record["uuid"] in self.arvrunner.processes:
342                 del self.arvrunner.processes[record["uuid"]]