Use oslo_utils.encodeutils.exception_to_unicode()

* Replace glance.common.utils.exception_to_str() with
  oslo_utils.encodeutils.exception_to_unicode().
* Remove exception_to_str() from glance.common.utils
* Add "from oslo_utils import encodeutils" and remove "from
  glance.common import utils" (when utils is no more used)
* glance/api/v2/images.py: replace utils.exception_to_str() with
  six.text_type() to cast the oslo_i18n message to Unicode

Glance exception_to_str() function was not compatible with Python 3,
whereas exception_to_unicode() is compatible with Python 3, it's in Oslo
common libraries and it's well tested.

This patch was first generated by a tool (modified version of sixer),
and then fixed to respect the PEP8 (especially the constraint of 80
columns).

Change-Id: I86008c8adc0c5664f96573c1015cc15e2d06e3e2
This commit is contained in:
Victor Stinner 2015-07-02 12:35:32 +02:00
parent 1c8cd0e86c
commit 1c186e23fd
45 changed files with 218 additions and 210 deletions

View File

@ -23,6 +23,7 @@ import glance_store as store
import glance_store.location
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import strutils
from webob.exc import HTTPBadRequest
@ -579,7 +580,7 @@ class Controller(controller.BaseController):
content_type="text/plain")
except exception.Invalid as e:
msg = (_("Failed to reserve image. Got error: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.exception(msg)
raise HTTPBadRequest(explanation=msg,
request=req,
@ -686,7 +687,7 @@ class Controller(controller.BaseController):
upload_utils.initiate_deletion(req, location_data, image_id)
except exception.Invalid as e:
msg = (_("Failed to activate image. Got error: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPBadRequest(explanation=msg,
request=req,
@ -744,11 +745,11 @@ class Controller(controller.BaseController):
# malicious user keeps on trying image-create using non-existent
# location url. Used log.debug because administrator can
# disable debug logs.
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise HTTPNotFound(explanation=e.msg, content_type="text/plain")
except (store.UnknownScheme, store.BadStoreUri) as e:
# NOTE(rajesht): See above note of store.NotFound
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise HTTPBadRequest(explanation=e.msg, content_type="text/plain")
def _handle_source(self, req, image_id, image_meta, image_data):
@ -782,7 +783,7 @@ class Controller(controller.BaseController):
image_size_store = store.get_size_from_backend(
location, req.context)
except (store.BadStoreUri, store.UnknownScheme) as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise HTTPBadRequest(explanation=e.msg,
request=req,
content_type="text/plain")
@ -1015,27 +1016,27 @@ class Controller(controller.BaseController):
except exception.Invalid as e:
msg = (_("Failed to update image metadata. Got error: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPBadRequest(explanation=msg,
request=req,
content_type="text/plain")
except exception.ImageNotFound as e:
msg = (_("Failed to find image to update: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPNotFound(explanation=msg,
request=req,
content_type="text/plain")
except exception.Forbidden as e:
msg = (_("Forbidden to update image: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPForbidden(explanation=msg,
request=req,
content_type="text/plain")
except (exception.Conflict, exception.Duplicate) as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
raise HTTPConflict(body=_('Image operation conflicts'),
request=req,
content_type='text/plain')
@ -1117,21 +1118,22 @@ class Controller(controller.BaseController):
registry.delete_image_metadata(req.context, id)
except exception.ImageNotFound as e:
msg = (_("Failed to find image to delete: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPNotFound(explanation=msg,
request=req,
content_type="text/plain")
except exception.Forbidden as e:
msg = (_("Forbidden to delete image: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise HTTPForbidden(explanation=msg,
request=req,
content_type="text/plain")
except exception.InUseByStore as e:
msg = (_("Image %(id)s could not be deleted because it is in use: "
"%(exc)s") % {"id": id, "exc": utils.exception_to_str(e)})
"%(exc)s")
% {"id": id, "exc": encodeutils.exception_to_unicode(e)})
LOG.warn(msg)
raise HTTPConflict(explanation=msg,
request=req,
@ -1168,7 +1170,7 @@ class ImageDeserializer(wsgi.JSONRequestDeserializer):
try:
result['image_meta'] = utils.get_image_meta_from_headers(request)
except exception.InvalidParameterValue as e:
msg = utils.exception_to_str(e)
msg = encodeutils.exception_to_unicode(e)
LOG.warn(msg, exc_info=True)
raise HTTPBadRequest(explanation=e.msg, request=request)

View File

@ -16,6 +16,7 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import webob.exc
from glance.api import policy
@ -97,7 +98,7 @@ class Controller(controller.BaseController):
registry.delete_member(req.context, image_id, id)
self._update_store_acls(req, image_id)
except exception.NotFound as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to remove membership from image "
@ -154,13 +155,13 @@ class Controller(controller.BaseController):
registry.add_member(req.context, image_id, id, can_share)
self._update_store_acls(req, image_id)
except exception.Invalid as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.NotFound as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
return webob.exc.HTTPNoContent()
@ -189,13 +190,13 @@ class Controller(controller.BaseController):
registry.replace_members(req.context, image_id, body)
self._update_store_acls(req, image_id)
except exception.Invalid as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.NotFound as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
return webob.exc.HTTPNoContent()
@ -216,10 +217,10 @@ class Controller(controller.BaseController):
try:
members = registry.get_member_images(req.context, id)
except exception.NotFound as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPForbidden(explanation=e.msg)
return dict(shared_images=members)

View File

@ -15,6 +15,7 @@
import glance_store as store_api
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import webob.exc
@ -197,7 +198,7 @@ def upload_data_to_store(req, image_meta, image_data, store, notifier):
except exception.Duplicate as e:
msg = (_("Attempt to upload duplicate image: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
# NOTE(dosaboy): do not delete the image since it is likely that this
# conflict is a result of another concurrent upload that will be
@ -209,7 +210,7 @@ def upload_data_to_store(req, image_meta, image_data, store, notifier):
except exception.Forbidden as e:
msg = (_("Forbidden upload attempt: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.warn(msg)
safe_kill(req, image_id, 'saving')
notifier.error('image.upload', msg)
@ -219,7 +220,7 @@ def upload_data_to_store(req, image_meta, image_data, store, notifier):
except store_api.StorageFull as e:
msg = (_("Image storage media is full: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.error(msg)
safe_kill(req, image_id, 'saving')
notifier.error('image.upload', msg)
@ -229,7 +230,7 @@ def upload_data_to_store(req, image_meta, image_data, store, notifier):
except store_api.StorageWriteDenied as e:
msg = (_("Insufficient permissions on image storage media: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
LOG.error(msg)
safe_kill(req, image_id, 'saving')
notifier.error('image.upload', msg)
@ -249,7 +250,7 @@ def upload_data_to_store(req, image_meta, image_data, store, notifier):
except exception.StorageQuotaFull as e:
msg = (_("Denying attempt to upload image because it exceeds the "
"quota: %s") % utils.exception_to_str(e))
"quota: %s") % encodeutils.exception_to_unicode(e))
LOG.warn(msg)
safe_kill(req, image_id, 'saving')
notifier.error('image.upload', msg)

View File

@ -14,6 +14,7 @@
# under the License.
import glance_store
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import webob.exc
@ -59,7 +60,7 @@ class ImageDataController(object):
except Exception as e:
msg = (_LE("Unable to restore image %(image_id)s: %(e)s") %
{'image_id': image.image_id,
'e': utils.exception_to_str(e)})
'e': encodeutils.exception_to_unicode(e)})
LOG.exception(msg)
@utils.mutating
@ -91,10 +92,11 @@ class ImageDataController(object):
except ValueError as e:
LOG.debug("Cannot save data for image %(id)s: %(e)s",
{'id': image_id, 'e': utils.exception_to_str(e)})
{'id': image_id,
'e': encodeutils.exception_to_unicode(e)})
self._restore(image_repo, image)
raise webob.exc.HTTPBadRequest(
explanation=utils.exception_to_str(e))
explanation=encodeutils.exception_to_unicode(e))
except glance_store.StoreAddDisabled:
msg = _("Error in store configuration. Adding images to store "
@ -105,7 +107,7 @@ class ImageDataController(object):
content_type='text/plain')
except exception.InvalidImageStatusTransition as e:
msg = utils.exception_to_str(e)
msg = encodeutils.exception_to_unicode(e)
LOG.exception(msg)
raise webob.exc.HTTPConflict(explanation=e.msg, request=req)
@ -120,7 +122,7 @@ class ImageDataController(object):
except glance_store.StorageFull as e:
msg = _("Image storage media "
"is full: %s") % utils.exception_to_str(e)
"is full: %s") % encodeutils.exception_to_unicode(e)
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
@ -128,7 +130,7 @@ class ImageDataController(object):
except exception.StorageQuotaFull as e:
msg = _("Image exceeds the storage "
"quota: %s") % utils.exception_to_str(e)
"quota: %s") % encodeutils.exception_to_unicode(e)
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
@ -136,7 +138,7 @@ class ImageDataController(object):
except exception.ImageSizeLimitExceeded as e:
msg = _("The incoming image is "
"too large: %s") % utils.exception_to_str(e)
"too large: %s") % encodeutils.exception_to_unicode(e)
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
@ -144,7 +146,7 @@ class ImageDataController(object):
except glance_store.StorageWriteDenied as e:
msg = _("Insufficient permissions on image "
"storage media: %s") % utils.exception_to_str(e)
"storage media: %s") % encodeutils.exception_to_unicode(e)
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPServiceUnavailable(explanation=msg,

View File

@ -18,6 +18,7 @@ import copy
import glance_store
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import timeutils
import six
import webob
@ -90,7 +91,8 @@ class ImageMembersController(object):
raise webob.exc.HTTPConflict(explanation=msg)
except exception.ImageMemberLimitExceeded as e:
msg = (_("Image member limit exceeded for image %(id)s: %(e)s:")
% {"id": image_id, "e": utils.exception_to_str(e)})
% {"id": image_id,
"e": encodeutils.exception_to_unicode(e)})
LOG.warning(msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
@ -127,7 +129,8 @@ class ImageMembersController(object):
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except ValueError as e:
msg = _("Incorrect request: %s") % utils.exception_to_str(e)
msg = (_("Incorrect request: %s")
% encodeutils.exception_to_unicode(e))
LOG.warning(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)

View File

@ -14,6 +14,7 @@
# under the License.
import glance_store
from oslo_log import log as logging
from oslo_utils import encodeutils
import webob.exc
from glance.api import policy
@ -56,12 +57,14 @@ class Controller(object):
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.Invalid as e:
msg = _("Could not update image: %s") % utils.exception_to_str(e)
msg = (_("Could not update image: %s")
% encodeutils.exception_to_unicode(e))
LOG.warning(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.ImageTagLimitExceeded as e:
msg = (_("Image tag limit exceeded for image %(id)s: %(e)s:")
% {"id": image_id, "e": utils.exception_to_str(e)})
% {"id": image_id,
"e": encodeutils.exception_to_unicode(e)})
LOG.warning(msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)

View File

@ -19,6 +19,7 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from oslo_utils import encodeutils
from oslo_utils import timeutils
import six
import six.moves.urllib.parse as urlparse
@ -73,7 +74,7 @@ class ImagesController(object):
except exception.InvalidParameterValue as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.LimitExceeded as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.Duplicate as dupex:
@ -83,9 +84,9 @@ class ImagesController(object):
except exception.ReadonlyProperty as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except TypeError as e:
LOG.debug(utils.exception_to_str(e))
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(
explanation=utils.exception_to_str(e))
explanation=encodeutils.exception_to_unicode(e))
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
@ -163,12 +164,12 @@ class ImagesController(object):
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.StorageQuotaFull as e:
msg = (_("Denying attempt to upload image because it exceeds the"
" quota: %s") % utils.exception_to_str(e))
" quota: %s") % encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=msg, request=req, content_type='text/plain')
except exception.LimitExceeded as e:
LOG.exception(utils.exception_to_str(e))
LOG.exception(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.NotAuthenticated as e:
@ -281,7 +282,7 @@ class ImagesController(object):
raise webob.exc.HTTPBadRequest(explanation=bse.msg)
except ValueError as ve: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=utils.exception_to_str(ve))
explanation=encodeutils.exception_to_unicode(ve))
def _do_add_locations(self, image, path_pos, value):
pos = self._get_locations_op_pos(path_pos,
@ -297,7 +298,7 @@ class ImagesController(object):
raise webob.exc.HTTPBadRequest(explanation=bse.msg)
except ValueError as ve: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=utils.exception_to_str(ve))
explanation=encodeutils.exception_to_unicode(ve))
def _do_remove_locations(self, image, path_pos):
pos = self._get_locations_op_pos(path_pos,
@ -311,7 +312,7 @@ class ImagesController(object):
image.locations.pop(pos)
except Exception as e:
raise webob.exc.HTTPInternalServerError(
explanation=utils.exception_to_str(e))
explanation=encodeutils.exception_to_unicode(e))
if len(image.locations) == 0 and image.status == 'active':
image.status = 'queued'
@ -358,7 +359,7 @@ class RequestDeserializer(wsgi.JSONRequestDeserializer):
if key in image:
msg = _("Attribute '%s' is read-only.") % key
raise webob.exc.HTTPForbidden(
explanation=utils.exception_to_str(msg))
explanation=six.text_type(msg))
def create(self, request):
body = self._get_request_body(request)

View File

@ -16,6 +16,7 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import six.moves.urllib.parse as urlparse
import webob.exc
@ -99,7 +100,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return namespaces
@ -175,7 +176,7 @@ class NamespaceController(object):
self._cleanup_namespace(ns_repo, namespace, namespace_created)
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
# Return the user namespace as we don't expose the id to user
@ -266,7 +267,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return namespace_detail
@ -296,7 +297,7 @@ class NamespaceController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return Namespace.to_wsme_model(updated_namespace,
@ -316,7 +317,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def delete_objects(self, req, namespace):
@ -332,7 +333,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def delete_tags(self, req, namespace):
@ -348,7 +349,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def delete_properties(self, req, namespace):
@ -364,7 +365,7 @@ class NamespaceController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def _prefix_property_name(self, namespace_detail, user_resource_type):

View File

@ -16,6 +16,7 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
@ -25,7 +26,6 @@ from glance.api.v2 import metadef_namespaces as namespaces
from glance.api.v2.model.metadef_object import MetadefObject
from glance.api.v2.model.metadef_object import MetadefObjects
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
from glance.common import wsme_utils
import glance.db
@ -67,7 +67,7 @@ class MetadefObjectsController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return MetadefObject.to_wsme_model(
new_meta_object,
@ -96,7 +96,7 @@ class MetadefObjectsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return metadef_objects
@ -116,7 +116,7 @@ class MetadefObjectsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def update(self, req, metadata_object, namespace, object_name):
@ -142,7 +142,7 @@ class MetadefObjectsController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return MetadefObject.to_wsme_model(
updated_metadata_obj,
@ -162,7 +162,7 @@ class MetadefObjectsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()

View File

@ -15,6 +15,7 @@
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
@ -25,7 +26,6 @@ from glance.api.v2.model.metadef_namespace import Namespace
from glance.api.v2.model.metadef_property_type import PropertyType
from glance.api.v2.model.metadef_property_type import PropertyTypes
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
@ -77,7 +77,7 @@ class NamespacePropertiesController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return namespace_properties
@ -109,7 +109,7 @@ class NamespacePropertiesController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return property
@ -129,7 +129,7 @@ class NamespacePropertiesController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return self._to_model(new_property_type)
@ -150,7 +150,7 @@ class NamespacePropertiesController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return self._to_model(updated_property_type)
@ -167,7 +167,7 @@ class NamespacePropertiesController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()

View File

@ -15,6 +15,7 @@
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
@ -25,7 +26,6 @@ from glance.api.v2.model.metadef_resource_type import ResourceTypeAssociation
from glance.api.v2.model.metadef_resource_type import ResourceTypeAssociations
from glance.api.v2.model.metadef_resource_type import ResourceTypes
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
@ -64,7 +64,7 @@ class ResourceTypeController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError(e)
return resource_types
@ -86,7 +86,7 @@ class ResourceTypeController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError(e)
return resource_types
@ -108,7 +108,7 @@ class ResourceTypeController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return ResourceTypeAssociation.to_wsme_model(new_resource_type)
@ -136,7 +136,7 @@ class ResourceTypeController(object):
LOG.error(msg)
raise webob.exc.HTTPNotFound(explanation=msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()

View File

@ -16,6 +16,7 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
@ -24,7 +25,6 @@ from glance.api import policy
from glance.api.v2.model.metadef_tag import MetadefTag
from glance.api.v2.model.metadef_tag import MetadefTags
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
from glance.common import wsme_utils
import glance.db
@ -68,7 +68,7 @@ class TagsController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return MetadefTag.to_wsme_model(new_meta_tag)
@ -95,7 +95,7 @@ class TagsController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return metadef_tags
@ -127,7 +127,7 @@ class TagsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return metadef_tags
@ -144,7 +144,7 @@ class TagsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def update(self, req, metadata_tag, namespace, tag_name):
@ -164,7 +164,7 @@ class TagsController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
return MetadefTag.to_wsme_model(updated_metadata_tag)
@ -182,7 +182,7 @@ class TagsController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()

View File

@ -20,6 +20,7 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
import oslo_serialization.jsonutils as json
from oslo_utils import encodeutils
from oslo_utils import timeutils
import six
import six.moves.urllib.parse as urlparse
@ -72,7 +73,7 @@ class TasksController(object):
pool.spawn_n(new_task.run, task_executor)
except exception.Forbidden as e:
msg = (_LW("Forbidden to create task. Reason: %(reason)s")
% {'reason': utils.exception_to_str(e)})
% {'reason': encodeutils.exception_to_unicode(e)})
LOG.warn(msg)
raise webob.exc.HTTPForbidden(explanation=e.msg)
return new_task
@ -96,10 +97,10 @@ class TasksController(object):
result['next_marker'] = tasks[-1].task_id
except (exception.NotFound, exception.InvalidSortKey,
exception.InvalidFilterRangeValue) as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.Forbidden as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPForbidden(explanation=e.msg)
result['tasks'] = tasks
return result
@ -109,14 +110,16 @@ class TasksController(object):
task_repo = self.gateway.get_task_repo(req.context)
task = task_repo.get(task_id)
except exception.NotFound as e:
msg = (_LW("Failed to find task %(task_id)s. Reason: %(reason)s") %
{'task_id': task_id, 'reason': utils.exception_to_str(e)})
msg = (_LW("Failed to find task %(task_id)s. Reason: %(reason)s")
% {'task_id': task_id,
'reason': encodeutils.exception_to_unicode(e)})
LOG.warn(msg)
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
msg = (_LW("Forbidden to get task %(task_id)s. Reason:"
" %(reason)s") %
{'task_id': task_id, 'reason': utils.exception_to_str(e)})
" %(reason)s")
% {'task_id': task_id,
'reason': encodeutils.exception_to_unicode(e)})
LOG.warn(msg)
raise webob.exc.HTTPForbidden(explanation=e.msg)
return task

View File

@ -19,6 +19,7 @@ import glance_store
import jsonschema
from oslo_config import cfg
from oslo_serialization import jsonutils as json
from oslo_utils import encodeutils
from oslo_utils import excutils
import semantic_version
import six
@ -214,7 +215,7 @@ class ArtifactsController(object):
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.StorageQuotaFull as e:
msg = (_("Denying attempt to upload artifact because it exceeds "
"the quota: %s") % utils.exception_to_str(e))
"the quota: %s") % encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=msg, request=req, content_type='text/plain')
except exception.Invalid as e:
@ -357,7 +358,7 @@ class ArtifactsController(object):
except Exception as e:
msg = (_LE("Unable to restore artifact %(artifact_id)s: %(e)s") %
{'artifact_id': artifact.id,
'e': utils.exception_to_str(e)})
'e': encodeutils.exception_to_unicode(e)})
LOG.exception(msg)
def list_artifact_types(self, req):

View File

@ -17,6 +17,7 @@ import uuid
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from glance.artifacts.domain import proxy
from glance.common.artifacts import definitions
@ -126,7 +127,7 @@ class ArtifactBlobProxy(proxy.ArtifactBlob):
' %s in store from URI') % self.blob.id
LOG.warn(msg)
except self.store_api.StoreDeleteNotSupported as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
except self.store_api.UnsupportedBackend:
exc_type = sys.exc_info()[0].__name__
msg = (_LE('Failed to delete blob'
@ -158,8 +159,9 @@ class ArtifactBlobProxy(proxy.ArtifactBlob):
return data
except Exception as e:
LOG.warn(_('Get blob %(name)s data failed: '
'%(err)s.') % {'name': self.blob.item_key,
'err': utils.exception_to_str(e)})
'%(err)s.')
% {'name': self.blob.item_key,
'err': encodeutils.exception_to_unicode(e)})
err = e
# tried all locations

View File

@ -19,6 +19,7 @@ import os
import glance_store as store_api
from glance_store import backend
from oslo_config import cfg
from oslo_utils import encodeutils
import six
from stevedore import named
from taskflow.patterns import linear_flow as lf
@ -29,7 +30,6 @@ from taskflow.types import failure
from glance.common import exception
from glance.common.scripts.image_import import main as image_import
from glance.common.scripts import utils as script_utils
from glance.common import utils as common_utils
from glance import i18n
@ -339,7 +339,7 @@ class _CompleteTask(task.Task):
# TODO(nikhil): need to bring back save_and_reraise_exception when
# necessary
err_msg = ("Error: " + six.text_type(type(e)) + ': ' +
common_utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
log_msg = err_msg + _LE("Task ID %s") % task.task_id
LOG.exception(log_msg)

View File

@ -25,8 +25,8 @@ import os
import sys
import eventlet
from oslo_utils import encodeutils
from glance.common import utils
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
@ -64,7 +64,7 @@ KNOWN_EXCEPTIONS = (RuntimeError,
def fail(e):
global KNOWN_EXCEPTIONS
return_code = KNOWN_EXCEPTIONS.index(type(e)) + 1
sys.stderr.write("ERROR: %s\n" % utils.exception_to_str(e))
sys.stderr.write("ERROR: %s\n" % encodeutils.exception_to_unicode(e))
sys.exit(return_code)

View File

@ -26,6 +26,7 @@ import os
import sys
import time
from oslo_utils import encodeutils
from oslo_utils import timeutils
from glance.common import utils
@ -69,7 +70,7 @@ def catch_error(action):
if options.debug:
raise
print("Failed to %s. Got error:" % action)
pieces = utils.exception_to_str(e).split('\n')
pieces = encodeutils.exception_to_unicode(e).split('\n')
for piece in pieces:
print(piece)
return FAILURE

View File

@ -46,7 +46,6 @@ import six
from glance.common import config
from glance.common import exception
from glance.common import utils
from glance.db import migration as db_migration
from glance.db.sqlalchemy import api as db_api
from glance.db.sqlalchemy import metadata
@ -326,7 +325,7 @@ def main():
for arg in CONF.command.action_args]
return CONF.command.action_fn(*func_args, **func_kwargs)
except exception.GlanceException as e:
sys.exit("ERROR: %s" % utils.exception_to_str(e))
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
if __name__ == '__main__':

View File

@ -25,6 +25,7 @@ import os
import sys
import eventlet
from oslo_utils import encodeutils
# Monkey patch socket and time
eventlet.patcher.monkey_patch(all=False, socket=True, time=True, thread=True)
@ -44,7 +45,6 @@ import osprofiler.notifier
import osprofiler.web
from glance.common import config
from glance.common import utils
from glance.common import wsgi
from glance import notifier
@ -75,7 +75,7 @@ def main():
default_port=9191)
server.wait()
except RuntimeError as e:
sys.exit("ERROR: %s" % utils.exception_to_str(e))
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
if __name__ == '__main__':

View File

@ -24,6 +24,7 @@ import sys
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from six.moves import http_client
import six.moves.urllib.parse as urlparse
from webob import exc
@ -700,7 +701,7 @@ def main():
try:
config.parse_args()
except RuntimeError as e:
sys.exit("ERROR: %s" % utils.exception_to_str(e))
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
# Setup logging
logging.setup('glance')
@ -715,10 +716,10 @@ def main():
command(CONF, CONF.args)
except TypeError as e:
LOG.error(_LE(command.__doc__) % {'prog': command.__name__}) # noqa
sys.exit("ERROR: %s" % utils.exception_to_str(e))
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
except ValueError as e:
LOG.error(_LE(command.__doc__) % {'prog': command.__name__}) # noqa
sys.exit("ERROR: %s" % utils.exception_to_str(e))
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
if __name__ == '__main__':

View File

@ -25,8 +25,8 @@ import os
import sys
import eventlet
from oslo_utils import encodeutils
from glance.common import utils
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(socket=True, time=True, select=True,
@ -62,7 +62,7 @@ KNOWN_EXCEPTIONS = (RuntimeError,
def fail(e):
global KNOWN_EXCEPTIONS
return_code = KNOWN_EXCEPTIONS.index(type(e)) + 1
sys.stderr.write("ERROR: %s\n" % utils.exception_to_str(e))
sys.stderr.write("ERROR: %s\n" % encodeutils.exception_to_unicode(e))
sys.exit(return_code)

View File

@ -21,6 +21,7 @@ import traceback
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import oslo_utils.importutils as imp
from oslo_utils import timeutils
import six
@ -28,7 +29,6 @@ from webob import exc
from glance.common import client
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
from glance import i18n
@ -184,7 +184,7 @@ class Controller(object):
if self.raise_exc:
raise
cls, val = e.__class__, utils.exception_to_str(e)
cls, val = e.__class__, encodeutils.exception_to_unicode(e)
msg = (_LE("RPC Call Error: %(val)s\n%(tb)s") %
dict(val=val, tb=traceback.format_exc()))
LOG.error(msg)

View File

@ -19,6 +19,7 @@ __all__ = [
from oslo_concurrency import lockutils
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import six
@ -26,7 +27,6 @@ from glance.api.v2 import images as v2_api
from glance.common import exception
from glance.common.scripts import utils as script_utils
from glance.common import store_utils
from glance.common import utils as common_utils
from glance import i18n
@ -71,7 +71,7 @@ def _execute(t_id, task_repo, image_repo, image_factory):
# TODO(nikhil): need to bring back save_and_reraise_exception when
# necessary
err_msg = ("Error: " + six.text_type(type(e)) + ': ' +
common_utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
log_msg = _LE(err_msg + ("Task ID %s" % task.task_id)) # noqa
LOG.exception(log_msg)
@ -156,7 +156,7 @@ def set_image_data(image, uri, task_id):
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.warn(_LW("Task %(task_id)s failed with exception %(error)s") %
{"error": common_utils.exception_to_str(e),
{"error": encodeutils.exception_to_unicode(e),
"task_id": task_id})
LOG.info(_LI("Task %(task_id)s: Could not import image file"
" %(image_data)s") % {"image_data": uri,

View File

@ -17,9 +17,9 @@ import sys
import glance_store as store_api
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import six.moves.urllib.parse as urlparse
from glance.common import utils
import glance.db as db_api
from glance import i18n
from glance import scrubber
@ -58,7 +58,7 @@ def safe_delete_from_backend(context, image_id, location):
msg = _LW('Failed to delete image %s in store from URI') % image_id
LOG.warn(msg)
except store_api.StoreDeleteNotSupported as e:
LOG.warn(utils.exception_to_str(e))
LOG.warn(encodeutils.exception_to_unicode(e))
except store_api.UnsupportedBackend:
exc_type = sys.exc_info()[0].__name__
msg = (_LE('Failed to delete image %(image_id)s from store: %(exc)s') %

View File

@ -40,7 +40,6 @@ import uuid
from OpenSSL import crypto
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import netutils
from oslo_utils import strutils
@ -656,18 +655,6 @@ def parse_valid_host_port(host_port):
return (host, int(port))
def exception_to_str(exc):
try:
error = six.text_type(exc)
except UnicodeError:
try:
error = str(exc)
except UnicodeError:
error = ("Caught '%(exception)s' exception." %
{"exception": exc.__class__.__name__})
return encodeutils.safe_encode(error, errors='ignore')
try:
REGEX_4BYTE_UNICODE = re.compile(u'[\U00010000-\U0010ffff]')
except re.error:

View File

@ -25,6 +25,7 @@ import re
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import timeutils
import six
import sqlalchemy
@ -32,7 +33,6 @@ from sqlalchemy import and_
from sqlalchemy.schema import MetaData
from sqlalchemy.sql import select
from glance.common import utils
from glance import i18n
LOG = logging.getLogger(__name__)
@ -187,7 +187,7 @@ def _populate_metadata(meta, metadata_path=None, merge=False,
if isfile(join(metadata_path, f))
and f.endswith('.json')]
except OSError as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
return
if not json_schema_files:
@ -208,7 +208,7 @@ def _populate_metadata(meta, metadata_path=None, merge=False,
with open(file) as json_file:
metadata = json.load(json_file)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
continue
values = {
@ -446,7 +446,7 @@ def _export_data_to_file(meta, path):
with open(file_name, 'w') as json_file:
json_file.write(json.dumps(values))
except Exception as e:
LOG.exception(utils.exception_to_str(e))
LOG.exception(encodeutils.exception_to_unicode(e))
LOG.info(_LI("Namespace %(namespace)s saved in %(file)s") % {
'namespace': namespace_file_name, 'file': file_name})

View File

@ -14,11 +14,11 @@
# under the License.
from oslo_log import log as logging
from oslo_utils import encodeutils
import six.moves.urllib.parse as urlparse
import sqlalchemy
from glance.common import exception
from glance.common import utils
from glance import i18n
LOG = logging.getLogger(__name__)
@ -59,7 +59,7 @@ def migrate_location_credentials(migrate_engine, to_quoted):
images_table.c.id == image['id']).values(
location=fixed_uri).execute()
except exception.BadStoreUri as e:
reason = utils.exception_to_str(e)
reason = encodeutils.exception_to_unicode(e)
msg = _LE("Invalid store uri for image: %(image_id)s. "
"Details: %(reason)s") % {'image_id': image.id,
'reason': reason}

View File

@ -32,12 +32,12 @@ import types # noqa
from glance_store._drivers import swift # noqa
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import six.moves.urllib.parse as urlparse
import sqlalchemy
from glance.common import crypt
from glance.common import exception
from glance.common import utils
from glance import i18n
LOG = logging.getLogger(__name__)
@ -93,7 +93,7 @@ def migrate_location_credentials(migrate_engine, to_quoted):
" %(image_id)s") % {'image_id': image['id']}
LOG.warn(msg)
except exception.BadStoreUri as e:
reason = utils.exception_to_str(e)
reason = encodeutils.exception_to_unicode(e)
msg = _LE("Invalid store uri for image: %(image_id)s. "
"Details: %(reason)s") % {'image_id': image.id,
'reason': reason}

View File

@ -21,6 +21,7 @@ import hashlib
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import units
@ -266,13 +267,13 @@ class ImageCache(object):
with excutils.save_and_reraise_exception():
# image_iter has given us bad, (size_checked_iter has found a
# bad length), or corrupt data (checksum is wrong).
LOG.exception(utils.exception_to_str(e))
LOG.exception(encodeutils.exception_to_unicode(e))
except Exception as e:
LOG.exception(_LE("Exception encountered while tee'ing "
"image '%(image_id)s' into cache: %(error)s. "
"Continuing with response.") %
{'image_id': image_id,
'error': utils.exception_to_str(e)})
'error': encodeutils.exception_to_unicode(e)})
# If no checksum provided continue responding even if
# caching failed.

View File

@ -60,11 +60,11 @@ import time
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import xattr
from glance.common import exception
from glance.common import utils
from glance import i18n
from glance.image_cache.drivers import base
@ -288,13 +288,13 @@ class Driver(base.Driver):
os.unlink(self.get_image_filepath(image_id, 'queue'))
def rollback(e):
set_attr('error', utils.exception_to_str(e))
set_attr('error', encodeutils.exception_to_unicode(e))
invalid_path = self.get_image_filepath(image_id, 'invalid')
LOG.debug("Fetch of cache file failed (%(e)s), rolling back by "
"moving '%(incomplete_path)s' to "
"'%(invalid_path)s'" %
{'e': utils.exception_to_str(e),
{'e': encodeutils.exception_to_unicode(e),
'incomplete_path': incomplete_path,
'invalid_path': invalid_path})
os.rename(incomplete_path, invalid_path)

View File

@ -19,6 +19,7 @@ import copy
import glance_store as store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from glance.common import exception
@ -396,8 +397,9 @@ class ImageProxy(glance.domain.proxy.Image):
return data
except Exception as e:
LOG.warn(_('Get image %(id)s data failed: '
'%(err)s.') % {'id': self.image.image_id,
'err': utils.exception_to_str(e)})
'%(err)s.')
% {'id': self.image.image_id,
'err': encodeutils.exception_to_unicode(e)})
err = e
# tried all locations
LOG.error(_LE('Glance tried all active locations to get data for '

View File

@ -20,13 +20,13 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import timeutils
import six
import webob
from glance.common import exception
from glance.common import utils
from glance.domain import proxy as domain_proxy
from glance import i18n
@ -378,54 +378,56 @@ class ImageProxy(NotificationProxy, domain_proxy.Image):
self.repo.set_data(data, size)
except glance_store.StorageFull as e:
msg = (_("Image storage media is full: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
except glance_store.StorageWriteDenied as e:
msg = (_("Insufficient permissions on image storage media: %s")
% utils.exception_to_str(e))
% encodeutils.exception_to_unicode(e))
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPServiceUnavailable(explanation=msg)
except ValueError as e:
msg = (_("Cannot save data for image %(image_id)s: %(error)s") %
{'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
'error': encodeutils.exception_to_unicode(e)})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPBadRequest(
explanation=utils.exception_to_str(e))
explanation=encodeutils.exception_to_unicode(e))
except exception.Duplicate as e:
msg = (_("Unable to upload duplicate image data for image"
"%(image_id)s: %(error)s") %
{'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
'error': encodeutils.exception_to_unicode(e)})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPConflict(explanation=msg)
except exception.Forbidden as e:
msg = (_("Not allowed to upload image data for image %(image_id)s:"
" %(error)s") % {'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
" %(error)s")
% {'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.NotFound as e:
exc_str = encodeutils.exception_to_unicode(e)
msg = (_("Image %(image_id)s could not be found after upload."
" The image may have been deleted during the upload:"
" %(error)s") % {'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
'error': exc_str})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPNotFound(explanation=utils.exception_to_str(e))
raise webob.exc.HTTPNotFound(explanation=exc_str)
except webob.exc.HTTPError as e:
with excutils.save_and_reraise_exception():
msg = (_("Failed to upload image data for image %(image_id)s"
" due to HTTP error: %(error)s") %
{'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
'error': encodeutils.exception_to_unicode(e)})
_send_notification(notify_error, 'image.upload', msg)
except Exception as e:
with excutils.save_and_reraise_exception():
msg = (_("Failed to upload image data for image %(image_id)s "
"due to internal error: %(error)s") %
{'image_id': self.repo.image_id,
'error': utils.exception_to_str(e)})
'error': encodeutils.exception_to_unicode(e)})
_send_notification(notify_error, 'image.upload', msg)
else:
self.send_notification('image.upload', self.repo)

View File

@ -19,6 +19,7 @@ Reference implementation registry server WSGI controller
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import strutils
from oslo_utils import timeutils
from webob import exc
@ -435,7 +436,7 @@ class Controller(object):
return exc.HTTPConflict(msg)
except exception.Invalid as e:
msg = (_("Failed to add image metadata. "
"Got error: %s") % utils.exception_to_str(e))
"Got error: %s") % encodeutils.exception_to_unicode(e))
LOG.error(msg)
return exc.HTTPBadRequest(msg)
except Exception:
@ -484,7 +485,7 @@ class Controller(object):
return dict(image=make_image_dict(updated_image))
except exception.Invalid as e:
msg = (_("Failed to update image metadata. "
"Got error: %s") % utils.exception_to_str(e))
"Got error: %s") % encodeutils.exception_to_unicode(e))
LOG.error(msg)
return exc.HTTPBadRequest(msg)
except exception.ImageNotFound:
@ -507,7 +508,7 @@ class Controller(object):
request=req,
content_type='text/plain')
except exception.Conflict as e:
LOG.info(utils.exception_to_str(e))
LOG.info(encodeutils.exception_to_unicode(e))
raise exc.HTTPConflict(body='Image operation conflicts',
request=req,
content_type='text/plain')

View File

@ -14,6 +14,7 @@
# under the License.
from oslo_log import log as logging
from oslo_utils import encodeutils
import webob.exc
from glance.common import exception
@ -130,7 +131,7 @@ class Controller(object):
"image %(id)s") % {'id': image_id}
LOG.warn(msg)
msg = (_("Invalid membership association: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=msg)
add = []
@ -147,7 +148,7 @@ class Controller(object):
"image %(id)s") % {'id': image_id}
LOG.warn(msg)
msg = (_("Invalid membership association: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=msg)
# Figure out what can_share should be
@ -250,7 +251,7 @@ class Controller(object):
"image %(id)s") % {'id': image_id}
LOG.warn(msg)
msg = (_("Invalid membership association: %s") %
utils.exception_to_str(e))
encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=msg)
# Look up an existing membership...

View File

@ -14,10 +14,10 @@
# under the License.
import jsonschema
from oslo_utils import encodeutils
import six
from glance.common import exception
from glance.common import utils
from glance import i18n
_ = i18n._
@ -39,8 +39,8 @@ class Schema(object):
try:
jsonschema.validate(obj, self.raw())
except jsonschema.ValidationError as e:
raise exception.InvalidObject(schema=self.name,
reason=utils.exception_to_str(e))
reason = encodeutils.exception_to_unicode(e)
raise exception.InvalidObject(schema=self.name, reason=reason)
def filter(self, obj):
filtered = {}

View File

@ -19,11 +19,11 @@ import time
import eventlet
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import six
from glance.common import crypt
from glance.common import exception
from glance.common import utils
from glance import context
import glance.db as db_api
from glance import i18n
@ -232,7 +232,7 @@ class Scrubber(object):
records = self.db_queue.get_all_locations()
except Exception as err:
LOG.error(_LE("Can not get scrub jobs from queue: %s") %
utils.exception_to_str(err))
encodeutils.exception_to_unicode(err))
return {}
delete_jobs = {}

View File

@ -17,6 +17,7 @@ import json
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import six
import webob.exc
@ -72,7 +73,7 @@ class SearchController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def plugins_info(self, req):
@ -84,7 +85,7 @@ class SearchController(object):
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()
def index(self, req, actions, default_index=None, default_type=None):
@ -107,7 +108,7 @@ class SearchController(object):
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError()

View File

@ -15,8 +15,8 @@
from oslo_log import log as logging
import oslo_messaging
from oslo_utils import encodeutils
from glance.common import utils
from glance.search.plugins import base
LOG = logging.getLogger(__name__)
@ -39,7 +39,7 @@ class ImageHandler(base.NotificationBase):
actions[event_type](payload)
return oslo_messaging.NotificationResult.HANDLED
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
def create(self, payload):
id = payload['id']

View File

@ -17,8 +17,8 @@ import six
from oslo_log import log as logging
import oslo_messaging
from oslo_utils import encodeutils
from glance.common import utils
from glance.search.plugins import base
LOG = logging.getLogger(__name__)
@ -57,7 +57,7 @@ class MetadefHandler(base.NotificationBase):
actions[event_type](payload)
return oslo_messaging.NotificationResult.HANDLED
except Exception as e:
LOG.error(utils.exception_to_str(e))
LOG.error(encodeutils.exception_to_unicode(e))
def run_create(self, id, payload):
self.engine.create(

View File

@ -15,6 +15,7 @@
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import six
import webob.exc
from wsme.rest import json
@ -25,7 +26,6 @@ from glance.api.v2.model.metadef_resource_type import ResourceTypeAssociation
from glance.api.v2.model.metadef_resource_type import ResourceTypeAssociations
from glance.api.v2.model.metadef_resource_type import ResourceTypes
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
@ -96,8 +96,9 @@ class ResourceTypeController(object):
rs_type_repo.add(new_resource_type)
except exception.Forbidden as e:
msg = (_LE("Forbidden to create resource type. Reason: %("
"reason)s") % {'reason': utils.exception_to_str(e)})
msg = (_LE("Forbidden to create resource type. "
"Reason: %(reason)s")
% {'reason': encodeutils.exception_to_unicode(e)})
LOG.error(msg)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotFound as e:
@ -155,7 +156,7 @@ class RequestDeserializer(wsgi.JSONRequestDeserializer):
if key in image:
msg = _("Attribute '%s' is read-only.") % key
raise webob.exc.HTTPForbidden(
explanation=utils.exception_to_str(msg))
explanation=encodeutils.exception_to_unicode(msg))
def create(self, request):
body = self._get_request_body(request)

View File

@ -13,8 +13,10 @@
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import encodeutils
import six
from glance.common import exception
from glance.common import utils
from glance.tests import utils as test_utils
@ -25,23 +27,26 @@ class GlanceExceptionTestCase(test_utils.BaseTestCase):
message = "default message"
exc = FakeGlanceException()
self.assertEqual('default message', utils.exception_to_str(exc))
self.assertEqual('default message',
encodeutils.exception_to_unicode(exc))
def test_specified_error_msg(self):
msg = exception.GlanceException('test')
self.assertIn('test', utils.exception_to_str(msg))
self.assertIn('test', encodeutils.exception_to_unicode(msg))
def test_default_error_msg_with_kwargs(self):
class FakeGlanceException(exception.GlanceException):
message = "default message: %(code)s"
exc = FakeGlanceException(code=500)
self.assertEqual("default message: 500", utils.exception_to_str(exc))
self.assertEqual("default message: 500",
encodeutils.exception_to_unicode(exc))
def test_specified_error_msg_with_kwargs(self):
msg = exception.GlanceException('test: %(code)s', code=500)
self.assertIn('test: 500', utils.exception_to_str(msg))
self.assertIn('test: 500', encodeutils.exception_to_unicode(msg))
def test_non_unicode_error_msg(self):
exc = exception.GlanceException(str('test'))
self.assertIsInstance(utils.exception_to_str(exc), str)
self.assertIsInstance(encodeutils.exception_to_unicode(exc),
six.text_type)

View File

@ -406,21 +406,6 @@ class TestUtils(test_utils.BaseTestCase):
utils.parse_valid_host_port,
pair)
def test_exception_to_str(self):
class FakeException(Exception):
def __str__(self):
raise UnicodeError()
ret = utils.exception_to_str(Exception('error message'))
self.assertEqual('error message', ret)
ret = utils.exception_to_str(Exception('\xa5 error message'))
self.assertEqual(' error message', ret)
ret = utils.exception_to_str(FakeException('\xa5 error message'))
self.assertEqual("Caught '%(exception)s' exception." %
{'exception': 'FakeException'}, ret)
class UUIDTestCase(test_utils.BaseTestCase):

View File

@ -19,10 +19,10 @@ import uuid
import mock
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_utils import encodeutils
from glance.common import crypt
from glance.common import exception
from glance.common import utils
import glance.context
import glance.db
from glance.db.sqlalchemy import api
@ -190,7 +190,7 @@ class TestImageRepo(test_utils.BaseTestCase):
fake_uuid = str(uuid.uuid4())
exc = self.assertRaises(exception.ImageNotFound, self.image_repo.get,
fake_uuid)
self.assertIn(fake_uuid, utils.exception_to_str(exc))
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
def test_get_forbidden(self):
self.assertRaises(exception.NotFound, self.image_repo.get, UUID4)
@ -370,7 +370,7 @@ class TestImageRepo(test_utils.BaseTestCase):
image.image_id = fake_uuid
exc = self.assertRaises(exception.ImageNotFound, self.image_repo.save,
image)
self.assertIn(fake_uuid, utils.exception_to_str(exc))
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
def test_remove_image(self):
image = self.image_repo.get(UUID1)
@ -385,7 +385,7 @@ class TestImageRepo(test_utils.BaseTestCase):
image.image_id = fake_uuid
exc = self.assertRaises(
exception.ImageNotFound, self.image_repo.remove, image)
self.assertIn(fake_uuid, utils.exception_to_str(exc))
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
class TestEncryptedLocations(test_utils.BaseTestCase):
@ -585,7 +585,7 @@ class TestImageMemberRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.image_member_repo.remove,
fake_member)
self.assertIn(fake_uuid, utils.exception_to_str(exc))
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
class TestTaskRepo(test_utils.BaseTestCase):

View File

@ -14,8 +14,9 @@
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import encodeutils
from glance.common import exception
from glance.common import utils
import glance.context
import glance.db
import glance.tests.unit.utils as unit_test_utils
@ -244,7 +245,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.namespace_repo.get,
fake_namespace)
self.assertIn(fake_namespace, utils.exception_to_str(exc))
self.assertIn(fake_namespace, encodeutils.exception_to_unicode(exc))
def test_get_namespace_forbidden(self):
self.assertRaises(exception.NotFound,
@ -299,7 +300,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
namespace.namespace = fake_name
exc = self.assertRaises(exception.NotFound, self.namespace_repo.remove,
namespace)
self.assertIn(fake_name, utils.exception_to_str(exc))
self.assertIn(fake_name, encodeutils.exception_to_unicode(exc))
def test_get_property(self):
property = self.property_repo.get(NAMESPACE1, PROPERTY1)
@ -311,7 +312,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.property_repo.get,
NAMESPACE2, PROPERTY1)
self.assertIn(PROPERTY1, utils.exception_to_str(exc))
self.assertIn(PROPERTY1, encodeutils.exception_to_unicode(exc))
def test_list_property(self):
properties = self.property_repo.list(filters={'namespace': NAMESPACE1})
@ -328,7 +329,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_property_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.property_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', utils.exception_to_str(exc))
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
def test_add_property(self):
# NOTE(pawel-koniszewski): Change db_property_fixture to
@ -392,7 +393,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_get_object_not_found(self):
exc = self.assertRaises(exception.NotFound, self.object_repo.get,
NAMESPACE2, OBJECT1)
self.assertIn(OBJECT1, utils.exception_to_str(exc))
self.assertIn(OBJECT1, encodeutils.exception_to_unicode(exc))
def test_list_object(self):
objects = self.object_repo.list(filters={'namespace': NAMESPACE1})
@ -407,7 +408,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_object_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.object_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', utils.exception_to_str(exc))
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
def test_add_object(self):
# NOTE(pawel-koniszewski): Change db_object_fixture to
@ -475,7 +476,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_get_tag_not_found(self):
exc = self.assertRaises(exception.NotFound, self.tag_repo.get,
NAMESPACE2, TAG1)
self.assertIn(TAG1, utils.exception_to_str(exc))
self.assertIn(TAG1, encodeutils.exception_to_unicode(exc))
def test_list_tag(self):
tags = self.tag_repo.list(filters={'namespace': NAMESPACE1})
@ -490,7 +491,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_tag_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.tag_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', utils.exception_to_str(exc))
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
def test_add_tag(self):
# NOTE(pawel-koniszewski): Change db_tag_fixture to