Decorator to run warmup before running a command
192233
def warmup(f):
    

    @wraps(f)
    def wrapped(self, *args, **kwargs):
        if not self.warmed_up:
            self.warmup()
        return f(self, *args, **kwargs)
    return wrapped
119244
def run_systemdrun(
            self, command, internal_background=False, return_full_dict=False,
            **kwargs):
        
        internalkw = deepcopy(kwargs) or {}
        original_ignore_st = internalkw.get("ignore_status", False)
        original_return_st = internalkw.get("return_output", False)
        internalkw["ignore_status"] = True
        internalkw["return_output"] = False
        unit_name = constants.CONU_ARTIFACT_TAG + "unit_" + random_str()
        opts = ["-M", self.name, "--unit", unit_name]
        lpath = "/var/tmp/{}".format(unit_name)
        comout = {}
        if self._run_systemdrun_decide():
            add_wait_var = "--wait"
        else:
            # keep service exist after it finish, to be able to read exit code
            add_wait_var = "-r"
        if internal_background:
            add_wait_var = ""
        if add_wait_var:
            opts.append(add_wait_var)
        # TODO: behave move similar to run_cmd function, unable to work with clean subprocess objects because systemd-run
        # does not support return stderr, stdout, and return code directly
        # find way how to do this in better way, machinectl shell is not possible
        # https://github.com/systemd/systemd/issues/5879
        # https://github.com/systemd/systemd/issues/5878
        bashworkaround = [
            "/bin/bash",
            "-c",
            "({comm})>{path}.stdout 2>{path}.stderr".format(
                comm=" ".join(command),
                path=lpath)]
        whole_cmd = ["systemd-run"] + opts + bashworkaround
        comout['command'] = command
        comout['return_code'] = run_cmd(whole_cmd, **internalkw) or 0
        if not internal_background:
            if not self._run_systemdrun_decide():
                comout['return_code'] = self._systemctl_wait_until_finish(
                    self.name, unit_name)
            if self.is_running():
                self.copy_from(
                    "{pin}.stdout".format(
                        pin=lpath), "{pin}.stdout".format(
                        pin=lpath))
                with open("{pin}.stdout".format(pin=lpath)) as f:
                    comout['stdout'] = f.read()
                self.copy_from(
                    "{pin}.stderr".format(
                        pin=lpath), "{pin}.stderr".format(
                        pin=lpath))
                with open("{pin}.stderr".format(pin=lpath)) as f:
                    comout['stderr'] = f.read()
            logger.debug(comout)
        if not original_ignore_st and comout['return_code'] != 0:
            raise subprocess.CalledProcessError(comout['command'], comout)
        if return_full_dict:
            return comout
        if original_return_st:
            return comout['stdout']
        else:
            return comout['return_code']
196216
def run_cmd(cmd, show_output=True, raise_errs=True, **kwargs):
    
    internal_assert(cmd and isinstance(cmd, list), "console commands must be passed as non-empty lists")
    try:
        from shutil import which
    except ImportError:
        pass
    else:
        cmd[0] = which(cmd[0]) or cmd[0]
    logger.log_cmd(cmd)
    try:
        if show_output and raise_errs:
            return subprocess.check_call(cmd, **kwargs)
        elif show_output:
            return subprocess.call(cmd, **kwargs)
        else:
            stdout, stderr, retcode = call_output(cmd, **kwargs)
            output = "".join(stdout + stderr)
            if retcode and raise_errs:
                raise subprocess.CalledProcessError(retcode, cmd, output=output)
            return output
    except OSError:
        logger.log_exc()
        if raise_errs:
            raise subprocess.CalledProcessError(oserror_retcode, cmd)
        elif show_output:
            return oserror_retcode
        else:
            return ""
1366942
def run_on(*, event: str):
        """"""

        def decorator(callback):
            @functools.wraps(callback)
            def decorator_wrapper():
                RTMClient.on(event=event, callback=callback)

            return decorator_wrapper()

        return decorator
1232366
def before_run(self):
        """"""
        # Actions and checks counters
        self.nb_checks = 0
        self.nb_internal_checks = 0
        self.nb_checks_launched = 0
        self.nb_actions_launched = 0

        self.nb_checks_results = 0
        self.nb_checks_results_timeout = 0
        self.nb_checks_results_passive = 0
        self.nb_checks_results_active = 0

        self.nb_actions_results = 0
        self.nb_actions_results_timeout = 0
        self.nb_actions_results_passive = 0

        self.nb_broks_dropped = 0
        self.nb_checks_dropped = 0
        self.nb_actions_dropped = 0

        # Broks, notifications, ... counters
        self.nb_broks = 0
        self.nb_notifications = 0
        self.nb_event_handlers = 0
        self.nb_external_commands = 0

        self.ticks = 0
62236
def green(fn=None, consume_green_mode=True):
    """"""

    def decorator(fn):
        @wraps(fn)
        def greener(obj, *args, **kwargs):
            args = (obj,) + args
            wait = kwargs.pop('wait', None)
            timeout = kwargs.pop('timeout', None)
            access = kwargs.pop if consume_green_mode else kwargs.get
            green_mode = access('green_mode', None)
            executor = get_object_executor(obj, green_mode)
            return executor.run(fn, args, kwargs, wait=wait, timeout=timeout)

        return greener

    if fn is None:
        return decorator
    return decorator(fn)
242774
function runBeforeDetach (args, methodMeta) {
    // skip if no beforeDetach methods
    if (!defined(methodMeta.beforeDetach)) {
        return
    }
    // run all functions
    _.each(methodMeta.beforeDetach, method => {
        // call method
        (method)(args, methodMeta.signature, 'beforeDetach')
        // log errors
        .catch(err => {
            // require log client
            if (!defined(methodMeta.logClient)) {
                return
            }
            // log error
            methodMeta.logClient.error(err, args.session)
        })
    })
}
772307
def run(self, handler):
        """"""
        import eventlet.patcher
        if not eventlet.patcher.is_monkey_patched(os):
            msg = ("%s requires eventlet.monkey_patch() (before "
                   "import)" % self.__class__.__name__)
            raise RuntimeError(msg)

        # Separate out wsgi.server arguments
        wsgi_args = {}
        for arg in ('log', 'environ', 'max_size', 'max_http_version',
                    'protocol', 'server_event', 'minimum_chunk_size',
                    'log_x_forwarded_for', 'custom_pool', 'keepalive',
                    'log_output', 'log_format', 'url_length_limit', 'debug',
                    'socket_timeout', 'capitalize_response_headers'):
            try:
                wsgi_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        if 'log_output' not in wsgi_args:
            wsgi_args['log_output'] = not self.quiet

        import eventlet.wsgi
        sock = self.options.pop('shared_socket', None) or self.get_socket()
        eventlet.wsgi.server(sock, handler, **wsgi_args)
478056
def decorator(func):
        """"""

        def function_timer(*args, **kwargs):
            """A nested function for timing other functions."""
            # Capture start time
            start = time.time()

            # Execute function with arguments
            value = func(*args, **kwargs)

            # Capture end time
            end = time.time()

            # Calculate run time
            runtime = end - start
            if runtime < 60:
                runtime = str('sec: ' + str('{:f}'.format(runtime)))
            else:
                runtime = str('min: ' + str('{:f}'.format(runtime / 60)))
            print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime))
            return value

        return function_timer
1136033
def __wrap_docker_exec(func):
    ''''''
    def call(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except OSError as e:
            if e.errno == errno.ENOENT:
                raise DockerExecuteError('Failed to execute docker. Is it installed?')
            raise
    return call
905882
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True,
             stderr=STDOUT):
        """"""
        if not cmd:
            error_msg = 'Passed empty text or list'
            raise AttributeError(error_msg)
        if isinstance(cmd, six.string_types):
            cmd = str(cmd)
        if shell:
            if isinstance(cmd, list):
                cmd = ' '.join(cmd)
        else:
            if isinstance(cmd, str):
                cmd = cmd.strip().split()
        out = method(cmd, shell=shell, cwd=cwd, stderr=stderr,
                     universal_newlines=universal_newlines)
        if isinstance(out, bytes):
            out = out.decode('utf-8')
        return str(out).strip()
992477
def execute(self, callback=None):
        
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        self.parser = parser = NewOptionParser(prog=self.prog_name,
                             usage=self.usage_info,
#                             version=self.get_version(),
                             formatter = NewFormatter(),
                             add_help_option = False,
                             option_list=self.option_list)
        
        if not self.global_options:
            global_options, args = parser.parse_args(self.argv)
            global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps'))
            handle_default_options(global_options)
            args = args[1:]
        else:
            global_options = self.global_options
            args = self.argv

        if global_options.envs:
            for x in global_options.envs:
                if '=' in x:
                    k, v = x.split('=')
                    os.environ[k.strip()] = v.strip()
                else:
                    print ('Error: environment variable definition (%s) format is not right, '
                           'shoule be -Ek=v or -Ek="a b"' % x)

        global_options.settings = global_options.settings or os.environ.get('SETTINGS', 'settings.ini')
        global_options.local_settings = global_options.local_settings or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini')
        
        if callback:
            callback(global_options)
            
        if len(args) == 0:
            if global_options.version:
                print self.get_version()
                sys.exit(0)
            else:
                self.print_help(global_options)
                sys.ext(1)

        self.do_command(args, global_options)
15523
def _wrap_run_cmd(jsonfile, mode='replay'):
    
    logger = logging.getLogger(__name__)
    records = []
    counter = 0
    json_opts = {'indent': 2, 'separators':(',',': '), 'sort_keys': True}
    def run_cmd_record(*args, **kwargs):
        response = run_cmd(*args, **kwargs)
        records.append({'args': args, 'kwargs': kwargs, 'response': response})
        with open(jsonfile, 'w') as out_fh:
            json.dump(records, out_fh, **json_opts)
        return response
    def run_cmd_replay(*args, **kwargs):
        record = records.pop(0)
        logger.debug("cached run_cmd, args=%s, kwargs=%s"
                     % (str(args), str(kwargs)) )
        assert list(record['args']) == list(args), \
            "run_cmd call #%d: Obtained args: '%s'; Expected args: '%s'" \
            % (counter+1, str(args), str(record['args']))
        assert record['kwargs'] == kwargs, \
            "run_cmd call #%d: Obtained kwargs: '%s'; Expected kwargs: '%s'" \
            % (counter+1, str(kwargs), str(record['kwargs']))
        response = record['response']
        if "\n" in response:
            if len(response.splitlines()) == 1:
                logger.debug("cached response: %s", response)
            else:
                logger.debug("cached response: ---\n%s\n---", response)
        else:
            logger.debug("cached response: '%s'", response)
        return response
    if mode == 'replay':
        with open(jsonfile) as in_fh:
            records = json.load(in_fh)
        return run_cmd_replay
    elif mode == 'record':
        return run_cmd_record
    else:
        raise ValueError("Invalid mode")
1028730
def _run_raw(self, cmd, ignore_errors=False):
    """"""
    # TODO: capture stdout/stderr for feature parity with aws_backend
    result = os.system(cmd)
    if result != 0:
      if ignore_errors:
        self.log(f"command ({cmd}) failed.")
        assert False, "_run_raw failed"
463290
def run(arguments: typing.List[str] = None):
    """"""
    initialize()

    from cauldron.invoke import parser
    from cauldron.invoke import invoker

    args = parser.parse(arguments)
    exit_code = invoker.run(args.get('command'), args)
    sys.exit(exit_code)
194208
def decorate(self, fun):
        """"""
        @wraps(fun)
        def _decorated(*args, **kwargs):
            # Push the config, run the function and pop it afterwards.
            self.push_config()
            try:
                return fun(*args, **kwargs)
            finally:
                self.pop_config()
        return _decorated
1089515
def run_command(args):
    """"""
    library_rc = 'pylintrc'
    test_rc = 'pylintrc.test'

    if os.path.exists(library_rc):
        os.remove(library_rc)

    if os.path.exists(test_rc):
        os.remove(test_rc)

    default_config = read_config(get_default_config())
    user_config = load_local_config(args.config)
    configuration = determine_final_config(user_config)

    make_rc(default_config, library_rc,
            additions=configuration.library_additions,
            replacements=configuration.library_replacements)
    make_rc(default_config, test_rc,
            additions=configuration.test_additions,
            replacements=configuration.test_replacements)

    lint_fileset(*args.library_filesets, rc_filename=library_rc,
                 description='Library')
    lint_fileset(*args.test_filesets, rc_filename=test_rc,
                 description='Test')