1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
11 from cwltool.process import get_feature, shortname, UnsupportedRequirement
12 from cwltool.errors import WorkflowException
13 from cwltool.command_line_tool import revmap_file, CommandLineTool
14 from cwltool.load_tool import fetch_document
15 from cwltool.builder import Builder
16 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
18 from schema_salad.sourceline import SourceLine
20 import ruamel.yaml as yaml
22 import arvados.collection
23 from arvados.errors import ApiError
25 from .arvdocker import arv_docker_get_image
26 from .runner import Runner, arvados_jobs_image, packed_workflow, upload_workflow_collection, trim_anonymous_location, remove_redundant_fields
27 from .pathmapper import VwdPathMapper, trim_listing
28 from .perf import Perf
30 from ._version import __version__
32 logger = logging.getLogger('arvados.cwl-runner')
33 metrics = logging.getLogger('arvados.cwl-runner.metrics')
35 crunchrunner_re = re.compile(r"^.*crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)$")
37 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
39 class ArvadosJob(object):
40 """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
42 def __init__(self, runner):
43 self.arvrunner = runner
47 def run(self, dry_run=False, pull_image=True, **kwargs):
49 "command": self.command_line
51 runtime_constraints = {}
53 with Perf(metrics, "generatefiles %s" % self.name):
54 if self.generatefiles["listing"]:
55 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
56 keep_client=self.arvrunner.keep_client,
57 num_retries=self.arvrunner.num_retries)
58 script_parameters["task.vwd"] = {}
59 generatemapper = VwdPathMapper([self.generatefiles], "", "",
62 with Perf(metrics, "createfiles %s" % self.name):
63 for f, p in generatemapper.items():
64 if p.type == "CreateFile":
65 with vwd.open(p.target, "w") as n:
66 n.write(p.resolved.encode("utf-8"))
69 with Perf(metrics, "generatefiles.save_new %s" % self.name):
72 for f, p in generatemapper.items():
74 script_parameters["task.vwd"][p.target] = p.resolved
75 if p.type == "CreateFile":
76 script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
78 script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
80 script_parameters["task.env"].update(self.environment)
83 script_parameters["task.stdin"] = self.stdin
86 script_parameters["task.stdout"] = self.stdout
89 script_parameters["task.stderr"] = self.stderr
92 script_parameters["task.successCodes"] = self.successCodes
93 if self.temporaryFailCodes:
94 script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
95 if self.permanentFailCodes:
96 script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
98 with Perf(metrics, "arv_docker_get_image %s" % self.name):
99 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
100 if docker_req and kwargs.get("use_container") is not False:
101 if docker_req.get("dockerOutputDirectory"):
102 raise SourceLine(docker_req, "dockerOutputDirectory", UnsupportedRequirement).makeError(
103 "Option 'dockerOutputDirectory' of DockerRequirement not supported.")
104 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api, docker_req, pull_image, self.arvrunner.project_uuid)
106 runtime_constraints["docker_image"] = "arvados/jobs"
108 resources = self.builder.resources
109 if resources is not None:
110 runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
111 runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
112 runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
114 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
116 if "keep_cache" in runtime_req:
117 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
118 runtime_constraints["min_ram_mb_per_node"] += runtime_req["keep_cache"]
119 if "outputDirType" in runtime_req:
120 if runtime_req["outputDirType"] == "local_output_dir":
121 script_parameters["task.keepTmpOutput"] = False
122 elif runtime_req["outputDirType"] == "keep_output_dir":
123 script_parameters["task.keepTmpOutput"] = True
125 filters = [["repository", "=", "arvados"],
126 ["script", "=", "crunchrunner"],
127 ["script_version", "in git", crunchrunner_git_commit]]
128 if not self.arvrunner.ignore_docker_for_reuse:
129 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
131 enable_reuse = kwargs.get("enable_reuse", True)
133 reuse_req, _ = get_feature(self, "http://arvados.org/cwl#ReuseRequirement")
135 enable_reuse = reuse_req["enableReuse"]
137 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
140 with Perf(metrics, "create %s" % self.name):
141 response = self.arvrunner.api.jobs().create(
143 "owner_uuid": self.arvrunner.project_uuid,
144 "script": "crunchrunner",
145 "repository": "arvados",
146 "script_version": "master",
147 "minimum_script_version": crunchrunner_git_commit,
148 "script_parameters": {"tasks": [script_parameters]},
149 "runtime_constraints": runtime_constraints
152 find_or_create=enable_reuse
153 ).execute(num_retries=self.arvrunner.num_retries)
155 self.uuid = response["uuid"]
156 self.arvrunner.process_submitted(self)
158 self.update_pipeline_component(response)
160 if response["state"] == "Complete":
161 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
162 # Give read permission to the desired project on reused jobs
163 if response["owner_uuid"] != self.arvrunner.project_uuid:
165 self.arvrunner.api.links().create(body={
166 'link_class': 'permission',
168 'tail_uuid': self.arvrunner.project_uuid,
169 'head_uuid': response["uuid"],
170 }).execute(num_retries=self.arvrunner.num_retries)
171 except ApiError as e:
172 # The user might not have "manage" access on the job: log
173 # a message and continue.
174 logger.info("Creating read permission on job %s: %s",
178 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
179 except Exception as e:
180 logger.exception("%s error" % (self.arvrunner.label(self)))
181 self.output_callback({}, "permanentFail")
183 def update_pipeline_component(self, record):
184 with self.arvrunner.workflow_eval_lock:
185 if self.arvrunner.pipeline:
186 self.arvrunner.pipeline["components"][self.name] = {"job": record}
187 with Perf(metrics, "update_pipeline_component %s" % self.name):
188 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(
189 uuid=self.arvrunner.pipeline["uuid"],
191 "components": self.arvrunner.pipeline["components"]
192 }).execute(num_retries=self.arvrunner.num_retries)
193 if self.arvrunner.uuid:
195 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
197 components = job["components"]
198 components[self.name] = record["uuid"]
199 self.arvrunner.api.jobs().update(
200 uuid=self.arvrunner.uuid,
202 "components": components
203 }).execute(num_retries=self.arvrunner.num_retries)
204 except Exception as e:
205 logger.info("Error adding to components: %s", e)
207 def done(self, record):
209 self.update_pipeline_component(record)
214 if record["state"] == "Complete":
215 processStatus = "success"
217 processStatus = "permanentFail"
222 with Perf(metrics, "inspect log %s" % self.name):
223 logc = arvados.collection.CollectionReader(record["log"],
224 api_client=self.arvrunner.api,
225 keep_client=self.arvrunner.keep_client,
226 num_retries=self.arvrunner.num_retries)
227 log = logc.open(logc.keys()[0])
234 # Determine the tmpdir, outdir and keep paths from
235 # the job run. Unfortunately, we can't take the first
236 # values we find (which are expected to be near the
237 # top) and stop scanning because if the node fails and
238 # the job restarts on a different node these values
239 # will different runs, and we need to know about the
240 # final run that actually produced output.
241 g = crunchrunner_re.match(l)
243 dirs[g.group(1)] = g.group(2)
245 if processStatus == "permanentFail":
246 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
248 with Perf(metrics, "output collection %s" % self.name):
249 outputs = done.done(self, record, dirs["tmpdir"],
250 dirs["outdir"], dirs["keep"])
251 except WorkflowException as e:
252 logger.error("%s unable to collect output from %s:\n%s",
253 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
254 processStatus = "permanentFail"
255 except Exception as e:
256 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
257 processStatus = "permanentFail"
259 # Note: Currently, on error output_callback is expecting an empty dict,
260 # anything else will fail.
261 if not isinstance(outputs, dict):
262 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
264 processStatus = "permanentFail"
266 self.output_callback(outputs, processStatus)
269 class RunnerJob(Runner):
270 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
272 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
273 """Create an Arvados job specification for this workflow.
275 The returned dict can be used to create a job (i.e., passed as
276 the +body+ argument to jobs().create()), or as a component in
277 a pipeline template or pipeline instance.
280 if self.tool.tool["id"].startswith("keep:"):
281 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
283 packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
284 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
285 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
287 adjustDirObjs(self.job_order, trim_listing)
288 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
289 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
292 self.job_order["arv:output_name"] = self.output_name
295 self.job_order["arv:output_tags"] = self.output_tags
297 self.job_order["arv:enable_reuse"] = self.enable_reuse
300 self.job_order["arv:on_error"] = self.on_error
302 if kwargs.get("debug"):
303 self.job_order["arv:debug"] = True
306 "script": "cwl-runner",
307 "script_version": "master",
308 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
309 "repository": "arvados",
310 "script_parameters": self.job_order,
311 "runtime_constraints": {
312 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
313 "min_ram_mb_per_node": self.submit_runner_ram
317 def run(self, **kwargs):
318 job_spec = self.arvados_job_spec(**kwargs)
320 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
322 job = self.arvrunner.api.jobs().create(
324 find_or_create=self.enable_reuse
325 ).execute(num_retries=self.arvrunner.num_retries)
327 for k,v in job_spec["script_parameters"].items():
328 if v is False or v is None or isinstance(v, dict):
329 job_spec["script_parameters"][k] = {"value": v}
331 del job_spec["owner_uuid"]
332 job_spec["job"] = job
335 "owner_uuid": self.arvrunner.project_uuid,
338 "cwl-runner": job_spec,
340 "state": "RunningOnServer",
342 if not self.enable_reuse:
343 instance_spec["properties"] = {"run_options": {"enable_job_reuse": False}}
345 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
346 body=instance_spec).execute(num_retries=self.arvrunner.num_retries)
347 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
349 if kwargs.get("wait") is False:
350 self.uuid = self.arvrunner.pipeline["uuid"]
353 self.uuid = job["uuid"]
354 self.arvrunner.process_submitted(self)
357 class RunnerTemplate(object):
358 """An Arvados pipeline template that invokes a CWL workflow."""
360 type_to_dataclass = {
361 'boolean': 'boolean',
363 'Directory': 'Collection',
369 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
370 submit_runner_ram=0, name=None, merged_map=None):
373 self.job = RunnerJob(
377 enable_reuse=enable_reuse,
380 submit_runner_ram=submit_runner_ram,
382 merged_map=merged_map)
385 def pipeline_component_spec(self):
386 """Return a component that Workbench and a-r-p-i will understand.
388 Specifically, translate CWL input specs to Arvados pipeline
389 format, like {"dataclass":"File","value":"xyz"}.
392 spec = self.job.arvados_job_spec()
394 # Most of the component spec is exactly the same as the job
395 # spec (script, script_version, etc.).
396 # spec['script_parameters'] isn't right, though. A component
397 # spec's script_parameters hash is a translation of
398 # self.tool.tool['inputs'] with defaults/overrides taken from
399 # the job order. So we move the job parameters out of the way
400 # and build a new spec['script_parameters'].
401 job_params = spec['script_parameters']
402 spec['script_parameters'] = {}
404 for param in self.tool.tool['inputs']:
405 param = copy.deepcopy(param)
407 # Data type and "required" flag...
408 types = param['type']
409 if not isinstance(types, list):
411 param['required'] = 'null' not in types
412 non_null_types = [t for t in types if t != "null"]
413 if len(non_null_types) == 1:
414 the_type = [c for c in non_null_types][0]
416 if isinstance(the_type, basestring):
417 dataclass = self.type_to_dataclass.get(the_type)
419 param['dataclass'] = dataclass
420 # Note: If we didn't figure out a single appropriate
421 # dataclass, we just left that attribute out. We leave
422 # the "type" attribute there in any case, which might help
425 # Title and description...
426 title = param.pop('label', '')
427 descr = param.pop('doc', '').rstrip('\n')
429 param['title'] = title
431 param['description'] = descr
433 # Fill in the value from the current job order, if any.
434 param_id = shortname(param.pop('id'))
435 value = job_params.get(param_id)
438 elif not isinstance(value, dict):
439 param['value'] = value
440 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
441 param['value'] = value['location'][5:]
443 spec['script_parameters'][param_id] = param
444 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
450 self.job.name: self.pipeline_component_spec(),
452 "name": self.job.name,
454 if self.runner.project_uuid:
455 body["owner_uuid"] = self.runner.project_uuid
457 self.runner.api.pipeline_templates().update(
458 uuid=self.uuid, body=body).execute(
459 num_retries=self.runner.num_retries)
460 logger.info("Updated template %s", self.uuid)
462 self.uuid = self.runner.api.pipeline_templates().create(
463 body=body, ensure_unique_name=True).execute(
464 num_retries=self.runner.num_retries)['uuid']
465 logger.info("Created template %s", self.uuid)