def get_zone_id(self, zone_id_or_name): client = self.client(version='2') try: zone_obj = client.zones.get(zone_id_or_name) return zone_obj['id'] except exceptions.NotFound: zones = client.zones.list(criterion=dict(name=zone_id_or_name)) if len(zones) == 1: return zones[0]['id'] raise heat_exception.EntityNotFound(entity='Designate Zone', name=zone_id_or_name)
def get_secret_by_ref(self, secret_ref): try: secret = self.client().secrets.get(secret_ref) # Force lazy loading. TODO(therve): replace with to_dict() secret.name return secret except Exception as ex: if self.is_not_found(ex): raise exception.EntityNotFound( entity="Secret", name=secret_ref) raise
def get_volume_type(self, volume_type): vt_id = None volume_type_list = self.client().volume_types.list() for vt in volume_type_list: if volume_type in [vt.name, vt.id]: vt_id = vt.id break if vt_id is None: raise exception.EntityNotFound(entity='VolumeType', name=volume_type) return vt_id
def test_stack_resource_describe_nonexist_stack(self, mock_get): non_exist_identifier = identifier.HeatIdentifier( self.ctx.tenant_id, 'wibble', '18d06e2e-44d3-4bef-9fbf-52480d604b02') mock_get.side_effect = exception.EntityNotFound(entity='Stack', name='test') ex = self.assertRaises(dispatcher.ExpectedException, self.eng.describe_stack_resource, self.ctx, non_exist_identifier, 'WebServer') self.assertEqual(exception.EntityNotFound, ex.exc_info[0]) mock_get.assert_called_once_with(self.ctx, non_exist_identifier)
def get_project_id(self, project): try: project_obj = self.client().client.projects.get(project) return project_obj.id except exceptions.NotFound: project_list = self.client().client.projects.list(name=project) for project_obj in project_list: if project_obj.name == project: return project_obj.id raise exception.EntityNotFound(entity='KeystoneProject', name=project)
def get_net_id_by_label(self, label): try: net_id = self.client().networks.find(label=label).id except exceptions.NotFound as ex: LOG.debug('Nova network (%(net)s) not found: %(ex)s', {'net': label, 'ex': ex}) raise exception.EntityNotFound(entity='Nova network', name=label) except exceptions.NoUniqueMatch as exc: LOG.debug('Nova network (%(net)s) is not unique matched: %(exc)s', {'net': label, 'exc': exc}) raise exception.PhysicalResourceNameAmbiguity(name=label) return net_id
def get_job_type(self, job_type): """Find the job type :param job_type: the name of sahara job type to find :returns: the name of :job_type: :raises: exception.EntityNotFound """ try: filters = {'name': job_type} return self.client().job_types.find_unique(**filters) except sahara_base.APIException: raise exception.EntityNotFound(entity='Job Type', name=job_type)
def test_set_watch_state_noexist(self, mock_load): state = watchrule.WatchRule.ALARM # State valid mock_load.side_effect = exception.EntityNotFound(entity='Watch Rule', name='test') ex = self.assertRaises(dispatcher.ExpectedException, self.eng.set_watch_state, self.ctx, watch_name="nonexistent", state=state) self.assertEqual(exception.EntityNotFound, ex.exc_info[0]) mock_load.assert_called_once_with(self.ctx, "nonexistent")
def get_plugin_id(self, plugin_name): """Get the id for the specified plugin name. :param plugin_name: the name of the plugin to find :returns: the id of :plugin: :raises exception.EntityNotFound: """ try: self.client().plugins.get(plugin_name) except sahara_base.APIException: raise exception.EntityNotFound(entity='Plugin', name=plugin_name)
def get_user_id(self, user): if user is None: return None try: user_obj = self.client().client.users.get(user) return user_obj.id except exceptions.NotFound: user_list = self.client().client.users.list(name=user) for user_obj in user_list: if user_obj.name == user: return user_obj.id raise exception.EntityNotFound(entity='KeystoneUser', name=user)
def get_domain_id(self, domain): if domain is None: return None try: domain_obj = self.client().client.domains.get(domain) return domain_obj.id except exceptions.NotFound: domain_list = self.client().client.domains.list(name=domain) for domain_obj in domain_list: if domain_obj.name == domain: return domain_obj.id raise exception.EntityNotFound(entity='KeystoneDomain', name=domain)
def get_group_id(self, group): if group is None: return None try: group_obj = self.client().client.groups.get(group) return group_obj.id except exceptions.NotFound: group_list = self.client().client.groups.list(name=group) for group_obj in group_list: if group_obj.name == group: return group_obj.id raise exception.EntityNotFound(entity='KeystoneGroup', name=group)
def _stub_nova_server_get(self, not_found=False): mock_server = mock.MagicMock() mock_server.image = {'id': 'dd619705-468a-4f7d-8a06-b84794b3561a'} mock_server.flavor = {'id': '1'} mock_server.key_name = 'test' mock_server.security_groups = [{u'name': u'hth_test'}] if not_found: self.patchobject(nova.NovaClientPlugin, 'get_server', side_effect=exception.EntityNotFound( entity='Server', name='5678')) else: self.patchobject(nova.NovaClientPlugin, 'get_server', return_value=mock_server)
def get_secret_by_ref(self, secret_ref): try: secret = self.client().secrets.get(secret_ref) # Force lazy loading. TODO(therve): replace with to_dict() secret.name return secret except Exception as ex: if self.is_not_found(ex): raise exception.EntityNotFound( entity="Secret", name=secret_ref) LOG.info('Failed to get Barbican secret from reference %s' % ( secret_ref)) raise
def get_live_resource_data(self): try: resource_data = self._show_resource() if not resource_data: # use attribute error, e.g. API call get raises AttributeError, # when evt is not exists or not ready (cinder bug 1562024). raise AttributeError() except Exception as ex: if (self.client_plugin().is_not_found(ex) or isinstance(ex, AttributeError)): raise exception.EntityNotFound(entity='Resource', name=self.name) raise return resource_data
def test_openstack_exception_with_kwargs(self): wrapper = fault.FaultWrapper(None) msg = wrapper._error(heat_exc.EntityNotFound(entity='Stack', name='a')) expected = { 'code': 404, 'error': { 'message': 'The Stack (a) could not be found.', 'traceback': None, 'type': 'EntityNotFound' }, 'explanation': 'The resource could not be found.', 'title': 'Not Found' } self.assertEqual(expected, msg)
def test_resource_delete_notfound(self): # if a resource is not found, handle_delete() should not raise # an exception. s = self.parse_stack() self.assertIsNone(scheduler.TaskRunner(s['test_me'].create)()) res_name = self.stack['test_me'].physical_resource_name() self.wr = watchrule.WatchRule.load(self.ctx, watch_name=res_name) with mock.patch.object(watchrule.WatchRule, 'destroy') as bad_destroy: watch_exc = exception.EntityNotFound(entity='Watch Rule', name='test') bad_destroy.side_effect = watch_exc self.assertIsNone(scheduler.TaskRunner(s['test_me'].delete)())
def get_server(self, server): """Return fresh server object. Substitutes Nova's NotFound for Heat's EntityNotFound, to be returned to user as HTTP error. """ try: return self.client().servers.get(server) except exceptions.NotFound as ex: LOG.warn(_LW('Server (%(server)s) not found: %(ex)s'), { 'server': server, 'ex': ex }) raise exception.EntityNotFound(entity='Server', name=server)
def get_host(self, host_name): """Get the host id specified by name. :param host_name: the name of host to find :returns: the list of match hosts :raises: exception.EntityNotFound """ host_list = self.client().hosts.list() for host in host_list: if host.host_name == host_name and host.service == self.COMPUTE: return host raise exception.EntityNotFound(entity='Host', name=host_name)
def get_service_id(self, service): try: service_obj = self.client().client.services.get(service) return service_obj.id except exceptions.NotFound: service_list = self.client().client.services.list(name=service) if len(service_list) == 1: return service_list[0].id elif len(service_list) > 1: raise exception.KeystoneServiceNameConflict(service=service) else: raise exception.EntityNotFound(entity='KeystoneService', name=service)
def get_image_id(self, image_identifier): """Return the ID for the specified image name or identifier. :param image_identifier: image name or a UUID-like identifier :returns: the id of the requested :image_identifier: :raises exception.EntityNotFound: :raises exception.PhysicalResourceNameAmbiguity: """ # leave this method for backward compatibility try: return self.find_resource_by_name_or_id('images', image_identifier) except exception.EntityNotFound: raise exception.EntityNotFound(entity='Image', name=image_identifier)
def get_user_id(self, user, domain=None): if user is None: return None if not domain: user, domain = self.parse_entity_with_domain(user, 'KeystoneUser') try: user_obj = self.client().client.users.get(user) return user_obj.id except ks_exceptions.NotFound: try: user_obj = self.client().client.users.find(name=user, domain_id=domain) return user_obj.id except ks_exceptions.NotFound: pass raise exception.EntityNotFound(entity='KeystoneUser', name=user)
def test_launch_config_create_with_instanceid_not_found(self): t = template_format.parse(inline_templates.as_template) lcp = t['Resources']['LaunchConfig']['Properties'] lcp['InstanceId'] = '5678' stack = utils.parse_stack(t, params=inline_templates.as_params) rsrc = stack['LaunchConfig'] self.patchobject(nova.NovaClientPlugin, 'get_server', side_effect=exception.EntityNotFound( entity='Server', name='5678')) msg = ("Property error : " "Resources.LaunchConfig.Properties.InstanceId: " "Error validating value '5678': The Server (5678) " "could not be found.") exc = self.assertRaises(exception.StackValidationFailed, rsrc.validate) self.assertIn(msg, six.text_type(exc))
def test_initiate_propagate_rsrc_retriggers_check_rsrc_on_new_stack_update( self, mock_stack_load, mock_rcr, mock_cru, mock_crc, mock_pcr, mock_csc): key = sync_point.make_key(self.resource.id, self.stack.current_traversal, self.is_update) mock_pcr.side_effect = exception.EntityNotFound(entity='Sync Point', name=key) updated_stack = stack.Stack(self.ctx, self.stack.name, self.stack.t, self.stack.id, current_traversal='some_newy_trvl_uuid') mock_stack_load.return_value = updated_stack self.cr._initiate_propagate_resource(self.ctx, self.resource.id, self.stack.current_traversal, self.is_update, self.resource, self.stack) mock_rcr.assert_called_once_with(self.ctx, self.resource.id, updated_stack)
def get_role_id(self, role, domain=None): if role is None: return None if not domain: role, domain = self.parse_entity_with_domain(role, 'KeystoneRole') try: role_obj = self.client().client.roles.get(role) return role_obj.id except ks_exceptions.NotFound: role_list = self.client().client.roles.list(name=role, domain=domain) for role_obj in role_list: if role_obj.name == role: return role_obj.id raise exception.EntityNotFound(entity='KeystoneRole', name=role)
def get_user_id(self, user, domain=None): if user is None: return None if not domain: user, domain = self.parse_entity_with_domain(user, 'KeystoneUser') try: user_obj = self.client().client.users.get(user) return user_obj.id except ks_exceptions.NotFound: user_list = self.client().client.users.list(name=user, domain=domain) for user_obj in user_list: if user_obj.name == user: return user_obj.id raise exception.EntityNotFound(entity='KeystoneUser', name=user)
def get_group_id(self, group, domain=None): if group is None: return None if not domain: group, domain = self.parse_entity_with_domain(group, 'KeystoneGroup') try: group_obj = self.client().client.groups.get(group) return group_obj.id except ks_exceptions.NotFound: group_list = self.client().client.groups.list(name=group, domain=domain) for group_obj in group_list: if group_obj.name == group: return group_obj.id raise exception.EntityNotFound(entity='KeystoneGroup', name=group)
def test_remote_exception(self): # We want tracebacks cfg.CONF.set_override('debug', True) error = heat_exc.EntityNotFound(entity='Stack', name='a') exc_info = (type(error), error, None) serialized = rpc_common.serialize_remote_exception(exc_info) remote_error = rpc_common.deserialize_remote_exception( serialized, ["heat.common.exception"]) wrapper = fault.FaultWrapper(None) msg = wrapper._error(remote_error) expected_message, expected_traceback = str( remote_error).split('\n', 1) expected = {'code': 404, 'error': {'message': expected_message, 'traceback': expected_traceback, 'type': 'EntityNotFound'}, 'explanation': 'The resource could not be found.', 'title': 'Not Found'} self.assertEqual(expected, msg)
def parse_entity_with_domain(self, entity_with_domain, entity_type): """Parse keystone entity user/role/project with domain. entity_with_domain should be in entity{domain} format. Returns a tuple of (entity, domain). """ try: match = re.search(r"\{(.*?)\}$", entity_with_domain) if match: entity = entity_with_domain[:match.start()] domain = match.group(1) domain = self.get_domain_id(domain) return (entity, domain) else: return (entity_with_domain, None) except Exception: raise exception.EntityNotFound(entity=entity_type, name=entity_with_domain)
def get_project_id(self, project, domain=None): if project is None: return None if not domain: project, domain = self.parse_entity_with_domain( project, 'KeystoneProject') try: project_obj = self.client().client.projects.get(project) return project_obj.id except ks_exceptions.NotFound: project_list = self.client().client.projects.list(name=project, domain=domain) for project_obj in project_list: if project_obj.name == project: return project_obj.id raise exception.EntityNotFound(entity='KeystoneProject', name=project)