def _get_ri_id_of_network(self, oc_client, network_id): try: network = oc_client.show('Virtual Network', network_id) ri_fq_name = network['fq_name'] + [network['fq_name'][-1]] for ri_ref in network.get('routing_instances', []): if ri_ref['to'] == ri_fq_name: return ri_ref['uuid'] except (oc_exc.OpenContrailAPINotFound, IndexError): raise n_exc.NetworkNotFound(net_id=network_id) raise n_exc.NetworkNotFound(net_id=network_id)
def get_network_adjust_mtu(*args, **kwargs): res = orig_get_network(*args, **kwargs) if res['name'] == 'net_trunk': if trunk_net_mtu == 'exc': raise n_exc.NetworkNotFound(net_id='net-id') res[api.MTU] = trunk_net_mtu elif res['name'] == 'net_subport': if subport_net_mtu == 'exc': raise n_exc.NetworkNotFound(net_id='net-id') res[api.MTU] = subport_net_mtu return res
def _net_id_to_moref(self, dvs_moref, net_id): """Gets the moref for the specific neutron network.""" # NOTE(garyk): return this from a cache if not found then invoke # code below. if dvs_moref: port_groups = self._session.invoke_api(vim_util, 'get_object_properties', self._session.vim, dvs_moref, ['portgroup']) if len(port_groups) and hasattr(port_groups[0], 'propSet'): for prop in port_groups[0].propSet: for val in prop.val[0]: props = self._session.invoke_api( vim_util, 'get_object_properties', self._session.vim, val, ['name']) if len(props) and hasattr(props[0], 'propSet'): for prop in props[0].propSet: # match name or mor id if net_id == prop.val or net_id == val.value: # NOTE(garyk): update cache return val raise exceptions.NetworkNotFound(net_id=net_id) else: return self._get_portgroup(net_id)
def create_segment(self, context, segment): """Create a segment.""" segment = segment['segment'] segment_id = segment.get('id') or uuidutils.generate_uuid() with context.session.begin(subtransactions=True): network_id = segment['network_id'] physical_network = segment[extension.PHYSICAL_NETWORK] if physical_network == constants.ATTR_NOT_SPECIFIED: physical_network = None network_type = segment[extension.NETWORK_TYPE] segmentation_id = segment[extension.SEGMENTATION_ID] if segmentation_id == constants.ATTR_NOT_SPECIFIED: segmentation_id = None args = {'id': segment_id, 'network_id': network_id, db.PHYSICAL_NETWORK: physical_network, db.NETWORK_TYPE: network_type, db.SEGMENTATION_ID: segmentation_id} new_segment = db.NetworkSegment(**args) try: context.session.add(new_segment) context.session.flush([new_segment]) except db_exc.DBReferenceError: raise n_exc.NetworkNotFound(net_id=network_id) registry.notify(resources.SEGMENT, events.PRECOMMIT_CREATE, self, context=context, segment=new_segment) return self._make_segment_dict(new_segment)
def get_lswitches(cluster, neutron_net_id): def lookup_switches_by_tag(): # Fetch extra logical switches lswitch_query_path = nsxlib._build_uri_path( LSWITCH_RESOURCE, fields="uuid,display_name,tags,lport_count", relations="LogicalSwitchStatus", filters={ 'tag': neutron_net_id, 'tag_scope': 'quantum_net_id' }) return nsxlib.get_all_query_pages(lswitch_query_path, cluster) lswitch_uri_path = nsxlib._build_uri_path(LSWITCH_RESOURCE, neutron_net_id, relations="LogicalSwitchStatus") results = [] try: ls = nsxlib.do_request(HTTP_GET, lswitch_uri_path, cluster=cluster) results.append(ls) for tag in ls['tags']: if (tag['scope'] == "multi_lswitch" and tag['tag'] == "True"): results.extend(lookup_switches_by_tag()) except exception.NotFound: # This is legit if the neutron network was created using # a post-Havana version of the plugin results.extend(lookup_switches_by_tag()) if results: return results else: raise exception.NetworkNotFound(net_id=neutron_net_id)
def update_dhcp_port(self, context, **kwargs): """Update the dhcp port.""" host = kwargs.get('host') port = kwargs.get('port') port['id'] = kwargs.get('port_id') port['port'][portbindings.HOST_ID] = host plugin = directory.get_plugin() try: network_id = port['port']['network_id'] old_port = plugin.get_port(context, port['id']) if (old_port['device_id'] != constants.DEVICE_ID_RESERVED_DHCP_PORT and old_port['device_id'] != utils.get_dhcp_agent_device_id(network_id, host)): return if not self._is_dhcp_agent_hosting_network(plugin, context, host, network_id): LOG.warning("The DHCP agent on %(host)s does not host the " "network %(net_id)s.", {"host": host, "net_id": network_id}) raise exceptions.NetworkNotFound(net_id=network_id) LOG.debug('Update dhcp port %(port)s ' 'from %(host)s.', {'port': port, 'host': host}) return self._port_action(plugin, context, port, 'update_port') except exceptions.PortNotFound: LOG.debug('Host %(host)s tried to update port ' '%(port_id)s which no longer exists.', {'host': host, 'port_id': port['id']})
def _validate_connection(self, context, gw_connection): seg_id = gw_connection.get('segmentation_id', None) l2_gw_id = gw_connection.get('l2_gateway_id') self._check_port_fault_status_and_switch_fault_status( context, l2_gw_id) check_vlan = ( self.service_plugin._is_vlan_configured_on_any_interface_for_l2gw( context, l2_gw_id)) nw_map = {} network_id = gw_connection.get(constants.NETWORK_ID) nw_map[constants.NETWORK_ID] = network_id nw_map['l2_gateway_id'] = l2_gw_id if seg_id: nw_map[constants.SEG_ID] = gw_connection.get(constants.SEG_ID) if not self.service_plugin._get_network(context, network_id): raise exceptions.NetworkNotFound(net_id=network_id) if self.service_plugin._retrieve_gateway_connections( context, l2_gw_id, nw_map): raise l2gw_exc.L2GatewayConnectionExists(mapping=nw_map, gateway_id=l2_gw_id) l2gw_validators.validate_network_mapping_list(nw_map, check_vlan) gw_db = self.service_plugin._get_l2_gateway(context, l2_gw_id) tenant_id = self.service_plugin._get_tenant_id_for_create( context, gw_db) l2gw_connection = self.service_plugin.get_l2_gateway_connections( context, filters={ 'network_id': [network_id], 'tenant_id': [tenant_id], 'l2_gateway_id': [l2_gw_id] }) if l2gw_connection: raise l2gw_exc.L2GatewayConnectionExists(mapping=nw_map, gateway_id=l2_gw_id)
def delete_network(context, id): """Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete. """ LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(context=context, limit=None, sorts=['id'], marker=None, page_reverse=False, id=id, scope=db_api.ONE) if not net: raise n_exc.NetworkNotFound(net_id=id) if not context.is_admin: if STRATEGY.is_provider_network(net.id): raise n_exc.NotAuthorized(net_id=id) if net.ports: raise n_exc.NetworkInUse(net_id=id) net_driver = registry.DRIVER_REGISTRY.get_driver(net["network_plugin"]) net_driver.delete_network(context, id) for subnet in net["subnets"]: subnets._delete_subnet(context, subnet) db_api.network_delete(context, net)
def _update_vxlan_port_groups_config(self, dvs_moref, net_id, net_moref, spec_update_calback, spec_update_data): port_groups = self._session.invoke_api(vim_util, 'get_object_properties', self._session.vim, dvs_moref, ['portgroup']) found = False if len(port_groups) and hasattr(port_groups[0], 'propSet'): for prop in port_groups[0].propSet: for pg_moref in prop.val[0]: props = self._session.invoke_api(vim_util, 'get_object_properties', self._session.vim, pg_moref, ['name']) if len(props) and hasattr(props[0], 'propSet'): for prop in props[0].propSet: if net_id in prop.val and net_moref in prop.val: found = True self._reconfigure_port_group( pg_moref, spec_update_calback, spec_update_data) if not found: raise exceptions.NetworkNotFound(net_id=net_id)
def delete_networks(cluster, net_id, lswitch_ids): for ls_id in lswitch_ids: path = "/ws.v1/lswitch/%s" % ls_id try: nsxlib.do_request(HTTP_DELETE, path, cluster=cluster) except exception.NotFound as e: LOG.error("Network not found, Error: %s", str(e)) raise exception.NetworkNotFound(net_id=ls_id)
def get_lswitch_by_id(cluster, lswitch_id): try: lswitch_uri_path = nsxlib._build_uri_path( LSWITCH_RESOURCE, lswitch_id, relations="LogicalSwitchStatus") return nsxlib.do_request(HTTP_GET, lswitch_uri_path, cluster=cluster) except exception.NotFound: # FIXME(salv-orlando): this should not raise a neutron exception raise exception.NetworkNotFound(net_id=lswitch_id)
def get_network_ip_availability(self, context, id=None, fields=None): """Return ip availability data for a specific network id.""" filters = {'network_id': [id]} result = self.get_network_ip_availabilities(context, filters) if result: return db_utils.resource_fields(result[0], fields) else: raise exceptions.NetworkNotFound(net_id=id)
def get_network(self, context, _id, fields=None): try: b_network = self.core_plugin.get_network(context, _id) subnet_ids = self._ensure_subnet(context, b_network, False) except q_exceptions.NotFound: t_ctx = t_context.get_context_from_neutron_context(context) if self._skip_non_api_query(t_ctx): raise q_exceptions.NetworkNotFound(net_id=_id) t_network = self.neutron_handle.handle_get(t_ctx, 'network', _id) if not t_network: raise q_exceptions.NetworkNotFound(net_id=_id) self._adapt_network_body(t_network) b_network = self.core_plugin.create_network( context, {'network': t_network}) subnet_ids = self._ensure_subnet(context, t_network) if subnet_ids: b_network['subnets'] = subnet_ids return self._fields(b_network, fields)
def _create_bottom_network(self, context, _id): t_ctx = t_context.get_context_from_neutron_context(context) t_network = self.neutron_handle.handle_get(t_ctx, 'network', _id) if not t_network: raise q_exceptions.NetworkNotFound(net_id=_id) self._adapt_network_body(t_network) t_network.pop('qos_policy_id', None) b_network = self.core_plugin.create_network(context, {'network': t_network}) return t_network, b_network
def test_convert_exception_to_http_exc_multiple_same_codes(self): e = exceptions.MultipleExceptions([ exceptions.NetworkNotFound(net_id='nid'), exceptions.PortNotFound(port_id='pid') ]) conv = common.convert_exception_to_http_exc(e, base_v2.FAULT_MAP, None) self.assertIsInstance(conv, exc.HTTPNotFound) self.assertEqual( "Network nid could not be found.\nPort pid could not be found.", jsonutils.loads(conv.body)['NeutronError']['message'])
def test_retryrequest_on_notfound(self): failure = exceptions.NetworkNotFound(net_id='whatever') action = "create_port:mac" with mock.patch.object(directory.get_plugin(), 'get_network', side_effect=failure): target = {'network_id': 'whatever'} try: policy.enforce(self.context, action, target) self.fail("Did not raise RetryRequest") except db_exc.RetryRequest as e: self.assertEqual(failure, e.inner_exc)
def create_segment(self, context, segment): """Create a segment.""" segment = segment['segment'] segment_id = segment.get('id') or uuidutils.generate_uuid() try: new_segment = self._create_segment_db(context, segment_id, segment) except db_exc.DBReferenceError: raise n_exc.NetworkNotFound(net_id=segment['network_id']) registry.notify(resources.SEGMENT, events.AFTER_CREATE, self, context=context, segment=new_segment) return self._make_segment_dict(new_segment)
def create_ip_policy(context, ip_policy): LOG.info("create_ip_policy for tenant %s" % context.tenant_id) ipp = ip_policy['ip_policy'] if not ipp.get("exclude"): raise n_exc.BadRequest(resource="ip_policy", msg="Empty ip_policy.exclude") network_ids = ipp.get("network_ids") subnet_ids = ipp.get("subnet_ids") if subnet_ids and network_ids: raise n_exc.BadRequest( resource="ip_policy", msg="network_ids and subnet_ids specified. only one allowed") if not subnet_ids and not network_ids: raise n_exc.BadRequest(resource="ip_policy", msg="network_ids or subnet_ids not specified") with context.session.begin(): if subnet_ids: subnets = db_api.subnet_find(context, id=subnet_ids, scope=db_api.ALL) if not subnets: raise n_exc.SubnetNotFound(subnet_id=subnet_ids) _check_for_pre_existing_policies_in(subnets) ensure_default_policy(ipp["exclude"], subnets) _validate_cidrs_fit_into_subnets(ipp["exclude"], subnets) ipp.pop("subnet_ids") ipp["subnets"] = subnets if network_ids: nets = db_api.network_find(context, id=network_ids, scope=db_api.ALL) if not nets: raise n_exc.NetworkNotFound(net_id=network_ids) _check_for_pre_existing_policies_in(nets) subnets = [ subnet for net in nets for subnet in net.get("subnets", []) ] ensure_default_policy(ipp["exclude"], subnets) _validate_cidrs_fit_into_subnets(ipp["exclude"], subnets) ipp.pop("network_ids") ipp["networks"] = nets ip_policy = db_api.ip_policy_create(context, **ipp) return v._make_ip_policy_dict(ip_policy)
def test_synchronize_network_not_found_in_db_no_raise(self): ctx = context.get_admin_context() with self._populate_data(ctx): # Put a network down to verify synchronization ls_uuid = list(self.fc._fake_lswitch_dict)[0] q_net_id = self._get_tag_dict( self.fc._fake_lswitch_dict[ls_uuid]['tags'])['quantum_net_id'] self.fc._fake_lswitch_dict[ls_uuid]['status'] = 'false' q_net_data = self._plugin._get_network(ctx, q_net_id) with mock.patch.object(self._plugin, '_get_network') as _get_network: _get_network.side_effect = n_exc.NetworkNotFound( net_id=q_net_data['id']) self._plugin._synchronizer.synchronize_network(ctx, q_net_data)
def _get_portgroup(self, net_id): """Get the port group moref of the net_id.""" results = self._session.invoke_api(vim_util, 'get_objects', self._session.vim, 'DistributedVirtualPortgroup', 100) while results: for pg in results.objects: for prop in pg.propSet: if net_id == prop.val: vim_util.cancel_retrieval(self._session.vim, results) return pg.obj results = vim_util.continue_retrieval(self._session.vim, results) raise exceptions.NetworkNotFound(net_id=net_id)
def test_create_subnet_precommit_without_network( self, mock_check_rg, mock_get_nw, mock_create_nw, mock_create_subnet): mock_check_rg.side_effect = azure_mock.get_fake_resource_group mock_get_nw.side_effect = exceptions.NetworkNotFound( net_id="fake_network_id") mock_create_nw.side_effect = azure_mock.create_anything mock_create_subnet.side_effect = azure_mock.create_anything self.assertIsNone(self.driver.create_subnet_precommit(self.context)) mock_create_subnet.assert_called_once_with( self.driver.network_client, azure_conf.resource_group, "net-" + self.context.current['network_id'], "subnet-" + self.context.current[api.ID], {'address_prefix': self.context.current['cidr']}) self.assertTrue(mock_create_nw.called)
def diagnose_network(context, id, fields): if not context.is_admin: raise n_exc.NotAuthorized() if id == "*": return { 'networks': [ _diag_network(context, net, fields) for net in db_api.network_find(context, scope=db_api.ALL) ] } db_net = db_api.network_find(context, id=id, scope=db_api.ONE) if not db_net: raise n_exc.NetworkNotFound(net_id=id) net = _diag_network(context, db_net, fields) return {'networks': net}
def get_network(self, context, _id, fields=None): try: b_network = self.core_plugin.get_network(context, _id) if not self._in_subnet_delete(context): subnet_ids = self._ensure_subnet(context, b_network, False) else: subnet_ids = [] except q_exceptions.NotFound: if self._in_subnet_delete(context): raise t_ctx = t_context.get_context_from_neutron_context(context) if self._skip_non_api_query(t_ctx): raise q_exceptions.NetworkNotFound(net_id=_id) t_network, b_network = self._create_bottom_network(context, _id) subnet_ids = self._ensure_subnet(context, t_network) if subnet_ids: b_network['subnets'] = subnet_ids return self._fields(b_network, fields)
def update_lswitch(cluster, lswitch_id, display_name, tenant_id=None, **kwargs): uri = nsxlib._build_uri_path(LSWITCH_RESOURCE, resource_id=lswitch_id) lswitch_obj = {"display_name": utils.check_and_truncate(display_name)} # NOTE: tag update will not 'merge' existing tags with new ones. tags = [] if tenant_id: tags = utils.get_tags(os_tid=tenant_id) # The 'tags' kwarg might existing and be None tags.extend(kwargs.get('tags') or []) if tags: lswitch_obj['tags'] = tags try: return nsxlib.do_request(HTTP_PUT, uri, jsonutils.dumps(lswitch_obj), cluster=cluster) except exception.NotFound as e: LOG.error(_LE("Network not found, Error: %s"), str(e)) raise exception.NetworkNotFound(net_id=lswitch_id)
def find_bgpvpns_for_network(self, context, network_id, bgpvpn_type=None): try: vn_obj = self._vnc_api.virtual_network_read(id=network_id, fields=['bgpvpn_refs']) except vnc_exc.NoIdError: raise neutron_exc.NetworkNotFound(net_id=network_id) bgpvpn_ids = [ bgpvpn_ref['uuid'] for bgpvpn_ref in vn_obj.get_bgpvpn_refs() or [] ] filters = {} if bgpvpn_type is not None: filters['bgpvpn_type'] = bgpvpn_type bgpvpns = [] for bgpvpn_obj in self._vnc_api.bgpvpns_list(obj_uuids=bgpvpn_ids, detail=True, filters=filters): bgpvpns.append(self._bgpvpn_to_neutron_dict(bgpvpn_obj)) return bgpvpns
def create_net_assoc(self, context, bgpvpn_id, network_association): try: bgpvpn_obj = self._vnc_api.bgpvpn_read(id=bgpvpn_id) except vnc_exc.NoIdError: raise bgpvpn_ext.BGPVPNNotFound(id=bgpvpn_id) net_id = network_association['network_id'] try: vn_obj = self._vnc_api.virtual_network_read(id=net_id) except vnc_exc.NoIdError: raise neutron_exc.NetworkNotFound(net_id=net_id) vn_obj.add_bgpvpn(bgpvpn_obj) try: self._vnc_api.virtual_network_update(vn_obj) except vnc_exc.BadRequest as exc: raise neutron_exc.BadRequest(resource='network_association', msg=str(exc)) # Use the network ID as association id network_association['id'] = net_id network_association['bgpvpn_id'] = bgpvpn_id network_association.pop('project_id', None) return bgpvpn_utils.make_net_assoc_dict(**network_association)
def delete_net_assoc(self, context, assoc_id, bgpvpn_id): try: bgpvpn_obj = self._vnc_api.bgpvpn_read(id=bgpvpn_id) except vnc_exc.NoIdError: raise bgpvpn_ext.BGPVPNNotFound(id=bgpvpn_id) try: vn_obj = self._vnc_api.virtual_network_read(id=assoc_id) except vnc_exc.NoIdError: raise neutron_exc.NetworkNotFound(net_id=assoc_id) vn_obj.del_bgpvpn(bgpvpn_obj) try: self._vnc_api.virtual_network_update(vn_obj) except vnc_exc.BadRequest as exc: raise neutron_exc.BadRequest(resource='network_association', msg=str(exc)) return bgpvpn_utils.make_net_assoc_dict( assoc_id, bgpvpn_obj.parent_uuid.replace('-', ''), bgpvpn_id, assoc_id, )
def update_network(context, id, network): """Update values of a network. : param context: neutron api request context : param id: UUID representing the network to update. : param network: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put' as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. """ LOG.info("update_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(context, id=id, scope=db_api.ONE) if not net: raise n_exc.NetworkNotFound(net_id=id) net_dict = network["network"] utils.pop_param(net_dict, "network_plugin") if not context.is_admin and "ipam_strategy" in net_dict: utils.pop_param(net_dict, "ipam_strategy") net = db_api.network_update(context, net, **net_dict) return v._make_network_dict(net)
def delete_network(context, id): """Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete. """ LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(context, None, None, None, False, id=id, scope=db_api.ONE) if not net: raise n_exc.NetworkNotFound(net_id=id) if net.ports: raise n_exc.NetworkInUse(net_id=id) net_driver = registry.DRIVER_REGISTRY.get_driver(net["network_plugin"]) net_driver.delete_network(context, id) for subnet in net["subnets"]: subnets._delete_subnet(context, subnet) db_api.network_delete(context, net)
def get_network(context, id, fields=None): """Retrieve a network. : param context: neutron api request context : param id: UUID representing the network to fetch. : param fields: a list of strings that are valid keys in a network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. Only these fields will be returned. """ LOG.info("get_network %s for tenant %s fields %s" % (id, context.tenant_id, fields)) network = db_api.network_find(context=context, limit=None, sorts=['id'], marker=None, page_reverse=False, id=id, join_subnets=True, scope=db_api.ONE) if not network: raise n_exc.NetworkNotFound(net_id=id) return v._make_network_dict(network, fields=fields)