X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/cc952178056bf6d29471f6986306fb673dcf394a..58b12d248ed05f8b75b16cee33b0e153e7be71f6:/sdk/cwl/arvados_cwl/executor.py diff --git a/sdk/cwl/arvados_cwl/executor.py b/sdk/cwl/arvados_cwl/executor.py index 100096ab17..c358426166 100644 --- a/sdk/cwl/arvados_cwl/executor.py +++ b/sdk/cwl/arvados_cwl/executor.py @@ -2,6 +2,12 @@ # # SPDX-License-Identifier: Apache-2.0 +from __future__ import division +from builtins import next +from builtins import object +from builtins import str +from future.utils import viewvalues + import argparse import logging import os @@ -53,6 +59,7 @@ class RuntimeStatusLoggingHandler(logging.Handler): def __init__(self, runtime_status_update_func): super(RuntimeStatusLoggingHandler, self).__init__() self.runtime_status_update = runtime_status_update_func + self.updatingRuntimeStatus = False def emit(self, record): kind = None @@ -60,22 +67,27 @@ class RuntimeStatusLoggingHandler(logging.Handler): kind = 'error' elif record.levelno >= logging.WARNING: kind = 'warning' - if kind is not None: - log_msg = record.getMessage() - if '\n' in log_msg: - # If the logged message is multi-line, use its first line as status - # and the rest as detail. - status, detail = log_msg.split('\n', 1) - self.runtime_status_update( - kind, - "%s: %s" % (record.name, status), - detail - ) - else: - self.runtime_status_update( - kind, - "%s: %s" % (record.name, record.getMessage()) - ) + if kind is not None and self.updatingRuntimeStatus is not True: + self.updatingRuntimeStatus = True + try: + log_msg = record.getMessage() + if '\n' in log_msg: + # If the logged message is multi-line, use its first line as status + # and the rest as detail. + status, detail = log_msg.split('\n', 1) + self.runtime_status_update( + kind, + "%s: %s" % (record.name, status), + detail + ) + else: + self.runtime_status_update( + kind, + "%s: %s" % (record.name, record.getMessage()) + ) + finally: + self.updatingRuntimeStatus = False + class ArvCwlExecutor(object): """Execute a CWL tool or workflow, submit work (using either jobs or @@ -157,7 +169,7 @@ class ArvCwlExecutor(object): raise Exception("Unsupported API '%s', expected one of %s" % (arvargs.work_api, expected_api)) if self.work_api == "jobs": - logger.warn(""" + logger.warning(""" ******************************* Using the deprecated 'jobs' API. @@ -180,6 +192,11 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods # if running inside a container if arvados_cwl.util.get_current_container(self.api, self.num_retries, logger): root_logger = logging.getLogger('') + + # Remove existing RuntimeStatusLoggingHandlers if they exist + handlers = [h for h in root_logger.handlers if not isinstance(h, RuntimeStatusLoggingHandler)] + root_logger.handlers = handlers + handler = RuntimeStatusLoggingHandler(self.runtime_status_update) root_logger.addHandler(handler) @@ -332,7 +349,7 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods if self.stop_polling.is_set(): break with self.workflow_eval_lock: - keys = list(self.processes.keys()) + keys = list(self.processes) if not keys: remain_wait = self.poll_interval continue @@ -350,8 +367,8 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods keys = keys[pageSize:] try: proc_states = table.list(filters=[["uuid", "in", page]]).execute(num_retries=self.num_retries) - except Exception as e: - logger.warn("Error checking states on API server: %s", e) + except Exception: + logger.exception("Error checking states on API server: %s") remain_wait = self.poll_interval continue @@ -382,9 +399,9 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods for i in self.intermediate_output_collections: try: self.api.collections().delete(uuid=i).execute(num_retries=self.num_retries) - except: - logger.warn("Failed to delete intermediate output: %s", sys.exc_info()[1], exc_info=(sys.exc_info()[1] if self.debug else False)) - if sys.exc_info()[0] is KeyboardInterrupt or sys.exc_info()[0] is SystemExit: + except Exception: + logger.warning("Failed to delete intermediate output: %s", sys.exc_info()[1], exc_info=(sys.exc_info()[1] if self.debug else False)) + except (KeyboardInterrupt, SystemExit): break def check_features(self, obj): @@ -401,7 +418,7 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods "Option 'dockerOutputDirectory' must be an absolute path.") if obj.get("class") == "http://commonwl.org/cwltool#Secrets" and self.work_api != "containers": raise SourceLine(obj, "class", UnsupportedRequirement).makeError("Secrets not supported with --api=jobs") - for v in obj.itervalues(): + for v in viewvalues(obj): self.check_features(v) elif isinstance(obj, list): for i,v in enumerate(obj): @@ -445,7 +462,7 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods logger.error("Creating CollectionReader for '%s' '%s': %s", k, v, e) raise except IOError as e: - logger.warn("While preparing output collection: %s", e) + logger.warning("While preparing output collection: %s", e) def rewrite(fileobj): fileobj["location"] = generatemapper.mapper(fileobj["location"]).target @@ -457,7 +474,8 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods adjustFileObjs(outputObj, rewrite) with final.open("cwl.output.json", "w") as f: - json.dump(outputObj, f, sort_keys=True, indent=4, separators=(',',': ')) + res = str(json.dumps(outputObj, sort_keys=True, indent=4, separators=(',',': '), ensure_ascii=False)) + f.write(res) final.save_new(name=name, owner_uuid=self.project_uuid, storage_classes=storage_classes, ensure_unique_name=True) @@ -494,8 +512,9 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods body={ 'is_trashed': True }).execute(num_retries=self.num_retries) - except Exception as e: - logger.info("Setting container output: %s", e) + except Exception: + logger.exception("Setting container output") + return elif self.work_api == "jobs" and "TASK_UUID" in os.environ: self.api.job_tasks().update(uuid=os.environ["TASK_UUID"], body={ @@ -559,7 +578,8 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods uuid=existing_uuid, submit_runner_ram=runtimeContext.submit_runner_ram, name=runtimeContext.name, - merged_map=merged_map) + merged_map=merged_map, + loadingContext=loadingContext) tmpl.save() # cwltool.main will write our return value to stdout. return (tmpl.uuid, "success") @@ -607,7 +627,7 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods visited.add(m.group(1)) estimated_size[0] += int(m.group(2)) visit_class(job_order, ("File", "Directory"), estimate_collection_cache) - runtimeContext.collection_cache_size = max(((estimated_size[0]*192) / (1024*1024))+1, 256) + runtimeContext.collection_cache_size = max(((estimated_size[0]*192) // (1024*1024))+1, 256) self.collection_cache.set_cap(runtimeContext.collection_cache_size*1024*1024) logger.info("Using collection cache size %s MiB", runtimeContext.collection_cache_size) @@ -618,11 +638,8 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods if self.work_api == "containers": if tool.tool["class"] == "CommandLineTool" and runtimeContext.wait and (not runtimeContext.always_submit_runner): runtimeContext.runnerjob = tool.tool["id"] - runnerjob = tool.job(job_order, - self.output_callback, - runtimeContext).next() else: - runnerjob = RunnerContainer(self, tool, job_order, runtimeContext.enable_reuse, + tool = RunnerContainer(self, tool, loadingContext, runtimeContext.enable_reuse, self.output_name, self.output_tags, submit_runner_ram=runtimeContext.submit_runner_ram, @@ -636,7 +653,7 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods collection_cache_size=runtimeContext.collection_cache_size, collection_cache_is_default=self.should_estimate_cache_size) elif self.work_api == "jobs": - runnerjob = RunnerJob(self, tool, job_order, runtimeContext.enable_reuse, + tool = RunnerJob(self, tool, loadingContext, runtimeContext.enable_reuse, self.output_name, self.output_tags, submit_runner_ram=runtimeContext.submit_runner_ram, @@ -654,10 +671,16 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods "state": "RunningOnClient"}).execute(num_retries=self.num_retries) logger.info("Pipeline instance %s", self.pipeline["uuid"]) - if runnerjob and not runtimeContext.wait: - submitargs = runtimeContext.copy() - submitargs.submit = False - runnerjob.run(submitargs) + if runtimeContext.cwl_runner_job is not None: + self.uuid = runtimeContext.cwl_runner_job.get('uuid') + + jobiter = tool.job(job_order, + self.output_callback, + runtimeContext) + + if runtimeContext.submit and not runtimeContext.wait: + runnerjob = next(jobiter) + runnerjob.run(runtimeContext) return (runnerjob.uuid, "success") current_container = arvados_cwl.util.get_current_container(self.api, self.num_retries, logger) @@ -672,14 +695,6 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods try: self.workflow_eval_lock.acquire() - if runnerjob: - jobiter = iter((runnerjob,)) - else: - if runtimeContext.cwl_runner_job is not None: - self.uuid = runtimeContext.cwl_runner_job.get('uuid') - jobiter = tool.job(job_order, - self.output_callback, - runtimeContext) # Holds the lock while this code runs and releases it when # it is safe to do so in self.workflow_eval_lock.wait(), @@ -723,13 +738,18 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods except: if sys.exc_info()[0] is KeyboardInterrupt or sys.exc_info()[0] is SystemExit: logger.error("Interrupted, workflow will be cancelled") + elif isinstance(sys.exc_info()[1], WorkflowException): + logger.error("Workflow execution failed:\n%s", sys.exc_info()[1], exc_info=(sys.exc_info()[1] if self.debug else False)) else: - logger.error("Execution failed:\n%s", sys.exc_info()[1], exc_info=(sys.exc_info()[1] if self.debug else False)) + logger.exception("Workflow execution failed") + if self.pipeline: self.api.pipeline_instances().update(uuid=self.pipeline["uuid"], body={"state": "Failed"}).execute(num_retries=self.num_retries) - if runnerjob and runnerjob.uuid and self.work_api == "containers": - self.api.container_requests().update(uuid=runnerjob.uuid, + if runtimeContext.submit and isinstance(tool, Runner): + runnerjob = tool + if runnerjob.uuid and self.work_api == "containers": + self.api.container_requests().update(uuid=runnerjob.uuid, body={"priority": "0"}).execute(num_retries=self.num_retries) finally: self.workflow_eval_lock.release() @@ -744,8 +764,8 @@ http://doc.arvados.org/install/install-api-server.html#disable_api_methods if self.final_output is None: raise WorkflowException("Workflow did not return a result.") - if runtimeContext.submit and isinstance(runnerjob, Runner): - logger.info("Final output collection %s", runnerjob.final_output) + if runtimeContext.submit and isinstance(tool, Runner): + logger.info("Final output collection %s", tool.final_output) else: if self.output_name is None: self.output_name = "Output of %s" % (shortname(tool.tool["id"]))