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 # Give read permission to the desired project on reused jobs
149 if response["owner_uuid"] != self.arvrunner.project_uuid:
150 self.arvrunner.api.links().create(body={
151 'link_class': 'permission',
153 'tail_uuid': self.arvrunner.project_uuid,
154 'head_uuid': response["uuid"],
155 }).execute(num_retries=self.arvrunner.num_retries)
157 with Perf(metrics, "done %s" % self.name):
160 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
161 except Exception as e:
162 logger.exception("%s error" % (self.arvrunner.label(self)))
163 self.output_callback({}, "permanentFail")
165 def update_pipeline_component(self, record):
166 if self.arvrunner.pipeline:
167 self.arvrunner.pipeline["components"][self.name] = {"job": record}
168 with Perf(metrics, "update_pipeline_component %s" % self.name):
169 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
171 "components": self.arvrunner.pipeline["components"]
172 }).execute(num_retries=self.arvrunner.num_retries)
173 if self.arvrunner.uuid:
175 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
177 components = job["components"]
178 components[self.name] = record["uuid"]
179 self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
181 "components": components
182 }).execute(num_retries=self.arvrunner.num_retries)
183 except Exception as e:
184 logger.info("Error adding to components: %s", e)
186 def done(self, record):
188 self.update_pipeline_component(record)
193 if record["state"] == "Complete":
194 processStatus = "success"
196 processStatus = "permanentFail"
201 with Perf(metrics, "inspect log %s" % self.name):
202 logc = arvados.collection.CollectionReader(record["log"],
203 api_client=self.arvrunner.api,
204 keep_client=self.arvrunner.keep_client,
205 num_retries=self.arvrunner.num_retries)
206 log = logc.open(logc.keys()[0])
212 # Determine the tmpdir, outdir and keepdir paths from
213 # the job run. Unfortunately, we can't take the first
214 # values we find (which are expected to be near the
215 # top) and stop scanning because if the node fails and
216 # the job restarts on a different node these values
217 # will different runs, and we need to know about the
218 # final run that actually produced output.
219 g = crunchrunner_re.match(l)
221 dirs[g.group(1)] = g.group(2)
223 if processStatus == "permanentFail":
224 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
226 with Perf(metrics, "output collection %s" % self.name):
227 outputs = done.done(self, record, dirs["tmpdir"],
228 dirs["outdir"], dirs["keep"])
229 except WorkflowException as e:
230 logger.error("%s unable to collect output from %s:\n%s",
231 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
232 processStatus = "permanentFail"
233 except Exception as e:
234 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
235 processStatus = "permanentFail"
237 # Note: Currently, on error output_callback is expecting an empty dict,
238 # anything else will fail.
239 if not isinstance(outputs, dict):
240 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
242 processStatus = "permanentFail"
244 self.output_callback(outputs, processStatus)
245 if record["uuid"] in self.arvrunner.processes:
246 del self.arvrunner.processes[record["uuid"]]
248 class RunnerJob(Runner):
249 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
251 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
252 """Create an Arvados job specification for this workflow.
254 The returned dict can be used to create a job (i.e., passed as
255 the +body+ argument to jobs().create()), or as a component in
256 a pipeline template or pipeline instance.
259 if self.tool.tool["id"].startswith("keep:"):
260 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
262 packed = packed_workflow(self.arvrunner, self.tool)
263 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
264 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
266 adjustDirObjs(self.job_order, trim_listing)
267 adjustFileObjs(self.job_order, trim_anonymous_location)
268 adjustDirObjs(self.job_order, trim_anonymous_location)
271 self.job_order["arv:output_name"] = self.output_name
274 self.job_order["arv:output_tags"] = self.output_tags
276 self.job_order["arv:enable_reuse"] = self.enable_reuse
279 self.job_order["arv:on_error"] = self.on_error
282 "script": "cwl-runner",
283 "script_version": "master",
284 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
285 "repository": "arvados",
286 "script_parameters": self.job_order,
287 "runtime_constraints": {
288 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
289 "min_ram_mb_per_node": self.submit_runner_ram
293 def run(self, *args, **kwargs):
294 job_spec = self.arvados_job_spec(*args, **kwargs)
296 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
298 job = self.arvrunner.api.jobs().create(
300 find_or_create=self.enable_reuse
301 ).execute(num_retries=self.arvrunner.num_retries)
303 for k,v in job_spec["script_parameters"].items():
304 if v is False or v is None or isinstance(v, dict):
305 job_spec["script_parameters"][k] = {"value": v}
307 del job_spec["owner_uuid"]
308 job_spec["job"] = job
309 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
311 "owner_uuid": self.arvrunner.project_uuid,
313 "components": {"cwl-runner": job_spec },
314 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
315 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
317 if kwargs.get("wait") is False:
318 self.uuid = self.arvrunner.pipeline["uuid"]
321 self.uuid = job["uuid"]
322 self.arvrunner.processes[self.uuid] = self
324 if job["state"] in ("Complete", "Failed", "Cancelled"):
328 class RunnerTemplate(object):
329 """An Arvados pipeline template that invokes a CWL workflow."""
331 type_to_dataclass = {
332 'boolean': 'boolean',
334 'Directory': 'Collection',
340 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
341 submit_runner_ram=0, name=None):
344 self.job = RunnerJob(
348 enable_reuse=enable_reuse,
351 submit_runner_ram=submit_runner_ram,
355 def pipeline_component_spec(self):
356 """Return a component that Workbench and a-r-p-i will understand.
358 Specifically, translate CWL input specs to Arvados pipeline
359 format, like {"dataclass":"File","value":"xyz"}.
362 spec = self.job.arvados_job_spec()
364 # Most of the component spec is exactly the same as the job
365 # spec (script, script_version, etc.).
366 # spec['script_parameters'] isn't right, though. A component
367 # spec's script_parameters hash is a translation of
368 # self.tool.tool['inputs'] with defaults/overrides taken from
369 # the job order. So we move the job parameters out of the way
370 # and build a new spec['script_parameters'].
371 job_params = spec['script_parameters']
372 spec['script_parameters'] = {}
374 for param in self.tool.tool['inputs']:
375 param = copy.deepcopy(param)
377 # Data type and "required" flag...
378 types = param['type']
379 if not isinstance(types, list):
381 param['required'] = 'null' not in types
382 non_null_types = [t for t in types if t != "null"]
383 if len(non_null_types) == 1:
384 the_type = [c for c in non_null_types][0]
386 if isinstance(the_type, basestring):
387 dataclass = self.type_to_dataclass.get(the_type)
389 param['dataclass'] = dataclass
390 # Note: If we didn't figure out a single appropriate
391 # dataclass, we just left that attribute out. We leave
392 # the "type" attribute there in any case, which might help
395 # Title and description...
396 title = param.pop('label', '')
397 descr = param.pop('doc', '').rstrip('\n')
399 param['title'] = title
401 param['description'] = descr
403 # Fill in the value from the current job order, if any.
404 param_id = shortname(param.pop('id'))
405 value = job_params.get(param_id)
408 elif not isinstance(value, dict):
409 param['value'] = value
410 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
411 param['value'] = value['location'][5:]
413 spec['script_parameters'][param_id] = param
414 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
420 self.job.name: self.pipeline_component_spec(),
422 "name": self.job.name,
424 if self.runner.project_uuid:
425 body["owner_uuid"] = self.runner.project_uuid
427 self.runner.api.pipeline_templates().update(
428 uuid=self.uuid, body=body).execute(
429 num_retries=self.runner.num_retries)
430 logger.info("Updated template %s", self.uuid)
432 self.uuid = self.runner.api.pipeline_templates().create(
433 body=body, ensure_unique_name=True).execute(
434 num_retries=self.runner.num_retries)['uuid']
435 logger.info("Created template %s", self.uuid)