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 if "outputDirType" in runtime_req:
114 if runtime_req["outputDirType"] == "local_output_dir":
115 script_parameters["task.keepTmpOutput"] = False
116 elif runtime_req["outputDirType"] == "keep_output_dir":
117 script_parameters["task.keepTmpOutput"] = True
119 filters = [["repository", "=", "arvados"],
120 ["script", "=", "crunchrunner"],
121 ["script_version", "in git", crunchrunner_git_commit]]
122 if not self.arvrunner.ignore_docker_for_reuse:
123 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
126 with Perf(metrics, "create %s" % self.name):
127 response = self.arvrunner.api.jobs().create(
129 "owner_uuid": self.arvrunner.project_uuid,
130 "script": "crunchrunner",
131 "repository": "arvados",
132 "script_version": "master",
133 "minimum_script_version": crunchrunner_git_commit,
134 "script_parameters": {"tasks": [script_parameters]},
135 "runtime_constraints": runtime_constraints
138 find_or_create=kwargs.get("enable_reuse", True)
139 ).execute(num_retries=self.arvrunner.num_retries)
141 self.arvrunner.processes[response["uuid"]] = self
143 self.update_pipeline_component(response)
145 if response["state"] == "Complete":
146 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
147 with Perf(metrics, "done %s" % self.name):
150 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
151 except Exception as e:
152 logger.exception("%s error" % (self.arvrunner.label(self)))
153 self.output_callback({}, "permanentFail")
155 def update_pipeline_component(self, record):
156 if self.arvrunner.pipeline:
157 self.arvrunner.pipeline["components"][self.name] = {"job": record}
158 with Perf(metrics, "update_pipeline_component %s" % self.name):
159 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
161 "components": self.arvrunner.pipeline["components"]
162 }).execute(num_retries=self.arvrunner.num_retries)
163 if self.arvrunner.uuid:
165 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
167 components = job["components"]
168 components[self.name] = record["uuid"]
169 self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
171 "components": components
172 }).execute(num_retries=self.arvrunner.num_retries)
173 except Exception as e:
174 logger.info("Error adding to components: %s", e)
176 def done(self, record):
178 self.update_pipeline_component(record)
183 if record["state"] == "Complete":
184 processStatus = "success"
186 processStatus = "permanentFail"
191 with Perf(metrics, "inspect log %s" % self.name):
192 logc = arvados.collection.CollectionReader(record["log"],
193 api_client=self.arvrunner.api,
194 keep_client=self.arvrunner.keep_client,
195 num_retries=self.arvrunner.num_retries)
196 log = logc.open(logc.keys()[0])
202 # Determine the tmpdir, outdir and keepdir paths from
203 # the job run. Unfortunately, we can't take the first
204 # values we find (which are expected to be near the
205 # top) and stop scanning because if the node fails and
206 # the job restarts on a different node these values
207 # will different runs, and we need to know about the
208 # final run that actually produced output.
209 g = crunchrunner_re.match(l)
211 dirs[g.group(1)] = g.group(2)
213 if processStatus == "permanentFail":
214 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
216 with Perf(metrics, "output collection %s" % self.name):
217 outputs = done.done(self, record, dirs["tmpdir"],
218 dirs["outdir"], dirs["keep"])
219 except WorkflowException as e:
220 logger.error("%s unable to collect output from %s:\n%s",
221 self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
222 processStatus = "permanentFail"
223 except Exception as e:
224 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
225 processStatus = "permanentFail"
227 # Note: Currently, on error output_callback is expecting an empty dict,
228 # anything else will fail.
229 if not isinstance(outputs, dict):
230 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
232 processStatus = "permanentFail"
234 self.output_callback(outputs, processStatus)
235 if record["uuid"] in self.arvrunner.processes:
236 del self.arvrunner.processes[record["uuid"]]
238 class RunnerJob(Runner):
239 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
241 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
242 """Create an Arvados job specification for this workflow.
244 The returned dict can be used to create a job (i.e., passed as
245 the +body+ argument to jobs().create()), or as a component in
246 a pipeline template or pipeline instance.
249 if self.tool.tool["id"].startswith("keep:"):
250 self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
252 packed = packed_workflow(self.arvrunner, self.tool)
253 wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
254 self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
256 adjustDirObjs(self.job_order, trim_listing)
257 adjustFileObjs(self.job_order, trim_anonymous_location)
258 adjustDirObjs(self.job_order, trim_anonymous_location)
261 self.job_order["arv:output_name"] = self.output_name
264 self.job_order["arv:output_tags"] = self.output_tags
266 self.job_order["arv:enable_reuse"] = self.enable_reuse
269 self.job_order["arv:on_error"] = self.on_error
272 "script": "cwl-runner",
273 "script_version": "master",
274 "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
275 "repository": "arvados",
276 "script_parameters": self.job_order,
277 "runtime_constraints": {
278 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
279 "min_ram_mb_per_node": self.submit_runner_ram
283 def run(self, *args, **kwargs):
284 job_spec = self.arvados_job_spec(*args, **kwargs)
286 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
288 job = self.arvrunner.api.jobs().create(
290 find_or_create=self.enable_reuse
291 ).execute(num_retries=self.arvrunner.num_retries)
293 for k,v in job_spec["script_parameters"].items():
294 if v is False or v is None or isinstance(v, dict):
295 job_spec["script_parameters"][k] = {"value": v}
297 del job_spec["owner_uuid"]
298 job_spec["job"] = job
299 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
301 "owner_uuid": self.arvrunner.project_uuid,
303 "components": {"cwl-runner": job_spec },
304 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
305 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
307 if kwargs.get("wait") is False:
308 self.uuid = self.arvrunner.pipeline["uuid"]
311 self.uuid = job["uuid"]
312 self.arvrunner.processes[self.uuid] = self
314 if job["state"] in ("Complete", "Failed", "Cancelled"):
318 class RunnerTemplate(object):
319 """An Arvados pipeline template that invokes a CWL workflow."""
321 type_to_dataclass = {
322 'boolean': 'boolean',
324 'Directory': 'Collection',
330 def __init__(self, runner, tool, job_order, enable_reuse, uuid,
331 submit_runner_ram=0, name=None):
334 self.job = RunnerJob(
338 enable_reuse=enable_reuse,
341 submit_runner_ram=submit_runner_ram,
345 def pipeline_component_spec(self):
346 """Return a component that Workbench and a-r-p-i will understand.
348 Specifically, translate CWL input specs to Arvados pipeline
349 format, like {"dataclass":"File","value":"xyz"}.
352 spec = self.job.arvados_job_spec()
354 # Most of the component spec is exactly the same as the job
355 # spec (script, script_version, etc.).
356 # spec['script_parameters'] isn't right, though. A component
357 # spec's script_parameters hash is a translation of
358 # self.tool.tool['inputs'] with defaults/overrides taken from
359 # the job order. So we move the job parameters out of the way
360 # and build a new spec['script_parameters'].
361 job_params = spec['script_parameters']
362 spec['script_parameters'] = {}
364 for param in self.tool.tool['inputs']:
365 param = copy.deepcopy(param)
367 # Data type and "required" flag...
368 types = param['type']
369 if not isinstance(types, list):
371 param['required'] = 'null' not in types
372 non_null_types = [t for t in types if t != "null"]
373 if len(non_null_types) == 1:
374 the_type = [c for c in non_null_types][0]
376 if isinstance(the_type, basestring):
377 dataclass = self.type_to_dataclass.get(the_type)
379 param['dataclass'] = dataclass
380 # Note: If we didn't figure out a single appropriate
381 # dataclass, we just left that attribute out. We leave
382 # the "type" attribute there in any case, which might help
385 # Title and description...
386 title = param.pop('label', '')
387 descr = param.pop('doc', '').rstrip('\n')
389 param['title'] = title
391 param['description'] = descr
393 # Fill in the value from the current job order, if any.
394 param_id = shortname(param.pop('id'))
395 value = job_params.get(param_id)
398 elif not isinstance(value, dict):
399 param['value'] = value
400 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
401 param['value'] = value['location'][5:]
403 spec['script_parameters'][param_id] = param
404 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
410 self.job.name: self.pipeline_component_spec(),
412 "name": self.job.name,
414 if self.runner.project_uuid:
415 body["owner_uuid"] = self.runner.project_uuid
417 self.runner.api.pipeline_templates().update(
418 uuid=self.uuid, body=body).execute(
419 num_retries=self.runner.num_retries)
420 logger.info("Updated template %s", self.uuid)
422 self.uuid = self.runner.api.pipeline_templates().create(
423 body=body, ensure_unique_name=True).execute(
424 num_retries=self.runner.num_retries)['uuid']
425 logger.info("Created template %s", self.uuid)