Execute the Cauldron container command
328287
def run():
    """"""

    command = sys.argv[1].strip().lower()
    print('[COMMAND]:', command)

    if command == 'test':
        return run_test()
    elif command == 'build':
        return run_build()
    elif command == 'up':
        return run_container()
    elif command == 'serve':
        import cauldron
        cauldron.run_server(port=5010, public=True)
28240
def execute(self):
        

        role_name = self._command_args['role_name']
        role_directory = os.getcwd()
        msg = 'Initializing new role {}...'.format(role_name)
        LOG.info(msg)

        if os.path.isdir(role_name):
            msg = ('The directory {} exists. '
                   'Cannot create new role.').format(role_name)
            util.sysexit_with_message(msg)

        template_directory = ''
        if 'template' in self._command_args.keys():
            template_directory = self._command_args['template']
        else:
            template_directory = 'role'
        self._process_templates(template_directory, self._command_args,
                                role_directory)
        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            'scenario/driver/{driver_name}'.format(**self._command_args),
            'scenario/verifier/{verifier_name}'.format(**self._command_args),
        ]
        for template in templates:
            self._process_templates(template, self._command_args,
                                    scenario_base_directory)
        self._process_templates('molecule', self._command_args, role_directory)

        role_directory = os.path.join(role_directory, role_name)
        msg = 'Initialized role in {} successfully.'.format(role_directory)
        LOG.success(msg)
389820
def run(self):
        
        _ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
        check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None))
1187834
def execute_command(self, request, command, frame):
        """"""
        return Response(frame.console.eval(command), mimetype="text/html")
766074
public function execute()
    {
        switch (strtolower(PSI_PLUGIN_HYPERV_ACCESS)) {
        case 'command':
            if (PSI_OS == 'WINNT') {
                try {
                    $objLocator = new COM('WbemScripting.SWbemLocator');
                    $wmic = $objLocator->ConnectServer('', 'root\CIMv2');
                    $buffer = CommonFunctions::getWMI($wmic, 'Win32_OperatingSystem', array('Version'));
                    if ($buffer && isset($buffer[0]) && isset($buffer[0]['Version'])) {
                        if (version_compare($buffer[0]['Version'], "6.2", ">=")) { // minimal windows 2012 or windows 8
                            $wmi = $objLocator->ConnectServer('', 'root\virtualization\v2');
                        } elseif (version_compare($buffer[0]['Version'], "6.0", ">=")) { // minimal windows 2008
                            $wmi = $objLocator->ConnectServer('', 'root\virtualization');
                        } else {
                           $this->global_error->addError("HyperV plugin", "Unsupported Windows version");
                           break;
                        }
                    } else {
                        $this->global_error->addError("HyperV plugin", "Unsupported Windows version");
                        break;
                    }
                    $result = CommonFunctions::getWMI($wmi, 'MSVM_ComputerSystem', array('InstallDate', 'EnabledState', 'ElementName'));
                    if (is_array($result)) foreach ($result as $machine) {
                        if ($machine['InstallDate'] !== null) {
                            $this->_filecontent[] = array($machine['ElementName'], $machine['EnabledState']);
                        }
                    }
                } catch (Exception $e) {
                }
            }
            break;
        case 'data':
            CommonFunctions::rfts(PSI_APP_ROOT."/data/hyperv.txt", $buffer);
            $processes = preg_split("/\n/", $buffer, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($processes as $process) {
                $ps = preg_split("/[\s]?\|[\s]?/", $process, -1, PREG_SPLIT_NO_EMPTY);
                if (count($ps) == 2) {
                    $this->_filecontent[] = array(trim($ps[0]), trim($ps[1]));
                }
            }
            break;
        default:
            $this->global_error->addConfigError("execute()", "[hyperv] ACCESS");
            break;
        }
    }
75234
def execute(self, args):
        """"""
        hook_name = os.path.basename(args[0])
        extra_vars = None
        if hook_name in self._actions:
            extra_vars = self._actions[hook_name](args[1:])
        else:
            super(AnsibleHooks, self).execute(args)

        charmhelpers.contrib.ansible.apply_playbook(
            self.playbook_path, tags=[hook_name], extra_vars=extra_vars)
275535
def exec(self, *command_tokens, command_context=None, **command_env):
		
		if self.adapter().match(command_context, **command_env) is False:
			cmd = WCommandProto.join_tokens(*command_tokens)
			spec = self.adapter().specification()
			if spec is not None:
				spec = [x.context_name() for x in spec]
				spec.reverse()
				spec = ','.join(spec)
			raise RuntimeError('Command mismatch: %s (context: %s)' % (cmd, spec))

		command_tokens = self.adapter().adapt(*command_tokens, command_context=command_context, **command_env)
		return self.original_command().exec(*command_tokens, command_context=command_context, **command_env)
1297176
def run(self):
        """"""
        _check_directory(self.directory)

        with DirectoryContextManager(self.directory):
            process = subprocess.Popen(self.arguments, shell=self._shell, env=self.env)

            _, _ = process.communicate()

        returncode = process.returncode

        if returncode != 0 and not self._ignore_errors:
            raise CommandError(
                '"{0}" failed (err code {1})'.format(self.__repr__(), returncode)
            )
1019389
async def execute_command(self, command):
        """"""
        self.apply_future = asyncio.Future(loop=self.loop)

        entry = self.log.write(self.storage.term, command)
        asyncio.ensure_future(self.append_entries(), loop=self.loop)

        await self.apply_future
84875
def execute(asynchronous: bool = False):
    
    r = Response()
    r.update(server=server_runner.get_server_data())

    cmd, args = parse_command_args(r)
    if r.failed:
        return flask.jsonify(r.serialize())

    try:
        commander.execute(cmd, args, r)
        if not r.thread:
            return flask.jsonify(r.serialize())

        if not asynchronous:
            r.thread.join()

        server_runner.active_execution_responses[r.thread.uid] = r

        # Watch the thread for a bit to see if the command finishes in
        # that time. If it does the command result will be returned directly
        # to the caller. Otherwise, a waiting command will be issued
        count = 0
        while count < 5:
            count += 1
            r.thread.join(0.25)
            if not r.thread.is_alive():
                break

        if r.thread.is_alive():
            return flask.jsonify(
                Response()
                .update(
                    run_log=r.get_thread_log(),
                    run_status='running',
                    run_uid=r.thread.uid,
                    step_changes=server_runner.get_running_step_changes(True),
                    server=server_runner.get_server_data()
                )
                .serialize()
            )

        del server_runner.active_execution_responses[r.thread.uid]
        r.update(
            run_log=r.get_thread_log(),
            run_status='complete',
            run_multiple_updates=False,
            run_uid=r.thread.uid
        )
    except Exception as err:
        r.fail(
            code='KERNEL_EXECUTION_FAILURE',
            message='Unable to execute command',
            cmd=cmd,
            args=args,
            error=err
        )

    return flask.jsonify(r.serialize())
1279892
def _exec(**kwargs):
    '''
    
    '''
    if 'ignore_retcode' not in kwargs:
        kwargs['ignore_retcode'] = True
    if 'output_loglevel' not in kwargs:
        kwargs['output_loglevel'] = 'quiet'
    return salt.modules.cmdmod.run_all(**kwargs)
1219783
function execute (str, { cwd }) {
  // command = replace(command, options);
  // command = prepend(command, options);

  let args = str.split(' ')
  const command = args.shift()
  args = [args.join(' ')]

  const subprocess = spawn(command, args, {
    detached: true,
    stdio: 'ignore',
    cwd
  })

  subprocess.unref()

  return subprocess.pid
}
866647
def run(self, command, variables=[], board=None, packages=[]):
        """"""

        # -- Check for the SConstruct file
        if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')):
            variables += ['-f']
            variables += [util.safe_join(
                util.get_folder('resources'), 'SConstruct')]
        else:
            click.secho('Info: use custom SConstruct file')

        # -- Resolve packages
        if self.profile.check_exe_default():
            # Run on `default` config mode
            if not util.resolve_packages(
              packages,
              self.profile.packages,
              self.resources.distribution.get('packages')
             ):
                # Exit if a package is not installed
                raise Exception
        else:
            click.secho('Info: native config mode')

        # -- Execute scons
        return self._execute_scons(command, variables, board)
754484
def container_run(platform: str,
                  nvidia_runtime: bool,
                  docker_registry: str,
                  shared_memory_size: str,
                  local_ccache_dir: str,
                  command: List[str],
                  cleanup: Cleanup,
                  environment: Dict[str, str],
                  dry_run: bool = False) -> int:
    """"""
    container_wait_s = 600
    #
    # Environment setup
    #
    environment.update({
        'CCACHE_MAXSIZE': '500G',
        'CCACHE_TEMPDIR': '/tmp/ccache',  # temp dir should be local and not shared
        'CCACHE_DIR': '/work/ccache',  # this path is inside the container as /work/ccache is
                                       # mounted
        'CCACHE_LOGFILE': '/tmp/ccache.log',  # a container-scoped log, useful for ccache
                                              # verification.
    })
    # These variables are passed to the container to the process tree killer can find runaway
    # process inside the container
    # https://wiki.jenkins.io/display/JENKINS/ProcessTreeKiller
    # https://github.com/jenkinsci/jenkins/blob/578d6bacb33a5e99f149de504c80275796f0b231/core/src/main/java/hudson/model/Run.java#L2393
    #
    jenkins_env_vars = ['BUILD_NUMBER', 'BUILD_ID', 'BUILD_TAG']
    environment.update({k: os.environ[k] for k in jenkins_env_vars if k in os.environ})
    environment.update({k: os.environ[k] for k in ['CCACHE_MAXSIZE'] if k in os.environ})

    tag = get_docker_tag(platform=platform, registry=docker_registry)
    mx_root = get_mxnet_root()
    local_build_folder = buildir()
    # We need to create it first, otherwise it will be created by the docker daemon with root only permissions
    os.makedirs(local_build_folder, exist_ok=True)
    os.makedirs(local_ccache_dir, exist_ok=True)
    logging.info("Using ccache directory: %s", local_ccache_dir)
    docker_client = docker.from_env()
    # Equivalent command
    docker_cmd_list = [
        get_docker_binary(nvidia_runtime),
        'run',
        "--cap-add",
        "SYS_PTRACE", # Required by ASAN
        '--rm',
        '--shm-size={}'.format(shared_memory_size),
        # mount mxnet root
        '-v', "{}:/work/mxnet".format(mx_root),
        # mount mxnet/build for storing build
        '-v', "{}:/work/build".format(local_build_folder),
        '-v', "{}:/work/ccache".format(local_ccache_dir),
        '-u', '{}:{}'.format(os.getuid(), os.getgid()),
        '-e', 'CCACHE_MAXSIZE={}'.format(environment['CCACHE_MAXSIZE']),
        # temp dir should be local and not shared
        '-e', 'CCACHE_TEMPDIR={}'.format(environment['CCACHE_TEMPDIR']),
        # this path is inside the container as /work/ccache is mounted
        '-e', "CCACHE_DIR={}".format(environment['CCACHE_DIR']),
        # a container-scoped log, useful for ccache verification.
        '-e', "CCACHE_LOGFILE={}".format(environment['CCACHE_LOGFILE']),
        '-ti',
        tag]
    docker_cmd_list.extend(command)
    docker_cmd = ' \\\n\t'.join(docker_cmd_list)
    logging.info("Running %s in container %s", command, tag)
    logging.info("Executing the equivalent of:\n%s\n", docker_cmd)
    # return code of the command inside docker
    ret = 0
    if not dry_run:
        #############################
        #
        signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT, signal.SIGTERM})
        # noinspection PyShadowingNames
        runtime = None
        if nvidia_runtime:
            # noinspection PyShadowingNames
            # runc is default (docker info | grep -i runtime)
            runtime = 'nvidia'
        container = docker_client.containers.run(
            tag,
            runtime=runtime,
            detach=True,
            command=command,
            shm_size=shared_memory_size,
            user='{}:{}'.format(os.getuid(), os.getgid()),
            cap_add='SYS_PTRACE',
            volumes={
                mx_root:
                    {'bind': '/work/mxnet', 'mode': 'rw'},
                local_build_folder:
                    {'bind': '/work/build', 'mode': 'rw'},
                local_ccache_dir:
                    {'bind': '/work/ccache', 'mode': 'rw'},
            },
            environment=environment)
        try:
            logging.info("Started container: %s", trim_container_id(container.id))
            # Race condition:
            # If the previous call is interrupted then it's possible that the container is not cleaned up
            # We avoid by masking the signals temporarily
            cleanup.add_container(container)
            signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT, signal.SIGTERM})
            #
            #############################

            stream = container.logs(stream=True, stdout=True, stderr=True)
            sys.stdout.flush()
            for chunk in stream:
                sys.stdout.buffer.write(chunk)
                sys.stdout.buffer.flush()
            sys.stdout.flush()
            stream.close()
            try:
                logging.info("Waiting for status of container %s for %d s.",
                            trim_container_id(container.id),
                            container_wait_s)
                wait_result = container.wait(timeout=container_wait_s)
                logging.info("Container exit status: %s", wait_result)
                ret = wait_result.get('StatusCode', 200)
                if ret != 0:
                    logging.error("Container exited with an error 😞")
                else:
                    logging.info("Container exited with success 👍")
            except Exception as e:
                logging.exception(e)
                ret = 150

            # Stop
            try:
                logging.info("Stopping container: %s", trim_container_id(container.id))
                container.stop()
            except Exception as e:
                logging.exception(e)
                ret = 151

            # Remove
            try:
                logging.info("Removing container: %s", trim_container_id(container.id))
                container.remove()
            except Exception as e:
                logging.exception(e)
                ret = 152
            cleanup.remove_container(container)
            containers = docker_client.containers.list()
            if containers:
                logging.info("Other running containers: %s", [trim_container_id(x.id) for x in containers])
        except docker.errors.NotFound as e:
            logging.info("Container was stopped before cleanup started: %s", e)
    return ret
585114
def execute(client, output_file, output_paths=None):
    """"""
    output_paths = output_paths or set()

    import cwltool.factory
    from cwltool import workflow
    from cwltool.context import LoadingContext, RuntimeContext
    from cwltool.utils import visit_class

    def construct_tool_object(toolpath_object, *args, **kwargs):
        """Fix missing locations."""
        protocol = 'file://'

        def addLocation(d):
            if 'location' not in d and 'path' in d:
                d['location'] = protocol + d['path']

        visit_class(toolpath_object, ('File', 'Directory'), addLocation)
        return workflow.default_make_tool(toolpath_object, *args, **kwargs)

    argv = sys.argv
    sys.argv = ['cwltool']

    # Keep all environment variables.
    runtime_context = RuntimeContext(
        kwargs={
            'rm_tmpdir': False,
            'move_outputs': 'leave',
            'preserve_entire_environment': True,
        }
    )
    loading_context = LoadingContext(
        kwargs={
            'construct_tool_object': construct_tool_object,
        }
    )

    factory = cwltool.factory.Factory(
        loading_context=loading_context,
        runtime_context=runtime_context,
    )
    process = factory.make(os.path.relpath(str(output_file)))
    outputs = process()

    sys.argv = argv

    # Move outputs to correct location in the repository.
    output_dirs = process.factory.executor.output_dirs

    def remove_prefix(location, prefix='file://'):
        if location.startswith(prefix):
            return location[len(prefix):]
        return location

    locations = {
        remove_prefix(output['location'])
        for output in outputs.values()
    }

    with progressbar(
        locations,
        label='Moving outputs',
    ) as bar:
        for location in bar:
            for output_dir in output_dirs:
                if location.startswith(output_dir):
                    output_path = location[len(output_dir):].lstrip(
                        os.path.sep
                    )
                    destination = client.path / output_path
                    if destination.is_dir():
                        shutil.rmtree(str(destination))
                        destination = destination.parent
                    shutil.move(location, str(destination))
                    continue

    unchanged_paths = client.remove_unmodified(output_paths)
    if unchanged_paths:
        click.echo(
            'Unchanged files:\n\n\t{0}'.format(
                '\n\t'.join(
                    click.style(path, fg='yellow') for path in unchanged_paths
                )
            )
        )
221046
def execute(self, *, args: Union[list, tuple], options: dict) -> tuple:
        ''''''
        cmd = self._build_cmd(args)
        process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE,
                                   encoding='utf-8', shell=options.get('shell', False), env=options.get('env'))
        return process
392916
def run_in_container(command, container_dir):
    
    container_p = local.path(container_dir)
    with local.cwd(container_p):
        uchrt = uchroot.with_mounts()
        uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r",
                      container_p]
        uchrt = uchrt["--"]

        cmd_path = container_p / command[0].lstrip('/')
        if not cmd_path.exists():
            LOG.error("The command does not exist inside the container! %s",
                      cmd_path)
            return

        cmd = uchrt[command]
        return cmd & FG