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