Manage the list of Alignak launched daemons

         Check if the daemon process is running

        :return: True if all daemons are running, else False
768589
def daemons_check(self):
        
        # First look if it's not too early to ping
        start = time.time()
        if self.daemons_last_check \
                and self.daemons_last_check + self.conf.daemons_check_period > start:
            logger.debug("Too early to check daemons, check period is %.2f seconds",
                         self.conf.daemons_check_period)
            return True

        logger.debug("Alignak launched daemons check")
        result = True

        procs = [psutil.Process()]
        for daemon in list(self.my_daemons.values()):
            # Get only the daemon (not useful for its children processes...)
            # procs = daemon['process'].children()
            procs.append(daemon['process'])
            for proc in procs:
                try:
                    logger.debug("Process %s is %s", proc.name(), proc.status())
                    # logger.debug("Process listening:", proc.name(), proc.status())
                    # for connection in proc.connections():
                    #     l_addr, l_port = connection.laddr if connection.laddr else ('', 0)
                    #     r_addr, r_port = connection.raddr if connection.raddr else ('', 0)
                    #     logger.debug("- %s:%s <-> %s:%s, %s", l_addr, l_port, r_addr, r_port,
                    #                  connection.status)
                    # Reset the daemon connection if it got broked...
                    if not daemon['satellite'].con:
                        if self.daemon_connection_init(daemon['satellite']):
                            # Set my satellite as alive :)
                            daemon['satellite'].set_alive()
                except psutil.NoSuchProcess:
                    pass
                except psutil.AccessDenied:
                    # Probably stopping...
                    if not self.will_stop and proc == daemon['process']:
                        logger.warning("Daemon %s/%s is not running!",
                                       daemon['satellite'].type, daemon['satellite'].name)
                        logger.debug("Access denied - Process %s is %s", proc.name(), proc.status())
                        if not self.start_daemon(daemon['satellite']):
                            # Set my satellite as dead :(
                            daemon['satellite'].set_dead()
                            result = False
                        else:
                            logger.info("I restarted %s/%s",
                                        daemon['satellite'].type, daemon['satellite'].name)
                            logger.info("Pausing %.2f seconds...", 0.5)
                            time.sleep(0.5)
                    else:
                        logger.info("Child process %s is %s", proc.name(), proc.status())

        # Set the last check as now
        self.daemons_last_check = start

        logger.debug("Checking daemons duration: %.2f seconds", time.time() - start)

        return result
325820
def main():
    
    try:
        args = parse_daemon_args(True)

        # Protect for windows multiprocessing that will RELAUNCH all
        while True:
            daemon = Arbiter(**args.__dict__)
            daemon.main()
            if not daemon.need_config_reload:
                break
            daemon = None
    except Exception as exp:  # pylint: disable=broad-except
        sys.stderr.write("*** Daemon exited because: %s" % str(exp))
        traceback.print_exc()
        exit(1)
681713
def os_is_running(pid):
    '''
    
    '''
    if isinstance(pid, six.string_types):
        pid = int(pid)
    if HAS_PSUTIL:
        return psutil.pid_exists(pid)
    else:
        try:
            os.kill(pid, 0)  # SIG 0 is the "are you alive?" signal
            return True
        except OSError:
            return False
731095
def checkdebug(self):
        
        # Global debugging
        opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
                             *self.files)
        for opt1 in opt:
            for opt2 in opt1.split(" "):
                if opt2 in ("--debug", "debug"):
                    return True
        return False
325081
def watch_processes(self):
        

        for process in list(self.processes):
            self.watch_process(process)

        # Cleanup processes
        self.processes = [p for p in self.processes if not p.get("dead")]

        if self.stopping and len(self.processes) == 0:
            self.stop_watch()
223461
def get_daemon_stats(self, details=False):
        
        # Call the base Daemon one
        res = super(Alignak, self).get_daemon_stats(details=details)

        res.update({'name': self.name, 'type': self.type, 'monitored_objects': {}})

        counters = res['counters']

        # Satellites counters
        counters['brokers'] = len(self.brokers)
        counters['pollers'] = len(self.pollers)
        counters['reactionners'] = len(self.reactionners)
        counters['receivers'] = len(self.receivers)

        if not self.sched:
            return res

        # # Hosts/services problems counters
        # m_solver = MacroResolver()
        # counters['hosts_problems'] = m_solver._get_total_host_problems()
        # counters['hosts_unhandled_problems'] = m_solver._get_total_host_problems_unhandled()
        # counters['services_problems'] = m_solver._get_total_service_problems()
        # counters['services_unhandled_problems'] = m_solver._get_total_service_problems_unhandled()

        # Get statistics from the scheduler
        scheduler_stats = self.sched.get_scheduler_stats(details=details)
        res['counters'].update(scheduler_stats['counters'])
        scheduler_stats.pop('counters')
        res.update(scheduler_stats)

        return res
1286188
def is_processing(self, taskid):
        '''
        
        '''
        return taskid in self.processing and self.processing[taskid].taskid
1070162
def _is_pid_running_on_unix(pid):
    
    try:
        os.kill(pid, 0)
    except OSError as err:
        # if error is ESRCH, it means the process doesn't exist
        return not err.errno == os.errno.ESRCH
    return True
441689
def target_is_busy(self, target_id=0):
        
        try:
            target = self._target(target_id=target_id)
        except:
            raise NoSuchTargetException()
        return target['state'] == "running"
511565
def _on_process_started(self):
        
        comm('backend process started')
        if self is None:
            return
        self.starting = False
        self.running = True
882958
def run(self, daemon=False):
        
        from aiida.engine import launch

        # If daemon is True, submit the process and return
        if daemon:
            node = launch.submit(self.process, **self.inputs)
            echo.echo_info('Submitted {}<{}>'.format(self.process_name, node.pk))
            return

        # Otherwise we run locally and wait for the process to finish
        echo.echo_info('Running {}'.format(self.process_name))
        try:
            _, node = launch.run_get_node(self.process, **self.inputs)
        except Exception as exception:  # pylint: disable=broad-except
            echo.echo_critical('an exception occurred during execution: {}'.format(str(exception)))

        if node.is_killed:
            echo.echo_critical('{}<{}> was killed'.format(self.process_name, node.pk))
        elif not node.is_finished_ok:
            arguments = [self.process_name, node.pk, node.exit_status, node.exit_message]
            echo.echo_warning('{}<{}> failed with exit status {}: {}'.format(*arguments))
        else:
            output = []
            echo.echo_success('{}<{}> finished successfully\n'.format(self.process_name, node.pk))
            for triple in sorted(node.get_outgoing().all(), key=lambda triple: triple.link_label):
                output.append([triple.link_label, '{}<{}>'.format(triple.node.__class__.__name__, triple.node.pk)])
            echo.echo(tabulate.tabulate(output, headers=['Output label', 'Node']))
886384
def run_sync(self) -> int:
        '''
        '''
        exit_status = asyncio.get_event_loop().run_until_complete(self.run())

        # The following loop close procedure should avoid deadlock while
        # allowing all callbacks to process before close()
        asyncio.get_event_loop().stop()
        asyncio.get_event_loop().run_forever()
        asyncio.get_event_loop().close()
        return exit_status
1037736
def _is_running(self, tries=10):
        
        # We can't possibly be running if our base_pathname isn't defined.
        if not self.base_pathname:
            return False

        if tries < 1:
            raise ValueError('tries must be > 0')

        cmd = [
            PostgresFinder.find_root() / 'pg_ctl',
            'status',
            '-D',
            self.base_pathname,
        ]
        votes = 0
        while abs(votes) < tries:
            time.sleep(0.1)
            running = (subprocess.call(cmd, stdout=DEV_NULL) == 0)
            if running and votes >= 0:
                votes += 1
            elif not running and votes <= 0:
                votes -= 1
            else:
                votes = 0

        return votes > 0
1052987
def is_correct(self):  # pylint: disable=too-many-branches, too-many-statements, too-many-locals
        
        logger.info('Running pre-flight check on configuration data, initial state: %s',
                    self.conf_is_correct)
        valid = self.conf_is_correct

        # Check if alignak_name is defined
        if not self.alignak_name:
            logger.info('Alignak name is not defined, using the main arbiter name...')
            for arbiter in self.arbiters:
                if not arbiter.spare:
                    self.alignak_name = arbiter.name
                    break
        logger.info('Alignak name is: %s', self.alignak_name)

        # Globally unmanaged parameters
        if not self.read_config_silent:
            logger.info('Checking global parameters...')

        # Old Nagios legacy unmanaged parameters
        self.check_error_on_hard_unmanaged_parameters()

        # If we got global event handlers, they should be valid
        if self.global_host_event_handler and not self.global_host_event_handler.is_valid():
            msg = "[%s::%s] global host event_handler '%s' is invalid" \
                  % (self.my_type, self.get_name(), self.global_host_event_handler.command)
            self.add_error(msg)
            valid = False

        if self.global_service_event_handler and not self.global_service_event_handler .is_valid():
            msg = "[%s::%s] global service event_handler '%s' is invalid" \
                  % (self.my_type, self.get_name(), self.global_service_event_handler .command)
            self.add_error(msg)
            valid = False

        if not self.read_config_silent:
            logger.info('Checked')

        if not self.read_config_silent:
            logger.info('Checking monitoring configuration...')

        classes = [strclss for _, _, strclss, _, _ in list(self.types_creations.values())]
        for strclss in sorted(classes):
            if strclss in ['hostescalations', 'serviceescalations']:
                logger.debug("Ignoring correctness check for '%s'...", strclss)
                continue

            if not self.read_config_silent:
                logger.info('- checking %s...', strclss)

            try:
                checked_list = getattr(self, strclss)
            except AttributeError:  # pragma: no cover, simple protection
                logger.info("\t%s are not present in the configuration", strclss)
                continue

            if not checked_list.is_correct():
                if not self.read_config_silent:
                    logger.info('Checked %s, configuration is incorrect!', strclss)

                valid = False
                self.configuration_errors += checked_list.configuration_errors
                self.add_error("%s configuration is incorrect!" % strclss)
                logger.error("%s configuration is incorrect!", strclss)
            if checked_list.configuration_warnings:
                self.configuration_warnings += checked_list.configuration_warnings
                logger.info("    %d warning(s), total: %d",
                            len(checked_list.configuration_warnings),
                            len(self.configuration_warnings))

            if not self.read_config_silent:
                try:
                    dump_list = sorted(checked_list, key=lambda k: k.get_name())
                except AttributeError:  # pragma: no cover, simple protection
                    dump_list = checked_list

                # Dump at DEBUG level because some tests break with INFO level, and it is not
                # really necessary to have information about each object ;
                for cur_obj in dump_list:
                    if strclss == 'services':
                        logger.debug('  %s', cur_obj.get_full_name())
                    else:
                        logger.debug('  %s', cur_obj.get_name())
                if checked_list:
                    logger.info('  checked %d', len(checked_list))
                else:
                    logger.info('  none')

        if not self.read_config_silent:
            logger.info('Checked')

        # Parse hosts and services for tags and realms
        hosts_tag = set()
        services_tag = set()
        for host in self.hosts:
            hosts_tag.add(host.poller_tag)
        for service in self.services:
            services_tag.add(service.poller_tag)

        # Check that for each poller_tag of a host, a poller exists with this tag
        pollers_tag = set()
        for poller in self.pollers:
            for tag in poller.poller_tags:
                pollers_tag.add(tag)

        if not hosts_tag.issubset(pollers_tag):
            for tag in hosts_tag.difference(pollers_tag):
                self.add_error("Error: some hosts have the poller_tag %s but no poller "
                               "has this tag" % tag)
                valid = False
        if not services_tag.issubset(pollers_tag):
            for tag in services_tag.difference(pollers_tag):
                self.add_error("some services have the poller_tag %s but no poller "
                               "has this tag" % tag)
                valid = False

        # Check that all hosts involved in business_rules are from the same realm
        for item in self.hosts:
            if not item.got_business_rule:
                continue

            realm = self.realms[item.realm]
            if not realm:
                # Something was wrong in the conf, will be raised elsewhere
                continue

            for elt_uuid in item.business_rule.list_all_elements():
                if elt_uuid not in self.hosts:
                    # An error or a service element
                    continue

                host = self.hosts[elt_uuid]
                if host.realm not in self.realms:
                    # Something was wrong in the conf, will be raised elsewhere
                    continue

                host_realm = self.realms[host.realm]
                if host_realm.get_name() != realm.get_name():
                    logger.error("Business_rule '%s' got some hosts from another realm: %s",
                                 item.get_full_name(), host_realm.get_name())
                    self.add_error("Error: Business_rule '%s' got hosts from another "
                                   "realm: %s" % (item.get_full_name(), host_realm.get_name()))
                    valid = False

        # for lst in [self.services, self.hosts]:
        #     for item in lst:
        #         if item.got_business_rule:
        #             e_ro = self.realms[item.realm]
        #             # Something was wrong in the conf, will be raised elsewhere
        #             if not e_ro:
        #                 continue
        #             e_r = e_ro.realm_name
        #             for elt_uuid in item.business_rule.list_all_elements():
        #                 if elt_uuid in self.hosts:
        #                     elt = self.hosts[elt_uuid]
        #                 else:
        #                     elt = self.services[elt_uuid]
        #                 r_o = self.realms[elt.realm]
        #                 # Something was wrong in the conf, will be raised elsewhere
        #                 if not r_o:
        #                     continue
        #                 elt_r = r_o.realm_name
        #                 if elt_r != e_r:
        #                     logger.error("Business_rule '%s' got hosts from another realm: %s",
        #                                  item.get_full_name(), elt_r)
        #                     self.add_error("Error: Business_rule '%s' got hosts from another "
        #                                    "realm: %s" % (item.get_full_name(), elt_r))
        #                     valid = False

        if self.configuration_errors:
            valid = False
            logger.error("Configuration errors:")
            for msg in self.configuration_errors:
                logger.error(msg)

        # If configuration error messages exist, then the configuration is not valid
        self.conf_is_correct = valid
169104
public function isRunning()
    {
        $this->checkDirExists();

        $pidFile = $this->directory.$this->filename;
        if (!file_exists($pidFile)) {
            return false;
        }

        $pid = file_get_contents($pidFile);
        // Empty pid file means the process is not running
        if (empty($pid)) {
            return false;
        }

        if (!is_dir('/proc/'))
        {
            /* OSX Workaround, not as good as using proc dir on linux, but oh well */
            exec('ps -Ac -o pid | awk \'{print $1}\' | grep \'^'.$pid.'$\'', $output, $return);

            if ($return == 0) {
                // process with the same id is still running
                return true;
            }
        }

        /* we assume the system is a linux system here */
        if (!is_dir('/proc/'.$pid)) {
            // process with the same id is still running
            return false;
        }

        return true;
    }
791477
def do_before_loop(self):
        
        logger.info("I am the arbiter: %s", self.link_to_myself.name)

        # If I am a spare, I do not have anything to do here...
        if not self.is_master:
            logger.debug("Waiting for my master death...")
            return

        # Arbiter check if some daemons need to be started
        if not self.daemons_start(run_daemons=True):
            self.request_stop(message="Some Alignak daemons did not started correctly.",
                              exit_code=4)

        if not self.daemons_check():
            self.request_stop(message="Some Alignak daemons cannot be checked.",
                              exit_code=4)

        # Make a pause to let our started daemons get ready...
        pause = max(1, max(self.conf.daemons_start_timeout, len(self.my_daemons) * 0.5))
        if pause:
            logger.info("Pausing %.2f seconds...", pause)
            time.sleep(pause)

        # Prepare and dispatch the monitored configuration
        self.configuration_dispatch()

        # Now we can get all initial broks for our satellites
        _t0 = time.time()
        self.get_initial_broks_from_satellites()
        statsmgr.timer('broks.get-initial', time.time() - _t0)

        # Now create the external commands manager
        # We are a dispatcher: our role is to dispatch commands to the schedulers
        self.external_commands_manager = ExternalCommandManager(
            self.conf, 'dispatcher', self, self.conf.accept_passive_unknown_check_results,
            self.conf.log_external_commands)
421175
def main():
    
    try:
        args = parse_daemon_args()
        daemon = Alignak(**args.__dict__)
        daemon.main()
    except Exception as exp:  # pylint: disable=broad-except
        sys.stderr.write("*** Daemon exited because: %s" % str(exp))
        traceback.print_exc()
        exit(1)