13306: Fixes futurize mistakes regarding PathMapper items()
[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 as e:
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 as e:
228                     logger.info("Error adding to components: %s", e)
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                 logger.error("%s unable to collect output from %s:\n%s",
276                              self.arvrunner.label(self), record["output"], e, exc_info=(e if self.arvrunner.debug else False))
277                 processStatus = "permanentFail"
278             except Exception as e:
279                 logger.exception("Got unknown exception while collecting output for job %s:", self.name)
280                 processStatus = "permanentFail"
281
282             # Note: Currently, on error output_callback is expecting an empty dict,
283             # anything else will fail.
284             if not isinstance(outputs, dict):
285                 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
286                 outputs = {}
287                 processStatus = "permanentFail"
288         finally:
289             self.output_callback(outputs, processStatus)
290
291
292 class RunnerJob(Runner):
293     """Submit and manage a Crunch job that runs crunch_scripts/cwl-runner."""
294
295     def arvados_job_spec(self, debug=False):
296         """Create an Arvados job specification for this workflow.
297
298         The returned dict can be used to create a job (i.e., passed as
299         the +body+ argument to jobs().create()), or as a component in
300         a pipeline template or pipeline instance.
301         """
302
303         if self.embedded_tool.tool["id"].startswith("keep:"):
304             self.job_order["cwl:tool"] = self.embedded_tool.tool["id"][5:]
305         else:
306             packed = packed_workflow(self.arvrunner, self.embedded_tool, self.merged_map)
307             wf_pdh = upload_workflow_collection(self.arvrunner, self.name, packed)
308             self.job_order["cwl:tool"] = "%s/workflow.cwl#main" % wf_pdh
309
310         adjustDirObjs(self.job_order, trim_listing)
311         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
312         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
313
314         if self.output_name:
315             self.job_order["arv:output_name"] = self.output_name
316
317         if self.output_tags:
318             self.job_order["arv:output_tags"] = self.output_tags
319
320         self.job_order["arv:enable_reuse"] = self.enable_reuse
321
322         if self.on_error:
323             self.job_order["arv:on_error"] = self.on_error
324
325         if debug:
326             self.job_order["arv:debug"] = True
327
328         return {
329             "script": "cwl-runner",
330             "script_version": "master",
331             "minimum_script_version": "570509ab4d2ef93d870fd2b1f2eab178afb1bad9",
332             "repository": "arvados",
333             "script_parameters": self.job_order,
334             "runtime_constraints": {
335                 "docker_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
336                 "min_ram_mb_per_node": self.submit_runner_ram
337             }
338         }
339
340     def run(self, runtimeContext):
341         job_spec = self.arvados_job_spec(runtimeContext.debug)
342
343         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
344
345         job = self.arvrunner.api.jobs().create(
346             body=job_spec,
347             find_or_create=self.enable_reuse
348         ).execute(num_retries=self.arvrunner.num_retries)
349
350         for k,v in viewitems(job_spec["script_parameters"]):
351             if v is False or v is None or isinstance(v, dict):
352                 job_spec["script_parameters"][k] = {"value": v}
353
354         del job_spec["owner_uuid"]
355         job_spec["job"] = job
356
357         instance_spec = {
358             "owner_uuid": self.arvrunner.project_uuid,
359             "name": self.name,
360             "components": {
361                 "cwl-runner": job_spec,
362             },
363             "state": "RunningOnServer",
364         }
365         if not self.enable_reuse:
366             instance_spec["properties"] = {"run_options": {"enable_job_reuse": False}}
367
368         self.arvrunner.pipeline = self.arvrunner.api.pipeline_instances().create(
369             body=instance_spec).execute(num_retries=self.arvrunner.num_retries)
370         logger.info("Created pipeline %s", self.arvrunner.pipeline["uuid"])
371
372         if runtimeContext.wait is False:
373             self.uuid = self.arvrunner.pipeline["uuid"]
374             return
375
376         self.uuid = job["uuid"]
377         self.arvrunner.process_submitted(self)
378
379
380 class RunnerTemplate(object):
381     """An Arvados pipeline template that invokes a CWL workflow."""
382
383     type_to_dataclass = {
384         'boolean': 'boolean',
385         'File': 'File',
386         'Directory': 'Collection',
387         'float': 'number',
388         'int': 'number',
389         'string': 'text',
390     }
391
392     def __init__(self, runner, tool, job_order, enable_reuse, uuid,
393                  submit_runner_ram=0, name=None, merged_map=None,
394                  loadingContext=None):
395         self.runner = runner
396         self.embedded_tool = tool
397         self.job = RunnerJob(
398             runner=runner,
399             tool=tool,
400             enable_reuse=enable_reuse,
401             output_name=None,
402             output_tags=None,
403             submit_runner_ram=submit_runner_ram,
404             name=name,
405             merged_map=merged_map,
406             loadingContext=loadingContext)
407         self.job.job_order = job_order
408         self.uuid = uuid
409
410     def pipeline_component_spec(self):
411         """Return a component that Workbench and a-r-p-i will understand.
412
413         Specifically, translate CWL input specs to Arvados pipeline
414         format, like {"dataclass":"File","value":"xyz"}.
415         """
416
417         spec = self.job.arvados_job_spec()
418
419         # Most of the component spec is exactly the same as the job
420         # spec (script, script_version, etc.).
421         # spec['script_parameters'] isn't right, though. A component
422         # spec's script_parameters hash is a translation of
423         # self.tool.tool['inputs'] with defaults/overrides taken from
424         # the job order. So we move the job parameters out of the way
425         # and build a new spec['script_parameters'].
426         job_params = spec['script_parameters']
427         spec['script_parameters'] = {}
428
429         for param in self.embedded_tool.tool['inputs']:
430             param = copy.deepcopy(param)
431
432             # Data type and "required" flag...
433             types = param['type']
434             if not isinstance(types, list):
435                 types = [types]
436             param['required'] = 'null' not in types
437             non_null_types = [t for t in types if t != "null"]
438             if len(non_null_types) == 1:
439                 the_type = [c for c in non_null_types][0]
440                 dataclass = None
441                 if isinstance(the_type, basestring):
442                     dataclass = self.type_to_dataclass.get(the_type)
443                 if dataclass:
444                     param['dataclass'] = dataclass
445             # Note: If we didn't figure out a single appropriate
446             # dataclass, we just left that attribute out.  We leave
447             # the "type" attribute there in any case, which might help
448             # downstream.
449
450             # Title and description...
451             title = param.pop('label', '')
452             descr = param.pop('doc', '').rstrip('\n')
453             if title:
454                 param['title'] = title
455             if descr:
456                 param['description'] = descr
457
458             # Fill in the value from the current job order, if any.
459             param_id = shortname(param.pop('id'))
460             value = job_params.get(param_id)
461             if value is None:
462                 pass
463             elif not isinstance(value, dict):
464                 param['value'] = value
465             elif param.get('dataclass') in ('File', 'Collection') and value.get('location'):
466                 param['value'] = value['location'][5:]
467
468             spec['script_parameters'][param_id] = param
469         spec['script_parameters']['cwl:tool'] = job_params['cwl:tool']
470         return spec
471
472     def save(self):
473         body = {
474             "components": {
475                 self.job.name: self.pipeline_component_spec(),
476             },
477             "name": self.job.name,
478         }
479         if self.runner.project_uuid:
480             body["owner_uuid"] = self.runner.project_uuid
481         if self.uuid:
482             self.runner.api.pipeline_templates().update(
483                 uuid=self.uuid, body=body).execute(
484                     num_retries=self.runner.num_retries)
485             logger.info("Updated template %s", self.uuid)
486         else:
487             self.uuid = self.runner.api.pipeline_templates().create(
488                 body=body, ensure_unique_name=True).execute(
489                     num_retries=self.runner.num_retries)['uuid']
490             logger.info("Created template %s", self.uuid)