7 from cwltool.process import get_feature, shortname
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
13 import arvados.collection
15 from .arvdocker import arv_docker_get_image
16 from .runner import Runner, arvados_jobs_image
17 from .pathmapper import InitialWorkDirPathMapper
18 from .perf import Perf
20 from ._version import __version__
22 logger = logging.getLogger('arvados.cwl-runner')
23 metrics = logging.getLogger('arvados.cwl-runner.metrics')
25 crunchrunner_re = re.compile(r"^\S+ \S+ \d+ \d+ stderr \S+ \S+ crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)")
27 class ArvadosJob(object):
28 """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
30 def __init__(self, runner):
31 self.arvrunner = runner
35 def run(self, dry_run=False, pull_image=True, **kwargs):
37 "command": self.command_line
39 runtime_constraints = {}
41 with Perf(metrics, "generatefiles %s" % self.name):
42 if self.generatefiles["listing"]:
43 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
44 keep_client=self.arvrunner.keep_client,
45 num_retries=self.arvrunner.num_retries)
46 script_parameters["task.vwd"] = {}
47 generatemapper = InitialWorkDirPathMapper([self.generatefiles], "", "",
50 with Perf(metrics, "createfiles %s" % self.name):
51 for f, p in generatemapper.items():
52 if p.type == "CreateFile":
53 with vwd.open(p.target, "w") as n:
54 n.write(p.resolved.encode("utf-8"))
56 with Perf(metrics, "generatefiles.save_new %s" % self.name):
59 for f, p in generatemapper.items():
61 script_parameters["task.vwd"][p.target] = p.resolved
62 if p.type == "CreateFile":
63 script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
65 script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
67 script_parameters["task.env"].update(self.environment)
70 script_parameters["task.stdin"] = self.stdin
73 script_parameters["task.stdout"] = self.stdout
76 script_parameters["task.stderr"] = self.stderr
79 script_parameters["task.successCodes"] = self.successCodes
80 if self.temporaryFailCodes:
81 script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
82 if self.permanentFailCodes:
83 script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
85 with Perf(metrics, "arv_docker_get_image %s" % self.name):
86 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
87 if docker_req and kwargs.get("use_container") is not False:
88 if docker_req.get("dockerOutputDirectory"):
89 raise UnsupportedRequirement("Option 'dockerOutputDirectory' of DockerRequirement not supported.")
90 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api, docker_req, pull_image, self.arvrunner.project_uuid)
92 runtime_constraints["docker_image"] = arvados_jobs_image(self.arvrunner)
94 resources = self.builder.resources
95 if resources is not None:
96 runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
97 runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
98 runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
100 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
102 if "keep_cache" in runtime_req:
103 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
104 if "outputDirType" in runtime_req:
105 if runtime_req["outputDirType"] == "local_output_dir":
106 script_parameters["task.keepTmpOutput"] = False
107 elif runtime_req["outputDirType"] == "keep_output_dir":
108 script_parameters["task.keepTmpOutput"] = True
110 filters = [["repository", "=", "arvados"],
111 ["script", "=", "crunchrunner"],
112 ["script_version", "in git", "9e5b98e8f5f4727856b53447191f9c06e3da2ba6"]]
113 if not self.arvrunner.ignore_docker_for_reuse:
114 filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
117 with Perf(metrics, "create %s" % self.name):
118 response = self.arvrunner.api.jobs().create(
120 "owner_uuid": self.arvrunner.project_uuid,
121 "script": "crunchrunner",
122 "repository": "arvados",
123 "script_version": "master",
124 "minimum_script_version": "9e5b98e8f5f4727856b53447191f9c06e3da2ba6",
125 "script_parameters": {"tasks": [script_parameters]},
126 "runtime_constraints": runtime_constraints
129 find_or_create=kwargs.get("enable_reuse", True)
130 ).execute(num_retries=self.arvrunner.num_retries)
132 self.arvrunner.processes[response["uuid"]] = self
134 self.update_pipeline_component(response)
136 logger.info("Job %s (%s) is %s", self.name, response["uuid"], response["state"])
138 if response["state"] in ("Complete", "Failed", "Cancelled"):
139 with Perf(metrics, "done %s" % self.name):
141 except Exception as e:
142 logger.exception("Job %s error" % (self.name))
143 self.output_callback({}, "permanentFail")
145 def update_pipeline_component(self, record):
146 if self.arvrunner.pipeline:
147 self.arvrunner.pipeline["components"][self.name] = {"job": record}
148 with Perf(metrics, "update_pipeline_component %s" % self.name):
149 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
151 "components": self.arvrunner.pipeline["components"]
152 }).execute(num_retries=self.arvrunner.num_retries)
153 if self.arvrunner.uuid:
155 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
157 components = job["components"]
158 components[self.name] = record["uuid"]
159 self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
161 "components": components
162 }).execute(num_retries=self.arvrunner.num_retries)
163 except Exception as e:
164 logger.info("Error adding to components: %s", e)
166 def done(self, record):
168 self.update_pipeline_component(record)
173 if record["state"] == "Complete":
174 processStatus = "success"
176 processStatus = "permanentFail"
181 with Perf(metrics, "inspect log %s" % self.name):
182 logc = arvados.collection.CollectionReader(record["log"],
183 api_client=self.arvrunner.api,
184 keep_client=self.arvrunner.keep_client,
185 num_retries=self.arvrunner.num_retries)
186 log = logc.open(logc.keys()[0])
192 # Determine the tmpdir, outdir and keepdir paths from
193 # the job run. Unfortunately, we can't take the first
194 # values we find (which are expected to be near the
195 # top) and stop scanning because if the node fails and
196 # the job restarts on a different node these values
197 # will different runs, and we need to know about the
198 # final run that actually produced output.
199 g = crunchrunner_re.match(l)
201 dirs[g.group(1)] = g.group(2)
203 with Perf(metrics, "output collection %s" % self.name):
204 outputs = done.done(self, record, dirs["tmpdir"],
205 dirs["outdir"], dirs["keep"])
206 except WorkflowException as e:
207 logger.error("Error while collecting output for job %s:\n%s", self.name, e, exc_info=(e if self.arvrunner.debug else False))
208 processStatus = "permanentFail"
209 except Exception as e:
210 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
211 processStatus = "permanentFail"
213 # Note: Currently, on error output_callback is expecting an empty dict,
214 # anything else will fail.
215 if not isinstance(outputs, dict):
216 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
218 processStatus = "permanentFail"
220 self.output_callback(outputs, processStatus)
222 del self.arvrunner.processes[record["uuid"]]
225 class RunnerJob(Runner):
226 """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
228 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
229 """Create an Arvados job specification for this workflow.
231 The returned dict can be used to create a job (i.e., passed as
232 the +body+ argument to jobs().create()), or as a component in
233 a pipeline template or pipeline instance.
236 workflowmapper = super(RunnerJob, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
238 # Need to filter this out, gets added by cwltool when providing
239 # parameters on the command line, and arv-run-pipeline-instance doesn't
241 if "job_order" in self.job_order:
242 del self.job_order["job_order"]
244 self.job_order["cwl:tool"] = workflowmapper.mapper(self.tool.tool["id"]).target[5:]
247 self.job_order["arv:output_name"] = self.output_name
250 self.job_order["arv:output_tags"] = self.output_tags
252 self.job_order["arv:enable_reuse"] = self.enable_reuse
255 "script": "cwl-runner",
256 "script_version": __version__,
257 "repository": "arvados",
258 "script_parameters": self.job_order,
259 "runtime_constraints": {
260 "docker_image": arvados_jobs_image(self.arvrunner),
261 "min_ram_mb_per_node": self.submit_runner_ram
265 def run(self, *args, **kwargs):
266 job_spec = self.arvados_job_spec(*args, **kwargs)
268 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
270 job = self.arvrunner.api.jobs().create(
272 find_or_create=self.enable_reuse
273 ).execute(num_retries=self.arvrunner.num_retries)
275 for k,v in job_spec["script_parameters"].items():
276 if v is False or v is None or isinstance(v, dict):
277 job_spec["script_parameters"][k] = {"value": v}
279 del job_spec["owner_uuid"]
280 job_spec["job"] = job
281 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
283 "owner_uuid": self.arvrunner.project_uuid,
284 "name": shortname(self.tool.tool["id"]),
285 "components": {"cwl-runner": job_spec },
286 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
287 logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
289 if kwargs.get("wait") is False:
290 self.uuid = self.arvrunner.pipeline["uuid"]
293 self.uuid = job["uuid"]
294 self.arvrunner.processes[self.uuid] = self
296 if job["state"] in ("Complete", "Failed", "Cancelled"):
300 class RunnerTemplate(object):
301 """An Arvados pipeline template that invokes a CWL workflow."""
303 type_to_dataclass = {
304 'boolean': 'boolean',
306 'Directory': 'Collection',
312 def __init__(self, runner, tool, job_order, enable_reuse, uuid, submit_runner_ram=0):
315 self.job = RunnerJob(
319 enable_reuse=enable_reuse,
322 submit_runner_ram=submit_runner_ram)
325 def pipeline_component_spec(self):
326 """Return a component that Workbench and a-r-p-i will understand.
328 Specifically, translate CWL input specs to Arvados pipeline
329 format, like {"dataclass":"File","value":"xyz"}.
332 spec = self.job.arvados_job_spec()
334 # Most of the component spec is exactly the same as the job
335 # spec (script, script_version, etc.).
336 # spec['script_parameters'] isn't right, though. A component
337 # spec's script_parameters hash is a translation of
338 # self.tool.tool['inputs'] with defaults/overrides taken from
339 # the job order. So we move the job parameters out of the way
340 # and build a new spec['script_parameters'].
341 job_params = spec['script_parameters']
342 spec['script_parameters'] = {}
344 for param in self.tool.tool['inputs']:
345 param = copy.deepcopy(param)
347 # Data type and "required" flag...
348 types = param['type']
349 if not isinstance(types, list):
351 param['required'] = 'null' not in types
352 non_null_types = set(types) - set(['null'])
353 if len(non_null_types) == 1:
354 the_type = [c for c in non_null_types][0]
355 dataclass = self.type_to_dataclass.get(the_type)
357 param['dataclass'] = dataclass
358 # Note: If we didn't figure out a single appropriate
359 # dataclass, we just left that attribute out. We leave
360 # the "type" attribute there in any case, which might help
363 # Title and description...
364 title = param.pop('label', '')
365 descr = param.pop('doc', '').rstrip('\n')
367 param['title'] = title
369 param['description'] = descr
371 # Fill in the value from the current job order, if any.
372 param_id = shortname(param.pop('id'))
373 value = job_params.get(param_id)
376 elif not isinstance(value, dict):
377 param['value'] = value
378 elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
379 param['value'] = value['location'][5:]
381 spec['script_parameters'][param_id] = param
382 spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
388 self.job.name: self.pipeline_component_spec(),
390 "name": self.job.name,
392 if self.runner.project_uuid:
393 body["owner_uuid"] = self.runner.project_uuid
395 self.runner.api.pipeline_templates().update(
396 uuid=self.uuid, body=body).execute(
397 num_retries=self.runner.num_retries)
398 logger.info("Updated template %s", self.uuid)
400 self.uuid = self.runner.api.pipeline_templates().create(
401 body=body, ensure_unique_name=True).execute(
402 num_retries=self.runner.num_retries)['uuid']
403 logger.info("Created template %s", self.uuid)