Return state of container (running or stopped)

    CLI Example:

    .. code-block:: bash

        salt myminion nspawn.state <name>
168490
def state(name):
    '''
    
    '''
    try:
        cmd = 'show {0} --property=State'.format(name)
        return _machinectl(cmd, ignore_retcode=True)['stdout'].split('=')[-1]
    except IndexError:
        return 'stopped'
286477
def state(self) -> SessionState:
        """"""
        if self.session_id is None:
            raise ValueError("session not yet started")
        session = self.client.get_session(self.session_id)
        if session is None:
            raise ValueError("session not found - it may have been shut down")
        return session.state
707124
ServerStatus getState() {
        final InternalState requiredState = this.requiredState;
        final InternalState state = internalState;
        if(requiredState == InternalState.FAILED) {
            return ServerStatus.FAILED;
        }
        switch (state) {
            case STOPPED:
                return ServerStatus.STOPPED;
            case SERVER_STARTED:
                return  ServerStatus.STARTED;
            default: {
                if(requiredState == InternalState.SERVER_STARTED) {
                    return ServerStatus.STARTING;
                } else {
                    return ServerStatus.STOPPING;
                }
            }
        }
    }
464578
def process(name):
    '''
    
    '''
    # Monitoring state, no changes will be made so no test interface needed
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {},
           'data': {}}  # Data field for monitoring state

    data = __salt__['status.pid'](name)
    if not data:
        ret['result'] = False
        ret['comment'] += 'Process signature "{0}" not found '.format(
            name
        )
        return ret
    ret['data'] = data
    ret['comment'] += 'Process signature "{0}" was found '.format(
        name
    )
    ret['result'] = True
    return ret
1312670
def state(self, context):
	
		
		
		state = None
		for line in self.read(context, [
			"status",
			context.resolve(self.__name)
		]):
			if line[2] == "state":
				state = line[3].strip()
		return state
770390
def _run(name,
         cmd,
         output=None,
         no_start=False,
         stdin=None,
         python_shell=True,
         preserve_state=False,
         output_loglevel='debug',
         ignore_retcode=False,
         use_vt=False,
         keep_env=None):
    '''
    
    '''
    orig_state = state(name)
    exc = None
    try:
        ret = __salt__['container_resource.run'](
            name,
            cmd,
            container_type=__virtualname__,
            exec_driver=EXEC_DRIVER,
            output=output,
            no_start=no_start,
            stdin=stdin,
            python_shell=python_shell,
            output_loglevel=output_loglevel,
            ignore_retcode=ignore_retcode,
            use_vt=use_vt,
            keep_env=keep_env)
    except Exception:
        raise
    finally:
        # Make sure we stop the container if necessary, even if an exception
        # was raised.
        if preserve_state \
                and orig_state == 'stopped' \
                and state(name) != 'stopped':
            stop(name)

    if output in (None, 'all'):
        return ret
    else:
        return ret[output]
297106
def status():
    '''
    
    '''
    puppet = _Puppet()

    if os.path.isfile(puppet.disabled_lockfile):
        return 'Administratively disabled'

    if os.path.isfile(puppet.run_lockfile):
        try:
            with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
                pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
                os.kill(pid, 0)  # raise an OSError if process doesn't exist
        except (OSError, ValueError):
            return 'Stale lockfile'
        else:
            return 'Applying a catalog'

    if os.path.isfile(puppet.agent_pidfile):
        try:
            with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
                pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
                os.kill(pid, 0)  # raise an OSError if process doesn't exist
        except (OSError, ValueError):
            return 'Stale pidfile'
        else:
            return 'Idle daemon'

    return 'Stopped'
737848
def _systemctl_status(name):
    '''
    
    '''
    contextkey = 'systemd._systemctl_status.%s' % name
    if contextkey in __context__:
        return __context__[contextkey]
    __context__[contextkey] = __salt__['cmd.run_all'](
        _systemctl_cmd('status', name),
        python_shell=False,
        redirect_stderr=True,
        ignore_retcode=True
    )
    return __context__[contextkey]
243762
def halted(name, graceful=True):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    zones = __salt__['zoneadm.list'](installed=True)
    if name in zones:
        ## zone exists
        if zones[name]['state'] != 'running':
            ## zone is not running
            ret['result'] = True
            ret['comment'] = 'Zone {0} already halted'.format(name)
        else:
            ## try and halt the zone
            if not __opts__['test']:
                zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
            if __opts__['test'] or zoneadm_res['status']:
                ret['result'] = True
                ret['changes'][name] = 'halted'
                ret['comment'] = 'Zone {0} halted'.format(name)
            else:
                ret['result'] = False
                ret['comment'] = 'Failed to halt {0}'.format(name)
    else:
        ## zone does not exist
        ret['comment'] = []
        ret['comment'].append(
            'The zone {0} is not in the installed state.'.format(name)
        )
        for zone in zones:
            if zones[zone]['uuid'] == name:
                ret['comment'].append(
                    'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
                        zone,
                        name,
                    )
                )
        ## note: a non existing zone is not running, we do not consider this a failure
        ret['result'] = True
        ret['comment'] = "\n".join(ret['comment'])

    return ret
413101
def find_state(self, container, start=None, end=None, avoid=None, initial_state=None, final_state=None):
        
        self.__set_cpu_state(initial_state)

        # Convert input native addresses to reil addresses.
        start = to_reil_address(start) if start else None
        end = to_reil_address(end) if end else None
        avoid = [to_reil_address(addr) for addr in avoid] if avoid else []

        # Load instruction pointer.
        ip = start if start else container[0].address

        execution_state = Queue()

        trace_current = []
        trace_final = []

        self.__fs_process_container(container, final_state, ip, end, avoid, initial_state, execution_state,
                                    trace_current, trace_final)

        # Only returns when all paths have been visited.
        assert execution_state.empty()

        return trace_final
1111586
def is_running(self):
        
        state = yield from self._get_container_state()
        if state == "running":
            return True
        if self.status == "started":  # The container crashed we need to clean
            yield from self.stop()
        return False
926822
def getPIDStatus(jobStoreName):
        
        try:
            jobstore = Toil.resumeJobStore(jobStoreName)
        except NoSuchJobStoreException:
            return 'QUEUED'
        except NoSuchFileException:
            return 'QUEUED'

        try:
            with jobstore.readSharedFileStream('pid.log') as pidFile:
                pid = int(pidFile.read())
                try:
                    os.kill(pid, 0)  # Does not kill process when 0 is passed.
                except OSError:  # Process not found, must be done.
                    return 'COMPLETED'
                else:
                    return 'RUNNING'
        except NoSuchFileException:
            pass
        return 'QUEUED'
938735
def restoreState(self):
        
        if os.path.exists(self._stateFile):
            try:
                fp = open(self._stateFile,  'r')
                stateObj = pickle.load(fp)
            except:
                raise IOError("Failure in reading plugin state from file: %s" 
                              % self._stateFile)
            return stateObj
        return None
1002050
def get_active_state(self) -> Optional[str]:
        """"""
        for state in self.get_run_states():
            if state.active:
                return state.name
        return None
103991
def get_pauses(jid=None):
    '''
    
    '''
    ret = {}
    active = __salt__['saltutil.is_running']('state.*')
    pause_dir = os.path.join(__opts__['cachedir'], 'state_pause')
    if not os.path.exists(pause_dir):
        return ret
    if jid is None:
        jids = os.listdir(pause_dir)
    elif isinstance(jid, list):
        jids = salt.utils.data.stringify(jid)
    else:
        jids = [six.text_type(jid)]
    for scan_jid in jids:
        is_active = False
        for active_data in active:
            if active_data['jid'] == scan_jid:
                is_active = True
        if not is_active:
            try:
                pause_path = os.path.join(pause_dir, scan_jid)
                os.remove(pause_path)
            except OSError:
                # Already gone
                pass
            continue
        data, pause_path = _get_pause(scan_jid)
        ret[scan_jid] = data
    return ret
1064627
def containers_running(get_container_name):
    
    running = []
    for n in ['web', 'postgres', 'solr', 'datapusher', 'redis']:
        info = docker.inspect_container(get_container_name(n))
        if info and not info['State']['Running']:
            running.append(n + '(halted)')
        elif info:
            running.append(n)
    return running
889177
def get_pid(name, path=None):
    '''
    
    '''
    if name not in list_(limit='running', path=path):
        raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
    info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
    pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
    return pid