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.draft2tool 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
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
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"^\S+ \S+ \d+ \d+ stderr \S+ \S+ 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"]
138 with Perf(metrics, "create %s" % self.name):
139 response = self.arvrunner.api.jobs().create(
141 "owner_uuid": self.arvrunner.project_uuid,
142 "script": "crunchrunner",
143 "repository": "arvados",
144 "script_version": "master",
145 "minimum_script_version": crunchrunner_git_commit,
146 "script_parameters": {"tasks": [script_parameters]},
147 "runtime_constraints": runtime_constraints
150 find_or_create=enable_reuse
151 ).execute(num_retries=self.arvrunner.num_retries)
153 self.arvrunner.processes[response["uuid"]] = self
155 self.update_pipeline_component(response)
157 if response["state"] == "Complete":
158 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
159 # Give read permission to the desired project on reused jobs
160 if response["owner_uuid"] != self.arvrunner.project_uuid:
162 self.arvrunner.api.links().create(body={
163 'link_class': 'permission',
165 'tail_uuid': self.arvrunner.project_uuid,
166 'head_uuid': response["uuid"],
167 }).execute(num_retries=self.arvrunner.num_retries)
168 except ApiError as e:
169 # The user might not have "manage" access on the job: log
170 # a message and continue.
171 logger.info("Creating read permission on job %s: %s",
175 with Perf(metrics, "done %s" % self.name):
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 if self.arvrunner.pipeline:
185 self.arvrunner.pipeline["components"][self.name] = {"job": record}
186 with Perf(metrics, "update_pipeline_component %s" % self.name):
187 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
189 "components": self.arvrunner.pipeline["components"]
190 }).execute(num_retries=self.arvrunner.num_retries)
191 if self.arvrunner.uuid:
193 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
195 components = job["components"]
196 components[self.name] = record["uuid"]
197 self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
199 "components": components
200 }).execute(num_retries=self.arvrunner.num_retries)
201 except Exception as e:
202 logger.info("Error adding to components: %s", e)
204 def done(self, record):
206 self.update_pipeline_component(record)
211 if record["state"] == "Complete":
212 processStatus = "success"
214 processStatus = "permanentFail"
219 with Perf(metrics, "inspect log %s" % self.name):
220 logc = arvados.collection.CollectionReader(record["log"],
221 api_client=self.arvrunner.api,
222 keep_client=self.arvrunner.keep_client,
223 num_retries=self.arvrunner.num_retries)
224 log = logc.open(logc.keys()[0])
230 # Determine the tmpdir, outdir and keepdir paths from
231 # the job run. Unfortunately, we can't take the first
232 # values we find (which are expected to be near the
233 # top) and stop scanning because if the node fails and
234 # the job restarts on a different node these values
235 # will different runs, and we need to know about the
236 # final run that actually produced output.
237 g = crunchrunner_re.match(l)
239 dirs[g.group(1)] = g.group(2)
241 if processStatus == "permanentFail":
242 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
244 with Perf(metrics, "output collection %s" % self.name):
245 outputs = done.done(self, record, dirs["tmpdir"],
246 dirs["outdir"], dirs["keep"])
247 except WorkflowException as e:
248 logger.error("%s unable to collect output from %s:\n%s",
249 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
250 processStatus = "permanentFail"
251 except Exception as e:
252 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
253 processStatus = "permanentFail"
255 # Note: Currently, on error output_callback is expecting an empty dict,
256 # anything else will fail.
257 if not isinstance(outputs, dict):
258 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
260 processStatus = "permanentFail"
262 self.output_callback(outputs, processStatus)
263 if record["uuid"] in self.arvrunner.processes:
264 del self.arvrunner.processes[record["uuid"]]
266 class RunnerJob(Runner):
267 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
269 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
270 """Create an Arvados job specification for this workflow.
272 The returned dict can be used to create a job (i.e., passed as
273 the +body+ argument to jobs().create()), or as a component in
274 a pipeline template or pipeline instance.
277 if self.tool.tool["id"].startswith("keep:"):
278 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
280 packed = packed_workflow(self.arvrunner, self.tool)
281 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
282 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
284 adjustDirObjs(self.job_order, trim_listing)
285 adjustFileObjs(self.job_order, trim_anonymous_location)
286 adjustDirObjs(self.job_order, trim_anonymous_location)
289 self.job_order["arv:output_name"] = self.output_name
292 self.job_order["arv:output_tags"] = self.output_tags
294 self.job_order["arv:enable_reuse"] = self.enable_reuse
297 self.job_order["arv:on_error"] = self.on_error
300 "script": "cwl-runner",
301 "script_version": "master",
302 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
303 "repository": "arvados",
304 "script_parameters": self.job_order,
305 "runtime_constraints": {
306 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
307 "min_ram_mb_per_node": self.submit_runner_ram
311 def run(self, *args, **kwargs):
312 job_spec = self.arvados_job_spec(*args, **kwargs)
314 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
316 job = self.arvrunner.api.jobs().create(
318 find_or_create=self.enable_reuse
319 ).execute(num_retries=self.arvrunner.num_retries)
321 for k,v in job_spec["script_parameters"].items():
322 if v is False or v is None or isinstance(v, dict):
323 job_spec["script_parameters"][k] = {"value": v}
325 del job_spec["owner_uuid"]
326 job_spec["job"] = job
327 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
329 "owner_uuid": self.arvrunner.project_uuid,
331 "components": {"cwl-runner": job_spec },
332 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
333 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
335 if kwargs.get("wait") is False:
336 self.uuid = self.arvrunner.pipeline["uuid"]
339 self.uuid = job["uuid"]
340 self.arvrunner.processes[self.uuid] = self
342 if job["state"] in ("Complete", "Failed", "Cancelled"):
346 class RunnerTemplate(object):
347 """An Arvados pipeline template that invokes a CWL workflow."""
349 type_to_dataclass = {
350 'boolean': 'boolean',
352 'Directory': 'Collection',
358 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
359 submit_runner_ram=0, name=None):
362 self.job = RunnerJob(
366 enable_reuse=enable_reuse,
369 submit_runner_ram=submit_runner_ram,
373 def pipeline_component_spec(self):
374 """Return a component that Workbench and a-r-p-i will understand.
376 Specifically, translate CWL input specs to Arvados pipeline
377 format, like {"dataclass":"File","value":"xyz"}.
380 spec = self.job.arvados_job_spec()
382 # Most of the component spec is exactly the same as the job
383 # spec (script, script_version, etc.).
384 # spec['script_parameters'] isn't right, though. A component
385 # spec's script_parameters hash is a translation of
386 # self.tool.tool['inputs'] with defaults/overrides taken from
387 # the job order. So we move the job parameters out of the way
388 # and build a new spec['script_parameters'].
389 job_params = spec['script_parameters']
390 spec['script_parameters'] = {}
392 for param in self.tool.tool['inputs']:
393 param = copy.deepcopy(param)
395 # Data type and "required" flag...
396 types = param['type']
397 if not isinstance(types, list):
399 param['required'] = 'null' not in types
400 non_null_types = [t for t in types if t != "null"]
401 if len(non_null_types) == 1:
402 the_type = [c for c in non_null_types][0]
404 if isinstance(the_type, basestring):
405 dataclass = self.type_to_dataclass.get(the_type)
407 param['dataclass'] = dataclass
408 # Note: If we didn't figure out a single appropriate
409 # dataclass, we just left that attribute out. We leave
410 # the "type" attribute there in any case, which might help
413 # Title and description...
414 title = param.pop('label', '')
415 descr = param.pop('doc', '').rstrip('\n')
417 param['title'] = title
419 param['description'] = descr
421 # Fill in the value from the current job order, if any.
422 param_id = shortname(param.pop('id'))
423 value = job_params.get(param_id)
426 elif not isinstance(value, dict):
427 param['value'] = value
428 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
429 param['value'] = value['location'][5:]
431 spec['script_parameters'][param_id] = param
432 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
438 self.job.name: self.pipeline_component_spec(),
440 "name": self.job.name,
442 if self.runner.project_uuid:
443 body["owner_uuid"] = self.runner.project_uuid
445 self.runner.api.pipeline_templates().update(
446 uuid=self.uuid, body=body).execute(
447 num_retries=self.runner.num_retries)
448 logger.info("Updated template %s", self.uuid)
450 self.uuid = self.runner.api.pipeline_templates().create(
451 body=body, ensure_unique_name=True).execute(
452 num_retries=self.runner.num_retries)['uuid']
453 logger.info("Created template %s", self.uuid)