1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
15 import arvados_cwl.util
16 import ruamel.yaml as yaml
18 from cwltool.errors import WorkflowException
19 from cwltool.process import UnsupportedRequirement, shortname
20 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
21 from cwltool.utils import aslist
22 from cwltool.job import JobBase
24 import arvados.collection
26 from .arvdocker import arv_docker_get_image
28 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields
29 from .fsaccess import CollectionFetcher
30 from .pathmapper import NoFollowPathMapper, trim_listing
31 from .perf import Perf
33 logger = logging.getLogger('arvados.cwl-runner')
34 metrics = logging.getLogger('arvados.cwl-runner.metrics')
36 class ArvadosContainer(JobBase):
37 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
39 def __init__(self, runner, job_runtime,
40 builder, # type: Builder
41 joborder, # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
42 make_path_mapper, # type: Callable[..., PathMapper]
43 requirements, # type: List[Dict[Text, Text]]
44 hints, # type: List[Dict[Text, Text]]
47 super(ArvadosContainer, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
48 self.arvrunner = runner
49 self.job_runtime = job_runtime
53 def update_pipeline_component(self, r):
56 def run(self, runtimeContext):
57 # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
58 # which calls makeJobRunner() to get a new ArvadosContainer
59 # object. The fields that define execution such as
60 # command_line, environment, etc are set on the
61 # ArvadosContainer object by CommandLineTool.job() before
64 runtimeContext = self.job_runtime
67 "command": self.command_line,
69 "output_path": self.outdir,
71 "priority": runtimeContext.priority,
75 runtime_constraints = {}
77 if runtimeContext.project_uuid:
78 container_request["owner_uuid"] = runtimeContext.project_uuid
80 if self.arvrunner.secret_store.has_secret(self.command_line):
81 raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
83 if self.arvrunner.secret_store.has_secret(self.environment):
84 raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
86 resources = self.builder.resources
87 if resources is not None:
88 runtime_constraints["vcpus"] = math.ceil(resources.get("cores", 1))
89 runtime_constraints["ram"] = math.ceil(resources.get("ram") * 2**20)
94 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
98 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
102 scheduling_parameters = {}
104 rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
105 rf.sort(key=lambda k: k.resolved)
107 for resolved, target, tp, stg in rf:
110 if prevdir and target.startswith(prevdir):
112 if tp == "Directory":
115 targetdir = os.path.dirname(target)
116 sp = resolved.split("/", 1)
117 pdh = sp[0][5:] # remove "keep:"
118 mounts[targetdir] = {
119 "kind": "collection",
120 "portable_data_hash": pdh
123 if tp == "Directory":
126 path = os.path.dirname(sp[1])
127 if path and path != "/":
128 mounts[targetdir]["path"] = path
129 prevdir = targetdir + "/"
131 with Perf(metrics, "generatefiles %s" % self.name):
132 if self.generatefiles["listing"]:
133 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
134 keep_client=self.arvrunner.keep_client,
135 num_retries=self.arvrunner.num_retries)
136 generatemapper = NoFollowPathMapper(self.generatefiles["listing"], "", "",
139 sorteditems = sorted(generatemapper.items(), None, key=lambda n: n[1].target)
141 logger.debug("generatemapper is %s", sorteditems)
143 with Perf(metrics, "createfiles %s" % self.name):
144 for f, p in sorteditems:
147 elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
148 if p.resolved.startswith("_:"):
151 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
152 vwd.copy(path, p.target, source_collection=source)
153 elif p.type == "CreateFile":
154 if self.arvrunner.secret_store.has_secret(p.resolved):
155 secret_mounts["%s/%s" % (self.outdir, p.target)] = {
157 "content": self.arvrunner.secret_store.retrieve(p.resolved)
160 with vwd.open(p.target, "w") as n:
161 n.write(p.resolved.encode("utf-8"))
163 def keepemptydirs(p):
164 if isinstance(p, arvados.collection.RichCollectionBase):
166 p.open(".keep", "w").close()
173 if not runtimeContext.current_container:
174 runtimeContext.current_container = arvados_cwl.util.get_current_container(self.arvrunner.api, self.arvrunner.num_retries, logger)
175 info = arvados_cwl.util.get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
176 vwd.save_new(name=info["name"],
177 owner_uuid=runtimeContext.project_uuid,
178 ensure_unique_name=True,
179 trash_at=info["trash_at"],
180 properties=info["properties"])
183 for f, p in sorteditems:
184 if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
185 (prev is not None and p.target.startswith(prev))):
187 mountpoint = "%s/%s" % (self.outdir, p.target)
188 mounts[mountpoint] = {"kind": "collection",
189 "portable_data_hash": vwd.portable_data_hash(),
191 if p.type.startswith("Writable"):
192 mounts[mountpoint]["writable"] = True
193 prev = p.target + "/"
195 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
197 container_request["environment"].update(self.environment)
200 sp = self.stdin[6:].split("/", 1)
201 mounts["stdin"] = {"kind": "collection",
202 "portable_data_hash": sp[0],
206 mounts["stderr"] = {"kind": "file",
207 "path": "%s/%s" % (self.outdir, self.stderr)}
210 mounts["stdout"] = {"kind": "file",
211 "path": "%s/%s" % (self.outdir, self.stdout)}
213 (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
215 docker_req = {"dockerImageId": "arvados/jobs"}
217 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
219 runtimeContext.pull_image,
220 runtimeContext.project_uuid)
222 api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
224 runtime_constraints["API"] = True
226 runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
228 if "keep_cache" in runtime_req:
229 runtime_constraints["keep_cache_ram"] = math.ceil(runtime_req["keep_cache"] * 2**20)
230 if "outputDirType" in runtime_req:
231 if runtime_req["outputDirType"] == "local_output_dir":
232 # Currently the default behavior.
234 elif runtime_req["outputDirType"] == "keep_output_dir":
235 mounts[self.outdir]= {
236 "kind": "collection",
240 partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
242 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
244 intermediate_output_req, _ = self.get_requirement("http://arvados.org/cwl#IntermediateOutput")
245 if intermediate_output_req:
246 self.output_ttl = intermediate_output_req["outputTTL"]
248 self.output_ttl = self.arvrunner.intermediate_output_ttl
250 if self.output_ttl < 0:
251 raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
253 if self.timelimit is not None:
254 scheduling_parameters["max_run_time"] = self.timelimit
256 extra_submit_params = {}
257 if runtimeContext.submit_runner_cluster:
258 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
260 container_request["output_name"] = "Output for step %s" % (self.name)
261 container_request["output_ttl"] = self.output_ttl
262 container_request["mounts"] = mounts
263 container_request["secret_mounts"] = secret_mounts
264 container_request["runtime_constraints"] = runtime_constraints
265 container_request["scheduling_parameters"] = scheduling_parameters
267 enable_reuse = runtimeContext.enable_reuse
269 reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
271 enable_reuse = reuse_req["enableReuse"]
272 container_request["use_existing"] = enable_reuse
274 if runtimeContext.runnerjob.startswith("arvwf:"):
275 wfuuid = runtimeContext.runnerjob[6:runtimeContext.runnerjob.index("#")]
276 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
277 if container_request["name"] == "main":
278 container_request["name"] = wfrecord["name"]
279 container_request["properties"]["template_uuid"] = wfuuid
281 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
284 if runtimeContext.submit_request_uuid:
285 response = self.arvrunner.api.container_requests().update(
286 uuid=runtimeContext.submit_request_uuid,
287 body=container_request,
288 **extra_submit_params
289 ).execute(num_retries=self.arvrunner.num_retries)
291 response = self.arvrunner.api.container_requests().create(
292 body=container_request,
293 **extra_submit_params
294 ).execute(num_retries=self.arvrunner.num_retries)
296 self.uuid = response["uuid"]
297 self.arvrunner.process_submitted(self)
299 if response["state"] == "Final":
300 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
302 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
303 except Exception as e:
304 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
305 self.output_callback({}, "permanentFail")
307 def done(self, record):
310 container = self.arvrunner.api.containers().get(
311 uuid=record["container_uuid"]
312 ).execute(num_retries=self.arvrunner.num_retries)
313 if container["state"] == "Complete":
314 rcode = container["exit_code"]
315 if self.successCodes and rcode in self.successCodes:
316 processStatus = "success"
317 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
318 processStatus = "temporaryFail"
319 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
320 processStatus = "permanentFail"
322 processStatus = "success"
324 processStatus = "permanentFail"
326 processStatus = "permanentFail"
328 if processStatus == "permanentFail":
329 logc = arvados.collection.CollectionReader(container["log"],
330 api_client=self.arvrunner.api,
331 keep_client=self.arvrunner.keep_client,
332 num_retries=self.arvrunner.num_retries)
333 label = self.arvrunner.label(self)
336 "%s (%s) error log:" % (label, record["uuid"]), maxlen=40)
338 if record["output_uuid"]:
339 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
340 # Compute the trash time to avoid requesting the collection record.
341 trash_at = ciso8601.parse_datetime_unaware(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
342 aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
343 orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
344 oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
345 logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
346 self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
347 self.arvrunner.add_intermediate_output(record["output_uuid"])
349 if container["output"]:
350 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
351 except WorkflowException as e:
352 logger.error("%s unable to collect output from %s:\n%s",
353 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
354 processStatus = "permanentFail"
355 except Exception as e:
356 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
357 processStatus = "permanentFail"
359 self.output_callback(outputs, processStatus)
362 class RunnerContainer(Runner):
363 """Submit and manage a container that runs arvados-cwl-runner."""
365 def arvados_job_spec(self, runtimeContext):
366 """Create an Arvados container request for this workflow.
368 The returned dict can be used to create a container passed as
369 the +body+ argument to container_requests().create().
372 adjustDirObjs(self.job_order, trim_listing)
373 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
374 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
377 for param in sorted(self.job_order.keys()):
378 if self.secret_store.has_secret(self.job_order[param]):
379 mnt = "/secrets/s%d" % len(secret_mounts)
380 secret_mounts[mnt] = {
382 "content": self.secret_store.retrieve(self.job_order[param])
384 self.job_order[param] = {"$include": mnt}
388 "output_path": "/var/spool/cwl",
389 "cwd": "/var/spool/cwl",
390 "priority": self.priority,
391 "state": "Committed",
392 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
394 "/var/lib/cwl/cwl.input.json": {
396 "content": self.job_order
400 "path": "/var/spool/cwl/cwl.output.json"
403 "kind": "collection",
407 "secret_mounts": secret_mounts,
408 "runtime_constraints": {
409 "vcpus": math.ceil(self.submit_runner_cores),
410 "ram": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),
413 "use_existing": self.enable_reuse,
417 if self.embedded_tool.tool.get("id", "").startswith("keep:"):
418 sp = self.embedded_tool.tool["id"].split('/')
419 workflowcollection = sp[0][5:]
420 workflowname = "/".join(sp[1:])
421 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
422 container_req["mounts"]["/var/lib/cwl/workflow"] = {
423 "kind": "collection",
424 "portable_data_hash": "%s" % workflowcollection
427 packed = packed_workflow(self.arvrunner, self.embedded_tool, self.merged_map)
428 workflowpath = "/var/lib/cwl/workflow.json#main"
429 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
433 if self.embedded_tool.tool.get("id", "").startswith("arvwf:"):
434 container_req["properties"]["template_uuid"] = self.embedded_tool.tool["id"][6:33]
437 # --local means execute the workflow instead of submitting a container request
438 # --api=containers means use the containers API
439 # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
440 # --disable-validate because we already validated so don't need to do it again
441 # --eval-timeout is the timeout for javascript invocation
442 # --parallel-task-count is the number of threads to use for job submission
443 # --enable/disable-reuse sets desired job reuse
444 # --collection-cache-size sets aside memory to store collections
445 command = ["arvados-cwl-runner",
448 "--no-log-timestamps",
449 "--disable-validate",
450 "--eval-timeout=%s" % self.arvrunner.eval_timeout,
451 "--thread-count=%s" % self.arvrunner.thread_count,
452 "--enable-reuse" if self.enable_reuse else "--disable-reuse",
453 "--collection-cache-size=%s" % self.collection_cache_size]
456 command.append("--output-name=" + self.output_name)
457 container_req["output_name"] = self.output_name
460 command.append("--output-tags=" + self.output_tags)
462 if runtimeContext.debug:
463 command.append("--debug")
465 if runtimeContext.storage_classes != "default":
466 command.append("--storage-classes=" + runtimeContext.storage_classes)
469 command.append("--on-error=" + self.on_error)
471 if self.intermediate_output_ttl:
472 command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
474 if self.arvrunner.trash_intermediate:
475 command.append("--trash-intermediate")
477 if self.arvrunner.project_uuid:
478 command.append("--project-uuid="+self.arvrunner.project_uuid)
480 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
482 container_req["command"] = command
487 def run(self, runtimeContext):
488 runtimeContext.keepprefix = "keep:"
489 job_spec = self.arvados_job_spec(runtimeContext)
490 if self.arvrunner.project_uuid:
491 job_spec["owner_uuid"] = self.arvrunner.project_uuid
493 extra_submit_params = {}
494 if runtimeContext.submit_runner_cluster:
495 extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
497 if runtimeContext.submit_request_uuid:
498 response = self.arvrunner.api.container_requests().update(
499 uuid=runtimeContext.submit_request_uuid,
501 **extra_submit_params
502 ).execute(num_retries=self.arvrunner.num_retries)
504 response = self.arvrunner.api.container_requests().create(
506 **extra_submit_params
507 ).execute(num_retries=self.arvrunner.num_retries)
509 self.uuid = response["uuid"]
510 self.arvrunner.process_submitted(self)
512 logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
514 def done(self, record):
516 container = self.arvrunner.api.containers().get(
517 uuid=record["container_uuid"]
518 ).execute(num_retries=self.arvrunner.num_retries)
519 except Exception as e:
520 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
521 self.arvrunner.output_callback({}, "permanentFail")
523 super(RunnerContainer, self).done(container)