def add_router_interface(self, context, router_id, interface_info): # Validate args router = self._get_router(context, router_id) tenant_id = router['tenant_id'] with db.context_manager.writer.using(context): # create interface in DB # TODO(wolverineav): hack until fixed at right place setattr(context, 'GUARD_TRANSACTION', False) new_intf_info = super(L3RestProxy, self).add_router_interface(context, router_id, interface_info) port = self._get_port(context, new_intf_info['port_id']) subnet_id = new_intf_info['subnet_id'] # we will use the port's subnet id as interface's id intf_details = self._get_router_intf_details(context, subnet_id) # get gateway_ip from port instead of gateway_ip if port.get("fixed_ips"): intf_details['ip_address'] = port["fixed_ips"][0]['ip_address'] # create interface on the network controller self.servers.rest_add_router_interface(tenant_id, router_id, intf_details) directory.get_plugin().update_port( context, port['id'], {'port': {'status': 'ACTIVE'}}) return new_intf_info
def setUp(self): config.cfg.CONF.set_override("extension_drivers", self._extension_drivers, group="ml2") mock.patch("neutron.services.qos.notification_drivers.message_queue" ".RpcQosServiceNotificationDriver").start() super(TestRevisionPlugin, self).setUp() self.cp = directory.get_plugin() self.l3p = directory.get_plugin(constants.L3) self.ctx = nctx.get_admin_context()
def _extract(self, resource_type, resource_id, field): # NOTE(salv-orlando): This check currently assumes the parent # resource is handled by the core plugin. It might be worth # having a way to map resources to plugins so to make this # check more general plugin = directory.get_plugin() if resource_type in service_const.EXT_PARENT_RESOURCE_MAPPING: plugin = directory.get_plugin( service_const.EXT_PARENT_RESOURCE_MAPPING[resource_type]) f = getattr(plugin, 'get_%s' % resource_type) # f *must* exist, if not found it is better to let neutron # explode. Check will be performed with admin context try: data = f(context.get_admin_context(), resource_id, fields=[field]) except exceptions.NotFound as e: # NOTE(kevinbenton): a NotFound exception can occur if a # list operation is happening at the same time as one of # the parents and its children being deleted. So we issue # a RetryRequest so the API will redo the lookup and the # problem items will be gone. raise db_exc.RetryRequest(e) except Exception: with excutils.save_and_reraise_exception(): LOG.exception('Policy check error while calling %s!', f) return data[field]
def get_routers_and_interfaces(self): core = directory.get_plugin() ctx = nctx.get_admin_context() routers = directory.get_plugin(plugin_constants.L3).get_routers(ctx) router_interfaces = list() for r in routers: ports = core.get_ports( ctx, filters={ 'device_id': [r['id']], 'device_owner': [n_const.DEVICE_OWNER_ROUTER_INTF]}) or [] for p in ports: router_interface = r.copy() net_id = p['network_id'] subnet_id = p['fixed_ips'][0]['subnet_id'] subnet = core.get_subnet(ctx, subnet_id) ml2_db = NetworkContext(self, ctx, {'id': net_id}) seg_id = ml2_db.network_segments[0]['segmentation_id'] router_interface['seg_id'] = seg_id router_interface['cidr'] = subnet['cidr'] router_interface['gip'] = subnet['gateway_ip'] router_interface['ip_version'] = subnet['ip_version'] router_interface['subnet_id'] = subnet_id router_interfaces.append(router_interface) return routers, router_interfaces
def setUp(self): self.cfg = self.useFixture(config_fixture.Config()) self.cfg.config(core_plugin='neutron.plugins.ml2.plugin.Ml2Plugin') self.cfg.config(mechanism_drivers=[ 'logger', 'opendaylight_v2'], group='ml2') self.useFixture(odl_base.OpenDaylightRestClientFixture()) self.cfg.config(service_plugins=['odl-router_v2']) core_plugin = cfg.CONF.core_plugin service_plugins = {'l3_plugin_name': 'odl-router_v2'} self.useFixture(odl_base.OpenDaylightJournalThreadFixture()) mock.patch.object(mech_driver_v2.OpenDaylightMechanismDriver, '_record_in_journal').start() mock.patch.object(mech_driver_v2.OpenDaylightMechanismDriver, 'sync_from_callback_precommit').start() mock.patch.object(mech_driver_v2.OpenDaylightMechanismDriver, 'sync_from_callback_postcommit').start() self.useFixture(odl_base.OpenDaylightPeriodicTaskFixture()) self.useFixture(odl_base.OpenDaylightFeaturesFixture()) self.useFixture(odl_base.OpenDaylightPseudoAgentPrePopulateFixture()) super(OpenDaylightL3TestCase, self).setUp( plugin=core_plugin, service_plugins=service_plugins) self.plugin = directory.get_plugin() self.plugin._network_is_external = mock.Mock(return_value=True) self.driver = directory.get_plugin(constants.L3) self.thread = journal.OpenDaylightJournalThread()
def __init__(self, sc_plugin, context, service_chain_instance, service_chain_specs, current_service_chain_node, position, current_service_profile, provider_group, consumer_group=None, management_group=None, original_service_chain_node=None, original_service_profile=None, service_targets=None, classifier=None, is_consumer_external=False): self._gbp_plugin = get_gbp_plugin() self._sc_plugin = sc_plugin self._plugin_context = context self._admin_context = None self._service_chain_instance = service_chain_instance self._current_service_chain_node = current_service_chain_node self._current_service_profile = current_service_profile self._original_service_chain_node = original_service_chain_node self._original_service_profile = original_service_profile self._service_targets = service_targets self._service_chain_specs = service_chain_specs self._provider_group = provider_group self._consumer_group = consumer_group self._management_group = management_group self._classifier = classifier self._is_consumer_external = is_consumer_external self._relevant_specs = None self._core_plugin = directory.get_plugin() self._l3_plugin = directory.get_plugin(constants.L3) self._position = position
def create_port_postcommit(self, context): if not self._is_port_supported(context.current): LOG.debug("Ignoring unsupported vnic type") return if self._is_port_sriov(context.current): LOG.debug("SR-IOV port, nothing to do") return # If bsn_l3 plugin and it is a gateway port, bind to ivs. if (self.l3_bsn_plugin and context.current['device_owner'] == ROUTER_GATEWAY_PORT_OWNER): directory.get_plugin().update_port_status( context._plugin_context, context.current['id'], const.PORT_STATUS_ACTIVE) try: # create port on the network controller port = self._prepare_port_for_controller(context) except servermanager.TenantIDNotFound as e: LOG.warning("Skipping create port %(port)s as %(exp)s", {'port': context.current.get('id'), 'exp': e}) return if port: # For vhostuser type ports, membership rule and endpoint was # created during bind_port, so skip this if port[portbindings.VIF_TYPE] == portbindings.VIF_TYPE_VHOST_USER: return self.async_port_create(port["network"]["tenant_id"], port["network"]["id"], port)
def setUp(self, policy_drivers=None, core_plugin=None, l3_plugin=None, ml2_options=None, sc_plugin=None, qos_plugin=None, trunk_plugin=None): core_plugin = core_plugin or ML2PLUS_PLUGIN policy_drivers = policy_drivers or ['neutron_resources'] config.cfg.CONF.set_override('policy_drivers', policy_drivers, group='group_policy') sc_cfg.cfg.CONF.set_override('node_drivers', ['dummy_driver'], group='node_composition_plugin') sc_cfg.cfg.CONF.set_override('node_plumber', 'dummy_plumber', group='node_composition_plugin') config.cfg.CONF.set_override('allow_overlapping_ips', True) super(CommonNeutronBaseTestCase, self).setUp(core_plugin=core_plugin, l3_plugin=l3_plugin, ml2_options=ml2_options, sc_plugin=sc_plugin, qos_plugin=qos_plugin, trunk_plugin=trunk_plugin) res = mock.patch('neutron.db.l3_db.L3_NAT_dbonly_mixin.' '_check_router_needs_rescheduling').start() res.return_value = None self._plugin = directory.get_plugin() self._plugin.remove_networks_from_down_agents = mock.Mock() self._plugin.is_agent_down = mock.Mock(return_value=False) self._context = nctx.get_admin_context() self._gbp_plugin = directory.get_plugin(pconst.GROUP_POLICY) self._l3_plugin = directory.get_plugin(constants.L3) config.cfg.CONF.set_override('debug', True)
def setUp(self): cfg.CONF.set_override('extension_drivers', self._extension_drivers, group='ml2') super(TestRevisionPlugin, self).setUp() self.cp = directory.get_plugin() self.l3p = directory.get_plugin(constants.L3) self._ctx = nctx.get_admin_context()
def test_net_tag_bumps_net_revision(self): with self.network() as network: rev = network["network"]["revision_number"] tag_plugin = directory.get_plugin("TAG") tag_plugin.update_tag(self.ctx, "networks", network["network"]["id"], "mytag") updated = directory.get_plugin().get_network(self.ctx, network["network"]["id"]) self.assertGreater(updated["revision_number"], rev) tag_plugin.delete_tag(self.ctx, "networks", network["network"]["id"], "mytag") rev = updated["revision_number"] updated = directory.get_plugin().get_network(self.ctx, network["network"]["id"]) self.assertGreater(updated["revision_number"], rev)
def get_active_networks_info(self, context, **kwargs): """Returns all the networks/subnets/ports in system.""" host = kwargs.get('host') LOG.debug('get_active_networks_info from %s', host) networks = self._get_active_networks(context, **kwargs) plugin = directory.get_plugin() filters = {'network_id': [network['id'] for network in networks]} ports = plugin.get_ports(context, filters=filters) # default is to filter subnets based on 'enable_dhcp' flag if kwargs.get('enable_dhcp_filter', True): filters['enable_dhcp'] = [True] # NOTE(kevinbenton): we sort these because the agent builds tags # based on position in the list and has to restart the process if # the order changes. subnets = sorted(plugin.get_subnets(context, filters=filters), key=operator.itemgetter('id')) # Handle the possibility that the dhcp agent(s) only has connectivity # inside a segment. If the segment service plugin is loaded and # there are active dhcp enabled subnets, then filter out the subnets # that are not on the host's segment. seg_plug = directory.get_plugin( segment_ext.SegmentPluginBase.get_plugin_type()) seg_subnets = [subnet for subnet in subnets if subnet.get('segment_id')] nonlocal_subnets = [] if seg_plug and seg_subnets: host_segment_ids = seg_plug.get_segments_by_hosts(context, [host]) # Gather the ids of all the subnets that are on a segment that # this host touches seg_subnet_ids = {subnet['id'] for subnet in seg_subnets if subnet['segment_id'] in host_segment_ids} # Gather the ids of all the networks that are routed routed_net_ids = {seg_subnet['network_id'] for seg_subnet in seg_subnets} # Remove the subnets with segments that are not in the same # segments as the host. Do this only for the networks that are # routed because we want non-routed networks to work as # before. nonlocal_subnets = [subnet for subnet in seg_subnets if subnet['id'] not in seg_subnet_ids] subnets = [subnet for subnet in subnets if subnet['network_id'] not in routed_net_ids or subnet['id'] in seg_subnet_ids] grouped_subnets = self._group_by_network_id(subnets) grouped_nonlocal_subnets = self._group_by_network_id(nonlocal_subnets) grouped_ports = self._group_by_network_id(ports) for network in networks: network['subnets'] = grouped_subnets.get(network['id'], []) network['non_local_subnets'] = ( grouped_nonlocal_subnets.get(network['id'], [])) network['ports'] = grouped_ports.get(network['id'], []) return networks
def setUp(self): cfg.CONF.set_override( 'service_plugins', ['neutron.services.l3_router.l3_router_plugin.L3RouterPlugin', 'neutron.services.flavors.flavors_plugin.FlavorsPlugin']) super(TestRouterController, self).setUp() plugin = directory.get_plugin() ctx = context.get_admin_context() l3_plugin = directory.get_plugin(n_const.L3) network_id = pecan_utils.create_network(ctx, plugin)['id'] self.subnet = pecan_utils.create_subnet(ctx, plugin, network_id) self.router = pecan_utils.create_router(ctx, l3_plugin)
def __init__(self): # REVISIT: Defer until after validating config? Or pass in PD # & MD? self.core_plugin = directory.get_plugin() self.md = self.core_plugin.mechanism_manager.mech_drivers[ 'apic_aim'].obj self.pd = self.md.gbp_driver self.sfcd = None sfc_plugin = directory.get_plugin('sfc') if sfc_plugin: driver = sfc_plugin.driver_manager.drivers.get('aim') if driver: self.sfcd = driver.obj
def get_resources(cls): """Returns Ext Resources.""" ip_controller = IpAddressesController( directory.get_plugin()) ip_port_controller = IpAddressPortController( directory.get_plugin()) resources = [] resources.append(extensions.ResourceExtension( Ip_addresses.get_alias(), ip_controller)) parent = {'collection_name': 'ip_addresses', 'member_name': 'ip_address'} resources.append(extensions.ResourceExtension( 'ports', ip_port_controller, parent=parent)) return resources
def test_net_tag_bumps_net_revision(self): with self.network() as network: rev = network['network']['revision_number'] tag_plugin = directory.get_plugin('TAG') tag_plugin.update_tag(self.ctx, 'networks', network['network']['id'], 'mytag') updated = directory.get_plugin().get_network( self.ctx, network['network']['id']) self.assertGreater(updated['revision_number'], rev) tag_plugin.delete_tag(self.ctx, 'networks', network['network']['id'], 'mytag') rev = updated['revision_number'] updated = directory.get_plugin().get_network( self.ctx, network['network']['id']) self.assertGreater(updated['revision_number'], rev)
def tearDown(self): # disables api_replay_mode for these tests cfg.CONF.set_override('api_replay_mode', False) # remove the extension from the plugin directory.get_plugin().supported_extension_aliases.remove( api_replay.ALIAS) # Revert the attributes map back to normal for attr_name in ('ports', 'networks', 'security_groups', 'security_group_rules', 'routers', 'policies'): attr_info = attributes.RESOURCES[attr_name] attr_info['id']['allow_post'] = False super(TestApiReplay, self).tearDown()
def test_validate_port_has_binding_host(self): with self.port() as port: core_plugin = directory.get_plugin() port['port']['binding:host_id'] = 'host' core_plugin.update_port(self.context, port['port']['id'], port) validator = rules.TrunkPortValidator(port['port']['id']) self.assertTrue(validator.is_bound(self.context))
def _get_net_id_by_portchain_id(self, context, portchain_id): sfc_plugin = directory.get_plugin('sfc') port_chain = sfc_plugin.get_port_chain(context, portchain_id) if not port_chain: raise n_exceptions.PortChainNotFound(portchain_id=portchain_id) port_pairs = sfc_plugin.get_port_pairs( context, {'portpairgroup_id': port_chain['port_pair_groups']}) if not port_pairs: raise n_exceptions.PortPairsNotFoundForPortPairGroup( portpairgroup_id=port_chain['port_pair_groups']) core_plugin = directory.get_plugin() port = super(central_plugin.TricirclePlugin, core_plugin ).get_port(context, port_pairs[0]['ingress']) if not port: raise n_exceptions.PortNotFound(port_id=port_pairs[0]['ingress']) return port['network_id']
def index(self, request, **kwargs): plugin = directory.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_AGENTS, {}) return plugin.list_dhcp_agents_hosting_network( request.context, kwargs['network_id'])
def index(self, request, **kwargs): plugin = directory.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_NETS, {}) return plugin.list_networks_on_dhcp_agent( request.context, kwargs['agent_id'])
def _update_routed_network_host_routes(self, context, network_id, deleted_cidr=None): """Update host routes on subnets on a routed network after event Host routes on the subnets on a routed network may need updates after any CREATE or DELETE event. :param network_id: Network ID :param deleted_cidr: The cidr of a deleted subnet. """ for subnet in self._get_subnets(context, network_id): host_routes = [{'destination': str(route.destination), 'nexthop': route.nexthop} for route in subnet.host_routes] calc_host_routes = self._calculate_routed_network_host_routes( context=context, ip_version=subnet.ip_version, network_id=subnet.network_id, subnet_id=subnet.id, segment_id=subnet.segment_id, host_routes=copy.deepcopy(host_routes), gateway_ip=subnet.gateway_ip, deleted_cidr=deleted_cidr) if self._host_routes_need_update(host_routes, calc_host_routes): LOG.debug( "Updating host routes for subnet %s on routed network %s", (subnet.id, subnet.network_id)) plugin = directory.get_plugin() plugin.update_subnet(context, subnet.id, {'subnet': { 'host_routes': calc_host_routes}})
def _get_net_id_by_port_id(self, context, port_id): core_plugin = directory.get_plugin() port = super(central_plugin.TricirclePlugin, core_plugin ).get_port(context, port_id) if not port: raise n_exceptions.PortNotFound(port_id=port_id) return port['network_id']
def create_port_changed_event(self, action, original_obj, returned_obj): port = None if action in ['update_port', 'delete_port']: port = returned_obj['port'] elif action in ['update_floatingip', 'create_floatingip', 'delete_floatingip']: # NOTE(arosen) if we are associating a floatingip the # port_id is in the returned_obj. Otherwise on disassociate # it's in the original_object port_id = (returned_obj['floatingip'].get('port_id') or original_obj.get('port_id')) if port_id is None: return ctx = context.get_admin_context() try: port = directory.get_plugin().get_port(ctx, port_id) except exc.PortNotFound: LOG.debug("Port %s was deleted, no need to send any " "notification", port_id) return if port and self._is_compute_port(port): if action == 'delete_port': return self._get_port_delete_event(port) else: return self._get_network_changed_event(port['device_id'])
def _notify_subnet_updated(self, resource, event, trigger, context, subnet, original_subnet, **kwargs): segment_id = subnet.get('segment_id') original_segment_id = original_subnet.get('segment_id') if not segment_id or subnet['ip_version'] != constants.IP_VERSION_4: return if original_segment_id != segment_id: # Migration to routed network, treat as create self._notify_subnet(context, subnet, segment_id) return filters = {'segment_id': [segment_id], 'ip_version': [constants.IP_VERSION_4]} if not subnet['allocation_pools']: plugin = directory.get_plugin() alloc_pools = [s['allocation_pools'] for s in plugin.get_subnets(context, filters=filters)] if not any(alloc_pools): self.batch_notifier.queue_event(Event( self._delete_nova_inventory, segment_id)) return original_total, original_reserved = ( self._calculate_inventory_total_and_reserved(original_subnet)) updated_total, updated_reserved = ( self._calculate_inventory_total_and_reserved(subnet)) total = updated_total - original_total reserved = updated_reserved - original_reserved if total or reserved: segment_host_mappings = None if not original_subnet['allocation_pools']: segment_host_mappings = net_obj.SegmentHostMapping.get_objects( context, segment_id=segment_id) self.batch_notifier.queue_event(Event( self._create_or_update_nova_inventory, segment_id, total=total, reserved=reserved, segment_host_mappings=segment_host_mappings))
def _prepare_subports(self, context): """Update subports segmentation details if INHERIT is requested.""" port_ids = { s['port_id']: i for i, s in enumerate(self.subports) if s.get('segmentation_type') == constants.INHERIT } core_plugin = directory.get_plugin() if not port_ids: return elif not n_utils.is_extension_supported(core_plugin, provider.ALIAS): msg = _("Cannot accept segmentation type %s") % constants.INHERIT raise n_exc.InvalidInput(error_message=msg) ports = core_plugin.get_ports(context, filters={'id': port_ids}) # this assumes a user does not try to trunk the same network # more than once. network_port_map = { x['network_id']: {'port_id': x['id']} for x in ports } networks = core_plugin.get_networks( context.elevated(), filters={'id': network_port_map}) for net in networks: port = network_port_map[net['id']] port.update({'segmentation_id': net[provider.SEGMENTATION_ID], 'segmentation_type': net[provider.NETWORK_TYPE]}) self.subports[port_ids[port['port_id']]] = port
def dvr_handle_new_service_port(self, context, port, dest_host=None): """Handle new dvr service port creation. When a new dvr service port is created, this function will schedule a dvr router to new compute node if needed and notify l3 agent on that node. The 'dest_host' will provide the destination host of the port in case of service port migration. """ port_host = dest_host or port[portbindings.HOST_ID] l3_agent_on_host = (self.get_l3_agents( context, filters={'host': [port_host]}) or [None])[0] if not l3_agent_on_host: return if dest_host: # Make sure we create the floatingip agent gateway port # for the destination node if fip is associated with this # fixed port l3plugin = directory.get_plugin(n_const.L3) ( l3plugin. check_for_fip_and_create_agent_gw_port_on_host_if_not_exists( context, port, dest_host)) subnet_ids = [ip['subnet_id'] for ip in port['fixed_ips']] router_ids = self.get_dvr_routers_by_subnet_ids(context, subnet_ids) if router_ids: LOG.debug('DVR: Handle new service port, host %(host)s, ' 'router ids %(router_ids)s', {'host': port_host, 'router_ids': router_ids}) self.l3_rpc_notifier.routers_updated_on_host( context, router_ids, port_host)
def setUp(self, plugin=None, ext_mgr=None): super(AllowedAddressPairTestCase, self).setUp(plugin) # Check if a plugin supports security groups plugin_obj = directory.get_plugin() self._skip_port_security = ('port-security' not in plugin_obj.supported_extension_aliases)
def can_be_trunked(self, context): """"Return true if a port can be trunked.""" if not self.is_bound(context): # An unbound port can be trunked, always. return True trunk_plugin = directory.get_plugin('trunk') vif_type = self._port.get(portbindings.VIF_TYPE) binding_host = self._port.get(portbindings.HOST_ID) # Determine the driver that will be in charge of the trunk: this # can be determined based on the vif type, whether or not the # driver is agent-based, and whether the host is running the agent # associated to the driver itself. host_agent_types = utils.get_agent_types_by_host(context, binding_host) drivers = [ driver for driver in trunk_plugin.registered_drivers if utils.is_driver_compatible( context, driver, vif_type, host_agent_types) ] if len(drivers) > 1: raise trunk_exc.TrunkPluginDriverConflict() elif len(drivers) == 1: return drivers[0].can_trunk_bound_port else: return False
def _add_az_to_response(router_res, router_db): l3_plugin = directory.get_plugin(constants.L3) if not extensions.is_extension_supported( l3_plugin, 'router_availability_zone'): return router_res['availability_zones'] = ( l3_plugin.get_router_availability_zones(router_db))
def update_device_up(self, rpc_context, **kwargs): """Device is up on agent.""" agent_id, host, device = self._get_request_details(kwargs) LOG.debug("Device %(device)s up at agent %(agent_id)s", {'device': device, 'agent_id': agent_id}) plugin = directory.get_plugin() port_id = plugin._device_to_port_id(rpc_context, device) port = plugin.port_bound_to_host(rpc_context, port_id, host) if host and not port: LOG.debug("Device %(device)s not bound to the" " agent host %(host)s", {'device': device, 'host': host}) # this might mean that a VM is in the process of live migration # and vif was plugged on the destination compute node; # need to notify nova explicitly port = ml2_db.get_port(rpc_context, port_id) # _device_to_port_id may have returned a truncated UUID if the # agent did not provide a full one (e.g. Linux Bridge case). if not port: LOG.debug("Port %s not found, will not notify nova.", port_id) return else: if port.device_owner.startswith( n_const.DEVICE_OWNER_COMPUTE_PREFIX): plugin.nova_notifier.notify_port_active_direct(port) return else: self.update_port_status_to_active(port, rpc_context, port_id, host) self.notify_l2pop_port_wiring(port_id, rpc_context, n_const.PORT_STATUS_ACTIVE, host)
def sc_plugin(self): return directory.get_plugin(pconst.SERVICECHAIN)
def _extend_port_dict_binding(port_res, port_db): plugin = directory.get_plugin() if not isinstance(plugin, PortBindingBaseMixin): return plugin.extend_port_dict_binding(port_res, port_db)
def _get_qos_plugin(self): if not self._qos_plugin: self._qos_plugin = directory.get_plugin(constants.QOS) return self._qos_plugin
def core_plugin(self): if not self._core_plugin: self._core_plugin = directory.get_plugin() return self._core_plugin
def plugin(self): if not hasattr(self, '_plugin'): self._plugin = directory.get_plugin() return self._plugin
def _get_device_details(self, rpc_context, agent_id, host, device, port_context): segment = port_context.bottom_bound_segment port = port_context.current if not segment: LOG.warning( "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} # obtain WRS subnet bindings subnets = port_context.subnet_segments() # obtain WRS qos policies plugin = directory.get_plugin() port_qos_id = plugin.get_qos_by_port(rpc_context, port['id']) if port_qos_id is not None: port_qos_policy = plugin.get_policy_for_qos( rpc_context, port_qos_id) else: port_qos_policy = None # obtain WRS qos policies network_qos_id = plugin.get_qos_by_network(rpc_context, port['network_id']) if network_qos_id is not None: network_qos_policy = plugin.get_policy_for_qos( rpc_context, network_qos_id) else: network_qos_policy = None network_qos_policy_id = port_context.network._network.get( qos_consts.QOS_POLICY_ID) entry = { 'device': device, 'network_id': port['network_id'], 'port_id': port['id'], 'tenant_id': port['tenant_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], 'mtu': port_context.network._network.get('mtu'), 'network': port_context.network.current, 'subnets': subnets, 'port_qos_policy': port_qos_policy, 'network_qos_policy': network_qos_policy, 'fixed_ips': port['fixed_ips'], 'device_owner': port['device_owner'], 'allowed_address_pairs': port['allowed_address_pairs'], 'port_security_enabled': port.get(psec.PORTSECURITY, False), 'qos_policy_id': port.get(qos_consts.QOS_POLICY_ID), 'network_qos_policy_id': network_qos_policy_id, 'profile': port[portbindings.PROFILE], 'trunk_port': bool('trunk_details' in port) } LOG.debug("Returning: %s", entry) return entry
def setUp(self): super(NSXv3DHCPAgentAZAwareWeightSchedulerTestCase, self).setUp() self.plugin = directory.get_plugin() self.ctx = context.get_admin_context()
def get_active_networks_info(self, context, **kwargs): """Returns all the networks/subnets/ports in system.""" host = kwargs.get('host') LOG.debug('get_active_networks_info from %s', host) networks = self._get_active_networks(context, **kwargs) plugin = directory.get_plugin() filters = {'network_id': [network['id'] for network in networks]} ports = plugin.get_ports(context, filters=filters) # default is to filter subnets based on 'enable_dhcp' flag if kwargs.get('enable_dhcp_filter', True): filters['enable_dhcp'] = [True] # NOTE(kevinbenton): we sort these because the agent builds tags # based on position in the list and has to restart the process if # the order changes. subnets = sorted(plugin.get_subnets(context, filters=filters), key=operator.itemgetter('id')) # Handle the possibility that the dhcp agent(s) only has connectivity # inside a segment. If the segment service plugin is loaded and # there are active dhcp enabled subnets, then filter out the subnets # that are not on the host's segment. seg_plug = directory.get_plugin( segment_ext.SegmentPluginBase.get_plugin_type()) seg_subnets = [ subnet for subnet in subnets if subnet.get('segment_id') ] nonlocal_subnets = [] if seg_plug and seg_subnets: host_segment_ids = seg_plug.get_segments_by_hosts(context, [host]) # Gather the ids of all the subnets that are on a segment that # this host touches seg_subnet_ids = { subnet['id'] for subnet in seg_subnets if subnet['segment_id'] in host_segment_ids } # Gather the ids of all the networks that are routed routed_net_ids = { seg_subnet['network_id'] for seg_subnet in seg_subnets } # Remove the subnets with segments that are not in the same # segments as the host. Do this only for the networks that are # routed because we want non-routed networks to work as # before. nonlocal_subnets = [ subnet for subnet in seg_subnets if subnet['id'] not in seg_subnet_ids ] subnets = [ subnet for subnet in subnets if subnet['network_id'] not in routed_net_ids or subnet['id'] in seg_subnet_ids ] grouped_subnets = self._group_by_network_id(subnets) grouped_nonlocal_subnets = self._group_by_network_id(nonlocal_subnets) grouped_ports = self._group_by_network_id(ports) for network in networks: network['subnets'] = grouped_subnets.get(network['id'], []) network['non_local_subnets'] = (grouped_nonlocal_subnets.get( network['id'], [])) network['ports'] = grouped_ports.get(network['id'], []) return networks
def setUp(self): super(TestPortsV2, self).setUp() self.plugin = directory.get_plugin() self.ctx = context.get_admin_context()
def _get_network(self, context, network_id): plugin = directory.get_plugin() return plugin.get_network(context, network_id)
def plugin(self): if self._plugin is None: self._plugin = directory.get_plugin() return self._plugin
def l2gwplugin(self): if self._l2gwplugin is None: self._l2gwplugin = directory.get_plugin(srv_const.L2GW) return self._l2gwplugin
def __init__(self, plugin): super(NSXvBgpDriver, self).__init__() self._plugin = plugin self._core_plugin = directory.get_plugin() self._nsxv = self._core_plugin.nsx_v self._edge_manager = self._core_plugin.edge_manager
def _extend_port_mido_portbinding(port_res, port_db): bind_port = port_db.port_binding_info if_name = bind_port.interface_name if bind_port else None plugin = directory.get_plugin() plugin._extend_mido_portbinding(port_res, if_name)
def get_valid_actions(self): actions = (ACCESS_SHARED, ) pl = directory.get_plugin() if 'external-net' in pl.supported_extension_aliases: actions += (ACCESS_EXTERNAL, ) return actions
def _get_subnet_context(self, context, network_id, subnet_id): plugin = directory.get_plugin() network = plugin.get_network(context, network_id) subnet = plugin.get_subnet(context, subnet_id) return driver_context.SubnetContext(plugin, context, subnet, network)
def setUp(self): super(TestRootController, self).setUp() self.setup_service_plugin() self.plugin = directory.get_plugin() self.ctx = context.get_admin_context()
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 = directory.get_plugin() port_id = plugin._device_to_port_id(rpc_context, 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 (not host or host == port_context.host): new_status = (n_const.PORT_STATUS_BUILD if port['admin_state_up'] else n_const.PORT_STATUS_DOWN) if port['status'] != new_status: plugin.update_port_status(rpc_context, port_id, new_status, host, port_context.network.current) network_qos_policy_id = port_context.network._network.get( qos_consts.QOS_POLICY_ID) 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), 'qos_policy_id': port.get(qos_consts.QOS_POLICY_ID), 'network_qos_policy_id': network_qos_policy_id, 'profile': port[portbindings.PROFILE] } LOG.debug("Returning: %s", entry) return entry
def _process_l3_delete(self, context, network_id): l3plugin = directory.get_plugin(plugin_constants.L3) if l3plugin: l3plugin.delete_disassociated_floatingips(context, network_id)
def setUp(self): super(TestPaginationAndSorting, self).setUp() self.plugin = directory.get_plugin() self.ctx = context.get_admin_context() self._create_networks(self.RESOURCE_COUNT) self.networks = self._get_collection()['networks']
def main(): """Main method for syncing neutron networks and ports with ovn nb db. This script provides a utility for syncing the OVN Northbound Database with the Neutron database. This script is used for the migration from ML2/OVS to ML2/OVN. """ conf = setup_conf() # if no config file is passed or no configuration options are passed # then load configuration from /etc/neutron/neutron.conf try: conf(project='neutron') except TypeError: LOG.error('Error parsing the configuration values. Please verify.') return logging.setup(conf, 'neutron_ovn_db_sync_util') LOG.info('Started Neutron OVN db sync') mode = ovn_conf.get_ovn_neutron_sync_mode() if mode not in [ovn_db_sync.SYNC_MODE_LOG, ovn_db_sync.SYNC_MODE_REPAIR]: LOG.error('Invalid sync mode : ["%s"]. Should be "log" or "repair"', mode) return # Validate and modify core plugin and ML2 mechanism drivers for syncing. if (cfg.CONF.core_plugin.endswith('.Ml2Plugin') or cfg.CONF.core_plugin == 'ml2'): cfg.CONF.core_plugin = ( 'neutron.cmd.ovn.neutron_ovn_db_sync_util.Ml2Plugin') if not cfg.CONF.ml2.mechanism_drivers: LOG.error('please use --config-file to specify ' 'neutron and ml2 configuration file.') return if 'ovn' not in cfg.CONF.ml2.mechanism_drivers: LOG.error('No "ovn" mechanism driver found : "%s".', cfg.CONF.ml2.mechanism_drivers) return cfg.CONF.set_override('mechanism_drivers', ['ovn-sync'], 'ml2') conf.service_plugins = [ 'neutron.services.ovn_l3.plugin.OVNL3RouterPlugin' ] else: LOG.error('Invalid core plugin : ["%s"].', cfg.CONF.core_plugin) return try: conn = impl_idl_ovn.get_connection(impl_idl_ovn.OvsdbNbOvnIdl) ovn_api = impl_idl_ovn.OvsdbNbOvnIdl(conn) except RuntimeError: LOG.error('Invalid --ovn-ovn_nb_connection parameter provided.') return try: sb_conn = impl_idl_ovn.get_connection(impl_idl_ovn.OvsdbSbOvnIdl) ovn_sb_api = impl_idl_ovn.OvsdbSbOvnIdl(sb_conn) except RuntimeError: LOG.error('Invalid --ovn-ovn_sb_connection parameter provided.') return manager.init() core_plugin = directory.get_plugin() ovn_driver = core_plugin.mechanism_manager.mech_drivers['ovn-sync'].obj ovn_driver._nb_ovn = ovn_api ovn_driver._sb_ovn = ovn_sb_api synchronizer = ovn_db_sync.OvnNbSynchronizer(core_plugin, ovn_api, ovn_sb_api, mode, ovn_driver) LOG.info('Sync for Northbound db started with mode : %s', mode) synchronizer.do_sync() LOG.info('Sync completed for Northbound db') sb_synchronizer = ovn_db_sync.OvnSbSynchronizer(core_plugin, ovn_sb_api, ovn_driver) LOG.info('Sync for Southbound db started with mode : %s', mode) sb_synchronizer.do_sync() LOG.info('Sync completed for Southbound db')
def __init__(self): super(PortForwardingPlugin, self).__init__() self.push_api = resources_rpc.ResourcesPushRpcApi() self.l3_plugin = directory.get_plugin(constants.L3) self.core_plugin = directory.get_plugin()
def get_core_plugin(cls): return directory.get_plugin()
def _plugin(self): if self._plugin_property is None: self._plugin_property = directory.get_plugin() return self._plugin_property
def initialize_all(): manager.init() ext_mgr = extensions.PluginAwareExtensionManager.get_instance() ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP) # At this stage we have a fully populated resource attribute map; # build Pecan controllers and routes for all core resources plugin = directory.get_plugin() for resource, collection in router.RESOURCES.items(): resource_registry.register_resource_by_name(resource) new_controller = res_ctrl.CollectionsController(collection, resource, plugin=plugin) manager.NeutronManager.set_controller_for_resource( collection, new_controller) manager.NeutronManager.set_plugin_for_resource(collection, plugin) pecanized_resources = ext_mgr.get_pecan_resources() for pec_res in pecanized_resources: manager.NeutronManager.set_controller_for_resource( pec_res.collection, pec_res.controller) manager.NeutronManager.set_plugin_for_resource(pec_res.collection, pec_res.plugin) # Now build Pecan Controllers and routes for all extensions resources = ext_mgr.get_resources() # Extensions controller is already defined, we don't need it. resources.pop(0) for ext_res in resources: path_prefix = ext_res.path_prefix.strip('/') collection = ext_res.collection # Retrieving the parent resource. It is expected the format of # the parent resource to be: # {'collection_name': 'name-of-collection', # 'member_name': 'name-of-resource'} # collection_name does not appear to be used in the legacy code # inside the controller logic, so we can assume we do not need it. parent = ext_res.parent or {} parent_resource = parent.get('member_name') collection_key = collection if parent_resource: collection_key = '/'.join([parent_resource, collection]) collection_actions = ext_res.collection_actions member_actions = ext_res.member_actions if manager.NeutronManager.get_controller_for_resource(collection_key): # This is a collection that already has a pecan controller, we # do not need to do anything else continue legacy_controller = getattr(ext_res.controller, 'controller', ext_res.controller) new_controller = None if isinstance(legacy_controller, base.Controller): resource = legacy_controller.resource plugin = legacy_controller.plugin attr_info = legacy_controller.attr_info member_actions = legacy_controller.member_actions pagination = legacy_controller.allow_pagination sorting = legacy_controller.allow_sorting # NOTE(blogan): legacy_controller and ext_res both can both have # member_actions. the member_actions for ext_res are strictly for # routing, while member_actions for legacy_controller are used for # handling the request once the routing has found the controller. # They're always the same so we will just use the ext_res # member_action. new_controller = res_ctrl.CollectionsController( collection, resource, resource_info=attr_info, parent_resource=parent_resource, member_actions=member_actions, plugin=plugin, allow_pagination=pagination, allow_sorting=sorting, collection_actions=collection_actions) # new_controller.collection has replaced hyphens with underscores manager.NeutronManager.set_plugin_for_resource( new_controller.collection, plugin) if path_prefix: manager.NeutronManager.add_resource_for_path_prefix( collection, path_prefix) else: new_controller = utils.ShimCollectionsController( collection, None, legacy_controller, collection_actions=collection_actions, member_actions=member_actions, action_status=ext_res.controller.action_status, collection_methods=ext_res.collection_methods) manager.NeutronManager.set_controller_for_resource( collection_key, new_controller) # Certain policy checks require that the extensions are loaded # and the RESOURCE_ATTRIBUTE_MAP populated before they can be # properly initialized. This can only be claimed with certainty # once this point in the code has been reached. In the event # that the policies have been initialized before this point, # calling reset will cause the next policy check to # re-initialize with all of the required data in place. policy.reset()
def _ml2_md_extend_address_scope_dict_bulk(results, _): plugin = directory.get_plugin() session = patch_neutron.get_current_session() with session.begin(subtransactions=True): plugin.extension_manager.extend_address_scope_dict_bulk( session, results)
def _fetch_subnet(cls, context, id): plugin = directory.get_plugin() return plugin._get_subnet_object(context, id)
def l3plugin(self): if not hasattr(self, '_l3plugin'): self._l3plugin = directory.get_plugin(plugin_constants.L3) return self._l3plugin
def plugin(self): if not getattr(self, '_plugin', None): self._plugin = directory.get_plugin() return self._plugin
def _extend_tags_dict(response_data, db_data): if not directory.get_plugin(tagging.TAG_PLUGIN_TYPE): return tags = [tag_db.tag for tag_db in db_data.standard_attr.tags] response_data['tags'] = tags