ab063867ac1c73bc6d04f20e148da45d9e21003f
[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 from arvados.errors import ApiError
20
21 from .arvdocker import arv_docker_get_image
22 from .runner import Runner, arvados_jobs_image, packed_workflow, upload_workflow_collection, trim_anonymous_location
23 from .pathmapper import VwdPathMapper, trim_listing
24 from .perf import Perf
25 from . import done
26 from ._version import __version__
27
28 logger = logging.getLogger('arvados.cwl-runner')
29 metrics = logging.getLogger('arvados.cwl-runner.metrics')
30
31 crunchrunner_re = re.compile(r"^\S+ \S+ \d+ \d+ stderr \S+ \S+ crunchrunner: \$\(task\.(tmpdir|outdir|keep)\)=(.*)")
32
33 crunchrunner_git_commit = 'a3f2cb186e437bfce0031b024b2157b73ed2717d'
34
35 class ArvadosJob(object):
36     """Submit and manage a Crunch job for executing a CWL CommandLineTool."""
37
38     def __init__(self, runner):
39         self.arvrunner = runner
40         self.running = False
41         self.uuid = None
42
43     def run(self, dry_run=False, pull_image=True, **kwargs):
44         script_parameters = {
45             "command": self.command_line
46         }
47         runtime_constraints = {}
48
49         with Perf(metrics, "generatefiles %s" % self.name):
50             if self.generatefiles["listing"]:
51                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
52                                                     keep_client=self.arvrunner.keep_client,
53                                                     num_retries=self.arvrunner.num_retries)
54                 script_parameters["task.vwd"] = {}
55                 generatemapper = VwdPathMapper([self.generatefiles], "", "",
56                                                separateDirs=False)
57
58                 with Perf(metrics, "createfiles %s" % self.name):
59                     for f, p in generatemapper.items():
60                         if p.type == "CreateFile":
61                             with vwd.open(p.target, "w") as n:
62                                 n.write(p.resolved.encode("utf-8"))
63
64                 if vwd:
65                     with Perf(metrics, "generatefiles.save_new %s" % self.name):
66                         vwd.save_new()
67
68                 for f, p in generatemapper.items():
69                     if p.type == "File":
70                         script_parameters["task.vwd"][p.target] = p.resolved
71                     if p.type == "CreateFile":
72                         script_parameters["task.vwd"][p.target] = "$(task.keep)/%s/%s" % (vwd.portable_data_hash(), p.target)
73
74         script_parameters["task.env"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
75         if self.environment:
76             script_parameters["task.env"].update(self.environment)
77
78         if self.stdin:
79             script_parameters["task.stdin"] = self.stdin
80
81         if self.stdout:
82             script_parameters["task.stdout"] = self.stdout
83
84         if self.stderr:
85             script_parameters["task.stderr"] = self.stderr
86
87         if self.successCodes:
88             script_parameters["task.successCodes"] = self.successCodes
89         if self.temporaryFailCodes:
90             script_parameters["task.temporaryFailCodes"] = self.temporaryFailCodes
91         if self.permanentFailCodes:
92             script_parameters["task.permanentFailCodes"] = self.permanentFailCodes
93
94         with Perf(metrics, "arv_docker_get_image %s" % self.name):
95             (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
96             if docker_req and kwargs.get("use_container") is not False:
97                 if docker_req.get("dockerOutputDirectory"):
98                     raise SourceLine(docker_req, "dockerOutputDirectory", UnsupportedRequirement).makeError(
99                         "Option 'dockerOutputDirectory' of DockerRequirement not supported.")
100                 runtime_constraints["docker_image"] = arv_docker_get_image(self.arvrunner.api, docker_req, pull_image, self.arvrunner.project_uuid)
101             else:
102                 runtime_constraints["docker_image"] = "arvados/jobs"
103
104         resources = self.builder.resources
105         if resources is not None:
106             runtime_constraints["min_cores_per_node"] = resources.get("cores", 1)
107             runtime_constraints["min_ram_mb_per_node"] = resources.get("ram")
108             runtime_constraints["min_scratch_mb_per_node"] = resources.get("tmpdirSize", 0) + resources.get("outdirSize", 0)
109
110         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
111         if runtime_req:
112             if "keep_cache" in runtime_req:
113                 runtime_constraints["keep_cache_mb_per_task"] = runtime_req["keep_cache"]
114                 runtime_constraints["min_ram_mb_per_node"] += runtime_req["keep_cache"]
115             if "outputDirType" in runtime_req:
116                 if runtime_req["outputDirType"] == "local_output_dir":
117                     script_parameters["task.keepTmpOutput"] = False
118                 elif runtime_req["outputDirType"] == "keep_output_dir":
119                     script_parameters["task.keepTmpOutput"] = True
120
121         filters = [["repository", "=", "arvados"],
122                    ["script", "=", "crunchrunner"],
123                    ["script_version", "in git", crunchrunner_git_commit]]
124         if not self.arvrunner.ignore_docker_for_reuse:
125             filters.append(["docker_image_locator", "in docker", runtime_constraints["docker_image"]])
126
127         try:
128             with Perf(metrics, "create %s" % self.name):
129                 response = self.arvrunner.api.jobs().create(
130                     body={
131                         "owner_uuid": self.arvrunner.project_uuid,
132                         "script": "crunchrunner",
133                         "repository": "arvados",
134                         "script_version": "master",
135                         "minimum_script_version": crunchrunner_git_commit,
136                         "script_parameters": {"tasks": [script_parameters]},
137                         "runtime_constraints": runtime_constraints
138                     },
139                     filters=filters,
140                     find_or_create=kwargs.get("enable_reuse", True)
141                 ).execute(num_retries=self.arvrunner.num_retries)
142
143             self.arvrunner.processes[response["uuid"]] = self
144
145             self.update_pipeline_component(response)
146
147             if response["state"] == "Complete":
148                 logger.info("%s reused job %s", self.arvrunner.label(self), response["uuid"])
149                 # Give read permission to the desired project on reused jobs
150                 if response["owner_uuid"] != self.arvrunner.project_uuid:
151                     try:
152                         self.arvrunner.api.links().create(body={
153                             'link_class': 'permission',
154                             'name': 'can_read',
155                             'tail_uuid': self.arvrunner.project_uuid,
156                             'head_uuid': response["uuid"],
157                             }).execute(num_retries=self.arvrunner.num_retries)
158                     except ApiError as e:
159                         # The user might not have "manage" access on the job: log
160                         # a message and continue.
161                         logger.info("Creating read permission on job %s: %s",
162                                     response["uuid"],
163                                     e)
164
165                 with Perf(metrics, "done %s" % self.name):
166                     self.done(response)
167             else:
168                 logger.info("%s %s is %s", self.arvrunner.label(self), response["uuid"], response["state"])
169         except Exception as e:
170             logger.exception("%s error" % (self.arvrunner.label(self)))
171             self.output_callback({}, "permanentFail")
172
173     def update_pipeline_component(self, record):
174         if self.arvrunner.pipeline:
175             self.arvrunner.pipeline["components"][self.name] = {"job": record}
176             with Perf(metrics, "update_pipeline_component %s" % self.name):
177                 self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().update(uuid=self.arvrunner.pipeline["uuid"],
178                                                                                  body={
179                                                                                     "components": self.arvrunner.pipeline["components"]
180                                                                                  }).execute(num_retries=self.arvrunner.num_retries)
181         if self.arvrunner.uuid:
182             try:
183                 job = self.arvrunner.api.jobs().get(uuid=self.arvrunner.uuid).execute()
184                 if job:
185                     components = job["components"]
186                     components[self.name] = record["uuid"]
187                     self.arvrunner.api.jobs().update(uuid=self.arvrunner.uuid,
188                         body={
189                             "components": components
190                         }).execute(num_retries=self.arvrunner.num_retries)
191             except Exception as e:
192                 logger.info("Error adding to components: %s", e)
193
194     def done(self, record):
195         try:
196             self.update_pipeline_component(record)
197         except:
198             pass
199
200         try:
201             if record["state"] == "Complete":
202                 processStatus = "success"
203             else:
204                 processStatus = "permanentFail"
205
206             outputs = {}
207             try:
208                 if record["output"]:
209                     with Perf(metrics, "inspect log %s" % self.name):
210                         logc = arvados.collection.CollectionReader(record["log"],
211                                                                    api_client=self.arvrunner.api,
212                                                                    keep_client=self.arvrunner.keep_client,
213                                                                    num_retries=self.arvrunner.num_retries)
214                         log = logc.open(logc.keys()[0])
215                         dirs = {}
216                         tmpdir = None
217                         outdir = None
218                         keepdir = None
219                         for l in log:
220                             # Determine the tmpdir, outdir and keepdir paths from
221                             # the job run.  Unfortunately, we can't take the first
222                             # values we find (which are expected to be near the
223                             # top) and stop scanning because if the node fails and
224                             # the job restarts on a different node these values
225                             # will different runs, and we need to know about the
226                             # final run that actually produced output.
227                             g = crunchrunner_re.match(l)
228                             if g:
229                                 dirs[g.group(1)] = g.group(2)
230
231                     if processStatus == "permanentFail":
232                         done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
233
234                     with Perf(metrics, "output collection %s" % self.name):
235                         outputs = done.done(self, record, dirs["tmpdir"],
236                                             dirs["outdir"], dirs["keep"])
237             except WorkflowException as e:
238                 logger.error("%s unable to collect output from %s:\n%s",
239                              self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
240                 processStatus = "permanentFail"
241             except Exception as e:
242                 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
243                 processStatus = "permanentFail"
244
245             # Note: Currently, on error output_callback is expecting an empty dict,
246             # anything else will fail.
247             if not isinstance(outputs, dict):
248                 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
249                 outputs = {}
250                 processStatus = "permanentFail"
251         finally:
252             self.output_callback(outputs, processStatus)
253             if record["uuid"] in self.arvrunner.processes:
254                 del self.arvrunner.processes[record["uuid"]]
255
256 class RunnerJob(Runner):
257     """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
258
259     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
260         """Create an Arvados job specification for this workflow.
261
262         The returned dict can be used to create a job (i.e., passed as
263         the +body+ argument to jobs().create()), or as a component in
264         a pipeline template or pipeline instance.
265         """
266
267         if self.tool.tool["id"].startswith("keep:"):
268             self.job_order["cwl:tool"] = self.tool.tool["id"][5:]
269         else:
270             packed = packed_workflow(self.arvrunner, self.tool)
271             wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
272             self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
273
274         adjustDirObjs(self.job_order, trim_listing)
275         adjustFileObjs(self.job_order, trim_anonymous_location)
276         adjustDirObjs(self.job_order, trim_anonymous_location)
277
278         if self.output_name:
279             self.job_order["arv:output_name"] = self.output_name
280
281         if self.output_tags:
282             self.job_order["arv:output_tags"] = self.output_tags
283
284         self.job_order["arv:enable_reuse"] = self.enable_reuse
285
286         if self.on_error:
287             self.job_order["arv:on_error"] = self.on_error
288
289         return {
290             "script": "cwl-runner",
291             "script_version": "master",
292             "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
293             "repository": "arvados",
294             "script_parameters": self.job_order,
295             "runtime_constraints": {
296                 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
297                 "min_ram_mb_per_node": self.submit_runner_ram
298             }
299         }
300
301     def run(self, *args, **kwargs):
302         job_spec = self.arvados_job_spec(*args, **kwargs)
303
304         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
305
306         job = self.arvrunner.api.jobs().create(
307             body=job_spec,
308             find_or_create=self.enable_reuse
309         ).execute(num_retries=self.arvrunner.num_retries)
310
311         for k,v in job_spec["script_parameters"].items():
312             if v is False or v is None or isinstance(v, dict):
313                 job_spec["script_parameters"][k] = {"value": v}
314
315         del job_spec["owner_uuid"]
316         job_spec["job"] = job
317         self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
318             body={
319                 "owner_uuid": self.arvrunner.project_uuid,
320                 "name": self.name,
321                 "components": {"cwl-runner": job_spec },
322                 "state": "RunningOnServer"}).execute(num_retries=self.arvrunner.num_retries)
323         logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
324
325         if kwargs.get("wait") is False:
326             self.uuid = self.arvrunner.pipeline["uuid"]
327             return
328
329         self.uuid = job["uuid"]
330         self.arvrunner.processes[self.uuid] = self
331
332         if job["state"] in ("Complete", "Failed", "Cancelled"):
333             self.done(job)
334
335
336 class RunnerTemplate(object):
337     """An Arvados pipeline template that invokes a CWL workflow."""
338
339     type_to_dataclass = {
340         'boolean': 'boolean',
341         'File': 'File',
342         'Directory': 'Collection',
343         'float': 'number',
344         'int': 'number',
345         'string': 'text',
346     }
347
348     def __init__(self, runner, tool, job_order, enable_reuse, uuid,
349                  submit_runner_ram=0, name=None):
350         self.runner = runner
351         self.tool = tool
352         self.job = RunnerJob(
353             runner=runner,
354             tool=tool,
355             job_order=job_order,
356             enable_reuse=enable_reuse,
357             output_name=None,
358             output_tags=None,
359             submit_runner_ram=submit_runner_ram,
360             name=name)
361         self.uuid = uuid
362
363     def pipeline_component_spec(self):
364         """Return a component that Workbench and a-r-p-i will understand.
365
366         Specifically, translate CWL input specs to Arvados pipeline
367         format, like {"dataclass":"File","value":"xyz"}.
368         """
369
370         spec = self.job.arvados_job_spec()
371
372         # Most of the component spec is exactly the same as the job
373         # spec (script, script_version, etc.).
374         # spec['script_parameters'] isn't right, though. A component
375         # spec's script_parameters hash is a translation of
376         # self.tool.tool['inputs'] with defaults/overrides taken from
377         # the job order. So we move the job parameters out of the way
378         # and build a new spec['script_parameters'].
379         job_params = spec['script_parameters']
380         spec['script_parameters'] = {}
381
382         for param in self.tool.tool['inputs']:
383             param = copy.deepcopy(param)
384
385             # Data type and "required" flag...
386             types = param['type']
387             if not isinstance(types, list):
388                 types = [types]
389             param['required'] = 'null' not in types
390             non_null_types = [t for t in types if t != "null"]
391             if len(non_null_types) == 1:
392                 the_type = [c for c in non_null_types][0]
393                 dataclass = None
394                 if isinstance(the_type, basestring):
395                     dataclass = self.type_to_dataclass.get(the_type)
396                 if dataclass:
397                     param['dataclass'] = dataclass
398             # Note: If we didn't figure out a single appropriate
399             # dataclass, we just left that attribute out.  We leave
400             # the "type" attribute there in any case, which might help
401             # downstream.
402
403             # Title and description...
404             title = param.pop('label', '')
405             descr = param.pop('doc', '').rstrip('\n')
406             if title:
407                 param['title'] = title
408             if descr:
409                 param['description'] = descr
410
411             # Fill in the value from the current job order, if any.
412             param_id = shortname(param.pop('id'))
413             value = job_params.get(param_id)
414             if value is None:
415                 pass
416             elif not isinstance(value, dict):
417                 param['value'] = value
418             elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
419                 param['value'] = value['location'][5:]
420
421             spec['script_parameters'][param_id] = param
422         spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
423         return spec
424
425     def save(self):
426         body = {
427             "components": {
428                 self.job.name: self.pipeline_component_spec(),
429             },
430             "name": self.job.name,
431         }
432         if self.runner.project_uuid:
433             body["owner_uuid"] = self.runner.project_uuid
434         if self.uuid:
435             self.runner.api.pipeline_templates().update(
436                 uuid=self.uuid, body=body).execute(
437                     num_retries=self.runner.num_retries)
438             logger.info("Updated template %s", self.uuid)
439         else:
440             self.uuid = self.runner.api.pipeline_templates().create(
441                 body=body, ensure_unique_name=True).execute(
442                     num_retries=self.runner.num_retries)['uuid']
443             logger.info("Created template %s", self.uuid)