Re-interpret the state returned by salt.state.run using our protocol.
516574
def _reinterpreted_state(state):
    '''
    
    '''
    ret = state['changes']
    state['changes'] = {}
    state['comment'] = ''

    out = ret.get('stdout')
    if not out:
        if ret.get('stderr'):
            state['comment'] = ret['stderr']
        return state

    is_json = False
    try:
        data = salt.utils.json.loads(out)
        if not isinstance(data, dict):
            return _failout(
                state,
                'script JSON output must be a JSON object (e.g., {})!'
            )
        is_json = True
    except ValueError:
        idx = out.rstrip().rfind('\n')
        if idx != -1:
            out = out[idx + 1:]
        data = {}
        try:
            for item in salt.utils.args.shlex_split(out):
                key, val = item.split('=')
                data[key] = val
        except ValueError:
            state = _failout(
                state,
                'Failed parsing script output! '
                'Stdout must be JSON or a line of name=value pairs.'
            )
            state['changes'].update(ret)
            return state

    changed = _is_true(data.get('changed', 'no'))

    if 'comment' in data:
        state['comment'] = data['comment']
        del data['comment']

    if changed:
        for key in ret:
            data.setdefault(key, ret[key])

        # if stdout is the state output in JSON, don't show it.
        # otherwise it contains the one line name=value pairs, strip it.
        data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
        state['changes'] = data

    #FIXME: if it's not changed but there's stdout and/or stderr then those
    #       won't be shown as the function output. (though, they will be shown
    #       inside INFO logs).
    return state
612096
def state(self):
        
        if self.method in ['OPTIONS', 'DESCRIBE', 'SETUP', 'PLAY']:
            state = STATE_STARTING
        elif self.method in ['KEEP-ALIVE']:
            state = STATE_PLAYING
        else:
            state = STATE_STOPPED
        _LOGGER.debug('RTSP session (%s) state %s', self.host, state)
        return state
814532
def _state_run(self):
        '''
        
        '''
        if self.opts['startup_states']:
            if self.opts.get('master_type', 'str') == 'disable' and \
                        self.opts.get('file_client', 'remote') == 'remote':
                log.warning(
                    'Cannot run startup_states when \'master_type\' is set '
                    'to \'disable\' and \'file_client\' is set to '
                    '\'remote\'. Skipping.'
                )
            else:
                data = {'jid': 'req', 'ret': self.opts.get('ext_job_cache', '')}
                if self.opts['startup_states'] == 'sls':
                    data['fun'] = 'state.sls'
                    data['arg'] = [self.opts['sls_list']]
                elif self.opts['startup_states'] == 'top':
                    data['fun'] = 'state.top'
                    data['arg'] = [self.opts['top_file']]
                else:
                    data['fun'] = 'state.highstate'
                    data['arg'] = []
                self._handle_decoded_payload(data)
255527
def _refresh_state(self):
    

    # DataFlow's DataflowPipelineResult does not refresh state, so we have to do it ourselves
    # as a workaround.
    # TODO(Change this to use runner_results.state once it refreshes itself)
    dataflow_internal_job = (
        self._runner_results._runner.dataflow_client.get_job(self._runner_results.job_id()))
    self._is_complete = str(dataflow_internal_job.currentState) in ['JOB_STATE_STOPPED',
                                                                    'JOB_STATE_DONE',
                                                                    'JOB_STATE_FAILED',
                                                                    'JOB_STATE_CANCELLED']
    self._fatal_error = getattr(self._runner_results._runner, 'last_error_msg', None)
    # Sometimes Dataflow does not populate runner.last_error_msg even if the job fails.
    if self._fatal_error is None and self._runner_results.state == 'FAILED':
      self._fatal_error = 'FAILED'
786928
public State<S, A> withState(Fn1<? super S, ? extends S> fn) {
        return state(s -> run(fn.apply(s)));
    }
482575
def exec_lowstate(self, client=None, token=None):
        '''
        
        '''
        lowstate = cherrypy.request.lowstate

        # Release the session lock before executing any potentially
        # long-running Salt commands. This allows different threads to execute
        # Salt commands concurrently without blocking.
        if cherrypy.request.config.get('tools.sessions.on', False):
            cherrypy.session.release_lock()

        # if the lowstate loaded isn't a list, lets notify the client
        if not isinstance(lowstate, list):
            raise cherrypy.HTTPError(400, 'Lowstates must be a list')

        # Make any requested additions or modifications to each lowstate, then
        # execute each one and yield the result.
        for chunk in lowstate:
            if token:
                chunk['token'] = token

            if 'token' in chunk:
                # Make sure that auth token is hex
                try:
                    int(chunk['token'], 16)
                except (TypeError, ValueError):
                    raise cherrypy.HTTPError(401, 'Invalid token')

            if 'token' in chunk:
                # Make sure that auth token is hex
                try:
                    int(chunk['token'], 16)
                except (TypeError, ValueError):
                    raise cherrypy.HTTPError(401, 'Invalid token')

            if client:
                chunk['client'] = client

            # Make any 'arg' params a list if not already.
            # This is largely to fix a deficiency in the urlencoded format.
            if 'arg' in chunk and not isinstance(chunk['arg'], list):
                chunk['arg'] = [chunk['arg']]

            ret = self.api.run(chunk)

            # Sometimes Salt gives us a return and sometimes an iterator
            if isinstance(ret, collections.Iterator):
                for i in ret:
                    yield i
            else:
                yield ret
777893
def _toState(self, state, *args, **kwargs):
        
        try:
            method = getattr(self, '_state_%s' % state)
        except AttributeError:
            raise ValueError("No such state %r" % state)

        log.msg("%s: to state %r" % (self.__class__.__name__, state))
        self._state = state
        method(*args, **kwargs)
658490
def rerun(self):

        

        self._state = states.SCHEDULING
        self._completed_flag = threading.Event()
        print 'Pipeline %s in %s state'%(self._uid, self._state)
981457
def popState(self):
        
        diff = self._states.pop() - len(self)
        if diff:
            self.extend(self._hidden[-diff:])
            del self._hidden[-diff:]
1062107
def run(self) -> 'QuantumFlowQVM':
        """"""
        assert self.status in ['loaded']
        self.status = 'running'
        self._ket = self._prog.run()
        # Should set state to 'done' after run complete.
        # Makes no sense to keep status at running. But pyQuil's
        # QuantumComputer calls wait() after run, which expects state to be
        # 'running', and whose only effect to is to set state to 'done'
        return self
204127
def show_lowstate(**kwargs):
    '''
    
    '''
    __opts__['grains'] = __grains__
    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
    st_ = salt.client.ssh.state.SSHHighState(
            opts,
            __pillar__,
            __salt__,
            __context__['fileclient'])
    st_.push_active()
    chunks = st_.compile_low_chunks()
    _cleanup_slsmod_low_data(chunks)
    return chunks
402147
function(rule) {
      var state = this.bt.current_state();
      try { return rule.call(this); } 
      catch(f) {
        this.bt.catch_mismatch(f);
        this.bt.restore(state);
      }
    }
800722
function stateStr(state) {
    if (state & STATE_CANCELLED) {
        return 'cancel';
    } else if (state & STATE_ENDED) {
        return 'end';
    } else if (state & STATE_CHANGED) {
        return 'move';
    } else if (state & STATE_BEGAN) {
        return 'start';
    }
    return '';
}
656347
def PopState(self, **unused_kwargs):
    """"""
    try:
      self.state = self.state_stack.pop()
      logging.debug('Returned state to {0:s}'.format(self.state))

      return self.state
    except IndexError:
      self.Error(
          'Tried to pop the state but failed - possible recursion error')
346822
def _compile_state(sls_opts, mods=None):
    '''
    
    '''
    st_ = HighState(sls_opts)

    if not mods:
        return st_.compile_low_chunks()

    high_data, errors = st_.render_highstate({sls_opts['saltenv']: mods})
    high_data, ext_errors = st_.state.reconcile_extend(high_data)
    errors += ext_errors
    errors += st_.state.verify_high(high_data)
    if errors:
        return errors

    high_data, req_in_errors = st_.state.requisite_in(high_data)
    errors += req_in_errors
    high_data = st_.state.apply_exclude(high_data)
    # Verify that the high data is structurally sound
    if errors:
        return errors

    # Compile and verify the raw chunks
    return st_.state.compile_high_data(high_data)
552070
def _load_states(self):
        '''
        
        '''
        if self.states_loader == 'thorium':
            self.states = salt.loader.thorium(self.opts, self.functions, {})  # TODO: Add runners, proxy?
        else:
            self.states = salt.loader.states(self.opts, self.functions, self.utils,
                                             self.serializers, context=self.state_con, proxy=self.proxy)
561562
def running_state(self, running_state):
        
        allowed_values = ["ONGOING", "PENDING", "ENDED"]  # noqa: E501
        if running_state not in allowed_values:
            raise ValueError(
                "Invalid value for `running_state` ({0}), must be one of {1}"  # noqa: E501
                .format(running_state, allowed_values)
            )

        self._running_state = running_state