Ejemplo n.º 1
0
 def setup_coreplugin(self, core_plugin=None, load_plugins=True):
     cp = PluginFixture(core_plugin)
     self.useFixture(cp)
     self.patched_dhcp_periodic = cp.patched_dhcp_periodic
     self.patched_default_svc_plugins = cp.patched_default_svc_plugins
     if load_plugins:
         manager.init()
    def setUp(self):
        super(TestLoggingPlugin, self).setUp()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch(
            'neutron.objects.base.NeutronDbObject.modify_fields_from_db'
        ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins",
            ["neutron.services.logapi.logging_plugin.LoggingPlugin"])

        manager.init()
        self.log_plugin = directory.get_plugin(plugin_const.LOG_API)
        self.log_plugin.driver_manager = mock.Mock()
        log_types = mock.PropertyMock(return_value=SUPPORTED_LOGGING_TYPES)
        self.log_plugin.driver_manager.supported_logging_types = \
            mock.patch('neutron.services.logapi.drivers.manager.'
                       'LoggingServiceDriverManager.supported_logging_types',
                       new_callable=log_types).start()
        self.ctxt = context.Context('admin', 'fake_tenant')
Ejemplo n.º 3
0
def main():
    cfg.CONF.register_cli_opts(cli_opts)
    config.init(sys.argv[1:])

    # Enable logging but prevent output to stderr.
    cfg.CONF.use_stderr = False
    config.setup_logging()

    if not cfg.CONF.config_file:
        sys.exit(_("ERROR: Unable to find configuration file via the default"
                   " search paths (~/.neutron/, ~/, /etc/neutron/, /etc/) and"
                   " the '--config-file' option!"))

    router.APIRouter.factory({})
    manager.init()

    gbp_plugin = directory.get_plugin('GROUP_POLICY')
    if not gbp_plugin:
        sys.exit("GBP service plugin not configured.")

    result = gbp_plugin.validate_state(cfg.CONF.repair)
    if result in [api.VALIDATION_FAILED_REPAIRABLE,
                  api.VALIDATION_FAILED_UNREPAIRABLE,
                  api.VALIDATION_FAILED_WITH_EXCEPTION]:
        sys.exit(result)
    return 0
Ejemplo n.º 4
0
    def setUp(self):
        super(TestQosPlugin, self).setUp()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        mock.patch(
            'neutron.objects.qos.policy.QosPolicy.obj_load_attr').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch(
            'neutron.objects.base.NeutronDbObject.modify_fields_from_db'
        ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["qos"])

        manager.init()
        self.qos_plugin = directory.get_plugin(constants.QOS)

        self.qos_plugin.driver_manager = mock.Mock()

        self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc'
                                   '.ResourcesPushRpcApi.push').start()

        self.ctxt = context.Context('fake_user', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()

        self.policy_data = {
            'policy': {'id': uuidutils.generate_uuid(),
                       'project_id': uuidutils.generate_uuid(),
                       'name': 'test-policy',
                       'description': 'Test policy description',
                       'shared': True}}

        self.rule_data = {
            'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(),
                                     'max_kbps': 100,
                                     'max_burst_kbps': 150},
            'dscp_marking_rule': {'id': uuidutils.generate_uuid(),
                                  'dscp_mark': 16},
            'minimum_bandwidth_rule': {
                'id': uuidutils.generate_uuid(),
                'min_kbps': 10}}

        self.policy = policy_object.QosPolicy(
            self.ctxt, **self.policy_data['policy'])

        self.rule = rule_object.QosBandwidthLimitRule(
            self.ctxt, **self.rule_data['bandwidth_limit_rule'])

        self.dscp_rule = rule_object.QosDscpMarkingRule(
            self.ctxt, **self.rule_data['dscp_marking_rule'])

        self.min_rule = rule_object.QosMinimumBandwidthRule(
            self.ctxt, **self.rule_data['minimum_bandwidth_rule'])
Ejemplo n.º 5
0
    def setUp(self):
        super(QosRuleTypeObjectTestCase, self).setUp()
        self.config_parse()

        self.setup_coreplugin(load_plugins=False)
        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["qos"])
        manager.init()
Ejemplo n.º 6
0
 def test_load_default_service_plugins(self):
     self.patched_default_svc_plugins.return_value = {
         'neutron.tests.unit.dummy_plugin.DummyServicePlugin': 'DUMMY'
     }
     cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
     manager.init()
     svc_plugins = directory.get_plugins()
     self.assertIn('DUMMY', svc_plugins)
Ejemplo n.º 7
0
    def test_service_plugin_by_name_is_loaded(self):
        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["dummy"])
        manager.init()
        plugin = directory.get_plugin(constants.DUMMY)

        self.assertIsInstance(
            plugin, dummy_plugin.DummyServicePlugin,
            "loaded plugin should be of type neutronDummyPlugin")
Ejemplo n.º 8
0
    def setUp(self):
        super(TestQosPlugin, self).setUp()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        mock.patch(
            'neutron.objects.qos.policy.QosPolicy.obj_load_attr').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch('neutron.objects.base.NeutronDbObject.modify_fields_from_db'
                   ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["qos"])

        manager.init()
        self.qos_plugin = directory.get_plugin(constants.QOS)
        self.qos_plugin.notification_driver_manager = mock.Mock()

        self.ctxt = context.Context('fake_user', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()

        self.policy_data = {
            'policy': {
                'id': uuidutils.generate_uuid(),
                'tenant_id': uuidutils.generate_uuid(),
                'name': 'test-policy',
                'description': 'Test policy description',
                'shared': True
            }
        }

        self.rule_data = {
            'bandwidth_limit_rule': {
                'id': uuidutils.generate_uuid(),
                'max_kbps': 100,
                'max_burst_kbps': 150
            },
            'dscp_marking_rule': {
                'id': uuidutils.generate_uuid(),
                'dscp_mark': 16
            }
        }

        self.policy = policy_object.QosPolicy(self.ctxt,
                                              **self.policy_data['policy'])

        self.rule = rule_object.QosBandwidthLimitRule(
            self.ctxt, **self.rule_data['bandwidth_limit_rule'])

        self.dscp_rule = rule_object.QosDscpMarkingRule(
            self.ctxt, **self.rule_data['dscp_marking_rule'])
Ejemplo n.º 9
0
 def test_core_plugin_supports_services(self):
     cfg.CONF.set_override(
         "core_plugin", "neutron.tests.unit.test_manager."
         "MultiServiceCorePlugin")
     manager.init()
     svc_plugins = directory.get_plugins()
     self.assertEqual(3, len(svc_plugins))
     self.assertIn(lib_const.CORE, svc_plugins.keys())
     self.assertIn(lib_const.LOADBALANCER, svc_plugins.keys())
     self.assertIn(dummy_plugin.DUMMY_SERVICE_TYPE, svc_plugins.keys())
Ejemplo n.º 10
0
    def test_service_plugin_by_name_is_loaded(self):
        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins",
                              [dummy_plugin.Dummy.get_alias()])
        manager.init()
        plugin = directory.get_plugin(dummy_plugin.DUMMY_SERVICE_TYPE)

        self.assertIsInstance(
            plugin, dummy_plugin.DummyServicePlugin,
            "loaded plugin should be of type neutronDummyPlugin")
Ejemplo n.º 11
0
 def test_core_plugin_supports_services(self):
     cfg.CONF.set_override("core_plugin",
                           "neutron.tests.unit.test_manager."
                           "MultiServiceCorePlugin")
     manager.init()
     svc_plugins = directory.get_plugins()
     self.assertEqual(3, len(svc_plugins))
     self.assertIn(constants.CORE, svc_plugins.keys())
     self.assertIn(constants.LOADBALANCER, svc_plugins.keys())
     self.assertIn(constants.DUMMY, svc_plugins.keys())
Ejemplo n.º 12
0
def eventlet_rpc_server():
    LOG.info("Eventlet based AMQP RPC server starting...")

    try:
        manager.init()
        rpc_workers_launcher = service.start_all_workers()
    except NotImplementedError:
        LOG.info("RPC was already started in parent process by " "plugin.")
    else:
        rpc_workers_launcher.wait()
Ejemplo n.º 13
0
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        manager.init()
        plugin = directory.get_plugin()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS,
                          member_actions=MEMBER_ACTIONS)

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            controller = base.create_resource(collection,
                                              resource,
                                              plugin,
                                              params,
                                              allow_bulk=allow_bulk,
                                              parent=parent,
                                              allow_pagination=True,
                                              allow_sorting=True)
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent['collection_name'],
                                                  parent['member_name'],
                                                  collection)
            mapper_kwargs = dict(controller=controller,
                                 requirements=REQUIREMENTS,
                                 path_prefix=path_prefix,
                                 **col_kwargs)
            return mapper.collection(collection, resource, **mapper_kwargs)

        mapper.connect('index', '/', controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(
                RESOURCES[resource], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(RESOURCES[resource],
                                                      dict()))
            resource_registry.register_resource_by_name(resource)

        for resource in SUB_RESOURCES:
            _map_resource(
                SUB_RESOURCES[resource]['collection_name'], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(
                    SUB_RESOURCES[resource]['collection_name'], dict()),
                SUB_RESOURCES[resource]['parent'])

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Ejemplo n.º 14
0
def eventlet_rpc_server():
    LOG.info("Eventlet based AMQP RPC server starting...")

    try:
        manager.init()
        rpc_workers_launcher = service.start_all_workers()
    except NotImplementedError:
        LOG.info("RPC was already started in parent process by "
                 "plugin.")
    else:
        rpc_workers_launcher.wait()
Ejemplo n.º 15
0
    def test_service_plugin_is_loaded(self):
        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins",
                              ["neutron.tests.unit.dummy_plugin."
                               "DummyServicePlugin"])
        manager.init()
        plugin = directory.get_plugin(constants.DUMMY)

        self.assertIsInstance(
            plugin, dummy_plugin.DummyServicePlugin,
            "loaded plugin should be of type neutronDummyPlugin")
Ejemplo n.º 16
0
    def test_service_plugin_is_loaded(self):
        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins",
                              ["neutron.tests.unit.dummy_plugin."
                               "DummyServicePlugin"])
        manager.init()
        plugin = directory.get_plugin(dummy_plugin.DUMMY_SERVICE_TYPE)

        self.assertIsInstance(
            plugin, dummy_plugin.DummyServicePlugin,
            "loaded plugin should be of type neutronDummyPlugin")
Ejemplo n.º 17
0
def eventlet_rpc_server():
    LOG.info("Eventlet based AMQP RPC server starting...")

    try:
        manager.init()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCES)
        rpc_workers_launcher = service.start_all_workers()
    except NotImplementedError:
        LOG.info("RPC was already started in parent process by " "plugin.")
    else:
        rpc_workers_launcher.wait()
Ejemplo n.º 18
0
def eventlet_rpc_server():
    LOG.info("Eventlet based AMQP RPC server starting...")

    try:
        manager.init()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCES)
        rpc_workers_launcher = service.start_rpc_workers()
    except NotImplementedError:
        LOG.info("RPC was already started in parent process by "
                 "plugin.")
    else:
        rpc_workers_launcher.wait()
Ejemplo n.º 19
0
 def test_manager_gathers_agent_notifiers_from_service_plugins(self):
     cfg.CONF.set_override("service_plugins",
                           ["neutron.tests.unit.dummy_plugin."
                            "DummyServicePlugin"])
     cfg.CONF.set_override("core_plugin",
                           "neutron.tests.unit.test_manager."
                           "CorePluginWithAgentNotifiers")
     expected = {'l3': 'l3_agent_notifier',
                 'dhcp': 'dhcp_agent_notifier',
                 'dummy': 'dummy_agent_notifier'}
     manager.init()
     core_plugin = directory.get_plugin()
     self.assertEqual(expected, core_plugin.agent_notifiers)
Ejemplo n.º 20
0
 def test_manager_gathers_agent_notifiers_from_service_plugins(self):
     cfg.CONF.set_override("service_plugins",
                           ["neutron.tests.unit.dummy_plugin."
                            "DummyServicePlugin"])
     cfg.CONF.set_override("core_plugin",
                           "neutron.tests.unit.test_manager."
                           "CorePluginWithAgentNotifiers")
     expected = {'l3': 'l3_agent_notifier',
                 'dhcp': 'dhcp_agent_notifier',
                 'dummy': 'dummy_agent_notifier'}
     manager.init()
     core_plugin = directory.get_plugin()
     self.assertEqual(expected, core_plugin.agent_notifiers)
Ejemplo n.º 21
0
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        manager.init()
        plugin = directory.get_plugin()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS,
                          member_actions=MEMBER_ACTIONS)

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            controller = base.create_resource(
                collection, resource, plugin, params, allow_bulk=allow_bulk,
                parent=parent, allow_pagination=True,
                allow_sorting=True)
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent['collection_name'],
                                                  parent['member_name'],
                                                  collection)
            mapper_kwargs = dict(controller=controller,
                                 requirements=REQUIREMENTS,
                                 path_prefix=path_prefix,
                                 **col_kwargs)
            return mapper.collection(collection, resource,
                                     **mapper_kwargs)

        mapper.connect('index', '/', controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(RESOURCES[resource], resource,
                          attributes.RESOURCE_ATTRIBUTE_MAP.get(
                              RESOURCES[resource], dict()))
            resource_registry.register_resource_by_name(resource)

        for resource in SUB_RESOURCES:
            _map_resource(SUB_RESOURCES[resource]['collection_name'], resource,
                          attributes.RESOURCE_ATTRIBUTE_MAP.get(
                              SUB_RESOURCES[resource]['collection_name'],
                              dict()),
                          SUB_RESOURCES[resource]['parent'])

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Ejemplo n.º 22
0
 def setUp(self, service_plugins=None, extensions=None):
     self.setup_coreplugin('ml2', load_plugins=False)
     super(PecanFunctionalTest, self).setUp()
     self.addCleanup(exts.PluginAwareExtensionManager.clear_instance)
     self.addCleanup(set_config, {}, overwrite=True)
     self.set_config_overrides()
     manager.init()
     ext_mgr = exts.PluginAwareExtensionManager.get_instance()
     if extensions:
         ext_mgr.extensions = extensions
     if service_plugins:
         service_plugins['CORE'] = ext_mgr.plugins.get('CORE')
         ext_mgr.plugins = service_plugins
     self.setup_app()
Ejemplo n.º 23
0
 def setUp(self, service_plugins=None, extensions=None):
     self.setup_coreplugin('ml2', load_plugins=False)
     super(PecanFunctionalTest, self).setUp()
     self.addCleanup(exts.PluginAwareExtensionManager.clear_instance)
     self.set_config_overrides()
     manager.init()
     ext_mgr = exts.PluginAwareExtensionManager.get_instance()
     if extensions:
         ext_mgr.extensions = extensions
     if service_plugins:
         service_plugins[constants.CORE] = ext_mgr.plugins.get(
             constants.CORE)
         ext_mgr.plugins = service_plugins
     self.app = create_test_app()
Ejemplo n.º 24
0
    def setUp(self):
        super(KaloomL3ServicePluginTestCase, self).setUp()
        self.mysqld = testing.mysqld.Mysqld(my_cnf={'skip-networking': None})
        URL = create_engine(self.mysqld.url()).url

        oslo_cfg.CONF.set_override('connection', URL, group='database')

        #"neutron-db-manage upgrade head" equivalent
        alembic_cfg = migration_cli.get_neutron_config()
        alembic_cfg.neutron_config = oslo_cfg.CONF
        test_helper.upgrade(alembic_cfg)

        #"neutron-kaloom-db-manage upgrade head" equivalent
        script_location = 'networking_kaloom.ml2.drivers.kaloom.db.migration:alembic_migrations'
        alembic_cfg_kaloom = alembic_config.Config()
        alembic_cfg_kaloom.set_main_option("script_location", script_location)
        alembic_cfg_kaloom.neutron_config = oslo_cfg.CONF
        test_helper.upgrade(alembic_cfg_kaloom)

        with patch.object(neutron_context.db_api, '_CTX_MANAGER',
                          test_helper.get_context_manager(URL)):
            self.ctx = neutron_context.get_admin_context()
            self.ctx.session
        #print self.ctx.session.connection().engine

        self.setup_coreplugin(load_plugins=False)
        oslo_cfg.CONF.set_override("core_plugin",
                                   test_db_base_plugin_v2.DB_PLUGIN_KLASS)
        oslo_cfg.CONF.set_override("service_plugins", ['segments'])
        manager.init()
        self.l2_plugin = directory.get_plugin()
        self.segments_plugin = importutils.import_object(
            'neutron.services.segments.plugin.Plugin')

        #patch
        plugin.db_api._CTX_MANAGER = test_helper.get_context_manager(URL)
        plugin.kaloom_db.db_api.context_manager = test_helper.get_context_manager(
            URL)
        db_api.context_manager = test_helper.get_context_manager(URL)

        #fix l3_port_check issue
        def delete_port(context, id, l3_port_check=True):
            return original_delete_port(context, id)

        original_delete_port = self.l2_plugin.delete_port
        self.l2_plugin.delete_port = Mock(side_effect=delete_port)
Ejemplo n.º 25
0
def main():
    config.init(sys.argv[1:])
    config.setup_logging()

    cxt = context.get_admin_context()
    manager.init()
    plugin = directory.get_plugin()
    l3_plugin = directory.get_plugin(constants.L3)
    notifier = n_rpc.get_notifier('network')
    for network in plugin.get_networks(cxt):
        notifier.info(cxt, 'network.exists', {'network': network})
    for subnet in plugin.get_subnets(cxt):
        notifier.info(cxt, 'subnet.exists', {'subnet': subnet})
    for port in plugin.get_ports(cxt):
        notifier.info(cxt, 'port.exists', {'port': port})
    for router in l3_plugin.get_routers(cxt):
        notifier.info(cxt, 'router.exists', {'router': router})
    for floatingip in l3_plugin.get_floatingips(cxt):
        notifier.info(cxt, 'floatingip.exists', {'floatingip': floatingip})
Ejemplo n.º 26
0
    def setUp(self):
        super(TestConntrackHelperPlugin, self).setUp()

        with mock.patch.object(
                resource_manager.ResourceCallbacksManager,
                '_singleton',
                new_callable=mock.PropertyMock(return_value=False)):

            self.cons_mgr = resource_manager.ConsumerResourceCallbacksManager()
            self.prod_mgr = resource_manager.ProducerResourceCallbacksManager()
            for mgr in (self.cons_mgr, self.prod_mgr):
                mgr.clear()

        mock.patch.object(cons_registry,
                          '_get_manager',
                          return_value=self.cons_mgr).start()

        mock.patch.object(prod_registry,
                          '_get_manager',
                          return_value=self.prod_mgr).start()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch('neutron.objects.base.NeutronDbObject.modify_fields_from_db'
                   ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins",
                              ["router", "conntrack_helper"])
        manager.init()
        # TODO(hjensas): Add CONNTRACKHELPER to neutron-lib Well-known
        #  service type constants.
        self.cth_plugin = directory.get_plugin("CONNTRACKHELPER")
        self.ctxt = context.Context('admin', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()
Ejemplo n.º 27
0
    def setUp(self):
        super(TestPortForwardingPlugin, self).setUp()

        with mock.patch.object(
                resource_manager.ResourceCallbacksManager,
                '_singleton',
                new_callable=mock.PropertyMock(return_value=False)):

            self.cons_mgr = resource_manager.ConsumerResourceCallbacksManager()
            self.prod_mgr = resource_manager.ProducerResourceCallbacksManager()
            for mgr in (self.cons_mgr, self.prod_mgr):
                mgr.clear()

        mock.patch.object(cons_registry,
                          '_get_manager',
                          return_value=self.cons_mgr).start()

        mock.patch.object(prod_registry,
                          '_get_manager',
                          return_value=self.prod_mgr).start()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron_lib.callbacks.registry.publish').start()
        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch('neutron.objects.base.NeutronDbObject.modify_fields_from_db'
                   ).start()
        mock.patch.object(router.FloatingIP, 'from_db_object').start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["router", "port_forwarding"])

        manager.init()
        self.pf_plugin = directory.get_plugin(lib_plugin_conts.PORTFORWARDING)
        self.ctxt = context.Context('admin', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()
Ejemplo n.º 28
0
    def __init__(self, neutron_context, plugin=None, grid_manager=None):
        self.context = neutron_context
        # Check if neutron_manager is loaded as accessing directory methods
        # before a Neutron Manager has had the chances to load the environment
        # may result in callers handling an empty directory.
        if not directory.is_loaded():
            manager.init()

        self.plugin = plugin if plugin else directory.get_plugin()
        if grid_manager:
            self.grid_mgr = grid_manager
        else:
            self.grid_mgr = grid.GridManager(self.context)
            self.grid_mgr.sync(True)

        self.grid_config = self.grid_mgr.grid_config
        self.grid_id = self.grid_config.grid_id

        self._cached_grid_members = None
        self._cached_network_views = None
        self._cached_mapping_conditions = None
Ejemplo n.º 29
0
    def setUp(self):
        super(TestLoggingPlugin, self).setUp()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch('neutron.objects.base.NeutronDbObject.modify_fields_from_db'
                   ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override(
            "service_plugins",
            ["neutron.services.logapi.logging_plugin.LoggingPlugin"])

        manager.init()
        self.log_plugin = directory.get_plugin(constants.LOG_API)
        self.ctxt = context.Context('fake_user', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()
Ejemplo n.º 30
0
    def setUp(self):
        cfg.CONF.set_override('extension_drivers',
                              self._extension_drivers,
                              group='ml2')
        cfg.CONF.set_override('service_plugins', self._extension_drivers)
        super(TestOVNClientQosExtension, self).setUp()
        self.setup_coreplugin(self.CORE_PLUGIN_CLASS, load_plugins=True)
        manager.init()
        self._mock_qos_loaded = mock.patch.object(
            core_qos.QosCoreResourceExtension, 'plugin_loaded')
        self.mock_qos_loaded = self._mock_qos_loaded.start()

        self.txn = _Context()
        mock_driver = mock.Mock()
        mock_driver._nb_idl.transaction.return_value = self.txn
        self.qos_driver = qos_extension.OVNClientQosExtension(mock_driver)
        self._mock_rules = mock.patch.object(self.qos_driver,
                                             '_update_port_qos_rules')
        self.mock_rules = self._mock_rules.start()
        self.addCleanup(self._mock_rules.stop)
        self.ctx = context.get_admin_context()
        self.project_id = uuidutils.generate_uuid()
        self._initialize_objs()
Ejemplo n.º 31
0
    def setUp(self):
        super(TestPortForwardingPlugin, self).setUp()

        with mock.patch.object(
            resource_manager.ResourceCallbacksManager, '_singleton',
            new_callable=mock.PropertyMock(return_value=False)):

            self.cons_mgr = resource_manager.ConsumerResourceCallbacksManager()
            self.prod_mgr = resource_manager.ProducerResourceCallbacksManager()
            for mgr in (self.cons_mgr, self.prod_mgr):
                mgr.clear()

        mock.patch.object(
            cons_registry, '_get_manager', return_value=self.cons_mgr).start()

        mock.patch.object(
            prod_registry, '_get_manager', return_value=self.prod_mgr).start()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch(
            'neutron.objects.base.NeutronDbObject.modify_fields_from_db'
        ).start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["router", "port_forwarding"])

        manager.init()
        self.pf_plugin = directory.get_plugin(lib_plugin_conts.PORTFORWARDING)
        self.ctxt = context.Context('admin', 'fake_tenant')
        mock.patch.object(self.ctxt.session, 'refresh').start()
        mock.patch.object(self.ctxt.session, 'expunge').start()
Ejemplo n.º 32
0
def initialize_all():
    manager.init()
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCES)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    plugin = directory.get_plugin()
    for resource, collection in RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        new_controller = res_ctrl.CollectionsController(collection, resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(collection, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(
            pec_res.collection, pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        # Retrieving the parent resource.  It is expected the format of
        # the parent resource to be:
        # {'collection_name': 'name-of-collection',
        #  'member_name': 'name-of-resource'}
        # collection_name does not appear to be used in the legacy code
        # inside the controller logic, so we can assume we do not need it.
        parent = ext_res.parent or {}
        parent_resource = parent.get('member_name')
        collection_key = collection
        if parent_resource:
            collection_key = '/'.join([parent_resource, collection])
        collection_actions = ext_res.collection_actions
        member_actions = ext_res.member_actions
        if manager.NeutronManager.get_controller_for_resource(collection_key):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            member_actions = legacy_controller.member_actions
            pagination = legacy_controller.allow_pagination
            sorting = legacy_controller.allow_sorting
            # NOTE(blogan): legacy_controller and ext_res both can both have
            # member_actions.  the member_actions for ext_res are strictly for
            # routing, while member_actions for legacy_controller are used for
            # handling the request once the routing has found the controller.
            # They're always the same so we will just use the ext_res
            # member_action.
            new_controller = res_ctrl.CollectionsController(
                collection, resource, resource_info=attr_info,
                parent_resource=parent_resource, member_actions=member_actions,
                plugin=plugin, allow_pagination=pagination,
                allow_sorting=sorting, collection_actions=collection_actions)
            # new_controller.collection has replaced hyphens with underscores
            manager.NeutronManager.set_plugin_for_resource(
                new_controller.collection, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        else:
            new_controller = utils.ShimCollectionsController(
                collection, None, legacy_controller,
                collection_actions=collection_actions,
                member_actions=member_actions,
                action_status=ext_res.controller.action_status,
                collection_methods=ext_res.collection_methods)

        manager.NeutronManager.set_controller_for_resource(
            collection_key, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Ejemplo n.º 33
0
 def setUp(self):
     super(TestPluginWorker, self).setUp()
     self.setup_coreplugin('ml2', load_plugins=False)
     self._plugin_patcher = mock.patch(TARGET_PLUGIN, autospec=True)
     self.plugin = self._plugin_patcher.start()
     manager.init()
Ejemplo n.º 34
0
 def test_can_load_core_plugin_without_datastore(self):
     cfg.CONF.set_override("core_plugin", 'neutron.tests.unit.dummy_plugin.'
                           'DummyCorePluginWithoutDatastore')
     manager.init()
Ejemplo n.º 35
0
 def setUp(self):
     super(TestPluginWorker, self).setUp()
     self.setup_coreplugin('ml2', load_plugins=False)
     self._plugin_patcher = mock.patch(TARGET_PLUGIN, autospec=True)
     self.plugin = self._plugin_patcher.start()
     manager.init()
Ejemplo n.º 36
0
    def _setUpExtension(self, plugin, service_type,
                        resource_attribute_map, extension_class,
                        resource_prefix, plural_mappings=None,
                        translate_resource_name=False,
                        allow_pagination=False, allow_sorting=False,
                        supported_extension_aliases=None,
                        use_quota=False,
                        ):

        self._resource_prefix = resource_prefix
        self._plural_mappings = plural_mappings or {}
        self._translate_resource_name = translate_resource_name

        # Ensure existing ExtensionManager is not used
        extensions.PluginAwareExtensionManager._instance = None

        self.useFixture(tools.AttributeMapMemento())

        # Create the default configurations
        self.config_parse()

        # just stubbing core plugin with plugin
        self.setup_coreplugin(plugin, load_plugins=False)
        cfg.CONF.set_override('core_plugin', plugin)
        if service_type:
            cfg.CONF.set_override('service_plugins', [plugin])

        self._plugin_patcher = mock.patch(plugin, autospec=True)
        self.plugin = self._plugin_patcher.start()
        instance = self.plugin.return_value
        if service_type:
            instance.get_plugin_type.return_value = service_type
        manager.init()

        if supported_extension_aliases is not None:
            instance.supported_extension_aliases = supported_extension_aliases
        if allow_pagination:
            # instance.__native_pagination_support = True
            native_pagination_attr_name = ("_%s__native_pagination_support"
                                           % instance.__class__.__name__)
            setattr(instance, native_pagination_attr_name, True)
        if allow_sorting:
            # instance.__native_sorting_support = True
            native_sorting_attr_name = ("_%s__native_sorting_support"
                                        % instance.__class__.__name__)
            setattr(instance, native_sorting_attr_name, True)
        if use_quota:
            quota.QUOTAS._driver = None
            cfg.CONF.set_override('quota_driver', 'neutron.quota.ConfDriver',
                                  group='QUOTAS')
        setattr(instance, 'path_prefix', resource_prefix)

        class ExtensionTestExtensionManager(object):
            def get_resources(self):
                # Add the resources to the global attribute map
                # This is done here as the setup process won't
                # initialize the main API router which extends
                # the global attribute map
                attributes.RESOURCE_ATTRIBUTE_MAP.update(
                    resource_attribute_map)
                return extension_class.get_resources()

            def get_actions(self):
                return []

            def get_request_extensions(self):
                return []

        ext_mgr = ExtensionTestExtensionManager()
        self.ext_mdw = test_extensions.setup_extensions_middleware(ext_mgr)
        self.api = webtest.TestApp(self.ext_mdw)
Ejemplo n.º 37
0
 def _setUp(self):
     super(PluginClientFixture, self)._setUp()
     self.useFixture(testlib_api.StaticSqlFixture())
     self.useFixture(self.plugin_conf)
     self.useFixture(base.PluginFixture(self.plugin_conf.plugin_name))
     manager.init()
Ejemplo n.º 38
0
    def setup_extension(self,
                        plugin,
                        service_type,
                        extension_class,
                        resource_prefix,
                        plural_mappings=None,
                        translate_resource_name=False,
                        allow_pagination=False,
                        allow_sorting=False,
                        supported_extension_aliases=None,
                        use_quota=False):

        self._resource_prefix = resource_prefix
        self._plural_mappings = plural_mappings or {}
        self._translate_resource_name = translate_resource_name

        # Ensure existing ExtensionManager is not used
        extensions.PluginAwareExtensionManager._instance = None

        self.useFixture(fixture.APIDefinitionFixture())

        # Create the default configurations
        self.config_parse()

        core_plugin = CORE_PLUGIN if service_type else plugin
        self.setup_coreplugin(core_plugin, load_plugins=False)
        if service_type:
            cfg.CONF.set_override('service_plugins', [plugin])

        self._plugin_patcher = mock.patch(plugin, autospec=True)
        self.plugin = self._plugin_patcher.start()
        instance = self.plugin.return_value
        if service_type:
            instance.get_plugin_type.return_value = service_type
        manager.init()

        if supported_extension_aliases is not None:
            instance.supported_extension_aliases = supported_extension_aliases
        if allow_pagination:
            # instance.__native_pagination_support = True
            native_pagination_attr_name = ("_%s__native_pagination_support" %
                                           instance.__class__.__name__)
            setattr(instance, native_pagination_attr_name, True)
        if allow_sorting:
            # instance.__native_sorting_support = True
            native_sorting_attr_name = ("_%s__native_sorting_support" %
                                        instance.__class__.__name__)
            setattr(instance, native_sorting_attr_name, True)
        if use_quota:
            quota.QUOTAS._driver = None
            cfg.CONF.set_override('quota_driver',
                                  'neutron.quota.ConfDriver',
                                  group='QUOTAS')
        setattr(instance, 'path_prefix', resource_prefix)

        class ExtensionTestExtensionManager(object):
            def get_resources(self):
                return extension_class.get_resources()

            def get_actions(self):
                return []

            def get_request_extensions(self):
                return []

        ext_mgr = ExtensionTestExtensionManager()
        self.ext_mdw = test_extensions.setup_extensions_middleware(ext_mgr)
        self.api = webtest.TestApp(self.ext_mdw)
Ejemplo n.º 39
0
def main():
    """Main method for syncing neutron networks and ports with ovn nb db.

    The utility syncs neutron db with ovn nb db.
    """
    conf = setup_conf()

    # if no config file is passed or no configuration options are passed
    # then load configuration from /etc/neutron/neutron.conf
    try:
        conf(project='neutron')
    except TypeError:
        LOG.error('Error parsing the configuration values. Please verify.')
        return

    logging.setup(conf, 'neutron_ovn_db_sync_util')
    LOG.info('Started Neutron OVN db sync')
    mode = ovn_config.get_ovn_neutron_sync_mode()
    if mode not in [ovn_db_sync.SYNC_MODE_LOG, ovn_db_sync.SYNC_MODE_REPAIR]:
        LOG.error('Invalid sync mode : ["%s"]. Should be "log" or "repair"',
                  mode)
        return

    # Validate and modify core plugin and ML2 mechanism drivers for syncing.
    if (cfg.CONF.core_plugin.endswith('.Ml2Plugin')
            or cfg.CONF.core_plugin == 'ml2'):
        cfg.CONF.core_plugin = (
            'networking_ovn.cmd.neutron_ovn_db_sync_util.Ml2Plugin')
        if not cfg.CONF.ml2.mechanism_drivers:
            LOG.error('please use --config-file to specify '
                      'neutron and ml2 configuration file.')
            return
        if 'ovn' not in cfg.CONF.ml2.mechanism_drivers:
            LOG.error('No "ovn" mechanism driver found : "%s".',
                      cfg.CONF.ml2.mechanism_drivers)
            return
        cfg.CONF.set_override('mechanism_drivers', ['ovn-sync'], 'ml2')
        conf.service_plugins = ['networking_ovn.l3.l3_ovn.OVNL3RouterPlugin']
    else:
        LOG.error('Invalid core plugin : ["%s"].', cfg.CONF.core_plugin)
        return

    try:
        conn = impl_idl_ovn.get_connection(impl_idl_ovn.OvsdbNbOvnIdl)
        ovn_api = impl_idl_ovn.OvsdbNbOvnIdl(conn)
    except RuntimeError:
        LOG.error('Invalid --ovn-ovn_nb_connection parameter provided.')
        return

    try:
        sb_conn = impl_idl_ovn.get_connection(impl_idl_ovn.OvsdbSbOvnIdl)
        ovn_sb_api = impl_idl_ovn.OvsdbSbOvnIdl(sb_conn)
    except RuntimeError:
        LOG.error('Invalid --ovn-ovn_sb_connection parameter provided.')
        return

    manager.init()
    core_plugin = directory.get_plugin()
    ovn_driver = core_plugin.mechanism_manager.mech_drivers['ovn-sync'].obj
    ovn_driver._nb_ovn = ovn_api
    ovn_driver._sb_ovn = ovn_sb_api

    synchronizer = ovn_db_sync.OvnNbSynchronizer(core_plugin, ovn_api,
                                                 ovn_sb_api, mode, ovn_driver)

    LOG.info('Sync for Northbound db started with mode : %s', mode)
    synchronizer.do_sync()
    LOG.info('Sync completed for Northbound db')

    sb_synchronizer = ovn_db_sync.OvnSbSynchronizer(core_plugin, ovn_sb_api,
                                                    ovn_driver)

    LOG.info('Sync for Southbound db started with mode : %s', mode)
    sb_synchronizer.do_sync()
    LOG.info('Sync completed for Southbound db')
def main():
    """Main method for syncing neutron networks and ports with ovn nb db.

    This script provides a utility for syncing the OVN Northbound Database
    with the Neutron database.

    This script is used for the migration from ML2/OVS to ML2/OVN.
    """
    conf = setup_conf()

    # if no config file is passed or no configuration options are passed
    # then load configuration from /etc/neutron/neutron.conf
    try:
        conf(project='neutron')
    except TypeError:
        LOG.error('Error parsing the configuration values. Please verify.')
        return

    logging.setup(conf, 'neutron_ovn_db_sync_util')
    LOG.info('Started Neutron OVN db sync')
    mode = ovn_conf.get_ovn_neutron_sync_mode()
    if mode not in [ovn_db_sync.SYNC_MODE_LOG, ovn_db_sync.SYNC_MODE_REPAIR]:
        LOG.error('Invalid sync mode : ["%s"]. Should be "log" or "repair"',
                  mode)
        return

    # Validate and modify core plugin and ML2 mechanism drivers for syncing.
    if (cfg.CONF.core_plugin.endswith('.Ml2Plugin')
            or cfg.CONF.core_plugin == 'ml2'):
        cfg.CONF.core_plugin = (
            'neutron.cmd.ovn.neutron_ovn_db_sync_util.Ml2Plugin')
        if not cfg.CONF.ml2.mechanism_drivers:
            LOG.error('please use --config-file to specify '
                      'neutron and ml2 configuration file.')
            return
        if 'ovn' not in cfg.CONF.ml2.mechanism_drivers:
            LOG.error('No "ovn" mechanism driver found : "%s".',
                      cfg.CONF.ml2.mechanism_drivers)
            return
        cfg.CONF.set_override('mechanism_drivers', ['ovn-sync'], 'ml2')
        conf.service_plugins = [
            'neutron.services.ovn_l3.plugin.OVNL3RouterPlugin',
            'neutron.services.segments.plugin.Plugin',
            'port_forwarding',
        ]
    else:
        LOG.error('Invalid core plugin : ["%s"].', cfg.CONF.core_plugin)
        return

    mech_worker = worker.MaintenanceWorker
    try:
        ovn_api = impl_idl_ovn.OvsdbNbOvnIdl.from_worker(mech_worker)
    except RuntimeError:
        LOG.error('Invalid --ovn-ovn_nb_connection parameter provided.')
        return

    try:
        ovn_sb_api = impl_idl_ovn.OvsdbSbOvnIdl.from_worker(mech_worker)
    except RuntimeError:
        LOG.error('Invalid --ovn-ovn_sb_connection parameter provided.')
        return

    manager.init()
    core_plugin = directory.get_plugin()
    driver = core_plugin.mechanism_manager.mech_drivers['ovn-sync']
    # The L3 code looks for the OVSDB connection on the 'ovn' driver
    # and will fail with a KeyError if it isn't there
    core_plugin.mechanism_manager.mech_drivers['ovn'] = driver
    ovn_driver = driver.obj
    ovn_driver._nb_ovn = ovn_api
    ovn_driver._sb_ovn = ovn_sb_api

    synchronizer = ovn_db_sync.OvnNbSynchronizer(core_plugin, ovn_api,
                                                 ovn_sb_api, mode, ovn_driver)

    LOG.info('Sync for Northbound db started with mode : %s', mode)
    synchronizer.do_sync()
    LOG.info('Sync completed for Northbound db')

    sb_synchronizer = ovn_db_sync.OvnSbSynchronizer(core_plugin, ovn_sb_api,
                                                    ovn_driver)

    LOG.info('Sync for Southbound db started with mode : %s', mode)
    sb_synchronizer.do_sync()
    LOG.info('Sync completed for Southbound db')
Ejemplo n.º 41
0
def main():
    """Main method for syncing neutron networks and ports with ovn nb db.

    The utility syncs neutron db with ovn nb db.
    """
    conf = setup_conf()

    # if no config file is passed or no configuration options are passed
    # then load configuration from /etc/neutron/neutron.conf
    try:
        conf(project='neutron')
    except TypeError:
        LOG.error(_LE('Error parsing the configuration values. '
                      'Please verify.'))
        return

    logging.setup(conf, 'neutron_ovn_db_sync_util')
    LOG.info(_LI('Started Neutron OVN db sync'))
    mode = ovn_config.get_ovn_neutron_sync_mode()
    if mode not in [ovn_db_sync.SYNC_MODE_LOG, ovn_db_sync.SYNC_MODE_REPAIR]:
        LOG.error(_LE('Invalid sync mode : ["%s"]. Should be "log" or '
                      '"repair"'), mode)
        return

    # Validate and modify core plugin and ML2 mechanism drivers for syncing.
    if (cfg.CONF.core_plugin.endswith('.Ml2Plugin') or
            cfg.CONF.core_plugin == 'ml2'):
        cfg.CONF.core_plugin = (
            'networking_ovn.cmd.neutron_ovn_db_sync_util.Ml2Plugin')
        if not cfg.CONF.ml2.mechanism_drivers:
            LOG.error(_LE('please use --config-file to specify '
                          'neutron and ml2 configuration file.'))
            return
        if 'ovn' not in cfg.CONF.ml2.mechanism_drivers:
            LOG.error(_LE('No "ovn" mechanism driver found : "%s".'),
                      cfg.CONF.ml2.mechanism_drivers)
            return
        cfg.CONF.set_override('mechanism_drivers', ['ovn-sync'], 'ml2')
        conf.service_plugins = ['networking_ovn.l3.l3_ovn.OVNL3RouterPlugin']
    else:
        LOG.error(_LE('Invalid core plugin : ["%s"].'), cfg.CONF.core_plugin)
        return

    try:
        ovn_api = impl_idl_ovn.OvsdbNbOvnIdl(None)
    except RuntimeError:
        LOG.error(_LE('Invalid --ovn-ovn_nb_connection parameter provided.'))
        return

    manager.init()
    core_plugin = directory.get_plugin()
    ovn_driver = core_plugin.mechanism_manager.mech_drivers['ovn-sync'].obj
    ovn_driver._nb_ovn = ovn_api

    synchronizer = ovn_db_sync.OvnNbSynchronizer(
        core_plugin, ovn_api, mode, ovn_driver)

    ctx = context.get_admin_context()

    LOG.info(_LI('Syncing the networks and ports with mode : %s'), mode)
    try:
        synchronizer.sync_address_sets(ctx)
    except Exception:
        LOG.exception(_LE("Error syncing  the Address Sets. Check the "
                          "--database-connection value again"))
        return
    try:
        synchronizer.sync_networks_ports_and_dhcp_opts(ctx)
    except Exception:
        LOG.exception(_LE("Error syncing  Networks, Ports and DHCP options "
                          "for unknown reason please try again"))
        return
    try:
        synchronizer.sync_acls(ctx)
    except Exception:
        LOG.exception(_LE("Error syncing  ACLs for unknown "
                          "reason please try again"))
        return
    try:
        synchronizer.sync_routers_and_rports(ctx)
    except Exception:
        LOG.exception(_LE("Error syncing  Routers and Router ports "
                          "please try again"))
        return
    LOG.info(_LI('Sync completed'))
Ejemplo n.º 42
0
 def test_can_load_core_plugin_without_datastore(self):
     cfg.CONF.set_override(
         "core_plugin", 'neutron.tests.unit.dummy_plugin.'
         'DummyCorePluginWithoutDatastore')
     manager.init()
Ejemplo n.º 43
0
def initialize_all():
    manager.init()
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    plugin = directory.get_plugin()
    for resource, collection in router.RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        new_controller = res_ctrl.CollectionsController(collection,
                                                        resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(collection, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(pec_res.collection,
                                                       pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        # Retrieving the parent resource.  It is expected the format of
        # the parent resource to be:
        # {'collection_name': 'name-of-collection',
        #  'member_name': 'name-of-resource'}
        # collection_name does not appear to be used in the legacy code
        # inside the controller logic, so we can assume we do not need it.
        parent = ext_res.parent or {}
        parent_resource = parent.get('member_name')
        collection_key = collection
        if parent_resource:
            collection_key = '/'.join([parent_resource, collection])
        collection_actions = ext_res.collection_actions
        member_actions = ext_res.member_actions
        if manager.NeutronManager.get_controller_for_resource(collection_key):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            member_actions = legacy_controller.member_actions
            pagination = legacy_controller.allow_pagination
            sorting = legacy_controller.allow_sorting
            # NOTE(blogan): legacy_controller and ext_res both can both have
            # member_actions.  the member_actions for ext_res are strictly for
            # routing, while member_actions for legacy_controller are used for
            # handling the request once the routing has found the controller.
            # They're always the same so we will just use the ext_res
            # member_action.
            new_controller = res_ctrl.CollectionsController(
                collection,
                resource,
                resource_info=attr_info,
                parent_resource=parent_resource,
                member_actions=member_actions,
                plugin=plugin,
                allow_pagination=pagination,
                allow_sorting=sorting,
                collection_actions=collection_actions)
            # new_controller.collection has replaced hyphens with underscores
            manager.NeutronManager.set_plugin_for_resource(
                new_controller.collection, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        elif isinstance(legacy_controller, wsgi.Controller):
            new_controller = utils.ShimCollectionsController(
                collection,
                None,
                legacy_controller,
                collection_actions=collection_actions,
                member_actions=member_actions)
        else:
            LOG.warning(
                _LW("Unknown controller type encountered %s.  It will"
                    "be ignored."), legacy_controller)
        manager.NeutronManager.set_controller_for_resource(
            collection_key, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Ejemplo n.º 44
0
 def setup_coreplugin(self, core_plugin=None, load_plugins=True):
     super(TimeStampChangedsinceTestCase, self).setup_coreplugin(
         self.plugin, load_plugins=False)
     self.patched_default_svc_plugins.return_value = ['timestamp']
     manager.init()
Ejemplo n.º 45
0
 def _setUp(self):
     super(PluginClientFixture, self)._setUp()
     self.useFixture(testlib_api.StaticSqlFixture())
     self.useFixture(self.plugin_conf)
     self.useFixture(base.PluginFixture(self.plugin_conf.plugin_name))
     manager.init()
Ejemplo n.º 46
0
    def setup_extension(self, plugin, service_type,
                        extension_class,
                        resource_prefix, plural_mappings=None,
                        translate_resource_name=False,
                        allow_pagination=False, allow_sorting=False,
                        supported_extension_aliases=None,
                        use_quota=False):

        self._resource_prefix = resource_prefix
        self._plural_mappings = plural_mappings or {}
        self._translate_resource_name = translate_resource_name

        # Ensure existing ExtensionManager is not used
        extensions.PluginAwareExtensionManager._instance = None

        self.useFixture(fixture.APIDefinitionFixture())

        # Create the default configurations
        self.config_parse()

        core_plugin = CORE_PLUGIN if service_type else plugin
        self.setup_coreplugin(core_plugin, load_plugins=False)
        if service_type:
            cfg.CONF.set_override('service_plugins', [plugin])

        self._plugin_patcher = mock.patch(plugin, autospec=True)
        self.plugin = self._plugin_patcher.start()
        instance = self.plugin.return_value
        if service_type:
            instance.get_plugin_type.return_value = service_type
        manager.init()

        if supported_extension_aliases is not None:
            instance.supported_extension_aliases = supported_extension_aliases
        if allow_pagination:
            # instance.__native_pagination_support = True
            native_pagination_attr_name = ("_%s__native_pagination_support"
                                           % instance.__class__.__name__)
            setattr(instance, native_pagination_attr_name, True)
        if allow_sorting:
            # instance.__native_sorting_support = True
            native_sorting_attr_name = ("_%s__native_sorting_support"
                                        % instance.__class__.__name__)
            setattr(instance, native_sorting_attr_name, True)
        if use_quota:
            quota.QUOTAS._driver = None
            cfg.CONF.set_override('quota_driver', 'neutron.quota.ConfDriver',
                                  group='QUOTAS')
        setattr(instance, 'path_prefix', resource_prefix)

        class ExtensionTestExtensionManager(object):
            def get_resources(self):
                return extension_class.get_resources()

            def get_actions(self):
                return []

            def get_request_extensions(self):
                return []

        ext_mgr = ExtensionTestExtensionManager()
        self.ext_mdw = test_extensions.setup_extensions_middleware(ext_mgr)
        self.api = webtest.TestApp(self.ext_mdw)
Ejemplo n.º 47
0
    def _setUpExtension(
        self,
        plugin,
        service_type,
        resource_attribute_map,
        extension_class,
        resource_prefix,
        plural_mappings=None,
        translate_resource_name=False,
        allow_pagination=False,
        allow_sorting=False,
        supported_extension_aliases=None,
        use_quota=False,
    ):

        self._resource_prefix = resource_prefix
        self._plural_mappings = plural_mappings or {}
        self._translate_resource_name = translate_resource_name

        # Ensure existing ExtensionManager is not used
        extensions.PluginAwareExtensionManager._instance = None

        self.useFixture(tools.AttributeMapMemento())

        # Create the default configurations
        self.config_parse()

        # just stubbing core plugin with plugin
        self.setup_coreplugin(plugin, load_plugins=False)
        cfg.CONF.set_override('core_plugin', plugin)
        if service_type:
            cfg.CONF.set_override('service_plugins', [plugin])

        self._plugin_patcher = mock.patch(plugin, autospec=True)
        self.plugin = self._plugin_patcher.start()
        instance = self.plugin.return_value
        if service_type:
            instance.get_plugin_type.return_value = service_type
        manager.init()

        if supported_extension_aliases is not None:
            instance.supported_extension_aliases = supported_extension_aliases
        if allow_pagination:
            # instance.__native_pagination_support = True
            native_pagination_attr_name = ("_%s__native_pagination_support" %
                                           instance.__class__.__name__)
            setattr(instance, native_pagination_attr_name, True)
        if allow_sorting:
            # instance.__native_sorting_support = True
            native_sorting_attr_name = ("_%s__native_sorting_support" %
                                        instance.__class__.__name__)
            setattr(instance, native_sorting_attr_name, True)
        if use_quota:
            quota.QUOTAS._driver = None
            cfg.CONF.set_override('quota_driver',
                                  'neutron.quota.ConfDriver',
                                  group='QUOTAS')
        setattr(instance, 'path_prefix', resource_prefix)

        class ExtensionTestExtensionManager(object):
            def get_resources(self):
                # Add the resources to the global attribute map
                # This is done here as the setup process won't
                # initialize the main API router which extends
                # the global attribute map
                attributes.RESOURCE_ATTRIBUTE_MAP.update(
                    resource_attribute_map)
                return extension_class.get_resources()

            def get_actions(self):
                return []

            def get_request_extensions(self):
                return []

        ext_mgr = ExtensionTestExtensionManager()
        self.ext_mdw = test_extensions.setup_extensions_middleware(ext_mgr)
        self.api = webtest.TestApp(self.ext_mdw)
Ejemplo n.º 48
0
 def setup_coreplugin(self, core_plugin=None, load_plugins=True):
     super(TimeStampChangedsinceTestCase,
           self).setup_coreplugin(self.plugin, load_plugins=False)
     self.patched_default_svc_plugins.return_value = ['timestamp']
     manager.init()
Ejemplo n.º 49
0
    def setUp(self):
        super(TestQosPlugin, self).setUp()
        self.setup_coreplugin(load_plugins=False)

        mock.patch('neutron.objects.db.api.create_object').start()
        mock.patch('neutron.objects.db.api.update_object').start()
        mock.patch('neutron.objects.db.api.delete_object').start()
        mock.patch('neutron.objects.db.api.get_object').start()
        _mock_qos_load_attr = mock.patch(
            'neutron.objects.qos.policy.QosPolicy.obj_load_attr')
        self.mock_qos_load_attr = _mock_qos_load_attr.start()
        # We don't use real models as per mocks above. We also need to mock-out
        # methods that work with real data types
        mock.patch('neutron.objects.base.NeutronDbObject.modify_fields_from_db'
                   ).start()
        mock.patch.object(policy_object.QosPolicy, 'unset_default').start()
        mock.patch.object(policy_object.QosPolicy, 'set_default').start()

        cfg.CONF.set_override("core_plugin", DB_PLUGIN_KLASS)
        cfg.CONF.set_override("service_plugins", ["qos"])

        manager.init()
        self.qos_plugin = directory.get_plugin(plugins_constants.QOS)

        self.qos_plugin.driver_manager = mock.Mock()

        self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc'
                                   '.ResourcesPushRpcApi.push').start()

        self.ctxt = context.Context('fake_user', 'fake_tenant')
        self.admin_ctxt = context.get_admin_context()

        self.policy_data = {
            'policy': {
                'id': uuidutils.generate_uuid(),
                'project_id': uuidutils.generate_uuid(),
                'name': 'test-policy',
                'description': 'Test policy description',
                'shared': True,
                'is_default': False
            }
        }

        self.rule_data = {
            'bandwidth_limit_rule': {
                'id': uuidutils.generate_uuid(),
                'max_kbps': 100,
                'max_burst_kbps': 150
            },
            'dscp_marking_rule': {
                'id': uuidutils.generate_uuid(),
                'dscp_mark': 16
            },
            'minimum_bandwidth_rule': {
                'id': uuidutils.generate_uuid(),
                'min_kbps': 10
            }
        }

        self.policy = policy_object.QosPolicy(self.ctxt,
                                              **self.policy_data['policy'])

        self.rule = rule_object.QosBandwidthLimitRule(
            self.ctxt, **self.rule_data['bandwidth_limit_rule'])

        self.dscp_rule = rule_object.QosDscpMarkingRule(
            self.ctxt, **self.rule_data['dscp_marking_rule'])

        self.min_rule = rule_object.QosMinimumBandwidthRule(
            self.ctxt, **self.rule_data['minimum_bandwidth_rule'])