Python oslo_config.cfg.ConfigOpts() Examples

The following are 30 code examples for showing how to use oslo_config.cfg.ConfigOpts(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module oslo_config.cfg , or try the search function .

Example 1
Project: gnocchi   Author: gnocchixyz   File: manage.py    License: Apache License 2.0 6 votes vote down vote up
def change_sack_size():
    conf = cfg.ConfigOpts()
    conf.register_cli_opts([_SACK_NUMBER_OPT])
    conf = service.prepare_service(conf=conf, log_to_std=True)
    s = incoming.get_driver(conf)
    try:
        report = s.measures_report(details=False)
    except incoming.SackDetectionError:
        LOG.error('Unable to detect the number of storage sacks.\n'
                  'Ensure gnocchi-upgrade has been executed.')
        return
    remainder = report['summary']['measures']
    if remainder:
        LOG.error('Cannot change sack when non-empty backlog. Process '
                  'remaining %s measures and try again', remainder)
        return
    LOG.info("Removing current %d sacks", s.NUM_SACKS)
    s.remove_sacks()
    LOG.info("Creating new %d sacks", conf.sacks_number)
    s.upgrade(conf.sacks_number) 
Example 2
Project: kuryr-kubernetes   Author: openstack   File: status.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    opt = cfg.SubCommandOpt(
        'category', title='command',
        description='kuryr-k8s-status command or category to execute',
        handler=add_parsers)

    conf = cfg.ConfigOpts()
    conf.register_cli_opt(opt)
    conf(sys.argv[1:])

    os_vif.initialize()
    objects.register_locally_defined_vifs()

    try:
        return conf.category.action_fn()
    except Exception:
        print('Error:\n%s' % traceback.format_exc())
        # This is 255 so it's not confused with the upgrade check exit codes.
        return 255 
Example 3
Project: castellan   Author: openstack   File: config.py    License: Apache License 2.0 6 votes vote down vote up
def setup_config(config_file=''):
    global TEST_CONF
    TEST_CONF = cfg.ConfigOpts()

    TEST_CONF.register_group(identity_group)
    TEST_CONF.register_opts(identity_options, group=identity_group)

    config_to_load = []
    local_config = './etc/castellan/castellan-functional.conf'
    main_config = '/etc/castellan/castellan-functional.conf'
    if os.path.isfile(config_file):
        config_to_load.append(config_file)
    elif os.path.isfile(local_config):
        config_to_load.append(local_config)
    elif os.path.isfile(main_config):
        config_to_load.append(main_config)

    TEST_CONF(
        (),  # Required to load an anonymous configuration
        default_config_files=config_to_load
    ) 
Example 4
Project: oslo.service   Author: openstack   File: eventlet_backdoor.py    License: Apache License 2.0 6 votes vote down vote up
def _main():
    import eventlet
    eventlet.monkey_patch(all=True)
    # Monkey patch the original current_thread to use the up-to-date _active
    # global variable. See https://bugs.launchpad.net/bugs/1863021 and
    # https://github.com/eventlet/eventlet/issues/592
    import __original_module_threading as orig_threading
    import threading  # noqa
    orig_threading.current_thread.__globals__['_active'] = threading._active

    from oslo_config import cfg

    logging.basicConfig(level=logging.DEBUG)

    conf = cfg.ConfigOpts()
    conf.register_cli_opts(_options.eventlet_backdoor_opts)
    conf(sys.argv[1:])

    where_running_thread = _initialize_if_enabled(conf)
    if not where_running_thread:
        raise RuntimeError(_("Did not create backdoor at requested location"))
    else:
        _where_running, thread = where_running_thread
        thread.wait() 
Example 5
Project: barbican   Author: openstack   File: vault_secret_store.py    License: Apache License 2.0 6 votes vote down vote up
def get_conf(self, conf=CONF):
        """Convert secret store conf into oslo conf

        Returns an oslo.config() object to pass to keymanager.API(conf)
        """
        vault_conf = cfg.ConfigOpts()
        options.set_defaults(
            vault_conf,
            backend='vault',
            vault_root_token_id=conf.vault_plugin.root_token_id,
            vault_approle_role_id=conf.vault_plugin.approle_role_id,
            vault_approle_secret_id=conf.vault_plugin.approle_secret_id,
            vault_kv_mountpoint=conf.vault_plugin.kv_mountpoint,
            vault_url=conf.vault_plugin.vault_url,
            vault_ssl_ca_crt_file=conf.vault_plugin.ssl_ca_crt_file,
            vault_use_ssl=conf.vault_plugin.use_ssl
        )
        return vault_conf 
Example 6
Project: senlin   Author: openstack   File: wsgi.py    License: Apache License 2.0 6 votes vote down vote up
def paste_deploy_app(paste_config_file, app_name, conf):
    """Load a WSGI app from a PasteDeploy configuration.

    Use deploy.loadapp() to load the app from the PasteDeploy configuration,
    ensuring that the supplied ConfigOpts object is passed to the app and
    filter constructors.

    :param paste_config_file: a PasteDeploy config file
    :param app_name: the name of the app/pipeline to load from the file
    :param conf: a ConfigOpts object to supply to the app and its filters
    :returns: the WSGI app
    """
    setup_paste_factories(conf)
    try:
        return deploy.loadapp("config:%s" % paste_config_file, name=app_name)
    finally:
        teardown_paste_factories() 
Example 7
Project: karbor   Author: openstack   File: eisoo.py    License: Apache License 2.0 6 votes vote down vote up
def create(context, conf):
    config_dir = utils.find_config(CONF.provider_config_dir)
    config_file = os.path.abspath(os.path.join(config_dir,
                                               'eisoo.conf'))
    config = cfg.ConfigOpts()
    config(args=['--config-file=' + config_file])
    config.register_opts(eisoo_client_opts,
                         group=SERVICE + '_client')

    LOG.info('Creating eisoo client with url %s.',
             config.eisoo_client.eisoo_endpoint)
    abclient = client.ABClient(config.eisoo_client.eisoo_endpoint,
                               config.eisoo_client.eisoo_app_id,
                               config.eisoo_client.eisoo_app_secret)

    return abclient 
Example 8
Project: karbor   Author: openstack   File: test_k8s_client.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(KubernetesClientTest, self).setUp()
        self._context = RequestContext(user_id='demo',
                                       project_id='abcd',
                                       auth_token='efgh',
                                       service_catalog=None)

        self.conf = cfg.ConfigOpts()
        k8s.register_opts(self.conf)
        self.host_url = 'https://192.168.98.35:6443'
        self.conf.set_default('k8s_host',
                              self.host_url,
                              'k8s_client')
        self.conf.set_override('k8s_ssl_ca_cert',
                               '/etc/provider.d/server-ca.crt',
                               'k8s_client')
        self.conf.set_override('k8s_cert_file',
                               '/etc/provider.d/client-admin.crt',
                               'k8s_client')
        self.conf.set_override('k8s_key_file',
                               '/etc/provider.d/client-admin.key',
                               'k8s_client') 
Example 9
Project: karbor   Author: openstack   File: test_swift_client.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(SwiftClientTest, self).setUp()
        service_catalog = [
            {
                'endpoints': [
                    {'publicURL': 'http://127.0.0.1:8080/v1/AUTH_abcd', }
                ],
                'type': 'object-store',
                'name': 'swift',
            },
        ]
        self._context = RequestContext(user_id='demo',
                                       project_id='abcd',
                                       auth_token='efgh',
                                       service_catalog=service_catalog)

        self.conf = cfg.ConfigOpts()
        swift.register_opts(self.conf) 
Example 10
Project: karbor   Author: openstack   File: test_cinder_protection_plugin.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(CinderProtectionPluginTest, self).setUp()
        plugin_config = cfg.ConfigOpts()
        plugin_config_fixture = self.useFixture(fixture.Config(plugin_config))
        plugin_config_fixture.load_raw_values(
            group='cinder_backup_protection_plugin',
            poll_interval=0,
        )
        self.plugin = CinderBackupProtectionPlugin(plugin_config)
        cfg.CONF.set_default('cinder_endpoint',
                             'http://127.0.0.1:8776/v2',
                             'cinder_client')

        self.cntxt = RequestContext(user_id='demo',
                                    project_id='abcd',
                                    auth_token='efgh')
        self.cinder_client = client_factory.ClientFactory.create_client(
            "cinder", self.cntxt) 
Example 11
Project: gnocchi   Author: gnocchixyz   File: http_proxy_to_wsgi.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, application, conf=None):
        """Base middleware constructor

        :param  conf: a cfg.ConfigOpts object
        """
        self.application = application
        self.oslo_conf = conf 
Example 12
Project: gnocchi   Author: gnocchixyz   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def prepare_conf():
    conf = cfg.ConfigOpts()

    opts.set_defaults()
    policy_opts.set_defaults(conf)
    return conf 
Example 13
Project: gnocchi   Author: gnocchixyz   File: metricd.py    License: Apache License 2.0 5 votes vote down vote up
def metricd():
    conf = cfg.ConfigOpts()
    conf.register_cli_opts([
        cfg.IntOpt("stop-after-processing-metrics",
                   default=0,
                   min=0,
                   help="Number of metrics to process without workers, "
                   "for testing purpose"),
    ])
    conf = service.prepare_service(conf=conf)

    if conf.stop_after_processing_metrics:
        metricd_tester(conf)
    else:
        MetricdServiceManager(conf).run() 
Example 14
Project: gnocchi   Author: gnocchixyz   File: manage.py    License: Apache License 2.0 5 votes vote down vote up
def upgrade():
    conf = cfg.ConfigOpts()
    sack_number_opt = copy.copy(_SACK_NUMBER_OPT)
    sack_number_opt.default = 128
    conf.register_cli_opts([
        cfg.BoolOpt("skip-index", default=False,
                    help="Skip index upgrade."),
        cfg.BoolOpt("skip-storage", default=False,
                    help="Skip storage upgrade."),
        cfg.BoolOpt("skip-incoming", default=False,
                    help="Skip incoming storage upgrade."),
        cfg.BoolOpt("skip-archive-policies-creation", default=False,
                    help="Skip default archive policies creation."),
        sack_number_opt,
    ])
    conf = service.prepare_service(conf=conf, log_to_std=True)
    if not conf.skip_index:
        index = indexer.get_driver(conf)
        LOG.info("Upgrading indexer %s", index)
        index.upgrade()
    if not conf.skip_storage:
        s = storage.get_driver(conf)
        LOG.info("Upgrading storage %s", s)
        s.upgrade()
    if not conf.skip_incoming:
        i = incoming.get_driver(conf)
        LOG.info("Upgrading incoming storage %s", i)
        i.upgrade(conf.sacks_number)

    if (not conf.skip_archive_policies_creation
            and not index.list_archive_policies()
            and not index.list_archive_policy_rules()):
        if conf.skip_index:
            index = indexer.get_driver(conf)
        for name, ap in six.iteritems(archive_policy.DEFAULT_ARCHIVE_POLICIES):
            index.create_archive_policy(ap)
        index.create_archive_policy_rule("default", "*", "low") 
Example 15
Project: gnocchi   Author: gnocchixyz   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def prepare_service(conf=None):
    if conf is None:
        conf = cfg.ConfigOpts()

    opts.set_defaults()
    policy_opts.set_defaults(conf)
    conf = service.prepare_service(conf=conf)
    cfg_path = conf.oslo_policy.policy_file
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)
    if cfg_path is None or not os.path.exists(cfg_path):
        cfg_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   '..', 'rest', 'policy.json'))
    conf.set_default('policy_file', cfg_path, group='oslo_policy')
    return conf 
Example 16
Project: gnocchi   Author: gnocchixyz   File: measures_injector.py    License: Apache License 2.0 5 votes vote down vote up
def injector():
    conf = cfg.ConfigOpts()
    conf.register_cli_opts([
        cfg.IntOpt("metrics", default=1, min=1),
        cfg.StrOpt("archive-policy-name", default="low"),
        cfg.StrOpt("creator", default="admin"),
        cfg.IntOpt("batch-of-measures", default=1000),
        cfg.IntOpt("measures-per-batch", default=10),
    ])
    conf = service.prepare_service(conf=conf)
    index = indexer.get_driver(conf)
    instore = incoming.get_driver(conf)

    def todo():
        metric = index.create_metric(
            uuid.uuid4(),
            creator=conf.creator,
            archive_policy_name=conf.archive_policy_name)

        for _ in six.moves.range(conf.batch_of_measures):
            measures = [
                incoming.Measure(
                    utils.dt_in_unix_ns(utils.utcnow()), random.random())
                for __ in six.moves.range(conf.measures_per_batch)]
            instore.add_measures(metric, measures)

    with futures.ThreadPoolExecutor(max_workers=conf.metrics) as executor:
        for m in six.moves.range(conf.metrics):
            executor.submit(todo) 
Example 17
Project: castellan   Author: openstack   File: _config_driver.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, group_name, config_file, mapping_file):
        conf = cfg.ConfigOpts()
        conf(args=[], default_config_files=[config_file])

        self._name = group_name
        self._mngr = key_manager.API(conf)
        self._mapping = {}

        cfg.ConfigParser(mapping_file, self._mapping).parse() 
Example 18
Project: castellan   Author: openstack   File: test_config_driver.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(CastellanSourceTestCase, self).setUp()
        self.driver = _config_driver.CastellanConfigurationSourceDriver()
        self.conf = cfg.ConfigOpts()
        self.conf_fixture = self.useFixture(fixture.Config(self.conf)) 
Example 19
Project: neutron-vpnaas   Author: openstack   File: test_scenario.py    License: Apache License 2.0 5 votes vote down vote up
def _get_config_opts(self):
        """Register default config options"""
        config = cfg.ConfigOpts()
        config.register_opts(common_config.core_opts)
        config.register_opts(common_config.core_cli_opts)
        config.register_opts(serviceprovider_opts, 'service_providers')
        config.register_opts(vpn_agent_opts, 'vpnagent')
        config.register_opts(ipsec.ipsec_opts, 'ipsec')
        config.register_opts(ipsec.openswan_opts, 'openswan')

        logging.register_options(config)
        agent_config.register_process_monitor_opts(config)
        ext_manager.register_opts(config)
        return config 
Example 20
Project: cotyledon   Author: sileht   File: examples.py    License: Apache License 2.0 5 votes vote down vote up
def oslo_app():
    conf = cfg.ConfigOpts()
    conf([], project='openstack-app', validate_default_values=True,
         version="0.1")

    p = cotyledon.ServiceManager()
    oslo_config_glue.setup(p, conf)
    p.add(OsloService)
    p.run() 
Example 21
Project: networking-odl   Author: openstack   File: set_ovs_hostconfigs.py    License: Apache License 2.0 5 votes vote down vote up
def setup_conf(args):
    """setup cmdline options."""
    conf = cfg.ConfigOpts()
    # NOTE, Logging options must be registered before parsing cli
    # options, refer:-
    # https://docs.openstack.org/oslo.log/latest/user/usage.html#oslo-logging-setup-methods
    logging.register_options(conf)

    if '-h' in args or '--help' in args:
        # Prints out script documentation."
        print(__doc__)

    conf.register_cli_opts(COMMAND_LINE_OPTIONS)
    conf(args=args)
    return conf 
Example 22
Project: networking-odl   Author: openstack   File: analyze_journal.py    License: Apache License 2.0 5 votes vote down vote up
def setup_conf(output, args):
    """setup cmdline options."""

    if any(flag in args for flag in ('-h', '--help')):
        six.print_(__doc__, file=output)

    conf = cfg.ConfigOpts()
    conf.register_cli_opts(COMMAND_LINE_OPTIONS)
    conf(args=args)
    return conf 
Example 23
Project: clapper   Author: rthallisey   File: tripleo-ansible-inventory.py    License: Apache License 2.0 5 votes vote down vote up
def _parse_config():
    default_config = os.environ.get('TRIPLEO_INVENTORY_CONFIG')
    if default_config:
        default_config = [default_config]

    configs = cfg.ConfigOpts()
    configs.register_cli_opts(opts)
    configs(prog='tripleo-ansible-inventory',
            default_config_files=default_config)
    if configs.auth_url is None:
        if "OS_AUTH_URL" in os.environ:
            configs.auth_url = os.environ.get('OS_AUTH_URL')
        else:
            print('ERROR: auth-url not defined and OS_AUTH_URL environment '
                  'variable missing, unable to proceed.', file=sys.stderr)
            sys.exit(1)
    if configs.username is None:
        if "OS_USERNAME" in os.environ:
            configs.username = os.environ.get('OS_USERNAME')
    if configs.password is None:
        if "OS_PASSWORD" in os.environ:
            configs.password = os.environ.get('OS_PASSWORD')
    if configs.project_name is None:
        if "OS_TENANT_NAME" in os.environ:
            configs.project_name = os.environ.get('OS_TENANT_NAME')
    if '/v2.0' in configs.auth_url:
        configs.auth_url = configs.auth_url.replace('/v2.0', '/v3')
    return configs 
Example 24
Project: oslo.log   Author: openstack   File: test_formatters.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(FormatUnhashableExceptionTest, self).setUp()
        self.config_fixture = self.useFixture(
            config_fixture.Config(cfg.ConfigOpts()))
        self.conf = self.config_fixture.conf
        log.register_options(self.conf) 
Example 25
Project: oslo.log   Author: openstack   File: test_log.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(CommonLoggerTestsMixIn, self).setUp()
        # common context has different fields to the defaults in log.py
        self.config_fixture = self.useFixture(
            fixture_config.Config(cfg.ConfigOpts()))
        self.config = self.config_fixture.config
        self.CONF = self.config_fixture.conf
        log.register_options(self.config_fixture.conf)
        self.config(logging_context_format_string='%(asctime)s %(levelname)s '
                                                  '%(name)s [%(request_id)s '
                                                  '%(user)s %(tenant)s] '
                                                  '%(message)s')
        self.log = None
        log._setup_logging_from_conf(self.config_fixture.conf, 'test', 'test')
        self.log_handlers = log.getLogger(None).logger.handlers 
Example 26
Project: oslo.log   Author: openstack   File: test_log.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(BaseTestCase, self).setUp()
        self.context_fixture = self.useFixture(
            fixture_context.ClearRequestContext())
        self.config_fixture = self.useFixture(
            fixture_config.Config(cfg.ConfigOpts()))
        self.config = self.config_fixture.config
        self.CONF = self.config_fixture.conf
        log.register_options(self.CONF)
        log.setup(self.CONF, 'base') 
Example 27
Project: oslo.log   Author: openstack   File: test_log.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, args=None):
            return cfg.ConfigOpts.__call__(self,
                                           args=args,
                                           prog='test',
                                           version='1.0',
                                           usage='%(prog)s FOO BAR',
                                           default_config_files=[]) 
Example 28
Project: oslo.log   Author: openstack   File: test_log.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(IsDebugEnabledTestCase, self).setUp()
        self.config_fixture = self.useFixture(
            fixture_config.Config(cfg.ConfigOpts()))
        self.config = self.config_fixture.config
        self.CONF = self.config_fixture.conf
        log.register_options(self.config_fixture.conf) 
Example 29
Project: openstacksdk   Author: openstack   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def _load_ks_cfg_opts(self):
        conf = cfg.ConfigOpts()
        for group, opts in self.oslo_config_dict.items():
            conf.register_group(cfg.OptGroup(group))
            if opts is not None:
                ks_loading.register_adapter_conf_options(conf, group)
                for name, val in opts.items():
                    conf.set_override(name, val, group=group)
        return conf

    # TODO(shade) Update this to handle service type aliases 
Example 30
Project: masakari   Author: openstack   File: test_conf.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, args=None, default_config_files=None):
            if default_config_files is None:
                default_config_files = []
            return cfg.ConfigOpts.__call__(
                self,
                args=args,
                prog='test',
                version='1.0',
                usage='%(prog)s FOO BAR',
                default_config_files=default_config_files,
                validate_default_values=True)