Rearrange neutronclient exceptions for more easy use

- Map exceptions from neutron server into corresponding client
  exceptions automatically (without exception mapping dict).
  An exception from Neutron server 'SomeException' will be
  mapped to an exception 'SomeExceptionClient' ('Client' suffix)
  if it is defined.

- If no corresponding exception is defined in client side,
  an exception per response code will be used. Previously
  NeutronClientException was used for all cases and a user
  of client library cannot know exception type without
  checking exception.status_code. It allows client lib users
  (such as Horizon) to handle exceptions more easily.

- All exceptions from client libarry inherit NeutronClientException
  and all CLI related exceptions inherits NeutronCLIError now.

- Remove unused exceptions (including Quantum v1 related)
- MalformedRequestBody is renamed to MalformedResponseBody
  because it is raised in deserializer and deserializer is
  used to parse not request but response.

Closes-Bug: #1296148
Change-Id: I99b9560b3afaf5884fd00353323267da450338fa
This commit is contained in:
Akihiro Motoki 2014-03-22 19:50:08 +09:00
parent debd91bb4a
commit ecad086e59
5 changed files with 170 additions and 127 deletions

@ -80,10 +80,11 @@ class ServiceCatalog(object):
if not matching_endpoints:
raise exceptions.EndpointNotFound()
elif len(matching_endpoints) > 1:
raise exceptions.AmbiguousEndpoints(message=matching_endpoints)
raise exceptions.AmbiguousEndpoints(
matching_endpoints=matching_endpoints)
else:
if endpoint_type not in matching_endpoints[0]:
raise exceptions.EndpointTypeNotFound(message=endpoint_type)
raise exceptions.EndpointTypeNotFound(type_=endpoint_type)
return matching_endpoints[0][endpoint_type]
@ -274,7 +275,7 @@ class HTTPClient(httplib2.Http):
endpoint.get('region') == self.region_name):
if self.endpoint_type not in endpoint:
raise exceptions.EndpointTypeNotFound(
message=self.endpoint_type)
type_=self.endpoint_type)
return endpoint[self.endpoint_type]
raise exceptions.EndpointNotFound()

@ -17,13 +17,21 @@ from neutronclient.common import _
"""
Neutron base exception handling.
Exceptions are classified into three categories:
* Exceptions corresponding to exceptions from neutron server:
This type of exceptions should inherit one of exceptions
in HTTP_EXCEPTION_MAP.
* Exceptions from client library:
This type of exceptions should inherit NeutronClientException.
* Exceptions from CLI code:
This type of exceptions should inherit NeutronCLIError.
"""
class NeutronException(Exception):
"""Base Neutron Exception
Taken from nova.exception.NovaException
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the constructor.
@ -31,10 +39,11 @@ class NeutronException(Exception):
"""
message = _("An unknown exception occurred.")
def __init__(self, **kwargs):
def __init__(self, message=None, **kwargs):
if message:
self.message = message
try:
self._error_string = self.message % kwargs
except Exception:
# at least get the core message out if something happened
self._error_string = self.message
@ -43,95 +52,124 @@ class NeutronException(Exception):
return self._error_string
class NotFound(NeutronException):
pass
class NeutronClientException(NeutronException):
"""Base exception which exceptions from Neutron are mapped into.
def __init__(self, **kwargs):
message = kwargs.get('message')
self.status_code = kwargs.get('status_code', 0)
if message:
self.message = message
super(NeutronClientException, self).__init__(**kwargs)
NOTE: on the client side, we use different exception types in order
to allow client library users to handle server exceptions in try...except
blocks. The actual error message is the one generated on the server side.
"""
def __init__(self, message=None, **kwargs):
if 'status_code' in kwargs:
self.status_code = kwargs['status_code']
super(NeutronClientException, self).__init__(message, **kwargs)
# NOTE: on the client side, we use different exception types in order
# to allow client library users to handle server exceptions in try...except
# blocks. The actual error message is the one generated on the server side
class NetworkNotFoundClient(NeutronClientException):
pass
# Base exceptions from Neutron
class PortNotFoundClient(NeutronClientException):
pass
class MalformedResponseBody(NeutronException):
message = _("Malformed response body: %(reason)s")
class StateInvalidClient(NeutronClientException):
pass
class NetworkInUseClient(NeutronClientException):
pass
class PortInUseClient(NeutronClientException):
pass
class IpAddressInUseClient(NeutronClientException):
pass
class AlreadyAttachedClient(NeutronClientException):
pass
class IpAddressGenerationFailureClient(NeutronClientException):
pass
class ExternalIpAddressExhaustedClient(NeutronClientException):
pass
class BadRequest(NeutronClientException):
status_code = 400
class Unauthorized(NeutronClientException):
status_code = 401
message = _("Unauthorized: bad credentials.")
class Forbidden(NeutronClientException):
status_code = 403
message = _("Forbidden: your credentials don't give you access to this "
"resource.")
class NotFound(NeutronClientException):
status_code = 404
class Conflict(NeutronClientException):
status_code = 409
class InternalServerError(NeutronClientException):
status_code = 500
class ServiceUnavailable(NeutronClientException):
status_code = 503
HTTP_EXCEPTION_MAP = {
400: BadRequest,
401: Unauthorized,
403: Forbidden,
404: NotFound,
409: Conflict,
500: InternalServerError,
503: ServiceUnavailable,
}
# Exceptions mapped to Neutron server exceptions
# These are defined if a user of client library needs specific exception.
# Exception name should be <Neutron Exception Name> + 'Client'
# e.g., NetworkNotFound -> NetworkNotFoundClient
class NetworkNotFoundClient(NotFound):
pass
class PortNotFoundClient(NotFound):
pass
class StateInvalidClient(BadRequest):
pass
class NetworkInUseClient(Conflict):
pass
class PortInUseClient(Conflict):
pass
class IpAddressInUseClient(Conflict):
pass
# TODO(amotoki): It is unused in Neutron, but it is referred to
# in Horizon code. After Horizon code is updated, remove it.
class AlreadyAttachedClient(Conflict):
pass
class IpAddressGenerationFailureClient(Conflict):
pass
class ExternalIpAddressExhaustedClient(BadRequest):
pass
# Exceptions from client library
class NoAuthURLProvided(Unauthorized):
message = _("auth_url was not provided to the Neutron client")
class EndpointNotFound(NeutronClientException):
"""Could not find Service or Region in Service Catalog."""
message = _("Could not find Service or Region in Service Catalog.")
class EndpointTypeNotFound(NeutronClientException):
"""Could not find endpoint type in Service Catalog."""
def __str__(self):
msg = _("Could not find endpoint type %s in Service Catalog.")
return msg % repr(self.message)
message = _("Could not find endpoint type %(type_)s in Service Catalog.")
class AmbiguousEndpoints(NeutronClientException):
"""Found more than one matching endpoint in Service Catalog."""
def __str__(self):
return _("AmbiguousEndpoints: %s") % repr(self.message)
class NeutronCLIError(NeutronClientException):
"""Exception raised when command line parsing fails."""
pass
message = _("Found more than one matching endpoint in Service Catalog: "
"%(matching_endpoints)")
class RequestURITooLong(NeutronClientException):
@ -146,47 +184,36 @@ class ConnectionFailed(NeutronClientException):
message = _("Connection to neutron failed: %(reason)s")
class BadInputError(Exception):
"""Error resulting from a client sending bad input to a server."""
pass
class SslCertificateValidationError(NeutronClientException):
message = _("SSL certificate validation has failed: %(reason)s")
class NoAuthURLProvided(BadInputError):
message = _("auth_url was not provided to the Neutron client")
class MalformedResponseBody(NeutronClientException):
message = _("Malformed response body: %(reason)s")
class Error(Exception):
def __init__(self, message=None):
super(Error, self).__init__(message)
class MalformedRequestBody(NeutronException):
message = _("Malformed request body: %(reason)s")
class Invalid(Error):
pass
class InvalidContentType(Invalid):
class InvalidContentType(NeutronClientException):
message = _("Invalid content type %(content_type)s.")
class UnsupportedVersion(Exception):
# Command line exceptions
class NeutronCLIError(NeutronException):
"""Exception raised when command line parsing fails."""
pass
class CommandError(NeutronCLIError):
pass
class UnsupportedVersion(NeutronCLIError):
"""Indicates that the user is trying to use an unsupported
version of the API
"""
pass
class CommandError(Exception):
pass
class NeutronClientNoUniqueMatch(NeutronClientException):
class NeutronClientNoUniqueMatch(NeutronCLIError):
message = _("Multiple %(resource)s matches found for name '%(name)s',"
" use an ID to be more specific.")
class SslCertificateValidationError(NeutronClientException):
message = _("SSL certificate validation has failed: %(reason)s")

@ -224,7 +224,7 @@ class JSONDeserializer(TextDeserializer):
return jsonutils.loads(datastring)
except ValueError:
msg = _("Cannot understand JSON")
raise exception.MalformedRequestBody(reason=msg)
raise exception.MalformedResponseBody(reason=msg)
def default(self, datastring):
return {'body': self._from_json(datastring)}
@ -297,7 +297,7 @@ class XMLDeserializer(TextDeserializer):
parseError = True
if parseError:
msg = _("Cannot understand XML")
raise exception.MalformedRequestBody(reason=msg)
raise exception.MalformedResponseBody(reason=msg)
else:
raise

@ -557,12 +557,26 @@ class CLITestV20ExceptionHandler(CLITestV20Base):
'IpAddressInUse', err_msg, '')
def test_exception_handler_v20_neutron_known_error(self):
error_msg = 'Network not found'
error_detail = 'Network detail'
self._test_exception_handler_v20(
exceptions.NetworkNotFoundClient, 404,
error_msg + '\n' + error_detail,
'NetworkNotFound', error_msg, error_detail)
known_error_map = [
('NetworkNotFound', exceptions.NetworkNotFoundClient, 404),
('PortNotFound', exceptions.PortNotFoundClient, 404),
('NetworkInUse', exceptions.NetworkInUseClient, 409),
('PortInUse', exceptions.PortInUseClient, 409),
('StateInvalid', exceptions.StateInvalidClient, 400),
('IpAddressInUse', exceptions.IpAddressInUseClient, 409),
('IpAddressGenerationFailure',
exceptions.IpAddressGenerationFailureClient, 409),
('ExternalIpAddressExhausted',
exceptions.ExternalIpAddressExhaustedClient, 400),
]
error_msg = 'dummy exception message'
error_detail = 'sample detail'
for server_exc, client_exc, status_code in known_error_map:
self._test_exception_handler_v20(
client_exc, status_code,
error_msg + '\n' + error_detail,
server_exc, error_msg, error_detail)
def test_exception_handler_v20_neutron_known_error_without_detail(self):
error_msg = 'Network not found'
@ -572,11 +586,20 @@ class CLITestV20ExceptionHandler(CLITestV20Base):
error_msg,
'NetworkNotFound', error_msg, error_detail)
def test_exception_handler_v20_neutron_unknown_error(self):
def test_exception_handler_v20_unknown_error_to_per_code_exception(self):
for status_code, client_exc in exceptions.HTTP_EXCEPTION_MAP.items():
error_msg = 'Unknown error'
error_detail = 'This is detail'
self._test_exception_handler_v20(
client_exc, status_code,
error_msg + '\n' + error_detail,
'UnknownError', error_msg, error_detail)
def test_exception_handler_v20_neutron_unknown_status_code(self):
error_msg = 'Unknown error'
error_detail = 'This is detail'
self._test_exception_handler_v20(
exceptions.NeutronClientException, 400,
exceptions.NeutronClientException, 501,
error_msg + '\n' + error_detail,
'UnknownError', error_msg, error_detail)

@ -31,18 +31,6 @@ from neutronclient.common import utils
_logger = logging.getLogger(__name__)
NEUTRON_ERRORS = {
'NetworkNotFound': exceptions.NetworkNotFoundClient,
'NetworkInUse': exceptions.NetworkInUseClient,
'PortNotFound': exceptions.PortNotFoundClient,
'RequestedStateInvalid': exceptions.StateInvalidClient,
'PortInUse': exceptions.PortInUseClient,
'IpAddressInUse': exceptions.IpAddressInUseClient,
'AlreadyAttached': exceptions.AlreadyAttachedClient,
'IpAddressGenerationFailure': exceptions.IpAddressGenerationFailureClient,
'ExternalIpAddressExhausted': exceptions.ExternalIpAddressExhaustedClient,
}
def exception_handler_v20(status_code, error_content):
"""Exception handler for API v2.0 client
@ -70,11 +58,15 @@ def exception_handler_v20(status_code, error_content):
except Exception:
bad_neutron_error_flag = True
if not bad_neutron_error_flag:
try:
# raise the appropriate error!
raise NEUTRON_ERRORS[error_type](message=error_message,
status_code=status_code)
except KeyError:
# If corresponding exception is defined, use it.
client_exc = getattr(exceptions, '%sClient' % error_type, None)
# Otherwise look up per status-code client exception
if not client_exc:
client_exc = exceptions.HTTP_EXCEPTION_MAP.get(status_code)
if client_exc:
raise client_exc(message=error_message,
status_code=status_code)
else:
raise exceptions.NeutronClientException(
status_code=status_code, message=error_message)
else: