8784: Fix test for latest firefox.
[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                 if response["owner_uuid"] != self.arvrunner.project_uuid:
150                     self.arvrunner.api.links().create(body={
151                         'link_class': 'permission',
152                         'name': 'can_read',
153                         'tail_uuid': self.arvrunner.project_uuid,
154                         'head_uuid': response["uuid"],
155                         }).execute(num_retries=self.arvrunner.num_retries)
156
157                 with Perf(metrics, "done %s" % self.name):
158                     self.done(response)
159             else:
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")
164
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"],
170                                                                                  body={
171                                                                                     "components": self.arvrunner.pipeline["components"]
172                                                                                  }).execute(num_retries=self.arvrunner.num_retries)
173         if self.arvrunner.uuid:
174             try:
175                 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
176                 if job:
177                     components = job["components"]
178                     components[self.name] = record["uuid"]
179                     self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
180                         body={
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)
185
186     def done(self, record):
187         try:
188             self.update_pipeline_component(record)
189         except:
190             pass
191
192         try:
193             if record["state"] == "Complete":
194                 processStatus = "success"
195             else:
196                 processStatus = "permanentFail"
197
198             outputs = {}
199             try:
200                 if record["output"]:
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])
207                         dirs = {}
208                         tmpdir = None
209                         outdir = None
210                         keepdir = None
211                         for l in log:
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)
220                             if g:
221                                 dirs[g.group(1)] = g.group(2)
222
223                     if processStatus == "permanentFail":
224                         done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
225
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"
236
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)
241                 outputs = {}
242                 processStatus = "permanentFail"
243         finally:
244             self.output_callback(outputs, processStatus)
245             if record["uuid"] in self.arvrunner.processes:
246                 del self.arvrunner.processes[record["uuid"]]
247
248 class RunnerJob(Runner):
249     """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
250
251     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
252         """Create an Arvados job specification for this workflow.
253
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.
257         """
258
259         if self.tool.tool["id"].startswith("keep:"):
260             self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
261         else:
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
265
266         adjustDirObjs(self.job_order, trim_listing)
267         adjustFileObjs(self.job_order, trim_anonymous_location)
268         adjustDirObjs(self.job_order, trim_anonymous_location)
269
270         if self.output_name:
271             self.job_order["arv:output_name"] = self.output_name
272
273         if self.output_tags:
274             self.job_order["arv:output_tags"] = self.output_tags
275
276         self.job_order["arv:enable_reuse"] = self.enable_reuse
277
278         if self.on_error:
279             self.job_order["arv:on_error"] = self.on_error
280
281         return {
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
290             }
291         }
292
293     def run(self, *args, **kwargs):
294         job_spec = self.arvados_job_spec(*args, **kwargs)
295
296         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
297
298         job = self.arvrunner.api.jobs().create(
299             body=job_spec,
300             find_or_create=self.enable_reuse
301         ).execute(num_retries=self.arvrunner.num_retries)
302
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}
306
307         del job_spec["owner_uuid"]
308         job_spec["job"] = job
309         self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
310             body={
311                 "owner_uuid": self.arvrunner.project_uuid,
312                 "name": self.name,
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"])
316
317         if kwargs.get("wait") is False:
318             self.uuid = self.arvrunner.pipeline["uuid"]
319             return
320
321         self.uuid = job["uuid"]
322         self.arvrunner.processes[self.uuid] = self
323
324         if job["state"] in ("Complete", "Failed", "Cancelled"):
325             self.done(job)
326
327
328 class RunnerTemplate(object):
329     """An Arvados pipeline template that invokes a CWL workflow."""
330
331     type_to_dataclass = {
332         'boolean': 'boolean',
333         'File': 'File',
334         'Directory': 'Collection',
335         'float': 'number',
336         'int': 'number',
337         'string': 'text',
338     }
339
340     def __init__(self, runner, tool, job_order, enable_reuse, uuid,
341                  submit_runner_ram=0, name=None):
342         self.runner = runner
343         self.tool = tool
344         self.job = RunnerJob(
345             runner=runner,
346             tool=tool,
347             job_order=job_order,
348             enable_reuse=enable_reuse,
349             output_name=None,
350             output_tags=None,
351             submit_runner_ram=submit_runner_ram,
352             name=name)
353         self.uuid = uuid
354
355     def pipeline_component_spec(self):
356         """Return a component that Workbench and a-r-p-i will understand.
357
358         Specifically, translate CWL input specs to Arvados pipeline
359         format, like {"dataclass":"File","value":"xyz"}.
360         """
361
362         spec = self.job.arvados_job_spec()
363
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'] = {}
373
374         for param in self.tool.tool['inputs']:
375             param = copy.deepcopy(param)
376
377             # Data type and "required" flag...
378             types = param['type']
379             if not isinstance(types, list):
380                 types = [types]
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]
385                 dataclass = None
386                 if isinstance(the_type, basestring):
387                     dataclass = self.type_to_dataclass.get(the_type)
388                 if dataclass:
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
393             # downstream.
394
395             # Title and description...
396             title = param.pop('label', '')
397             descr = param.pop('doc', '').rstrip('\n')
398             if title:
399                 param['title'] = title
400             if descr:
401                 param['description'] = descr
402
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)
406             if value is None:
407                 pass
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:]
412
413             spec['script_parameters'][param_id] = param
414         spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
415         return spec
416
417     def save(self):
418         body = {
419             "components": {
420                 self.job.name: self.pipeline_component_spec(),
421             },
422             "name": self.job.name,
423         }
424         if self.runner.project_uuid:
425             body["owner_uuid"] = self.runner.project_uuid
426         if self.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)
431         else:
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)