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