def resolve_ext_resource(self, resource, name_or_id): """Returns the id and validate neutron ext resource.""" path = self._resolve_resource_path(resource) try: record = self.client().show_ext(path + '/%s', name_or_id) return record.get(resource).get('id') except exceptions.NotFound: res_plural = resource + 's' result = self.client().list_ext(collection=res_plural, path=path, retrieve_all=True) resources = result.get(res_plural) matched = [] for res in resources: if res.get('name') == name_or_id: matched.append(res.get('id')) if len(matched) > 1: raise exceptions.NeutronClientNoUniqueMatch(resource=resource, name=name_or_id) elif len(matched) == 0: not_found_message = (_("Unable to find %(resource)s with name " "or id '%(name_or_id)s'") % { 'resource': resource, 'name_or_id': name_or_id }) raise exceptions.NotFound(message=not_found_message) else: return matched[0]
def find_resource_by_id(client, resource, resource_id, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = _get_resource_plural(cmd_resource, client) resource_plural = _get_resource_plural(resource, client) obj_lister = getattr(client, "list_%s" % cmd_resource_plural) # perform search by id only if we are passing a valid UUID match = re.match(UUID_PATTERN, resource_id) collection = resource_plural if match: params = {'id': resource_id} if fields: params['fields'] = fields if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) if data and data[collection]: return data[collection][0] not_found_message = (_("Unable to find %(resource)s with id " "'%(id)s'") % {'resource': resource, 'id': resource_id}) # 404 is raised by exceptions.NotFound to simulate serverside behavior raise exceptions.NotFound(message=not_found_message)
def _find_resource_by_name(client, resource, name, project_id=None, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = _get_resource_plural(cmd_resource, client) resource_plural = _get_resource_plural(resource, client) obj_lister = getattr(client, "list_%s" % cmd_resource_plural) params = {'name': name} if fields: params['fields'] = fields if project_id: params['tenant_id'] = project_id if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) collection = resource_plural info = data[collection] if len(info) > 1: raise exceptions.NeutronClientNoUniqueMatch(resource=resource, name=name) elif len(info) == 0: not_found_message = (_("Unable to find %(resource)s with name " "'%(name)s'") % {'resource': resource, 'name': name}) # 404 is raised by exceptions.NotFound to simulate serverside behavior raise exceptions.NotFound(message=not_found_message) else: return info[0]
def test_validate_instance_nics(self, create_neutron_cli_mock): test_instances = [ {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "surprise"}]}, {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "foo-bar"}]}, {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "foo-bar"}]}] self.assertRaises(exception.ClusterNetworksNotEqual, models.validate_instance_nics, Mock(), test_instances) test_instances = [ {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "foo-bar"}]}, {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "foo-bar"}]}, {'volume_size': 1, 'flavor_id': '1234', 'nics': [{"net-id": "foo-bar"}]}] create_neutron_cli_mock.return_value.find_resource = Mock( side_effect=neutron_exceptions.NotFound( "Nic id not found %s" % id)) self.assertRaises(exception.NetworkNotFound, models.validate_instance_nics, Mock(), test_instances)
def find_sfc_resource(client, resource, name_or_id): """Returns the id and validate sfc resource.""" path = _resolve_resource_path(resource) try: record = client.show_ext(path + '/%s', name_or_id) return record.get(resource).get('id') except exceptions.NotFound: res_plural = resource + 's' record = client.list_ext(collection=res_plural, path=path, retrieve_all=True) record1 = record.get(res_plural) rec_chk = [] for rec in record1: if rec.get('name') == name_or_id: rec_chk.append(rec.get('id')) if len(rec_chk) > 1: raise exceptions.NeutronClientNoUniqueMatch(resource=resource, name=name_or_id) elif len(rec_chk) == 0: not_found_message = (_("Unable to find %(resource)s with name " "or id '%(name_or_id)s'") % { 'resource': resource, 'name_or_id': name_or_id }) raise exceptions.NotFound(message=not_found_message) else: return rec_chk[0]
def _get_resources_by_filters(self, resource_type, unique_item=False, **filters): """Retrieves item(s) from filters. By default, a list is returned. If unique_item set to True, only the first resource is returned. """ try: resource = getattr(self.neutron_client, 'list_%ss' % resource_type)(**filters) conversion_function = getattr( utils, 'convert_%s_dict_to_model' % resource_type) if not resource['%ss' % resource_type]: # no items found raise neutron_client_exceptions.NotFound() elif unique_item: return conversion_function(resource['%ss' % resource_type][0]) else: return list( map(conversion_function, resource['%ss' % resource_type])) except neutron_client_exceptions.NotFound: message = _('{resource_type} not found ' '({resource_type} Filters: {filters}.').format( resource_type=resource_type, filters=filters) raise getattr( base, '%sNotFound' % ''.join([w.capitalize() for w in resource_type.split('_')]))(message) except Exception: message = _('Error retrieving {resource_type} ' '({resource_type} Filters: {filters}.').format( resource_type=resource_type, filters=filters) LOG.exception(message) raise base.NetworkException(message)
def delete_flow_classifiers(self, context, flowclassifier_id): fc = self.get_resource('flow_classifier', context, flowclassifier_id) if not fc: raise client_exceptions.NotFound() for pc in BOTTOM1_PORTCHAINS: if flowclassifier_id in pc['flow_classifiers']: raise client_exceptions.Conflict("in use") self.delete_resources('flow_classifier', context, flowclassifier_id)
def delete_port_pair_groups(self, context, portpairgroup_id): ppg = self.get_resource('port_pair_group', context, portpairgroup_id) if not ppg: raise client_exceptions.NotFound() for pc in BOTTOM1_PORTCHAINS: if portpairgroup_id in pc['port_pair_groups']: raise client_exceptions.Conflict("in use") self.delete_resources('port_pair_group', context, portpairgroup_id)
def delete_port_pairs(self, context, portpair_id): pp = self.get_resource('port_pair', context, portpair_id) if not pp: raise client_exceptions.NotFound() pp = self.get_resource('port_pair', context, portpair_id) if pp and pp.get('portpairgroup_id'): raise client_exceptions.Conflict("in use") self.delete_resources('port_pair', context, portpair_id)
def test_delete_subnet_inconsistent_os(self): self.set_mock_db_items(fakes.DB_VPC_1, fakes.DB_SUBNET_1) self.neutron.remove_interface_router.side_effect = ( neutron_exception.NotFound()) self.neutron.show_subnet.return_value = ({'subnet': fakes.OS_SUBNET_1}) self.neutron.delete_network.side_effect = ( neutron_exception.NetworkInUseClient()) resp = self.execute('DeleteSubnet', {'SubnetId': fakes.ID_EC2_SUBNET_1}) self.assertEqual(True, resp['return']) self.neutron.show_subnet.side_effect = neutron_exception.NotFound() resp = self.execute('DeleteSubnet', {'SubnetId': fakes.ID_EC2_SUBNET_1}) self.assertEqual(True, resp['return'])
def test_delete_subnetpool_not_found(self): self.patchobject(neutronclient.Client, 'delete_subnetpool', side_effect=qe.NotFound(status_code=404)) rsrc = self.create_subnetpool() ref_id = rsrc.FnGetRefId() self.assertEqual('fc68ea2c-b60b-4b4f-bd82-94ec81110766', ref_id) self.assertIsNone(scheduler.TaskRunner(rsrc.delete)()) self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
def test_delete_floating_ip_not_found(self, mock_has_service, mock_neutron_client): mock_has_service.return_value = True mock_neutron_client.delete_floatingip.side_effect = \ n_exc.NotFound() ret = self.cloud.delete_floating_ip(floating_ip_id='a-wild-id-appears') self.assertFalse(ret)
def make_subnet_args(self, link_params, network_id): """ Function to create kwargs required for neutron_subnet_create API Arguments: link_params: Protobuf GI object RwcalYang.YangData_RwProject_Project_VirtualLinkReqParams() Returns: A kwargs dictionary for subnet operation """ kwargs = {'network_id' : network_id, 'dhcp_params': {'enable_dhcp': True}, 'gateway_ip' : None,} if link_params.ip_profile_params.has_field('ip_version'): kwargs['ip_version'] = 6 if link_params.ip_profile_params.ip_version == 'ipv6' else 4 else: kwargs['ip_version'] = 4 if link_params.ip_profile_params.has_field('subnet_address'): kwargs['cidr'] = link_params.ip_profile_params.subnet_address elif link_params.ip_profile_params.has_field('subnet_prefix_pool'): name = link_params.ip_profile_params.subnet_prefix_pool pools = [ p['id'] for p in self.driver._neutron_subnet_prefix_pool if p['name'] == name ] if not pools: self.log.error("Could not find subnet pool with name :%s to be used for network: %s", link_params.ip_profile_params.subnet_prefix_pool, link_params.name) raise NeutronException.NotFound("SubnetPool with name %s not found"%(link_params.ip_profile_params.subnet_prefix_pool)) kwargs['subnetpool_id'] = pools[0] elif link_params.has_field('subnet'): kwargs['cidr'] = link_params.subnet else: raise NeutronException.NeutronException("No IP Prefix or Pool name specified") if link_params.ip_profile_params.has_field('dhcp_params'): if link_params.ip_profile_params.dhcp_params.has_field('enabled'): kwargs['dhcp_params']['enable_dhcp'] = link_params.ip_profile_params.dhcp_params.enabled if link_params.ip_profile_params.dhcp_params.has_field('start_address'): kwargs['dhcp_params']['start_address'] = link_params.ip_profile_params.dhcp_params.start_address if link_params.ip_profile_params.dhcp_params.has_field('count'): kwargs['dhcp_params']['count'] = link_params.ip_profile_params.dhcp_params.count if link_params.ip_profile_params.has_field('dns_server'): kwargs['dns_server'] = [] for server in link_params.ip_profile_params.dns_server: kwargs['dns_server'].append(server.address) if link_params.ip_profile_params.has_field('gateway_address'): kwargs['gateway_ip'] = link_params.ip_profile_params.gateway_address return kwargs
def test_delete_security_group_rule_not_found(self, mock_nova, mock_neutron): self.cloud.secgroup_source = 'neutron' mock_neutron.delete_security_group_rule.side_effect = ( neutron_exc.NotFound()) r = self.cloud.delete_security_group('doesNotExist') self.assertFalse(r) self.cloud.secgroup_source = 'nova' mock_neutron.security_group_rules.delete.side_effect = ( nova_exc.NotFound("uh oh")) r = self.cloud.delete_security_group('doesNotExist') self.assertFalse(r)
def test_get_server_external_ipv4_neutron_exception( self, mock_get_server_ip, mock_search_ports, mock_has_service): # Testing Clouds with a non working Neutron mock_has_service.return_value = True mock_search_ports.side_effect = neutron_exceptions.NotFound() mock_get_server_ip.return_value = PUBLIC_V4 srv = meta.obj_to_dict( fakes.FakeServer(id='test-id', name='test-name', status='ACTIVE')) ip = meta.get_server_external_ipv4(cloud=shade.openstack_cloud(), server=srv) self.assertEqual(PUBLIC_V4, ip) self.assertTrue(mock_get_server_ip.called)
def delete_resources(self, _type, ctx, _id): if _type == constants.RT_PORT_PAIR: pp = self.get_resource(constants.RT_PORT_PAIR, ctx, _id) if not pp: raise client_exceptions.NotFound() if pp['portpairgroup_id']: raise client_exceptions.Conflict(constants.STR_IN_USE) elif _type == constants.RT_FLOW_CLASSIFIER: pc_list = self._res_map[self.region_name][constants.RT_PORT_CHAIN] for pc in pc_list: if _id in pc['flow_classifiers']: raise client_exceptions.Conflict(constants.STR_IN_USE) return super(FakeClient, self).delete_resources(_type, ctx, _id)
def _port_get(self, port_id): """ Returns a dictionary object describing the attributes of the port Arguments: port_id (string): UUID of the port Returns: A dictionary object of the port attributes """ port = self._nt_drv.list_ports(id=port_id)['ports'] if not port: raise NeutronException.NotFound("Could not find port_id %s" % (port_id)) return port[0]
def find_resource_by_name_or_id(client, resource, name_or_id, project_id=None, cmd_resource=None, parent_id=None, fields=None): try: return find_resource_by_id(client, resource, name_or_id, cmd_resource, parent_id, fields) except exceptions.NotFound: try: return _find_resource_by_name(client, resource, name_or_id, project_id, cmd_resource, parent_id, fields) except exceptions.NotFound: not_found_message = (_("Unable to find %(resource)s with name " "or id '%(name_or_id)s'") % {'resource': resource, 'name_or_id': name_or_id}) raise exceptions.NotFound( message=not_found_message)
def take_action(self, parsed_args): client = self.app.client_manager.nuageclient project_id = self._find_project_id(parsed_args.project) try: obj = client.show_project_netpartition_mapping( project_id)[RESOURCE_NAME] except neutron_exc.NotFound: raise neutron_exc.NotFound('No Project netpartition ' 'mapping was found for Project ' '{}.'.format(parsed_args.project)) try: obj['net_partition_name'] = client.show_net_partition( obj['net_partition_id'])['net_partition']['name'] except neutron_exc.NotFound: pass columns, display_columns = column_util.get_columns(obj, _attr_map) data = utils.get_dict_properties(obj, columns) return display_columns, data
def find_resource(self, resource, name_or_id, project_id=None, cmd_resource=None, parent_id=None, fields=None): if resource == 'security_group': # lookup first by unique id sg = self._fake_security_groups.get(name_or_id) if sg: return sg # lookup by name, raise an exception on duplicates res = None for sg in self._fake_security_groups.values(): if sg['name'] == name_or_id: if res: raise n_exc.NeutronClientNoUniqueMatch( resource=resource, name=name_or_id) res = sg if res: return res raise n_exc.NotFound("Fake %s '%s' not found." % (resource, name_or_id))
def get_network_by_name(self, network_name): if network_name is None: raise ValueError('network_name must be provided') neutron_client = self.__get_neutron_client() logger.debug('Retrieving network with name %s', network_name) result = neutron_client.list_networks() matches = [] for network in result['networks']: if network['name'] == network_name: matches.append(network) if len(matches) > 1: raise neutronexceptions.NeutronClientNoUniqueMatch( resource='Network', name=network_name) elif len(matches) == 1: return matches[0] else: raise neutronexceptions.NotFound( message='Unable to find network with name \'{0}\''.format( network_name))
def test_safe_delete_vpnservice(self): vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.neutron.delete_vpnservice.assert_called_once_with( fakes.ID_OS_VPNSERVICE_1) self.neutron.delete_vpnservice.side_effect = ( neutron_exception.NotFound()) with fixtures.FakeLogger() as log: vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.assertEqual(0, len(log.output)) self.neutron.delete_vpnservice.side_effect = ( neutron_exception.Conflict()) with fixtures.FakeLogger() as log: vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.assertIn(fakes.ID_EC2_SUBNET_1, log.output) self.assertIn(fakes.ID_OS_VPNSERVICE_1, log.output)
def test_delete_association_successful_if_create_failed(self): server = self.fc.servers.list()[0] self.patchobject(self.fc.servers, 'get', return_value=server) self.mock_create_floatingip() self.mock_show_floatingip() self.patchobject(server, 'interface_list', side_effect=[q_exceptions.NotFound('Not FOund')]) t = template_format.parse(eip_template_ipassoc) stack = utils.parse_stack(t) self.create_eip(t, stack, 'IPAddress') resource_defns = stack.t.resource_definitions(stack) rsrc = eip.ElasticIpAssociation('IPAssoc', resource_defns['IPAssoc'], stack) self.assertIsNone(rsrc.validate()) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.create)) self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state) scheduler.TaskRunner(rsrc.delete)() self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
def test_stop_vpn_connection(self): # delete several connections os_conn_ids = [fakes.random_os_id() for _x in range(3)] fake_conn = { 'os_ipsec_site_connections': { fakes.random_ec2_id('subnet'): conn_id for conn_id in os_conn_ids } } vpn_connection_api._stop_vpn_connection(self.neutron, fake_conn) self.assertEqual(3, self.neutron.delete_ipsec_site_connection.call_count) for conn_id in os_conn_ids: self.neutron.delete_ipsec_site_connection.assert_any_call(conn_id) # delete several connections with exception suppressing self.neutron.reset_mock() self.neutron.delete_ipsec_site_connection.side_effect = [ None, neutron_exception.NotFound(), None ] vpn_connection_api._stop_vpn_connection(self.neutron, fake_conn) self.assertEqual(3, self.neutron.delete_ipsec_site_connection.call_count)
def test_delete_association_successful_if_create_failed(self): self._mock_server(mock_interface=True) self.mock_create_floatingip() self.mock_show_floatingip('fc68ea2c-b60b-4b4f-bd82-94ec81110766') self.mock_list_floatingips() self.mock_update_floatingip(ex=q_exceptions.NotFound('Not Found')) self.m.ReplayAll() t = template_format.parse(eip_template_ipassoc) stack = utils.parse_stack(t) self.create_eip(t, stack, 'IPAddress') resource_defns = stack.t.resource_definitions(stack) rsrc = eip.ElasticIpAssociation('IPAssoc', resource_defns['IPAssoc'], stack) self.assertIsNone(rsrc.validate()) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.create)) self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state) scheduler.TaskRunner(rsrc.delete)() self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state) self.m.VerifyAll()
def __configure_mock_neutron_driver_with_not_found(self, network_name): self.mock_neutron_driver.get_network_by_name.side_effect = neutronexceptions.NotFound( message='Unable to find network with name \'{0}\''.format( network_name))
def test_delete_not_found(self): self._create_stack() self.rbac.resource_id_set('bca25c0e-5937-4341-a911-53e202629269') self.neutron_client.delete_rbac_policy.side_effect = ( exceptions.NotFound()) self.assertIsNone(self.rbac.handle_delete())
def test__neutron_exceptions_resource_not_found(self): with mock.patch.object(shade._tasks, 'NetworkList', side_effect=n_exc.NotFound()): self.assertRaises(exc.OpenStackCloudResourceNotFound, self.cloud.list_networks)
def delete_port_chains(self, context, portchain_id): pc = self.get_resource('port_chain', context, portchain_id) if not pc: raise client_exceptions.NotFound() self.delete_resources('port_chain', context, portchain_id)
def test_init_with_invalid_network_id(self): self.mock_net.side_effect = neutron_exceptions.NotFound() self.assertRaises(exceptions.FloatingIPNetworkNotFound, neutron.FloatingIPPool, 'invalid-net-id')