Store the command result for complex state machines.

    It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR.
511350
def a_store_cmd_result(ctx):
    
    result = ctx.ctrl.before
    # check if multi line
    index = result.find('\n')
    if index > 0:
        # remove first line
        result = result[index + 1:]
    ctx.device.last_command_result = result.replace('\r', '')
    return True
1039217
function Output(options) {
  options = options || {};
  this.command = options.command || '';
  this.args = options.args || {};
  this.typed = options.typed || '';
  this.canonical = options.canonical || '';
  this.hidden = options.hidden === true ? true : false;

  this.data = undefined;
  this.completed = false;
  this.error = false;
  this.start = new Date();

  this.deferred = Promise.defer();
  this.then = this.deferred.promise.then;

  this.onClose = util.createEvent('Output.onClose');
  this.onChange = util.createEvent('Output.onChange');
}
1327440
def _execute(self, execute_inputs, execute_outputs, backward_execution=False):
        
        self._script.build_module()

        outcome_item = self._script.execute(self, execute_inputs, execute_outputs, backward_execution)

        # in the case of backward execution the outcome is not relevant
        if backward_execution:
            return

        # If the state was preempted, the state must be left on the preempted outcome
        if self.preempted:
            return Outcome(-2, "preempted")

        # Outcome id was returned
        if outcome_item in self.outcomes:
            return self.outcomes[outcome_item]

        # Outcome name was returned
        for outcome_id, outcome in self.outcomes.items():
            if outcome.name == outcome_item:
                return self.outcomes[outcome_id]

        logger.error("Returned outcome of {0} not existing: {1}".format(self, outcome_item))
        return Outcome(-1, "aborted")
756674
def store_state(self, state, popl_db=True):
        
        self.state = state
        if popl_db:
            fw_dict = self.get_fw_dict()
            self.append_state_final_result(fw_dict.get('fw_id'),
                                           self.get_local_final_result(),
                                           state)
835952
def _store(self, message_key: str, result: Result, ttl: int) -> None:  # pragma: no cover
        
        raise NotImplementedError("%(classname)r does not implement _store()" % {
            "classname": type(self).__name__,
        })
362378
async function execAndReport({ cmd, name }) {
  try {
    const {
      failed,
      // code,
      // timedOut,
      stdout,
      stderr,
      // message,
    } = await execa.shell(cmd);
    process.stdout.write(stdout);
    process.stderr.write(stderr);
    await setCheckRun({
      name,
      status: 'completed',
      conclusion: 'success',
      output: {
        title: name,
        summary: `Ran ${cmd}`,
      },
    });
    return failed;
  } catch (err) {
    const {
      failed,
      // code,
      // timedOut,
      stdout,
      stderr,
      message,
    } = err;
    process.stdout.write(stdout);
    process.stderr.write(stderr);
    await setCheckRun({
      name,
      status: 'completed',
      conclusion: 'failure',
      output: {
        title: name,
        summary: `Ran ${cmd}`,
        text: `
<pre><code>
${message}
</code></pre>
        `.trim(),
      },
    });

    return failed;
  }
}
835246
def finalize_concurrency_state(self, outcome):
        
        final_outcome = outcome
        self.write_output_data()
        self.check_output_data_type()
        self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data)
        self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE

        singleton.state_machine_execution_engine._modify_run_to_states(self)

        if self.preempted:
            final_outcome = Outcome(-2, "preempted")
        return self.finalize(final_outcome)
1113415
def save_inventory(inventory, hosts_file=HOSTS_FILE):
    '''
    '''
    with open(hosts_file, 'w') as f:
        inventory.write(f)
30774
function Result(cmd, err, stdout, stderr) {
  this.cmd = cmd;
  this.err = err;
  this.stdout = strip(stdout);
  this.stderr = strip(stderr);
}
435185
def _persist(self):
        
        # run the block/command
        for command in self.commands:
            try:
                process = Popen(
                    [command],
                    stdout=PIPE,
                    stderr=PIPE,
                    universal_newlines=True,
                    env=self.env,
                    shell=True,
                )
            except Exception as e:
                retcode = process.poll()
                msg = "Command '{cmd}' {error} retcode {retcode}"
                self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))

            # persistent blocklet output can be of two forms.  Either each row
            # of the output is on a new line this is much easier to deal with)
            # or else the output can be continuous and just flushed when ready.
            # The second form is more tricky, if we find newlines then we
            # switch to easy parsing of the output.

            # When we have output we store in self.persistent_output and then
            # trigger the module to update.

            fd = process.stdout.fileno()
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            has_newlines = False
            while True:
                line = process.stdout.read(1)
                # switch to a non-blocking read as we do not know the output
                # length
                fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
                line += process.stdout.read(1024)
                # switch back to blocking so we can wait for the next output
                fcntl.fcntl(fd, fcntl.F_SETFL, fl)
                if process.poll():
                    break
                if self.py3.is_python_2():
                    line = line.decode("utf-8")
                self.persistent_output = line
                self.py3.update()
                if line[-1] == "\n":
                    has_newlines = True
                    break
                if line == "":
                    break
            if has_newlines:
                msg = "Switch to newline persist method {cmd}"
                self.py3.log(msg.format(cmd=command))
                # just read the output in a sane manner
                for line in iter(process.stdout.readline, b""):
                    if process.poll():
                        break
                    if self.py3.is_python_2():
                        line = line.decode("utf-8")
                    self.persistent_output = line
                    self.py3.update()
        self.py3.log("command exited {cmd}".format(cmd=command))
        self.persistent_output = "Error\nError\n{}".format(
            self.py3.COLOR_ERROR or self.py3.COLOR_BAD
        )
        self.py3.update()
1112306
function command(req, res) {

  this.stats.commands++;

  //console.dir(this);

  // guaranteed to have a string command by connection
  var cmd = req.cmd
    // guaranteed to have an arguments array by connection
    , args = req.args

    // select implementation should guarantee a valid db index
    // on the connection
    , db = this.store.getDatabase(req.conn.db)
    // info object used by the validate function
    , exec = this.execs[cmd]
    , info = {
      db: db, conf: this.conf, conn: req.conn, exec: exec, commands: this.execs}
    // should we queue this command in a transaction
    // of just execute it
    , queue = cmd !== DISCARD && cmd !== EXEC
    // flag if command is acceptable when busy
    , acceptable;

  // raw arguments list, before validation
  // used so that the slowlog does not show modified arguments
  req.raw = args.slice(0);

  //console.error('server processing command: %s', cmd);
  //console.error('server processing command: %j', args);
    //

  if(ScriptManager.busy && !req.script) {
    // compare on command instances
    // in case they have been renamed
    acceptable =
      (exec === Shutdown
       && ('' + args[0] || '').toLowerCase() === NOSAVE)
      || (exec === Script
        && ('' + args[0] || '').toLowerCase() === KILL);
    if(!acceptable) return res.send(StoreError.Busy);
  }

  if(exec === false) {
    return res.send(StoreError.UnknownDisabled);
  }else if(!exec) {
    return res.send(new UnknownCommand(cmd));
  }

  try {
    exec.validate.call(this, cmd, args, info);

    // inject references
    req.db = db;
    req.conf = this.conf;
    req.exec = exec;

    // these properties are available on the req
    delete info.db;
    delete info.conn;
    delete info.conf;

    // inject the info object which is decorated with
    // additional useful information on validation
    req.info = info;

    // alias the command definition
    req.def = req.exec.definition;
  }catch(e) {
    // let the transaction decide how to proceed on error
    if(req.conn.transaction) {
      return req.conn.transaction.add(e, req, res);
    }
    return res.send(e);
  }

  if(req.conn.transaction && queue) {
    return req.conn.transaction.add(null, req, res);
  }

  this.execute(exec, req, res);

}
907773
public function cmdGetCache()
    {
        $id = $this->getParam(0);

        if (empty($id)) {
            $this->errorAndExit($this->text('Invalid command'));
        }

        $result = $this->cache->get($id);

        if (!isset($result)) {
            $this->errorAndExit($this->text('Unexpected result'));
        }

        $this->outputFormat($result, 'json');
        $this->output();
    }
1154764
def state_machine_success():
    """"""
    from furious.async import Async
    from furious.context import get_current_async

    result = get_current_async().result

    if result == 'ALPHA':
        logging.info('Inserting continuation for state %s.', result)
        return Async(target=complex_state_generator_alpha, args=[result])

    elif result == 'BRAVO':
        logging.info('Inserting continuation for state %s.', result)
        return Async(target=complex_state_generator_bravo, args=[result])

    logging.info('Done working, stop now.')
399351
def aggregate_result(self, return_code, output, service_description='', specific_servers=None):
        '''
        
        '''
        if specific_servers == None:
            specific_servers = self.servers
        else:
            specific_servers = set(self.servers).intersection(specific_servers)

        for server in specific_servers:
            if not self.servers[server]['send_errors_only'] or return_code > 0:
                self.servers[server]['results'].append({'return_code': return_code,
                           'output': output,
                           'service_description': service_description,
                           'return_status': STATUSES[return_code][0],
                           'custom_fqdn': self.servers[server]['custom_fqdn']})
                LOG.info("[email][%s][%s]: Aggregate result: %r", service_description, server, self.servers[server]['results'][-1])
51679
def record_result(self, res, prg=''):
        
        self._log(self.logFileResult , force_to_string(res), prg)
485762
def write_output(self):
        
        # output
        self.tcex.log.debug('output_strings: {}'.format(self.output_strings))

        self.tcex.playbook.create_output('string.operation', self.args.tc_action)
        self.tcex.playbook.create_output('string.outputs', self.output_strings)
        if self.output_strings:
            self.tcex.playbook.create_output('string.outputs.0', self.output_strings[0])
        self.tcex.playbook.create_output('string.outputs.count', len(self.output_strings))
137195
def put(self):
        
        return self.manager.put(
            id=self.id,
            name=self.name,
            description=self.description,
            command_to_run=self.command_to_run,
            environment_variables=self.environment_variables,
            required_arguments=self.required_arguments,
            required_arguments_default_values=(
                self.required_arguments_default_values
            ),
            logs_path=self.logs_path,
            results_path=self.results_path,
            container_image=self.container_image,
            container_type=self.container_type,
        )