Ejemplo n.º 1
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 delete_tenant_rpc_server(self, tid):
        if tid not in self.rpc_servers:
            LOG.warning(_LW("rpc server not found. tid=%s"), tid)
            return {'result': 'FAILED'}

        LOG.debug('RPCServer delete: stop %s', tid)
        self.rpc_servers[tid]['server'].stop()

        LOG.debug('RPCServer delete: wait %s', tid)
        self.rpc_servers[tid]['server'].wait()

        LOG.debug('RPCServer delete: pop %s', tid)
        self.rpc_servers.pop(tid)

        LOG.debug('RPCServer delete: sleep %s', tid)
        eventlet.sleep(0)

        ret = {
            'result': 'SUCCESS',
            'tenant_id': tid
        }

        LOG.debug("RPCServer deleted: %s", ret)

        return ret
Ejemplo n.º 3
0
    def _create_vlan(self, context, **kwargs):
        nwa_tenant_id = kwargs.get('nwa_tenant_id')
        nwa_info = kwargs.get('nwa_info')
        nwa_data = kwargs.get('nwa_data')

        network_id = nwa_info['network']['id']
        nw_vlan_key = data_utils.get_vlan_key(network_id)
        if nw_vlan_key in nwa_data:
            LOG.warning(_LW("aleady in vlan_key %s"), nw_vlan_key)
            return nwa_data

        rcode, body = self.client.l2.create_vlan(
            nwa_tenant_id,
            nwa_info['subnet']['netaddr'],
            nwa_info['subnet']['mask'],
            nwa_info['network']['vlan_type'],
            openstack_network_id=network_id
        )

        if rcode == 200 and body['status'] == 'SUCCEED':
            # create vlan succeed.
            LOG.debug("CreateVlan succeed.")
            data_utils.set_network_data(nwa_data, network_id, nwa_info,
                                        body['resultdata']['LogicalNWName'])
            data_utils.set_vlan_data(nwa_data, network_id,
                                     body['resultdata']['VlanID'])
        else:
            # create vlan failed.
            LOG.error(_LE("CreateVlan Failed."))
            raise nwa_exc.AgentProxyException(value=nwa_data)

        return nwa_data
Ejemplo n.º 4
0
    def create_tenant_fw(self, context, **kwargs):
        nwa_data = self.proxy_l2.ensure_l2_network(context, **kwargs)
        device_id = kwargs['nwa_info']['device']['id']
        network_id = kwargs['nwa_info']['network']['id']
        dev_key = data_utils.get_device_key(device_id)
        net_key = data_utils.get_device_net_key(device_id, network_id)
        if dev_key not in nwa_data:
            nwa_data = self._create_tenant_fw(nwa_data, context, **kwargs)
        elif net_key not in nwa_data:
            nwa_data = self._update_tenant_fw(context,
                                              connect='connect',
                                              nwa_data=nwa_data,
                                              **kwargs)
        else:
            LOG.warning(_LW("unknown device."))

        if not nwa_data:
            raise nwa_exc.AgentProxyException(value=kwargs['nwa_data'])
        ret = self.proxy_tenant.update_tenant_binding(context,
                                                      kwargs['tenant_id'],
                                                      kwargs['nwa_tenant_id'],
                                                      nwa_data)
        resource_group_name_nw = kwargs['nwa_info']['resource_group_name_nw']
        vlan_id = data_utils.get_vp_net_vlan_id(nwa_data, network_id,
                                                resource_group_name_nw,
                                                nwa_const.NWA_DEVICE_TFW)

        self.nwa_l2_rpc.update_port_state_with_notifier(
            context, device_id, self.agent_top.agent_id,
            kwargs['nwa_info']['port']['id'], {
                api.PHYSICAL_NETWORK: kwargs['nwa_info']['physical_network'],
                api.NETWORK_TYPE: n_constants.TYPE_VLAN,
                api.SEGMENTATION_ID: vlan_id
            }, network_id)
        return ret
Ejemplo n.º 5
0
def load_json_from_file(name, json_file, json_str, default_value):
    if json_file:
        json_file_abspath = cfg.CONF.find_file(json_file)
        if not json_file_abspath:
            LOG.error(_LE('Failed to load %(name)s_file'
                          '"%(json_file)s": file not found'),
                      {'name': name, 'json_file': json_file})
            raise cfg.Error(_('NECNWA option parse error'))
        try:
            with open(json_file_abspath) as f:
                return jsonutils.loads(f.read())
        except Exception as e:
            LOG.error(_LE('Failed to load %(name)s_file '
                          '"%(json_file)s": %(reason)s'),
                      {'reason': e, 'name': name, 'json_file': json_file})
            raise cfg.Error(_('NECNWA option parse error'))
    elif json_str:
        try:
            return jsonutils.loads(json_str)
        except Exception as e:
            LOG.error(_LE('NECNWA option error during loading %(name)s '
                          '(%(data)s): %(reason)s'),
                      {'reason': e, 'name': name, 'data': json_str})
            raise cfg.Error(_('NECNWA option parse error'))
    else:
        LOG.warning(_LW('%(name)s is not configured. '
                        'Make sure to set [NWA] %(name)s_file '
                        'in NWA plugin configuration file. '
                        'Using %(default)s as default value.'),
                    {'name': name, 'default': default_value})
        return default_value
    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
Ejemplo n.º 7
0
def del_portinfo(session, id):
    try:
        with session.begin(subtransactions=True):
            portinfo = session.query(nmodels.PortInfo).filter_by(id=id).one()
            session.delete(portinfo)
    except sa.orm.exc.NoResultFound:
        LOG.warning(_LW("del_portinfo(): NotFound portinfo for "
                        "port_id: %s"), id)
Ejemplo n.º 8
0
 def _create_nwa_agent_tenant_queue(self, context, tenant_id):
     if (self._is_alive_nwa_agent(context)
             and necnwa_api.get_nwa_tenant_queue(context.session,
                                                 tenant_id) is None):
         self.nwa_rpc.create_server(context, tenant_id)
         necnwa_api.add_nwa_tenant_queue(context.session, tenant_id)
     else:
         LOG.warning(_LW('%s is not alive.'), nwa_const.NWA_AGENT_TYPE)
Ejemplo n.º 9
0
def del_portinfo(session, id):
    try:
        with session.begin(subtransactions=True):
            portinfo = session.query(nmodels.PortInfo).filter_by(id=id).one()
            session.delete(portinfo)
    except sa.orm.exc.NoResultFound:
        LOG.warning(
            _LW("del_portinfo(): NotFound portinfo for "
                "port_id: %s"), id)
Ejemplo n.º 10
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
Ejemplo n.º 11
0
 def _cleanup_ofc_tenant(self, context, tenant_id, deleting):
     if not self._check_ofc_tenant_in_use(context, tenant_id, deleting):
         try:
             if self.ofc.exists_ofc_tenant(context, tenant_id):
                 self.ofc.delete_ofc_tenant(context, tenant_id)
             else:
                 LOG.debug('_cleanup_ofc_tenant: No OFC tenant for %s',
                           tenant_id)
         except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
             LOG.warn(_LW("delete_ofc_tenant() failed due to %s"), exc)
Ejemplo n.º 12
0
 def _cleanup_ofc_tenant(self, context, tenant_id, deleting):
     if not self._check_ofc_tenant_in_use(context, tenant_id, deleting):
         try:
             if self.ofc.exists_ofc_tenant(context, tenant_id):
                 self.ofc.delete_ofc_tenant(context, tenant_id)
             else:
                 LOG.debug('_cleanup_ofc_tenant: No OFC tenant for %s',
                           tenant_id)
         except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
             LOG.warn(_LW("delete_ofc_tenant() failed due to %s"), exc)
Ejemplo n.º 13
0
 def _l2_delete_general_dev(self, context, use_original_port=False):
     try:
         kwargs = self._make_l2api_kwargs(
             context, use_original_port=use_original_port)
         self._l2_delete_segment(context, kwargs['nwa_info'])
         proxy = self._get_l2api_proxy(context, kwargs['tenant_id'])
         kwargs['nwa_info'] = self._revert_dhcp_agent_device_id(
             context, kwargs['nwa_info'])
         proxy.delete_general_dev(context.network._plugin_context, **kwargs)
     except nwa_exc.TenantNotFound as e:
         LOG.warning(_LW("skip delete_general_dev: %s"), e)
Ejemplo n.º 14
0
 def _l2_delete_general_dev(self, context, use_original_port=False):
     try:
         kwargs = self._make_l2api_kwargs(
             context, use_original_port=use_original_port)
         self._l2_delete_segment(context, kwargs['nwa_info'])
         proxy = self._get_l2api_proxy(context, kwargs['tenant_id'])
         kwargs['nwa_info'] = self._revert_dhcp_agent_device_id(
             context, kwargs['nwa_info'])
         proxy.delete_general_dev(context.network._plugin_context, **kwargs)
     except nwa_exc.TenantNotFound as e:
         LOG.warning(_LW("skip delete_general_dev: %s"), e)
Ejemplo n.º 15
0
 def create_port_precommit(self, context):
     if not self.necnwa_router:
         return
     device_owner = context._port['device_owner']
     if not self.is_router(device_owner):
         LOG.warning(_LW("device owner missmatch device_owner=%s"),
                     device_owner)
         return
     self._l3_create_tenant_fw(context)
     physical_network = self._find_nwa_physical_network(context)
     if physical_network:
         self._bind_segment_to_vif_type(context, physical_network)
Ejemplo n.º 16
0
def del_ofc_item(session, resource, neutron_id):
    try:
        model = _get_resource_model(resource)
        with session.begin(subtransactions=True):
            item = session.query(model).filter_by(neutron_id=neutron_id).one()
            session.delete(item)
        return True
    except sa.orm.exc.NoResultFound:
        LOG.warning(_LW("del_ofc_item(): NotFound item "
                        "(resource=%(resource)s, id=%(id)s) "),
                    {'resource': resource, 'id': neutron_id})
        return False
Ejemplo n.º 17
0
 def create_port_precommit(self, context):
     if not self.necnwa_router:
         return
     device_owner = context._port['device_owner']
     if not self.is_router(device_owner):
         LOG.warning(_LW("device owner missmatch device_owner=%s"),
                     device_owner)
         return
     self._l3_create_tenant_fw(context)
     physical_network = self._find_nwa_physical_network(context)
     if physical_network:
         self._bind_segment_to_vif_type(context, physical_network)
Ejemplo n.º 18
0
 def disassociate_floatingips(self, context, port_id, do_notify=True):
     floating_ips = context.session.query(l3_db.FloatingIP).filter(
         or_(l3_db.FloatingIP.fixed_port_id == port_id,
             l3_db.FloatingIP.floating_port_id == port_id)
     )
     if not floating_ips:
         LOG.warning(_LW('floatingip not found %s'), port_id)
     for fip in floating_ips:
         self._delete_nat(context, fip)
     router_ids = super(NECNWAL3Plugin, self).disassociate_floatingips(
         context, port_id, do_notify)
     return router_ids
Ejemplo n.º 19
0
    def delete_tenant(self, context, **kwargs):
        """delete tenant.

        @param context: contains user information.
        @param kwargs: nwa_tenant_id
        @return: result(succeed = (True, dict(empty)  other = False, None)
        """
        nwa_tenant_id = kwargs.get('nwa_tenant_id')
        rcode, body = self.client.tenant.delete_tenant(nwa_tenant_id)
        if rcode != 200:
            LOG.warning(_LW('unexpected status code %s in delete_tenant'),
                        rcode)
        return body
Ejemplo n.º 20
0
 def _create_nwa_agent_tenant_queue(self, context, tenant_id):
     if (
             self._is_alive_nwa_agent(context) and
             necnwa_api.get_nwa_tenant_queue(
                 context.session,
                 tenant_id
             ) is None
     ):
         self.nwa_rpc.create_server(context, tenant_id)
         necnwa_api.add_nwa_tenant_queue(context.session, tenant_id)
     else:
         LOG.warning(_LW('%s is not alive.'),
                     nwa_const.NWA_AGENT_TYPE)
Ejemplo n.º 21
0
 def try_to_bind_segment_for_agent(self, context, segment, agent):
     device_owner = context._port['device_owner']
     if not self.necnwa_router or not self.is_router(device_owner):
         physical_network = self._find_nwa_physical_network(context, agent)
         if physical_network:
             self._bind_segment_to_vif_type(context, physical_network)
             self._bind_port_nwa_debug_message(context)
             self._l2_create_general_dev(context)
             return True
         LOG.warning(_LW("binding segment not found for agent=%s"), agent)
     return super(
         NECNWAMechanismDriver, self
     ).try_to_bind_segment_for_agent(context, segment, agent)
Ejemplo n.º 22
0
 def try_to_bind_segment_for_agent(self, context, segment, agent):
     device_owner = context._port['device_owner']
     if not self.necnwa_router or not self.is_router(device_owner):
         physical_network = self._find_nwa_physical_network(context, agent)
         if physical_network:
             self._bind_segment_to_vif_type(context, physical_network)
             self._bind_port_nwa_debug_message(context)
             self._l2_create_general_dev(context)
             return True
         LOG.warning(_LW("binding segment not found for agent=%s"), agent)
     return super(NECNWAMechanismDriver,
                  self).try_to_bind_segment_for_agent(
                      context, segment, agent)
Ejemplo n.º 23
0
def del_ofc_item(session, resource, neutron_id):
    try:
        model = _get_resource_model(resource)
        with session.begin(subtransactions=True):
            item = session.query(model).filter_by(neutron_id=neutron_id).one()
            session.delete(item)
        return True
    except sa.orm.exc.NoResultFound:
        LOG.warning(
            _LW("del_ofc_item(): NotFound item "
                "(resource=%(resource)s, id=%(id)s) "), {
                    'resource': resource,
                    'id': neutron_id
                })
        return False
Ejemplo n.º 24
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]
Ejemplo n.º 25
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]
Ejemplo n.º 26
0
def load_json_from_file(name, json_file, json_str, default_value):
    if json_file:
        json_file_abspath = cfg.CONF.find_file(json_file)
        if not json_file_abspath:
            LOG.error(
                _LE('Failed to load %(name)s_file'
                    '"%(json_file)s": file not found'), {
                        'name': name,
                        'json_file': json_file
                    })
            raise cfg.Error(_('NECNWA option parse error'))
        try:
            with open(json_file_abspath) as f:
                return jsonutils.loads(f.read())
        except Exception as e:
            LOG.error(
                _LE('Failed to load %(name)s_file '
                    '"%(json_file)s": %(reason)s'), {
                        'reason': e,
                        'name': name,
                        'json_file': json_file
                    })
            raise cfg.Error(_('NECNWA option parse error'))
    elif json_str:
        try:
            return jsonutils.loads(json_str)
        except Exception as e:
            LOG.error(
                _LE('NECNWA option error during loading %(name)s '
                    '(%(data)s): %(reason)s'), {
                        'reason': e,
                        'name': name,
                        'data': json_str
                    })
            raise cfg.Error(_('NECNWA option parse error'))
    else:
        LOG.warning(
            _LW('%(name)s is not configured. '
                'Make sure to set [NWA] %(name)s_file '
                'in NWA plugin configuration file. '
                'Using %(default)s as default value.'), {
                    'name': name,
                    'default': default_value
                })
        return default_value
Ejemplo n.º 27
0
 def delete_general_dev(self, tenant_id, dc_resource_group_name,
                        logical_name, vlan_type='BusinessVLAN',
                        port_type=None, openstack_network_id=None):
     body = {
         'DeleteNW_DeviceType1': 'GeneralDev',
         'TenantID': tenant_id,
         'DeleteNW_VlanLogicalName1': logical_name,
         'DeleteNW_VlanType1': vlan_type,
         'DeleteNW_DCResourceGroupName': dc_resource_group_name
     }
     if logical_name and openstack_network_id:
         LOG.warning(_LW('VLAN logical name and id to be specified '
                         'in the exclusive.'))
     if openstack_network_id:
         body['DeleteNW_VlanLogicalID1'] = openstack_network_id
     if port_type:
         body['DeleteNW_PortType1'] = port_type
     return self.client.call_workflow(
         tenant_id, self.client.post, 'DeleteGeneralDev', body
     )
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
    def create_tenant_fw(self, context, **kwargs):
        nwa_data = self.proxy_l2.ensure_l2_network(context, **kwargs)
        device_id = kwargs['nwa_info']['device']['id']
        network_id = kwargs['nwa_info']['network']['id']
        dev_key = data_utils.get_device_key(device_id)
        net_key = data_utils.get_device_net_key(device_id, network_id)
        if dev_key not in nwa_data:
            nwa_data = self._create_tenant_fw(nwa_data, context, **kwargs)
        elif net_key not in nwa_data:
            nwa_data = self._update_tenant_fw(
                context, connect='connect', nwa_data=nwa_data, **kwargs)
        else:
            LOG.warning(_LW("unknown device."))

        if not nwa_data:
            raise nwa_exc.AgentProxyException(value=kwargs['nwa_data'])
        ret = self.proxy_tenant.update_tenant_binding(
            context,
            kwargs['tenant_id'], kwargs['nwa_tenant_id'],
            nwa_data
        )
        resource_group_name_nw = kwargs['nwa_info']['resource_group_name_nw']
        vlan_id = data_utils.get_vp_net_vlan_id(nwa_data, network_id,
                                                resource_group_name_nw,
                                                nwa_const.NWA_DEVICE_TFW)

        self.nwa_l2_rpc.update_port_state_with_notifier(
            context,
            device_id,
            self.agent_top.agent_id,
            kwargs['nwa_info']['port']['id'],
            {
                api.PHYSICAL_NETWORK: kwargs['nwa_info']['physical_network'],
                api.NETWORK_TYPE: n_constants.TYPE_VLAN,
                api.SEGMENTATION_ID: vlan_id
            },
            network_id
        )
        return ret
Ejemplo n.º 30
0
    def delete_tenant_rpc_server(self, tid):
        if tid not in self.rpc_servers:
            LOG.warning(_LW("rpc server not found. tid=%s"), tid)
            return {'result': 'FAILED'}

        LOG.debug('RPCServer delete: stop %s', tid)
        self.rpc_servers[tid]['server'].stop()

        LOG.debug('RPCServer delete: wait %s', tid)
        self.rpc_servers[tid]['server'].wait()

        LOG.debug('RPCServer delete: pop %s', tid)
        self.rpc_servers.pop(tid)

        LOG.debug('RPCServer delete: sleep %s', tid)
        eventlet.sleep(0)

        ret = {'result': 'SUCCESS', 'tenant_id': tid}

        LOG.debug("RPCServer deleted: %s", ret)

        return ret
Ejemplo n.º 31
0
 def delete_general_dev(self,
                        tenant_id,
                        dc_resource_group_name,
                        logical_name,
                        vlan_type='BusinessVLAN',
                        port_type=None,
                        openstack_network_id=None):
     body = {
         'DeleteNW_DeviceType1': 'GeneralDev',
         'TenantID': tenant_id,
         'DeleteNW_VlanLogicalName1': logical_name,
         'DeleteNW_VlanType1': vlan_type,
         'DeleteNW_DCResourceGroupName': dc_resource_group_name
     }
     if logical_name and openstack_network_id:
         LOG.warning(
             _LW('VLAN logical name and id to be specified '
                 'in the exclusive.'))
     if openstack_network_id:
         body['DeleteNW_VlanLogicalID1'] = openstack_network_id
     if port_type:
         body['DeleteNW_PortType1'] = port_type
     return self.client.call_workflow(tenant_id, self.client.post,
                                      'DeleteGeneralDev', body)
Ejemplo n.º 32
0
 def add_interface(self, context, router_id, port):
     port_id = port['id']
     # port['fixed_ips'] may be empty if ext_net has no subnet.
     # Such port is invalid for a router port and we don't create a port
     # on OFC. The port is removed in l3_db._create_router_gw_port.
     if not port['fixed_ips']:
         LOG.warning(
             _LW('RouterOpenFlowDriver.add_interface(): the '
                 'requested port '
                 'has no subnet. add_interface() is skipped. '
                 'router_id=%(id)s, port=%(port)s)'), {
                     'id': router_id,
                     'port': port
                 })
         return port
     fixed_ip = port['fixed_ips'][0]
     subnet = self.plugin._get_subnet(context, fixed_ip['subnet_id'])
     port_info = {
         'network_id': port['network_id'],
         'ip_address': fixed_ip['ip_address'],
         'cidr': subnet['cidr'],
         'mac_address': port['mac_address']
     }
     try:
         self.ofc.add_ofc_router_interface(context, router_id, port_id,
                                           port_info)
         new_status = nconst.ROUTER_STATUS_ACTIVE
         necutils.update_resource_status(context, "port", port_id,
                                         new_status)
         return port
     except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("add_router_interface() failed due to %s"), exc)
             new_status = nconst.ROUTER_STATUS_ERROR
             necutils.update_resource_status(context, "port", port_id,
                                             new_status)
Ejemplo n.º 33
0
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 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