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