12764: Fixes
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import logging
6 import json
7 import os
8 import urllib
9 import time
10 import datetime
11 import ciso8601
12
13 import ruamel.yaml as yaml
14
15 from cwltool.errors import WorkflowException
16 from cwltool.process import get_feature, UnsupportedRequirement, shortname
17 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
18 from cwltool.utils import aslist
19
20 import arvados.collection
21
22 from .arvdocker import arv_docker_get_image
23 from . import done
24 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields
25 from .fsaccess import CollectionFetcher
26 from .pathmapper import NoFollowPathMapper, trim_listing
27 from .perf import Perf
28
29 logger = logging.getLogger('arvados.cwl-runner')
30 metrics = logging.getLogger('arvados.cwl-runner.metrics')
31
32 class ArvadosContainer(object):
33     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
34
35     def __init__(self, runner):
36         self.arvrunner = runner
37         self.running = False
38         self.uuid = None
39
40     def update_pipeline_component(self, r):
41         pass
42
43     def run(self, dry_run=False, pull_image=True, **kwargs):
44         container_request = {
45             "command": self.command_line,
46             "owner_uuid": self.arvrunner.project_uuid,
47             "name": self.name,
48             "output_path": self.outdir,
49             "cwd": self.outdir,
50             "priority": 1,
51             "state": "Committed",
52             "properties": {},
53         }
54         runtime_constraints = {}
55
56         resources = self.builder.resources
57         if resources is not None:
58             runtime_constraints["vcpus"] = resources.get("cores", 1)
59             runtime_constraints["ram"] = resources.get("ram") * 2**20
60
61         mounts = {
62             self.outdir: {
63                 "kind": "tmp",
64                 "capacity": resources.get("outdirSize", 0) * 2**20
65             },
66             self.tmpdir: {
67                 "kind": "tmp",
68                 "capacity": resources.get("tmpdirSize", 0) * 2**20
69             }
70         }
71         scheduling_parameters = {}
72
73         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
74         rf.sort(key=lambda k: k.resolved)
75         prevdir = None
76         for resolved, target, tp, stg in rf:
77             if not stg:
78                 continue
79             if prevdir and target.startswith(prevdir):
80                 continue
81             if tp == "Directory":
82                 targetdir = target
83             else:
84                 targetdir = os.path.dirname(target)
85             sp = resolved.split("/", 1)
86             pdh = sp[0][5:]   # remove "keep:"
87             mounts[targetdir] = {
88                 "kind": "collection",
89                 "portable_data_hash": pdh
90             }
91             if len(sp) == 2:
92                 if tp == "Directory":
93                     path = sp[1]
94                 else:
95                     path = os.path.dirname(sp[1])
96                 if path and path != "/":
97                     mounts[targetdir]["path"] = path
98             prevdir = targetdir + "/"
99
100         with Perf(metrics, "generatefiles %s" % self.name):
101             if self.generatefiles["listing"]:
102                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
103                                                     keep_client=self.arvrunner.keep_client,
104                                                     num_retries=self.arvrunner.num_retries)
105                 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
106                                                     separateDirs=False)
107
108                 with Perf(metrics, "createfiles %s" % self.name):
109                     for f, p in generatemapper.items():
110                         if not p.target:
111                             pass
112                         elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
113                             source, path = self.arvrunner.fs_access.get_collection(p.resolved)
114                             vwd.copy(path, p.target, source_collection=source)
115                         elif p.type == "CreateFile":
116                             with vwd.open(p.target, "w") as n:
117                                 n.write(p.resolved.encode("utf-8"))
118
119                 with Perf(metrics, "generatefiles.save_new %s" % self.name):
120                     vwd.save_new()
121
122                 for f, p in generatemapper.items():
123                     if not p.target:
124                         continue
125                     mountpoint = "%s/%s" % (self.outdir, p.target)
126                     mounts[mountpoint] = {"kind": "collection",
127                                           "portable_data_hash": vwd.portable_data_hash(),
128                                           "path": p.target}
129                     if p.type.startswith("Writable"):
130                         mounts[mountpoint]["writable"] = True
131
132         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
133         if self.environment:
134             container_request["environment"].update(self.environment)
135
136         if self.stdin:
137             sp = self.stdin[6:].split("/", 1)
138             mounts["stdin"] = {"kind": "collection",
139                                 "portable_data_hash": sp[0],
140                                 "path": sp[1]}
141
142         if self.stderr:
143             mounts["stderr"] = {"kind": "file",
144                                 "path": "%s/%s" % (self.outdir, self.stderr)}
145
146         if self.stdout:
147             mounts["stdout"] = {"kind": "file",
148                                 "path": "%s/%s" % (self.outdir, self.stdout)}
149
150         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
151         if not docker_req:
152             docker_req = {"dockerImageId": "arvados/jobs"}
153
154         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
155                                                                      docker_req,
156                                                                      pull_image,
157                                                                      self.arvrunner.project_uuid)
158
159         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
160         if api_req:
161             runtime_constraints["API"] = True
162
163         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
164         if runtime_req:
165             if "keep_cache" in runtime_req:
166                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
167             if "outputDirType" in runtime_req:
168                 if runtime_req["outputDirType"] == "local_output_dir":
169                     # Currently the default behavior.
170                     pass
171                 elif runtime_req["outputDirType"] == "keep_output_dir":
172                     mounts[self.outdir]= {
173                         "kind": "collection",
174                         "writable": True
175                     }
176
177         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
178         if partition_req:
179             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
180
181         intermediate_output_req, _ = get_feature(self, "http://arvados.org/cwl#IntermediateOutput")
182         if intermediate_output_req:
183             self.output_ttl = intermediate_output_req["outputTTL"]
184         else:
185             self.output_ttl = self.arvrunner.intermediate_output_ttl
186
187         if self.output_ttl < 0:
188             raise WorkflowError("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
189
190         container_request["output_ttl"] = self.output_ttl
191         container_request["mounts"] = mounts
192         container_request["runtime_constraints"] = runtime_constraints
193         container_request["scheduling_parameters"] = scheduling_parameters
194
195         enable_reuse = kwargs.get("enable_reuse", True)
196         if enable_reuse:
197             reuse_req, _ = get_feature(self, "http://arvados.org/cwl#ReuseRequirement")
198             if reuse_req:
199                 enable_reuse = reuse_req["enableReuse"]
200         container_request["use_existing"] = enable_reuse
201
202         if kwargs.get("runnerjob", "").startswith("arvwf:"):
203             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
204             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
205             if container_request["name"] == "main":
206                 container_request["name"] = wfrecord["name"]
207             container_request["properties"]["template_uuid"] = wfuuid
208
209         try:
210             response = self.arvrunner.api.container_requests().create(
211                 body=container_request
212             ).execute(num_retries=self.arvrunner.num_retries)
213
214             self.uuid = response["uuid"]
215             self.arvrunner.processes[self.uuid] = self
216
217             if response["state"] == "Final":
218                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
219                 self.done(response)
220             else:
221                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
222         except Exception as e:
223             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
224             self.output_callback({}, "permanentFail")
225
226     def done(self, record):
227         outputs = {}
228         try:
229             container = self.arvrunner.api.containers().get(
230                 uuid=record["container_uuid"]
231             ).execute(num_retries=self.arvrunner.num_retries)
232             if container["state"] == "Complete":
233                 rcode = container["exit_code"]
234                 if self.successCodes and rcode in self.successCodes:
235                     processStatus = "success"
236                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
237                     processStatus = "temporaryFail"
238                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
239                     processStatus = "permanentFail"
240                 elif rcode == 0:
241                     processStatus = "success"
242                 else:
243                     processStatus = "permanentFail"
244             else:
245                 processStatus = "permanentFail"
246
247             if processStatus == "permanentFail":
248                 logc = arvados.collection.CollectionReader(container["log"],
249                                                            api_client=self.arvrunner.api,
250                                                            keep_client=self.arvrunner.keep_client,
251                                                            num_retries=self.arvrunner.num_retries)
252                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
253
254             if record["output_uuid"]:
255                 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
256                     # Compute the trash time to avoid requesting the collection record.
257                     trash_at = ciso8601.parse_datetime_unaware(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
258                     aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
259                     orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
260                     oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
261                     logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
262                         self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
263                 self.arvrunner.add_intermediate_output(record["output_uuid"])
264
265             if container["output"]:
266                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
267         except WorkflowException as e:
268             logger.error("%s unable to collect output from %s:\n%s",
269                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
270             processStatus = "permanentFail"
271         except Exception as e:
272             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
273             processStatus = "permanentFail"
274         finally:
275             self.output_callback(outputs, processStatus)
276             if record["uuid"] in self.arvrunner.processes:
277                 del self.arvrunner.processes[record["uuid"]]
278
279
280 class RunnerContainer(Runner):
281     """Submit and manage a container that runs arvados-cwl-runner."""
282
283     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
284         """Create an Arvados container request for this workflow.
285
286         The returned dict can be used to create a container passed as
287         the +body+ argument to container_requests().create().
288         """
289
290         adjustDirObjs(self.job_order, trim_listing)
291         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
292         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
293
294         container_req = {
295             "owner_uuid": self.arvrunner.project_uuid,
296             "name": self.name,
297             "output_path": "/var/spool/cwl",
298             "cwd": "/var/spool/cwl",
299             "priority": 1,
300             "state": "Committed",
301             "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
302             "mounts": {
303                 "/var/lib/cwl/cwl.input.json": {
304                     "kind": "json",
305                     "content": self.job_order
306                 },
307                 "stdout": {
308                     "kind": "file",
309                     "path": "/var/spool/cwl/cwl.output.json"
310                 },
311                 "/var/spool/cwl": {
312                     "kind": "collection",
313                     "writable": True
314                 }
315             },
316             "runtime_constraints": {
317                 "vcpus": 1,
318                 "ram": 1024*1024 * self.submit_runner_ram,
319                 "API": True
320             },
321             "use_existing": self.enable_reuse,
322             "properties": {}
323         }
324
325         if self.tool.tool.get("id", "").startswith("keep:"):
326             sp = self.tool.tool["id"].split('/')
327             workflowcollection = sp[0][5:]
328             workflowname = "/".join(sp[1:])
329             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
330             container_req["mounts"]["/var/lib/cwl/workflow"] = {
331                 "kind": "collection",
332                 "portable_data_hash": "%s" % workflowcollection
333             }
334         else:
335             packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
336             workflowpath = "/var/lib/cwl/workflow.json#main"
337             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
338                 "kind": "json",
339                 "content": packed
340             }
341             if self.tool.tool.get("id", "").startswith("arvwf:"):
342                 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
343
344
345         command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
346         if self.output_name:
347             command.append("--output-name=" + self.output_name)
348             container_req["output_name"] = self.output_name
349
350         if self.output_tags:
351             command.append("--output-tags=" + self.output_tags)
352
353         if kwargs.get("debug"):
354             command.append("--debug")
355
356         if self.enable_reuse:
357             command.append("--enable-reuse")
358         else:
359             command.append("--disable-reuse")
360
361         if self.on_error:
362             command.append("--on-error=" + self.on_error)
363
364         if self.intermediate_output_ttl:
365             command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
366
367         if self.arvrunner.trash_intermediate:
368             command.append("--trash-intermediate")
369
370         if self.arvrunner.project_uuid:
371             command.append("--project-uuid="+self.arvrunner.project_uuid)
372
373         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
374
375         container_req["command"] = command
376
377         return container_req
378
379
380     def run(self, *args, **kwargs):
381         kwargs["keepprefix"] = "keep:"
382         job_spec = self.arvados_job_spec(*args, **kwargs)
383         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
384
385         response = self.arvrunner.api.container_requests().create(
386             body=job_spec
387         ).execute(num_retries=self.arvrunner.num_retries)
388
389         self.uuid = response["uuid"]
390         self.arvrunner.processes[self.uuid] = self
391
392         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
393
394         if response["state"] == "Final":
395             self.done(response)
396
397     def done(self, record):
398         try:
399             container = self.arvrunner.api.containers().get(
400                 uuid=record["container_uuid"]
401             ).execute(num_retries=self.arvrunner.num_retries)
402         except Exception as e:
403             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
404             self.arvrunner.output_callback({}, "permanentFail")
405         else:
406             super(RunnerContainer, self).done(container)
407         finally:
408             if record["uuid"] in self.arvrunner.processes:
409                 del self.arvrunner.processes[record["uuid"]]