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