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