Ejemplo n.º 1
0
def load_driver(plugin, ofc_manager):

    if (PROVIDER_OPENFLOW in ROUTER_DRIVER_MAP and
        not ofc_manager.driver.router_supported):
        LOG.warning(
            _('OFC does not support router with provider=%(provider)s, '
              'so removed it from supported provider '
              '(new router driver map=%(driver_map)s)'),
            {'provider': PROVIDER_OPENFLOW,
             'driver_map': ROUTER_DRIVER_MAP})
        del ROUTER_DRIVER_MAP[PROVIDER_OPENFLOW]

    if config.PROVIDER.default_router_provider not in ROUTER_DRIVER_MAP:
        LOG.error(_('default_router_provider %(default)s is supported! '
                    'Please specify one of %(supported)s'),
                  {'default': config.PROVIDER.default_router_provider,
                   'supported': ROUTER_DRIVER_MAP.keys()})
        raise SystemExit(1)

    enabled_providers = (set(config.PROVIDER.router_providers +
                             [config.PROVIDER.default_router_provider]) &
                         set(ROUTER_DRIVER_MAP.keys()))

    for driver in enabled_providers:
        driver_klass = importutils.import_class(ROUTER_DRIVER_MAP[driver])
        ROUTER_DRIVERS[driver] = driver_klass(plugin, ofc_manager)

    LOG.info(_('Enabled router drivers: %s'), ROUTER_DRIVERS.keys())

    if not ROUTER_DRIVERS:
        LOG.error(_('No router provider is enabled. neutron-server terminated!'
                    ' (supported=%(supported)s, configured=%(config)s)'),
                  {'supported': ROUTER_DRIVER_MAP.keys(),
                   'config': config.PROVIDER.router_providers})
        raise SystemExit(1)
 def __init__(self, plugin):
     self._resource_name = RESOURCE_NAME
     self._plugin = plugin
     self._driver = importutils.import_class(
         cfg.CONF.QUOTAS.quota_driver
     )
     self._update_extended_attributes = True
Ejemplo n.º 3
0
 def __init__(self, plugin):
     self._resource_name = RESOURCE_NAME
     self._plugin = plugin
     self._driver = importutils.import_class(
         cfg.CONF.QUOTAS.quota_driver
     )
     self._update_extended_attributes = True
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        # If multiple class specified for same extension, last one will win
        # according to DictOpt behavior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class or ext_class == 'None':
                    self.supported_extension_aliases.append(ext_name)
                    continue
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                for method in dir(ext_instance):
                    for prefix in ['get', 'update', 'delete', 'create']:
                        if method.startswith('%s_' % prefix):
                            setattr(self, method,
                                    ext_instance.__getattribute__(method))
                self.supported_extension_aliases.append(ext_name)
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                # Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(
                    ext_name=ext_name, ext_class=ext_class)
        self._build_auth_details()
Ejemplo n.º 5
0
    def __init__(self, host=None):
        super(DhcpAgent, self).__init__(host=host)
        self.needs_resync = False
        self.conf = cfg.CONF
        self.cache = NetworkCache()
        self.root_helper = config.get_root_helper(self.conf)
        self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)

        # Work out if DHCP serving for bridged or routed VM interfaces.
        try:
            interface_driver = importutils.import_object(
                self.conf.interface_driver, self.conf)
            self.bridged = interface_driver.bridged()
        except Exception as e:
            msg = (_("Error importing interface driver '%(driver)s': "
                   "%(inner)s") % {'driver': self.conf.interface_driver,
                                   'inner': e})
            LOG.error(msg)
            raise SystemExit(msg)

        ctx = context.get_admin_context_without_session()
        self.plugin_rpc = DhcpPluginApi(topics.PLUGIN,
                                        ctx,
                                        self.bridged and
                                        self.conf.use_namespaces)
        # create dhcp dir to store dhcp info
        dhcp_dir = os.path.dirname("/%s/dhcp/" % self.conf.state_path)
        if not os.path.isdir(dhcp_dir):
            os.makedirs(dhcp_dir, 0o755)
        self.dhcp_version = self.dhcp_driver_cls.check_version()
        self._populate_networks_cache()
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        # If multiple class specified for same extension, last one will win
        # according to DictOpt behavior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class or ext_class == 'None':
                    self.supported_extension_aliases.append(ext_name)
                    continue
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                for method in dir(ext_instance):
                    for prefix in ['get', 'update', 'delete', 'create']:
                        if method.startswith('%s_' % prefix):
                            setattr(self, method,
                                    ext_instance.__getattribute__(method))
                self.supported_extension_aliases.append(ext_name)
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                # Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(ext_name=ext_name,
                                                    ext_class=ext_class)
        self._build_auth_details()
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        self._contrail_extensions_instances = []
        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        #If multiple class specified for same extension, last one will win
        #according to DictOpt beheivior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class:
                    LOG.error(_('Malformed contrail extension...'))
                    continue
                self.supported_extension_aliases.append(ext_name)
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                self._contrail_extensions_instances.append(ext_instance)
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                #Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(
                    ext_name=ext_name, ext_class=ext_class)

        self._multi_tenancy = cfg.CONF.APISERVER.multi_tenancy
        self._max_retries = cfg.CONF.APISERVER.max_retries
        self._retry_interval = cfg.CONF.APISERVER.retry_interval
Ejemplo n.º 8
0
    def __init__(self, host=None):
        super(DhcpAgent, self).__init__(host=host)
        self.needs_resync = False
        self.conf = cfg.CONF
        self.cache = NetworkCache()
        self.root_helper = config.get_root_helper(self.conf)
        self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)

        # Work out if DHCP serving for bridged or routed VM interfaces.
        try:
            interface_driver = importutils.import_object(
                self.conf.interface_driver, self.conf)
            self.bridged = interface_driver.bridged()
        except Exception as e:
            msg = (_("Error importing interface driver '%(driver)s': "
                     "%(inner)s") % {
                         'driver': self.conf.interface_driver,
                         'inner': e
                     })
            LOG.error(msg)
            raise SystemExit(msg)

        ctx = context.get_admin_context_without_session()
        self.plugin_rpc = DhcpPluginApi(
            topics.PLUGIN, ctx, self.bridged and self.conf.use_namespaces)
        # create dhcp dir to store dhcp info
        dhcp_dir = os.path.dirname("/%s/dhcp/" % self.conf.state_path)
        if not os.path.isdir(dhcp_dir):
            os.makedirs(dhcp_dir, 0o755)
        self.dhcp_version = self.dhcp_driver_cls.check_version()
        self._populate_networks_cache()
Ejemplo n.º 9
0
def load_driver(plugin, ofc_manager):

    if (PROVIDER_OPENFLOW in ROUTER_DRIVER_MAP and
        not ofc_manager.driver.router_supported):
        LOG.warning(
            _('OFC does not support router with provider=%(provider)s, '
              'so removed it from supported provider '
              '(new router driver map=%(driver_map)s)'),
            {'provider': PROVIDER_OPENFLOW,
             'driver_map': ROUTER_DRIVER_MAP})
        del ROUTER_DRIVER_MAP[PROVIDER_OPENFLOW]

    if config.PROVIDER.default_router_provider not in ROUTER_DRIVER_MAP:
        LOG.error(_('default_router_provider %(default)s is supported! '
                    'Please specify one of %(supported)s'),
                  {'default': config.PROVIDER.default_router_provider,
                   'supported': ROUTER_DRIVER_MAP.keys()})
        raise SystemExit(1)

    enabled_providers = (set(config.PROVIDER.router_providers +
                             [config.PROVIDER.default_router_provider]) &
                         set(ROUTER_DRIVER_MAP.keys()))

    for driver in enabled_providers:
        driver_klass = importutils.import_class(ROUTER_DRIVER_MAP[driver])
        ROUTER_DRIVERS[driver] = driver_klass(plugin, ofc_manager)

    LOG.info(_('Enabled router drivers: %s'), ROUTER_DRIVERS.keys())

    if not ROUTER_DRIVERS:
        LOG.error(_('No router provider is enabled. neutron-server terminated!'
                    ' (supported=%(supported)s, configured=%(config)s)'),
                  {'supported': ROUTER_DRIVER_MAP.keys(),
                   'config': config.PROVIDER.router_providers})
        raise SystemExit(1)
Ejemplo n.º 10
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        # Add a Fake 'something' resource to RESOURCE_ATTRIBUTE_MAP
        attributes.RESOURCE_ATTRIBUTE_MAP.update(FAKE_RESOURCE)
        self.rules = dict((k, common_policy.parse_rule(v)) for k, v in {
            "context_is_admin": "role:admin",
            "admin_or_network_owner": "rule:context_is_admin or "
                                      "tenant_id:%(network:tenant_id)s",
            "admin_or_owner": ("rule:context_is_admin or "
                               "tenant_id:%(tenant_id)s"),
            "admin_only": "rule:context_is_admin",
            "regular_user": "******",
            "shared": "field:networks:shared=True",
            "external": "field:networks:router:external=True",
            "default": '@',

            "create_network": "rule:admin_or_owner",
            "create_network:shared": "rule:admin_only",
            "update_network": '@',
            "update_network:shared": "rule:admin_only",

            "get_network": "rule:admin_or_owner or "
                           "rule:shared or "
                           "rule:external",
            "create_port:mac": "rule:admin_or_network_owner",
            "create_something": "rule:admin_or_owner",
            "create_something:attr": "rule:admin_or_owner",
            "create_something:attr:sub_attr_1": "rule:admin_or_owner",
            "create_something:attr:sub_attr_2": "rule:admin_only",

            "get_firewall_policy": "rule:admin_or_owner or "
                            "rule:shared",
            "get_firewall_rule": "rule:admin_or_owner or "
                            "rule:shared"
        }.items())

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        def remove_fake_resource():
            del attributes.RESOURCE_ATTRIBUTE_MAP["%ss" % FAKE_RESOURCE_NAME]

        self.patcher = mock.patch.object(neutron.policy,
                                         'init',
                                         new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(remove_fake_resource)
        self.context = context.Context('fake', 'fake', roles=['user'])
        plugin_klass = importutils.import_class(
            "neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch('neutron.manager.NeutronManager')
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
Ejemplo n.º 11
0
    def __init__(self, app, conf, **local_conf):
        cfg.CONF.register_opts(self.opts)

        # Determine the context class to use
        self.ctxcls = RequestContext
        if 'context_class' in local_conf:
            self.ctxcls = importutils.import_class(local_conf['context_class'])

        super(ContextMiddleware, self).__init__(app)
Ejemplo n.º 12
0
    def __init__(self, app, conf, **local_conf):
        cfg.CONF.register_opts(self.opts)

        # Determine the context class to use
        self.ctxcls = RequestContext
        if 'context_class' in local_conf:
            self.ctxcls = importutils.import_class(local_conf['context_class'])

        super(ContextMiddleware, self).__init__(app)
 def _load_plugin(self, plugin_provider):
     LOG.debug(_("Plugin location: %s"), plugin_provider)
     try:
         plugin = importutils.import_class(plugin_provider)
         return plugin()
     except ImportError:
         with excutils.save_and_reraise_exception():
             LOG.exception(_('Load plugin error: %(provider)s'),
                           provider=plugin_provider)
Ejemplo n.º 14
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        # Add a Fake 'something' resource to RESOURCE_ATTRIBUTE_MAP
        attributes.RESOURCE_ATTRIBUTE_MAP.update(FAKE_RESOURCE)
        self.rules = dict((k, common_policy.parse_rule(v)) for k, v in {
            "context_is_admin": "role:admin",
            "admin_or_network_owner": "rule:context_is_admin or "
                                      "tenant_id:%(network:tenant_id)s",
            "admin_or_owner": ("rule:context_is_admin or "
                               "tenant_id:%(tenant_id)s"),
            "admin_only": "rule:context_is_admin",
            "regular_user": "******",
            "shared": "field:networks:shared=True",
            "external": "field:networks:router:external=True",
            "default": '@',

            "create_network": "rule:admin_or_owner",
            "create_network:shared": "rule:admin_only",
            "update_network": '@',
            "update_network:shared": "rule:admin_only",

            "get_network": "rule:admin_or_owner or "
                           "rule:shared or "
                           "rule:external",
            "create_port:mac": "rule:admin_or_network_owner",
            "create_something": "rule:admin_or_owner",
            "create_something:attr": "rule:admin_or_owner",
            "create_something:attr:sub_attr_1": "rule:admin_or_owner",
            "create_something:attr:sub_attr_2": "rule:admin_only"
        }.items())

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        def remove_fake_resource():
            del attributes.RESOURCE_ATTRIBUTE_MAP["%ss" % FAKE_RESOURCE_NAME]

        self.patcher = mock.patch.object(neutron.policy,
                                         'init',
                                         new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(self.patcher.stop)
        self.addCleanup(remove_fake_resource)
        self.context = context.Context('fake', 'fake', roles=['user'])
        plugin_klass = importutils.import_class(
            "neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch('neutron.manager.NeutronManager')
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
        self.addCleanup(self.manager_patcher.stop)
Ejemplo n.º 15
0
    def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 *args, **kwargs):

        self.binary = binary
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.manager = manager_class(host=host, *args, **kwargs)
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []
        super(Service, self).__init__(host, topic, manager=self.manager)
Ejemplo n.º 16
0
    def __init__(self, host=None):
        super(DhcpAgent, self).__init__(host=host)
        self.needs_resync = False
        self.conf = cfg.CONF
        self.cache = NetworkCache()
        self.root_helper = config.get_root_helper(self.conf)
        self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
        ctx = context.get_admin_context_without_session()
        self.plugin_rpc = DhcpPluginApi(topics.PLUGIN, ctx)
        self.device_manager = DeviceManager(self.conf, self.plugin_rpc)
        self.lease_relay = DhcpLeaseRelay(self.update_lease)

        self.dhcp_version = self.dhcp_driver_cls.check_version()
        self._populate_networks_cache()
    def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 *args, **kwargs):

        self.binary = binary
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.manager = manager_class(host=host, *args, **kwargs)
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []
        super(Service, self).__init__(host, topic, manager=self.manager)
Ejemplo n.º 18
0
 def _get_plugin_instance(self, namespace, plugin_provider):
     try:
         # Try to resolve plugin by name
         mgr = driver.DriverManager(namespace, plugin_provider)
         plugin_class = mgr.driver
     except RuntimeError as e1:
         # fallback to class name
         try:
             plugin_class = importutils.import_class(plugin_provider)
         except ImportError as e2:
             LOG.exception(_("Error loading plugin by name, %s"), e1)
             LOG.exception(_("Error loading plugin by class, %s"), e2)
             raise ImportError(_("Plugin not found."))
     return plugin_class()
Ejemplo n.º 19
0
    def __init__(self, host=None):
        super(DhcpAgent, self).__init__(host=host)
        self.needs_resync = False
        self.conf = cfg.CONF
        self.cache = NetworkCache()
        self.root_helper = config.get_root_helper(self.conf)
        self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
        ctx = context.get_admin_context_without_session()
        self.plugin_rpc = DhcpPluginApi(topics.PLUGIN, ctx)
        self.device_manager = DeviceManager(self.conf, self.plugin_rpc)
        self.lease_relay = DhcpLeaseRelay(self.update_lease)

        self.dhcp_version = self.dhcp_driver_cls.check_version()
        self._populate_networks_cache()
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        # If multiple class specified for same extension, last one will win
        # according to DictOpt behavior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class:
                    LOG.error(_('Malformed contrail extension...'))
                    continue
                self.supported_extension_aliases.append(ext_name)
                if ext_class == 'None':
                    continue
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                for method in dir(ext_instance):
                    for prefix in ['get', 'update', 'delete', 'create']:
                        if method.startswith('%s_' % prefix):
                            setattr(self, method,
                                    ext_instance.__getattribute__(method))
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                # Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(
                    ext_name=ext_name, ext_class=ext_class)

        #keystone
        self._authn_token = None
        if cfg.CONF.auth_strategy == 'keystone':
            kcfg = cfg.CONF.keystone_authtoken
            body = '{"auth":{"passwordCredentials":{'
            body += ' "username": "******",' % (kcfg.admin_user)
            body += ' "password": "******"},' % (kcfg.admin_password)
            body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)

            self._authn_body = body
            self._authn_token = cfg.CONF.keystone_authtoken.admin_token
            self._keystone_url = "%s://%s:%s%s" % (
                cfg.CONF.keystone_authtoken.auth_protocol,
                cfg.CONF.keystone_authtoken.auth_host,
                cfg.CONF.keystone_authtoken.auth_port,
                "/v2.0/tokens")
Ejemplo n.º 21
0
 def _get_plugin_instance(self, namespace, plugin_provider):
     try:
         # Try to resolve plugin by name
         mgr = driver.DriverManager(namespace, plugin_provider)
         plugin_class = mgr.driver
     except RuntimeError as e1:
         # fallback to class name
         try:
             plugin_class = importutils.import_class(plugin_provider)
         except ImportError as e2:
             LOG.exception(_("Error loading plugin by name, %s"), e1)
             LOG.exception(_("Error loading plugin by class, %s"), e2)
             raise ImportError(_("Plugin not found."))
     return plugin_class()
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        self._contrail_extensions_instances = []
        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        #If multiple class specified for same extension, last one will win
        #according to DictOpt beheivior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class:
                    LOG.error(_('Malformed contrail extension...'))
                    continue
                self.supported_extension_aliases.append(ext_name)
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                self._contrail_extensions_instances.append(ext_instance)
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                #Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(
                    ext_name=ext_name, ext_class=ext_class)

        self._multi_tenancy = cfg.CONF.APISERVER.multi_tenancy
        self._max_retries = cfg.CONF.APISERVER.max_retries
        self._retry_interval = cfg.CONF.APISERVER.retry_interval

        #keystone
        self._authn_token = None
        if cfg.CONF.auth_strategy == 'keystone':
            kcfg = cfg.CONF.keystone_authtoken
            body = '{"auth":{"passwordCredentials":{'
            body += ' "username": "******",' % (kcfg.admin_user)
            body += ' "password": "******"},' % (kcfg.admin_password)
            body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)

            self._authn_body = body
            self._authn_token = cfg.CONF.keystone_authtoken.admin_token
            self._keystone_url = "%s://%s:%s%s" % (
                cfg.CONF.keystone_authtoken.auth_protocol,
                cfg.CONF.keystone_authtoken.auth_host,
                cfg.CONF.keystone_authtoken.auth_port,
                "/v2.0/tokens")
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        # If multiple class specified for same extension, last one will win
        # according to DictOpt behavior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class:
                    LOG.error(_('Malformed contrail extension...'))
                    continue
                self.supported_extension_aliases.append(ext_name)
                if ext_class == 'None':
                    continue
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                for method in dir(ext_instance):
                    for prefix in ['get', 'update', 'delete', 'create']:
                        if method.startswith('%s_' % prefix):
                            setattr(self, method,
                                    ext_instance.__getattribute__(method))
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                # Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(ext_name=ext_name,
                                                    ext_class=ext_class)

        #keystone
        self._authn_token = None
        if cfg.CONF.auth_strategy == 'keystone':
            kcfg = cfg.CONF.keystone_authtoken
            body = '{"auth":{"passwordCredentials":{'
            body += ' "username": "******",' % (kcfg.admin_user)
            body += ' "password": "******"},' % (kcfg.admin_password)
            body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)

            self._authn_body = body
            self._authn_token = cfg.CONF.keystone_authtoken.admin_token
            self._keystone_url = "%s://%s:%s%s" % (
                cfg.CONF.keystone_authtoken.auth_protocol,
                cfg.CONF.keystone_authtoken.auth_host,
                cfg.CONF.keystone_authtoken.auth_port, "/v2.0/tokens")
Ejemplo n.º 24
0
 def __init__(self, host=None):
     super(DhcpAgent, self).__init__(host=host)
     self.needs_resync = False
     self.conf = cfg.CONF
     self.cache = NetworkCache()
     self.root_helper = config.get_root_helper(self.conf)
     self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
     ctx = context.get_admin_context_without_session()
     self.plugin_rpc = DhcpPluginApi(topics.PLUGIN, ctx, self.conf.use_namespaces)
     # create dhcp dir to store dhcp info
     dhcp_dir = os.path.dirname("/%s/dhcp/" % self.conf.state_path)
     if not os.path.isdir(dhcp_dir):
         os.makedirs(dhcp_dir, 0o755)
     self.dhcp_version = self.dhcp_driver_cls.check_version()
     self._populate_networks_cache()
Ejemplo n.º 25
0
    def _parse_class_args(self):
        """Parse the contrailplugin.ini file.

        Opencontrail supports extension such as ipam, policy, these extensions
        can be configured in the plugin configuration file as shown below.
        Plugin then loads the specified extensions.
        contrail_extensions=ipam:<classpath>,policy:<classpath>
        """

        self._contrail_extensions_instances = []
        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
        #If multiple class specified for same extension, last one will win
        #according to DictOpt beheivior
        for ext_name, ext_class in contrail_extensions.items():
            try:
                if not ext_class:
                    LOG.error(_('Malformed contrail extension...'))
                    continue
                self.supported_extension_aliases.append(ext_name)
                ext_class = importutils.import_class(ext_class)
                ext_instance = ext_class()
                ext_instance.set_core(self)
                self._contrail_extensions_instances.append(ext_instance)
            except Exception:
                LOG.exception(_("Contrail Backend Error"))
                #Converting contrail backend error to Neutron Exception
                raise InvalidContrailExtensionError(ext_name=ext_name,
                                                    ext_class=ext_class)

        self._multi_tenancy = cfg.CONF.APISERVER.multi_tenancy
        self._max_retries = cfg.CONF.APISERVER.max_retries
        self._retry_interval = cfg.CONF.APISERVER.retry_interval

        #keystone
        self._authn_token = None
        if cfg.CONF.auth_strategy == 'keystone':
            kcfg = cfg.CONF.keystone_authtoken
            body = '{"auth":{"passwordCredentials":{'
            body += ' "username": "******",' % (kcfg.admin_user)
            body += ' "password": "******"},' % (kcfg.admin_password)
            body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)

            self._authn_body = body
            self._authn_token = cfg.CONF.keystone_authtoken.admin_token
            self._keystone_url = "%s://%s:%s%s" % (
                cfg.CONF.keystone_authtoken.auth_protocol,
                cfg.CONF.keystone_authtoken.auth_host,
                cfg.CONF.keystone_authtoken.auth_port, "/v2.0/tokens")
Ejemplo n.º 26
0
 def __init__(self, host=None):
     super(DhcpAgent, self).__init__(host=host)
     self.needs_resync = False
     self.conf = cfg.CONF
     self.cache = NetworkCache()
     self.root_helper = config.get_root_helper(self.conf)
     self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
     ctx = context.get_admin_context_without_session()
     self.plugin_rpc = DhcpPluginApi(topics.PLUGIN, ctx,
                                     self.conf.use_namespaces)
     # create dhcp dir to store dhcp info
     dhcp_dir = os.path.dirname("/%s/dhcp/" % self.conf.state_path)
     if not os.path.isdir(dhcp_dir):
         os.makedirs(dhcp_dir, 0o755)
     self.dhcp_version = self.dhcp_driver_cls.check_version()
     self._populate_networks_cache()
Ejemplo n.º 27
0
    def _load_service_plugins(self):
        """Loads service plugins.

        Starts from the core plugin and checks if it supports
        advanced services then loads classes provided in configuration.
        """
        # load services from the core plugin first
        self._load_services_from_core_plugin()

        plugin_providers = cfg.CONF.service_plugins
        LOG.debug(_("Loading service plugins: %s"), plugin_providers)
        for provider in plugin_providers:
            if provider == '':
                continue
            try:
                LOG.info(_("Loading Plugin: %s"), provider)
                plugin_class = importutils.import_class(provider)
            except ImportError:
                LOG.exception(_("Error loading plugin"))
                raise ImportError(_("Plugin not found."))
            plugin_inst = plugin_class()

            # only one implementation of svc_type allowed
            # specifying more than one plugin
            # for the same type is a fatal exception
            if plugin_inst.get_plugin_type() in self.service_plugins:
                raise ValueError(_("Multiple plugins for service "
                                   "%s were configured"),
                                 plugin_inst.get_plugin_type())

            self.service_plugins[plugin_inst.get_plugin_type()] = plugin_inst

            # search for possible agent notifiers declared in service plugin
            # (needed by agent management extension)
            if (hasattr(self.plugin, 'agent_notifiers') and
                    hasattr(plugin_inst, 'agent_notifiers')):
                self.plugin.agent_notifiers.update(plugin_inst.agent_notifiers)

            LOG.debug(_("Successfully loaded %(type)s plugin. "
                        "Description: %(desc)s"),
                      {"type": plugin_inst.get_plugin_type(),
                       "desc": plugin_inst.get_plugin_description()})
Ejemplo n.º 28
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        self.rules = dict(
            (k, common_policy.parse_rule(v))
            for k, v in {
                "context_is_admin": "role:admin",
                "admin_or_network_owner": "rule:context_is_admin or " "tenant_id:%(network:tenant_id)s",
                "admin_or_owner": ("rule:context_is_admin or " "tenant_id:%(tenant_id)s"),
                "admin_only": "rule:context_is_admin",
                "regular_user": "******",
                "shared": "field:networks:shared=True",
                "external": "field:networks:router:external=True",
                "default": "@",
                "create_network": "rule:admin_or_owner",
                "create_network:shared": "rule:admin_only",
                "update_network": "@",
                "update_network:shared": "rule:admin_only",
                "get_network": "rule:admin_or_owner or " "rule:shared or " "rule:external",
                "create_port:mac": "rule:admin_or_network_owner",
            }.items()
        )

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        self.patcher = mock.patch.object(neutron.policy, "init", new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(self.patcher.stop)
        self.context = context.Context("fake", "fake", roles=["user"])
        plugin_klass = importutils.import_class("neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch("neutron.manager.NeutronManager")
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
        self.addCleanup(self.manager_patcher.stop)
Ejemplo n.º 29
0
def load_driver(plugin, ofc_manager):

    if PROVIDER_OPENFLOW in ROUTER_DRIVER_MAP and not ofc_manager.driver.router_supported:
        LOG.warning(
            _(
                "OFC does not support router with provider=%(provider)s, "
                "so removed it from supported provider "
                "(new router driver map=%(driver_map)s)"
            ),
            {"provider": PROVIDER_OPENFLOW, "driver_map": ROUTER_DRIVER_MAP},
        )
        del ROUTER_DRIVER_MAP[PROVIDER_OPENFLOW]

    if config.PROVIDER.default_router_provider not in ROUTER_DRIVER_MAP:
        LOG.error(
            _("default_router_provider %(default)s is supported! " "Please specify one of %(supported)s"),
            {"default": config.PROVIDER.default_router_provider, "supported": ROUTER_DRIVER_MAP.keys()},
        )
        raise SystemExit(1)

    enabled_providers = set(config.PROVIDER.router_providers + [config.PROVIDER.default_router_provider]) & set(
        ROUTER_DRIVER_MAP.keys()
    )

    for driver in enabled_providers:
        driver_klass = importutils.import_class(ROUTER_DRIVER_MAP[driver])
        ROUTER_DRIVERS[driver] = driver_klass(plugin, ofc_manager)

    LOG.info(_("Enabled router drivers: %s"), ROUTER_DRIVERS.keys())

    if not ROUTER_DRIVERS:
        LOG.error(
            _(
                "No router provider is enabled. neutron-server terminated!"
                " (supported=%(supported)s, configured=%(config)s)"
            ),
            {"supported": ROUTER_DRIVER_MAP.keys(), "config": config.PROVIDER.router_providers},
        )
        raise SystemExit(1)
Ejemplo n.º 30
0
    def __init__(self, options=None, config_file=None):
        # If no options have been provided, create an empty dict
        if not options:
            options = {}

        msg = validate_pre_plugin_load()
        if msg:
            LOG.critical(msg)
            raise Exception(msg)

        # NOTE(jkoelker) Testing for the subclass with the __subclasshook__
        #                breaks tach monitoring. It has been removed
        #                intentianally to allow v2 plugins to be monitored
        #                for performance metrics.
        plugin_provider = cfg.CONF.core_plugin
        LOG.debug(_("Plugin location: %s"), plugin_provider)
        # If the plugin can't be found let them know gracefully
        try:
            LOG.info(_("Loading Plugin: %s"), plugin_provider)
            plugin_klass = importutils.import_class(plugin_provider)
        except ImportError:
            LOG.exception(_("Error loading plugin"))
            raise Exception(_("Plugin not found. "))
        legacy.modernize_quantum_config(cfg.CONF)
        self.plugin = plugin_klass()

        msg = validate_post_plugin_load()
        if msg:
            LOG.critical(msg)
            raise Exception(msg)

        # core plugin as a part of plugin collection simplifies
        # checking extensions
        # TODO(enikanorov): make core plugin the same as
        # the rest of service plugins
        self.service_plugins = {constants.CORE: self.plugin}
        self._load_service_plugins()
Ejemplo n.º 31
0
def Nova_API():

    cls = importutils.import_class(cfg.CONF.nova_api_class)
    return cls()
Ejemplo n.º 32
0
 def _load_plugin(self, plugin_provider):
     LOG.debug(_("Plugin location: %s"), plugin_provider)
     plugin_klass = importutils.import_class(plugin_provider)
     return plugin_klass()
Ejemplo n.º 33
0
 def _load_plugin(self, plugin_provider):
     LOG.debug(_("Plugin location: %s"), plugin_provider)
     plugin_klass = importutils.import_class(plugin_provider)
     return plugin_klass()
Ejemplo n.º 34
0
#    License for the specific language governing permissions and limitations
#    under the License.

import sys

from oslo.config import cfg

from neutron.agent.common import config
from neutron.agent.linux import interface
from neutron.debug import debug_agent
from neutron.openstack.common import importutils
from neutronclient.common import exceptions as exc
from neutronclient import shell

COMMAND_V2 = {
    'probe-create': importutils.import_class(
        'neutron.debug.commands.CreateProbe'),
    'probe-delete': importutils.import_class(
        'neutron.debug.commands.DeleteProbe'),
    'probe-list': importutils.import_class(
        'neutron.debug.commands.ListProbe'),
    'probe-clear': importutils.import_class(
        'neutron.debug.commands.ClearProbe'),
    'probe-exec': importutils.import_class(
        'neutron.debug.commands.ExecProbe'),
    'ping-all': importutils.import_class(
        'neutron.debug.commands.PingAll'),
    #TODO(nati)  ping, netcat , nmap, bench
}
COMMANDS = {'2.0': COMMAND_V2}

Ejemplo n.º 35
0
from neutron.common import exceptions
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
from neutron.openstack.common import uuidutils
from neutron import quota
from oslo.config import cfg

from quark.db import api as db_api
from quark import plugin_views as v
from quark import utils

CONF = cfg.CONF
LOG = logging.getLogger("neutron.quark")

ipam_driver = (importutils.import_class(CONF.QUARK.ipam_driver))()
net_driver = (importutils.import_class(CONF.QUARK.net_driver))()
net_driver.load_config()


def create_port(context, port):
    """Create a port

    Create a port which is a connection point of a device (e.g., a VM
    NIC) to attach to a L2 Neutron network.
    : param context: neutron api request context
    : param port: dictionary describing the port, with keys
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.  All keys will be populated.
    """
    LOG.info("create_port for tenant %s" % context.tenant_id)
Ejemplo n.º 36
0
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
from neutron.openstack.common import uuidutils
from neutron import quota
from oslo.config import cfg

from quark.db import api as db_api
from quark import plugin_views as v


CONF = cfg.CONF
LOG = logging.getLogger("neutron.quark")
DEFAULT_SG_UUID = "00000000-0000-0000-0000-000000000000"


net_driver = (importutils.import_class(CONF.QUARK.net_driver))()
net_driver.load_config()


def _validate_security_group_rule(context, rule):
    PROTOCOLS = {"icmp": 1, "tcp": 6, "udp": 17}
    ALLOWED_WITH_RANGE = [6, 17]

    if rule.get("remote_ip_prefix") and rule.get("remote_group_id"):
        raise sg_ext.SecurityGroupRemoteGroupAndRemoteIpPrefix()

    protocol = rule.pop('protocol')
    port_range_min = rule['port_range_min']
    port_range_max = rule['port_range_max']

    if protocol:
Ejemplo n.º 37
0
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
neutron_config = config.neutron_config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
logging_config.fileConfig(config.config_file_name)

plugin_class_path = neutron_config.core_plugin
active_plugins = [plugin_class_path]
active_plugins += neutron_config.service_plugins

for class_path in active_plugins:
    importutils.import_class(class_path)

# set the target for 'autogenerate' support
target_metadata = model_base.BASEV2.metadata


def set_mysql_engine():
    try:
        mysql_engine = neutron_config.command.mysql_engine
    except cfg.NoSuchOptError:
        mysql_engine = None

    global MYSQL_ENGINE
    MYSQL_ENGINE = (mysql_engine or
                    model_base.BASEV2.__table_args__['mysql_engine'])
Ejemplo n.º 38
0
def Nova_API():

    cls = importutils.import_class(cfg.CONF.nova_api_class)
    return cls()
Ejemplo n.º 39
0
DATABASE_QUOTA_DRIVER = 'neutron.extensions._quotav2_driver.DbQuotaDriver'

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
neutron_config = config.neutron_config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

plugin_class_path = neutron_config.core_plugin
active_plugins = [plugin_class_path]
active_plugins += neutron_config.service_plugins

plugin_klass = importutils.import_class(plugin_class_path)

# set the target for 'autogenerate' support
target_metadata = model_base.BASEV2.metadata


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.
 def _load_driver(self, driver_provider):
     LOG.debug(_("Driver location: %s"), driver_provider)
     plugin_klass = importutils.import_class(driver_provider)
     return plugin_klass(self.conf)
Ejemplo n.º 41
0
#    under the License.

import sys

from oslo.config import cfg

from neutron.agent.common import config
from neutron.agent.linux import interface
from neutron.debug import debug_agent
from neutron.openstack.common import importutils
from neutronclient.common import exceptions as exc
from neutronclient import shell

COMMAND_V2 = {
    'probe-create':
    importutils.import_class('neutron.debug.commands.CreateProbe'),
    'probe-delete':
    importutils.import_class('neutron.debug.commands.DeleteProbe'),
    'probe-list': importutils.import_class('neutron.debug.commands.ListProbe'),
    'probe-clear':
    importutils.import_class('neutron.debug.commands.ClearProbe'),
    'probe-exec': importutils.import_class('neutron.debug.commands.ExecProbe'),
    'ping-all': importutils.import_class('neutron.debug.commands.PingAll'),
    #TODO(nati)  ping, netcat , nmap, bench
}
COMMANDS = {'2.0': COMMAND_V2}


class NeutronDebugShell(shell.NeutronShell):
    def __init__(self, api_version):
        super(NeutronDebugShell, self).__init__(api_version)
Ejemplo n.º 42
0
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
neutron_config = config.neutron_config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
logging_config.fileConfig(config.config_file_name)

plugin_class_path = neutron_config.core_plugin
active_plugins = [plugin_class_path]
active_plugins += neutron_config.service_plugins

for class_path in active_plugins:
    importutils.import_class(class_path)

# set the target for 'autogenerate' support
target_metadata = model_base.BASEV2.metadata


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with either a URL
    or an Engine.

    Calls to context.execute() here emit the given string to the
    script output.

    """
Ejemplo n.º 43
0
 def _load_driver(self, driver_provider):
     LOG.debug(_("Driver location: %s"), driver_provider)
     plugin_klass = importutils.import_class(driver_provider)
     return plugin_klass(self.conf)
 def __init__(self):
     self.policy_driver = import_class(CONF.niblick.policy_driver)()
Ejemplo n.º 45
0

DATABASE_QUOTA_DRIVER = "neutron.extensions._quotav2_driver.DbQuotaDriver"

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
neutron_config = config.neutron_config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

plugin_class_path = neutron_config.core_plugin

plugin_klass = importutils.import_class(plugin_class_path)

# set the target for 'autogenerate' support
target_metadata = model_base.BASEV2.metadata


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.
Ejemplo n.º 46
0
def get_driver(driver_name):
    LOG.info(_("Loading OFC driver: %s"), driver_name)
    driver_klass = DRIVER_LIST.get(driver_name) or driver_name
    return importutils.import_class(driver_klass)
Ejemplo n.º 47
0
from neutron.openstack.common import timeutils
from oslo.config import cfg

from quark.db import api as db_api
from quark.db import models as models
from quark import exceptions as q_exc
from quark import network_strategy
from quark.plugin_modules import routes
from quark import plugin_views as v
from quark import utils

CONF = cfg.CONF
LOG = logging.getLogger(__name__)
STRATEGY = network_strategy.STRATEGY

ipam_driver = (importutils.import_class(CONF.QUARK.ipam_driver))()


def _validate_subnet_cidr(context, network_id, new_subnet_cidr):
    """Validate the CIDR for a subnet.

    Verifies the specified CIDR does not overlap with the ones defined
    for the other subnets specified for this network, or with any other
    CIDR if overlapping IPs are disabled.

    """
    if neutron_cfg.cfg.CONF.allow_overlapping_ips:
        return

    new_subnet_ipset = netaddr.IPSet([new_subnet_cidr])
Ejemplo n.º 48
0
def get_driver(driver_name):
    LOG.info(_("Loading OFC driver: %s"), driver_name)
    driver_klass = DRIVER_LIST.get(driver_name) or driver_name
    return importutils.import_class(driver_klass)