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,
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
61 def update_pipeline_component(self, r):
64 def _required_env(self):
66 env["HOME"] = self.outdir
67 env["TMPDIR"] = self.tmpdir
70 def run(self, toplevelRuntimeContext):
71 # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
72 # which calls makeJobRunner() to get a new ArvadosContainer
73 # object. The fields that define execution such as
74 # command_line, environment, etc are set on the
75 # ArvadosContainer object by CommandLineTool.job() before
78 runtimeContext = self.job_runtime
80 if runtimeContext.submit_request_uuid:
81 container_request = self.arvrunner.api.container_requests().get(
82 uuid=runtimeContext.submit_request_uuid
83 ).execute(num_retries=self.arvrunner.num_retries)
85 container_request = {}
87 container_request["command"] = self.command_line
88 container_request["name"] = self.name
89 container_request["output_path"] = self.outdir
90 container_request["cwd"] = self.outdir
91 container_request["priority"] = runtimeContext.priority
92 container_request["state"] = "Uncommitted"
93 container_request.setdefault("properties", {})
95 container_request["properties"]["cwl_input"] = self.joborder
97 runtime_constraints = {}
99 if runtimeContext.project_uuid:
100 container_request["owner_uuid"] = runtimeContext.project_uuid
102 if self.arvrunner.secret_store.has_secret(self.command_line):
103 raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
105 if self.arvrunner.secret_store.has_secret(self.environment):
106 raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
108 resources = self.builder.resources
109 if resources is not None:
110 runtime_constraints["vcpus"] = math.ceil(resources.get("cores", 1))
111 runtime_constraints["ram"] = math.ceil(resources.get("ram") * 2**20)
116 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
120 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
124 scheduling_parameters = {}
126 rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
127 rf.sort(key=lambda k: k.resolved)
129 for resolved, target, tp, stg in rf:
132 if prevdir and target.startswith(prevdir):
134 if tp == "Directory":
137 targetdir = os.path.dirname(target)
138 sp = resolved.split("/", 1)
139 pdh = sp[0][5:] # remove "keep:"
140 mounts[targetdir] = {
141 "kind": "collection",
142 "portable_data_hash": pdh
144 if pdh in self.pathmapper.pdh_to_uuid:
145 mounts[targetdir]["uuid"] = self.pathmapper.pdh_to_uuid[pdh]
147 if tp == "Directory":
150 path = os.path.dirname(sp[1])
151 if path and path != "/":
152 mounts[targetdir]["path"] = path
153 prevdir = targetdir + "/"
155 intermediate_collection_info = arvados_cwl.util.get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
157 with Perf(metrics, "generatefiles %s" % self.name):
158 if self.generatefiles["listing"]:
159 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
160 keep_client=self.arvrunner.keep_client,
161 num_retries=self.arvrunner.num_retries)
162 generatemapper = NoFollowPathMapper(self.generatefiles["listing"], "", "",
165 sorteditems = sorted(generatemapper.items(), key=lambda n: n[1].target)
167 logger.debug("generatemapper is %s", sorteditems)
169 with Perf(metrics, "createfiles %s" % self.name):
170 for f, p in sorteditems:
174 if p.target.startswith("/"):
175 dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
179 if p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
180 if p.resolved.startswith("_:"):
183 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
184 vwd.copy(path or ".", dst, source_collection=source)
185 elif p.type == "CreateFile":
186 if self.arvrunner.secret_store.has_secret(p.resolved):
187 mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
188 secret_mounts[mountpoint] = {
190 "content": self.arvrunner.secret_store.retrieve(p.resolved)
193 with vwd.open(dst, "w") as n:
196 def keepemptydirs(p):
197 if isinstance(p, arvados.collection.RichCollectionBase):
199 p.open(".keep", "w").close()
206 if not runtimeContext.current_container:
207 runtimeContext.current_container = arvados_cwl.util.get_current_container(self.arvrunner.api, self.arvrunner.num_retries, logger)
208 vwd.save_new(name=intermediate_collection_info["name"],
209 owner_uuid=runtimeContext.project_uuid,
210 ensure_unique_name=True,
211 trash_at=intermediate_collection_info["trash_at"],
212 properties=intermediate_collection_info["properties"])
215 for f, p in sorteditems:
216 if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
217 (prev is not None and p.target.startswith(prev))):
219 if p.target.startswith("/"):
220 dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
223 mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
224 mounts[mountpoint] = {"kind": "collection",
225 "portable_data_hash": vwd.portable_data_hash(),
227 if p.type.startswith("Writable"):
228 mounts[mountpoint]["writable"] = True
229 prev = p.target + "/"
231 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
233 container_request["environment"].update(self.environment)
236 sp = self.stdin[6:].split("/", 1)
237 mounts["stdin"] = {"kind": "collection",
238 "portable_data_hash": sp[0],
242 mounts["stderr"] = {"kind": "file",
243 "path": "%s/%s" % (self.outdir, self.stderr)}
246 mounts["stdout"] = {"kind": "file",
247 "path": "%s/%s" % (self.outdir, self.stdout)}
249 (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
251 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
253 runtimeContext.pull_image,
256 network_req, _ = self.get_requirement("NetworkAccess")
258 runtime_constraints["API"] = network_req["networkAccess"]
260 api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
262 runtime_constraints["API"] = True
264 use_disk_cache = (self.arvrunner.api.config()["Containers"].get("DefaultKeepCacheRAM", 0) == 0)
266 keep_cache_type_req, _ = self.get_requirement("http://arvados.org/cwl#KeepCacheTypeRequirement")
267 if keep_cache_type_req:
268 if "keepCacheType" in keep_cache_type_req:
269 if keep_cache_type_req["keepCacheType"] == "ram_cache":
270 use_disk_cache = False
272 runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
274 if "keep_cache" in runtime_req:
276 # If DefaultKeepCacheRAM is zero it means we should use disk cache.
277 runtime_constraints["keep_cache_disk"] = math.ceil(runtime_req["keep_cache"] * 2**20)
279 runtime_constraints["keep_cache_ram"] = math.ceil(runtime_req["keep_cache"] * 2**20)
280 if "outputDirType" in runtime_req:
281 if runtime_req["outputDirType"] == "local_output_dir":
282 # Currently the default behavior.
284 elif runtime_req["outputDirType"] == "keep_output_dir":
285 mounts[self.outdir]= {
286 "kind": "collection",
290 partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
292 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
294 intermediate_output_req, _ = self.get_requirement("http://arvados.org/cwl#IntermediateOutput")
295 if intermediate_output_req:
296 self.output_ttl = intermediate_output_req["outputTTL"]
298 self.output_ttl = self.arvrunner.intermediate_output_ttl
300 if self.output_ttl < 0:
301 raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
304 if self.arvrunner.api._rootDesc["revision"] >= "20210628":
305 storage_class_req, _ = self.get_requirement("http://arvados.org/cwl#OutputStorageClass")
306 if storage_class_req and storage_class_req.get("intermediateStorageClass"):
307 container_request["output_storage_classes"] = aslist(storage_class_req["intermediateStorageClass"])
309 container_request["output_storage_classes"] = runtimeContext.intermediate_storage_classes.strip().split(",")
311 cuda_req, _ = self.get_requirement("http://commonwl.org/cwltool#CUDARequirement")
313 runtime_constraints["cuda"] = {
314 "device_count": resources.get("cudaDeviceCount", 1),
315 "driver_version": cuda_req["cudaVersionMin"],
316 "hardware_capability": aslist(cuda_req["cudaComputeCapability"])[0]
319 if runtimeContext.enable_preemptible is False:
320 scheduling_parameters["preemptible"] = False
322 preemptible_req, _ = self.get_requirement("http://arvados.org/cwl#UsePreemptible")
324 scheduling_parameters["preemptible"] = preemptible_req["usePreemptible"]
325 elif runtimeContext.enable_preemptible is True:
326 scheduling_parameters["preemptible"] = True
327 elif runtimeContext.enable_preemptible is None:
330 if self.timelimit is not None and self.timelimit > 0:
331 scheduling_parameters["max_run_time"] = self.timelimit
333 extra_submit_params = {}
334 if runtimeContext.submit_runner_cluster:
335 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
337 container_request["output_name"] = cleanup_name_for_collection("Output from step %s" % (self.name))
338 container_request["output_ttl"] = self.output_ttl
339 container_request["mounts"] = mounts
340 container_request["secret_mounts"] = secret_mounts
341 container_request["runtime_constraints"] = runtime_constraints
342 container_request["scheduling_parameters"] = scheduling_parameters
344 enable_reuse = runtimeContext.enable_reuse
346 reuse_req, _ = self.get_requirement("WorkReuse")
348 enable_reuse = reuse_req["enableReuse"]
349 reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
351 enable_reuse = reuse_req["enableReuse"]
352 container_request["use_existing"] = enable_reuse
354 properties_req, _ = self.get_requirement("http://arvados.org/cwl#ProcessProperties")
356 for pr in properties_req["processProperties"]:
357 container_request["properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
359 output_properties_req, _ = self.get_requirement("http://arvados.org/cwl#OutputCollectionProperties")
360 if output_properties_req:
361 if self.arvrunner.api._rootDesc["revision"] >= "20220510":
362 container_request["output_properties"] = {}
363 for pr in output_properties_req["outputProperties"]:
364 container_request["output_properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
366 logger.warning("%s API revision is %s, revision %s is required to support setting properties on output collections.",
367 self.arvrunner.label(self), self.arvrunner.api._rootDesc["revision"], "20220510")
371 oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
373 if oom_retry_req.get('memoryRetryMultiplier'):
374 ram_multiplier.append(oom_retry_req.get('memoryRetryMultiplier'))
375 elif oom_retry_req.get('memoryRetryMultipler'):
376 ram_multiplier.append(oom_retry_req.get('memoryRetryMultipler'))
378 ram_multiplier.append(2)
380 if runtimeContext.runnerjob.startswith("arvwf:"):
381 wfuuid = runtimeContext.runnerjob[6:runtimeContext.runnerjob.index("#")]
382 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
383 if container_request["name"] == "main":
384 container_request["name"] = wfrecord["name"]
385 container_request["properties"]["template_uuid"] = wfuuid
387 if self.attempt_count == 0:
388 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
391 ram = runtime_constraints["ram"]
393 self.uuid = runtimeContext.submit_request_uuid
395 for i in ram_multiplier:
396 runtime_constraints["ram"] = ram * i
399 response = self.arvrunner.api.container_requests().update(
401 body=container_request,
402 **extra_submit_params
403 ).execute(num_retries=self.arvrunner.num_retries)
405 response = self.arvrunner.api.container_requests().create(
406 body=container_request,
407 **extra_submit_params
408 ).execute(num_retries=self.arvrunner.num_retries)
409 self.uuid = response["uuid"]
411 if response["container_uuid"] is not None:
414 if response["container_uuid"] is None:
415 runtime_constraints["ram"] = ram * ram_multiplier[self.attempt_count]
417 container_request["state"] = "Committed"
418 response = self.arvrunner.api.container_requests().update(
420 body=container_request,
421 **extra_submit_params
422 ).execute(num_retries=self.arvrunner.num_retries)
424 self.arvrunner.process_submitted(self)
425 self.attempt_count += 1
427 if response["state"] == "Final":
428 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
430 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
431 except Exception as e:
432 logger.exception("%s error submitting container\n%s", self.arvrunner.label(self), e)
433 logger.debug("Container request was %s", container_request)
434 self.output_callback({}, "permanentFail")
436 def out_of_memory_retry(self, record, container):
437 oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
438 if oom_retry_req is None:
441 # Sometimes it gets killed with no warning
442 if container["exit_code"] == 137:
445 logc = arvados.collection.CollectionReader(record["log_uuid"],
446 api_client=self.arvrunner.api,
447 keep_client=self.arvrunner.keep_client,
448 num_retries=self.arvrunner.num_retries)
451 def callback(v1, v2, v3):
454 done.logtail(logc, callback, "", maxlen=1000)
456 # Check allocation failure
457 oom_matches = oom_retry_req.get('memoryErrorRegex') or r'(bad_alloc|out ?of ?memory|memory ?error|container using over 9.% of memory)'
458 if re.search(oom_matches, loglines[0], re.IGNORECASE | re.MULTILINE):
463 def done(self, record):
468 container = self.arvrunner.api.containers().get(
469 uuid=record["container_uuid"]
470 ).execute(num_retries=self.arvrunner.num_retries)
471 if container["state"] == "Complete":
472 rcode = container["exit_code"]
473 if self.successCodes and rcode in self.successCodes:
474 processStatus = "success"
475 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
476 processStatus = "temporaryFail"
477 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
478 processStatus = "permanentFail"
480 processStatus = "success"
482 processStatus = "permanentFail"
484 if processStatus == "permanentFail" and self.attempt_count == 1 and self.out_of_memory_retry(record, container):
485 logger.warning("%s Container failed with out of memory error, retrying with more RAM.",
486 self.arvrunner.label(self))
487 self.job_runtime.submit_request_uuid = None
494 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.",
495 self.arvrunner.label(self))
497 processStatus = "permanentFail"
500 if record["log_uuid"]:
501 logc = arvados.collection.Collection(record["log_uuid"],
502 api_client=self.arvrunner.api,
503 keep_client=self.arvrunner.keep_client,
504 num_retries=self.arvrunner.num_retries)
506 if processStatus == "permanentFail" and logc is not None:
507 label = self.arvrunner.label(self)
510 "%s (%s) error log:" % (label, record["uuid"]), maxlen=40, include_crunchrun=(rcode is None or rcode > 127))
512 if record["output_uuid"]:
513 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
514 # Compute the trash time to avoid requesting the collection record.
515 trash_at = ciso8601.parse_datetime_as_naive(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
516 aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
517 orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
518 oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
519 logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
520 self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
521 self.arvrunner.add_intermediate_output(record["output_uuid"])
523 if container["output"]:
524 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
526 properties = record["properties"].copy()
527 properties["cwl_output"] = outputs
528 self.arvrunner.api.container_requests().update(
530 body={"container_request": {"properties": properties}}
531 ).execute(num_retries=self.arvrunner.num_retries)
533 if logc is not None and self.job_runtime.enable_usage_report is not False:
535 summarizer = crunchstat_summary.summarizer.ContainerRequestSummarizer(
537 collection_object=logc,
539 arv=self.arvrunner.api)
541 with logc.open("usage_report.html", "wt") as mr:
542 mr.write(summarizer.html_report())
545 # Post warnings about nodes that are under-utilized.
546 for rc in summarizer._recommend_gen(lambda x: x):
547 self.job_runtime.usage_report_notes.append(rc)
549 except Exception as e:
550 logger.warning("%s unable to generate resource usage report",
551 self.arvrunner.label(self),
552 exc_info=(e if self.arvrunner.debug else False))
554 except WorkflowException as e:
555 # Only include a stack trace if in debug mode.
556 # A stack trace may obfuscate more useful output about the workflow.
557 logger.error("%s unable to collect output from %s:\n%s",
558 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
559 processStatus = "permanentFail"
561 logger.exception("%s while getting output object:", self.arvrunner.label(self))
562 processStatus = "permanentFail"
565 self.output_callback(outputs, processStatus)
568 class RunnerContainer(Runner):
569 """Submit and manage a container that runs arvados-cwl-runner."""
571 def arvados_job_spec(self, runtimeContext, git_info):
572 """Create an Arvados container request for this workflow.
574 The returned dict can be used to create a container passed as
575 the +body+ argument to container_requests().create().
578 adjustDirObjs(self.job_order, trim_listing)
579 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
580 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
583 for param in sorted(self.job_order.keys()):
584 if self.secret_store.has_secret(self.job_order[param]):
585 mnt = "/secrets/s%d" % len(secret_mounts)
586 secret_mounts[mnt] = {
588 "content": self.secret_store.retrieve(self.job_order[param])
590 self.job_order[param] = {"$include": mnt}
592 container_image = arvados_jobs_image(self.arvrunner, self.jobs_image, runtimeContext)
594 workflow_runner_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#WorkflowRunnerResources")
595 if workflow_runner_req and workflow_runner_req.get("acrContainerImage"):
596 container_image = workflow_runner_req.get("acrContainerImage")
600 "output_path": "/var/spool/cwl",
601 "cwd": "/var/spool/cwl",
602 "priority": self.priority,
603 "state": "Committed",
604 "container_image": container_image,
606 "/var/lib/cwl/cwl.input.json": {
608 "content": self.job_order
612 "path": "/var/spool/cwl/cwl.output.json"
615 "kind": "collection",
619 "secret_mounts": secret_mounts,
620 "runtime_constraints": {
621 "vcpus": math.ceil(self.submit_runner_cores),
622 "ram": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),
625 "use_existing": self.reuse_runner,
629 if self.embedded_tool.tool.get("id", "").startswith("keep:"):
630 sp = self.embedded_tool.tool["id"].split('/')
631 workflowcollection = sp[0][5:]
632 workflowname = "/".join(sp[1:])
633 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
634 container_req["mounts"]["/var/lib/cwl/workflow"] = {
635 "kind": "collection",
636 "portable_data_hash": "%s" % workflowcollection
638 elif self.embedded_tool.tool.get("id", "").startswith("arvwf:"):
639 uuid, frg = urllib.parse.urldefrag(self.embedded_tool.tool["id"])
640 workflowpath = "/var/lib/cwl/workflow.json#" + frg
641 packedtxt = self.loadingContext.loader.fetch_text(uuid)
642 yaml = ruamel.yaml.YAML(typ='safe', pure=True)
643 packed = yaml.load(packedtxt)
644 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
648 container_req["properties"]["template_uuid"] = self.embedded_tool.tool["id"][6:33]
649 elif self.embedded_tool.tool.get("id", "").startswith("file:"):
650 raise WorkflowException("Tool id '%s' is a local file but expected keep: or arvwf:" % self.embedded_tool.tool.get("id"))
652 main = self.loadingContext.loader.idx["_:main"]
653 if main.get("id") == "_:main":
655 workflowpath = "/var/lib/cwl/workflow.json#main"
656 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
661 container_req["properties"].update({k.replace("http://arvados.org/cwl#", "arv:"): v for k, v in git_info.items()})
663 properties_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#ProcessProperties")
665 builder = make_builder(self.job_order, self.embedded_tool.hints, self.embedded_tool.requirements, runtimeContext, self.embedded_tool.metadata)
666 for pr in properties_req["processProperties"]:
667 container_req["properties"][pr["propertyName"]] = builder.do_eval(pr["propertyValue"])
669 # --local means execute the workflow instead of submitting a container request
670 # --api=containers means use the containers API
671 # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
672 # --disable-validate because we already validated so don't need to do it again
673 # --eval-timeout is the timeout for javascript invocation
674 # --parallel-task-count is the number of threads to use for job submission
675 # --enable/disable-reuse sets desired job reuse
676 # --collection-cache-size sets aside memory to store collections
677 command = ["arvados-cwl-runner",
680 "--no-log-timestamps",
681 "--disable-validate",
683 "--eval-timeout=%s" % self.arvrunner.eval_timeout,
684 "--thread-count=%s" % self.arvrunner.thread_count,
685 "--enable-reuse" if self.enable_reuse else "--disable-reuse",
686 "--collection-cache-size=%s" % self.collection_cache_size]
689 command.append("--output-name=" + self.output_name)
690 container_req["output_name"] = self.output_name
693 command.append("--output-tags=" + self.output_tags)
695 if runtimeContext.debug:
696 command.append("--debug")
698 if runtimeContext.storage_classes != "default" and runtimeContext.storage_classes:
699 command.append("--storage-classes=" + runtimeContext.storage_classes)
701 if runtimeContext.intermediate_storage_classes != "default" and runtimeContext.intermediate_storage_classes:
702 command.append("--intermediate-storage-classes=" + runtimeContext.intermediate_storage_classes)
704 if runtimeContext.on_error:
705 command.append("--on-error=" + self.on_error)
707 if runtimeContext.intermediate_output_ttl:
708 command.append("--intermediate-output-ttl=%d" % runtimeContext.intermediate_output_ttl)
710 if runtimeContext.trash_intermediate:
711 command.append("--trash-intermediate")
713 if runtimeContext.project_uuid:
714 command.append("--project-uuid="+runtimeContext.project_uuid)
717 command.append("--enable-dev")
719 if runtimeContext.enable_preemptible is True:
720 command.append("--enable-preemptible")
722 if runtimeContext.enable_preemptible is False:
723 command.append("--disable-preemptible")
725 if runtimeContext.varying_url_params:
726 command.append("--varying-url-params="+runtimeContext.varying_url_params)
728 if runtimeContext.prefer_cached_downloads:
729 command.append("--prefer-cached-downloads")
731 if runtimeContext.enable_usage_report is True:
732 command.append("--enable-usage-report")
734 if runtimeContext.enable_usage_report is False:
735 command.append("--disable-usage-report")
738 command.append("--fast-parser")
740 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
742 container_req["command"] = command
747 def run(self, runtimeContext):
748 runtimeContext.keepprefix = "keep:"
749 job_spec = self.arvados_job_spec(runtimeContext, self.git_info)
750 if runtimeContext.project_uuid:
751 job_spec["owner_uuid"] = runtimeContext.project_uuid
753 extra_submit_params = {}
754 if runtimeContext.submit_runner_cluster:
755 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
757 if runtimeContext.submit_request_uuid:
758 if "cluster_id" in extra_submit_params:
759 # Doesn't make sense for "update" and actually fails
760 del extra_submit_params["cluster_id"]
761 response = self.arvrunner.api.container_requests().update(
762 uuid=runtimeContext.submit_request_uuid,
764 **extra_submit_params
765 ).execute(num_retries=self.arvrunner.num_retries)
767 response = self.arvrunner.api.container_requests().create(
769 **extra_submit_params
770 ).execute(num_retries=self.arvrunner.num_retries)
772 self.uuid = response["uuid"]
773 self.arvrunner.process_submitted(self)
775 logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
777 workbench2 = self.arvrunner.api.config()["Services"]["Workbench2"]["ExternalURL"]
779 url = "{}processes/{}".format(workbench2, response["uuid"])
780 logger.info("Monitor workflow progress at %s", url)
783 def done(self, record):
785 container = self.arvrunner.api.containers().get(
786 uuid=record["container_uuid"]
787 ).execute(num_retries=self.arvrunner.num_retries)
788 container["log"] = record["log_uuid"]
790 logger.exception("%s while getting runner container", self.arvrunner.label(self))
791 self.arvrunner.output_callback({}, "permanentFail")
793 super(RunnerContainer, self).done(container)