further cleanup of nova/exceptions.py

This commit is contained in:
Brian Waldon 2011-04-27 14:03:05 -07:00
parent 26d44d12b3
commit 8e6875e8c9
12 changed files with 69 additions and 75 deletions

View File

@ -49,8 +49,6 @@ flags.DECLARE('service_down_time', 'nova.scheduler.driver')
LOG = logging.getLogger("nova.api.cloud")
InvalidInputException = exception.InvalidInputException
def _gen_key(context, user_id, key_name):
"""Generate a key
@ -398,11 +396,11 @@ class CloudController(object):
ip_protocol = str(ip_protocol)
if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
raise InvalidInputException(_('%s is not a valid ipProtocol') %
(ip_protocol,))
raise exception.InvalidIpProtocol(protocol=ip_protocol)
if ((min(from_port, to_port) < -1) or
(max(from_port, to_port) > 65535)):
raise InvalidInputException(_('Invalid port range'))
raise exception.InvalidPortRange(from_port=from_port,
to_port=to_port)
values['protocol'] = ip_protocol
values['from_port'] = from_port

View File

@ -48,7 +48,7 @@ class Controller(common.OpenstackController):
"""We cannot depend on the db layer to check for admin access
for the auth manager, so we do it here"""
if not context.is_admin:
raise exception.NotAuthorized(_("Not admin user."))
raise exception.AdminRequired()
def index(self, req):
raise faults.Fault(webob.exc.HTTPNotImplemented())

View File

@ -48,7 +48,7 @@ class Controller(common.OpenstackController):
"""We cannot depend on the db layer to check for admin access
for the auth manager, so we do it here"""
if not context.is_admin:
raise exception.NotAuthorized(_("Not admin user"))
raise exception.AdminRequired()
def index(self, req):
"""Return all users in brief"""

View File

@ -303,7 +303,8 @@ class AuthManager(object):
LOG.debug('signature: %s', signature)
if signature != expected_signature:
LOG.audit(_("Invalid signature for user %s"), user.name)
raise exception.NotAuthorized(_('Signature does not match'))
raise exception.InvalidSignature(signature=signature,
user=user)
elif check_type == 'ec2':
# NOTE(vish): hmac can't handle unicode, so encode ensures that
# secret isn't unicode
@ -314,7 +315,8 @@ class AuthManager(object):
LOG.debug('signature: %s', signature)
if signature != expected_signature:
LOG.audit(_("Invalid signature for user %s"), user.name)
raise exception.NotAuthorized(_('Signature does not match'))
raise exception.InvalidSignature(signature=signature,
user=user)
return (user, project)
def get_access_key(self, user, project):

View File

@ -37,11 +37,11 @@ def create(name, memory, vcpus, local_gb, flavorid, swap=0,
try:
int(option)
except ValueError:
raise exception.InvalidInputException(
_("create arguments must be positive integers"))
raise exception.InvalidInput(reason=_("create arguments must "
"be positive integers"))
if (int(memory) <= 0) or (int(vcpus) <= 0) or (int(local_gb) < 0):
raise exception.InvalidInputException(
_("create arguments must be positive integers"))
raise exception.InvalidInput(reason=_("create arguments must "
"be positive integers"))
try:
db.instance_type_create(
@ -64,7 +64,7 @@ def create(name, memory, vcpus, local_gb, flavorid, swap=0,
def destroy(name):
"""Marks instance types as deleted."""
if name is None:
raise exception.InvalidInputException(_("No instance type specified"))
raise exception.InstanceNotFound(instance_id=instance_name)
else:
try:
db.instance_type_destroy(context.get_admin_context(), name)
@ -76,7 +76,7 @@ def destroy(name):
def purge(name):
"""Removes instance types from database."""
if name is None:
raise exception.InvalidInputException(_("No instance type specified"))
raise exception.InnstanceNotFound(instance_id=name)
else:
try:
db.instance_type_purge(context.get_admin_context(), name)

View File

@ -94,7 +94,7 @@ def require_admin_context(f):
"""
def wrapper(*args, **kwargs):
if not is_admin_context(args[0]):
raise exception.NotAuthorized()
raise exception.AdminRequired()
return f(*args, **kwargs)
return wrapper
@ -105,7 +105,7 @@ def require_context(f):
"""
def wrapper(*args, **kwargs):
if not is_admin_context(args[0]) and not is_user_context(args[0]):
raise exception.NotAuthorized()
raise exception.AdminRequired()
return f(*args, **kwargs)
return wrapper

View File

@ -55,42 +55,6 @@ class ApiError(Error):
super(ApiError, self).__init__('%s: %s' % (code, message))
class NotFound(Error):
pass
class InstanceNotFound(NotFound):
def __init__(self, message, instance_id):
self.instance_id = instance_id
super(InstanceNotFound, self).__init__(message)
class VolumeNotFound(NotFound):
def __init__(self, message, volume_id):
self.volume_id = volume_id
super(VolumeNotFound, self).__init__(message)
class NotAuthorized(Error):
pass
class NotEmpty(Error):
pass
class InvalidInputException(Error):
pass
class InvalidContentType(Error):
pass
class TimeoutException(Error):
pass
class DBError(Error):
"""Wraps an implementation specific exception."""
def __init__(self, inner_exception):
@ -146,9 +110,43 @@ class NovaException(Exception):
return self._error_string
#TODO(bcwaldon): EOL this exception!
class NotAuthorized(NovaException):
message = _("Not authorized.")
def __init__(self, *args, **kwargs):
super(NotFound, self).__init__(**kwargs)
class AdminRequired(NotAuthorized):
message = _("User does not have admin privileges")
class Invalid(NovaException):
pass
message = _("Unacceptable parameters.")
class InvalidSignature(Invalid):
message = _("Invalid signature %(signature)s for user %(user)s.")
class InvalidInput(Invalid):
message = _("Invalid input received") + ": %(reason)s"
class InvalidInstanceType(Invalid):
message = _("Invalid instance type %(instance_type)s.")
class InvalidPortRange(Invalid):
message = _("Invalid port range %(from_port)s:%(to_port)s.")
class InvalidIpProtocol(Invalid):
message = _("Invalid IP protocol %(protocol)s.")
class InvalidContentType(Invalid):
message = _("Invalid content type %(content_type)s.")
class InstanceNotRunning(Invalid):
@ -533,3 +531,7 @@ class ProjectExists(Duplicate):
class InstanceExists(Duplicate):
message = _("Instance %(name)s already exists.")
class MigrationError(NovaException):
message = _("Migration error") + ": %(reason)s"

View File

@ -255,11 +255,9 @@ class Scheduler(object):
mem_avail = mem_total - mem_used
mem_inst = instance_ref['memory_mb']
if mem_avail <= mem_inst:
raise exception.NotEmpty(_("Unable to migrate %(ec2_id)s "
"to destination: %(dest)s "
"(host:%(mem_avail)s "
"<= instance:%(mem_inst)s)")
% locals())
reason = _("Unable to migrate %(ec2_id)s to destination: %(dest)s "
"(host:%(mem_avail)s <= instance:%(mem_inst)s)")
raise exception.MigrationError(reason=reason % locals())
def mounted_on_same_shared_storage(self, context, instance_ref, dest):
"""Check if the src and dest host mount same shared storage.

View File

@ -75,13 +75,13 @@ class InstanceTypeTestCase(test.TestCase):
def test_invalid_create_args_should_fail(self):
"""Ensures that instance type creation fails with invalid args"""
self.assertRaises(
exception.InvalidInputException,
exception.InvalidInput,
instance_types.create, self.name, 0, 1, 120, self.flavorid)
self.assertRaises(
exception.InvalidInputException,
exception.InvalidInput,
instance_types.create, self.name, 256, -1, 120, self.flavorid)
self.assertRaises(
exception.InvalidInputException,
exception.InvalidInput,
instance_types.create, self.name, 256, 1, "aa", self.flavorid)
def test_non_existant_inst_type_shouldnt_delete(self):

View File

@ -768,14 +768,10 @@ class SimpleDriverTestCase(test.TestCase):
s_ref = self._create_compute_service(host='somewhere',
memory_mb_used=12)
try:
self.scheduler.driver._live_migration_dest_check(self.context,
i_ref,
'somewhere')
except exception.NotEmpty, e:
c = (e.message.find('Unable to migrate') >= 0)
self.assertRaises(exception.MigrationError,
self.scheduler.driver._live_migration_dest_check,
self.context, i_ref, 'somewhere')
self.assertTrue(c)
db.instance_destroy(self.context, instance_id)
db.service_destroy(self.context, s_ref['id'])

View File

@ -1059,8 +1059,7 @@ class LibvirtConnection(driver.ComputeDriver):
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_DOMAIN:
msg = _("Instance %s not found") % instance_name
raise exception.NotFound(msg)
raise exception.InstanceNotFound(instance_id=instance_name)
msg = _("Error from libvirt while looking up %(instance_name)s: "
"[Error Code %(error_code)s] %(ex)s") % locals()

View File

@ -428,7 +428,7 @@ class Serializer(object):
try:
return handlers[content_type]
except Exception:
raise exception.InvalidContentType()
raise exception.InvalidContentType(content_type=content_type)
def serialize(self, data, content_type):
"""Serialize a dictionary into the specified content type."""
@ -451,8 +451,7 @@ class Serializer(object):
try:
return handlers[content_type]
except Exception:
raise exception.InvalidContentType(_('Invalid content type %s'
% content_type))
raise exception.InvalidContentType(content_type=content_type)
def _from_json(self, datastring):
return utils.loads(datastring)