19982: Add arv:failed_container_resubmitted property
[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.request, urllib.parse, urllib.error
9 import time
10 import datetime
11 import ciso8601
12 import uuid
13 import math
14 import re
15
16 import arvados_cwl.util
17 import ruamel.yaml
18
19 from cwltool.errors import WorkflowException
20 from cwltool.process import UnsupportedRequirement, shortname
21 from cwltool.utils import aslist, adjustFileObjs, adjustDirObjs, visit_class
22 from cwltool.job import JobBase
23
24 import arvados.collection
25
26 import crunchstat_summary.summarizer
27 import crunchstat_summary.reader
28
29 from .arvdocker import arv_docker_get_image
30 from . import done
31 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields, make_builder
32 from .fsaccess import CollectionFetcher
33 from .pathmapper import NoFollowPathMapper, trim_listing
34 from .perf import Perf
35 from ._version import __version__
36
37 logger = logging.getLogger('arvados.cwl-runner')
38 metrics = logging.getLogger('arvados.cwl-runner.metrics')
39
40 def cleanup_name_for_collection(name):
41     return name.replace("/", " ")
42
43 class ArvadosContainer(JobBase):
44     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
45
46     def __init__(self, runner, job_runtime, globpatterns,
47                  builder,   # type: Builder
48                  joborder,  # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
49                  make_path_mapper,  # type: Callable[..., PathMapper]
50                  requirements,      # type: List[Dict[Text, Text]]
51                  hints,     # type: List[Dict[Text, Text]]
52                  name       # type: Text
53     ):
54         super(ArvadosContainer, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
55         self.arvrunner = runner
56         self.job_runtime = job_runtime
57         self.running = False
58         self.uuid = None
59         self.attempt_count = 0
60         self.globpatterns = globpatterns
61
62     def update_pipeline_component(self, r):
63         pass
64
65     def _required_env(self):
66         env = {}
67         env["HOME"] = self.outdir
68         env["TMPDIR"] = self.tmpdir
69         return env
70
71     def run(self, toplevelRuntimeContext):
72         # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
73         # which calls makeJobRunner() to get a new ArvadosContainer
74         # object.  The fields that define execution such as
75         # command_line, environment, etc are set on the
76         # ArvadosContainer object by CommandLineTool.job() before
77         # run() is called.
78
79         runtimeContext = self.job_runtime
80
81         if runtimeContext.submit_request_uuid:
82             container_request = self.arvrunner.api.container_requests().get(
83                 uuid=runtimeContext.submit_request_uuid
84             ).execute(num_retries=self.arvrunner.num_retries)
85         else:
86             container_request = {}
87
88         container_request["command"] = self.command_line
89         container_request["name"] = self.name
90         container_request["output_path"] = self.outdir
91         container_request["cwd"] = self.outdir
92         container_request["priority"] = runtimeContext.priority
93         container_request["state"] = "Uncommitted"
94         container_request.setdefault("properties", {})
95
96         container_request["properties"]["cwl_input"] = self.joborder
97
98         runtime_constraints = {}
99
100         if runtimeContext.project_uuid:
101             container_request["owner_uuid"] = runtimeContext.project_uuid
102
103         if self.arvrunner.secret_store.has_secret(self.command_line):
104             raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
105
106         if self.arvrunner.secret_store.has_secret(self.environment):
107             raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
108
109         resources = self.builder.resources
110         if resources is not None:
111             runtime_constraints["vcpus"] = math.ceil(resources.get("cores", 1))
112             runtime_constraints["ram"] = math.ceil(resources.get("ram") * 2**20)
113
114         mounts = {
115             self.outdir: {
116                 "kind": "tmp",
117                 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
118             },
119             self.tmpdir: {
120                 "kind": "tmp",
121                 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
122             }
123         }
124         secret_mounts = {}
125         scheduling_parameters = {}
126
127         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
128         rf.sort(key=lambda k: k.resolved)
129         prevdir = None
130         for resolved, target, tp, stg in rf:
131             if not stg:
132                 continue
133             if prevdir and target.startswith(prevdir):
134                 continue
135             if tp == "Directory":
136                 targetdir = target
137             else:
138                 targetdir = os.path.dirname(target)
139             sp = resolved.split("/", 1)
140             pdh = sp[0][5:]   # remove "keep:"
141             mounts[targetdir] = {
142                 "kind": "collection",
143                 "portable_data_hash": pdh
144             }
145             if pdh in self.pathmapper.pdh_to_uuid:
146                 mounts[targetdir]["uuid"] = self.pathmapper.pdh_to_uuid[pdh]
147             if len(sp) == 2:
148                 if tp == "Directory":
149                     path = sp[1]
150                 else:
151                     path = os.path.dirname(sp[1])
152                 if path and path != "/":
153                     mounts[targetdir]["path"] = path
154             prevdir = targetdir + "/"
155
156         intermediate_collection_info = arvados_cwl.util.get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
157
158         with Perf(metrics, "generatefiles %s" % self.name):
159             if self.generatefiles["listing"]:
160                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
161                                                     keep_client=self.arvrunner.keep_client,
162                                                     num_retries=self.arvrunner.num_retries)
163                 generatemapper = NoFollowPathMapper(self.generatefiles["listing"], "", "",
164                                                     separateDirs=False)
165
166                 sorteditems = sorted(generatemapper.items(), key=lambda n: n[1].target)
167
168                 logger.debug("generatemapper is %s", sorteditems)
169
170                 with Perf(metrics, "createfiles %s" % self.name):
171                     for f, p in sorteditems:
172                         if not p.target:
173                             continue
174
175                         if p.target.startswith("/"):
176                             dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
177                         else:
178                             dst = p.target
179
180                         if p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
181                             if p.resolved.startswith("_:"):
182                                 vwd.mkdirs(dst)
183                             else:
184                                 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
185                                 vwd.copy(path or ".", dst, source_collection=source)
186                         elif p.type == "CreateFile":
187                             if self.arvrunner.secret_store.has_secret(p.resolved):
188                                 mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
189                                 secret_mounts[mountpoint] = {
190                                     "kind": "text",
191                                     "content": self.arvrunner.secret_store.retrieve(p.resolved)
192                                 }
193                             else:
194                                 with vwd.open(dst, "w") as n:
195                                     n.write(p.resolved)
196
197                 def keepemptydirs(p):
198                     if isinstance(p, arvados.collection.RichCollectionBase):
199                         if len(p) == 0:
200                             p.open(".keep", "w").close()
201                         else:
202                             for c in p:
203                                 keepemptydirs(p[c])
204
205                 keepemptydirs(vwd)
206
207                 if not runtimeContext.current_container:
208                     runtimeContext.current_container = arvados_cwl.util.get_current_container(self.arvrunner.api, self.arvrunner.num_retries, logger)
209                 vwd.save_new(name=intermediate_collection_info["name"],
210                              owner_uuid=runtimeContext.project_uuid,
211                              ensure_unique_name=True,
212                              trash_at=intermediate_collection_info["trash_at"],
213                              properties=intermediate_collection_info["properties"])
214
215                 prev = None
216                 for f, p in sorteditems:
217                     if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
218                         (prev is not None and p.target.startswith(prev))):
219                         continue
220                     if p.target.startswith("/"):
221                         dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
222                     else:
223                         dst = p.target
224                     mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
225                     mounts[mountpoint] = {"kind": "collection",
226                                           "portable_data_hash": vwd.portable_data_hash(),
227                                           "path": dst}
228                     if p.type.startswith("Writable"):
229                         mounts[mountpoint]["writable"] = True
230                     prev = p.target + "/"
231
232         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
233         if self.environment:
234             container_request["environment"].update(self.environment)
235
236         if self.stdin:
237             sp = self.stdin[6:].split("/", 1)
238             mounts["stdin"] = {"kind": "collection",
239                                 "portable_data_hash": sp[0],
240                                 "path": sp[1]}
241
242         if self.stderr:
243             mounts["stderr"] = {"kind": "file",
244                                 "path": "%s/%s" % (self.outdir, self.stderr)}
245
246         if self.stdout:
247             mounts["stdout"] = {"kind": "file",
248                                 "path": "%s/%s" % (self.outdir, self.stdout)}
249
250         (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
251
252         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
253                                                                     docker_req,
254                                                                     runtimeContext.pull_image,
255                                                                     runtimeContext)
256
257         network_req, _ = self.get_requirement("NetworkAccess")
258         if network_req:
259             runtime_constraints["API"] = network_req["networkAccess"]
260
261         api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
262         if api_req:
263             runtime_constraints["API"] = True
264
265         use_disk_cache = (self.arvrunner.api.config()["Containers"].get("DefaultKeepCacheRAM", 0) == 0)
266
267         keep_cache_type_req, _ = self.get_requirement("http://arvados.org/cwl#KeepCacheTypeRequirement")
268         if keep_cache_type_req:
269             if "keepCacheType" in keep_cache_type_req:
270                 if keep_cache_type_req["keepCacheType"] == "ram_cache":
271                     use_disk_cache = False
272
273         runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
274         if runtime_req:
275             if "keep_cache" in runtime_req:
276                 if use_disk_cache:
277                     # If DefaultKeepCacheRAM is zero it means we should use disk cache.
278                     runtime_constraints["keep_cache_disk"] = math.ceil(runtime_req["keep_cache"] * 2**20)
279                 else:
280                     runtime_constraints["keep_cache_ram"] = math.ceil(runtime_req["keep_cache"] * 2**20)
281             if "outputDirType" in runtime_req:
282                 if runtime_req["outputDirType"] == "local_output_dir":
283                     # Currently the default behavior.
284                     pass
285                 elif runtime_req["outputDirType"] == "keep_output_dir":
286                     mounts[self.outdir]= {
287                         "kind": "collection",
288                         "writable": True
289                     }
290
291         partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
292         if partition_req:
293             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
294
295         intermediate_output_req, _ = self.get_requirement("http://arvados.org/cwl#IntermediateOutput")
296         if intermediate_output_req:
297             self.output_ttl = intermediate_output_req["outputTTL"]
298         else:
299             self.output_ttl = self.arvrunner.intermediate_output_ttl
300
301         if self.output_ttl < 0:
302             raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
303
304
305         if self.arvrunner.api._rootDesc["revision"] >= "20210628":
306             storage_class_req, _ = self.get_requirement("http://arvados.org/cwl#OutputStorageClass")
307             if storage_class_req and storage_class_req.get("intermediateStorageClass"):
308                 container_request["output_storage_classes"] = aslist(storage_class_req["intermediateStorageClass"])
309             else:
310                 container_request["output_storage_classes"] = runtimeContext.intermediate_storage_classes.strip().split(",")
311
312         cuda_req, _ = self.get_requirement("http://commonwl.org/cwltool#CUDARequirement")
313         if cuda_req:
314             runtime_constraints["cuda"] = {
315                 "device_count": resources.get("cudaDeviceCount", 1),
316                 "driver_version": cuda_req["cudaVersionMin"],
317                 "hardware_capability": aslist(cuda_req["cudaComputeCapability"])[0]
318             }
319
320         if runtimeContext.enable_preemptible is False:
321             scheduling_parameters["preemptible"] = False
322         else:
323             preemptible_req, _ = self.get_requirement("http://arvados.org/cwl#UsePreemptible")
324             if preemptible_req:
325                 scheduling_parameters["preemptible"] = preemptible_req["usePreemptible"]
326             elif runtimeContext.enable_preemptible is True:
327                 scheduling_parameters["preemptible"] = True
328             elif runtimeContext.enable_preemptible is None:
329                 pass
330
331         if scheduling_parameters.get("preemptible") and self.may_resubmit_non_preemptible():
332             # Only make one attempt, because if it is preempted we
333             # will resubmit and ask for a non-preemptible instance.
334             container_request["container_count_max"] = 1
335
336         if self.timelimit is not None and self.timelimit > 0:
337             scheduling_parameters["max_run_time"] = self.timelimit
338
339         extra_submit_params = {}
340         if runtimeContext.submit_runner_cluster:
341             extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
342
343         container_request["output_name"] = cleanup_name_for_collection("Output from step %s" % (self.name))
344         container_request["output_ttl"] = self.output_ttl
345         container_request["mounts"] = mounts
346         container_request["secret_mounts"] = secret_mounts
347         container_request["runtime_constraints"] = runtime_constraints
348         container_request["scheduling_parameters"] = scheduling_parameters
349
350         enable_reuse = runtimeContext.enable_reuse
351         if enable_reuse:
352             reuse_req, _ = self.get_requirement("WorkReuse")
353             if reuse_req:
354                 enable_reuse = reuse_req["enableReuse"]
355             reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
356             if reuse_req:
357                 enable_reuse = reuse_req["enableReuse"]
358         container_request["use_existing"] = enable_reuse
359
360         properties_req, _ = self.get_requirement("http://arvados.org/cwl#ProcessProperties")
361         if properties_req:
362             for pr in properties_req["processProperties"]:
363                 container_request["properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
364
365         output_properties_req, _ = self.get_requirement("http://arvados.org/cwl#OutputCollectionProperties")
366         if output_properties_req:
367             if self.arvrunner.api._rootDesc["revision"] >= "20220510":
368                 container_request["output_properties"] = {}
369                 for pr in output_properties_req["outputProperties"]:
370                     container_request["output_properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
371             else:
372                 logger.warning("%s API revision is %s, revision %s is required to support setting properties on output collections.",
373                                self.arvrunner.label(self), self.arvrunner.api._rootDesc["revision"], "20220510")
374
375         if self.arvrunner.api._rootDesc["revision"] >= "20240502" and self.globpatterns:
376             output_glob = []
377             for gb in self.globpatterns:
378                 gb = self.builder.do_eval(gb)
379                 if not gb:
380                     continue
381                 for gbeval in aslist(gb):
382                     if gbeval.startswith(self.outdir+"/"):
383                         gbeval = gbeval[len(self.outdir)+1:]
384                     while gbeval.startswith("./"):
385                         gbeval = gbeval[2:]
386
387                     if gbeval in (self.outdir, "", "."):
388                         output_glob.append("**")
389                     elif gbeval.endswith("/"):
390                         output_glob.append(gbeval+"**")
391                     else:
392                         output_glob.append(gbeval)
393                         output_glob.append(gbeval + "/**")
394
395             if "**" in output_glob:
396                 # if it's going to match all, prefer not to provide it
397                 # at all.
398                 output_glob.clear()
399
400             if output_glob:
401                 # Tools should either use cwl.output.json or
402                 # outputBinding globs. However, one CWL conformance
403                 # test has both, so we need to make sure we collect
404                 # cwl.output.json in this case. That test uses
405                 # cwl.output.json return a string, but also uses
406                 # outputBinding.
407                 output_glob.append("cwl.output.json")
408
409                 # It could happen that a tool creates cwl.output.json,
410                 # references a file, but also uses a outputBinding
411                 # glob that doesn't include the file being referenced.
412                 #
413                 # In this situation, output_glob will only match the
414                 # pattern we know about.  If cwl.output.json referred
415                 # to other files in the output, those would be
416                 # missing.  We could upload the entire output, but we
417                 # currently have no way of knowing at this point
418                 # whether cwl.output.json will be used this way.
419                 #
420                 # Because this is a corner case, I'm inclined to leave
421                 # this as a known issue for now.  No conformance tests
422                 # do this and I'd even be inclined to have it ruled
423                 # incompatible in the CWL spec if it did come up.
424                 # That said, in retrospect it would have been good to
425                 # require CommandLineTool to declare when it expects
426                 # cwl.output.json.
427
428                 container_request["output_glob"] = output_glob
429
430         ram_multiplier = [1]
431
432         oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
433         if oom_retry_req:
434             if oom_retry_req.get('memoryRetryMultiplier'):
435                 ram_multiplier.append(oom_retry_req.get('memoryRetryMultiplier'))
436             elif oom_retry_req.get('memoryRetryMultipler'):
437                 ram_multiplier.append(oom_retry_req.get('memoryRetryMultipler'))
438             else:
439                 ram_multiplier.append(2)
440
441         if runtimeContext.runnerjob.startswith("arvwf:"):
442             wfuuid = runtimeContext.runnerjob[6:runtimeContext.runnerjob.index("#")]
443             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
444             if container_request["name"] == "main":
445                 container_request["name"] = wfrecord["name"]
446             container_request["properties"]["template_uuid"] = wfuuid
447
448         if self.attempt_count == 0:
449             self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
450
451         try:
452             ram = runtime_constraints["ram"]
453
454             self.uuid = runtimeContext.submit_request_uuid
455
456             for i in ram_multiplier:
457                 runtime_constraints["ram"] = ram * i
458
459                 if self.uuid:
460                     response = self.arvrunner.api.container_requests().update(
461                         uuid=self.uuid,
462                         body=container_request,
463                         **extra_submit_params
464                     ).execute(num_retries=self.arvrunner.num_retries)
465                 else:
466                     response = self.arvrunner.api.container_requests().create(
467                         body=container_request,
468                         **extra_submit_params
469                     ).execute(num_retries=self.arvrunner.num_retries)
470                     self.uuid = response["uuid"]
471
472                 if response["container_uuid"] is not None:
473                     break
474
475             if response["container_uuid"] is None:
476                 runtime_constraints["ram"] = ram * ram_multiplier[self.attempt_count]
477
478             container_request["state"] = "Committed"
479             response = self.arvrunner.api.container_requests().update(
480                 uuid=self.uuid,
481                 body=container_request,
482                 **extra_submit_params
483             ).execute(num_retries=self.arvrunner.num_retries)
484
485             self.arvrunner.process_submitted(self)
486             self.attempt_count += 1
487
488             if response["state"] == "Final":
489                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
490             else:
491                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
492         except Exception as e:
493             logger.exception("%s error submitting container\n%s", self.arvrunner.label(self), e)
494             logger.debug("Container request was %s", container_request)
495             self.output_callback({}, "permanentFail")
496
497     def may_resubmit_non_preemptible(self):
498         if self.job_runtime.enable_resubmit_non_preemptible is False:
499             # explicitly disabled
500             return False
501
502         spot_instance_retry_req, _ = self.get_requirement("http://arvados.org/cwl#PreemptionBehavior")
503         if spot_instance_retry_req:
504             if spot_instance_retry_req["resubmitNonPreemptible"] is False:
505                 # explicitly disabled by hint
506                 return False
507         elif self.job_runtime.enable_resubmit_non_preemptible is None:
508             # default behavior is we don't retry
509             return False
510
511         # At this point, by process of elimination either
512         # resubmitNonPreemptible or enable_resubmit_non_preemptible
513         # must be True, so now check if the container was actually
514         # preempted.
515
516         return True
517
518     def spot_instance_retry(self, record, container):
519         return self.may_resubmit_non_preemptible() and bool(container["runtime_status"].get("preemptionNotice"))
520
521     def out_of_memory_retry(self, record, container):
522         oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
523         if oom_retry_req is None:
524             return False
525
526         # Sometimes it gets killed with no warning
527         if container["exit_code"] == 137:
528             return True
529
530         logc = arvados.collection.CollectionReader(record["log_uuid"],
531                                                    api_client=self.arvrunner.api,
532                                                    keep_client=self.arvrunner.keep_client,
533                                                    num_retries=self.arvrunner.num_retries)
534
535         loglines = [""]
536         def callback(v1, v2, v3):
537             loglines[0] = v3
538
539         done.logtail(logc, callback, "", maxlen=1000)
540
541         # Check allocation failure
542         oom_matches = oom_retry_req.get('memoryErrorRegex') or r'(bad_alloc|out ?of ?memory|memory ?error|container using over 9.% of memory)'
543         if re.search(oom_matches, loglines[0], re.IGNORECASE | re.MULTILINE):
544             return True
545
546         return False
547
548     def done(self, record):
549         outputs = {}
550         retried = False
551         rcode = None
552         do_retry = False
553
554         try:
555             container = self.arvrunner.api.containers().get(
556                 uuid=record["container_uuid"]
557             ).execute(num_retries=self.arvrunner.num_retries)
558
559             if container["state"] == "Complete":
560                 rcode = container["exit_code"]
561                 if self.successCodes and rcode in self.successCodes:
562                     processStatus = "success"
563                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
564                     processStatus = "temporaryFail"
565                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
566                     processStatus = "permanentFail"
567                 elif rcode == 0:
568                     processStatus = "success"
569                 else:
570                     processStatus = "permanentFail"
571
572                 if processStatus == "permanentFail" and self.attempt_count == 1 and self.out_of_memory_retry(record, container):
573                     logger.info("%s Container failed with out of memory error.  Retrying container with more RAM.",
574                                  self.arvrunner.label(self))
575                     self.job_runtime = self.job_runtime.copy()
576                     do_retry = True
577
578                 if rcode == 137 and not do_retry:
579                     logger.warning("%s Container may have been killed for using too much RAM.  Try resubmitting with a higher 'ramMin' or use the arv:OutOfMemoryRetry feature.",
580                                  self.arvrunner.label(self))
581             else:
582                 processStatus = "permanentFail"
583
584             if processStatus == "permanentFail" and self.attempt_count == 1 and self.spot_instance_retry(record, container):
585                 logger.info("%s Container failed because the preemptible instance it was running on was reclaimed.  Retrying container on a non-preemptible instance.")
586                 self.job_runtime = self.job_runtime.copy()
587                 self.job_runtime.enable_preemptible = False
588                 do_retry = True
589
590             if do_retry:
591                 # Add a property indicating that this container was resubmitted.
592                 updateproperties = record["properties"].copy()
593                 olduuid = self.uuid
594                 self.job_runtime.submit_request_uuid = None
595                 self.uuid = None
596                 self.run(None)
597                 # this flag suppresses calling the output callback, we only want to set this
598                 # when we're sure that the resubmission has happened without issue.
599                 retried = True
600                 # Add a property to the old container request indicating it
601                 # was retried
602                 updateproperties["arv:failed_container_resubmitted"] = self.uuid
603                 self.arvrunner.api.container_requests().update(uuid=olduuid,
604                                                                body={"properties": updateproperties}).execute()
605                 return
606
607             logc = None
608             if record["log_uuid"]:
609                 logc = arvados.collection.Collection(record["log_uuid"],
610                                                      api_client=self.arvrunner.api,
611                                                      keep_client=self.arvrunner.keep_client,
612                                                      num_retries=self.arvrunner.num_retries)
613
614             if processStatus == "permanentFail" and logc is not None:
615                 label = self.arvrunner.label(self)
616                 done.logtail(
617                     logc, logger.error,
618                     "%s (%s) error log:" % (label, record["uuid"]), maxlen=40, include_crunchrun=(rcode is None or rcode > 127))
619
620             if record["output_uuid"]:
621                 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
622                     # Compute the trash time to avoid requesting the collection record.
623                     trash_at = ciso8601.parse_datetime_as_naive(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
624                     aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
625                     orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
626                     oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
627                     logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
628                         self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
629                 self.arvrunner.add_intermediate_output(record["output_uuid"])
630
631             if container["output"]:
632                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
633
634             properties = record["properties"].copy()
635             properties["cwl_output"] = outputs
636             self.arvrunner.api.container_requests().update(
637                 uuid=self.uuid,
638                 body={"container_request": {"properties": properties}}
639             ).execute(num_retries=self.arvrunner.num_retries)
640
641             if logc is not None and self.job_runtime.enable_usage_report is not False:
642                 try:
643                     summarizer = crunchstat_summary.summarizer.ContainerRequestSummarizer(
644                         record,
645                         collection_object=logc,
646                         label=self.name,
647                         arv=self.arvrunner.api)
648                     summarizer.run()
649                     with logc.open("usage_report.html", "wt") as mr:
650                         mr.write(summarizer.html_report())
651                     logc.save()
652
653                     # Post warnings about nodes that are under-utilized.
654                     for rc in summarizer._recommend_gen(lambda x: x):
655                         self.job_runtime.usage_report_notes.append(rc)
656
657                 except Exception as e:
658                     logger.warning("%s unable to generate resource usage report",
659                                  self.arvrunner.label(self),
660                                  exc_info=(e if self.arvrunner.debug else False))
661
662         except WorkflowException as e:
663             # Only include a stack trace if in debug mode.
664             # A stack trace may obfuscate more useful output about the workflow.
665             logger.error("%s unable to collect output from %s:\n%s",
666                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
667             processStatus = "permanentFail"
668         except Exception:
669             logger.exception("%s while getting output object:", self.arvrunner.label(self))
670             processStatus = "permanentFail"
671         finally:
672             if not retried:
673                 self.output_callback(outputs, processStatus)
674
675
676 class RunnerContainer(Runner):
677     """Submit and manage a container that runs arvados-cwl-runner."""
678
679     def arvados_job_spec(self, runtimeContext, git_info):
680         """Create an Arvados container request for this workflow.
681
682         The returned dict can be used to create a container passed as
683         the +body+ argument to container_requests().create().
684         """
685
686         adjustDirObjs(self.job_order, trim_listing)
687         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
688         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
689
690         secret_mounts = {}
691         for param in sorted(self.job_order.keys()):
692             if self.secret_store.has_secret(self.job_order[param]):
693                 mnt = "/secrets/s%d" % len(secret_mounts)
694                 secret_mounts[mnt] = {
695                     "kind": "text",
696                     "content": self.secret_store.retrieve(self.job_order[param])
697                 }
698                 self.job_order[param] = {"$include": mnt}
699
700         container_image = arvados_jobs_image(self.arvrunner, self.jobs_image, runtimeContext)
701
702         workflow_runner_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#WorkflowRunnerResources")
703         if workflow_runner_req and workflow_runner_req.get("acrContainerImage"):
704             container_image = workflow_runner_req.get("acrContainerImage")
705
706         container_req = {
707             "name": self.name,
708             "output_path": "/var/spool/cwl",
709             "cwd": "/var/spool/cwl",
710             "priority": self.priority,
711             "state": "Committed",
712             "container_image": container_image,
713             "mounts": {
714                 "/var/lib/cwl/cwl.input.json": {
715                     "kind": "json",
716                     "content": self.job_order
717                 },
718                 "stdout": {
719                     "kind": "file",
720                     "path": "/var/spool/cwl/cwl.output.json"
721                 },
722                 "/var/spool/cwl": {
723                     "kind": "collection",
724                     "writable": True
725                 }
726             },
727             "secret_mounts": secret_mounts,
728             "runtime_constraints": {
729                 "vcpus": math.ceil(self.submit_runner_cores),
730                 "ram": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),
731                 "API": True
732             },
733             "use_existing": self.reuse_runner,
734             "properties": {}
735         }
736
737         if self.embedded_tool.tool.get("id", "").startswith("keep:"):
738             sp = self.embedded_tool.tool["id"].split('/')
739             workflowcollection = sp[0][5:]
740             workflowname = "/".join(sp[1:])
741             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
742             container_req["mounts"]["/var/lib/cwl/workflow"] = {
743                 "kind": "collection",
744                 "portable_data_hash": "%s" % workflowcollection
745             }
746         elif self.embedded_tool.tool.get("id", "").startswith("arvwf:"):
747             uuid, frg = urllib.parse.urldefrag(self.embedded_tool.tool["id"])
748             workflowpath = "/var/lib/cwl/workflow.json#" + frg
749             packedtxt = self.loadingContext.loader.fetch_text(uuid)
750             yaml = ruamel.yaml.YAML(typ='safe', pure=True)
751             packed = yaml.load(packedtxt)
752             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
753                 "kind": "json",
754                 "content": packed
755             }
756             container_req["properties"]["template_uuid"] = self.embedded_tool.tool["id"][6:33]
757         elif self.embedded_tool.tool.get("id", "").startswith("file:"):
758             raise WorkflowException("Tool id '%s' is a local file but expected keep: or arvwf:" % self.embedded_tool.tool.get("id"))
759         else:
760             main = self.loadingContext.loader.idx["_:main"]
761             if main.get("id") == "_:main":
762                 del main["id"]
763             workflowpath = "/var/lib/cwl/workflow.json#main"
764             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
765                 "kind": "json",
766                 "content": main
767             }
768
769         container_req["properties"].update({k.replace("http://arvados.org/cwl#", "arv:"): v for k, v in git_info.items()})
770
771         properties_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#ProcessProperties")
772         if properties_req:
773             builder = make_builder(self.job_order, self.embedded_tool.hints, self.embedded_tool.requirements, runtimeContext, self.embedded_tool.metadata)
774             for pr in properties_req["processProperties"]:
775                 container_req["properties"][pr["propertyName"]] = builder.do_eval(pr["propertyValue"])
776
777         # --local means execute the workflow instead of submitting a container request
778         # --api=containers means use the containers API
779         # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
780         # --disable-validate because we already validated so don't need to do it again
781         # --eval-timeout is the timeout for javascript invocation
782         # --parallel-task-count is the number of threads to use for job submission
783         # --enable/disable-reuse sets desired job reuse
784         # --collection-cache-size sets aside memory to store collections
785         command = ["arvados-cwl-runner",
786                    "--local",
787                    "--api=containers",
788                    "--no-log-timestamps",
789                    "--disable-validate",
790                    "--disable-color",
791                    "--eval-timeout=%s" % self.arvrunner.eval_timeout,
792                    "--thread-count=%s" % self.arvrunner.thread_count,
793                    "--enable-reuse" if self.enable_reuse else "--disable-reuse",
794                    "--collection-cache-size=%s" % self.collection_cache_size]
795
796         if self.output_name:
797             command.append("--output-name=" + self.output_name)
798             container_req["output_name"] = self.output_name
799
800         if self.output_tags:
801             command.append("--output-tags=" + self.output_tags)
802
803         if runtimeContext.debug:
804             command.append("--debug")
805
806         if runtimeContext.storage_classes != "default" and runtimeContext.storage_classes:
807             command.append("--storage-classes=" + runtimeContext.storage_classes)
808
809         if runtimeContext.intermediate_storage_classes != "default" and runtimeContext.intermediate_storage_classes:
810             command.append("--intermediate-storage-classes=" + runtimeContext.intermediate_storage_classes)
811
812         if runtimeContext.on_error:
813             command.append("--on-error=" + self.on_error)
814
815         if runtimeContext.intermediate_output_ttl:
816             command.append("--intermediate-output-ttl=%d" % runtimeContext.intermediate_output_ttl)
817
818         if runtimeContext.trash_intermediate:
819             command.append("--trash-intermediate")
820
821         if runtimeContext.project_uuid:
822             command.append("--project-uuid="+runtimeContext.project_uuid)
823
824         if self.enable_dev:
825             command.append("--enable-dev")
826
827         if runtimeContext.enable_preemptible is True:
828             command.append("--enable-preemptible")
829
830         if runtimeContext.enable_preemptible is False:
831             command.append("--disable-preemptible")
832
833         if runtimeContext.varying_url_params:
834             command.append("--varying-url-params="+runtimeContext.varying_url_params)
835
836         if runtimeContext.prefer_cached_downloads:
837             command.append("--prefer-cached-downloads")
838
839         if runtimeContext.enable_usage_report is True:
840             command.append("--enable-usage-report")
841
842         if runtimeContext.enable_usage_report is False:
843             command.append("--disable-usage-report")
844
845         if self.fast_parser:
846             command.append("--fast-parser")
847
848         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
849
850         container_req["command"] = command
851
852         return container_req
853
854
855     def run(self, runtimeContext):
856         runtimeContext.keepprefix = "keep:"
857         job_spec = self.arvados_job_spec(runtimeContext, self.git_info)
858         if runtimeContext.project_uuid:
859             job_spec["owner_uuid"] = runtimeContext.project_uuid
860
861         extra_submit_params = {}
862         if runtimeContext.submit_runner_cluster:
863             extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
864
865         if runtimeContext.submit_request_uuid:
866             if "cluster_id" in extra_submit_params:
867                 # Doesn't make sense for "update" and actually fails
868                 del extra_submit_params["cluster_id"]
869             response = self.arvrunner.api.container_requests().update(
870                 uuid=runtimeContext.submit_request_uuid,
871                 body=job_spec,
872                 **extra_submit_params
873             ).execute(num_retries=self.arvrunner.num_retries)
874         else:
875             response = self.arvrunner.api.container_requests().create(
876                 body=job_spec,
877                 **extra_submit_params
878             ).execute(num_retries=self.arvrunner.num_retries)
879
880         self.uuid = response["uuid"]
881         self.arvrunner.process_submitted(self)
882
883         logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
884
885         workbench2 = self.arvrunner.api.config()["Services"]["Workbench2"]["ExternalURL"]
886         if workbench2:
887             url = "{}processes/{}".format(workbench2, response["uuid"])
888             logger.info("Monitor workflow progress at %s", url)
889
890
891     def done(self, record):
892         try:
893             container = self.arvrunner.api.containers().get(
894                 uuid=record["container_uuid"]
895             ).execute(num_retries=self.arvrunner.num_retries)
896             container["log"] = record["log_uuid"]
897         except Exception:
898             logger.exception("%s while getting runner container", self.arvrunner.label(self))
899             self.arvrunner.output_callback({}, "permanentFail")
900         else:
901             super(RunnerContainer, self).done(container)