Merge branch '12764-writable-file' refs #12764
[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                 logger.debug("generatemapper is %s", generatemapper._pathmap)
109
110                 with Perf(metrics, "createfiles %s" % self.name):
111                     for f, p in generatemapper.items():
112                         if not p.target:
113                             pass
114                         elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
115                             if p.resolved.startswith("_:"):
116                                 vwd.mkdirs(p.target)
117                             else:
118                                 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
119                                 vwd.copy(path, p.target, source_collection=source)
120                         elif p.type == "CreateFile":
121                             with vwd.open(p.target, "w") as n:
122                                 n.write(p.resolved.encode("utf-8"))
123
124                 def keepemptydirs(p):
125                     if isinstance(p, arvados.collection.RichCollectionBase):
126                         if len(p) == 0:
127                             p.open(".keep", "w").close()
128                         else:
129                             for c in p:
130                                 keepemptydirs(p[c])
131
132                 keepemptydirs(vwd)
133
134                 with Perf(metrics, "generatefiles.save_new %s" % self.name):
135                     vwd.save_new()
136
137                 for f, p in generatemapper.items():
138                     if not p.target:
139                         continue
140                     mountpoint = "%s/%s" % (self.outdir, p.target)
141                     mounts[mountpoint] = {"kind": "collection",
142                                           "portable_data_hash": vwd.portable_data_hash(),
143                                           "path": p.target}
144                     if p.type.startswith("Writable"):
145                         mounts[mountpoint]["writable"] = True
146
147         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
148         if self.environment:
149             container_request["environment"].update(self.environment)
150
151         if self.stdin:
152             sp = self.stdin[6:].split("/", 1)
153             mounts["stdin"] = {"kind": "collection",
154                                 "portable_data_hash": sp[0],
155                                 "path": sp[1]}
156
157         if self.stderr:
158             mounts["stderr"] = {"kind": "file",
159                                 "path": "%s/%s" % (self.outdir, self.stderr)}
160
161         if self.stdout:
162             mounts["stdout"] = {"kind": "file",
163                                 "path": "%s/%s" % (self.outdir, self.stdout)}
164
165         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
166         if not docker_req:
167             docker_req = {"dockerImageId": "arvados/jobs"}
168
169         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
170                                                                      docker_req,
171                                                                      pull_image,
172                                                                      self.arvrunner.project_uuid)
173
174         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
175         if api_req:
176             runtime_constraints["API"] = True
177
178         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
179         if runtime_req:
180             if "keep_cache" in runtime_req:
181                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
182             if "outputDirType" in runtime_req:
183                 if runtime_req["outputDirType"] == "local_output_dir":
184                     # Currently the default behavior.
185                     pass
186                 elif runtime_req["outputDirType"] == "keep_output_dir":
187                     mounts[self.outdir]= {
188                         "kind": "collection",
189                         "writable": True
190                     }
191
192         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
193         if partition_req:
194             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
195
196         intermediate_output_req, _ = get_feature(self, "http://arvados.org/cwl#IntermediateOutput")
197         if intermediate_output_req:
198             self.output_ttl = intermediate_output_req["outputTTL"]
199         else:
200             self.output_ttl = self.arvrunner.intermediate_output_ttl
201
202         if self.output_ttl < 0:
203             raise WorkflowError("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
204
205         container_request["output_ttl"] = self.output_ttl
206         container_request["mounts"] = mounts
207         container_request["runtime_constraints"] = runtime_constraints
208         container_request["scheduling_parameters"] = scheduling_parameters
209
210         enable_reuse = kwargs.get("enable_reuse", True)
211         if enable_reuse:
212             reuse_req, _ = get_feature(self, "http://arvados.org/cwl#ReuseRequirement")
213             if reuse_req:
214                 enable_reuse = reuse_req["enableReuse"]
215         container_request["use_existing"] = enable_reuse
216
217         if kwargs.get("runnerjob", "").startswith("arvwf:"):
218             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
219             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
220             if container_request["name"] == "main":
221                 container_request["name"] = wfrecord["name"]
222             container_request["properties"]["template_uuid"] = wfuuid
223
224         try:
225             response = self.arvrunner.api.container_requests().create(
226                 body=container_request
227             ).execute(num_retries=self.arvrunner.num_retries)
228
229             self.uuid = response["uuid"]
230             self.arvrunner.processes[self.uuid] = self
231
232             if response["state"] == "Final":
233                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
234                 self.done(response)
235             else:
236                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
237         except Exception as e:
238             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
239             self.output_callback({}, "permanentFail")
240
241     def done(self, record):
242         outputs = {}
243         try:
244             container = self.arvrunner.api.containers().get(
245                 uuid=record["container_uuid"]
246             ).execute(num_retries=self.arvrunner.num_retries)
247             if container["state"] == "Complete":
248                 rcode = container["exit_code"]
249                 if self.successCodes and rcode in self.successCodes:
250                     processStatus = "success"
251                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
252                     processStatus = "temporaryFail"
253                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
254                     processStatus = "permanentFail"
255                 elif rcode == 0:
256                     processStatus = "success"
257                 else:
258                     processStatus = "permanentFail"
259             else:
260                 processStatus = "permanentFail"
261
262             if processStatus == "permanentFail":
263                 logc = arvados.collection.CollectionReader(container["log"],
264                                                            api_client=self.arvrunner.api,
265                                                            keep_client=self.arvrunner.keep_client,
266                                                            num_retries=self.arvrunner.num_retries)
267                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
268
269             if record["output_uuid"]:
270                 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
271                     # Compute the trash time to avoid requesting the collection record.
272                     trash_at = ciso8601.parse_datetime_unaware(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
273                     aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
274                     orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
275                     oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
276                     logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
277                         self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
278                 self.arvrunner.add_intermediate_output(record["output_uuid"])
279
280             if container["output"]:
281                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
282         except WorkflowException as e:
283             logger.error("%s unable to collect output from %s:\n%s",
284                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
285             processStatus = "permanentFail"
286         except Exception as e:
287             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
288             processStatus = "permanentFail"
289         finally:
290             self.output_callback(outputs, processStatus)
291             if record["uuid"] in self.arvrunner.processes:
292                 del self.arvrunner.processes[record["uuid"]]
293
294
295 class RunnerContainer(Runner):
296     """Submit and manage a container that runs arvados-cwl-runner."""
297
298     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
299         """Create an Arvados container request for this workflow.
300
301         The returned dict can be used to create a container passed as
302         the +body+ argument to container_requests().create().
303         """
304
305         adjustDirObjs(self.job_order, trim_listing)
306         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
307         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
308
309         container_req = {
310             "owner_uuid": self.arvrunner.project_uuid,
311             "name": self.name,
312             "output_path": "/var/spool/cwl",
313             "cwd": "/var/spool/cwl",
314             "priority": 1,
315             "state": "Committed",
316             "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
317             "mounts": {
318                 "/var/lib/cwl/cwl.input.json": {
319                     "kind": "json",
320                     "content": self.job_order
321                 },
322                 "stdout": {
323                     "kind": "file",
324                     "path": "/var/spool/cwl/cwl.output.json"
325                 },
326                 "/var/spool/cwl": {
327                     "kind": "collection",
328                     "writable": True
329                 }
330             },
331             "runtime_constraints": {
332                 "vcpus": 1,
333                 "ram": 1024*1024 * self.submit_runner_ram,
334                 "API": True
335             },
336             "use_existing": self.enable_reuse,
337             "properties": {}
338         }
339
340         if self.tool.tool.get("id", "").startswith("keep:"):
341             sp = self.tool.tool["id"].split('/')
342             workflowcollection = sp[0][5:]
343             workflowname = "/".join(sp[1:])
344             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
345             container_req["mounts"]["/var/lib/cwl/workflow"] = {
346                 "kind": "collection",
347                 "portable_data_hash": "%s" % workflowcollection
348             }
349         else:
350             packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
351             workflowpath = "/var/lib/cwl/workflow.json#main"
352             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
353                 "kind": "json",
354                 "content": packed
355             }
356             if self.tool.tool.get("id", "").startswith("arvwf:"):
357                 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
358
359
360         command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
361         if self.output_name:
362             command.append("--output-name=" + self.output_name)
363             container_req["output_name"] = self.output_name
364
365         if self.output_tags:
366             command.append("--output-tags=" + self.output_tags)
367
368         if kwargs.get("debug"):
369             command.append("--debug")
370
371         if self.enable_reuse:
372             command.append("--enable-reuse")
373         else:
374             command.append("--disable-reuse")
375
376         if self.on_error:
377             command.append("--on-error=" + self.on_error)
378
379         if self.intermediate_output_ttl:
380             command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
381
382         if self.arvrunner.trash_intermediate:
383             command.append("--trash-intermediate")
384
385         if self.arvrunner.project_uuid:
386             command.append("--project-uuid="+self.arvrunner.project_uuid)
387
388         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
389
390         container_req["command"] = command
391
392         return container_req
393
394
395     def run(self, *args, **kwargs):
396         kwargs["keepprefix"] = "keep:"
397         job_spec = self.arvados_job_spec(*args, **kwargs)
398         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
399
400         response = self.arvrunner.api.container_requests().create(
401             body=job_spec
402         ).execute(num_retries=self.arvrunner.num_retries)
403
404         self.uuid = response["uuid"]
405         self.arvrunner.processes[self.uuid] = self
406
407         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
408
409         if response["state"] == "Final":
410             self.done(response)
411
412     def done(self, record):
413         try:
414             container = self.arvrunner.api.containers().get(
415                 uuid=record["container_uuid"]
416             ).execute(num_retries=self.arvrunner.num_retries)
417         except Exception as e:
418             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
419             self.arvrunner.output_callback({}, "permanentFail")
420         else:
421             super(RunnerContainer, self).done(container)
422         finally:
423             if record["uuid"] in self.arvrunner.processes:
424                 del self.arvrunner.processes[record["uuid"]]