1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
11 from cwltool.process import 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
17 from cwltool.job import JobBase
19 from schema_salad.sourceline import SourceLine
21 import ruamel.yaml as yaml
23 import arvados.collection
24 from arvados.errors import ApiError
26 from .arvdocker import arv_docker_get_image
27 from .runner import Runner, arvados_jobs_image, packed_workflow, upload_workflow_collection, trim_anonymous_location, remove_redundant_fields
28 from .pathmapper import VwdPathMapper, trim_listing
29 from .perf import Perf
31 from ._version import __version__
33 logger = logging.getLogger('arvados.cwl-runner')
34 metrics = logging.getLogger('arvados.cwl-runner.metrics')
36 crunchrunner_re = re.compile(r"^.*crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)$")
38 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
40 class ArvadosJob(JobBase):
41 """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
43 def __init__(self, runner,
44 builder, # type: Builder
45 joborder, # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
46 make_path_mapper, # type: Callable[..., PathMapper]
47 requirements, # type: List[Dict[Text, Text]]
48 hints, # type: List[Dict[Text, Text]]
51 super(ArvadosJob, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
52 self.arvrunner = runner
56 def run(self, runtimeContext):
58 "command": self.command_line
60 runtime_constraints = {}
62 with Perf(metrics, "generatefiles %s" % self.name):
63 if self.generatefiles["listing"]:
64 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
65 keep_client=self.arvrunner.keep_client,
66 num_retries=self.arvrunner.num_retries)
67 script_parameters["task.vwd"] = {}
68 generatemapper = VwdPathMapper([self.generatefiles], "", "",
71 with Perf(metrics, "createfiles %s" % self.name):
72 for f, p in generatemapper.items():
73 if p.type == "CreateFile":
74 with vwd.open(p.target, "w") as n:
75 n.write(p.resolved.encode("utf-8"))
78 with Perf(metrics, "generatefiles.save_new %s" % self.name):
81 for f, p in generatemapper.items():
83 script_parameters["task.vwd"][p.target] = p.resolved
84 if p.type == "CreateFile":
85 script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
87 script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
89 script_parameters["task.env"].update(self.environment)
92 script_parameters["task.stdin"] = self.stdin
95 script_parameters["task.stdout"] = self.stdout
98 script_parameters["task.stderr"] = self.stderr
100 if self.successCodes:
101 script_parameters["task.successCodes"] = self.successCodes
102 if self.temporaryFailCodes:
103 script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
104 if self.permanentFailCodes:
105 script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
107 with Perf(metrics, "arv_docker_get_image %s" % self.name):
108 (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
109 if docker_req and runtimeContext.use_container is not False:
110 if docker_req.get("dockerOutputDirectory"):
111 raise SourceLine(docker_req, "dockerOutputDirectory", UnsupportedRequirement).makeError(
112 "Option 'dockerOutputDirectory' of DockerRequirement not supported.")
113 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api,
115 runtimeContext.pull_image,
116 self.arvrunner.project_uuid)
118 runtime_constraints["docker_image"] = "arvados/jobs"
120 resources = self.builder.resources
121 if resources is not None:
122 runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
123 runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
124 runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
126 runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
128 if "keep_cache" in runtime_req:
129 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
130 runtime_constraints["min_ram_mb_per_node"] += runtime_req["keep_cache"]
131 if "outputDirType" in runtime_req:
132 if runtime_req["outputDirType"] == "local_output_dir":
133 script_parameters["task.keepTmpOutput"] = False
134 elif runtime_req["outputDirType"] == "keep_output_dir":
135 script_parameters["task.keepTmpOutput"] = True
137 filters = [["repository", "=", "arvados"],
138 ["script", "=", "crunchrunner"],
139 ["script_version", "in git", crunchrunner_git_commit]]
140 if not self.arvrunner.ignore_docker_for_reuse:
141 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
143 enable_reuse = runtimeContext.enable_reuse
145 reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
147 enable_reuse = reuse_req["enableReuse"]
149 self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
152 with Perf(metrics, "create %s" % self.name):
153 response = self.arvrunner.api.jobs().create(
155 "owner_uuid": self.arvrunner.project_uuid,
156 "script": "crunchrunner",
157 "repository": "arvados",
158 "script_version": "master",
159 "minimum_script_version": crunchrunner_git_commit,
160 "script_parameters": {"tasks": [script_parameters]},
161 "runtime_constraints": runtime_constraints
164 find_or_create=enable_reuse
165 ).execute(num_retries=self.arvrunner.num_retries)
167 self.uuid = response["uuid"]
168 self.arvrunner.process_submitted(self)
170 self.update_pipeline_component(response)
172 if response["state"] == "Complete":
173 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
174 # Give read permission to the desired project on reused jobs
175 if response["owner_uuid"] != self.arvrunner.project_uuid:
177 self.arvrunner.api.links().create(body={
178 'link_class': 'permission',
180 'tail_uuid': self.arvrunner.project_uuid,
181 'head_uuid': response["uuid"],
182 }).execute(num_retries=self.arvrunner.num_retries)
183 except ApiError as e:
184 # The user might not have "manage" access on the job: log
185 # a message and continue.
186 logger.info("Creating read permission on job %s: %s",
190 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
191 except Exception as e:
192 logger.exception("%s error" % (self.arvrunner.label(self)))
193 self.output_callback({}, "permanentFail")
195 def update_pipeline_component(self, record):
196 with self.arvrunner.workflow_eval_lock:
197 if self.arvrunner.pipeline:
198 self.arvrunner.pipeline["components"][self.name] = {"job": record}
199 with Perf(metrics, "update_pipeline_component %s" % self.name):
200 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(
201 uuid=self.arvrunner.pipeline["uuid"],
203 "components": self.arvrunner.pipeline["components"]
204 }).execute(num_retries=self.arvrunner.num_retries)
205 if self.arvrunner.uuid:
207 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
209 components = job["components"]
210 components[self.name] = record["uuid"]
211 self.arvrunner.api.jobs().update(
212 uuid=self.arvrunner.uuid,
214 "components": components
215 }).execute(num_retries=self.arvrunner.num_retries)
216 except Exception as e:
217 logger.info("Error adding to components: %s", e)
219 def done(self, record):
221 self.update_pipeline_component(record)
226 if record["state"] == "Complete":
227 processStatus = "success"
229 processStatus = "permanentFail"
234 with Perf(metrics, "inspect log %s" % self.name):
235 logc = arvados.collection.CollectionReader(record["log"],
236 api_client=self.arvrunner.api,
237 keep_client=self.arvrunner.keep_client,
238 num_retries=self.arvrunner.num_retries)
239 log = logc.open(logc.keys()[0])
246 # Determine the tmpdir, outdir and keep paths from
247 # the job run. Unfortunately, we can't take the first
248 # values we find (which are expected to be near the
249 # top) and stop scanning because if the node fails and
250 # the job restarts on a different node these values
251 # will different runs, and we need to know about the
252 # final run that actually produced output.
253 g = crunchrunner_re.match(l)
255 dirs[g.group(1)] = g.group(2)
257 if processStatus == "permanentFail":
258 done.logtail(logc, logger.error, "%s (%s) error log:" % (self.arvrunner.label(self), record["uuid"]), maxlen=40)
260 with Perf(metrics, "output collection %s" % self.name):
261 outputs = done.done(self, record, dirs["tmpdir"],
262 dirs["outdir"], dirs["keep"])
263 except WorkflowException as e:
264 logger.error("%s unable to collect output from %s:\n%s",
265 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
266 processStatus = "permanentFail"
267 except Exception as e:
268 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
269 processStatus = "permanentFail"
271 # Note: Currently, on error output_callback is expecting an empty dict,
272 # anything else will fail.
273 if not isinstance(outputs, dict):
274 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
276 processStatus = "permanentFail"
278 self.output_callback(outputs, processStatus)
281 class RunnerJob(Runner):
282 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
284 def arvados_job_spec(self, debug=False):
285 """Create an Arvados job specification for this workflow.
287 The returned dict can be used to create a job (i.e., passed as
288 the +body+ argument to jobs().create()), or as a component in
289 a pipeline template or pipeline instance.
292 if self.tool.tool["id"].startswith("keep:"):
293 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
295 packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
296 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
297 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
299 adjustDirObjs(self.job_order, trim_listing)
300 visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
301 visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
304 self.job_order["arv:output_name"] = self.output_name
307 self.job_order["arv:output_tags"] = self.output_tags
309 self.job_order["arv:enable_reuse"] = self.enable_reuse
312 self.job_order["arv:on_error"] = self.on_error
315 self.job_order["arv:debug"] = True
318 "script": "cwl-runner",
319 "script_version": "master",
320 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
321 "repository": "arvados",
322 "script_parameters": self.job_order,
323 "runtime_constraints": {
324 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
325 "min_ram_mb_per_node": self.submit_runner_ram
329 def run(self, runtimeContext):
330 job_spec = self.arvados_job_spec(runtimeContext.debug)
332 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
334 job = self.arvrunner.api.jobs().create(
336 find_or_create=self.enable_reuse
337 ).execute(num_retries=self.arvrunner.num_retries)
339 for k,v in job_spec["script_parameters"].items():
340 if v is False or v is None or isinstance(v, dict):
341 job_spec["script_parameters"][k] = {"value": v}
343 del job_spec["owner_uuid"]
344 job_spec["job"] = job
347 "owner_uuid": self.arvrunner.project_uuid,
350 "cwl-runner": job_spec,
352 "state": "RunningOnServer",
354 if not self.enable_reuse:
355 instance_spec["properties"] = {"run_options": {"enable_job_reuse": False}}
357 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
358 body=instance_spec).execute(num_retries=self.arvrunner.num_retries)
359 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
361 if runtimeContext.wait is False:
362 self.uuid = self.arvrunner.pipeline["uuid"]
365 self.uuid = job["uuid"]
366 self.arvrunner.process_submitted(self)
369 class RunnerTemplate(object):
370 """An Arvados pipeline template that invokes a CWL workflow."""
372 type_to_dataclass = {
373 'boolean': 'boolean',
375 'Directory': 'Collection',
381 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
382 submit_runner_ram=0, name=None, merged_map=None):
385 self.job = RunnerJob(
389 enable_reuse=enable_reuse,
392 submit_runner_ram=submit_runner_ram,
394 merged_map=merged_map)
397 def pipeline_component_spec(self):
398 """Return a component that Workbench and a-r-p-i will understand.
400 Specifically, translate CWL input specs to Arvados pipeline
401 format, like {"dataclass":"File","value":"xyz"}.
404 spec = self.job.arvados_job_spec()
406 # Most of the component spec is exactly the same as the job
407 # spec (script, script_version, etc.).
408 # spec['script_parameters'] isn't right, though. A component
409 # spec's script_parameters hash is a translation of
410 # self.tool.tool['inputs'] with defaults/overrides taken from
411 # the job order. So we move the job parameters out of the way
412 # and build a new spec['script_parameters'].
413 job_params = spec['script_parameters']
414 spec['script_parameters'] = {}
416 for param in self.tool.tool['inputs']:
417 param = copy.deepcopy(param)
419 # Data type and "required" flag...
420 types = param['type']
421 if not isinstance(types, list):
423 param['required'] = 'null' not in types
424 non_null_types = [t for t in types if t != "null"]
425 if len(non_null_types) == 1:
426 the_type = [c for c in non_null_types][0]
428 if isinstance(the_type, basestring):
429 dataclass = self.type_to_dataclass.get(the_type)
431 param['dataclass'] = dataclass
432 # Note: If we didn't figure out a single appropriate
433 # dataclass, we just left that attribute out. We leave
434 # the "type" attribute there in any case, which might help
437 # Title and description...
438 title = param.pop('label', '')
439 descr = param.pop('doc', '').rstrip('\n')
441 param['title'] = title
443 param['description'] = descr
445 # Fill in the value from the current job order, if any.
446 param_id = shortname(param.pop('id'))
447 value = job_params.get(param_id)
450 elif not isinstance(value, dict):
451 param['value'] = value
452 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
453 param['value'] = value['location'][5:]
455 spec['script_parameters'][param_id] = param
456 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
462 self.job.name: self.pipeline_component_spec(),
464 "name": self.job.name,
466 if self.runner.project_uuid:
467 body["owner_uuid"] = self.runner.project_uuid
469 self.runner.api.pipeline_templates().update(
470 uuid=self.uuid, body=body).execute(
471 num_retries=self.runner.num_retries)
472 logger.info("Updated template %s", self.uuid)
474 self.uuid = self.runner.api.pipeline_templates().create(
475 body=body, ensure_unique_name=True).execute(
476 num_retries=self.runner.num_retries)['uuid']
477 logger.info("Created template %s", self.uuid)