3 # Implement cwl-runner interface for submitting and running work on Arvados, using
4 # either the Crunch jobs API or Crunch containers API.
14 from functools import partial
15 import pkg_resources # part of setuptools
17 from cwltool.errors import WorkflowException
19 import cwltool.workflow
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__
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
41 logger = logging.getLogger('arvados.cwl-runner')
42 metrics = logging.getLogger('arvados.cwl-runner.metrics')
43 logger.setLevel(logging.INFO)
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.
52 def __init__(self, api_client, work_api=None, keep_client=None, output_name=None):
55 self.lock = threading.Lock()
56 self.cond = threading.Condition(self.lock)
57 self.final_output = None
58 self.final_status = None
62 self.work_api = work_api
63 self.stop_polling = threading.Event()
66 self.final_output_collection = None
67 self.output_name = output_name
68 self.project_uuid = None
70 if keep_client is not None:
71 self.keep_client = keep_client
73 self.keep_client = arvados.keep.KeepClient(api_client=self.api, num_retries=self.num_retries)
75 if self.work_api is None:
76 # todo: autodetect API to use.
77 self.work_api = "jobs"
79 if self.work_api not in ("containers", "jobs"):
80 raise Exception("Unsupported API '%s'" % self.work_api)
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)
89 return cwltool.workflow.defaultMakeTool(toolpath_object, **kwargs)
91 def output_callback(self, out, processStatus):
92 if processStatus == "success":
93 logger.info("Overall process status is %s", processStatus)
95 self.api.pipeline_instances().update(uuid=self.pipeline["uuid"],
96 body={"state": "Complete"}).execute(num_retries=self.num_retries)
98 logger.warn("Overall process status is %s", processStatus)
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
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"]
111 j = self.processes[uuid]
112 logger.info("Job %s (%s) is Running", j.name, uuid)
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"]
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"])
127 def poll_states(self):
128 """Poll status of jobs or containers listed in the processes dict.
130 Runs in a separate thread.
134 self.stop_polling.wait(15)
135 if self.stop_polling.is_set():
138 keys = self.processes.keys()
142 if self.work_api == "containers":
143 table = self.poll_api.containers()
144 elif self.work_api == "jobs":
145 table = self.poll_api.jobs()
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)
153 for p in proc_states["items"]:
155 "object_uuid": p["uuid"],
156 "event_type": "update",
162 def get_uploaded(self):
163 return self.uploaded.copy()
165 def add_uploaded(self, src, pair):
166 self.uploaded[src] = pair
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):
176 self.check_writable(v)
178 def make_output_collection(self, name, outputObj):
179 outputObj = copy.deepcopy(outputObj)
182 def capture(fileobj):
183 files.append(fileobj)
185 adjustDirObjs(outputObj, capture)
186 adjustFileObjs(outputObj, capture)
188 generatemapper = FinalOutputPathMapper(files, "", "", separateDirs=False)
190 final = arvados.collection.Collection(api_client=self.api,
191 keep_client=self.keep_client,
192 num_retries=self.num_retries)
195 for k,v in generatemapper.items():
197 srccollection = sp[0][5:]
198 if srccollection not in srccollections:
199 srccollections[srccollection] = arvados.collection.CollectionReader(
202 keep_client=self.keep_client,
203 num_retries=self.num_retries)
204 reader = srccollections[srccollection]
206 srcpath = "/".join(sp[1:]) if len(sp) > 1 else "."
207 final.copy(srcpath, v.target, source_collection=reader, overwrite=False)
209 logger.warn("While preparing output collection: %s", e)
211 def rewrite(fileobj):
212 fileobj["location"] = generatemapper.mapper(fileobj["location"]).target
213 for k in ("basename", "size", "listing"):
217 adjustDirObjs(outputObj, rewrite)
218 adjustFileObjs(outputObj, rewrite)
220 with final.open("cwl.output.json", "w") as f:
221 json.dump(outputObj, f, sort_keys=True, indent=4, separators=(',',': '))
223 final.save_new(name=name, owner_uuid=self.project_uuid, ensure_unique_name=True)
225 logger.info("Final output collection %s \"%s\" (%s)", final.portable_data_hash(),
226 final.api_response()["name"],
227 final.manifest_locator())
229 self.final_output_collection = final
231 def arv_executor(self, tool, job_order, **kwargs):
232 self.debug = kwargs.get("debug")
234 tool.visit(self.check_writable)
236 useruuid = self.api.users().current().execute()["uuid"]
237 self.project_uuid = kwargs.get("project_uuid") if kwargs.get("project_uuid") else useruuid
239 make_fs_access = kwargs.get("make_fs_access") or partial(CollectionFsAccess,
241 keep_client=self.keep_client)
242 self.fs_access = make_fs_access(kwargs["basedir"])
244 if kwargs.get("create_template"):
245 tmpl = RunnerTemplate(self, tool, job_order, kwargs.get("enable_reuse"))
247 # cwltool.main will write our return value to stdout.
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"))
253 self.ignore_docker_for_reuse = kwargs.get("ignore_docker_for_reuse")
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")
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)"
272 upload_instance(self, shortname(tool.tool["id"]), tool, job_order)
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,
282 runnerjob = RunnerContainer(self, tool, job_order, kwargs.get("enable_reuse"), self.output_name)
284 runnerjob = RunnerJob(self, tool, job_order, kwargs.get("enable_reuse"), self.output_name)
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(
290 "owner_uuid": self.project_uuid,
291 "name": shortname(tool.tool["id"]),
293 "state": "RunningOnClient"}).execute(num_retries=self.num_retries)
294 logger.info("Pipeline instance %s", self.pipeline["uuid"])
296 if runnerjob and not kwargs.get("wait"):
297 runnerjob.run(wait=kwargs.get("wait"))
298 return runnerjob.uuid
300 self.poll_api = arvados.api('v1')
301 self.polling_thread = threading.Thread(target=self.poll_states)
302 self.polling_thread.start()
305 jobiter = iter((runnerjob,))
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,
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.
319 loopperf = Perf(metrics, "jobiter")
321 for runnable in jobiter:
324 with Perf(metrics, "run"):
325 runnable.run(**kwargs)
330 logger.error("Workflow is deadlocked, no runnable jobs and not waiting on any pending jobs.")
335 while self.processes:
338 except UnsupportedRequirement:
341 if sys.exc_info()[0] is KeyboardInterrupt:
342 logger.error("Interrupted, marking pipeline as failed")
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))
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)
353 self.stop_polling.set()
354 self.polling_thread.join()
356 if self.final_status == "UnsupportedRequirement":
357 raise UnsupportedRequirement("Check log for details.")
359 if self.final_status != "success":
360 raise WorkflowException("Workflow failed.")
362 if self.final_output is None:
363 raise WorkflowException("Workflow did not return a result.")
365 if kwargs.get("submit") and isinstance(runnerjob, Runner):
366 logger.info("Final output collection %s", runnerjob.final_output)
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)
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))
376 return self.final_output
380 """Print version string of key packages for provenance and debugging."""
382 arvcwlpkg = pkg_resources.require("arvados-cwl-runner")
383 arvpkg = pkg_resources.require("arvados-python-client")
384 cwlpkg = pkg_resources.require("cwltool")
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)
391 def arg_parser(): # type: () -> argparse.ArgumentParser
392 parser = argparse.ArgumentParser(description='Arvados executor for Common Workflow Language')
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")
399 parser.add_argument("--eval-timeout",
400 help="Time to wait for a Javascript expression to evaluate before giving an error, default 20s.",
403 parser.add_argument("--version", action="store_true", help="Print version and exit")
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")
410 parser.add_argument("--metrics", action="store_true", help="Print timing metrics")
412 parser.add_argument("--tool-help", action="store_true", help="Print command line help for tool")
414 exgroup = parser.add_mutually_exclusive_group()
415 exgroup.add_argument("--enable-reuse", action="store_true",
416 default=True, dest="enable_reuse",
418 exgroup.add_argument("--disable-reuse", action="store_false",
419 default=True, dest="enable_reuse",
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.",
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.")
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")
443 parser.add_argument("--api", type=str,
444 default=None, dest="work_api",
445 help="Select work submission API, one of 'jobs' or 'containers'.")
447 parser.add_argument("--compute-checksum", action="store_true", default=False,
448 help="Compute checksum of contents while collecting outputs",
449 dest="compute_checksum")
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.")
458 res = pkg_resources.resource_stream(__name__, 'arv-cwl-schema.yml')
459 cache["http://arvados.org/cwl"] = res.read()
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] = {}
468 def main(args, stdout, stderr, api_client=None, keep_client=None):
469 parser = arg_parser()
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 = ({}, "")
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:
487 logger.setLevel(logging.DEBUG)
490 logger.setLevel(logging.WARN)
491 logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
494 metrics.setLevel(logging.DEBUG)
495 logging.getLogger("cwltool.metrics").setLevel(logging.DEBUG)
497 arvargs.conformance_test = None
498 arvargs.use_container = True
500 return cwltool.main.main(args=arvargs,
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))