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