7 from cwltool.process import get_feature, shortname, UnsupportedRequirement
8 from cwltool.errors import WorkflowException
9 from cwltool.draft2tool import revmap_file, CommandLineTool
10 from cwltool.load_tool import fetch_document
11 from cwltool.builder import Builder
12 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs
14 from schema_salad.sourceline import SourceLine
16 import ruamel.yaml as yaml
18 import arvados.collection
20 from .arvdocker import arv_docker_get_image
21 from .runner import Runner, arvados_jobs_image, packed_workflow, upload_workflow_collection, trim_anonymous_location
22 from .pathmapper import VwdPathMapper, trim_listing
23 from .perf import Perf
25 from ._version import __version__
27 logger = logging.getLogger('arvados.cwl-runner')
28 metrics = logging.getLogger('arvados.cwl-runner.metrics')
30 crunchrunner_re = re.compile(r"^\S+ \S+ \d+ \d+ stderr \S+ \S+ crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)")
32 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
34 class ArvadosJob(object):
35 """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
37 def __init__(self, runner):
38 self.arvrunner = runner
42 def run(self, dry_run=False, pull_image=True, **kwargs):
44 "command": self.command_line
46 runtime_constraints = {}
48 with Perf(metrics, "generatefiles %s" % self.name):
49 if self.generatefiles["listing"]:
50 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
51 keep_client=self.arvrunner.keep_client,
52 num_retries=self.arvrunner.num_retries)
53 script_parameters["task.vwd"] = {}
54 generatemapper = VwdPathMapper([self.generatefiles], "", "",
57 with Perf(metrics, "createfiles %s" % self.name):
58 for f, p in generatemapper.items():
59 if p.type == "CreateFile":
60 with vwd.open(p.target, "w") as n:
61 n.write(p.resolved.encode("utf-8"))
64 with Perf(metrics, "generatefiles.save_new %s" % self.name):
67 for f, p in generatemapper.items():
69 script_parameters["task.vwd"][p.target] = p.resolved
70 if p.type == "CreateFile":
71 script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
73 script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
75 script_parameters["task.env"].update(self.environment)
78 script_parameters["task.stdin"] = self.stdin
81 script_parameters["task.stdout"] = self.stdout
84 script_parameters["task.stderr"] = self.stderr
87 script_parameters["task.successCodes"] = self.successCodes
88 if self.temporaryFailCodes:
89 script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
90 if self.permanentFailCodes:
91 script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
93 with Perf(metrics, "arv_docker_get_image %s" % self.name):
94 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
95 if docker_req and kwargs.get("use_container") is not False:
96 if docker_req.get("dockerOutputDirectory"):
97 raise SourceLine(docker_req, "dockerOutputDirectory", UnsupportedRequirement).makeError(
98 "Option 'dockerOutputDirectory' of DockerRequirement not supported.")
99 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api, docker_req, pull_image, self.arvrunner.project_uuid)
101 runtime_constraints["docker_image"] = "arvados/jobs"
103 resources = self.builder.resources
104 if resources is not None:
105 runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
106 runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
107 runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
109 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
111 if "keep_cache" in runtime_req:
112 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
113 runtime_constraints["min_ram_mb_per_node"] += runtime_req["keep_cache"]
114 if "outputDirType" in runtime_req:
115 if runtime_req["outputDirType"] == "local_output_dir":
116 script_parameters["task.keepTmpOutput"] = False
117 elif runtime_req["outputDirType"] == "keep_output_dir":
118 script_parameters["task.keepTmpOutput"] = True
120 filters = [["repository", "=", "arvados"],
121 ["script", "=", "crunchrunner"],
122 ["script_version", "in git", crunchrunner_git_commit]]
123 if not self.arvrunner.ignore_docker_for_reuse:
124 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
127 with Perf(metrics, "create %s" % self.name):
128 response = self.arvrunner.api.jobs().create(
130 "owner_uuid": self.arvrunner.project_uuid,
131 "script": "crunchrunner",
132 "repository": "arvados",
133 "script_version": "master",
134 "minimum_script_version": crunchrunner_git_commit,
135 "script_parameters": {"tasks": [script_parameters]},
136 "runtime_constraints": runtime_constraints
139 find_or_create=kwargs.get("enable_reuse", True)
140 ).execute(num_retries=self.arvrunner.num_retries)
142 self.arvrunner.processes[response["uuid"]] = self
144 self.update_pipeline_component(response)
146 if response["state"] == "Complete":
147 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
148 with Perf(metrics, "done %s" % self.name):
151 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
152 except Exception as e:
153 logger.exception("%s error" % (self.arvrunner.label(self)))
154 self.output_callback({}, "permanentFail")
156 def update_pipeline_component(self, record):
157 if self.arvrunner.pipeline:
158 self.arvrunner.pipeline["components"][self.name] = {"job": record}
159 with Perf(metrics, "update_pipeline_component %s" % self.name):
160 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
162 "components": self.arvrunner.pipeline["components"]
163 }).execute(num_retries=self.arvrunner.num_retries)
164 if self.arvrunner.uuid:
166 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
168 components = job["components"]
169 components[self.name] = record["uuid"]
170 self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
172 "components": components
173 }).execute(num_retries=self.arvrunner.num_retries)
174 except Exception as e:
175 logger.info("Error adding to components: %s", e)
177 def done(self, record):
179 self.update_pipeline_component(record)
184 if record["state"] == "Complete":
185 processStatus = "success"
187 processStatus = "permanentFail"
192 with Perf(metrics, "inspect log %s" % self.name):
193 logc = arvados.collection.CollectionReader(record["log"],
194 api_client=self.arvrunner.api,
195 keep_client=self.arvrunner.keep_client,
196 num_retries=self.arvrunner.num_retries)
197 log = logc.open(logc.keys()[0])
203 # Determine the tmpdir, outdir and keepdir paths from
204 # the job run. Unfortunately, we can't take the first
205 # values we find (which are expected to be near the
206 # top) and stop scanning because if the node fails and
207 # the job restarts on a different node these values
208 # will different runs, and we need to know about the
209 # final run that actually produced output.
210 g = crunchrunner_re.match(l)
212 dirs[g.group(1)] = g.group(2)
214 if processStatus == "permanentFail":
215 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
217 with Perf(metrics, "output collection %s" % self.name):
218 outputs = done.done(self, record, dirs["tmpdir"],
219 dirs["outdir"], dirs["keep"])
220 except WorkflowException as e:
221 logger.error("%s unable to collect output from %s:\n%s",
222 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
223 processStatus = "permanentFail"
224 except Exception as e:
225 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
226 processStatus = "permanentFail"
228 # Note: Currently, on error output_callback is expecting an empty dict,
229 # anything else will fail.
230 if not isinstance(outputs, dict):
231 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
233 processStatus = "permanentFail"
235 self.output_callback(outputs, processStatus)
236 if record["uuid"] in self.arvrunner.processes:
237 del self.arvrunner.processes[record["uuid"]]
239 class RunnerJob(Runner):
240 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
242 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
243 """Create an Arvados job specification for this workflow.
245 The returned dict can be used to create a job (i.e., passed as
246 the +body+ argument to jobs().create()), or as a component in
247 a pipeline template or pipeline instance.
250 if self.tool.tool["id"].startswith("keep:"):
251 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
253 packed = packed_workflow(self.arvrunner, self.tool)
254 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
255 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
257 adjustDirObjs(self.job_order, trim_listing)
258 adjustFileObjs(self.job_order, trim_anonymous_location)
259 adjustDirObjs(self.job_order, trim_anonymous_location)
262 self.job_order["arv:output_name"] = self.output_name
265 self.job_order["arv:output_tags"] = self.output_tags
267 self.job_order["arv:enable_reuse"] = self.enable_reuse
270 self.job_order["arv:on_error"] = self.on_error
273 "script": "cwl-runner",
274 "script_version": "master",
275 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
276 "repository": "arvados",
277 "script_parameters": self.job_order,
278 "runtime_constraints": {
279 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
280 "min_ram_mb_per_node": self.submit_runner_ram
284 def run(self, *args, **kwargs):
285 job_spec = self.arvados_job_spec(*args, **kwargs)
287 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
289 job = self.arvrunner.api.jobs().create(
291 find_or_create=self.enable_reuse
292 ).execute(num_retries=self.arvrunner.num_retries)
294 for k,v in job_spec["script_parameters"].items():
295 if v is False or v is None or isinstance(v, dict):
296 job_spec["script_parameters"][k] = {"value": v}
298 del job_spec["owner_uuid"]
299 job_spec["job"] = job
300 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
302 "owner_uuid": self.arvrunner.project_uuid,
304 "components": {"cwl-runner": job_spec },
305 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
306 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
308 if kwargs.get("wait") is False:
309 self.uuid = self.arvrunner.pipeline["uuid"]
312 self.uuid = job["uuid"]
313 self.arvrunner.processes[self.uuid] = self
315 if job["state"] in ("Complete", "Failed", "Cancelled"):
319 class RunnerTemplate(object):
320 """An Arvados pipeline template that invokes a CWL workflow."""
322 type_to_dataclass = {
323 'boolean': 'boolean',
325 'Directory': 'Collection',
331 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
332 submit_runner_ram=0, name=None):
335 self.job = RunnerJob(
339 enable_reuse=enable_reuse,
342 submit_runner_ram=submit_runner_ram,
346 def pipeline_component_spec(self):
347 """Return a component that Workbench and a-r-p-i will understand.
349 Specifically, translate CWL input specs to Arvados pipeline
350 format, like {"dataclass":"File","value":"xyz"}.
353 spec = self.job.arvados_job_spec()
355 # Most of the component spec is exactly the same as the job
356 # spec (script, script_version, etc.).
357 # spec['script_parameters'] isn't right, though. A component
358 # spec's script_parameters hash is a translation of
359 # self.tool.tool['inputs'] with defaults/overrides taken from
360 # the job order. So we move the job parameters out of the way
361 # and build a new spec['script_parameters'].
362 job_params = spec['script_parameters']
363 spec['script_parameters'] = {}
365 for param in self.tool.tool['inputs']:
366 param = copy.deepcopy(param)
368 # Data type and "required" flag...
369 types = param['type']
370 if not isinstance(types, list):
372 param['required'] = 'null' not in types
373 non_null_types = [t for t in types if t != "null"]
374 if len(non_null_types) == 1:
375 the_type = [c for c in non_null_types][0]
377 if isinstance(the_type, basestring):
378 dataclass = self.type_to_dataclass.get(the_type)
380 param['dataclass'] = dataclass
381 # Note: If we didn't figure out a single appropriate
382 # dataclass, we just left that attribute out. We leave
383 # the "type" attribute there in any case, which might help
386 # Title and description...
387 title = param.pop('label', '')
388 descr = param.pop('doc', '').rstrip('\n')
390 param['title'] = title
392 param['description'] = descr
394 # Fill in the value from the current job order, if any.
395 param_id = shortname(param.pop('id'))
396 value = job_params.get(param_id)
399 elif not isinstance(value, dict):
400 param['value'] = value
401 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
402 param['value'] = value['location'][5:]
404 spec['script_parameters'][param_id] = param
405 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
411 self.job.name: self.pipeline_component_spec(),
413 "name": self.job.name,
415 if self.runner.project_uuid:
416 body["owner_uuid"] = self.runner.project_uuid
418 self.runner.api.pipeline_templates().update(
419 uuid=self.uuid, body=body).execute(
420 num_retries=self.runner.num_retries)
421 logger.info("Updated template %s", self.uuid)
423 self.uuid = self.runner.api.pipeline_templates().create(
424 body=body, ensure_unique_name=True).execute(
425 num_retries=self.runner.num_retries)['uuid']
426 logger.info("Created template %s", self.uuid)