11557: Merge branch 'master' into 11557-acr-output-col-perms
[arvados.git] / sdk / cwl / arvados_cwl / arvjob.py
1 import logging
2 import re
3 import copy
4 import json
5 import time
6
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
13
14 from schema_salad.sourceline import SourceLine
15
16 import ruamel.yaml as yaml
17
18 import arvados.collection
19
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
24 from . import done
25 from ._version import __version__
26
27 logger = logging.getLogger('arvados.cwl-runner')
28 metrics = logging.getLogger('arvados.cwl-runner.metrics')
29
30 crunchrunner_re = re.compile(r"^\S+ \S+ \d+ \d+ stderr \S+ \S+ crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)")
31
32 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
33
34 class ArvadosJob(object):
35     """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
36
37     def __init__(self, runner):
38         self.arvrunner = runner
39         self.running = False
40         self.uuid = None
41
42     def run(self, dry_run=False, pull_image=True, **kwargs):
43         script_parameters = {
44             "command": self.command_line
45         }
46         runtime_constraints = {}
47
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], "", "",
55                                                separateDirs=False)
56
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"))
62
63                 if vwd:
64                     with Perf(metrics, "generatefiles.save_new %s" % self.name):
65                         vwd.save_new()
66
67                 for f, p in generatemapper.items():
68                     if p.type == "File":
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)
72
73         script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
74         if self.environment:
75             script_parameters["task.env"].update(self.environment)
76
77         if self.stdin:
78             script_parameters["task.stdin"] = self.stdin
79
80         if self.stdout:
81             script_parameters["task.stdout"] = self.stdout
82
83         if self.stderr:
84             script_parameters["task.stderr"] = self.stderr
85
86         if self.successCodes:
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
92
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)
100             else:
101                 runtime_constraints["docker_image"] = "arvados/jobs"
102
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)
108
109         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
110         if runtime_req:
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
119
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"]])
125
126         try:
127             with Perf(metrics, "create %s" % self.name):
128                 response = self.arvrunner.api.jobs().create(
129                     body={
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
137                     },
138                     filters=filters,
139                     find_or_create=kwargs.get("enable_reuse", True)
140                 ).execute(num_retries=self.arvrunner.num_retries)
141
142             self.arvrunner.processes[response["uuid"]] = self
143
144             self.update_pipeline_component(response)
145
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):
149                     self.done(response)
150             else:
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")
155
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"],
161                                                                                  body={
162                                                                                     "components": self.arvrunner.pipeline["components"]
163                                                                                  }).execute(num_retries=self.arvrunner.num_retries)
164         if self.arvrunner.uuid:
165             try:
166                 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
167                 if job:
168                     components = job["components"]
169                     components[self.name] = record["uuid"]
170                     self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
171                         body={
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)
176
177     def done(self, record):
178         try:
179             self.update_pipeline_component(record)
180         except:
181             pass
182
183         try:
184             if record["state"] == "Complete":
185                 processStatus = "success"
186             else:
187                 processStatus = "permanentFail"
188
189             outputs = {}
190             try:
191                 if record["output"]:
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])
198                         dirs = {}
199                         tmpdir = None
200                         outdir = None
201                         keepdir = None
202                         for l in log:
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)
211                             if g:
212                                 dirs[g.group(1)] = g.group(2)
213
214                     if processStatus == "permanentFail":
215                         done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
216
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"
227
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)
232                 outputs = {}
233                 processStatus = "permanentFail"
234         finally:
235             self.output_callback(outputs, processStatus)
236             if record["uuid"] in self.arvrunner.processes:
237                 del self.arvrunner.processes[record["uuid"]]
238
239 class RunnerJob(Runner):
240     """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
241
242     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
243         """Create an Arvados job specification for this workflow.
244
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.
248         """
249
250         if self.tool.tool["id"].startswith("keep:"):
251             self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
252         else:
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
256
257         adjustDirObjs(self.job_order, trim_listing)
258         adjustFileObjs(self.job_order, trim_anonymous_location)
259         adjustDirObjs(self.job_order, trim_anonymous_location)
260
261         if self.output_name:
262             self.job_order["arv:output_name"] = self.output_name
263
264         if self.output_tags:
265             self.job_order["arv:output_tags"] = self.output_tags
266
267         self.job_order["arv:enable_reuse"] = self.enable_reuse
268
269         if self.on_error:
270             self.job_order["arv:on_error"] = self.on_error
271
272         return {
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
281             }
282         }
283
284     def run(self, *args, **kwargs):
285         job_spec = self.arvados_job_spec(*args, **kwargs)
286
287         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
288
289         job = self.arvrunner.api.jobs().create(
290             body=job_spec,
291             find_or_create=self.enable_reuse
292         ).execute(num_retries=self.arvrunner.num_retries)
293
294         if self.enable_reuse:
295             # When reusing jobs, copy its output/log collection to the desired project
296             reused_collections = [('Output', job.get('output', None)),
297                                   ('Log', job.get('log', None))]
298             for col_type, pdh in [(n, p) for n, p in reused_collections if p]:
299                 c = arvados.collection.Collection(pdh,
300                                                   api_client=self.arvrunner.api,
301                                                   keep_client=self.arvrunner.keep_client,
302                                                   num_retries=self.arvrunner.num_retries)
303                 c.save_new(name="{} of {}".format(col_type, self.name),
304                            owner_uuid=self.arvrunner.project_uuid,
305                            ensure_unique_name=True,
306                            num_retries=self.arvrunner.num_retries)
307                 logger.info("Copied reused job's %s to collection %s",
308                             col_type.lower(),
309                             c.manifest_locator())
310             # Give read permission to the desired project on reused jobs
311             for job_name, job_uuid in job.get('components', {}).items():
312                 self.arvrunner.api.links().create(body={
313                     'link_class': 'can_read',
314                     'tail_uuid': self.arvrunner.project_uuid,
315                     'head_uuid': job_uuid,
316                     }).execute(num_retries=self.arvrunner.num_retries)
317
318         for k,v in job_spec["script_parameters"].items():
319             if v is False or v is None or isinstance(v, dict):
320                 job_spec["script_parameters"][k] = {"value": v}
321
322         del job_spec["owner_uuid"]
323         job_spec["job"] = job
324         self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
325             body={
326                 "owner_uuid": self.arvrunner.project_uuid,
327                 "name": self.name,
328                 "components": {"cwl-runner": job_spec },
329                 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
330         logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
331
332         if kwargs.get("wait") is False:
333             self.uuid = self.arvrunner.pipeline["uuid"]
334             return
335
336         self.uuid = job["uuid"]
337         self.arvrunner.processes[self.uuid] = self
338
339         if job["state"] in ("Complete", "Failed", "Cancelled"):
340             self.done(job)
341
342
343 class RunnerTemplate(object):
344     """An Arvados pipeline template that invokes a CWL workflow."""
345
346     type_to_dataclass = {
347         'boolean': 'boolean',
348         'File': 'File',
349         'Directory': 'Collection',
350         'float': 'number',
351         'int': 'number',
352         'string': 'text',
353     }
354
355     def __init__(self, runner, tool, job_order, enable_reuse, uuid,
356                  submit_runner_ram=0, name=None):
357         self.runner = runner
358         self.tool = tool
359         self.job = RunnerJob(
360             runner=runner,
361             tool=tool,
362             job_order=job_order,
363             enable_reuse=enable_reuse,
364             output_name=None,
365             output_tags=None,
366             submit_runner_ram=submit_runner_ram,
367             name=name)
368         self.uuid = uuid
369
370     def pipeline_component_spec(self):
371         """Return a component that Workbench and a-r-p-i will understand.
372
373         Specifically, translate CWL input specs to Arvados pipeline
374         format, like {"dataclass":"File","value":"xyz"}.
375         """
376
377         spec = self.job.arvados_job_spec()
378
379         # Most of the component spec is exactly the same as the job
380         # spec (script, script_version, etc.).
381         # spec['script_parameters'] isn't right, though. A component
382         # spec's script_parameters hash is a translation of
383         # self.tool.tool['inputs'] with defaults/overrides taken from
384         # the job order. So we move the job parameters out of the way
385         # and build a new spec['script_parameters'].
386         job_params = spec['script_parameters']
387         spec['script_parameters'] = {}
388
389         for param in self.tool.tool['inputs']:
390             param = copy.deepcopy(param)
391
392             # Data type and "required" flag...
393             types = param['type']
394             if not isinstance(types, list):
395                 types = [types]
396             param['required'] = 'null' not in types
397             non_null_types = [t for t in types if t != "null"]
398             if len(non_null_types) == 1:
399                 the_type = [c for c in non_null_types][0]
400                 dataclass = None
401                 if isinstance(the_type, basestring):
402                     dataclass = self.type_to_dataclass.get(the_type)
403                 if dataclass:
404                     param['dataclass'] = dataclass
405             # Note: If we didn't figure out a single appropriate
406             # dataclass, we just left that attribute out.  We leave
407             # the "type" attribute there in any case, which might help
408             # downstream.
409
410             # Title and description...
411             title = param.pop('label', '')
412             descr = param.pop('doc', '').rstrip('\n')
413             if title:
414                 param['title'] = title
415             if descr:
416                 param['description'] = descr
417
418             # Fill in the value from the current job order, if any.
419             param_id = shortname(param.pop('id'))
420             value = job_params.get(param_id)
421             if value is None:
422                 pass
423             elif not isinstance(value, dict):
424                 param['value'] = value
425             elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
426                 param['value'] = value['location'][5:]
427
428             spec['script_parameters'][param_id] = param
429         spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
430         return spec
431
432     def save(self):
433         body = {
434             "components": {
435                 self.job.name: self.pipeline_component_spec(),
436             },
437             "name": self.job.name,
438         }
439         if self.runner.project_uuid:
440             body["owner_uuid"] = self.runner.project_uuid
441         if self.uuid:
442             self.runner.api.pipeline_templates().update(
443                 uuid=self.uuid, body=body).execute(
444                     num_retries=self.runner.num_retries)
445             logger.info("Updated template %s", self.uuid)
446         else:
447             self.uuid = self.runner.api.pipeline_templates().create(
448                 body=body, ensure_unique_name=True).execute(
449                     num_retries=self.runner.num_retries)['uuid']
450             logger.info("Created template %s", self.uuid)