def resources(self, value): """Return a generator of resources :param value: This can be a stack object, or the name of a stack for which the resources are to be listed. :returns: A generator of resource objects if the stack exists and there are resources in it. If the stack cannot be found, an exception is thrown. :rtype: A generator of :class:`~openstack.orchestration.v1.resource.Resource` :raises: :class:`~openstack.exceptions.ResourceNotFound` when the stack cannot be found. """ # first try treat the value as a stack object or an ID try: stk = stack.Stack.from_id(value) except ValueError: raise exceptions.ResourceNotFound("No stack found for %(v)s" % {'v': value}) # if stack object doesn't contain a valid name, it means the object # was created on the fly so we need to retrieve its name if not stk.name: stk = self.find_stack(value) if stk is None: raise exceptions.ResourceNotFound("No stack found for %(v)s" % {'v': value}) path_args = { 'stack_name': stk.name, 'stack_id': stk.id, } return self._list(stack_resource.Resource, paginated=False, path_args=path_args)
def test_node_delete_success(self): node = self._create_node() self.senlin_mock.get_node.side_effect = [ exceptions.ResourceNotFound('SenlinNode'), ] scheduler.TaskRunner(node.delete)() self.senlin_mock.delete_node.assert_called_once_with(node.resource_id)
def test_policy_update_not_found(self): arglist = ['--name', 'new_policy', 'c6b8b252'] parsed_args = self.check_parser(self.cmd, arglist, []) self.mock_client.get_policy.side_effect = sdk_exc.ResourceNotFound() error = self.assertRaises(sdk_exc.ResourceNotFound, self.cmd.take_action, parsed_args) self.assertIn('ResourceNotFound: ResourceNotFound', str(error))
def test_get_not_found(self): self.res.fetch.side_effect = exceptions.ResourceNotFound( message="test", http_status=404) self.assertRaisesRegex( exceptions.ResourceNotFound, "test", self.sot._get, RetrieveableResource, self.res)
def list(cls, session, ignore_missing=True, base_path=None, **params): session = cls._get_session(session) excludes = set(["paginated", "stream_name", "query_checkpoint", "id"]) print(params) if len(params) > 2: base_path = f'checkpoints?stream_name={params["stream_name"]}&' for key, value in params.items(): if key not in excludes: base_path = base_path + key + "=" + value + "&" base_path = base_path[:-1] else: base_path = f'checkpoints?stream_name={params["stream_name"]}' microversion = cls._get_microversion_for_list(session) data = session.get(base_path, headers={"Accept": "application/json"}, params=None, microversion=microversion) exceptions.raise_from_response(data) result = data.json() print(result) if result is not None: return result if ignore_missing: return None raise exceptions.ResourceNotFound("No %s found for %s" % (cls.__name__, params['name_or_id']))
def test_validate_false(self): self.mock_get_profile.side_effect = exceptions.ResourceNotFound( 'PROFILE_ID') self.assertFalse(self.constraint.validate("PROFILE_ID", self.ctx)) self.mock_get_profile.side_effect = exceptions.HttpException( 'PROFILE_ID') self.assertFalse(self.constraint.validate("PROFILE_ID", self.ctx))
def fetch(self, session, requires_id=True, error_message=None): stk = super(Stack, self).fetch(session, requires_id=requires_id, error_message=error_message) if stk and stk.status in ['DELETE_COMPLETE', 'ADOPT_COMPLETE']: raise exceptions.ResourceNotFound("No stack found for %s" % stk.id) return stk
def test_success(self, mock_pr): pr = mock_pr.return_value instances = [{ 'hostname': 'host1' }, { 'hostname': 'host3' }, { 'hostname': 'host2', 'resource_class': 'compute', 'capabilities': { 'answer': '42' } }] existing = mock.MagicMock(hostname='host2') pr.show_instance.side_effect = [ sdk_exc.ResourceNotFound(""), metalsmith.exceptions.Error(""), existing, ] action = baremetal_deploy.CheckExistingInstancesAction(instances) result = action.run(mock.Mock()) self.assertEqual( { 'instances': [existing.to_dict.return_value], 'not_found': [{ 'hostname': 'host1', 'image': 'overcloud-full' }, { 'hostname': 'host3', 'image': 'overcloud-full' }] }, result) pr.show_instance.assert_has_calls( [mock.call(host) for host in ['host1', 'host3', 'host2']])
def fetch(self, session, requires_id=True, base_path=None, error_message=None, **params): """Get a remote resource based on this instance. :param session: The session to use for making this request. :type session: :class:`~keystoneauth1.adapter.Adapter` :param boolean requires_id: A boolean indicating whether resource ID should be part of the requested URI. :param str base_path: Base part of the URI for fetching resources, if different from :data:`~openstack.resource.Resource.base_path`. :param str error_message: An Error message to be returned if requested object does not exist. :param dict params: Additional parameters that can be consumed. :return: This :class:`Resource` instance. :raises: :exc:`~openstack.exceptions.MethodNotSupported` if :data:`Resource.allow_fetch` is not set to ``True``. :raises: :exc:`~openstack.exceptions.ResourceNotFound` if the resource was not found. """ data = self.list(session, paginated=False, id=self.id) result = self._get_one_match(self.id, data) if not result: raise exceptions.ResourceNotFound("No Instance found for %s" % (self.id)) self._body.attributes.update(result._body.attributes) self._body.clean() return self
def get_quotas(self, session, requires_id=True, params=None): if not self.allow_get: raise exceptions.MethodNotSupported(self, "get") try: request = self._prepare_request(requires_id=requires_id) endpoint_override = self.service.get_endpoint_override() service = self.get_service_filter(self, session) response = session.get(request.uri, endpoint_filter=self.service, microversion=service.microversion, endpoint_override=endpoint_override, params=params) self._translate_response(response) return self except exceptions.NotFoundException as e: raise exceptions.ResourceNotFound(message="No %s found for %s" % ("Quota", self.tenant_id), details=e.details, response=e.response, request_id=e.request_id, url=e.url, method=e.method, http_status=e.http_status, cause=e.cause, code=e.code)
def take_action(self, parsed_args): masakari_client = self.app.client_manager.ha uuid = masakariclient_utils.get_uuid_by_name(masakari_client, parsed_args.segment) attrs = { 'name': parsed_args.name, 'description': parsed_args.description, 'recovery_method': parsed_args.recovery_method, 'service_type': parsed_args.service_type, } if masakari_client.default_microversion: api_version = api_versions.APIVersion( masakari_client.default_microversion) if (api_version >= api_versions.APIVersion("1.2") and parsed_args.is_enabled is not None): attrs['is_enabled'] = strutils.bool_from_string( parsed_args.is_enabled, strict=True) # Remove not specified keys attrs = masakariclient_utils.remove_unspecified_items(attrs) try: masakari_client.update_segment(segment=uuid, **attrs) # Reraise. To unify exceptions with other functions. except sdk_exc.NotFoundException: LOG.debug(_("Segment is not found: %s"), parsed_args) raise sdk_exc.ResourceNotFound(_('No Segment found for %s') % uuid) except Exception as ex: LOG.debug(_("Failed to update segment: %s"), parsed_args) raise ex return _show_segment(masakari_client, uuid)
def find(cls, session, name_or_id, ignore_missing=True, **params): # No direct request possible, thus go directly to list data = cls.list(session, **params) result = None for maybe_result in data: # Since ID might be both int and str force cast id_value = str(cls._get_id(maybe_result)) name_value = maybe_result.name if str(name_or_id) in (id_value, name_value): if 'host' in params and maybe_result['host'] != params['host']: continue # Only allow one resource to be found. If we already # found a match, raise an exception to show it. if result is None: result = maybe_result else: msg = "More than one %s exists with the name '%s'." msg = (msg % (cls.__name__, name_or_id)) raise exceptions.DuplicateResource(msg) if result is not None: return result if ignore_missing: return None raise exceptions.ResourceNotFound( "No %s found for %s" % (cls.__name__, name_or_id))
def delete(self, session, has_body=False, ignore_missing=True, **data): """Delete the remote resource based on this instance. :param session: The session to use for making this request. :param has_body: Should mapping response body to resource. :param ignore_missing: Ignore missing or error. :param data: Query conditions in delete operation. :return: This :class:`Resource` instance. """ if not self.allow_delete: raise exceptions.MethodNotSupported(self, "delete") request = self._prepare_request() endpoint_override = self.service.get_endpoint_override() query_params = self._query_mapping._transpose(data) try: response = session.delete(request.uri, endpoint_filter=self.service, endpoint_override=endpoint_override, headers={"Accept": ""}, params=query_params) except exceptions.NotFoundException: if ignore_missing: return None else: raise exceptions.ResourceNotFound( message="Not found the resource.") self._translate_response(response, has_body=has_body) return self
def list(cls, session, ignore_missing=True, base_path=None, **params): session = cls._get_session(session) # concat attrs to build a new base_path while excluding unnecessary params excludes = set( ["paginated", "stream_name", "prepend_key", "query_cursor"]) base_path = f'cursors?stream-name={params["stream_name"]}&' for key, value in params.items(): if key not in excludes: base_path = base_path + key.replace("_", "-") + "=" + value + "&" base_path = base_path[:-1] microversion = cls._get_microversion_for_list(session) data = session.get(base_path, headers={"Accept": "application/json"}, params=None, microversion=microversion) exceptions.raise_from_response(data) result = data.json() if result is not None: return result if ignore_missing: return None raise exceptions.ResourceNotFound("No %s found for %s" % (cls.__name__, params['name_or_id']))
def _get(self, resource_type, value=None, path_args=None, args=None): """Get a resource :param resource_type: The type of resource to get. :type resource_type: :class:`~openstack.resource.Resource` :param value: The value to get. Can be either the ID of a resource or a :class:`~openstack.resource.Resource` subclass. :param path_args: A dict containing arguments for forming the request URL, if needed. :param args: A optional dict containing arguments that will be translated into query strings when forming the request URL. :returns: The result of the ``get`` :rtype: :class:`~openstack.resource.Resource` """ res = self._get_resource(resource_type, value, path_args) try: return res.get(self._session, args=args) except exceptions.NotFoundException as e: raise exceptions.ResourceNotFound(message="No %s found for %s" % (resource_type.__name__, value), details=e.details, response=e.response, request_id=e.request_id, url=e.url, method=e.method, http_status=e.http_status, cause=e.cause)
def take_action(self, parsed_args): masakari_client = self.app.client_manager.ha segment_id = masakariclient_utils.get_uuid_by_name( masakari_client, parsed_args.segment_id) uuid = masakariclient_utils.get_uuid_by_name(masakari_client, parsed_args.host, segment=segment_id) attrs = { 'name': parsed_args.name, 'type': parsed_args.type, 'control_attributes': parsed_args.control_attributes, 'reserved': parsed_args.reserved, 'on_maintenance': parsed_args.on_maintenance, } # Remove not specified keys attrs = masakariclient_utils.remove_unspecified_items(attrs) try: masakari_client.update_host(uuid, segment_id=segment_id, **attrs) except sdk_exc.NotFoundException: # Reraise. To unify exceptions with other functions. LOG.debug(_("Segment host is not found: %s"), parsed_args) raise sdk_exc.ResourceNotFound(_('No Host found for %s') % uuid) except Exception as ex: LOG.debug(_("Failed to update segment host: %s"), parsed_args) raise ex return _show_host(masakari_client, segment_id, uuid)
def test_validate_false(self): self.mock_get_cluster.side_effect = exceptions.ResourceNotFound( 'CLUSTER_ID') self.assertFalse(self.constraint.validate("CLUSTER_ID", self.ctx)) self.mock_get_cluster.side_effect = exceptions.HttpException( 'CLUSTER_ID') self.assertFalse(self.constraint.validate("CLUSTER_ID", self.ctx))
def test_on_present_sriov(self, ged, get_k8s_client, update_port_pci_info, activate_vif): ged.return_value = [self._driver] kp = kuryrport.KuryrPortHandler() self._vif2.plugin = constants.KURYR_VIF_TYPE_SRIOV self._vif2.active = True self._kp['status']['vifs'] = { 'eth0': { 'default': True, 'vif': self._vif2.obj_to_primitive() }, 'eth1': { 'default': False, 'vif': self._vif1.obj_to_primitive() } } CONF.set_override('enable_node_annotations', True, group='sriov') self.addCleanup(CONF.clear_override, 'enable_node_annotations', group='sriov') activate_vif.side_effect = os_exc.ResourceNotFound() kp.on_present(self._kp) update_port_pci_info.assert_called_once_with(self._host, self._vif2)
def test_fetch(self): sess = mock.Mock() sess.default_microversion = None sot = stack.Stack(**FAKE) sess.get = mock.Mock() sess.get.side_effect = [ test_resource.FakeResponse( {'stack': { 'stack_status': 'CREATE_COMPLETE' }}, 200), test_resource.FakeResponse( {'stack': { 'stack_status': 'CREATE_COMPLETE' }}, 200), exceptions.ResourceNotFound(message='oops'), test_resource.FakeResponse( {'stack': { 'stack_status': 'DELETE_COMPLETE' }}, 200) ] self.assertEqual(sot, sot.fetch(sess)) sess.get.assert_called_with('stacks/{id}'.format(id=sot.id), microversion=None) sot.fetch(sess, resolve_outputs=False) sess.get.assert_called_with( 'stacks/{id}?resolve_outputs=False'.format(id=sot.id), microversion=None) ex = self.assertRaises(exceptions.ResourceNotFound, sot.fetch, sess) self.assertEqual('oops', str(ex)) ex = self.assertRaises(exceptions.ResourceNotFound, sot.fetch, sess) self.assertEqual('No stack found for %s' % FAKE_ID, str(ex))
def take_action(self, parsed_args): masakari_client = self.app.client_manager.ha uuid = masakariclient_utils.get_uuid_by_name(masakari_client, parsed_args.segment) attrs = { 'name': parsed_args.name, 'description': parsed_args.description, 'recovery_method': parsed_args.recovery_method, 'service_type': parsed_args.service_type, } # Remove not specified keys attrs = masakariclient_utils.remove_unspecified_items(attrs) try: masakari_client.update_segment(segment=uuid, **attrs) # Reraise. To unify exceptions with other functions. except sdk_exc.NotFoundException: LOG.debug(_("Segment is not found: %s"), parsed_args) raise sdk_exc.ResourceNotFound(_('No Segment found for %s') % uuid) except Exception as ex: LOG.debug(_("Failed to update segment: %s"), parsed_args) raise ex return _show_segment(masakari_client, uuid)
def test_success(self): pr = mock.Mock() baremetal = mock.Mock() instances = [ {'hostname': 'host1', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host3', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host2', 'resource_class': 'compute', 'capabilities': {'answer': '42'}, 'image': {'href': 'overcloud-full'}} ] existing = mock.MagicMock(hostname='host2', allocation=None) existing.uuid = 'aaaa' pr.show_instance.side_effect = [ sdk_exc.ResourceNotFound(""), metalsmith.exceptions.Error(""), existing, ] found, not_found = bd.check_existing(instances, pr, baremetal) self.assertEqual([existing], found) self.assertEqual([{ 'hostname': 'host1', 'image': {'href': 'overcloud-full'}, }, { 'hostname': 'host3', 'image': {'href': 'overcloud-full'}, }], not_found) pr.show_instance.assert_has_calls([ mock.call(host) for host in ['host1', 'host3', 'host2'] ])
def test_node_show_not_found(self): arglist = ['my_node'] parsed_args = self.check_parser(self.cmd, arglist, []) self.mock_client.get_node.side_effect = sdk_exc.ResourceNotFound() error = self.assertRaises(exc.CommandError, self.cmd.take_action, parsed_args) self.assertEqual('Node not found: my_node', str(error))
def fetch(self, session, requires_id=True, base_path=None, error_message=None, resolve_outputs=True): if not self.allow_fetch: raise exceptions.MethodNotSupported(self, "fetch") request = self._prepare_request(requires_id=requires_id, base_path=base_path) # session = self._get_session(session) microversion = self._get_microversion_for(session, 'fetch') # NOTE(gtema): would be nice to simply use QueryParameters, however # Heat return 302 with parameters being set into URL and requests # apply parameters again, what results in them being set doubled if not resolve_outputs: request.url = request.url + '?resolve_outputs=False' response = session.get(request.url, microversion=microversion) kwargs = {} if error_message: kwargs['error_message'] = error_message self.microversion = microversion self._translate_response(response, **kwargs) if self and self.status in ['DELETE_COMPLETE', 'ADOPT_COMPLETE']: raise exceptions.ResourceNotFound( "No stack found for %s" % self.id) return self
def _get(self, resource_type, value=None, **attrs): """Get a resource :param resource_type: The type of resource to get. :type resource_type: :class:`~openstack.resource2.Resource` :param value: The value to get. Can be either the ID of a resource or a :class:`~openstack.resource2.Resource` subclass. :param dict attrs: Attributes to be passed onto the :meth:`~openstack.resource2.Resource.get` method. These should correspond to either :class:`~openstack.resource2.Body` or :class:`~openstack.resource2.Header` values on this resource. :returns: The result of the ``get`` :rtype: :class:`~openstack.resource2.Resource` """ res = self._get_resource(resource_type, value, **attrs) try: return res.get(self.session) except exceptions.NotFoundException as e: raise exceptions.ResourceNotFound( message="No %s found for %s" % (resource_type.__name__, value), details=e.details, response=e.response, request_id=e.request_id, url=e.url, method=e.method, http_status=e.http_status, cause=e.cause)
def test_recv_delete_not_found(self): self.senlin_mock.delete_receiver.side_effect = [ exceptions.ResourceNotFound(http_status=404) ] recv = self._create_recv(self.t) scheduler.TaskRunner(recv.delete)() self.senlin_mock.delete_receiver.assert_called_once_with( recv.resource_id)
def test_cluster_delete_success(self): cluster = self._create_cluster(self.t) self.senlin_mock.get_cluster.side_effect = [ exceptions.ResourceNotFound('SenlinCluster'), ] scheduler.TaskRunner(cluster.delete)() self.senlin_mock.delete_cluster.assert_called_once_with( cluster.resource_id)
def test_resources_stack_not_found(self, mock_list, mock_find): stack_name = 'test_stack' mock_find.side_effect = exceptions.ResourceNotFound( 'No stack found for test_stack') ex = self.assertRaises(exceptions.ResourceNotFound, self.proxy.resources, stack_name) self.assertEqual('No stack found for test_stack', str(ex))
def test_validation(self): self.mock_find_segment.side_effect = [ "seg1", exceptions.ResourceNotFound(), exceptions.DuplicateResource() ] self.assertTrue(self.constraint.validate("foo", self.ctx)) self.assertFalse(self.constraint.validate("bar", self.ctx)) self.assertFalse(self.constraint.validate("baz", self.ctx))
def test_policy_type_show_not_found(self): arglist = ['senlin.policy.deletion-1.0'] parsed_args = self.check_parser(self.cmd, arglist, []) self.mock_client.get_policy_type.side_effect = ( sdk_exc.ResourceNotFound()) error = self.assertRaises(exc.CommandError, self.cmd.take_action, parsed_args) self.assertEqual('Policy Type not found: senlin.policy.deletion-1.0', str(error))
def test_profile_type_show_not_found(self): arglist = ['os.heat.stack-1.1'] parsed_args = self.check_parser(self.cmd, arglist, []) self.mock_client.get_profile_type.side_effect = ( sdk_exc.ResourceNotFound()) error = self.assertRaises(exc.CommandError, self.cmd.take_action, parsed_args) self.assertEqual('Profile Type not found: os.heat.stack-1.1', str(error))