10194: arvados/jobs a-c-r pinning WIP
[arvados.git] / sdk / cwl / arvados_cwl / __init__.py
1 #!/usr/bin/env python
2
3 # Implement cwl-runner interface for submitting and running work on Arvados, using
4 # either the Crunch jobs API or Crunch containers API.
5
6 import argparse
7 import logging
8 import os
9 import sys
10 import threading
11 import hashlib
12 import copy
13 import json
14 from functools import partial
15 import pkg_resources  # part of setuptools
16
17 from cwltool.errors import WorkflowException
18 import cwltool.main
19 import cwltool.workflow
20 import schema_salad
21
22 import arvados
23 import arvados.config
24
25 from .arvcontainer import ArvadosContainer, RunnerContainer
26 from .arvjob import ArvadosJob, RunnerJob, RunnerTemplate
27 from. runner import Runner, upload_instance
28 from .arvtool import ArvadosCommandTool
29 from .arvworkflow import ArvadosWorkflow, upload_workflow
30 from .fsaccess import CollectionFsAccess
31 from .perf import Perf
32 from .pathmapper import FinalOutputPathMapper
33 from ._version import __version__
34
35 from cwltool.pack import pack
36 from cwltool.process import shortname, UnsupportedRequirement, getListing
37 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs
38 from cwltool.draft2tool import compute_checksums
39 from arvados.api import OrderedJsonModel
40
41 logger = logging.getLogger('arvados.cwl-runner')
42 metrics = logging.getLogger('arvados.cwl-runner.metrics')
43 logger.setLevel(logging.INFO)
44
45
46 class ArvCwlRunner(object):
47     """Execute a CWL tool or workflow, submit work (using either jobs or
48     containers API), wait for them to complete, and report output.
49
50     """
51
52     def __init__(self, api_client, work_api=None, keep_client=None, output_name=None):
53         self.api = api_client
54         self.processes = {}
55         self.lock = threading.Lock()
56         self.cond = threading.Condition(self.lock)
57         self.final_output = None
58         self.final_status = None
59         self.uploaded = {}
60         self.num_retries = 4
61         self.uuid = None
62         self.work_api = work_api
63         self.stop_polling = threading.Event()
64         self.poll_api = None
65         self.pipeline = None
66         self.final_output_collection = None
67         self.output_name = output_name
68         self.project_uuid = None
69
70         if keep_client is not None:
71             self.keep_client = keep_client
72         else:
73             self.keep_client = arvados.keep.KeepClient(api_client=self.api, num_retries=self.num_retries)
74
75         if self.work_api is None:
76             # todo: autodetect API to use.
77             self.work_api = "jobs"
78
79         if self.work_api not in ("containers", "jobs"):
80             raise Exception("Unsupported API '%s'" % self.work_api)
81
82     def arv_make_tool(self, toolpath_object, **kwargs):
83         kwargs["work_api"] = self.work_api
84         if "class" in toolpath_object and toolpath_object["class"] == "CommandLineTool":
85             return ArvadosCommandTool(self, toolpath_object, **kwargs)
86         elif "class" in toolpath_object and toolpath_object["class"] == "Workflow":
87             return ArvadosWorkflow(self, toolpath_object, **kwargs)
88         else:
89             return cwltool.workflow.defaultMakeTool(toolpath_object, **kwargs)
90
91     def output_callback(self, out, processStatus):
92         if processStatus == "success":
93             logger.info("Overall process status is %s", processStatus)
94             if self.pipeline:
95                 self.api.pipeline_instances().update(uuid=self.pipeline["uuid"],
96                                                      body={"state": "Complete"}).execute(num_retries=self.num_retries)
97         else:
98             logger.warn("Overall process status is %s", processStatus)
99             if self.pipeline:
100                 self.api.pipeline_instances().update(uuid=self.pipeline["uuid"],
101                                                      body={"state": "Failed"}).execute(num_retries=self.num_retries)
102         self.final_status = processStatus
103         self.final_output = out
104
105     def on_message(self, event):
106         if "object_uuid" in event:
107             if event["object_uuid"] in self.processes and event["event_type"] == "update":
108                 if event["properties"]["new_attributes"]["state"] == "Running" and self.processes[event["object_uuid"]].running is False:
109                     uuid = event["object_uuid"]
110                     with self.lock:
111                         j = self.processes[uuid]
112                         logger.info("Job %s (%s) is Running", j.name, uuid)
113                         j.running = True
114                         j.update_pipeline_component(event["properties"]["new_attributes"])
115                 elif event["properties"]["new_attributes"]["state"] in ("Complete", "Failed", "Cancelled"):
116                     uuid = event["object_uuid"]
117                     try:
118                         self.cond.acquire()
119                         j = self.processes[uuid]
120                         logger.info("Job %s (%s) is %s", j.name, uuid, event["properties"]["new_attributes"]["state"])
121                         with Perf(metrics, "done %s" % j.name):
122                             j.done(event["properties"]["new_attributes"])
123                         self.cond.notify()
124                     finally:
125                         self.cond.release()
126
127     def poll_states(self):
128         """Poll status of jobs or containers listed in the processes dict.
129
130         Runs in a separate thread.
131         """
132
133         while True:
134             self.stop_polling.wait(15)
135             if self.stop_polling.is_set():
136                 break
137             with self.lock:
138                 keys = self.processes.keys()
139             if not keys:
140                 continue
141
142             if self.work_api == "containers":
143                 table = self.poll_api.containers()
144             elif self.work_api == "jobs":
145                 table = self.poll_api.jobs()
146
147             try:
148                 proc_states = table.list(filters=[["uuid", "in", keys]]).execute(num_retries=self.num_retries)
149             except Exception as e:
150                 logger.warn("Error checking states on API server: %s", e)
151                 continue
152
153             for p in proc_states["items"]:
154                 self.on_message({
155                     "object_uuid": p["uuid"],
156                     "event_type": "update",
157                     "properties": {
158                         "new_attributes": p
159                     }
160                 })
161
162     def get_uploaded(self):
163         return self.uploaded.copy()
164
165     def add_uploaded(self, src, pair):
166         self.uploaded[src] = pair
167
168     def check_writable(self, obj):
169         if isinstance(obj, dict):
170             if obj.get("writable"):
171                 raise UnsupportedRequirement("InitialWorkDir feature 'writable: true' not supported")
172             for v in obj.itervalues():
173                 self.check_writable(v)
174         if isinstance(obj, list):
175             for v in obj:
176                 self.check_writable(v)
177
178     def make_output_collection(self, name, outputObj):
179         outputObj = copy.deepcopy(outputObj)
180
181         files = []
182         def capture(fileobj):
183             files.append(fileobj)
184
185         adjustDirObjs(outputObj, capture)
186         adjustFileObjs(outputObj, capture)
187
188         generatemapper = FinalOutputPathMapper(files, "", "", separateDirs=False)
189
190         final = arvados.collection.Collection(api_client=self.api,
191                                               keep_client=self.keep_client,
192                                               num_retries=self.num_retries)
193
194         srccollections = {}
195         for k,v in generatemapper.items():
196             sp = k.split("/")
197             srccollection = sp[0][5:]
198             if srccollection not in srccollections:
199                 srccollections[srccollection] = arvados.collection.CollectionReader(
200                     srccollection,
201                     api_client=self.api,
202                     keep_client=self.keep_client,
203                     num_retries=self.num_retries)
204             reader = srccollections[srccollection]
205             try:
206                 srcpath = "/".join(sp[1:]) if len(sp) > 1 else "."
207                 final.copy(srcpath, v.target, source_collection=reader, overwrite=False)
208             except IOError as e:
209                 logger.warn("While preparing output collection: %s", e)
210
211         def rewrite(fileobj):
212             fileobj["location"] = generatemapper.mapper(fileobj["location"]).target
213             for k in ("basename", "size", "listing"):
214                 if k in fileobj:
215                     del fileobj[k]
216
217         adjustDirObjs(outputObj, rewrite)
218         adjustFileObjs(outputObj, rewrite)
219
220         with final.open("cwl.output.json", "w") as f:
221             json.dump(outputObj, f, sort_keys=True, indent=4, separators=(',',': '))
222
223         final.save_new(name=name, owner_uuid=self.project_uuid, ensure_unique_name=True)
224
225         logger.info("Final output collection %s \"%s\" (%s)", final.portable_data_hash(),
226                     final.api_response()["name"],
227                     final.manifest_locator())
228
229         self.final_output_collection = final
230
231     def arv_executor(self, tool, job_order, **kwargs):
232         self.debug = kwargs.get("debug")
233
234         tool.visit(self.check_writable)
235
236         useruuid = self.api.users().current().execute()["uuid"]
237         self.project_uuid = kwargs.get("project_uuid") if kwargs.get("project_uuid") else useruuid
238         self.pipeline = None
239         make_fs_access = kwargs.get("make_fs_access") or partial(CollectionFsAccess,
240                                                                  api_client=self.api,
241                                                                  keep_client=self.keep_client)
242         self.fs_access = make_fs_access(kwargs["basedir"])
243
244         if kwargs.get("create_template"):
245             tmpl = RunnerTemplate(self, tool, job_order, kwargs.get("enable_reuse"))
246             tmpl.save()
247             # cwltool.main will write our return value to stdout.
248             return tmpl.uuid
249
250         if kwargs.get("create_workflow") or kwargs.get("update_workflow"):
251             return upload_workflow(self, tool, job_order, self.project_uuid, kwargs.get("update_workflow"))
252
253         self.ignore_docker_for_reuse = kwargs.get("ignore_docker_for_reuse")
254
255         kwargs["make_fs_access"] = make_fs_access
256         kwargs["enable_reuse"] = kwargs.get("enable_reuse")
257         kwargs["use_container"] = True
258         kwargs["tmpdir_prefix"] = "tmp"
259         kwargs["on_error"] = "continue"
260         kwargs["compute_checksum"] = kwargs.get("compute_checksum")
261
262         if self.work_api == "containers":
263             kwargs["outdir"] = "/var/spool/cwl"
264             kwargs["docker_outdir"] = "/var/spool/cwl"
265             kwargs["tmpdir"] = "/tmp"
266             kwargs["docker_tmpdir"] = "/tmp"
267         elif self.work_api == "jobs":
268             kwargs["outdir"] = "$(task.outdir)"
269             kwargs["docker_outdir"] = "$(task.outdir)"
270             kwargs["tmpdir"] = "$(task.tmpdir)"
271
272         upload_instance(self, shortname(tool.tool["id"]), tool, job_order)
273
274         runnerjob = None
275         if kwargs.get("submit"):
276             if self.work_api == "containers":
277                 if tool.tool["class"] == "CommandLineTool":
278                     runnerjob = tool.job(job_order,
279                                          self.output_callback,
280                                          **kwargs).next()
281                 else:
282                     runnerjob = RunnerContainer(self, tool, job_order, kwargs.get("enable_reuse"), self.output_name)
283             else:
284                 runnerjob = RunnerJob(self, tool, job_order, kwargs.get("enable_reuse"), self.output_name)
285
286         if not kwargs.get("submit") and "cwl_runner_job" not in kwargs and not self.work_api == "containers":
287             # Create pipeline for local run
288             self.pipeline = self.api.pipeline_instances().create(
289                 body={
290                     "owner_uuid": self.project_uuid,
291                     "name": shortname(tool.tool["id"]),
292                     "components": {},
293                     "state": "RunningOnClient"}).execute(num_retries=self.num_retries)
294             logger.info("Pipeline instance %s", self.pipeline["uuid"])
295
296         if runnerjob and not kwargs.get("wait"):
297             runnerjob.run(wait=kwargs.get("wait"))
298             return runnerjob.uuid
299
300         self.poll_api = arvados.api('v1')
301         self.polling_thread = threading.Thread(target=self.poll_states)
302         self.polling_thread.start()
303
304         if runnerjob:
305             jobiter = iter((runnerjob,))
306         else:
307             if "cwl_runner_job" in kwargs:
308                 self.uuid = kwargs.get("cwl_runner_job").get('uuid')
309             jobiter = tool.job(job_order,
310                                self.output_callback,
311                                **kwargs)
312
313         try:
314             self.cond.acquire()
315             # Will continue to hold the lock for the duration of this code
316             # except when in cond.wait(), at which point on_message can update
317             # job state and process output callbacks.
318
319             loopperf = Perf(metrics, "jobiter")
320             loopperf.__enter__()
321             for runnable in jobiter:
322                 loopperf.__exit__()
323                 if runnable:
324                     with Perf(metrics, "run"):
325                         runnable.run(**kwargs)
326                 else:
327                     if self.processes:
328                         self.cond.wait(1)
329                     else:
330                         logger.error("Workflow is deadlocked, no runnable jobs and not waiting on any pending jobs.")
331                         break
332                 loopperf.__enter__()
333             loopperf.__exit__()
334
335             while self.processes:
336                 self.cond.wait(1)
337
338         except UnsupportedRequirement:
339             raise
340         except:
341             if sys.exc_info()[0] is KeyboardInterrupt:
342                 logger.error("Interrupted, marking pipeline as failed")
343             else:
344                 logger.error("Caught unhandled exception, marking pipeline as failed.  Error was: %s", sys.exc_info()[1], exc_info=(sys.exc_info()[1] if self.debug else False))
345             if self.pipeline:
346                 self.api.pipeline_instances().update(uuid=self.pipeline["uuid"],
347                                                      body={"state": "Failed"}).execute(num_retries=self.num_retries)
348             if runnerjob and runnerjob.uuid and self.work_api == "containers":
349                 self.api.container_requests().update(uuid=runnerjob.uuid,
350                                                      body={"priority": "0"}).execute(num_retries=self.num_retries)
351         finally:
352             self.cond.release()
353             self.stop_polling.set()
354             self.polling_thread.join()
355
356         if self.final_status == "UnsupportedRequirement":
357             raise UnsupportedRequirement("Check log for details.")
358
359         if self.final_status != "success":
360             raise WorkflowException("Workflow failed.")
361
362         if self.final_output is None:
363             raise WorkflowException("Workflow did not return a result.")
364
365         if kwargs.get("submit") and isinstance(runnerjob, Runner):
366             logger.info("Final output collection %s", runnerjob.final_output)
367         else:
368             if self.output_name is None:
369                 self.output_name = "Output of %s" % (shortname(tool.tool["id"]))
370             self.make_output_collection(self.output_name, self.final_output)
371
372         if kwargs.get("compute_checksum"):
373             adjustDirObjs(self.final_output, partial(getListing, self.fs_access))
374             adjustFileObjs(self.final_output, partial(compute_checksums, self.fs_access))
375
376         return self.final_output
377
378
379 def versionstring():
380     """Print version string of key packages for provenance and debugging."""
381
382     arvcwlpkg = pkg_resources.require("arvados-cwl-runner")
383     arvpkg = pkg_resources.require("arvados-python-client")
384     cwlpkg = pkg_resources.require("cwltool")
385
386     return "%s %s %s, %s %s, %s %s" % (sys.argv[0], __version__, arvcwlpkg[0].version,
387                                     "arvados-python-client", arvpkg[0].version,
388                                     "cwltool", cwlpkg[0].version)
389
390
391 def arg_parser():  # type: () -> argparse.ArgumentParser
392     parser = argparse.ArgumentParser(description='Arvados executor for Common Workflow Language')
393
394     parser.add_argument("--basedir", type=str,
395                         help="Base directory used to resolve relative references in the input, default to directory of input object file or current directory (if inputs piped/provided on command line).")
396     parser.add_argument("--outdir", type=str, default=os.path.abspath('.'),
397                         help="Output directory, default current directory")
398
399     parser.add_argument("--eval-timeout",
400                         help="Time to wait for a Javascript expression to evaluate before giving an error, default 20s.",
401                         type=float,
402                         default=20)
403     parser.add_argument("--version", action="store_true", help="Print version and exit")
404
405     exgroup = parser.add_mutually_exclusive_group()
406     exgroup.add_argument("--verbose", action="store_true", help="Default logging")
407     exgroup.add_argument("--quiet", action="store_true", help="Only print warnings and errors.")
408     exgroup.add_argument("--debug", action="store_true", help="Print even more logging")
409
410     parser.add_argument("--metrics", action="store_true", help="Print timing metrics")
411
412     parser.add_argument("--tool-help", action="store_true", help="Print command line help for tool")
413
414     exgroup = parser.add_mutually_exclusive_group()
415     exgroup.add_argument("--enable-reuse", action="store_true",
416                         default=True, dest="enable_reuse",
417                         help="")
418     exgroup.add_argument("--disable-reuse", action="store_false",
419                         default=True, dest="enable_reuse",
420                         help="")
421
422     parser.add_argument("--project-uuid", type=str, metavar="UUID", help="Project that will own the workflow jobs, if not provided, will go to home project.")
423     parser.add_argument("--output-name", type=str, help="Name to use for collection that stores the final output.", default=None)
424     parser.add_argument("--ignore-docker-for-reuse", action="store_true",
425                         help="Ignore Docker image version when deciding whether to reuse past jobs.",
426                         default=False)
427
428     exgroup = parser.add_mutually_exclusive_group()
429     exgroup.add_argument("--submit", action="store_true", help="Submit workflow to run on Arvados.",
430                         default=True, dest="submit")
431     exgroup.add_argument("--local", action="store_false", help="Run workflow on local host (submits jobs to Arvados).",
432                         default=True, dest="submit")
433     exgroup.add_argument("--create-template", action="store_true", help="Create an Arvados pipeline template.")
434     exgroup.add_argument("--create-workflow", action="store_true", help="Create an Arvados workflow.")
435     exgroup.add_argument("--update-workflow", type=str, metavar="UUID", help="Update existing Arvados workflow with uuid.")
436
437     exgroup = parser.add_mutually_exclusive_group()
438     exgroup.add_argument("--wait", action="store_true", help="After submitting workflow runner job, wait for completion.",
439                         default=True, dest="wait")
440     exgroup.add_argument("--no-wait", action="store_false", help="Submit workflow runner job and exit.",
441                         default=True, dest="wait")
442
443     parser.add_argument("--api", type=str,
444                         default=None, dest="work_api",
445                         help="Select work submission API, one of 'jobs' or 'containers'.")
446
447     parser.add_argument("--compute-checksum", action="store_true", default=False,
448                         help="Compute checksum of contents while collecting outputs",
449                         dest="compute_checksum")
450
451     parser.add_argument("workflow", type=str, nargs="?", default=None, help="The workflow to execute")
452     parser.add_argument("job_order", nargs=argparse.REMAINDER, help="The input object to the workflow.")
453
454     return parser
455
456 def add_arv_hints():
457     cache = {}
458     res = pkg_resources.resource_stream(__name__, 'arv-cwl-schema.yml')
459     cache["http://arvados.org/cwl"] = res.read()
460     res.close()
461     document_loader, cwlnames, _, _ = cwltool.process.get_schema("v1.0")
462     _, extnames, _, _ = schema_salad.schema.load_schema("http://arvados.org/cwl", cache=cache)
463     for n in extnames.names:
464         if not cwlnames.has_name("http://arvados.org/cwl#"+n, ""):
465             cwlnames.add_name("http://arvados.org/cwl#"+n, "", extnames.get_name(n, ""))
466         document_loader.idx["http://arvados.org/cwl#"+n] = {}
467
468 def main(args, stdout, stderr, api_client=None, keep_client=None):
469     parser = arg_parser()
470
471     job_order_object = None
472     arvargs = parser.parse_args(args)
473     if (arvargs.create_template or arvargs.create_workflow or arvargs.update_workflow) and not arvargs.job_order:
474         job_order_object = ({}, "")
475
476     add_arv_hints()
477
478     try:
479         if api_client is None:
480             api_client=arvados.api('v1', model=OrderedJsonModel())
481         runner = ArvCwlRunner(api_client, work_api=arvargs.work_api, keep_client=keep_client, output_name=arvargs.output_name)
482     except Exception as e:
483         logger.error(e)
484         return 1
485
486     if arvargs.debug:
487         logger.setLevel(logging.DEBUG)
488
489     if arvargs.quiet:
490         logger.setLevel(logging.WARN)
491         logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
492
493     if arvargs.metrics:
494         metrics.setLevel(logging.DEBUG)
495         logging.getLogger("cwltool.metrics").setLevel(logging.DEBUG)
496
497     arvargs.conformance_test = None
498     arvargs.use_container = True
499
500     return cwltool.main.main(args=arvargs,
501                              stdout=stdout,
502                              stderr=stderr,
503                              executor=runner.arv_executor,
504                              makeTool=runner.arv_make_tool,
505                              versionfunc=versionstring,
506                              job_order_object=job_order_object,
507                              make_fs_access=partial(CollectionFsAccess, api_client=api_client))