1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 from past.builtins import basestring
6 from builtins import object
7 from future.utils import viewitems
15 from cwltool.process import shortname, UnsupportedRequirement
16 from cwltool.errors import WorkflowException
17 from cwltool.command_line_tool import revmap_file, CommandLineTool
18 from cwltool.load_tool import fetch_document
19 from cwltool.builder import Builder
20 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
21 from cwltool.job import JobBase
23 from schema_salad.sourceline import SourceLine
25 import arvados_cwl.util
26 import ruamel.yaml as yaml
28 import arvados.collection
29 from arvados.errors import ApiError
31 from .arvdocker import arv_docker_get_image
32 from .runner import Runner, arvados_jobs_image, packed_workflow, upload_workflow_collection, trim_anonymous_location, remove_redundant_fields
33 from .pathmapper import VwdPathMapper, trim_listing
34 from .perf import Perf
36 from ._version import __version__
37 from .util import get_intermediate_collection_info
39 logger = logging.getLogger('arvados.cwl-runner')
40 metrics = logging.getLogger('arvados.cwl-runner.metrics')
42 crunchrunner_re = re.compile(r"^.*crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)$")
44 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
46 class ArvadosJob(JobBase):
47 """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
49 def __init__(self, runner,
50 builder, # type: Builder
51 joborder, # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
52 make_path_mapper, # type: Callable[..., PathMapper]
53 requirements, # type: List[Dict[Text, Text]]
54 hints, # type: List[Dict[Text, Text]]
57 super(ArvadosJob, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
58 self.arvrunner = runner
62 def run(self, runtimeContext):
64 "command": self.command_line
66 runtime_constraints = {}
68 with Perf(metrics, "generatefiles %s" % self.name):
69 if self.generatefiles["listing"]:
70 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
71 keep_client=self.arvrunner.keep_client,
72 num_retries=self.arvrunner.num_retries)
73 script_parameters["task.vwd"] = {}
74 generatemapper = VwdPathMapper(self.generatefiles["listing"], "", "",
77 with Perf(metrics, "createfiles %s" % self.name):
78 for f, p in generatemapper.items():
79 if p.type == "CreateFile":
80 with vwd.open(p.target, "w") as n:
81 n.write(p.resolved.encode("utf-8"))
84 with Perf(metrics, "generatefiles.save_new %s" % self.name):
85 info = get_intermediate_collection_info(self.name, None, runtimeContext.intermediate_output_ttl)
86 vwd.save_new(name=info["name"],
87 owner_uuid=self.arvrunner.project_uuid,
88 ensure_unique_name=True,
89 trash_at=info["trash_at"],
90 properties=info["properties"])
92 for f, p in generatemapper.items():
94 script_parameters["task.vwd"][p.target] = p.resolved
95 if p.type == "CreateFile":
96 script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
98 script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
100 script_parameters["task.env"].update(self.environment)
103 script_parameters["task.stdin"] = self.stdin
106 script_parameters["task.stdout"] = self.stdout
109 script_parameters["task.stderr"] = self.stderr
111 if self.successCodes:
112 script_parameters["task.successCodes"] = self.successCodes
113 if self.temporaryFailCodes:
114 script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
115 if self.permanentFailCodes:
116 script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
118 with Perf(metrics, "arv_docker_get_image %s" % self.name):
119 (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
120 if docker_req and runtimeContext.use_container is not False:
121 if docker_req.get("dockerOutputDirectory"):
122 raise SourceLine(docker_req, "dockerOutputDirectory", UnsupportedRequirement).makeError(
123 "Option 'dockerOutputDirectory' of DockerRequirement not supported.")
124 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api,
126 runtimeContext.pull_image,
127 self.arvrunner.project_uuid)
129 runtime_constraints["docker_image"] = "arvados/jobs"
131 resources = self.builder.resources
132 if resources is not None:
133 runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
134 runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
135 runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
137 runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
139 if "keep_cache" in runtime_req:
140 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
141 runtime_constraints["min_ram_mb_per_node"] += runtime_req["keep_cache"]
142 if "outputDirType" in runtime_req:
143 if runtime_req["outputDirType"] == "local_output_dir":
144 script_parameters["task.keepTmpOutput"] = False
145 elif runtime_req["outputDirType"] == "keep_output_dir":
146 script_parameters["task.keepTmpOutput"] = True
148 filters = [["repository", "=", "arvados"],
149 ["script", "=", "crunchrunner"],
150 ["script_version", "in git", crunchrunner_git_commit]]
151 if not self.arvrunner.ignore_docker_for_reuse:
152 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
154 enable_reuse = runtimeContext.enable_reuse
156 reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
158 enable_reuse = reuse_req["enableReuse"]
160 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
163 with Perf(metrics, "create %s" % self.name):
164 response = self.arvrunner.api.jobs().create(
166 "owner_uuid": self.arvrunner.project_uuid,
167 "script": "crunchrunner",
168 "repository": "arvados",
169 "script_version": "master",
170 "minimum_script_version": crunchrunner_git_commit,
171 "script_parameters": {"tasks": [script_parameters]},
172 "runtime_constraints": runtime_constraints
175 find_or_create=enable_reuse
176 ).execute(num_retries=self.arvrunner.num_retries)
178 self.uuid = response["uuid"]
179 self.arvrunner.process_submitted(self)
181 self.update_pipeline_component(response)
183 if response["state"] == "Complete":
184 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
185 # Give read permission to the desired project on reused jobs
186 if response["owner_uuid"] != self.arvrunner.project_uuid:
188 self.arvrunner.api.links().create(body={
189 'link_class': 'permission',
191 'tail_uuid': self.arvrunner.project_uuid,
192 'head_uuid': response["uuid"],
193 }).execute(num_retries=self.arvrunner.num_retries)
194 except ApiError as e:
195 # The user might not have "manage" access on the job: log
196 # a message and continue.
197 logger.info("Creating read permission on job %s: %s",
201 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
203 logger.exception("%s error" % (self.arvrunner.label(self)))
204 self.output_callback({}, "permanentFail")
206 def update_pipeline_component(self, record):
207 with self.arvrunner.workflow_eval_lock:
208 if self.arvrunner.pipeline:
209 self.arvrunner.pipeline["components"][self.name] = {"job": record}
210 with Perf(metrics, "update_pipeline_component %s" % self.name):
211 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(
212 uuid=self.arvrunner.pipeline["uuid"],
214 "components": self.arvrunner.pipeline["components"]
215 }).execute(num_retries=self.arvrunner.num_retries)
216 if self.arvrunner.uuid:
218 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
220 components = job["components"]
221 components[self.name] = record["uuid"]
222 self.arvrunner.api.jobs().update(
223 uuid=self.arvrunner.uuid,
225 "components": components
226 }).execute(num_retries=self.arvrunner.num_retries)
228 logger.exception("Error adding to components")
230 def done(self, record):
232 self.update_pipeline_component(record)
237 if record["state"] == "Complete":
238 processStatus = "success"
240 processStatus = "permanentFail"
245 with Perf(metrics, "inspect log %s" % self.name):
246 logc = arvados.collection.CollectionReader(record["log"],
247 api_client=self.arvrunner.api,
248 keep_client=self.arvrunner.keep_client,
249 num_retries=self.arvrunner.num_retries)
250 log = logc.open(list(logc.keys())[0])
257 # Determine the tmpdir, outdir and keep paths from
258 # the job run. Unfortunately, we can't take the first
259 # values we find (which are expected to be near the
260 # top) and stop scanning because if the node fails and
261 # the job restarts on a different node these values
262 # will different runs, and we need to know about the
263 # final run that actually produced output.
264 g = crunchrunner_re.match(l)
266 dirs[g.group(1)] = g.group(2)
268 if processStatus == "permanentFail":
269 done.logtail(logc, logger.error, "%s (%s) error log:" % (self.arvrunner.label(self), record["uuid"]), maxlen=40)
271 with Perf(metrics, "output collection %s" % self.name):
272 outputs = done.done(self, record, dirs["tmpdir"],
273 dirs["outdir"], dirs["keep"])
274 except WorkflowException as e:
275 # Only include a stack trace if in debug mode.
276 # This is most likely a user workflow error and a stack trace may obfuscate more useful output.
277 logger.error("%s unable to collect output from %s:\n%s",
278 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
279 processStatus = "permanentFail"
281 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
282 processStatus = "permanentFail"
284 # Note: Currently, on error output_callback is expecting an empty dict,
285 # anything else will fail.
286 if not isinstance(outputs, dict):
287 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
289 processStatus = "permanentFail"
291 self.output_callback(outputs, processStatus)
294 class RunnerJob(Runner):
295 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
297 def arvados_job_spec(self, debug=False):
298 """Create an Arvados job specification for this workflow.
300 The returned dict can be used to create a job (i.e., passed as
301 the +body+ argument to jobs().create()), or as a component in
302 a pipeline template or pipeline instance.
305 if self.embedded_tool.tool["id"].startswith("keep:"):
306 self.job_order["cwl:tool"] = self.embedded_tool.tool["id"][5:]
308 packed = packed_workflow(self.arvrunner, self.embedded_tool, self.merged_map)
309 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
310 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
312 adjustDirObjs(self.job_order, trim_listing)
313 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
314 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
317 self.job_order["arv:output_name"] = self.output_name
320 self.job_order["arv:output_tags"] = self.output_tags
322 self.job_order["arv:enable_reuse"] = self.enable_reuse
325 self.job_order["arv:on_error"] = self.on_error
328 self.job_order["arv:debug"] = True
331 "script": "cwl-runner",
332 "script_version": "master",
333 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
334 "repository": "arvados",
335 "script_parameters": self.job_order,
336 "runtime_constraints": {
337 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
338 "min_ram_mb_per_node": self.submit_runner_ram
342 def run(self, runtimeContext):
343 job_spec = self.arvados_job_spec(runtimeContext.debug)
345 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
347 job = self.arvrunner.api.jobs().create(
349 find_or_create=self.enable_reuse
350 ).execute(num_retries=self.arvrunner.num_retries)
352 for k,v in viewitems(job_spec["script_parameters"]):
353 if v is False or v is None or isinstance(v, dict):
354 job_spec["script_parameters"][k] = {"value": v}
356 del job_spec["owner_uuid"]
357 job_spec["job"] = job
360 "owner_uuid": self.arvrunner.project_uuid,
363 "cwl-runner": job_spec,
365 "state": "RunningOnServer",
367 if not self.enable_reuse:
368 instance_spec["properties"] = {"run_options": {"enable_job_reuse": False}}
370 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
371 body=instance_spec).execute(num_retries=self.arvrunner.num_retries)
372 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
374 if runtimeContext.wait is False:
375 self.uuid = self.arvrunner.pipeline["uuid"]
378 self.uuid = job["uuid"]
379 self.arvrunner.process_submitted(self)
382 class RunnerTemplate(object):
383 """An Arvados pipeline template that invokes a CWL workflow."""
385 type_to_dataclass = {
386 'boolean': 'boolean',
388 'Directory': 'Collection',
394 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
395 submit_runner_ram=0, name=None, merged_map=None,
396 loadingContext=None):
398 self.embedded_tool = tool
399 self.job = RunnerJob(
402 enable_reuse=enable_reuse,
405 submit_runner_ram=submit_runner_ram,
407 merged_map=merged_map,
408 loadingContext=loadingContext)
409 self.job.job_order = job_order
412 def pipeline_component_spec(self):
413 """Return a component that Workbench and a-r-p-i will understand.
415 Specifically, translate CWL input specs to Arvados pipeline
416 format, like {"dataclass":"File","value":"xyz"}.
419 spec = self.job.arvados_job_spec()
421 # Most of the component spec is exactly the same as the job
422 # spec (script, script_version, etc.).
423 # spec['script_parameters'] isn't right, though. A component
424 # spec's script_parameters hash is a translation of
425 # self.tool.tool['inputs'] with defaults/overrides taken from
426 # the job order. So we move the job parameters out of the way
427 # and build a new spec['script_parameters'].
428 job_params = spec['script_parameters']
429 spec['script_parameters'] = {}
431 for param in self.embedded_tool.tool['inputs']:
432 param = copy.deepcopy(param)
434 # Data type and "required" flag...
435 types = param['type']
436 if not isinstance(types, list):
438 param['required'] = 'null' not in types
439 non_null_types = [t for t in types if t != "null"]
440 if len(non_null_types) == 1:
441 the_type = [c for c in non_null_types][0]
443 if isinstance(the_type, basestring):
444 dataclass = self.type_to_dataclass.get(the_type)
446 param['dataclass'] = dataclass
447 # Note: If we didn't figure out a single appropriate
448 # dataclass, we just left that attribute out. We leave
449 # the "type" attribute there in any case, which might help
452 # Title and description...
453 title = param.pop('label', '')
454 descr = param.pop('doc', '').rstrip('\n')
456 param['title'] = title
458 param['description'] = descr
460 # Fill in the value from the current job order, if any.
461 param_id = shortname(param.pop('id'))
462 value = job_params.get(param_id)
465 elif not isinstance(value, dict):
466 param['value'] = value
467 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
468 param['value'] = value['location'][5:]
470 spec['script_parameters'][param_id] = param
471 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
477 self.job.name: self.pipeline_component_spec(),
479 "name": self.job.name,
481 if self.runner.project_uuid:
482 body["owner_uuid"] = self.runner.project_uuid
484 self.runner.api.pipeline_templates().update(
485 uuid=self.uuid, body=body).execute(
486 num_retries=self.runner.num_retries)
487 logger.info("Updated template %s", self.uuid)
489 self.uuid = self.runner.api.pipeline_templates().create(
490 body=body, ensure_unique_name=True).execute(
491 num_retries=self.runner.num_retries)['uuid']
492 logger.info("Created template %s", self.uuid)