def __init__(self,
                 host=None,
                 port=None,
                 use_ssl=True,
                 auth=None,
                 umf_api_version=UMF_API_VERSION):
        """Creates a new client to some NWA.

        :param host: The host where service resides
        :param port: The port where service resides
        :param use_ssl: True to use SSL, False to use HTTP
        :param: auth: function to generate Authorization header.
        """
        self.host = host
        self.port = port
        self.use_ssl = use_ssl
        self.auth = auth
        self.umf_api_version = umf_api_version

        LOG.info(
            _LI('NWA init: host=%(host)s port=%(port)s use_ssl=%(use_ssl)s '
                'auth=%(auth)s'), {
                    'host': self.host,
                    'port': self.port,
                    'use_ssl': self.use_ssl,
                    'auth': self.auth
                })
        LOG.info(_LI('NWA init: umf api version: %s'), self.umf_api_version)
    def create_tenant_rpc_server(self, tid):
        """create_ blocking rpc server

        @param tid: openstack tenant id
        """
        ret = {}

        if tid in self.rpc_servers:
            LOG.warning(
                _LW("already in message queue and server. queue=%s"),
                self.rpc_servers[tid]['topic']
            )
            return {'result': 'FAILED'}

        topic = "%s-%s" % (self.topic, tid)

        target = Target(
            topic=topic, server=cfg.CONF.host, fanout=False)

        assert n_rpc.TRANSPORT is not None
        serializer = n_rpc.RequestContextSerializer(None)

        server = get_rpc_server(
            n_rpc.TRANSPORT, target,
            self.agent_top.endpoints,
            'blocking', serializer
        )

        LOG.debug("RPCServer create: topic=%s", topic)
        if self.greenpool.free() < 1:
            self.greenpool_size += nwa_const.NWA_GREENPOOL_ADD_SIZE
            self.greenpool.resize(self.greenpool_size)
            LOG.info(_LI('RPCServer greenpool resize %s'), self.greenpool_size)

        def server_start():
            while True:
                try:
                    LOG.debug('RPCServer thread %d start %s',
                              (self.greenpool.running(), server))
                    server.start()
                    LOG.debug('RPCServer thread end %s', server)
                    break
                except Exception as e:
                    LOG.exception(_LE('RPCServer thread start failed: %s'), e)

        self.rpc_servers[tid] = {
            'thread': self.greenpool.spawn(server_start),
            'server': server,
            'topic': topic
        }
        eventlet.sleep(0)
        LOG.info(_LI('RPCServer started: %(topic)s server=%(server)s'),
                 {'topic': topic, 'server': server})

        ret['result'] = 'SUCCESS'
        ret['tenant_id'] = tid
        ret['topic'] = topic

        return ret
Example #3
0
    def create_tenant_rpc_server(self, tid):
        """create_ blocking rpc server

        @param tid: openstack tenant id
        """
        ret = {}

        if tid in self.rpc_servers:
            LOG.warning(_LW("already in message queue and server. queue=%s"),
                        self.rpc_servers[tid]['topic'])
            return {'result': 'FAILED'}

        topic = "%s-%s" % (self.topic, tid)

        target = Target(topic=topic, server=cfg.CONF.host, fanout=False)

        assert n_rpc.TRANSPORT is not None
        serializer = n_rpc.RequestContextSerializer(None)

        server = get_rpc_server(n_rpc.TRANSPORT, target,
                                self.agent_top.endpoints, 'blocking',
                                serializer)

        LOG.debug("RPCServer create: topic=%s", topic)
        if self.greenpool.free() < 1:
            self.greenpool_size += nwa_const.NWA_GREENPOOL_ADD_SIZE
            self.greenpool.resize(self.greenpool_size)
            LOG.info(_LI('RPCServer greenpool resize %s'), self.greenpool_size)

        def server_start():
            while True:
                try:
                    LOG.debug('RPCServer thread %d start %s',
                              (self.greenpool.running(), server))
                    server.start()
                    LOG.debug('RPCServer thread end %s', server)
                    break
                except Exception as e:
                    LOG.exception(_LE('RPCServer thread start failed: %s'), e)

        self.rpc_servers[tid] = {
            'thread': self.greenpool.spawn(server_start),
            'server': server,
            'topic': topic
        }
        eventlet.sleep(0)
        LOG.info(_LI('RPCServer started: %(topic)s server=%(server)s'), {
            'topic': topic,
            'server': server
        })

        ret['result'] = 'SUCCESS'
        ret['tenant_id'] = tid
        ret['topic'] = topic

        return ret
Example #4
0
    def setup_rpc(self):
        self.host = socket.gethostname()
        self.agent_id = 'nec-q-agent.%s' % self.host
        LOG.info(_LI("RPC agent_id: %s"), self.agent_id)

        self.topic = topics.AGENT
        self.context = q_context.get_admin_context_without_session()

        self.plugin_rpc = NECPluginApi(topics.PLUGIN)
        self.state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
        self.sg_plugin_rpc = sg_rpc.SecurityGroupServerRpcApi(topics.PLUGIN)
        self.sg_agent = sg_rpc.SecurityGroupAgentRpc(self.context,
                                                     self.sg_plugin_rpc)

        # RPC network init
        # Handle updates from service
        self.callback_nec = NECAgentRpcCallback(self.context,
                                                self, self.sg_agent)
        self.callback_sg = SecurityGroupAgentRpcCallback(self.context,
                                                         self.sg_agent)
        self.endpoints = [self.callback_nec, self.callback_sg]
        # Define the listening consumer for the agent
        consumers = [[topics.PORT, topics.UPDATE],
                     [topics.SECURITY_GROUP, topics.UPDATE]]
        self.connection = agent_rpc.create_consumers(self.endpoints,
                                                     self.topic,
                                                     consumers)

        report_interval = cfg.CONF.AGENT.report_interval
        if report_interval:
            heartbeat = loopingcall.FixedIntervalLoopingCall(
                self._report_state)
            heartbeat.start(interval=report_interval)
    def _delete_nat(self, context, fip):
        if not fip['router_id'] or not fip['fixed_ip_address']:
            LOG.debug('already deleted %s', fip)
            return
        tenant_id = nwa_l3_db.get_tenant_id_by_router(
            context.session, fip['router_id']
        )
        nwa_tenant_id = nwa_com_utils.get_nwa_tenant_id(tenant_id)

        fl_data = {
            'floating_ip_address': fip['floating_ip_address'],
            'fixed_ip_address': fip['fixed_ip_address'],
            'id': fip['id'],
            'device_id': fip['router_id'],
            'floating_network_id': fip['floating_network_id'],
            'tenant_id': fip['tenant_id']
        }
        LOG.info(_LI('delete_nat fl_data=%s'), fl_data)

        proxy = self._get_nwa_proxy(self, tenant_id)
        proxy.delete_nat(
            context, tenant_id=tenant_id,
            nwa_tenant_id=nwa_tenant_id,
            floating=fl_data
        )
 def get_tenant_semaphore(cls, tenant_id):
     if not isinstance(tenant_id, six.string_types) or tenant_id == '':
         raise TypeError('%s is not a string' % tenant_id)
     with Semaphore.lock:
         if tenant_id not in Semaphore.tenants:
             LOG.info(_LI('create semaphore for %s'), tenant_id)
             Semaphore.tenants[tenant_id] = Semaphore()
         return Semaphore.tenants[tenant_id]
 def get_tenant_semaphore(cls, tenant_id):
     if not isinstance(tenant_id, six.string_types) or tenant_id == '':
         raise TypeError('%s is not a string' % tenant_id)
     with Semaphore.lock:
         if tenant_id not in Semaphore.tenants:
             LOG.info(_LI('create semaphore for %s'), tenant_id)
             Semaphore.tenants[tenant_id] = Semaphore()
         return Semaphore.tenants[tenant_id]
    def update_tenant_rpc_servers(self, rpc_context, **kwargs):
        session = db_api.get_session()

        with session.begin(subtransactions=True):
            q_tids = [q.tenant_id
                      for q in necnwa_api.get_nwa_tenant_queues(session)]
        plugin = manager.NeutronManager.get_plugin()
        tenant_ids = [server['tenant_id'] for server in kwargs['servers']]
        ret = []
        for tenant_id in set(q_tids) - set(tenant_ids):
            LOG.info(_LI("RPCServer only db tid=%s, send create_server"),
                     tenant_id)
            plugin.nwa_rpc.create_server(rpc_context, tenant_id)
            ret.append({'tenant_id': tenant_id})
        for tenant_id in set(tenant_ids) - set(q_tids):
            LOG.info(_LI("RPCServer only agent tid=%s, send delete_server"),
                     tenant_id)
            plugin.nwa_rpc.delete_server(rpc_context, tenant_id)
        return {'servers': ret}
Example #9
0
 def update_ports(self, context, agent_id, datapath_id,
                  port_added, port_removed):
     """RPC to update information of ports on Neutron Server."""
     LOG.info(_LI("Update ports: added=%(added)s, "
                  "removed=%(removed)s"),
              {'added': port_added, 'removed': port_removed})
     cctxt = self.client.prepare()
     return cctxt.call(context, 'update_ports',
                       agent_id=agent_id,
                       datapath_id=datapath_id,
                       port_added=port_added,
                       port_removed=port_removed)
Example #10
0
    def do_single_request(self, method, action, body=None):
        action = cfg.CONF.OFC.path_prefix + action
        LOG.debug("Client request: %(host)s:%(port)s "
                  "%(method)s %(action)s [%(body)s]",
                  {'host': self.host, 'port': self.port,
                   'method': method, 'action': action, 'body': body})
        if isinstance(body, dict):
            body = jsonutils.dumps(body)
        try:
            res = self._get_response(method, action, body)
            data = res.text
            LOG.debug("OFC returns [%(status)s:%(data)s]",
                      {'status': res.status_code,
                       'data': data})

            # Try to decode JSON data if possible.
            try:
                data = jsonutils.loads(data)
            except (ValueError, TypeError):
                pass

            if res.status_code in (requests.codes.OK,
                                   requests.codes.CREATED,
                                   requests.codes.ACCEPTED,
                                   requests.codes.NO_CONTENT):
                return data
            elif res.status_code == requests.codes.SERVICE_UNAVAILABLE:
                retry_after = res.headers.get('retry-after')
                LOG.warning(_LW("OFC returns ServiceUnavailable "
                                "(retry-after=%s)"), retry_after)
                raise nexc.OFCServiceUnavailable(retry_after=retry_after)
            elif res.status_code == requests.codes.NOT_FOUND:
                LOG.info(_LI("Specified resource %s does not exist on OFC "),
                         action)
                raise nexc.OFCResourceNotFound(resource=action)
            else:
                LOG.warning(_LW("Operation on OFC failed: "
                                "status=%(status)s, detail=%(detail)s"),
                            {'status': res.status_code, 'detail': data})
                params = {'reason': _("Operation on OFC failed"),
                          'status': res.status_code}
                if isinstance(data, dict):
                    params['err_code'] = data.get('err_code')
                    params['err_msg'] = data.get('err_msg')
                else:
                    params['err_msg'] = data
                raise nexc.OFCException(**params)
        except requests.exceptions.RequestException as e:
            reason = _("Failed to connect OFC : %s") % e
            LOG.error(reason)
            raise nexc.OFCException(reason=reason)
    def _terminate_l2_network(self, context, nwa_data, **kwargs):
        tenant_id = kwargs.get('tenant_id')
        nwa_tenant_id = kwargs.get('nwa_tenant_id')
        nwa_info = kwargs.get('nwa_info')
        network_id = nwa_info['network']['id']

        # port check on segment.
        if check_vlan(network_id, nwa_data):
            raise nwa_exc.AgentProxyException(value=nwa_data)

        # delete vlan
        # raise AgentProxyException if fail
        nwa_data = self._delete_vlan(context, nwa_data=nwa_data, **kwargs)
        # delete vlan end.

        # tenant network check.
        for k in nwa_data:
            if re.match('NW_.*', k):
                raise nwa_exc.AgentProxyException(value=nwa_data)

        LOG.info(_LI("delete_tenant_nw"))
        # raise AgentProxyException if fail
        nwa_data = self._delete_tenant_nw(context, nwa_data=nwa_data, **kwargs)

        # delete tenant
        LOG.info(_LI("delete_tenant"))
        nwa_data = self.proxy_tenant.delete_tenant(
            context,
            nwa_data=nwa_data,
            **kwargs
        )
        # delete tenant end.

        # delete nwa_tenant binding.
        LOG.info(_LI("delete_nwa_tenant_binding"))
        return self.nwa_tenant_rpc.delete_nwa_tenant_binding(
            context, tenant_id, nwa_tenant_id
        )
    def deactivate_port(self, context, port, raise_exc=True):
        """Deactivate port by deleting port from OFC if exists."""
        if not self.ofc.exists_ofc_port(context, port['id']):
            LOG.debug(
                "deactivate_port(): skip, ofc_port for port=%s "
                "does not exist.", port['id'])
            return port

        try:
            self.ofc.delete_ofc_port(context, port['id'], port)
            utils.update_resource_status_if_changed(context,
                                                    "port",
                                                    port,
                                                    const.PORT_STATUS_DOWN,
                                                    ignore_error=True)
            return port
        except (nexc.OFCResourceNotFound, nexc.OFCMappingNotFound):
            # There is a case where multiple delete_port operation are
            # running concurrently. For example, delete_port from
            # release_dhcp_port and deletion of network owned ports in
            # delete_network. In such cases delete_ofc_port may receive
            # 404 error from OFC.
            # Also there is a case where neutron port is deleted
            # between exists_ofc_port and get_ofc_id in delete_ofc_port.
            # In this case OFCMappingNotFound is raised.
            # These two cases are valid situations.
            LOG.info(
                _LI("deactivate_port(): OFC port for port=%s is "
                    "already removed."), port['id'])
            # The port is already removed, so there is no need
            # to update status in the database.
            port['status'] = const.PORT_STATUS_DOWN
            return port
        except nexc.OFCException as exc:
            with excutils.save_and_reraise_exception() as ctxt:
                LOG.error(
                    _LE("Failed to delete port=%(port)s from OFC: "
                        "%(exc)s"), {
                            'port': port['id'],
                            'exc': exc
                        })
                utils.update_resource_status_if_changed(
                    context,
                    "port",
                    port,
                    const.PORT_STATUS_ERROR,
                    ignore_error=True)
                if not raise_exc:
                    ctxt.reraise = False
                    return port
    def __init__(self, host=None, port=None, use_ssl=True, auth=None,
                 umf_api_version=UMF_API_VERSION):
        """Creates a new client to some NWA.

        :param host: The host where service resides
        :param port: The port where service resides
        :param use_ssl: True to use SSL, False to use HTTP
        :param: auth: function to generate Authorization header.
        """
        self.host = host
        self.port = port
        self.use_ssl = use_ssl
        self.auth = auth
        self.umf_api_version = umf_api_version

        LOG.info(
            _LI('NWA init: host=%(host)s port=%(port)s use_ssl=%(use_ssl)s '
                'auth=%(auth)s'),
            {'host': self.host, 'port': self.port, 'use_ssl': self.use_ssl,
             'auth': self.auth}
        )
        LOG.info(_LI('NWA init: umf api version: %s'),
                 self.umf_api_version)
Example #14
0
 def get_nwa_proxy(self, tid, context=None):
     if tid not in self.nwa_proxies:
         self.nwa_proxies[tid] = nwa_proxy_api.NECNWAProxyApi(
             nwa_const.NWA_AGENT_TOPIC, tid)
         if context:
             self._create_nwa_agent_tenant_queue(context, tid)
             nwa_topics = self.get_nwa_topics(context, tid)
             if len(nwa_topics) == 1:
                 LOG.info(_LI('NWA tenant queue: new topic is %s'),
                          str(nwa_topics[0]))
             else:
                 LOG.warning(_LW('NWA tenant queue is not created. tid=%s'),
                             tid)
     LOG.debug('proxy tid=%s', tid)
     return self.nwa_proxies[tid]
    def update_floatingip(self, context, fpid, floatingip):
        port_id_specified = 'port_id' in floatingip['floatingip']
        if not port_id_specified:
            LOG.error(_LE("port_id key is not found in %s"), floatingip)
            raise exc.PortNotFound(port_id=None)

        port_id = floatingip['floatingip'].get('port_id')
        try:
            if port_id_specified and not port_id:
                floating = context.session.query(l3_db.FloatingIP).filter_by(
                    id=fpid).one()
                self._delete_nat(context, floating)
        except sa.orm.exc.NoResultFound:
            raise exc.PortNotFound(port_id=port_id)

        ret = super(NECNWAL3Plugin, self).update_floatingip(
            context, fpid, floatingip)

        try:
            if port_id_specified and port_id:
                floating = context.session.query(l3_db.FloatingIP).filter_by(
                    id=fpid).one()
                tenant_id = nwa_l3_db.get_tenant_id_by_router(
                    context.session,
                    floating['router_id']
                )
                nwa_tenant_id = nwa_com_utils.get_nwa_tenant_id(tenant_id)

                fl_data = {
                    'floating_ip_address': floating['floating_ip_address'],
                    'fixed_ip_address': floating['fixed_ip_address'],
                    'id': fpid, 'device_id': floating['router_id'],
                    'floating_network_id': floating['floating_network_id'],
                    'tenant_id': floating['tenant_id'],
                    'floating_port_id': floating['floating_port_id']
                }
                LOG.info(_LI('setting_nat fl_data is %s'), fl_data)
                proxy = self._get_nwa_proxy(self, tenant_id)
                proxy.setting_nat(
                    context, tenant_id=tenant_id,
                    nwa_tenant_id=nwa_tenant_id,
                    floating=fl_data
                )

        except sa.orm.exc.NoResultFound:
            raise exc.PortNotFound(port_id=port_id)

        return ret
 def get_nwa_proxy(self, tid, context=None):
     if tid not in self.nwa_proxies:
         self.nwa_proxies[tid] = nwa_proxy_api.NECNWAProxyApi(
             nwa_const.NWA_AGENT_TOPIC, tid
         )
         if context:
             self._create_nwa_agent_tenant_queue(context, tid)
             nwa_topics = self.get_nwa_topics(context, tid)
             if len(nwa_topics) == 1:
                 LOG.info(_LI('NWA tenant queue: new topic is %s'),
                          str(nwa_topics[0]))
             else:
                 LOG.warning(_LW('NWA tenant queue is not created. tid=%s'),
                             tid)
     LOG.debug('proxy tid=%s', tid)
     return self.nwa_proxies[tid]
Example #17
0
 def do_request(self, method, action, body=None):
     max_attempts = cfg.CONF.OFC.api_max_attempts
     for i in range(max_attempts, 0, -1):
         try:
             return self.do_single_request(method, action, body)
         except nexc.OFCServiceUnavailable as e:
             with excutils.save_and_reraise_exception() as ctxt:
                 try:
                     wait_time = int(e.retry_after)
                 except (ValueError, TypeError):
                     wait_time = None
                 if i > 1 and wait_time:
                     LOG.info(_LI("Waiting for %s seconds due to "
                                  "OFC Service_Unavailable."), wait_time)
                     time.sleep(wait_time)
                     ctxt.reraise = False
                     continue
def load_driver(plugin, ofc_manager):

    if (PROVIDER_OPENFLOW in ROUTER_DRIVER_MAP
            and not ofc_manager.driver.router_supported):
        LOG.warning(
            _LW('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 cfg.CONF.PROVIDER.default_router_provider not in ROUTER_DRIVER_MAP:
        LOG.error(
            _LE('default_router_provider %(default)s is supported! '
                'Please specify one of %(supported)s'), {
                    'default': cfg.CONF.PROVIDER.default_router_provider,
                    'supported': ROUTER_DRIVER_MAP.keys()
                })
        raise SystemExit(1)

    enabled_providers = (set(cfg.CONF.PROVIDER.router_providers +
                             [cfg.CONF.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(_LI('Enabled router drivers: %s'), ROUTER_DRIVERS.keys())

    if not ROUTER_DRIVERS:
        LOG.error(
            _LE('No router provider is enabled. neutron-server '
                'terminated! (supported=%(supported)s, '
                'configured=%(config)s)'), {
                    'supported': ROUTER_DRIVER_MAP.keys(),
                    'config': cfg.CONF.PROVIDER.router_providers
                })
        raise SystemExit(1)
    def deactivate_port(self, context, port, raise_exc=True):
        """Deactivate port by deleting port from OFC if exists."""
        if not self.ofc.exists_ofc_port(context, port['id']):
            LOG.debug("deactivate_port(): skip, ofc_port for port=%s "
                      "does not exist.", port['id'])
            return port

        try:
            self.ofc.delete_ofc_port(context, port['id'], port)
            utils.update_resource_status_if_changed(
                context, "port", port, const.PORT_STATUS_DOWN,
                ignore_error=True)
            return port
        except (nexc.OFCResourceNotFound, nexc.OFCMappingNotFound):
            # There is a case where multiple delete_port operation are
            # running concurrently. For example, delete_port from
            # release_dhcp_port and deletion of network owned ports in
            # delete_network. In such cases delete_ofc_port may receive
            # 404 error from OFC.
            # Also there is a case where neutron port is deleted
            # between exists_ofc_port and get_ofc_id in delete_ofc_port.
            # In this case OFCMappingNotFound is raised.
            # These two cases are valid situations.
            LOG.info(_LI("deactivate_port(): OFC port for port=%s is "
                         "already removed."), port['id'])
            # The port is already removed, so there is no need
            # to update status in the database.
            port['status'] = const.PORT_STATUS_DOWN
            return port
        except nexc.OFCException as exc:
            with excutils.save_and_reraise_exception() as ctxt:
                LOG.error(_LE("Failed to delete port=%(port)s from OFC: "
                              "%(exc)s"), {'port': port['id'], 'exc': exc})
                utils.update_resource_status_if_changed(
                    context, "port", port, const.PORT_STATUS_ERROR,
                    ignore_error=True)
                if not raise_exc:
                    ctxt.reraise = False
                    return port
def load_driver(plugin, ofc_manager):

    if (PROVIDER_OPENFLOW in ROUTER_DRIVER_MAP and
            not ofc_manager.driver.router_supported):
        LOG.warning(
            _LW('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 cfg.CONF.PROVIDER.default_router_provider not in ROUTER_DRIVER_MAP:
        LOG.error(_LE('default_router_provider %(default)s is supported! '
                      'Please specify one of %(supported)s'),
                  {'default': cfg.CONF.PROVIDER.default_router_provider,
                   'supported': ROUTER_DRIVER_MAP.keys()})
        raise SystemExit(1)

    enabled_providers = (set(cfg.CONF.PROVIDER.router_providers +
                             [cfg.CONF.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(_LI('Enabled router drivers: %s'), ROUTER_DRIVERS.keys())

    if not ROUTER_DRIVERS:
        LOG.error(_LE('No router provider is enabled. neutron-server '
                      'terminated! (supported=%(supported)s, '
                      'configured=%(config)s)'),
                  {'supported': ROUTER_DRIVER_MAP.keys(),
                   'config': cfg.CONF.PROVIDER.router_providers})
        raise SystemExit(1)
 def delete_tenant_semaphore(cls, tenant_id):
     with Semaphore.lock:
         if tenant_id in Semaphore.tenants:
             LOG.info(_LI('delete semaphore for %s'), tenant_id)
             del Semaphore.tenants[tenant_id]
def get_driver(driver_name):
    LOG.info(_LI("Loading OFC driver: %s"), driver_name)
    driver_klass = DRIVER_LIST.get(driver_name) or driver_name
    return importutils.import_class(driver_klass)
def get_driver(driver_name):
    LOG.info(_LI("Loading OFC driver: %s"), driver_name)
    driver_klass = DRIVER_LIST.get(driver_name) or driver_name
    return importutils.import_class(driver_klass)
 def delete_tenant_semaphore(cls, tenant_id):
     with Semaphore.lock:
         if tenant_id in Semaphore.tenants:
             LOG.info(_LI('delete semaphore for %s'), tenant_id)
             del Semaphore.tenants[tenant_id]
    def get_device_details(self, rpc_context, **kwargs):
        """Agent requests device details."""
        agent_id = kwargs.get('agent_id')
        device = kwargs.get('device')
        host = kwargs.get('host')
        # cached networks used for reducing number of network db calls
        # for server internal usage only
        cached_networks = kwargs.get('cached_networks')
        LOG.debug("Device %(device)s details requested by agent "
                  "%(agent_id)s with host %(host)s",
                  {'device': device, 'agent_id': agent_id, 'host': host})

        plugin = manager.NeutronManager.get_plugin()
        port_id = plugin._device_to_port_id(device)
        port_context = plugin.get_bound_port_context(rpc_context,
                                                     port_id,
                                                     host,
                                                     cached_networks)
        if not port_context:
            LOG.debug("Device %(device)s requested by agent "
                      "%(agent_id)s not found in database",
                      {'device': device, 'agent_id': agent_id})
            return {'device': device}

        segment = port_context.bottom_bound_segment
        port = port_context.current
        # caching information about networks for future use
        if cached_networks is not None:
            if port['network_id'] not in cached_networks:
                cached_networks[port['network_id']] = (
                    port_context.network.current)

        if not segment:
            LOG.warning(_LW("Device %(device)s requested by agent "
                            "%(agent_id)s on network %(network_id)s not "
                            "bound, vif_type: %(vif_type)s"),
                        {'device': device,
                         'agent_id': agent_id,
                         'network_id': port['network_id'],
                         'vif_type': port_context.vif_type})
            return {'device': device}

        if segment['segmentation_id'] == 0:
            entry = {'device': device}
            LOG.info(_LI('The segmentation_id is not yet finalized, '
                         'it is replaced to return %s'), entry)
            return entry

        if not host or host == port_context.host:
            new_status = (constants.PORT_STATUS_BUILD if port['admin_state_up']
                          else constants.PORT_STATUS_DOWN)
            if (
                    port['status'] != new_status and
                    port['status'] != constants.PORT_STATUS_ACTIVE
            ):
                plugin.update_port_status(rpc_context,
                                          port_id,
                                          new_status,
                                          host)

        entry = {'device': device,
                 'network_id': port['network_id'],
                 'port_id': port['id'],
                 'mac_address': port['mac_address'],
                 'admin_state_up': port['admin_state_up'],
                 'network_type': segment[api.NETWORK_TYPE],
                 'segmentation_id': segment[api.SEGMENTATION_ID],
                 'physical_network': segment[api.PHYSICAL_NETWORK],
                 'fixed_ips': port['fixed_ips'],
                 'device_owner': port['device_owner'],
                 'allowed_address_pairs': port['allowed_address_pairs'],
                 'port_security_enabled': port.get(psec.PORTSECURITY, True),
                 'profile': port[portbindings.PROFILE]}
        if 'security_groups' in port:
            entry['security_groups'] = port['security_groups']
        LOG.debug("Returning: %s", entry)
        return entry
    def get_device_details(self, rpc_context, **kwargs):
        """Agent requests device details."""
        agent_id = kwargs.get('agent_id')
        device = kwargs.get('device')
        host = kwargs.get('host')
        # cached networks used for reducing number of network db calls
        # for server internal usage only
        cached_networks = kwargs.get('cached_networks')
        LOG.debug(
            "Device %(device)s details requested by agent "
            "%(agent_id)s with host %(host)s", {
                'device': device,
                'agent_id': agent_id,
                'host': host
            })

        plugin = manager.NeutronManager.get_plugin()
        port_id = plugin._device_to_port_id(device)
        port_context = plugin.get_bound_port_context(rpc_context, port_id,
                                                     host, cached_networks)
        if not port_context:
            LOG.debug(
                "Device %(device)s requested by agent "
                "%(agent_id)s not found in database", {
                    'device': device,
                    'agent_id': agent_id
                })
            return {'device': device}

        segment = port_context.bottom_bound_segment
        port = port_context.current
        # caching information about networks for future use
        if cached_networks is not None:
            if port['network_id'] not in cached_networks:
                cached_networks[port['network_id']] = (
                    port_context.network.current)

        if not segment:
            LOG.warning(
                _LW("Device %(device)s requested by agent "
                    "%(agent_id)s on network %(network_id)s not "
                    "bound, vif_type: %(vif_type)s"), {
                        'device': device,
                        'agent_id': agent_id,
                        'network_id': port['network_id'],
                        'vif_type': port_context.vif_type
                    })
            return {'device': device}

        if segment['segmentation_id'] == 0:
            entry = {'device': device}
            LOG.info(
                _LI('The segmentation_id is not yet finalized, '
                    'it is replaced to return %s'), entry)
            return entry

        if not host or host == port_context.host:
            new_status = (constants.PORT_STATUS_BUILD if port['admin_state_up']
                          else constants.PORT_STATUS_DOWN)
            if (port['status'] != new_status
                    and port['status'] != constants.PORT_STATUS_ACTIVE):
                plugin.update_port_status(rpc_context, port_id, new_status,
                                          host)

        entry = {
            'device': device,
            'network_id': port['network_id'],
            'port_id': port['id'],
            'mac_address': port['mac_address'],
            'admin_state_up': port['admin_state_up'],
            'network_type': segment[api.NETWORK_TYPE],
            'segmentation_id': segment[api.SEGMENTATION_ID],
            'physical_network': segment[api.PHYSICAL_NETWORK],
            'fixed_ips': port['fixed_ips'],
            'device_owner': port['device_owner'],
            'allowed_address_pairs': port['allowed_address_pairs'],
            'port_security_enabled': port.get(psec.PORTSECURITY, True),
            'profile': port[portbindings.PROFILE]
        }
        if 'security_groups' in port:
            entry['security_groups'] = port['security_groups']
        LOG.debug("Returning: %s", entry)
        return entry