示例#1
0
    def setUp(self):
        super(CassandraStorageFlavorsTests, self).setUp()

        self.flavor_id = uuid.uuid1()

        # create mocked config and driver
        conf = cfg.ConfigOpts()
        conf.register_opt(
            cfg.StrOpt('datacenter',
                       default='',
                       help='datacenter where the C* cluster hosted'))
        conf.register_opts(driver.CASSANDRA_OPTIONS,
                           group=driver.CASSANDRA_GROUP)

        cassandra_driver = driver.CassandraStorageDriver(conf)

        migrations_patcher = mock.patch('cdeploy.migrator.Migrator')
        migrations_patcher.start()
        self.addCleanup(migrations_patcher.stop)

        # stubbed cassandra driver
        self.fc = flavors.FlavorsController(cassandra_driver)
示例#2
0
def init_conf(read_conf=True):
    global _CONF
    if _CONF is not None:
        return _CONF

    default_config_files = None
    if read_conf:
        confpath = os.path.join(
            os.path.dirname(os.path.realpath(heat_integrationtests.__file__)),
            'heat_integrationtests.conf')
        if os.path.isfile(confpath):
            default_config_files = [confpath]

    _CONF = cfg.ConfigOpts()
    logging.register_options(_CONF)
    _CONF(args=[],
          project='heat_integrationtests',
          default_config_files=default_config_files)

    for group, opts in list_opts():
        _CONF.register_opts(opts, group=group)
    return _CONF
示例#3
0
    def test_generator_raises_error(self):
        """Verifies that errors from extension manager are not suppressed."""
        class FakeException(Exception):
            pass

        class FakeEP(object):

            def __init__(self):
                self.name = 'callback_is_expected'
                self.require = self.resolve
                self.load = self.resolve

            def resolve(self, *args, **kwargs):
                raise FakeException()

        fake_ep = FakeEP()
        self.conf = cfg.ConfigOpts()
        self.conf.register_opts(generator._generator_opts)
        self.conf.set_default('namespace', fake_ep.name)
        fake_eps = mock.Mock(return_value=[fake_ep])
        with mock.patch('pkg_resources.iter_entry_points', fake_eps):
            self.assertRaises(FakeException, generator.generate, self.conf)
示例#4
0
def _generate_sample(app, policy_file, base_name):
    def info(msg):
        LOG.info('[%s] %s' % (__name__, msg))

    # If we are given a file that isn't an absolute path, look for it
    # in the source directory if it doesn't exist.
    candidates = [
        policy_file,
        os.path.join(
            app.srcdir,
            policy_file,
        ),
    ]
    for c in candidates:
        if os.path.isfile(c):
            info('reading config generator instructions from %s' % c)
            config_path = c
            break
    else:
        raise ValueError("Could not find policy_generator_config_file %r" %
                         app.config.policy_generator_config_file)

    if base_name:
        out_file = os.path.join(app.srcdir, base_name) + '.policy.yaml.sample'
        if not os.path.isdir(os.path.dirname(os.path.abspath(out_file))):
            os.mkdir(os.path.dirname(os.path.abspath(out_file)))
    else:
        file_name = 'sample.policy.yaml'
        out_file = os.path.join(app.srcdir, file_name)

    info('writing sample policy to %s' % out_file)
    # NOTE(bnemec): We don't want to do cli parsing on the global object here
    # because that can break consumers who do cli arg registration on import
    # in their documented modules. It's not allowed to register a cli arg after
    # the args have been parsed once.
    conf = cfg.ConfigOpts()
    generator.generate_sample(
        args=['--config-file', config_path, '--output-file', out_file],
        conf=conf)
示例#5
0
文件: base.py 项目: wenchma/zaqar
    def setUp(self):
        super(TestBase, self).setUp()

        self.useFixture(fixtures.FakeLogger('zaqar'))

        if os.environ.get('OS_STDOUT_CAPTURE') is not None:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') is not None:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        if self.config_file:
            self.config_file = helpers.override_mongo_conf(
                self.config_file, self)
            self.conf = self.load_conf(self.config_file)
        else:
            self.conf = cfg.ConfigOpts()

        self.conf.register_opts(configs._GENERAL_OPTIONS)
        self.conf.register_opts(configs._DRIVER_OPTIONS,
                                group=configs._DRIVER_GROUP)
示例#6
0
 def setUp(self):
     super(TestUpgradeCheckResourceProviders, self).setUp()
     self.output = StringIO()
     self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.output))
     # We always need the API DB to be setup.
     self.useFixture(nova_fixtures.Database(database='api'))
     # Setting up the placement fixtures is complex because we need
     # the status command (which access the placement tables directly)
     # to have access to the right database engine. So first we create
     # a config, then the PlacementFixtur and then monkey patch the
     # old placement get_placement_engine code.
     config = cfg.ConfigOpts()
     conf_fixture = self.useFixture(config_fixture.Config(config))
     placement_fixture = self.useFixture(
         func_fixtures.PlacementFixture(conf_fixture=conf_fixture, db=True))
     self.placement_api = placement_fixture.api
     # We need the code in status to be using the database we've set up.
     self.useFixture(
         fixtures.MonkeyPatch(
             'nova.api.openstack.placement.db_api.get_placement_engine',
             placement.db_api.get_placement_engine))
     self.cmd = status.UpgradeCommands()
示例#7
0
 def plug_port(self, port_name):
     # TODO(jlibosva): Don't use interface driver for fullstack fake
     # machines as the port should be treated by OVS agent and not by
     # external party
     interface_config = cfg.ConfigOpts()
     config.register_interface_opts(interface_config)
     ovs_interface = interface.OVSInterfaceDriver(interface_config)
     ovs_interface.plug_new(None,
                            self.port_id,
                            port_name,
                            self.mac,
                            bridge=self.bridge.br_name,
                            namespace=self.namespace)
     # NOTE(mangelajo): for OVS implementations remove the DEAD VLAN tag
     # on ports that we intend to use as fake vm interfaces, they
     # need to be flat. This is related to lp#1767422
     self.bridge.clear_db_attribute("Port", port_name, "tag")
     # Clear vlan_mode that is added for each new port. lp#1930414
     self.bridge.clear_db_attribute("Port", port_name, "vlan_mode")
     self.bridge.clear_db_attribute("Port", port_name, "trunks")
     self.addCleanup(self.bridge.delete_port, port_name)
     self.port = ip_lib.IPDevice(port_name, self.namespace)
示例#8
0
    def setUp(self):
        super(TestDriver, self).setUp()

        pyrax_cloud_dns_patcher = mock.patch('pyrax.cloud_dns')
        pyrax_cloud_dns_patcher.start()
        self.addCleanup(pyrax_cloud_dns_patcher.stop)

        pyrax_set_credentials_patcher = mock.patch('pyrax.set_credentials')
        self.mock_credentials = pyrax_set_credentials_patcher.start()
        self.addCleanup(pyrax_set_credentials_patcher.stop)

        pyrax_set_setting_patcher = mock.patch('pyrax.set_setting')
        self.mock_settings = pyrax_set_setting_patcher.start()
        self.addCleanup(pyrax_set_setting_patcher.stop)

        rs_options_patcher = mock.patch.object(driver,
                                               'RACKSPACE_OPTIONS',
                                               new=RACKSPACE_OPTIONS)
        rs_options_patcher.start()
        self.addCleanup(rs_options_patcher.stop)

        self.conf = cfg.ConfigOpts()
示例#9
0
def main(args=None, prog=None):
    conf = cfg.ConfigOpts()
    conf.register_cli_opts(common_opts)
    conf(sys.argv[1:])

    # print('rules %s' % (conf.rules, ))
    # print('querys %s' % (conf.query, ))

    default_policy = "default"
    run = agnostic.Runtime()
    run.create_policy(default_policy)

    for l in reqs(conf.rules):
        run.insert(l)

    err_count = 0
    for l in reqs(conf.query):
        ans = run.select(l)
        if ans != '':
            err_count += 1
            print(ans)
    return
示例#10
0
    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='admin',
                                       project_id='abcd',
                                       auth_token='efgh',
                                       service_catalog=service_catalog)

        self.conf = cfg.ConfigOpts()
        swift.register_opts(self.conf)
示例#11
0
    def setUp(self):
        super(TestFwaasL3AgentRpcCallback, self).setUp()

        self.conf = cfg.ConfigOpts()
        self.conf.register_opts(base_config.core_opts)
        self.conf.register_opts(l3_config.OPTS)
        self.conf.register_opts(ha.OPTS)
        self.conf.register_opts(firewall_agent_api.FWaaSOpts, 'fwaas')
        self.api = FWaasAgent(self.conf)
        self.api.fwaas_driver = test_firewall_agent_api.NoopFwaasDriver()
        self.adminContext = context.get_admin_context()
        self.router_id = str(uuid.uuid4())
        self.agent_conf = mock.Mock()
        self.ri_kwargs = {
            'router': {
                'id': self.router_id,
                'tenant_id': str(uuid.uuid4())
            },
            'agent_conf': self.agent_conf,
            'interface_driver': mock.ANY,
            'use_ipv6': mock.ANY,
        }
示例#12
0
    def test_creation_from_config(self, create_engine, get_maker):
        conf = cfg.ConfigOpts()
        conf.register_opts(db_options.database_opts, group='database')

        overrides = {
            'connection': 'sqlite:///:memory:',
            'slave_connection': None,
            'connection_debug': 100,
            'max_pool_size': 10,
            'mysql_sql_mode': 'TRADITIONAL',
        }
        for optname, optvalue in overrides.items():
            conf.set_override(optname, optvalue, group='database')

        session.EngineFacade.from_config(conf,
                                         autocommit=False,
                                         expire_on_commit=True)

        create_engine.assert_called_once_with(
            sql_connection='sqlite:///:memory:',
            connection_debug=100,
            max_pool_size=10,
            mysql_sql_mode='TRADITIONAL',
            sqlite_fk=False,
            idle_timeout=mock.ANY,
            retry_interval=mock.ANY,
            max_retries=mock.ANY,
            max_overflow=mock.ANY,
            connection_trace=mock.ANY,
            sqlite_synchronous=mock.ANY,
            pool_timeout=mock.ANY,
            thread_checkin=mock.ANY,
            json_serializer=None,
            json_deserializer=None,
            logging_name=mock.ANY,
        )
        get_maker.assert_called_once_with(engine=create_engine(),
                                          autocommit=False,
                                          expire_on_commit=True)
    def test_load_datasources_value_with_errors(self):
        # setup
        entity_graph_opts = [
            cfg.StrOpt('datasources_values_dir',
                       default=utils.get_resources_dir() +
                       '/datasources_values/erroneous_values'),
        ]
        conf = cfg.ConfigOpts()
        conf.register_opts(entity_graph_opts, group='entity_graph')
        conf.register_opts(self.DATASOURCES_OPTS, group='datasources')
        self._load_datasources(conf)

        # action
        info_mapper = DatasourceInfoMapper(conf)

        # test assertions
        missing_values = 1
        erroneous_values = 1
        num_valid_datasources = len(info_mapper.datasources_value_confs) + \
            missing_values + erroneous_values
        self.assertThat(conf.datasources.types,
                        matchers.HasLength(num_valid_datasources))
示例#14
0
    def setUp(self):
        super(VolumeGlanceProtectionPluginTest, self).setUp()

        plugin_config = cfg.ConfigOpts()
        plugin_config_fixture = self.useFixture(fixture.Config(plugin_config))
        plugin_config_fixture.load_raw_values(group='volume_glance_plugin',
                                              poll_interval=0,
                                              backup_image_object_size=65536)
        self.plugin = VolumeGlanceProtectionPlugin(plugin_config)
        cfg.CONF.set_default('glance_endpoint', 'http://127.0.0.1:9292',
                             'glance_client')

        cfg.CONF.set_default('cinder_endpoint', 'http://127.0.0.1:8774/v2.1',
                             '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)
        self.glance_client = client_factory.ClientFactory.create_client(
            "glance", self.cntxt)
        self.checkpoint = FakeCheckpoint()
示例#15
0
def main(check_callback):
    """Simple implementation of main for upgrade checks

    This can be used in upgrade check commands to provide the minimum
    necessary parameter handling and logic.

    :param check_callback: The check function from the concrete implementation
                           of UpgradeCommands.
    """
    add_parsers = functools.partial(_add_parsers,
                                    check_callback=check_callback)
    opt = cfg.SubCommandOpt('category', handler=add_parsers)
    conf = cfg.ConfigOpts()
    conf.register_cli_opt(opt)
    conf(sys.argv[1:])

    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
示例#16
0
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")
 def setUp(self):
     super(TestNetworkRoutingOperationsAci, self).setUp()
     self.agent = mock.Mock()
     self.conf = cfg.ConfigOpts()
     self.conf.register_opts(bc.core_opts)
     self.conf.register_opts(cfg_agent.OPTS, "cfg_agent")
     self.l3pluginApi_cls_p = mock.patch(
         'networking_cisco.plugins.cisco.cfg_agent.service_helpers.'
         'routing_svc_helper.CiscoRoutingPluginApi')
     l3plugin_api_cls = self.l3pluginApi_cls_p.start()
     self.plugin_api = mock.Mock()
     l3plugin_api_cls.return_value = self.plugin_api
     self.plugin_api.get_routers = mock.MagicMock()
     self.looping_call_p = mock.patch(
         'oslo_service.loopingcall.FixedIntervalLoopingCall')
     self.looping_call_p.start()
     mock.patch('networking_cisco.backwards_compatibility.'
                'rpc.Connection').start()
     self.routing_helper = aci_svc_helper.RoutingServiceHelperAci(
         helper.HOST, self.conf, self.agent)
     self.routing_helper._external_gateway_added = mock.Mock()
     self.routing_helper._external_gateway_removed = mock.Mock()
示例#18
0
    def _load_config(self, resource_api, file_list, domain_name):
        def assert_no_more_than_one_sql_driver(new_config, config_file):
            """Ensure there is more than one sql driver.

            Check to see if the addition of the driver in this new config
            would cause there to now be more than one sql driver.

            """
            if (new_config['driver'].is_sql
                    and (self.driver.is_sql or self._any_sql)):
                # The addition of this driver would cause us to have more than
                # one sql driver, so raise an exception.
                raise exception.MultipleSQLDriversInConfig(
                    config_file=config_file)
            self._any_sql = new_config['driver'].is_sql

        try:
            domain_ref = resource_api.get_domain_by_name(domain_name)
        except exception.DomainNotFound:
            LOG.warning(
                _LW('Invalid domain name (%s) found in config file name'),
                domain_name)
            return

        # Create a new entry in the domain config dict, which contains
        # a new instance of both the conf environment and driver using
        # options defined in this set of config files.  Later, when we
        # service calls via this Manager, we'll index via this domain
        # config dict to make sure we call the right driver
        domain_config = {}
        domain_config['cfg'] = cfg.ConfigOpts()
        config.configure(conf=domain_config['cfg'])
        domain_config['cfg'](args=[],
                             project='keystone',
                             default_config_files=file_list)
        domain_config['driver'] = self._load_driver(domain_config)
        assert_no_more_than_one_sql_driver(domain_config, file_list)
        self[domain_ref['id']] = domain_config
示例#19
0
def setup_config(config_file=''):
    global TEST_CONF
    TEST_CONF = cfg.ConfigOpts()

    identity_group = cfg.OptGroup(name='identity')
    identity_options = [
        cfg.StrOpt('auth_version', default='3'),
        cfg.StrOpt('uri', default='http://localhost:5000/v3'),
        cfg.StrOpt('username', default='demo'),
        cfg.StrOpt('password', default='password'),
        cfg.StrOpt('project_name', default='demo'),
        cfg.StrOpt('user_domain_name', default='default'),
        cfg.StrOpt('project_domain_name', default='default')
    ]
    TEST_CONF.register_group(identity_group)
    TEST_CONF.register_opts(identity_options, group=identity_group)

    message_broker_group = cfg.OptGroup(name='message_broker')
    message_broker_options = [
        cfg.StrOpt('flavor', default='8795'),
    ]
    TEST_CONF.register_group(message_broker_group)
    TEST_CONF.register_opts(message_broker_options, group=message_broker_group)

    # Figure out which config to load
    config_to_load = []
    local_config = 'cue-integration.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)
    else:
        config_to_load.append('/etc/cue/cue-integration.conf')

    # Actually parse config
    TEST_CONF(
        (),  # Required to load a anonymous config
        default_config_files=config_to_load)
示例#20
0
def new_config():
    conf = cfg.ConfigOpts()
    log.register_options(conf)
    conf.register_opts(context_opts)
    conf.register_opts(common_opts)
    conf.register_opts(host_opts)
    conf.register_opts(_options.eventlet_backdoor_opts)
    conf.register_opts(_options.periodic_opts)

    conf.register_opts(_options.ssl_opts, "ssl")
    conf.register_group(queue_opt_group)
    conf.register_opts(queue_opts, group=queue_opt_group)
    conf.register_group(ks_queue_opt_group)
    conf.register_opts(ks_queue_opts, group=ks_queue_opt_group)
    conf.register_opts(cleaner_opts, group=cleaner_opt_group)
    conf.register_opts(worker_opts, group=worker_opt_group)
    conf.register_opts(mail_opts, group=mail_opt_group)

    # Update default values from libraries that carry their own oslo.config
    # initialization and configuration.
    set_middleware_defaults()

    return conf
示例#21
0
    def setUp(self):
        super(TestFWaasV2AgentExtensionBase, self).setUp()

        self.fake = fake_data.FakeFWaaSL2Agent()
        self.port = self.fake.create('port')
        self.port_minimal = self.fake.create('port', minimal=True)
        self.fwg = self.fake.create('fwg')
        self.fwg_with_rule = self.fake.create('fwg_with_rule')
        self.port_id = self.port['port_id']
        self.fwg_id = self.fwg['id']
        self.host = fake_data.HOST
        self.ctx = context.get_admin_context()

        self.l2 = fwaas_v2.FWaaSV2AgentExtension()
        self.l2.consume_api(mock.Mock())
        self.driver = mock.patch(
            'neutron.manager.NeutronManager.load_class_for_provider').start()
        self.l2.initialize(None, 'ovs')
        self.l2.vlan_manager = mock.Mock()
        self.conf = cfg.ConfigOpts()
        self.l2.fwg_map = mock.Mock()
        self.l2.conf.host = self.host
        self.rpc = self.l2.plugin_rpc
示例#22
0
    def __init__(self, application, conf=None):
        self.application = application
        # NOTE(sileht): If the configuration come from oslo.config
        # just use it.
        if isinstance(conf, cfg.ConfigOpts):
            self.conf = []
            self.oslo_conf = conf
        else:
            self.conf = conf or []
            if "oslo_config_project" in self.conf:
                if 'oslo_config_file' in self.conf:
                    default_config_files = [self.conf['oslo_config_file']]
                else:
                    default_config_files = None
                self.oslo_conf = cfg.ConfigOpts()
                self.oslo_conf([],
                               project=self.conf['oslo_config_project'],
                               default_config_files=default_config_files,
                               validate_default_values=True)

            else:
                # Fallback to global object
                self.oslo_conf = cfg.CONF
示例#23
0
    def setUp(self):
        super(TestFWaaSL3AgentExtension, self).setUp()

        self.conf = cfg.ConfigOpts()
        self.conf.register_opts(l3_config.OPTS)
        self.conf.register_opts(firewall_agent_api.FWaaSOpts, 'fwaas')
        self.conf.host = 'myhost'
        self.api = FWaasAgent(self.conf)
        self.api.agent_api = mock.Mock()
        self.api.fwaas_driver = test_firewall_agent_api.NoopFwaasDriverV2()
        self.adminContext = context.get_admin_context()
        self.context = mock.sentinel.context
        self.router_id = uuidutils.generate_uuid()
        self.agent_conf = mock.Mock()
        self.ri_kwargs = {
            'router': {
                'id': self.router_id,
                'project_id': uuidutils.generate_uuid()
            },
            'agent_conf': self.agent_conf,
            'interface_driver': mock.ANY,
            'use_ipv6': mock.ANY
        }
示例#24
0
    def _load_providers(self):
        """load provider"""
        config_dir = utils.find_config(CONF.provider_config_dir)

        for config_file in os.listdir(config_dir):
            if not config_file.endswith('.conf'):
                continue
            config_path = os.path.abspath(os.path.join(config_dir,
                                                       config_file))
            provider_config = cfg.ConfigOpts()
            provider_config(args=['--config-file=' + config_path])
            provider_config.register_opts(provider_opts, 'provider')
            try:
                provider = PluggableProtectionProvider(provider_config)
            except Exception as e:
                LOG.error(
                    _LE("Load provider: %(provider)s failed. "
                        "Reason: %(reason)s"), {
                            'provider': provider_config.provider.name,
                            'reason': e
                        })
            else:
                self.providers[provider.id] = provider
示例#25
0
    def setUp(self):
        super(TestModSanQueue, self).setUp()
        self.cert_obj_json = {
            "cert_type": "san",
            "domain_name": "www.abc.com",
            "flavor_id": "premium"
        }

        # Need this fake class bc zake's fake client
        # does not take any host parameters
        class fake_kz_client(fake_client.FakeClient):
            def __init__(self, hosts):
                super(self.__class__, self).__init__()

        zookeeper_client_patcher = mock.patch(
            'kazoo.client.KazooClient',
            fake_kz_client
        )
        zookeeper_client_patcher.start()
        self.addCleanup(zookeeper_client_patcher.stop)

        self.conf = cfg.ConfigOpts()
        self.zk_queue = zookeeper_queue.ZookeeperModSanQueue(self.conf)
示例#26
0
    def _setUp(self):
        super(OVSPortFixture, self)._setUp()

        interface_config = cfg.ConfigOpts()
        interface_config.register_opts(interface.OPTS)
        ovs_interface = interface.OVSInterfaceDriver(interface_config)

        # because in some tests this port can be used to providing connection
        # between linuxbridge agents and vlan_id can be also added to this
        # device name it has to be max LB_DEVICE_NAME_MAX_LEN long
        port_name = tests_base.get_rand_name(
            LB_DEVICE_NAME_MAX_LEN,
            PORT_PREFIX
        )
        ovs_interface.plug_new(
            None,
            self.port_id,
            port_name,
            self.mac,
            bridge=self.bridge.br_name,
            namespace=self.namespace)
        self.addCleanup(self.bridge.delete_port, port_name)
        self.port = ip_lib.IPDevice(port_name, self.namespace)
示例#27
0
    def _build_store(self):
        # NOTE(flaper87): Due to the nice glance_store api (#sarcasm), we're
        # forced to build our own config object, register the required options
        # (and by required I mean *ALL* of them, even the ones we don't want),
        # and create our own store instance by calling a private function.
        # This is certainly unfortunate but it's the best we can do until the
        # glance_store refactor is done. A good thing is that glance_store is
        # under our team's management and it gates on Glance so changes to
        # this API will (should?) break task's tests.
        # TODO(abhishekk): After removal of backend module from glance_store
        # need to change this to use multi_backend module.
        conf = cfg.ConfigOpts()
        try:
            backend.register_opts(conf)
        except cfg.DuplicateOptError:
            pass

        conf.set_override('filesystem_store_datadir',
                          CONF.node_staging_uri[7:],
                          group='glance_store')

        # NOTE(flaper87): Do not even try to judge me for this... :(
        # With the glance_store refactor, this code will change, until
        # that happens, we don't have a better option and this is the
        # least worst one, IMHO.
        store = backend._load_store(conf, 'file')

        if store is None:
            msg = (_("%(task_id)s of %(task_type)s not configured "
                     "properly. Could not load the filesystem store") % {
                         'task_id': self.task_id,
                         'task_type': self.task_type
                     })
            raise exception.BadTaskConfiguration(msg)

        store.configure()
        return store
示例#28
0
    def setUp(self):
        super(TestPublisher, self).setUp()
        self.conf = cfg.ConfigOpts()
        self.useFixture(ConfFixture(self.conf))

        # Patches the publisher socket class
        self.m_publisher_socket_cls = MagicMock(spec=Socket)
        # Patches the publisher socket instance
        self.m_publisher_socket = MagicMock(spec=Socket, name="nn_socket")
        self.m_publisher_socket_cls.return_value = self.m_publisher_socket

        self.patches.extend([
            # Deactivates the nanomsg socket
            patch(
                "watcher_metering.publisher.base.nanomsg.Socket",
                new=self.m_publisher_socket_cls,
            ),
            patch.object(
                StoreClientLoader, "load", new=MagicMock(),
            ),
        ])

        # Applies all of our patches before each test
        for _patch in self.patches:
            _patch.start()

        self.publisher = Publisher(
            use_nanoconfig_service=False,
            publisher_endpoint="fake://fake_endpoint",
            nanoconfig_service_endpoint="",
            nanoconfig_update_endpoint="",
            nanoconfig_profile="nanoconfig://test_profile",
            metrics_store="riemann",
            max_queue_size=5,
            max_worker=5,
            min_worker=1,
        )
示例#29
0
文件: utils.py 项目: Akanksha08/zaqar
def dynamic_conf(uri, options, conf=None):
    """Given metadata, yields a dynamic configuration.

    :param uri: pool location
    :type uri: six.text_type
    :param options: additional pool metadata
    :type options: dict
    :param conf: Optional conf object to copy
    :type conf: `oslo_config.cfg.ConfigOpts`
    :returns: Configuration object suitable for constructing storage
              drivers
    :rtype: oslo_config.cfg.ConfigOpts
    """
    storage_type = six.moves.urllib_parse.urlparse(uri).scheme

    # NOTE(cpp-cabrera): parse storage-specific opts:
    # 'drivers:storage:{type}'
    storage_opts = utils.dict_to_conf({'uri': uri, 'options': options})
    storage_group = u'drivers:message_store:%s' % storage_type

    # NOTE(cpp-cabrera): register those options!
    if conf is None:
        conf = cfg.ConfigOpts()
    else:
        conf = copy.copy(conf)

    if storage_group not in conf:
        conf.register_opts(storage_opts, group=storage_group)

    if 'drivers' not in conf:
        # NOTE(cpp-cabrera): parse general opts: 'drivers'
        driver_opts = utils.dict_to_conf({'storage': storage_type})
        conf.register_opts(driver_opts, group=u'drivers')

    conf.set_override('storage', storage_type, 'drivers')
    conf.set_override('uri', uri, group=storage_group)
    return conf
示例#30
0
    def setUp(self):
        super(TestCeilometerClient, self).setUp()
        self.conf = cfg.ConfigOpts()
        self.useFixture(ConfFixture(self.conf))

        self.patches.extend([
            patch.object(KeystoneClient,
                         "token",
                         new=PropertyMock(return_value="fake-token")),
            patch.object(KeystoneClient,
                         "ceilometer_uri",
                         new=PropertyMock(
                             return_value="http://fake-ceilometer-ep:7777")),
        ])

        self.client = CeilometerClient(
            auth_uri="http://fake-keystone-ep:1337",
            admin_user="******",
            admin_password="******",
            admin_tenant_name="fake_tenant",
        )

        for _patch in self.patches:
            _patch.start()