1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
8 import urllib.request, urllib.parse, urllib.error
16 import arvados_cwl.util
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
24 import arvados.collection
26 import crunchstat_summary.summarizer
27 import crunchstat_summary.reader
29 from .arvdocker import arv_docker_get_image
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__
37 logger = logging.getLogger('arvados.cwl-runner')
38 metrics = logging.getLogger('arvados.cwl-runner.metrics')
40 def cleanup_name_for_collection(name):
41 return name.replace("/", " ")
43 class ArvadosContainer(JobBase):
44 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
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]]
54 super(ArvadosContainer, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
55 self.arvrunner = runner
56 self.job_runtime = job_runtime
59 self.attempt_count = 0
60 self.globpatterns = globpatterns
62 def update_pipeline_component(self, r):
65 def _required_env(self):
67 env["HOME"] = self.outdir
68 env["TMPDIR"] = self.tmpdir
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
79 runtimeContext = self.job_runtime
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)
86 container_request = {}
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", {})
96 container_request["properties"]["cwl_input"] = self.joborder
98 runtime_constraints = {}
100 if runtimeContext.project_uuid:
101 container_request["owner_uuid"] = runtimeContext.project_uuid
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")
106 if self.arvrunner.secret_store.has_secret(self.environment):
107 raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
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)
117 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
121 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
125 scheduling_parameters = {}
127 rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
128 rf.sort(key=lambda k: k.resolved)
130 for resolved, target, tp, stg in rf:
133 if prevdir and target.startswith(prevdir):
135 if tp == "Directory":
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
145 if pdh in self.pathmapper.pdh_to_uuid:
146 mounts[targetdir]["uuid"] = self.pathmapper.pdh_to_uuid[pdh]
148 if tp == "Directory":
151 path = os.path.dirname(sp[1])
152 if path and path != "/":
153 mounts[targetdir]["path"] = path
154 prevdir = targetdir + "/"
156 intermediate_collection_info = arvados_cwl.util.get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
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"], "", "",
166 sorteditems = sorted(generatemapper.items(), key=lambda n: n[1].target)
168 logger.debug("generatemapper is %s", sorteditems)
170 with Perf(metrics, "createfiles %s" % self.name):
171 for f, p in sorteditems:
175 if p.target.startswith("/"):
176 dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
180 if p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
181 if p.resolved.startswith("_:"):
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] = {
191 "content": self.arvrunner.secret_store.retrieve(p.resolved)
194 with vwd.open(dst, "w") as n:
197 def keepemptydirs(p):
198 if isinstance(p, arvados.collection.RichCollectionBase):
200 p.open(".keep", "w").close()
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"])
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))):
220 if p.target.startswith("/"):
221 dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
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(),
228 if p.type.startswith("Writable"):
229 mounts[mountpoint]["writable"] = True
230 prev = p.target + "/"
232 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
234 container_request["environment"].update(self.environment)
237 sp = self.stdin[6:].split("/", 1)
238 mounts["stdin"] = {"kind": "collection",
239 "portable_data_hash": sp[0],
243 mounts["stderr"] = {"kind": "file",
244 "path": "%s/%s" % (self.outdir, self.stderr)}
247 mounts["stdout"] = {"kind": "file",
248 "path": "%s/%s" % (self.outdir, self.stdout)}
250 (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
252 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
254 runtimeContext.pull_image,
257 network_req, _ = self.get_requirement("NetworkAccess")
259 runtime_constraints["API"] = network_req["networkAccess"]
261 api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
263 runtime_constraints["API"] = True
265 use_disk_cache = (self.arvrunner.api.config()["Containers"].get("DefaultKeepCacheRAM", 0) == 0)
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
273 runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
275 if "keep_cache" in runtime_req:
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)
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.
285 elif runtime_req["outputDirType"] == "keep_output_dir":
286 mounts[self.outdir]= {
287 "kind": "collection",
291 partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
293 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
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"]
299 self.output_ttl = self.arvrunner.intermediate_output_ttl
301 if self.output_ttl < 0:
302 raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
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"])
310 container_request["output_storage_classes"] = runtimeContext.intermediate_storage_classes.strip().split(",")
312 cuda_req, _ = self.get_requirement("http://commonwl.org/cwltool#CUDARequirement")
314 if self.arvrunner.api._rootDesc["revision"] >= "20250128":
316 runtime_constraints["gpu"] = {
318 "device_count": resources.get("cudaDeviceCount", 1),
319 "driver_version": cuda_req["cudaVersionMin"],
320 "hardware_target": aslist(cuda_req["cudaComputeCapability"]),
321 "vram": cuda_req["cudaVram"]*1024*1024,
325 runtime_constraints["cuda"] = {
326 "device_count": resources.get("cudaDeviceCount", 1),
327 "driver_version": cuda_req["cudaVersionMin"],
328 "hardware_capability": aslist(cuda_req["cudaComputeCapability"])[0]
331 rocm_req, _ = self.get_requirement("http://arvados.org/cwl#ROCmRequirement")
333 if self.arvrunner.api._rootDesc["revision"] >= "20250128":
334 runtime_constraints["gpu"] = {
336 "device_count": rocm_req["rocmDeviceCountMin"],
337 "driver_version": rocm_req["rocmDriverVersion"],
338 "hardware_target": aslist(rocm_req["rocmTarget"]),
339 "vram": rocm_req["rocmVram"]*1024*1024,
342 raise WorkflowException("Arvados API server does not support ROCm (requires Arvados 3.1+)")
344 if runtimeContext.enable_preemptible is False:
345 scheduling_parameters["preemptible"] = False
347 preemptible_req, _ = self.get_requirement("http://arvados.org/cwl#UsePreemptible")
349 scheduling_parameters["preemptible"] = preemptible_req["usePreemptible"]
350 elif runtimeContext.enable_preemptible is True:
351 scheduling_parameters["preemptible"] = True
352 elif runtimeContext.enable_preemptible is None:
355 if scheduling_parameters.get("preemptible") and self.may_resubmit_non_preemptible():
356 # Only make one attempt, because if it is preempted we
357 # will resubmit and ask for a non-preemptible instance.
358 container_request["container_count_max"] = 1
360 if self.timelimit is not None and self.timelimit > 0:
361 scheduling_parameters["max_run_time"] = self.timelimit
363 extra_submit_params = {}
364 if runtimeContext.submit_runner_cluster:
365 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
367 container_request["output_name"] = cleanup_name_for_collection("Output from step %s" % (self.name))
368 container_request["output_ttl"] = self.output_ttl
369 container_request["mounts"] = mounts
370 container_request["secret_mounts"] = secret_mounts
371 container_request["runtime_constraints"] = runtime_constraints
372 container_request["scheduling_parameters"] = scheduling_parameters
374 enable_reuse = runtimeContext.enable_reuse
376 reuse_req, _ = self.get_requirement("WorkReuse")
378 enable_reuse = reuse_req["enableReuse"]
379 reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
381 enable_reuse = reuse_req["enableReuse"]
382 container_request["use_existing"] = enable_reuse
384 properties_req, _ = self.get_requirement("http://arvados.org/cwl#ProcessProperties")
386 for pr in properties_req["processProperties"]:
387 container_request["properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
389 output_properties_req, _ = self.get_requirement("http://arvados.org/cwl#OutputCollectionProperties")
390 if output_properties_req:
391 if self.arvrunner.api._rootDesc["revision"] >= "20220510":
392 container_request["output_properties"] = {}
393 for pr in output_properties_req["outputProperties"]:
394 container_request["output_properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
396 logger.warning("%s API revision is %s, revision %s is required to support setting properties on output collections.",
397 self.arvrunner.label(self), self.arvrunner.api._rootDesc["revision"], "20220510")
399 if self.arvrunner.api._rootDesc["revision"] >= "20240502" and self.globpatterns:
401 for gb in self.globpatterns:
402 gb = self.builder.do_eval(gb)
405 for gbeval in aslist(gb):
406 if gbeval.startswith(self.outdir+"/"):
407 gbeval = gbeval[len(self.outdir)+1:]
408 while gbeval.startswith("./"):
411 if gbeval in (self.outdir, "", "."):
412 output_glob.append("**")
413 elif gbeval.endswith("/"):
414 output_glob.append(gbeval+"**")
416 output_glob.append(gbeval)
417 output_glob.append(gbeval + "/**")
419 if "**" in output_glob:
420 # if it's going to match all, prefer not to provide it
425 # Tools should either use cwl.output.json or
426 # outputBinding globs. However, one CWL conformance
427 # test has both, so we need to make sure we collect
428 # cwl.output.json in this case. That test uses
429 # cwl.output.json return a string, but also uses
431 output_glob.append("cwl.output.json")
433 # It could happen that a tool creates cwl.output.json,
434 # references a file, but also uses a outputBinding
435 # glob that doesn't include the file being referenced.
437 # In this situation, output_glob will only match the
438 # pattern we know about. If cwl.output.json referred
439 # to other files in the output, those would be
440 # missing. We could upload the entire output, but we
441 # currently have no way of knowing at this point
442 # whether cwl.output.json will be used this way.
444 # Because this is a corner case, I'm inclined to leave
445 # this as a known issue for now. No conformance tests
446 # do this and I'd even be inclined to have it ruled
447 # incompatible in the CWL spec if it did come up.
448 # That said, in retrospect it would have been good to
449 # require CommandLineTool to declare when it expects
452 container_request["output_glob"] = output_glob
456 oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
458 if oom_retry_req.get('memoryRetryMultiplier'):
459 ram_multiplier.append(oom_retry_req.get('memoryRetryMultiplier'))
460 elif oom_retry_req.get('memoryRetryMultipler'):
461 ram_multiplier.append(oom_retry_req.get('memoryRetryMultipler'))
463 ram_multiplier.append(2)
465 if runtimeContext.runnerjob.startswith("arvwf:"):
466 wfuuid = runtimeContext.runnerjob[6:runtimeContext.runnerjob.index("#")]
467 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
468 if container_request["name"] == "main":
469 container_request["name"] = wfrecord["name"]
470 container_request["properties"]["template_uuid"] = wfuuid
472 if self.attempt_count == 0:
473 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
476 ram = runtime_constraints["ram"]
478 self.uuid = runtimeContext.submit_request_uuid
480 for i in ram_multiplier:
481 runtime_constraints["ram"] = ram * i
484 response = self.arvrunner.api.container_requests().update(
486 body=container_request,
487 **extra_submit_params
488 ).execute(num_retries=self.arvrunner.num_retries)
490 response = self.arvrunner.api.container_requests().create(
491 body=container_request,
492 **extra_submit_params
493 ).execute(num_retries=self.arvrunner.num_retries)
494 self.uuid = response["uuid"]
496 if response["container_uuid"] is not None:
499 if response["container_uuid"] is None:
500 runtime_constraints["ram"] = ram * ram_multiplier[self.attempt_count]
502 container_request["state"] = "Committed"
503 response = self.arvrunner.api.container_requests().update(
505 body=container_request,
506 **extra_submit_params
507 ).execute(num_retries=self.arvrunner.num_retries)
509 self.arvrunner.process_submitted(self)
510 self.attempt_count += 1
512 if response["state"] == "Final":
513 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
515 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
516 except Exception as e:
517 logger.exception("%s error submitting container\n%s", self.arvrunner.label(self), e)
518 logger.debug("Container request was %s", container_request)
519 self.output_callback({}, "permanentFail")
521 def may_resubmit_non_preemptible(self):
522 if self.job_runtime.enable_resubmit_non_preemptible is False:
523 # explicitly disabled
526 spot_instance_retry_req, _ = self.get_requirement("http://arvados.org/cwl#PreemptionBehavior")
527 if spot_instance_retry_req:
528 if spot_instance_retry_req["resubmitNonPreemptible"] is False:
529 # explicitly disabled by hint
531 elif self.job_runtime.enable_resubmit_non_preemptible is None:
532 # default behavior is we don't retry
535 # At this point, by process of elimination either
536 # resubmitNonPreemptible or enable_resubmit_non_preemptible
537 # must be True, so now check if the container was actually
542 def spot_instance_retry(self, record, container):
543 return self.may_resubmit_non_preemptible() and bool(container["runtime_status"].get("preemptionNotice"))
545 def out_of_memory_retry(self, record, container):
546 oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
547 if oom_retry_req is None:
550 # Sometimes it gets killed with no warning
551 if container["exit_code"] == 137:
554 logc = arvados.collection.CollectionReader(record["log_uuid"],
555 api_client=self.arvrunner.api,
556 keep_client=self.arvrunner.keep_client,
557 num_retries=self.arvrunner.num_retries)
560 def callback(v1, v2, v3):
563 done.logtail(logc, callback, "", maxlen=1000)
565 # Check allocation failure
566 oom_matches = oom_retry_req.get('memoryErrorRegex') or r'(bad_alloc|out ?of ?memory|memory ?error|container using over 9.% of memory)'
567 if re.search(oom_matches, loglines[0], re.IGNORECASE | re.MULTILINE):
572 def done(self, record):
579 container = self.arvrunner.api.containers().get(
580 uuid=record["container_uuid"]
581 ).execute(num_retries=self.arvrunner.num_retries)
583 if container["state"] == "Complete":
584 rcode = container["exit_code"]
585 if self.successCodes and rcode in self.successCodes:
586 processStatus = "success"
587 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
588 processStatus = "temporaryFail"
589 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
590 processStatus = "permanentFail"
592 processStatus = "success"
594 processStatus = "permanentFail"
596 if processStatus == "permanentFail" and self.attempt_count == 1 and self.out_of_memory_retry(record, container):
597 logger.info("%s Container failed with out of memory error. Retrying container with more RAM.",
598 self.arvrunner.label(self))
599 self.job_runtime = self.job_runtime.copy()
602 if rcode == 137 and not do_retry:
603 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.",
604 self.arvrunner.label(self))
606 processStatus = "permanentFail"
608 if processStatus == "permanentFail" and self.attempt_count == 1 and self.spot_instance_retry(record, container):
609 logger.info("%s Container failed because the preemptible instance it was running on was reclaimed. Retrying container on a non-preemptible instance.")
610 self.job_runtime = self.job_runtime.copy()
611 self.job_runtime.enable_preemptible = False
615 # Add a property indicating that this container was resubmitted.
616 updateproperties = record["properties"].copy()
618 self.job_runtime.submit_request_uuid = None
621 # this flag suppresses calling the output callback, we only want to set this
622 # when we're sure that the resubmission has happened without issue.
624 # Add a property to the old container request indicating it
626 updateproperties["arv:failed_container_resubmitted"] = self.uuid
627 self.arvrunner.api.container_requests().update(uuid=olduuid,
628 body={"properties": updateproperties}).execute()
632 if record["log_uuid"]:
633 logc = arvados.collection.Collection(record["log_uuid"],
634 api_client=self.arvrunner.api,
635 keep_client=self.arvrunner.keep_client,
636 num_retries=self.arvrunner.num_retries)
638 if processStatus == "permanentFail" and logc is not None:
639 label = self.arvrunner.label(self)
642 "%s (%s) error log:" % (label, record["uuid"]), maxlen=40, include_crunchrun=(rcode is None or rcode > 127))
644 if record["output_uuid"]:
645 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
646 # Compute the trash time to avoid requesting the collection record.
647 trash_at = ciso8601.parse_datetime_as_naive(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
648 aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
649 orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
650 oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
651 logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
652 self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
653 self.arvrunner.add_intermediate_output(record["output_uuid"])
655 if container["output"]:
656 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
658 properties = record["properties"].copy()
659 properties["cwl_output"] = outputs
660 self.arvrunner.api.container_requests().update(
662 body={"container_request": {"properties": properties}}
663 ).execute(num_retries=self.arvrunner.num_retries)
665 if logc is not None and self.job_runtime.enable_usage_report is not False:
667 summarizer = crunchstat_summary.summarizer.ContainerRequestSummarizer(
669 collection_object=logc,
671 arv=self.arvrunner.api)
673 with logc.open("usage_report.html", "wt") as mr:
674 mr.write(summarizer.html_report())
677 # Post warnings about nodes that are under-utilized.
678 for rc in summarizer._recommend_gen(lambda x: x):
679 self.job_runtime.usage_report_notes.append(rc)
681 except Exception as e:
682 logger.warning("%s unable to generate resource usage report",
683 self.arvrunner.label(self),
684 exc_info=(e if self.arvrunner.debug else False))
686 except WorkflowException as e:
687 # Only include a stack trace if in debug mode.
688 # A stack trace may obfuscate more useful output about the workflow.
689 logger.error("%s unable to collect output from %s:\n%s",
690 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
691 processStatus = "permanentFail"
693 logger.exception("%s while getting output object:", self.arvrunner.label(self))
694 processStatus = "permanentFail"
697 self.output_callback(outputs, processStatus)
700 class RunnerContainer(Runner):
701 """Submit and manage a container that runs arvados-cwl-runner."""
703 def arvados_job_spec(self, runtimeContext, git_info):
704 """Create an Arvados container request for this workflow.
706 The returned dict can be used to create a container passed as
707 the +body+ argument to container_requests().create().
710 adjustDirObjs(self.job_order, trim_listing)
711 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
712 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
715 for param in sorted(self.job_order.keys()):
716 if self.secret_store.has_secret(self.job_order[param]):
717 mnt = "/secrets/s%d" % len(secret_mounts)
718 secret_mounts[mnt] = {
720 "content": self.secret_store.retrieve(self.job_order[param])
722 self.job_order[param] = {"$include": mnt}
724 container_image = arvados_jobs_image(self.arvrunner, self.jobs_image, runtimeContext)
726 workflow_runner_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#WorkflowRunnerResources")
727 if workflow_runner_req and workflow_runner_req.get("acrContainerImage"):
728 container_image = workflow_runner_req.get("acrContainerImage")
732 "output_path": "/var/spool/cwl",
733 "cwd": "/var/spool/cwl",
734 "priority": self.priority,
735 "state": "Committed",
736 "container_image": container_image,
738 "/var/lib/cwl/cwl.input.json": {
740 "content": self.job_order
744 "path": "/var/spool/cwl/cwl.output.json"
747 "kind": "collection",
751 "secret_mounts": secret_mounts,
752 "runtime_constraints": {
753 "vcpus": math.ceil(self.submit_runner_cores),
754 "ram": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),
757 "use_existing": self.reuse_runner,
761 if self.embedded_tool.tool.get("id", "").startswith("keep:"):
762 sp = self.embedded_tool.tool["id"].split('/')
763 workflowcollection = sp[0][5:]
764 workflowname = "/".join(sp[1:])
765 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
766 container_req["mounts"]["/var/lib/cwl/workflow"] = {
767 "kind": "collection",
768 "portable_data_hash": "%s" % workflowcollection
770 elif self.embedded_tool.tool.get("id", "").startswith("arvwf:"):
771 uuid, frg = urllib.parse.urldefrag(self.embedded_tool.tool["id"])
772 workflowpath = "/var/lib/cwl/workflow.json#" + frg
773 packedtxt = self.loadingContext.loader.fetch_text(uuid)
774 yaml = ruamel.yaml.YAML(typ='safe', pure=True)
775 packed = yaml.load(packedtxt)
776 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
780 container_req["properties"]["template_uuid"] = self.embedded_tool.tool["id"][6:33]
781 elif self.embedded_tool.tool.get("id", "").startswith("file:"):
782 raise WorkflowException("Tool id '%s' is a local file but expected keep: or arvwf:" % self.embedded_tool.tool.get("id"))
784 main = self.loadingContext.loader.idx["_:main"]
785 if main.get("id") == "_:main":
787 workflowpath = "/var/lib/cwl/workflow.json#main"
788 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
793 container_req["properties"].update({k.replace("http://arvados.org/cwl#", "arv:"): v for k, v in git_info.items()})
795 properties_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#ProcessProperties")
797 builder = make_builder(self.job_order, self.embedded_tool.hints, self.embedded_tool.requirements, runtimeContext, self.embedded_tool.metadata)
798 for pr in properties_req["processProperties"]:
799 container_req["properties"][pr["propertyName"]] = builder.do_eval(pr["propertyValue"])
801 # --local means execute the workflow instead of submitting a container request
802 # --api=containers means use the containers API
803 # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
804 # --disable-validate because we already validated so don't need to do it again
805 # --eval-timeout is the timeout for javascript invocation
806 # --parallel-task-count is the number of threads to use for job submission
807 # --enable/disable-reuse sets desired job reuse
808 # --collection-cache-size sets aside memory to store collections
809 command = ["arvados-cwl-runner",
812 "--no-log-timestamps",
813 "--disable-validate",
815 "--eval-timeout=%s" % self.arvrunner.eval_timeout,
816 "--thread-count=%s" % self.arvrunner.thread_count,
817 "--enable-reuse" if self.enable_reuse else "--disable-reuse",
818 "--collection-cache-size=%s" % self.collection_cache_size]
821 command.append("--output-name=" + self.output_name)
822 container_req["output_name"] = self.output_name
825 command.append("--output-tags=" + self.output_tags)
827 if runtimeContext.debug:
828 command.append("--debug")
830 if runtimeContext.storage_classes != "default" and runtimeContext.storage_classes:
831 command.append("--storage-classes=" + runtimeContext.storage_classes)
833 if runtimeContext.intermediate_storage_classes != "default" and runtimeContext.intermediate_storage_classes:
834 command.append("--intermediate-storage-classes=" + runtimeContext.intermediate_storage_classes)
836 if runtimeContext.on_error:
837 command.append("--on-error=" + self.on_error)
839 if runtimeContext.intermediate_output_ttl:
840 command.append("--intermediate-output-ttl=%d" % runtimeContext.intermediate_output_ttl)
842 if runtimeContext.trash_intermediate:
843 command.append("--trash-intermediate")
845 if runtimeContext.project_uuid:
846 command.append("--project-uuid="+runtimeContext.project_uuid)
849 command.append("--enable-dev")
851 if runtimeContext.enable_preemptible is True:
852 command.append("--enable-preemptible")
854 if runtimeContext.enable_preemptible is False:
855 command.append("--disable-preemptible")
857 if runtimeContext.varying_url_params:
858 command.append("--varying-url-params="+runtimeContext.varying_url_params)
860 if runtimeContext.prefer_cached_downloads:
861 command.append("--prefer-cached-downloads")
863 if runtimeContext.enable_usage_report is True:
864 command.append("--enable-usage-report")
866 if runtimeContext.enable_usage_report is False:
867 command.append("--disable-usage-report")
870 command.append("--fast-parser")
872 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
874 container_req["command"] = command
879 def run(self, runtimeContext):
880 runtimeContext.keepprefix = "keep:"
881 job_spec = self.arvados_job_spec(runtimeContext, self.git_info)
882 if runtimeContext.project_uuid:
883 job_spec["owner_uuid"] = runtimeContext.project_uuid
885 extra_submit_params = {}
886 if runtimeContext.submit_runner_cluster:
887 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
889 if runtimeContext.submit_request_uuid:
890 if "cluster_id" in extra_submit_params:
891 # Doesn't make sense for "update" and actually fails
892 del extra_submit_params["cluster_id"]
893 response = self.arvrunner.api.container_requests().update(
894 uuid=runtimeContext.submit_request_uuid,
896 **extra_submit_params
897 ).execute(num_retries=self.arvrunner.num_retries)
899 response = self.arvrunner.api.container_requests().create(
901 **extra_submit_params
902 ).execute(num_retries=self.arvrunner.num_retries)
904 self.uuid = response["uuid"]
905 self.arvrunner.process_submitted(self)
907 logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
909 workbench2 = self.arvrunner.api.config()["Services"]["Workbench2"]["ExternalURL"]
911 url = "{}processes/{}".format(workbench2, response["uuid"])
912 logger.info("Monitor workflow progress at %s", url)
915 def done(self, record):
917 container = self.arvrunner.api.containers().get(
918 uuid=record["container_uuid"]
919 ).execute(num_retries=self.arvrunner.num_retries)
920 container["log"] = record["log_uuid"]
922 logger.exception("%s while getting runner container", self.arvrunner.label(self))
923 self.arvrunner.output_callback({}, "permanentFail")
925 super(RunnerContainer, self).done(container)