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.
"""
pass 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`
"""
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
"""HTTP 401 - Unauthorized.
class Unauthorized(HTTPClientError): Similar to 403 Forbidden, but specifically for use when authentication
"""HTTP 401 - Unauthorized. is required and has failed or has not yet been provided.
An alias of :py:exc:`keystoneauth1.exceptions.http.Unauthorized`
"""
Similar to 403 Forbidden, but specifically for use when authentication PaymentRequired = _exc.PaymentRequired
is required and has failed or has not yet been provided. """HTTP 402 - Payment Required.
"""
http_status = 401
message = _("Unauthorized")
Reserved for future use.
An alias of :py:exc:`keystoneauth1.exceptions.http.PaymentRequired`
"""
class PaymentRequired(HTTPClientError): Forbidden = _exc.Forbidden
"""HTTP 402 - Payment Required. """HTTP 403 - Forbidden.
Reserved for future use. The request was a valid request, but the server is refusing to respond
""" to it.
http_status = 402 An alias of :py:exc:`keystoneauth1.exceptions.http.Forbidden`
message = _("Payment Required") """
NotFound = _exc.NotFound
"""HTTP 404 - Not Found.
class Forbidden(HTTPClientError): The requested resource could not be found but may be available again
"""HTTP 403 - Forbidden. in the future.
An alias of :py:exc:`keystoneauth1.exceptions.http.NotFound`
"""
The request was a valid request, but the server is refusing to respond MethodNotAllowed = _exc.MethodNotAllowed
to it. """HTTP 405 - Method Not Allowed.
"""
http_status = 403
message = _("Forbidden")
A request was made of a resource using a request method not supported
by that resource.
An alias of :py:exc:`keystoneauth1.exceptions.http.MethodNotAllowed`
"""
class NotFound(HTTPClientError): NotAcceptable = _exc.NotAcceptable
"""HTTP 404 - Not Found. """HTTP 406 - Not Acceptable.
The requested resource could not be found but may be available again The requested resource is only capable of generating content not
in the future. acceptable according to the Accept headers sent in the request.
""" An alias of :py:exc:`keystoneauth1.exceptions.http.NotAcceptable`
http_status = 404 """
message = _("Not Found")
ProxyAuthenticationRequired = _exc.ProxyAuthenticationRequired
"""HTTP 407 - Proxy Authentication Required.
class MethodNotAllowed(HTTPClientError): The client must first authenticate itself with the proxy.
"""HTTP 405 - Method Not Allowed. An alias of :py:exc:`keystoneauth1.exceptions.http.ProxyAuthenticationRequired`
"""
A request was made of a resource using a request method not supported RequestTimeout = _exc.RequestTimeout
by that resource. """HTTP 408 - Request Timeout.
"""
http_status = 405
message = _("Method Not Allowed")
The server timed out waiting for the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.RequestTimeout`
"""
class NotAcceptable(HTTPClientError): Conflict = _exc.Conflict
"""HTTP 406 - Not Acceptable. """HTTP 409 - Conflict.
The requested resource is only capable of generating content not Indicates that the request could not be processed because of conflict
acceptable according to the Accept headers sent in the request. in the request, such as an edit conflict.
""" An alias of :py:exc:`keystoneauth1.exceptions.http.Conflict`
http_status = 406 """
message = _("Not Acceptable")
Gone = _exc.Gone
"""HTTP 410 - Gone.
class ProxyAuthenticationRequired(HTTPClientError): Indicates that the resource requested is no longer available and will
"""HTTP 407 - Proxy Authentication Required. not be available again.
An alias of :py:exc:`keystoneauth1.exceptions.http.Gone`
"""
The client must first authenticate itself with the proxy. LengthRequired = _exc.LengthRequired
""" """HTTP 411 - Length Required.
http_status = 407
message = _("Proxy Authentication Required")
The request did not specify the length of its content, which is
required by the requested resource.
An alias of :py:exc:`keystoneauth1.exceptions.http.LengthRequired`
"""
class RequestTimeout(HTTPClientError): PreconditionFailed = _exc.PreconditionFailed
"""HTTP 408 - Request Timeout. """HTTP 412 - Precondition Failed.
The server timed out waiting for the request. The server does not meet one of the preconditions that the requester
""" put on the request.
http_status = 408 An alias of :py:exc:`keystoneauth1.exceptions.http.PreconditionFailed`
message = _("Request Timeout") """
RequestEntityTooLarge = _exc.RequestEntityTooLarge
"""HTTP 413 - Request Entity Too Large.
class Conflict(HTTPClientError): The request is larger than the server is willing or able to process.
"""HTTP 409 - Conflict. An alias of :py:exc:`keystoneauth1.exceptions.http.RequestEntityTooLarge`
"""
Indicates that the request could not be processed because of conflict RequestUriTooLong = _exc.RequestUriTooLong
in the request, such as an edit conflict. """HTTP 414 - Request-URI Too Long.
"""
http_status = 409
message = _("Conflict")
The URI provided was too long for the server to process.
An alias of :py:exc:`keystoneauth1.exceptions.http.RequestUriTooLong`
"""
class Gone(HTTPClientError): UnsupportedMediaType = _exc.UnsupportedMediaType
"""HTTP 410 - Gone. """HTTP 415 - Unsupported Media Type.
Indicates that the resource requested is no longer available and will The request entity has a media type which the server or resource does
not be available again. not support.
""" An alias of :py:exc:`keystoneauth1.exceptions.http.UnsupportedMediaType`
http_status = 410 """
message = _("Gone")
RequestedRangeNotSatisfiable = _exc.RequestedRangeNotSatisfiable
"""HTTP 416 - Requested Range Not Satisfiable.
class LengthRequired(HTTPClientError): The client has asked for a portion of the file, but the server cannot
"""HTTP 411 - Length Required. supply that portion.
An alias of
:py:exc:`keystoneauth1.exceptions.http.RequestedRangeNotSatisfiable`
"""
The request did not specify the length of its content, which is ExpectationFailed = _exc.ExpectationFailed
required by the requested resource. """HTTP 417 - Expectation Failed.
"""
http_status = 411
message = _("Length Required")
The server cannot meet the requirements of the Expect request-header field.
An alias of :py:exc:`keystoneauth1.exceptions.http.ExpectationFailed`
"""
class PreconditionFailed(HTTPClientError): UnprocessableEntity = _exc.UnprocessableEntity
"""HTTP 412 - Precondition Failed. """HTTP 422 - Unprocessable Entity.
The server does not meet one of the preconditions that the requester The request was well-formed but was unable to be followed due to semantic
put on the request. errors.
""" An alias of :py:exc:`keystoneauth1.exceptions.http.UnprocessableEntity`
http_status = 412 """
message = _("Precondition Failed")
InternalServerError = _exc.InternalServerError
"""HTTP 500 - Internal Server Error.
class RequestEntityTooLarge(HTTPClientError): A generic error message, given when no more specific message is suitable.
"""HTTP 413 - Request Entity Too Large. An alias of :py:exc:`keystoneauth1.exceptions.http.InternalServerError`
"""
The request is larger than the server is willing or able to process. HttpNotImplemented = _exc.HttpNotImplemented
""" """HTTP 501 - Not Implemented.
http_status = 413
message = _("Request Entity Too Large")
def __init__(self, *args, **kwargs): The server either does not recognize the request method, or it lacks
try: the ability to fulfill the request.
self.retry_after = int(kwargs.pop('retry_after')) An alias of :py:exc:`keystoneauth1.exceptions.http.HttpNotImplemented`
except (KeyError, ValueError): """
self.retry_after = 0
super(RequestEntityTooLarge, self).__init__(*args, **kwargs) BadGateway = _exc.BadGateway
"""HTTP 502 - Bad Gateway.
The server was acting as a gateway or proxy and received an invalid
response from the upstream server.
An alias of :py:exc:`keystoneauth1.exceptions.http.BadGateway`
"""
class RequestUriTooLong(HTTPClientError): ServiceUnavailable = _exc.ServiceUnavailable
"""HTTP 414 - Request-URI Too Long. """HTTP 503 - Service Unavailable.
The URI provided was too long for the server to process. The server is currently unavailable.
""" An alias of :py:exc:`keystoneauth1.exceptions.http.ServiceUnavailable`
http_status = 414 """
message = _("Request-URI Too Long")
GatewayTimeout = _exc.GatewayTimeout
"""HTTP 504 - Gateway Timeout.
class UnsupportedMediaType(HTTPClientError): The server was acting as a gateway or proxy and did not receive a timely
"""HTTP 415 - Unsupported Media Type. response from the upstream server.
An alias of :py:exc:`keystoneauth1.exceptions.http.GatewayTimeout`
"""
The request entity has a media type which the server or resource does HttpVersionNotSupported = _exc.HttpVersionNotSupported
not support. """HTTP 505 - HttpVersion Not Supported.
"""
http_status = 415
message = _("Unsupported Media Type")
The server does not support the HTTP protocol version used in the request.
An alias of :py:exc:`keystoneauth1.exceptions.http.HttpVersionNotSupported`
"""
class RequestedRangeNotSatisfiable(HTTPClientError): from_response = _exc.from_response
"""HTTP 416 - Requested Range Not Satisfiable. """Returns an instance of :class:`HttpError` or subclass based on response.
The client has asked for a portion of the file, but the server cannot An alias of :py:func:`keystoneauth1.exceptions.http.from_response`
supply that portion. """
"""
http_status = 416
message = _("Requested Range Not Satisfiable")
class ExpectationFailed(HTTPClientError):
"""HTTP 417 - Expectation Failed.
The server cannot meet the requirements of the Expect request-header field.
"""
http_status = 417
message = _("Expectation Failed")
class UnprocessableEntity(HTTPClientError):
"""HTTP 422 - Unprocessable Entity.
The request was well-formed but was unable to be followed due to semantic
errors.
"""
http_status = 422
message = _("Unprocessable Entity")
class InternalServerError(HttpServerError):
"""HTTP 500 - Internal Server Error.
A generic error message, given when no more specific message is suitable.
"""
http_status = 500
message = _("Internal Server Error")
# NotImplemented is a python keyword.
class HttpNotImplemented(HttpServerError):
"""HTTP 501 - Not Implemented.
The server either does not recognize the request method, or it lacks
the ability to fulfill the request.
"""
http_status = 501
message = _("Not Implemented")
class BadGateway(HttpServerError):
"""HTTP 502 - Bad Gateway.
The server was acting as a gateway or proxy and received an invalid
response from the upstream server.
"""
http_status = 502
message = _("Bad Gateway")
class ServiceUnavailable(HttpServerError):
"""HTTP 503 - Service Unavailable.
The server is currently unavailable.
"""
http_status = 503
message = _("Service Unavailable")
class GatewayTimeout(HttpServerError):
"""HTTP 504 - Gateway Timeout.
The server was acting as a gateway or proxy and did not receive a timely
response from the upstream server.
"""
http_status = 504
message = _("Gateway Timeout")
class HttpVersionNotSupported(HttpServerError):
"""HTTP 505 - HttpVersion Not Supported.
The server does not support the HTTP protocol version used in the request.
"""
http_status = 505
message = _("HTTP Version Not Supported")
# _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.
:param response: instance of `requests.Response` class
: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,47 +366,40 @@ 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
"""There were no auth plugins that could be created from the parameters
provided.
class NoMatchingPlugin(ClientException): An alias of :py:exc:`keystoneauth1.exceptions.auth_plugins.NoMatchingPlugin`
"""There were no auth plugins that could be created from the parameters """
provided.
:param str name: The name of the plugin that was attempted to load.
.. 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):