Set the minion running flag and issue the appropriate warnings if
        the minion cannot be started or is already running
969541
def _pre_tune(self):
        '''
        
        '''
        if self._running is None:
            self._running = True
        elif self._running is False:
            log.error(
                'This %s was scheduled to stop. Not running %s.tune_in()',
                self.__class__.__name__, self.__class__.__name__
            )
            return
        elif self._running is True:
            log.error(
                'This %s is already running. Not running %s.tune_in()',
                self.__class__.__name__, self.__class__.__name__
            )
            return

        try:
            log.info(
                '%s is starting as user \'%s\'',
                self.__class__.__name__, salt.utils.user.get_user()
            )
        except Exception as err:
            # Only windows is allowed to fail here. See #3189. Log as debug in
            # that case. Else, error.
            log.log(
                salt.utils.platform.is_windows() and logging.DEBUG or logging.ERROR,
                'Failed to get the user who is starting %s',
                self.__class__.__name__,
                exc_info=err
            )
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
38462
def abort(self, msg=None):
        '''
        '''
        if not self.abort_run.is_set():
            if msg:
                logging.error('%s%s Aborting run...', msg, ('' if msg[-1] in punctuation else '.'))
            else:
                logging.error('Aborting run...')
        self.abort_run.set()
        self.stop_run.set()
955622
def process_presence_events(self, salt_data, token, opts):
        '''
        
        '''
        log.debug('In presence')
        changed = False

        # check if any connections were dropped
        if set(salt_data['data'].get('lost', [])):
            dropped_minions = set(salt_data['data'].get('lost', []))
        else:
            dropped_minions = set(self.minions) - set(salt_data['data'].get('present', []))

        for minion in dropped_minions:
            changed = True
            log.debug('Popping %s', minion)
            self.minions.pop(minion, None)

        # check if any new connections were made
        if set(salt_data['data'].get('new', [])):
            log.debug('got new minions')
            new_minions = set(salt_data['data'].get('new', []))
            changed = True
        elif set(salt_data['data'].get('present', [])) - set(self.minions):
            log.debug('detected new minions')
            new_minions = set(salt_data['data'].get('present', [])) - set(self.minions)
            changed = True
        else:
            new_minions = []

        tgt = ','.join(new_minions)
        for mid in new_minions:
            log.debug('Adding minion')
            self.minions[mid] = {}

        if tgt:
            changed = True
            client = salt.netapi.NetapiClient(opts)
            client.run(
                {
                    'fun': 'grains.items',
                    'tgt': tgt,
                    'expr_type': 'list',
                    'mode': 'client',
                    'client': 'local',
                    'asynchronous': 'local_async',
                    'token': token,
                })

        if changed:
            self.publish_minions()
1047873
def run(self):
        
        self.pre_run()
        first = True
        while self.runnable:
            self.pre_call_message()

            if first:
                self.pre_first_call_message()
            
            message, payload = self.listener.get()
            getattr(self, message)(payload)

            if first:
                first = False
                self.post_first_call_message()
                
            self.post_call_message()

        self.post_run()
1174569
def _run(self):
        """"""
        self.set_state(self.STATE_INITIALIZING)
        self.ioloop = ioloop.IOLoop.current()
        self.consumer_lock = locks.Lock()

        self.sentry_client = self.setup_sentry(
            self._kwargs['config'], self.consumer_name)

        try:
            self.setup()
        except (AttributeError, ImportError):
            return self.on_startup_error(
                'Failed to import the Python module for {}'.format(
                    self.consumer_name))

        if not self.is_stopped:
            try:
                self.ioloop.start()
            except KeyboardInterrupt:
                LOGGER.warning('CTRL-C while waiting for clean shutdown')
918081
def run(self):
        
        listener = EventServer(self.address, EventNotifyHandler)
        log.info("Event listener running on %s", listener.server_address)
        # Listen for events until told to stop
        while not self.stop_flag.is_set():
            listener.handle_request()
1075667
def run_key(self, key):
        '''
        
        '''
        def func(*args, **kwargs):
            '''
            Run a remote call
            '''
            args = list(args)
            for _key, _val in kwargs:
                args.append('{0}={1}'.format(_key, _val))
            return self.local.cmd(self.minion, key, args)
        return func
759091
def patch_keepalive_run():
    
    _run = luigi.worker.KeepAliveThread.run

    def run(self):
        # do not run the keep-alive loop when sandboxed
        if os.getenv("LAW_SANDBOX_SWITCHED") == "1":
            self.stop()
        else:
            _run(self)

    luigi.worker.KeepAliveThread.run = run
960706
private void ensurePullAndPushRunning() {
        log.trace("State should be PLAYING to running this task: {}", subscriberStream.getState());
        if (pullMode && pullAndPush == null && subscriberStream.getState() == StreamState.PLAYING) {
            // client buffer is at least 100ms
            pullAndPush = subscriberStream.scheduleWithFixedDelay(new PullAndPushRunnable(), 10);
        }
    }
1098397
def publish_minions(self):
        '''
        
        '''
        log.debug('in publish minions')
        minions = {}

        log.debug('starting loop')
        for minion, minion_info in six.iteritems(self.minions):
            log.debug(minion)
            # log.debug(minion_info)
            curr_minion = {}
            curr_minion.update(minion_info)
            curr_minion.update({'id': minion})
            minions[minion] = curr_minion
        log.debug('ended loop')
        ret = {'minions': minions}
        self.handler.write_message(
            salt.utils.json.dumps(ret) + str('\n\n'))
50040
def send_stop_signal(self, silent=False):
        
        if self.is_running():
            self._stop_signal = True
        elif not silent:
            raise RuntimeError('Loop is currently not running')
783326
def start(ctx, **kwargs):
    
    update_context(ctx, kwargs)

    daemon = mk_daemon(ctx)

    if ctx.debug or kwargs['no_fork']:
        daemon.run()
    else:
        daemon.start()
215674
def _spawn_minions(self, timeout=60):
        '''
        
        '''
        # Run masters discovery over SSDP. This may modify the whole configuration,
        # depending of the networking and sets of masters. If match is 'any' we let
        # eval_master handle the discovery instead so disconnections can also handle
        # discovery
        if isinstance(self.opts['discovery'], dict) and self.opts['discovery'].get('multimaster'):
            self._discover_masters()

        masters = self.opts['master']
        if (self.opts['master_type'] in ('failover', 'distributed')) or not isinstance(self.opts['master'], list):
            masters = [masters]

        for master in masters:
            s_opts = copy.deepcopy(self.opts)
            s_opts['master'] = master
            s_opts['multimaster'] = True
            minion = self._create_minion_object(s_opts,
                                                s_opts['auth_timeout'],
                                                False,
                                                io_loop=self.io_loop,
                                                loaded_base_name='salt.loader.{0}'.format(s_opts['master']),
                                                jid_queue=self.jid_queue)
            self.io_loop.spawn_callback(self._connect_minion, minion)
        self.io_loop.call_later(timeout, self._check_minions)
848343
def _run_runner(self):
        '''
        
        '''
        import salt.minion
        ret = {}
        low = {'fun': self.opts['fun']}
        try:
            # Allocate a jid
            async_pub = self._gen_async_pub()
            self.jid = async_pub['jid']

            fun_args = salt.utils.args.parse_input(
                    self.opts['arg'],
                    no_parse=self.opts.get('no_parse', []))

            verify_fun(self.functions, low['fun'])
            args, kwargs = salt.minion.load_args_and_kwargs(
                self.functions[low['fun']],
                fun_args)
            low['arg'] = args
            low['kwarg'] = kwargs

            if self.opts.get('eauth'):
                if 'token' in self.opts:
                    try:
                        with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_:
                            low['key'] = salt.utils.stringutils.to_unicode(fp_.readline())
                    except IOError:
                        low['token'] = self.opts['token']

                # If using eauth and a token hasn't already been loaded into
                # low, prompt the user to enter auth credentials
                if 'token' not in low and 'key' not in low and self.opts['eauth']:
                    # This is expensive. Don't do it unless we need to.
                    import salt.auth
                    resolver = salt.auth.Resolver(self.opts)
                    res = resolver.cli(self.opts['eauth'])
                    if self.opts['mktoken'] and res:
                        tok = resolver.token_cli(
                                self.opts['eauth'],
                                res
                                )
                        if tok:
                            low['token'] = tok.get('token', '')
                    if not res:
                        log.error('Authentication failed')
                        return ret
                    low.update(res)
                    low['eauth'] = self.opts['eauth']
            else:
                user = salt.utils.user.get_specific_user()

            if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']:
                low['kwarg']['orchestration_jid'] = async_pub['jid']

            # Run the runner!
            if self.opts.get('async', False):
                if self.opts.get('eauth'):
                    async_pub = self.cmd_async(low)
                else:
                    async_pub = self.asynchronous(self.opts['fun'],
                                                  low,
                                                  user=user,
                                                  pub=async_pub)

                # by default: info will be not enough to be printed out !
                log.warning(
                    'Running in asynchronous mode. Results of this execution may '
                    'be collected by attaching to the master event bus or '
                    'by examing the master job cache, if configured. '
                    'This execution is running under tag %s', async_pub['tag']
                )
                return async_pub['jid']  # return the jid

            # otherwise run it in the main process
            if self.opts.get('eauth'):
                ret = self.cmd_sync(low)
                if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}:
                    outputter = ret['outputter']
                    ret = ret['data']
                else:
                    outputter = None
                display_output(ret, outputter, self.opts)
            else:
                ret = self._proc_function(self.opts['fun'],
                                          low,
                                          user,
                                          async_pub['tag'],
                                          async_pub['jid'],
                                          daemonize=False)
        except salt.exceptions.SaltException as exc:
            evt = salt.utils.event.get_event('master', opts=self.opts)
            evt.fire_event({'success': False,
                            'return': '{0}'.format(exc),
                            'retcode': 254,
                            'fun': self.opts['fun'],
                            'fun_args': fun_args,
                            'jid': self.jid},
                           tag='salt/run/{0}/ret'.format(self.jid))
            # Attempt to grab documentation
            if 'fun' in low:
                ret = self.get_docs('{0}*'.format(low['fun']))
            else:
                ret = None

            # If we didn't get docs returned then
            # return the `not availble` message.
            if not ret:
                ret = '{0}'.format(exc)
            if not self.opts.get('quiet', False):
                display_output(ret, 'nested', self.opts)
        else:
            # If we don't have any values in ret by now, that's a problem.
            # Otherwise, we shouldn't be overwriting the retcode.
            if not ret:
                ret = {
                    'retcode': salt.defaults.exitcodes.EX_SOFTWARE,
                }
        log.debug('Runner return: %s', ret)

        return ret
1010613
public void setRunning(boolean running)
  {
    if (tc.isEntryEnabled())
    {
      SibTr.entry(tc, "setRunning");
      SibTr.exit(tc, "setRunning");
    }

    _isRunning = running;
    
    return;
  }
685247
public function daemonRunCommand(): void
    {
        $ret = ProcessUtil::daemonRun(function ($pid){
            $this->output->info("will running background by new process: $pid");
        });

        if ($ret === 0) {
            $this->output->liteError('current env is not support process create.');
        }
    }