1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
14 import ruamel.yaml as yaml
16 from cwltool.errors import WorkflowException
17 from cwltool.process import get_feature, UnsupportedRequirement, shortname
18 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
19 from cwltool.utils import aslist
21 import arvados.collection
23 from arvados.errors import ApiError
24 from .arvdocker import arv_docker_get_image
26 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields
27 from .fsaccess import CollectionFetcher
28 from .pathmapper import NoFollowPathMapper, trim_listing
29 from .perf import Perf
31 logger = logging.getLogger('arvados.cwl-runner')
32 metrics = logging.getLogger('arvados.cwl-runner.metrics')
34 class ArvadosContainer(object):
35 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
37 def __init__(self, runner):
38 self.arvrunner = runner
42 def update_pipeline_component(self, r):
45 def run(self, dry_run=False, pull_image=True, **kwargs):
46 # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
47 # which calls makeJobRunner() to get a new ArvadosContainer
48 # object. The fields that define execution such as
49 # command_line, environment, etc are set on the
50 # ArvadosContainer object by CommandLineTool.job() before
54 "command": self.command_line,
56 "output_path": self.outdir,
58 "priority": kwargs.get("priority"),
62 runtime_constraints = {}
64 if self.arvrunner.project_uuid:
65 container_request["owner_uuid"] = self.arvrunner.project_uuid
67 if self.arvrunner.secret_store.has_secret(self.command_line):
68 raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
70 if self.arvrunner.secret_store.has_secret(self.environment):
71 raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
73 resources = self.builder.resources
74 if resources is not None:
75 runtime_constraints["vcpus"] = resources.get("cores", 1)
76 runtime_constraints["ram"] = resources.get("ram") * 2**20
81 "capacity": resources.get("outdirSize", 0) * 2**20
85 "capacity": resources.get("tmpdirSize", 0) * 2**20
89 scheduling_parameters = {}
91 rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
92 rf.sort(key=lambda k: k.resolved)
94 for resolved, target, tp, stg in rf:
97 if prevdir and target.startswith(prevdir):
102 targetdir = os.path.dirname(target)
103 sp = resolved.split("/", 1)
104 pdh = sp[0][5:] # remove "keep:"
105 mounts[targetdir] = {
106 "kind": "collection",
107 "portable_data_hash": pdh
110 if tp == "Directory":
113 path = os.path.dirname(sp[1])
114 if path and path != "/":
115 mounts[targetdir]["path"] = path
116 prevdir = targetdir + "/"
118 with Perf(metrics, "generatefiles %s" % self.name):
119 if self.generatefiles["listing"]:
120 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
121 keep_client=self.arvrunner.keep_client,
122 num_retries=self.arvrunner.num_retries)
123 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
126 sorteditems = sorted(generatemapper.items(), None, key=lambda n: n[1].target)
128 logger.debug("generatemapper is %s", sorteditems)
130 with Perf(metrics, "createfiles %s" % self.name):
131 for f, p in sorteditems:
134 elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
135 if p.resolved.startswith("_:"):
138 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
139 vwd.copy(path, p.target, source_collection=source)
140 elif p.type == "CreateFile":
141 if self.arvrunner.secret_store.has_secret(p.resolved):
142 secret_mounts["%s/%s" % (self.outdir, p.target)] = {
144 "content": self.arvrunner.secret_store.retrieve(p.resolved)
147 with vwd.open(p.target, "w") as n:
148 n.write(p.resolved.encode("utf-8"))
150 def keepemptydirs(p):
151 if isinstance(p, arvados.collection.RichCollectionBase):
153 p.open(".keep", "w").close()
161 if self.arvrunner.intermediate_output_ttl > 0:
162 trash_time = datetime.datetime.now() + datetime.timedelta(seconds=self.arvrunner.intermediate_output_ttl)
164 current_container_uuid = None
166 current_container = self.arvrunner.api.containers().current().execute(num_retries=self.arvrunner.num_retries)
167 current_container_uuid = current_container['uuid']
168 except ApiError as e:
169 # Status code 404 just means we're not running in a container.
170 if e.resp.status != 404:
171 logger.info("Getting current container: %s", e)
172 props = {"type": "Intermediate",
173 "container": current_container_uuid}
175 with Perf(metrics, "generatefiles.save_new %s" % self.name):
176 vwd.save_new(name="Intermediate collection",
177 ensure_unique_name=True,
182 for f, p in sorteditems:
183 if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
184 (prev is not None and p.target.startswith(prev))):
186 mountpoint = "%s/%s" % (self.outdir, p.target)
187 mounts[mountpoint] = {"kind": "collection",
188 "portable_data_hash": vwd.portable_data_hash(),
190 if p.type.startswith("Writable"):
191 mounts[mountpoint]["writable"] = True
192 prev = p.target + "/"
194 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
196 container_request["environment"].update(self.environment)
199 sp = self.stdin[6:].split("/", 1)
200 mounts["stdin"] = {"kind": "collection",
201 "portable_data_hash": sp[0],
205 mounts["stderr"] = {"kind": "file",
206 "path": "%s/%s" % (self.outdir, self.stderr)}
209 mounts["stdout"] = {"kind": "file",
210 "path": "%s/%s" % (self.outdir, self.stdout)}
212 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
214 docker_req = {"dockerImageId": "arvados/jobs"}
216 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
219 self.arvrunner.project_uuid)
221 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
223 runtime_constraints["API"] = True
225 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
227 if "keep_cache" in runtime_req:
228 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
229 if "outputDirType" in runtime_req:
230 if runtime_req["outputDirType"] == "local_output_dir":
231 # Currently the default behavior.
233 elif runtime_req["outputDirType"] == "keep_output_dir":
234 mounts[self.outdir]= {
235 "kind": "collection",
239 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
241 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
243 intermediate_output_req, _ = get_feature(self, "http://arvados.org/cwl#IntermediateOutput")
244 if intermediate_output_req:
245 self.output_ttl = intermediate_output_req["outputTTL"]
247 self.output_ttl = self.arvrunner.intermediate_output_ttl
249 if self.output_ttl < 0:
250 raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
252 container_request["output_ttl"] = self.output_ttl
253 container_request["mounts"] = mounts
254 container_request["secret_mounts"] = secret_mounts
255 container_request["runtime_constraints"] = runtime_constraints
256 container_request["scheduling_parameters"] = scheduling_parameters
258 enable_reuse = kwargs.get("enable_reuse", True)
260 reuse_req, _ = get_feature(self, "http://arvados.org/cwl#ReuseRequirement")
262 enable_reuse = reuse_req["enableReuse"]
263 container_request["use_existing"] = enable_reuse
265 if kwargs.get("runnerjob", "").startswith("arvwf:"):
266 wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
267 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
268 if container_request["name"] == "main":
269 container_request["name"] = wfrecord["name"]
270 container_request["properties"]["template_uuid"] = wfuuid
272 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
275 if kwargs.get("submit_request_uuid"):
276 response = self.arvrunner.api.container_requests().update(
277 uuid=kwargs["submit_request_uuid"],
278 body=container_request
279 ).execute(num_retries=self.arvrunner.num_retries)
281 response = self.arvrunner.api.container_requests().create(
282 body=container_request
283 ).execute(num_retries=self.arvrunner.num_retries)
285 self.uuid = response["uuid"]
286 self.arvrunner.process_submitted(self)
288 if response["state"] == "Final":
289 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
291 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
292 except Exception as e:
293 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
294 self.output_callback({}, "permanentFail")
296 def done(self, record):
299 container = self.arvrunner.api.containers().get(
300 uuid=record["container_uuid"]
301 ).execute(num_retries=self.arvrunner.num_retries)
302 if container["state"] == "Complete":
303 rcode = container["exit_code"]
304 if self.successCodes and rcode in self.successCodes:
305 processStatus = "success"
306 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
307 processStatus = "temporaryFail"
308 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
309 processStatus = "permanentFail"
311 processStatus = "success"
313 processStatus = "permanentFail"
315 processStatus = "permanentFail"
317 if processStatus == "permanentFail":
318 logc = arvados.collection.CollectionReader(container["log"],
319 api_client=self.arvrunner.api,
320 keep_client=self.arvrunner.keep_client,
321 num_retries=self.arvrunner.num_retries)
322 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
324 if record["output_uuid"]:
325 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
326 # Compute the trash time to avoid requesting the collection record.
327 trash_at = ciso8601.parse_datetime_unaware(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
328 aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
329 orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
330 oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
331 logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
332 self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
333 self.arvrunner.add_intermediate_output(record["output_uuid"])
335 if container["output"]:
336 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
337 except WorkflowException as e:
338 logger.error("%s unable to collect output from %s:\n%s",
339 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
340 processStatus = "permanentFail"
341 except Exception as e:
342 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
343 processStatus = "permanentFail"
345 self.output_callback(outputs, processStatus)
348 class RunnerContainer(Runner):
349 """Submit and manage a container that runs arvados-cwl-runner."""
351 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
352 """Create an Arvados container request for this workflow.
354 The returned dict can be used to create a container passed as
355 the +body+ argument to container_requests().create().
358 adjustDirObjs(self.job_order, trim_listing)
359 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
360 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
363 for param in sorted(self.job_order.keys()):
364 if self.secret_store.has_secret(self.job_order[param]):
365 mnt = "/secrets/s%d" % len(secret_mounts)
366 secret_mounts[mnt] = {
368 "content": self.secret_store.retrieve(self.job_order[param])
370 self.job_order[param] = {"$include": mnt}
374 "output_path": "/var/spool/cwl",
375 "cwd": "/var/spool/cwl",
376 "priority": self.priority,
377 "state": "Committed",
378 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
380 "/var/lib/cwl/cwl.input.json": {
382 "content": self.job_order
386 "path": "/var/spool/cwl/cwl.output.json"
389 "kind": "collection",
393 "secret_mounts": secret_mounts,
394 "runtime_constraints": {
396 "ram": 1024*1024 * self.submit_runner_ram,
399 "use_existing": self.enable_reuse,
403 if self.tool.tool.get("id", "").startswith("keep:"):
404 sp = self.tool.tool["id"].split('/')
405 workflowcollection = sp[0][5:]
406 workflowname = "/".join(sp[1:])
407 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
408 container_req["mounts"]["/var/lib/cwl/workflow"] = {
409 "kind": "collection",
410 "portable_data_hash": "%s" % workflowcollection
413 packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
414 workflowpath = "/var/lib/cwl/workflow.json#main"
415 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
419 if self.tool.tool.get("id", "").startswith("arvwf:"):
420 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
423 # --local means execute the workflow instead of submitting a container request
424 # --api=containers means use the containers API
425 # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
426 # --disable-validate because we already validated so don't need to do it again
427 # --eval-timeout is the timeout for javascript invocation
428 # --parallel-task-count is the number of threads to use for job submission
429 # --enable/disable-reuse sets desired job reuse
430 command = ["arvados-cwl-runner",
433 "--no-log-timestamps",
434 "--disable-validate",
435 "--eval-timeout=%s" % self.arvrunner.eval_timeout,
436 "--thread-count=%s" % self.arvrunner.thread_count,
437 "--enable-reuse" if self.enable_reuse else "--disable-reuse"]
440 command.append("--output-name=" + self.output_name)
441 container_req["output_name"] = self.output_name
444 command.append("--output-tags=" + self.output_tags)
446 if kwargs.get("debug"):
447 command.append("--debug")
450 command.append("--on-error=" + self.on_error)
452 if self.intermediate_output_ttl:
453 command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
455 if self.arvrunner.trash_intermediate:
456 command.append("--trash-intermediate")
458 if self.arvrunner.project_uuid:
459 command.append("--project-uuid="+self.arvrunner.project_uuid)
461 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
463 container_req["command"] = command
468 def run(self, **kwargs):
469 kwargs["keepprefix"] = "keep:"
470 job_spec = self.arvados_job_spec(**kwargs)
471 if self.arvrunner.project_uuid:
472 job_spec["owner_uuid"] = self.arvrunner.project_uuid
474 if kwargs.get("submit_request_uuid"):
475 response = self.arvrunner.api.container_requests().update(
476 uuid=kwargs["submit_request_uuid"],
478 ).execute(num_retries=self.arvrunner.num_retries)
480 response = self.arvrunner.api.container_requests().create(
482 ).execute(num_retries=self.arvrunner.num_retries)
484 self.uuid = response["uuid"]
485 self.arvrunner.process_submitted(self)
487 logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
489 def done(self, record):
491 container = self.arvrunner.api.containers().get(
492 uuid=record["container_uuid"]
493 ).execute(num_retries=self.arvrunner.num_retries)
494 except Exception as e:
495 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
496 self.arvrunner.output_callback({}, "permanentFail")
498 super(RunnerContainer, self).done(container)