Map keystoneclient exceptions to keystoneauth

To allow people to use a keystoneauth session with keystoneclient we
need to make it so that any exceptions that keystoneclient catch are the
same as what keystoneauth might throw.

The only practical way to do this is to map the keystoneclient
exceptions onto the keystoneauth equivalents. This is fairly easy as all
these exceptions were extracted from keystoneclient initially.

Closes-Bug: #1515048
Change-Id: I3b74b0ba1e1f9dda937a2d90e2d75ff0b7597a9b
This commit is contained in:
Jamie Lennox
2015-11-11 10:51:42 +11:00
parent 4a070903d2
commit bdd44d3142
2 changed files with 226 additions and 349 deletions

View File

@@ -224,7 +224,9 @@ latex_documents = [
# If false, no module index is generated. # If false, no module index is generated.
#latex_use_modindex = True #latex_use_modindex = True
keystoneauth_url = 'http://docs.openstack.org/developer/keystoneauth/'
intersphinx_mapping = { intersphinx_mapping = {
'python': ('http://docs.python.org/', None), 'python': ('http://docs.python.org/', None),
'osloconfig': ('http://docs.openstack.org/developer/oslo.config/', None), 'osloconfig': ('http://docs.openstack.org/developer/oslo.config/', None),
'keystoneauth1': (keystoneauth_url, None),
} }

View File

@@ -14,18 +14,40 @@
# under the License. # under the License.
"""Exception definitions.""" """Exception definitions."""
import inspect from keystoneauth1 import exceptions as _exc
import sys
import six
from keystoneclient.i18n import _ from keystoneclient.i18n import _
class ClientException(Exception): ClientException = _exc.ClientException
"""The base exception class for all exceptions this library raises. """The base exception class for all exceptions this library raises.
An alias of :py:exc:`keystoneauth1.exceptions.base.ClientException`
"""
ConnectionError = _exc.ConnectionError
"""Cannot connect to API service.
An alias of :py:exc:`keystoneauth1.exceptions.connection.ConnectionError`
"""
ConnectionRefused = _exc.ConnectFailure
"""Connection refused while trying to connect to API service.
An alias of :py:exc:`keystoneauth1.exceptions.connection.ConnectFailure`
"""
SSLError = _exc.SSLError
"""An SSL error occurred.
An alias of :py:exc:`keystoneauth1.exceptions.connection.SSLError`
"""
AuthorizationFailure = _exc.AuthorizationFailure
"""Cannot authorize API client.
An alias of :py:exc:`keystoneauth1.exceptions.auth.AuthorizationFailure`
""" """
pass
class ValidationError(ClientException): class ValidationError(ClientException):
@@ -43,21 +65,6 @@ class CommandError(ClientException):
pass pass
class AuthorizationFailure(ClientException):
"""Cannot authorize API client."""
pass
class ConnectionError(ClientException):
"""Cannot connect to API service."""
pass
class ConnectionRefused(ConnectionError):
"""Connection refused while trying to connect to API service."""
pass
class AuthPluginOptionsMissing(AuthorizationFailure): class AuthPluginOptionsMissing(AuthorizationFailure):
"""Auth plugin misses some options.""" """Auth plugin misses some options."""
def __init__(self, opt_names): def __init__(self, opt_names):
@@ -80,14 +87,17 @@ class NoUniqueMatch(ClientException):
pass pass
class EndpointException(ClientException): EndpointException = _exc.CatalogException
"""Something is rotten in Service Catalog.""" """Something is rotten in Service Catalog.
pass
An alias of :py:exc:`keystoneauth1.exceptions.catalog.CatalogException`
"""
class EndpointNotFound(EndpointException): EndpointNotFound = _exc.EndpointNotFound
"""Could not find requested endpoint in Service Catalog.""" """Could not find requested endpoint in Service Catalog.
pass
An alias of :py:exc:`keystoneauth1.exceptions.catalog.EndpointNotFound`
"""
class AmbiguousEndpoints(EndpointException): class AmbiguousEndpoints(EndpointException):
@@ -98,26 +108,26 @@ class AmbiguousEndpoints(EndpointException):
self.endpoints = endpoints self.endpoints = endpoints
class HttpError(ClientException): HttpError = _exc.HttpError
"""The base exception class for all HTTP exceptions. """The base exception class for all HTTP exceptions.
"""
http_status = 0
message = _("HTTP Error")
def __init__(self, message=None, details=None, An alias of :py:exc:`keystoneauth1.exceptions.http.HttpError`
response=None, request_id=None, """
url=None, method=None, http_status=None):
self.http_status = http_status or self.http_status HTTPClientError = _exc.HTTPClientError
self.message = message or self.message """Client-side HTTP error.
self.details = details
self.request_id = request_id Exception for cases in which the client seems to have erred.
self.response = response An alias of :py:exc:`keystoneauth1.exceptions.http.HTTPClientError`
self.url = url """
self.method = method
formatted_string = "%s (HTTP %s)" % (self.message, self.http_status) HttpServerError = _exc.HttpServerError
if request_id: """Server-side HTTP error.
formatted_string += " (Request-ID: %s)" % request_id
super(HttpError, self).__init__(formatted_string) Exception for cases in which the server is aware that it has
erred or is incapable of performing the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.HttpServerError`
"""
class HTTPRedirection(HttpError): class HTTPRedirection(HttpError):
@@ -125,23 +135,6 @@ class HTTPRedirection(HttpError):
message = _("HTTP Redirection") message = _("HTTP Redirection")
class HTTPClientError(HttpError):
"""Client-side HTTP error.
Exception for cases in which the client seems to have erred.
"""
message = _("HTTP Client Error")
class HttpServerError(HttpError):
"""Server-side HTTP error.
Exception for cases in which the server is aware that it has
erred or is incapable of performing the request.
"""
message = _("HTTP Server Error")
class MultipleChoices(HTTPRedirection): class MultipleChoices(HTTPRedirection):
"""HTTP 300 - Multiple Choices. """HTTP 300 - Multiple Choices.
@@ -152,318 +145,207 @@ class MultipleChoices(HTTPRedirection):
message = _("Multiple Choices") message = _("Multiple Choices")
class BadRequest(HTTPClientError): BadRequest = _exc.BadRequest
"""HTTP 400 - Bad Request. """HTTP 400 - Bad Request.
The request cannot be fulfilled due to bad syntax. The request cannot be fulfilled due to bad syntax.
An alias of :py:exc:`keystoneauth1.exceptions.http.BadRequest`
""" """
http_status = 400
message = _("Bad Request")
Unauthorized = _exc.Unauthorized
class Unauthorized(HTTPClientError):
"""HTTP 401 - Unauthorized. """HTTP 401 - Unauthorized.
Similar to 403 Forbidden, but specifically for use when authentication Similar to 403 Forbidden, but specifically for use when authentication
is required and has failed or has not yet been provided. is required and has failed or has not yet been provided.
An alias of :py:exc:`keystoneauth1.exceptions.http.Unauthorized`
""" """
http_status = 401
message = _("Unauthorized")
PaymentRequired = _exc.PaymentRequired
class PaymentRequired(HTTPClientError):
"""HTTP 402 - Payment Required. """HTTP 402 - Payment Required.
Reserved for future use. Reserved for future use.
An alias of :py:exc:`keystoneauth1.exceptions.http.PaymentRequired`
""" """
http_status = 402
message = _("Payment Required")
Forbidden = _exc.Forbidden
class Forbidden(HTTPClientError):
"""HTTP 403 - Forbidden. """HTTP 403 - Forbidden.
The request was a valid request, but the server is refusing to respond The request was a valid request, but the server is refusing to respond
to it. to it.
An alias of :py:exc:`keystoneauth1.exceptions.http.Forbidden`
""" """
http_status = 403
message = _("Forbidden")
NotFound = _exc.NotFound
class NotFound(HTTPClientError):
"""HTTP 404 - Not Found. """HTTP 404 - Not Found.
The requested resource could not be found but may be available again The requested resource could not be found but may be available again
in the future. in the future.
An alias of :py:exc:`keystoneauth1.exceptions.http.NotFound`
""" """
http_status = 404
message = _("Not Found")
MethodNotAllowed = _exc.MethodNotAllowed
class MethodNotAllowed(HTTPClientError):
"""HTTP 405 - Method Not Allowed. """HTTP 405 - Method Not Allowed.
A request was made of a resource using a request method not supported A request was made of a resource using a request method not supported
by that resource. by that resource.
An alias of :py:exc:`keystoneauth1.exceptions.http.MethodNotAllowed`
""" """
http_status = 405
message = _("Method Not Allowed")
NotAcceptable = _exc.NotAcceptable
class NotAcceptable(HTTPClientError):
"""HTTP 406 - Not Acceptable. """HTTP 406 - Not Acceptable.
The requested resource is only capable of generating content not The requested resource is only capable of generating content not
acceptable according to the Accept headers sent in the request. acceptable according to the Accept headers sent in the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.NotAcceptable`
""" """
http_status = 406
message = _("Not Acceptable")
ProxyAuthenticationRequired = _exc.ProxyAuthenticationRequired
class ProxyAuthenticationRequired(HTTPClientError):
"""HTTP 407 - Proxy Authentication Required. """HTTP 407 - Proxy Authentication Required.
The client must first authenticate itself with the proxy. The client must first authenticate itself with the proxy.
An alias of :py:exc:`keystoneauth1.exceptions.http.ProxyAuthenticationRequired`
""" """
http_status = 407
message = _("Proxy Authentication Required")
RequestTimeout = _exc.RequestTimeout
class RequestTimeout(HTTPClientError):
"""HTTP 408 - Request Timeout. """HTTP 408 - Request Timeout.
The server timed out waiting for the request. The server timed out waiting for the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.RequestTimeout`
""" """
http_status = 408
message = _("Request Timeout")
Conflict = _exc.Conflict
class Conflict(HTTPClientError):
"""HTTP 409 - Conflict. """HTTP 409 - Conflict.
Indicates that the request could not be processed because of conflict Indicates that the request could not be processed because of conflict
in the request, such as an edit conflict. in the request, such as an edit conflict.
An alias of :py:exc:`keystoneauth1.exceptions.http.Conflict`
""" """
http_status = 409
message = _("Conflict")
Gone = _exc.Gone
class Gone(HTTPClientError):
"""HTTP 410 - Gone. """HTTP 410 - Gone.
Indicates that the resource requested is no longer available and will Indicates that the resource requested is no longer available and will
not be available again. not be available again.
An alias of :py:exc:`keystoneauth1.exceptions.http.Gone`
""" """
http_status = 410
message = _("Gone")
LengthRequired = _exc.LengthRequired
class LengthRequired(HTTPClientError):
"""HTTP 411 - Length Required. """HTTP 411 - Length Required.
The request did not specify the length of its content, which is The request did not specify the length of its content, which is
required by the requested resource. required by the requested resource.
An alias of :py:exc:`keystoneauth1.exceptions.http.LengthRequired`
""" """
http_status = 411
message = _("Length Required")
PreconditionFailed = _exc.PreconditionFailed
class PreconditionFailed(HTTPClientError):
"""HTTP 412 - Precondition Failed. """HTTP 412 - Precondition Failed.
The server does not meet one of the preconditions that the requester The server does not meet one of the preconditions that the requester
put on the request. put on the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.PreconditionFailed`
""" """
http_status = 412
message = _("Precondition Failed")
RequestEntityTooLarge = _exc.RequestEntityTooLarge
class RequestEntityTooLarge(HTTPClientError):
"""HTTP 413 - Request Entity Too Large. """HTTP 413 - Request Entity Too Large.
The request is larger than the server is willing or able to process. The request is larger than the server is willing or able to process.
An alias of :py:exc:`keystoneauth1.exceptions.http.RequestEntityTooLarge`
""" """
http_status = 413
message = _("Request Entity Too Large")
def __init__(self, *args, **kwargs): RequestUriTooLong = _exc.RequestUriTooLong
try:
self.retry_after = int(kwargs.pop('retry_after'))
except (KeyError, ValueError):
self.retry_after = 0
super(RequestEntityTooLarge, self).__init__(*args, **kwargs)
class RequestUriTooLong(HTTPClientError):
"""HTTP 414 - Request-URI Too Long. """HTTP 414 - Request-URI Too Long.
The URI provided was too long for the server to process. The URI provided was too long for the server to process.
An alias of :py:exc:`keystoneauth1.exceptions.http.RequestUriTooLong`
""" """
http_status = 414
message = _("Request-URI Too Long")
UnsupportedMediaType = _exc.UnsupportedMediaType
class UnsupportedMediaType(HTTPClientError):
"""HTTP 415 - Unsupported Media Type. """HTTP 415 - Unsupported Media Type.
The request entity has a media type which the server or resource does The request entity has a media type which the server or resource does
not support. not support.
An alias of :py:exc:`keystoneauth1.exceptions.http.UnsupportedMediaType`
""" """
http_status = 415
message = _("Unsupported Media Type")
RequestedRangeNotSatisfiable = _exc.RequestedRangeNotSatisfiable
class RequestedRangeNotSatisfiable(HTTPClientError):
"""HTTP 416 - Requested Range Not Satisfiable. """HTTP 416 - Requested Range Not Satisfiable.
The client has asked for a portion of the file, but the server cannot The client has asked for a portion of the file, but the server cannot
supply that portion. supply that portion.
An alias of
:py:exc:`keystoneauth1.exceptions.http.RequestedRangeNotSatisfiable`
""" """
http_status = 416
message = _("Requested Range Not Satisfiable")
ExpectationFailed = _exc.ExpectationFailed
class ExpectationFailed(HTTPClientError):
"""HTTP 417 - Expectation Failed. """HTTP 417 - Expectation Failed.
The server cannot meet the requirements of the Expect request-header field. The server cannot meet the requirements of the Expect request-header field.
An alias of :py:exc:`keystoneauth1.exceptions.http.ExpectationFailed`
""" """
http_status = 417
message = _("Expectation Failed")
UnprocessableEntity = _exc.UnprocessableEntity
class UnprocessableEntity(HTTPClientError):
"""HTTP 422 - Unprocessable Entity. """HTTP 422 - Unprocessable Entity.
The request was well-formed but was unable to be followed due to semantic The request was well-formed but was unable to be followed due to semantic
errors. errors.
An alias of :py:exc:`keystoneauth1.exceptions.http.UnprocessableEntity`
""" """
http_status = 422
message = _("Unprocessable Entity")
InternalServerError = _exc.InternalServerError
class InternalServerError(HttpServerError):
"""HTTP 500 - Internal Server Error. """HTTP 500 - Internal Server Error.
A generic error message, given when no more specific message is suitable. A generic error message, given when no more specific message is suitable.
An alias of :py:exc:`keystoneauth1.exceptions.http.InternalServerError`
""" """
http_status = 500
message = _("Internal Server Error")
HttpNotImplemented = _exc.HttpNotImplemented
# NotImplemented is a python keyword.
class HttpNotImplemented(HttpServerError):
"""HTTP 501 - Not Implemented. """HTTP 501 - Not Implemented.
The server either does not recognize the request method, or it lacks The server either does not recognize the request method, or it lacks
the ability to fulfill the request. the ability to fulfill the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.HttpNotImplemented`
""" """
http_status = 501
message = _("Not Implemented")
BadGateway = _exc.BadGateway
class BadGateway(HttpServerError):
"""HTTP 502 - Bad Gateway. """HTTP 502 - Bad Gateway.
The server was acting as a gateway or proxy and received an invalid The server was acting as a gateway or proxy and received an invalid
response from the upstream server. response from the upstream server.
An alias of :py:exc:`keystoneauth1.exceptions.http.BadGateway`
""" """
http_status = 502
message = _("Bad Gateway")
ServiceUnavailable = _exc.ServiceUnavailable
class ServiceUnavailable(HttpServerError):
"""HTTP 503 - Service Unavailable. """HTTP 503 - Service Unavailable.
The server is currently unavailable. The server is currently unavailable.
An alias of :py:exc:`keystoneauth1.exceptions.http.ServiceUnavailable`
""" """
http_status = 503
message = _("Service Unavailable")
GatewayTimeout = _exc.GatewayTimeout
class GatewayTimeout(HttpServerError):
"""HTTP 504 - Gateway Timeout. """HTTP 504 - Gateway Timeout.
The server was acting as a gateway or proxy and did not receive a timely The server was acting as a gateway or proxy and did not receive a timely
response from the upstream server. response from the upstream server.
An alias of :py:exc:`keystoneauth1.exceptions.http.GatewayTimeout`
""" """
http_status = 504
message = _("Gateway Timeout")
HttpVersionNotSupported = _exc.HttpVersionNotSupported
class HttpVersionNotSupported(HttpServerError):
"""HTTP 505 - HttpVersion Not Supported. """HTTP 505 - HttpVersion Not Supported.
The server does not support the HTTP protocol version used in the request. The server does not support the HTTP protocol version used in the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.HttpVersionNotSupported`
""" """
http_status = 505
message = _("HTTP Version Not Supported")
from_response = _exc.from_response
# _code_map contains all the classes that have http_status attribute.
_code_map = dict(
(getattr(obj, 'http_status', None), obj)
for name, obj in six.iteritems(vars(sys.modules[__name__]))
if inspect.isclass(obj) and getattr(obj, 'http_status', False)
)
def from_response(response, method, url):
"""Returns an instance of :class:`HttpError` or subclass based on response. """Returns an instance of :class:`HttpError` or subclass based on response.
:param response: instance of `requests.Response` class An alias of :py:func:`keystoneauth1.exceptions.http.from_response`
:param method: HTTP method used for request
:param url: URL used for request
""" """
req_id = response.headers.get("x-openstack-request-id")
# NOTE(hdd) true for older versions of nova and cinder
if not req_id:
req_id = response.headers.get("x-compute-request-id")
kwargs = {
"http_status": response.status_code,
"response": response,
"method": method,
"url": url,
"request_id": req_id,
}
if "retry-after" in response.headers:
kwargs["retry_after"] = response.headers["retry-after"]
content_type = response.headers.get("Content-Type", "")
if content_type.startswith("application/json"):
try:
body = response.json()
except ValueError:
pass
else:
if isinstance(body, dict):
error = body.get(list(body)[0])
if isinstance(error, dict):
kwargs["message"] = (error.get("message") or
error.get("faultstring"))
kwargs["details"] = (error.get("details") or
six.text_type(body))
elif content_type.startswith("text/"):
kwargs["details"] = getattr(response, 'text', '')
try:
cls = _code_map[response.status_code]
except KeyError:
if 500 <= response.status_code < 600:
cls = HttpServerError
elif 400 <= response.status_code < 500:
cls = HTTPClientError
else:
cls = HttpError
return cls(**kwargs)
# NOTE(akurilin): This alias should be left here to support backwards # NOTE(akurilin): This alias should be left here to support backwards
# compatibility until we are sure that usage of these exceptions in # compatibility until we are sure that usage of these exceptions in
# projects is correct. # projects is correct.
ConnectionError = ConnectionRefused
HTTPNotImplemented = HttpNotImplemented HTTPNotImplemented = HttpNotImplemented
Timeout = RequestTimeout Timeout = RequestTimeout
HTTPError = HttpError HTTPError = HttpError
@@ -484,48 +366,41 @@ class CMSError(Exception):
msg = _('Unable to sign or verify data.') msg = _('Unable to sign or verify data.')
super(CMSError, self).__init__(msg) super(CMSError, self).__init__(msg)
EmptyCatalog = _exc.EmptyCatalog
"""The service catalog is empty.
class EmptyCatalog(EndpointNotFound): An alias of :py:exc:`keystoneauth1.exceptions.catalog.EmptyCatalog`
"""The service catalog is empty.""" """
pass
DiscoveryFailure = _exc.DiscoveryFailure
"""Discovery of client versions failed.
class SSLError(ConnectionRefused): An alias of :py:exc:`keystoneauth1.exceptions.discovery.DiscoveryFailure`
"""An SSL error occurred.""" """
VersionNotAvailable = _exc.VersionNotAvailable
"""Discovery failed as the version you requested is not available.
class DiscoveryFailure(ClientException): An alias of :py:exc:`keystoneauth1.exceptions.discovery.VersionNotAvailable`
"""Discovery of client versions failed.""" """
class VersionNotAvailable(DiscoveryFailure):
"""Discovery failed as the version you requested is not available."""
class MethodNotImplemented(ClientException): class MethodNotImplemented(ClientException):
"""Method not implemented by the keystoneclient API.""" """Method not implemented by the keystoneclient API."""
MissingAuthPlugin = _exc.MissingAuthPlugin
"""An authenticated request is required but no plugin available.
class MissingAuthPlugin(ClientException): An alias of :py:exc:`keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin`
"""An authenticated request is required but no plugin available.""" """
NoMatchingPlugin = _exc.NoMatchingPlugin
class NoMatchingPlugin(ClientException):
"""There were no auth plugins that could be created from the parameters """There were no auth plugins that could be created from the parameters
provided. provided.
:param str name: The name of the plugin that was attempted to load. An alias of :py:exc:`keystoneauth1.exceptions.auth_plugins.NoMatchingPlugin`
.. py:attribute:: name
The name of the plugin that was attempted to load.
""" """
def __init__(self, name):
self.name = name
msg = _('The plugin %s could not be found') % name
super(NoMatchingPlugin, self).__init__(msg)
class UnsupportedParameters(ClientException): class UnsupportedParameters(ClientException):
"""A parameter that was provided or returned is not supported. """A parameter that was provided or returned is not supported.