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