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