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