Пример #1
0
    def get(self, member_id):
        try:
            db_api_image_member = self.db_api.image_member_find(
                self.context, self.image.image_id, member_id)
            if not db_api_image_member:
                raise exception.NotFound()
        except (exception.NotFound, exception.Forbidden):
            raise exception.NotFound()

        image_member = self._format_image_member_from_db(
            db_api_image_member[0])
        return image_member
Пример #2
0
 def remove_tags(self, namespace):
     try:
         self.db_api.metadef_tag_delete_namespace_content(
             self.context, namespace.namespace)
     except (exception.NotFound, exception.Forbidden):
         msg = _("The specified namespace %s could not be found")
         raise exception.NotFound(msg % namespace.namespace)
Пример #3
0
 def get(self, task_id):
     try:
         db_api_task = self.db_api.task_get(self.context, task_id)
     except (exception.NotFound, exception.Forbidden):
         msg = _('Could not find task %s') % task_id
         raise exception.NotFound(msg)
     return self._format_task_from_db(db_api_task)
Пример #4
0
    def show(self, req, namespace, property_name, filters=None):
        try:
            if filters and filters['resource_type']:
                rs_repo = self.gateway.get_metadef_resource_type_repo(
                    req.context)
                db_resource_type = rs_repo.get(filters['resource_type'],
                                               namespace)
                prefix = db_resource_type.prefix
                if prefix and property_name.startswith(prefix):
                    property_name = property_name[len(prefix):]
                else:
                    msg = (_("Property %(property_name)s does not start "
                             "with the expected resource type association "
                             "prefix of '%(prefix)s'.") % {
                                 'property_name': property_name,
                                 'prefix': prefix
                             })
                    raise exception.NotFound(msg)

            prop_repo = self.gateway.get_metadef_property_repo(req.context)
            db_property = prop_repo.get(namespace, property_name)
            property = self._to_model(db_property)
        except exception.Forbidden as e:
            LOG.debug(
                "User not permitted to show metadata property '%s' "
                "within '%s' namespace", property_name, namespace)
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(encodeutils.exception_to_unicode(e))
            raise webob.exc.HTTPInternalServerError()
        return property
 def delete(self, req, namespace, resource_type):
     rs_type_repo = self.gateway.get_metadef_resource_type_repo(req.context)
     try:
         filters = {}
         found = False
         filters['namespace'] = namespace
         db_resource_type_list = rs_type_repo.list(filters=filters)
         for db_resource_type in db_resource_type_list:
             if db_resource_type.name == resource_type:
                 db_resource_type.delete()
                 rs_type_repo.remove(db_resource_type)
                 found = True
         if not found:
             raise exception.NotFound()
     except exception.Forbidden as e:
         raise webob.exc.HTTPForbidden(explanation=e.msg)
     except exception.NotFound as e:
         msg = (_("Failed to find resource type %(resourcetype)s to "
                  "delete") % {
                      'resourcetype': resource_type
                  })
         LOG.error(msg)
         raise webob.exc.HTTPNotFound(explanation=msg)
     except Exception as e:
         LOG.error(e)
         raise webob.exc.HTTPInternalServerError()
Пример #6
0
 def remove(self, metadata_tag):
     try:
         self.db_api.metadef_tag_delete(self.context,
                                        metadata_tag.namespace.namespace,
                                        metadata_tag.name)
     except (exception.NotFound, exception.Forbidden):
         msg = _("The specified metadata tag %s could not be found")
         raise exception.NotFound(msg % metadata_tag.name)
Пример #7
0
 def save(self, namespace):
     try:
         self.db_api.metadef_namespace_update(
             self.context, namespace.namespace_id,
             self._format_namespace_to_db(namespace))
     except exception.NotFound as e:
         raise exception.NotFound(explanation=e.msg)
     return namespace
Пример #8
0
 def get(self, namespace):
     try:
         db_api_namespace = self.db_api.metadef_namespace_get(
             self.context, namespace)
     except (exception.NotFound, exception.Forbidden):
         msg = _('Could not find namespace %s') % namespace
         raise exception.NotFound(msg)
     return self._format_namespace_from_db(db_api_namespace)
Пример #9
0
 def save(self, image_member, from_state=None):
     image_member_values = self._format_image_member_to_db(image_member)
     try:
         new_values = self.db_api.image_member_update(
             self.context, image_member.id, image_member_values)
     except (exception.NotFound, exception.Forbidden):
         raise exception.NotFound()
     image_member.updated_at = new_values['updated_at']
Пример #10
0
 def remove(self, property):
     try:
         self.db_api.metadef_property_delete(self.context,
                                             property.namespace.namespace,
                                             property.name)
     except (exception.NotFound, exception.Forbidden):
         msg = _("The specified property %s could not be found")
         raise exception.NotFound(msg % property.name)
Пример #11
0
 def save(self, task):
     task_values = self._format_task_to_db(task)
     try:
         updated_values = self.db_api.task_update(self.context,
                                                  task.task_id, task_values)
     except (exception.NotFound, exception.Forbidden):
         msg = _('Could not find task %s') % task.task_id
         raise exception.NotFound(msg)
     task.updated_at = updated_values['updated_at']
Пример #12
0
    def remove(self, resource_type):
        try:
            self.db_api.metadef_resource_type_association_delete(
                self.context, resource_type.namespace.namespace,
                resource_type.name)

        except (exception.NotFound, exception.Forbidden):
            msg = _("The specified resource type %s could not be found ")
            raise exception.NotFound(msg % resource_type.name)
Пример #13
0
 def save(self, metadata_tag):
     try:
         self.db_api.metadef_tag_update(
             self.context, metadata_tag.namespace.namespace,
             metadata_tag.tag_id,
             self._format_metadef_tag_to_db(metadata_tag))
     except exception.NotFound as e:
         raise exception.NotFound(explanation=e.msg)
     return metadata_tag
Пример #14
0
 def save(self, property):
     try:
         self.db_api.metadef_property_update(
             self.context, property.namespace.namespace,
             property.property_id,
             self._format_metadef_property_to_db(property))
     except exception.NotFound as e:
         raise exception.NotFound(explanation=e.msg)
     return property
Пример #15
0
 def get(self, namespace, property_name):
     try:
         namespace_entity = self.meta_namespace_repo.get(namespace)
         db_property_type = self.db_api.metadef_property_get(
             self.context, namespace, property_name)
     except (exception.NotFound, exception.Forbidden):
         msg = _('Could not find property %s') % property_name
         raise exception.NotFound(msg)
     return self._format_metadef_property_from_db(db_property_type,
                                                  namespace_entity)
Пример #16
0
 def get(self, namespace, name):
     try:
         namespace_entity = self.meta_namespace_repo.get(namespace)
         db_metadata_tag = self.db_api.metadef_tag_get(
             self.context, namespace, name)
     except (exception.NotFound, exception.Forbidden):
         msg = _('Could not find metadata tag %s') % name
         raise exception.NotFound(msg)
     return self._format_metadef_tag_from_db(db_metadata_tag,
                                             namespace_entity)
Пример #17
0
    def _verify_metadata(self, image_meta):
        """
        Sanity check the 'deleted' and 'size' metadata values.
        """
        # NOTE: admins can see image metadata in the v1 API, but shouldn't
        # be able to download the actual image data.
        if image_meta['status'] == 'deleted' and image_meta['deleted']:
            raise exception.NotFound()

        if not image_meta['size']:
            # override image size metadata with the actual cached
            # file size, see LP Bug #900959
            image_meta['size'] = self.cache.get_image_size(image_meta['id'])
Пример #18
0
    def test_catch_error_not_found(self, mock_function):
        mock_function.side_effect = exception.NotFound()

        self.assertEqual(cache_manage.FAILURE,
                         cache_manage.list_cached(mock.Mock(), None))
Пример #19
0
 def remove(self, image_member):
     try:
         self.db_api.image_member_delete(self.context, image_member.id)
     except (exception.NotFound, exception.Forbidden):
         msg = _("The specified member %s could not be found")
         raise exception.NotFound(msg % image_member.id)
Пример #20
0
 def data_iterator():
     self.notifier.log = []
     yield 'abcde'
     raise exception.NotFound('Not found')
Пример #21
0
    def _do_request(self, method, url, body, headers):
        """
        Connects to the server and issues a request.  Handles converting
        any returned HTTP error status codes to OpenStack/Glance exceptions
        and closing the server connection. Returns the result data, or
        raises an appropriate exception.

        :param method: HTTP method ("GET", "POST", "PUT", etc...)
        :param url: urlparse.ParsedResult object with URL information
        :param body: data to send (as string, filelike or iterable),
                     or None (default)
        :param headers: mapping of key/value pairs to add as headers

        :note

        If the body param has a read attribute, and method is either
        POST or PUT, this method will automatically conduct a chunked-transfer
        encoding and use the body as a file object or iterable, transferring
        chunks of data using the connection's send() method. This allows large
        objects to be transferred efficiently without buffering the entire
        body in memory.
        """
        if url.query:
            path = url.path + "?" + url.query
        else:
            path = url.path

        try:
            connection_type = self.get_connection_type()
            headers = self._encode_headers(headers or {})
            headers.update(osprofiler.web.get_trace_id_headers())

            if 'x-auth-token' not in headers and self.auth_token:
                headers['x-auth-token'] = self.auth_token

            c = connection_type(url.hostname, url.port, **self.connect_kwargs)

            def _pushing(method):
                return method.lower() in ('post', 'put')

            def _simple(body):
                return body is None or isinstance(body, bytes)

            def _filelike(body):
                return hasattr(body, 'read')

            def _sendbody(connection, iter):
                connection.endheaders()
                for sent in iter:
                    # iterator has done the heavy lifting
                    pass

            def _chunkbody(connection, iter):
                connection.putheader('Transfer-Encoding', 'chunked')
                connection.endheaders()
                for chunk in iter:
                    connection.send('%x\r\n%s\r\n' % (len(chunk), chunk))
                connection.send('0\r\n\r\n')

            # Do a simple request or a chunked request, depending
            # on whether the body param is file-like or iterable and
            # the method is PUT or POST
            #
            if not _pushing(method) or _simple(body):
                # Simple request...
                c.request(method, path, body, headers)
            elif _filelike(body) or self._iterable(body):
                c.putrequest(method, path)

                use_sendfile = self._sendable(body)

                # According to HTTP/1.1, Content-Length and Transfer-Encoding
                # conflict.
                for header, value in headers.items():
                    if use_sendfile or header.lower() != 'content-length':
                        c.putheader(header, str(value))

                iter = utils.chunkreadable(body)

                if use_sendfile:
                    # send actual file without copying into userspace
                    _sendbody(c, iter)
                else:
                    # otherwise iterate and chunk
                    _chunkbody(c, iter)
            else:
                raise TypeError('Unsupported image type: %s' % body.__class__)

            res = c.getresponse()

            def _retry(res):
                return res.getheader('Retry-After')

            def read_body(res):
                body = res.read()
                if six.PY3:
                    body = body.decode('utf-8')
                return body

            status_code = self.get_status_code(res)
            if status_code in self.OK_RESPONSE_CODES:
                return res
            elif status_code in self.REDIRECT_RESPONSE_CODES:
                raise exception.RedirectException(res.getheader('Location'))
            elif status_code == http_client.UNAUTHORIZED:
                raise exception.NotAuthenticated(read_body(res))
            elif status_code == http_client.FORBIDDEN:
                raise exception.Forbidden(read_body(res))
            elif status_code == http_client.NOT_FOUND:
                raise exception.NotFound(read_body(res))
            elif status_code == http_client.CONFLICT:
                raise exception.Duplicate(read_body(res))
            elif status_code == http_client.BAD_REQUEST:
                raise exception.Invalid(read_body(res))
            elif status_code == http_client.MULTIPLE_CHOICES:
                raise exception.MultipleChoices(body=read_body(res))
            elif status_code == http_client.REQUEST_ENTITY_TOO_LARGE:
                raise exception.LimitExceeded(retry=_retry(res),
                                              body=read_body(res))
            elif status_code == http_client.INTERNAL_SERVER_ERROR:
                raise exception.ServerError()
            elif status_code == http_client.SERVICE_UNAVAILABLE:
                raise exception.ServiceUnavailable(retry=_retry(res))
            else:
                raise exception.UnexpectedStatus(status=status_code,
                                                 body=read_body(res))

        except (socket.error, IOError) as e:
            raise exception.ClientConnectionError(e)
Пример #22
0
 def test_upload_non_existent_image_before_save(self):
     request = unit_test_utils.get_fake_request()
     self.image_repo.result = exception.NotFound()
     self.assertRaises(webob.exc.HTTPNotFound, self.controller.upload,
                       request, str(uuid.uuid4()), 'ABC', 3)
Пример #23
0
 def fake_get_v1_image_metadata(*args, **kwargs):
     raise exception.NotFound()