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