Monitored configuration preparation and dispatch

        :return: None
359303
def configuration_dispatch(self, not_configured=None):
        
        if not not_configured:
            self.dispatcher = Dispatcher(self.conf, self.link_to_myself)
            # I set my own dispatched configuration as the provided one...
            # because I will not push a configuration to myself :)
            self.cur_conf = self.conf

            # Loop for the first configuration dispatching, if the first dispatch fails, bail out!
            # Without a correct configuration, Alignak daemons will not run correctly
            first_connection_try_count = 0
            logger.info("Connecting to my satellites...")
            while True:
                first_connection_try_count += 1

                # Initialize connection with all our satellites
                self.all_connected = True
                for satellite in self.dispatcher.all_daemons_links:
                    if satellite == self.link_to_myself:
                        continue
                    if not satellite.active:
                        continue
                    connected = self.daemon_connection_init(satellite, set_wait_new_conf=True)
                    logger.debug("  %s is %s", satellite, connected)
                    self.all_connected = self.all_connected and connected

                if self.all_connected:
                    logger.info("- satellites connection #%s is ok", first_connection_try_count)
                    break
                else:
                    logger.warning("- satellites connection #%s is not correct; "
                                   "let's give another chance after %d seconds...",
                                   first_connection_try_count,
                                   self.link_to_myself.polling_interval)
                    if first_connection_try_count >= 3:
                        self.request_stop("All the daemons connections could not be established "
                                          "despite %d tries! "
                                          "Sorry, I bail out!" % first_connection_try_count,
                                          exit_code=4)
                    time.sleep(self.link_to_myself.polling_interval)

            # Now I have a connection with all the daemons I need to contact them,
            # check they are alive and ready to run
            _t0 = time.time()
            self.all_connected = self.dispatcher.check_reachable()
            statsmgr.timer('dispatcher.check-alive', time.time() - _t0)

            _t0 = time.time()
            # Preparing the configuration for dispatching
            logger.info("Preparing the configuration for dispatching...")
            self.dispatcher.prepare_dispatch()
            statsmgr.timer('dispatcher.prepare-dispatch', time.time() - _t0)
            logger.info("- configuration is ready to dispatch")

        # Loop for the first configuration dispatching, if the first dispatch fails, bail out!
        # Without a correct configuration, Alignak daemons will not run correctly
        first_dispatch_try_count = 0
        logger.info("Dispatching the configuration to my satellites...")
        while True:
            first_dispatch_try_count += 1

            # Check reachable - if a configuration is prepared, this will force the
            # daemons communication, and the dispatching will be launched
            _t0 = time.time()
            logger.info("- configuration dispatching #%s...", first_dispatch_try_count)
            self.dispatcher.check_reachable(forced=True)
            statsmgr.timer('dispatcher.dispatch', time.time() - _t0)

            # Make a pause to let our satellites get ready...
            pause = max(1, max(self.conf.daemons_dispatch_timeout, len(self.my_daemons) * 0.5))
            # pause = len(self.my_daemons) * 0.2
            logger.info("- pausing %d seconds...", pause)
            time.sleep(pause)

            _t0 = time.time()
            logger.info("- checking configuration dispatch...")
            # Checking the dispatch is accepted
            self.dispatcher.check_dispatch()
            statsmgr.timer('dispatcher.check-dispatch', time.time() - _t0)
            if self.dispatcher.dispatch_ok:
                logger.info("- configuration dispatching #%s is ok", first_dispatch_try_count)
                break
            else:
                logger.warning("- configuration dispatching #%s is not correct; "
                               "let's give another chance...", first_dispatch_try_count)
                if first_dispatch_try_count >= 3:
                    self.request_stop("The configuration could not be dispatched despite %d tries! "
                                      "Sorry, I bail out!" % first_connection_try_count,
                                      exit_code=4)
278720
def get_config_from_options(**options):
    """"""
    data = []
    #  Set whether or not to daemonize.
    #  Unlike supervisord, our default is to stay in the foreground.
    data.append("[supervisord]\n")
    if options.get("daemonize",False):
        data.append("nodaemon=false\n")
    else:
        data.append("nodaemon=true\n")
    if options.get("pidfile",None):
        data.append("pidfile=%s\n" % (options["pidfile"],))
    if options.get("logfile",None):
        data.append("logfile=%s\n" % (options["logfile"],))
    #  Set which programs to launch automatically on startup.
    for progname in options.get("launch",None) or []:
        data.append("[program:%s]\nautostart=true\n" % (progname,))
    for progname in options.get("nolaunch",None) or []:
        data.append("[program:%s]\nautostart=false\n" % (progname,))
    #  Set which programs to include/exclude from the config
    for progname in options.get("include",None) or []:
        data.append("[program:%s]\nexclude=false\n" % (progname,))
    for progname in options.get("exclude",None) or []:
        data.append("[program:%s]\nexclude=true\n" % (progname,))
    #  Set which programs to autoreload when code changes.
    #  When this option is specified, the default for all other
    #  programs becomes autoreload=false.
    if options.get("autoreload",None):
        data.append("[program:autoreload]\nexclude=false\nautostart=true\n")
        data.append("[program:__defaults__]\nautoreload=false\n")
        for progname in options["autoreload"]:
            data.append("[program:%s]\nautoreload=true\n" % (progname,))
    #  Set whether to use the autoreloader at all.
    if options.get("noreload",False):
        data.append("[program:autoreload]\nexclude=true\n")
    return "".join(data)
587587
def autoconf(self):
        
        opcinfo = OPCinfo(self._host, self._port, self._user, self._password, 
                          self._monpath, self._ssl)
        return opcinfo is not None
979690
protected function prepareSystemEnv()
    {
        proc_nice(Daemon::$config->workerpriority->value);

        register_shutdown_function(function () {
            $this->shutdown(true);
        });

        $this->setTitle(
            Daemon::$runName . ': worker process'
            . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value
                ? ' (' . Daemon::$config->pidfile->value . ')' : '')
        );


        if (isset(Daemon::$config->group->value)) {
            $sg = posix_getgrnam(Daemon::$config->group->value);
        }

        if (isset(Daemon::$config->user->value)) {
            $su = posix_getpwnam(Daemon::$config->user->value);
        }

        $flushCache = false;
        if (Daemon::$config->chroot->value !== '/') {
            if (posix_getuid() != 0) {
                Daemon::log('You must have the root privileges to change root.');
                exit(0);
            } elseif (!chroot(Daemon::$config->chroot->value)) {
                Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.');
                exit(0);
            }
            $flushCache = true;
        }

        if (isset(Daemon::$config->group->value)) {
            if ($sg === false) {
                Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.');
                exit(0);
            } elseif (($sg['gid'] != posix_getgid()) && (!posix_setgid($sg['gid']))) {
                Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
                exit(0);
            }
            $flushCache = true;
        }

        if (isset(Daemon::$config->user->value)) {
            if ($su === false) {
                Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.');
                exit(0);
            } elseif ($su['uid'] != posix_getuid() & !posix_setuid($su['uid'])) {
                Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
                exit(0);
            }
            $flushCache = true;
        }
        if ($flushCache) {
            clearstatcache(true);
        }
        if (Daemon::$config->cwd->value !== '.') {
            if (!@chdir(Daemon::$config->cwd->value)) {
                Daemon::log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.');
            }
            clearstatcache(true);
        }
    }
172470
def _configuration(self, *args, **kwargs):
        '''
        
        '''

        data = dict()
        self.db.open()
        for pkg in self.db.get(Package):
            configs = list()
            for pkg_cfg in self.db.get(PackageCfgFile, eq={'pkgid': pkg.id}):
                configs.append(pkg_cfg.path)
            data[pkg.name] = configs

        if not data:
            raise InspectorQueryException("No inspected configuration yet available.")

        return data
174394
def manage(options)
      init_log if options[:verbose]
      AgentConfig.cfg_dir = options[:cfg_dir]
      options[:timeout] ||= DEFAULT_TIMEOUT
      request_stats(options)
    rescue Exception => e
      fail("#{e}\n#{e.backtrace.join("\n")}") unless e.is_a?(SystemExit)
    end
414809
def main(_):
  """"""
  utility.set_up_logging()
  if not FLAGS.config:
    raise KeyError('You must specify a configuration.')
  logdir = FLAGS.logdir and os.path.expanduser(os.path.join(
      FLAGS.logdir, '{}-{}'.format(FLAGS.timestamp, FLAGS.config)))
  try:
    config = utility.load_config(logdir)
  except IOError:
    config = tools.AttrDict(getattr(configs, FLAGS.config)())
    config = utility.save_config(config, logdir)
  for score in train(config, FLAGS.env_processes):
    tf.logging.info('Score {}.'.format(score))
422442
def main(self) -> None:
        """"""
        path = ask_path("where should the config be stored?", ".snekrc")

        conf = configobj.ConfigObj()

        tools = self.get_tools()
        for tool in tools:
            conf[tool] = getattr(self, tool)()  # pylint: disable=assignment-from-no-return
        conf.filename = path
        conf.write()

        print("Written config file!")

        if "pylint" in tools:
            print(
                "Please also run `pylint --generate-rcfile` to complete setup")
23411
def monitor(msg, *args, **kwargs):
    
    if len(logging.root.handlers) == 0:
        logging.basicConfig()
    logging.root.monitor(msg, *args, **kwargs)
1004228
def update_conf(self):
        
        parsed = self.parse_conf()

        if not parsed:
            return None

        # Update app config
        self.app.config.update(parsed)
914463
def configure(self, options, conf):
        
        super(LeakDetectorPlugin, self).configure(options, conf)
        if options.leak_detector_level:
            self.reporting_level = int(options.leak_detector_level)
        self.report_delta = options.leak_detector_report_delta
        self.patch_mock = options.leak_detector_patch_mock
        self.ignore_patterns = options.leak_detector_ignore_patterns
        self.save_traceback = options.leak_detector_save_traceback
        self.multiprocessing_enabled = bool(getattr(options, 'multiprocess_workers', False))
178356
def with_updated_configuration(self, options=None,
                                   attribute_options=None):
        
        return self._mapping.with_updated_configuration(options=options,
                                                        attribute_options=
                                                            attribute_options)
1032229
def configure(self):
        """"""
        if self.debug is not None and not self.debug:
            self._remove_debug_handlers()
        self._remove_debug_only()
        logging.config.dictConfig(self.config)
        try:
            logging.captureWarnings(True)
        except AttributeError:
            pass
154127
def _prep_mod_opts(self):
        '''
        
        '''
        mod_opts = {}
        for key, val in six.iteritems(self.opts):
            if key == 'logger':
                continue
            mod_opts[key] = val
        return mod_opts
450722
def setup_handlers():
    '''
    
    '''
    __grains__ = salt.loader.grains(__opts__)
    __salt__ = salt.loader.minion_mods(__opts__)
    if 'sentry_handler' not in __opts__:
        log.debug('No \'sentry_handler\' key was found in the configuration')
        return False
    options = {}
    dsn = get_config_value('dsn')
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse
            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
        except ValueError as exc:
            log.info(
                'Raven failed to parse the configuration provided DSN: %s', exc
            )

    if not dsn:
        for key in ('project', 'servers', 'public_key', 'secret_key'):
            config_value = get_config_value(key)
            if config_value is None and key not in options:
                log.debug(
                    'The required \'sentry_handler\' configuration key, '
                    '\'%s\', is not properly configured. Not configuring '
                    'the sentry logging handler.', key
                )
                return
            elif config_value is None:
                continue
            options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        'site': get_config_value('site'),

        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        'name': get_config_value('name'),

        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        'exclude_paths': get_config_value('exclude_paths', ()),

        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        'include_paths': get_config_value('include_paths', ()),

        # list_max_length: The maximum number of items a list-like container
        # should store.
        'list_max_length': get_config_value('list_max_length'),

        # string_max_length: The maximum characters of a string that should be
        # stored.
        'string_max_length': get_config_value('string_max_length'),

        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        'auto_log_stacks': get_config_value('auto_log_stacks'),

        # timeout: If supported, the timeout value for sending messages to
        # remote.
        'timeout': get_config_value('timeout', 1),

        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        'processors': get_config_value('processors'),

        # dsn: Ensure the DSN is passed into the client
        'dsn': dsn
    })

    client = raven.Client(**options)
    context = get_config_value('context')
    context_dict = {}
    if context is not None:
        for tag in context:
            try:
                tag_value = __grains__[tag]
            except KeyError:
                log.debug('Sentry tag \'%s\' not found in grains.', tag)
                continue
            if tag_value:
                context_dict[tag] = tag_value
        if context_dict:
            client.context.merge({'tags': context_dict})
    try:
        handler = SentryHandler(client)

        exclude_patterns = get_config_value('exclude_patterns', None)
        if exclude_patterns:
            filter_regexes = [re.compile(pattern) for pattern in exclude_patterns]

            class FilterExcludedMessages(object):
                @staticmethod
                def filter(record):
                    m = record.getMessage()
                    return not any(regex.search(m) for regex in filter_regexes)

            handler.addFilter(FilterExcludedMessages())

        handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
        return handler
    except ValueError as exc:
        log.debug('Failed to setup the sentry logging handler', exc_info=True)
738306
def _getConfiguration(self):
        
        configDirectoryPath = os.path.join("application", "config")
        config = Config(configDirectoryPath)
        configData = config.getData()

        # setting application parameters
        reactor.suggestThreadPoolSize(
            int(configData["performance"]["threadPoolSize"])
        )

        return configData
620088
def initialise(self, args=None, env=None, file=None, cwd=None):
        
        self.spec_file = args and args.specs or None
        self.cwd = cwd or os.getcwd()
        self.file = file
        return self.spec_file is not None