Merge "Replaces exceptions.Error with NovaException"

This commit is contained in:
Jenkins 2012-05-07 21:52:29 +00:00 committed by Gerrit Code Review
commit f729925f5a
38 changed files with 204 additions and 203 deletions

View File

@ -188,7 +188,8 @@ class ExtensionManager(object):
LOG.audit(_('Loaded extension: %s'), alias)
if alias in self.extensions:
raise exception.Error("Found duplicate extension: %s" % alias)
raise exception.NovaException("Found duplicate extension: %s"
% alias)
self.extensions[alias] = ext
def get_resources(self):

View File

@ -447,7 +447,7 @@ class AuthManager(object):
"""
if role == 'projectmanager':
if not project:
raise exception.Error(_("Must specify project"))
raise exception.NovaException(_("Must specify project"))
return self.is_project_manager(user, project)
global_role = self._has_role(User.safe_id(user),

View File

@ -78,7 +78,7 @@ class Signer(object):
def s3_authorization(self, headers, verb, path):
"""Generate S3 authorization string."""
if not boto:
raise exception.Error('boto is not installed')
raise exception.NovaException('boto is not installed')
c_string = boto.utils.canonical_string(verb, path, headers)
hmac_copy = self.hmac.copy()
hmac_copy.update(c_string)
@ -97,7 +97,7 @@ class Signer(object):
return self._calc_signature_1(params)
if params['SignatureVersion'] == '2':
return self._calc_signature_2(params, verb, server_string, path)
raise exception.Error('Unknown Signature Version: %s' %
raise exception.NovaException('Unknown Signature Version: %s' %
params['SignatureVersion'])
@staticmethod
@ -140,16 +140,17 @@ class Signer(object):
string_to_sign = '%s\n%s\n%s\n' % (verb, server_string, path)
if 'SignatureMethod' not in params:
raise exception.Error('No SignatureMethod specified')
raise exception.NovaException('No SignatureMethod specified')
if params['SignatureMethod'] == 'HmacSHA256':
if not self.hmac_256:
raise exception.Error('SHA256 not supported on this server')
msg = _('SHA256 not supported on this server')
raise exception.NovaException(msg)
current_hmac = self.hmac_256
elif params['SignatureMethod'] == 'HmacSHA1':
current_hmac = self.hmac
else:
raise exception.Error('SignatureMethod %s not supported'
raise exception.NovaException('SignatureMethod %s not supported'
% params['SignatureMethod'])
keys = params.keys()

View File

@ -128,10 +128,10 @@ class BaseAPI(base.Base):
params = {}
if not host:
if not instance:
raise exception.Error(_("No compute host specified"))
raise exception.NovaException(_("No compute host specified"))
host = instance['host']
if not host:
raise exception.Error(_("Unable to find host for "
raise exception.NovaException(_("Unable to find host for "
"Instance %s") % instance['uuid'])
queue = self.db.queue_get_for(context, FLAGS.compute_topic, host)
if instance:

View File

@ -74,12 +74,12 @@ IMPL = utils.LazyPluggable('db_backend',
sqlalchemy='nova.db.sqlalchemy.api')
class NoMoreNetworks(exception.Error):
class NoMoreNetworks(exception.NovaException):
"""No more available networks."""
pass
class NoMoreTargets(exception.Error):
class NoMoreTargets(exception.NovaException):
"""No more available targets"""
pass

View File

@ -72,7 +72,7 @@ def db_sync(version=None):
try:
version = int(version)
except ValueError:
raise exception.Error(_("version should be an integer"))
raise exception.NovaException(_("version should be an integer"))
current_version = db_version()
repository = _find_migrate_repo()

View File

@ -31,6 +31,7 @@ import sys
import webob.exc
from nova import log as logging
from nova.openstack.common import excutils
LOG = logging.getLogger(__name__)
@ -62,28 +63,6 @@ class ProcessExecutionError(IOError):
IOError.__init__(self, message)
class Error(Exception):
pass
class EC2APIError(Error):
def __init__(self, message='Unknown', code=None):
self.msg = message
self.code = code
if code:
outstr = '%s: %s' % (code, message)
else:
outstr = '%s' % message
super(EC2APIError, self).__init__(outstr)
class DBError(Error):
"""Wraps an implementation specific exception."""
def __init__(self, inner_exception=None):
self.inner_exception = inner_exception
super(DBError, self).__init__(str(inner_exception))
def wrap_db_error(f):
def _wrap(*args, **kwargs):
try:
@ -113,36 +92,30 @@ def wrap_exception(notifier=None, publisher_id=None, event_type=None,
try:
return f(*args, **kw)
except Exception, e:
# Save exception since it can be clobbered during processing
# below before we can re-raise
exc_info = sys.exc_info()
with excutils.save_and_reraise_exception():
if notifier:
payload = dict(args=args, exception=e)
payload.update(kw)
if notifier:
payload = dict(args=args, exception=e)
payload.update(kw)
# Use a temp vars so we don't shadow
# our outer definitions.
temp_level = level
if not temp_level:
temp_level = notifier.ERROR
# Use a temp vars so we don't shadow
# our outer definitions.
temp_level = level
if not temp_level:
temp_level = notifier.ERROR
temp_type = event_type
if not temp_type:
# If f has multiple decorators, they must use
# functools.wraps to ensure the name is
# propagated.
temp_type = f.__name__
temp_type = event_type
if not temp_type:
# If f has multiple decorators, they must use
# functools.wraps to ensure the name is
# propagated.
temp_type = f.__name__
context = get_context_from_function_and_args(f,
args,
kw)
context = get_context_from_function_and_args(f,
args,
kw)
notifier.notify(context, publisher_id, temp_type,
temp_level, payload)
# re-raise original exception since it may have been clobbered
raise exc_info[0], exc_info[1], exc_info[2]
notifier.notify(context, publisher_id, temp_type,
temp_level, payload)
return functools.wraps(f)(wrapped)
return inner
@ -183,6 +156,26 @@ class NovaException(Exception):
super(NovaException, self).__init__(message)
class EC2APIError(NovaException):
message = _("Unknown")
def __init__(self, message=None, code=None):
self.msg = message
self.code = code
if code:
outstr = '%s: %s' % (code, message)
else:
outstr = '%s' % message
super(EC2APIError, self).__init__(outstr)
class DBError(NovaException):
"""Wraps an implementation specific exception."""
def __init__(self, inner_exception=None):
self.inner_exception = inner_exception
super(DBError, self).__init__(str(inner_exception))
class DecryptionFailure(NovaException):
message = _("Failed to decrypt text")

View File

@ -376,15 +376,15 @@ class S3ImageService(object):
"args": {"project_id": context.project_id,
"text": base64.b64encode(encrypted_key)}})
except Exception, exc:
raise exception.Error(_('Failed to decrypt private key: %s')
% exc)
msg = _('Failed to decrypt private key: %s') % exc
raise exception.NovaException(msg)
try:
iv = rpc.call(elevated, FLAGS.cert_topic,
{"method": "decrypt_text",
"args": {"project_id": context.project_id,
"text": base64.b64encode(encrypted_iv)}})
except Exception, exc:
raise exception.Error(_('Failed to decrypt initialization '
raise exception.NovaException(_('Failed to decrypt initialization '
'vector: %s') % exc)
try:
@ -395,7 +395,7 @@ class S3ImageService(object):
'-iv', '%s' % (iv,),
'-out', '%s' % (decrypted_filename,))
except exception.ProcessExecutionError, exc:
raise exception.Error(_('Failed to decrypt image file '
raise exception.NovaException(_('Failed to decrypt image file '
'%(image_file)s: %(err)s') %
{'image_file': encrypted_filename,
'err': exc.stdout})
@ -407,7 +407,7 @@ class S3ImageService(object):
for n in tar_file.getnames():
if not os.path.abspath(os.path.join(path, n)).startswith(path):
tar_file.close()
raise exception.Error(_('Unsafe filenames in image'))
raise exception.NovaException(_('Unsafe filenames in image'))
tar_file.close()
@staticmethod

View File

@ -1043,7 +1043,8 @@ class LinuxBridgeInterfaceDriver(LinuxNetInterfaceDriver):
if (err and err != "device %s is already a member of a bridge;"
"can't enslave it to bridge %s.\n" % (interface, bridge)):
raise exception.Error('Failed to add interface: %s' % err)
msg = _('Failed to add interface: %s') % err
raise exception.NovaException(msg)
# Don't forward traffic unless we were told to be a gateway
ipv4_filter = iptables_manager.ipv4['filter']

View File

@ -158,7 +158,7 @@ FLAGS = flags.FLAGS
FLAGS.register_opts(network_opts)
class AddressAlreadyAllocated(exception.Error):
class AddressAlreadyAllocated(exception.NovaException):
"""Address was already allocated."""
pass
@ -1245,8 +1245,8 @@ class NetworkManager(manager.SchedulerDependentManager):
fixed_ip = self.db.fixed_ip_get_by_address(context, address)
if fixed_ip['instance_id'] is None:
raise exception.Error(_('IP %s leased that is not associated') %
address)
msg = _('IP %s leased that is not associated') % address
raise exception.NovaException(msg)
now = utils.utcnow()
self.db.fixed_ip_update(context,
fixed_ip['address'],
@ -1262,8 +1262,8 @@ class NetworkManager(manager.SchedulerDependentManager):
fixed_ip = self.db.fixed_ip_get_by_address(context, address)
if fixed_ip['instance_id'] is None:
raise exception.Error(_('IP %s released that is not associated') %
address)
msg = _('IP %s released that is not associated') % address
raise exception.NovaException(msg)
if not fixed_ip['leased']:
LOG.warn(_('IP %s released that was not leased'), address,
context=context)

View File

@ -134,9 +134,9 @@ class TestS3ImageService(test.TestCase):
self.assertEqual(block_device_mapping, expected_bdm)
def test_s3_malicious_tarballs(self):
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.image_service._test_for_malicious_tarball,
"/unused", os.path.join(os.path.dirname(__file__), 'abs.tar.gz'))
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.image_service._test_for_malicious_tarball,
"/unused", os.path.join(os.path.dirname(__file__), 'rel.tar.gz'))

View File

@ -56,10 +56,6 @@ def good_function():
return 99
def bad_function_error():
raise exception.Error()
def bad_function_exception(blah="a", boo="b", context=None):
raise test.TestingException()
@ -69,10 +65,6 @@ class WrapExceptionTestCase(test.TestCase):
wrapped = exception.wrap_exception()
self.assertEquals(99, wrapped(good_function)())
def test_wrap_exception_throws_error(self):
wrapped = exception.wrap_exception()
self.assertRaises(exception.Error, wrapped(bad_function_error))
def test_wrap_exception_throws_exception(self):
wrapped = exception.wrap_exception()
self.assertRaises(test.TestingException,

View File

@ -1193,8 +1193,8 @@ class LibvirtConnTestCase(test.TestCase):
conn.ensure_filtering_rules_for_instance(instance_ref,
network_info,
time=fake_timer)
except exception.Error, e:
c1 = (0 <= e.message.find('Timeout migrating for'))
except exception.NovaException, e:
c1 = (0 <= str(e).find('Timeout migrating for'))
self.assertTrue(c1)
self.assertEqual(29, fake_timer.counter, "Didn't wait the expected "

View File

@ -65,14 +65,14 @@ class SignerTestCase(test.TestCase):
'GET', 'server', '/foo'))
def test_generate_invalid_signature_method_defined(self):
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.signer.generate,
{'SignatureVersion': '2',
'SignatureMethod': 'invalid_method'},
'GET', 'server', '/foo')
def test_generate_no_signature_method_defined(self):
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.signer.generate,
{'SignatureVersion': '2'},
'GET', 'server', '/foo')
@ -85,7 +85,7 @@ class SignerTestCase(test.TestCase):
# Create Signer again now that hashlib.sha256 is None
self.signer = signer.Signer(
'uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o')
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.signer.generate,
{'SignatureVersion': '2',
'SignatureMethod': 'HmacSHA256'},
@ -106,7 +106,7 @@ class SignerTestCase(test.TestCase):
'GET', 'server', '/foo'))
def test_generate_unknown_version(self):
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.signer.generate,
{'SignatureMethod': 'HmacSHA256', 'SignatureVersion': '9'},
'GET', 'server', '/foo')

View File

@ -87,7 +87,7 @@ exit 1
os.unlink(tmpfilename2)
def test_unknown_kwargs_raises_error(self):
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
utils.execute,
'/usr/bin/env', 'true',
this_is_not_a_valid_kwarg=True)
@ -229,16 +229,16 @@ class GetFromPathTestCase(test.TestCase):
def test_bad_xpath(self):
f = utils.get_from_path
self.assertRaises(exception.Error, f, [], None)
self.assertRaises(exception.Error, f, [], "")
self.assertRaises(exception.Error, f, [], "/")
self.assertRaises(exception.Error, f, [], "/a")
self.assertRaises(exception.Error, f, [], "/a/")
self.assertRaises(exception.Error, f, [], "//")
self.assertRaises(exception.Error, f, [], "//a")
self.assertRaises(exception.Error, f, [], "a//a")
self.assertRaises(exception.Error, f, [], "a//a/")
self.assertRaises(exception.Error, f, [], "a/a/")
self.assertRaises(exception.NovaException, f, [], None)
self.assertRaises(exception.NovaException, f, [], "")
self.assertRaises(exception.NovaException, f, [], "/")
self.assertRaises(exception.NovaException, f, [], "/a")
self.assertRaises(exception.NovaException, f, [], "/a/")
self.assertRaises(exception.NovaException, f, [], "//")
self.assertRaises(exception.NovaException, f, [], "//a")
self.assertRaises(exception.NovaException, f, [], "a//a")
self.assertRaises(exception.NovaException, f, [], "a//a/")
self.assertRaises(exception.NovaException, f, [], "a/a/")
def test_real_failure1(self):
# Real world failure case...

View File

@ -195,7 +195,7 @@ class VolumeTestCase(test.TestCase):
instance_ref = db.volume_get_instance(self.context, volume_id)
self.assertEqual(instance_ref['id'], instance_id)
self.assertRaises(exception.Error,
self.assertRaises(exception.NovaException,
self.volume.delete_volume,
self.context,
volume_id)

View File

@ -304,7 +304,7 @@ class XenAPIVMTestCase(test.TestCase):
instance = self._create_instance()
name = "MySnapshot"
self.assertRaises(exception.Error, self.conn.snapshot,
self.assertRaises(exception.NovaException, self.conn.snapshot,
self.context, instance, name)
def test_instance_snapshot(self):

View File

@ -208,5 +208,5 @@ class HpSanISCSITestCase(test.TestCase):
def test_cliq_error(self):
try:
self.driver._cliq_run_xml("testError", {})
except exception.Error:
except exception.NovaException:
pass

View File

@ -167,7 +167,7 @@ def execute(*cmd, **kwargs):
the command is prefixed by the command specified
in the root_helper FLAG.
:raises exception.Error: on receiving unknown arguments
:raises exception.NovaException: on receiving unknown arguments
:raises exception.ProcessExecutionError:
:returns: a tuple, (stdout, stderr) from the spawned process, or None if
@ -188,8 +188,8 @@ def execute(*cmd, **kwargs):
shell = kwargs.pop('shell', False)
if len(kwargs):
raise exception.Error(_('Got unknown keyword args '
'to utils.execute: %r') % kwargs)
raise exception.NovaException(_('Got unknown keyword args '
'to utils.execute: %r') % kwargs)
if run_as_root:
cmd = shlex.split(FLAGS.root_helper) + list(cmd)
@ -271,11 +271,12 @@ def ssh_execute(ssh, cmd, process_input=None,
addl_env=None, check_exit_code=True):
LOG.debug(_('Running cmd (SSH): %s'), ' '.join(cmd))
if addl_env:
raise exception.Error(_('Environment not supported over SSH'))
raise exception.NovaException(_('Environment not supported over SSH'))
if process_input:
# This is (probably) fixable if we need it...
raise exception.Error(_('process_input not supported over SSH'))
msg = _('process_input not supported over SSH')
raise exception.NovaException(msg)
stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd)
channel = stdout_stream.channel
@ -484,11 +485,12 @@ def get_my_linklocal(interface):
if address[0] is not None:
return address[0]
else:
raise exception.Error(_('Link Local address is not found.:%s')
% if_str)
msg = _('Link Local address is not found.:%s') % if_str
raise exception.NovaException(msg)
except Exception as ex:
raise exception.Error(_("Couldn't get Link Local IP of %(interface)s"
" :%(ex)s") % locals())
msg = _("Couldn't get Link Local IP of %(interface)s"
" :%(ex)s") % locals()
raise exception.NovaException(msg)
def utcnow():
@ -598,7 +600,8 @@ class LazyPluggable(object):
if not self.__backend:
backend_name = FLAGS[self.__pivot]
if backend_name not in self.__backends:
raise exception.Error(_('Invalid backend: %s') % backend_name)
msg = _('Invalid backend: %s') % backend_name
raise exception.NovaException(msg)
backend = self.__backends[backend_name]
if isinstance(backend, tuple):
@ -1005,12 +1008,12 @@ def get_from_path(items, path):
"""
if path is None:
raise exception.Error('Invalid mini_xpath')
raise exception.NovaException('Invalid mini_xpath')
(first_token, sep, remainder) = path.partition('/')
if first_token == '':
raise exception.Error('Invalid mini_xpath')
raise exception.NovaException('Invalid mini_xpath')
results = []

View File

@ -39,4 +39,4 @@ def get_baremetal_nodes():
elif d == 'fake':
return fake.get_baremetal_nodes()
else:
raise exception.Error(_("Unknown baremetal driver %(d)s"))
raise exception.NovaException(_("Unknown baremetal driver %(d)s"))

View File

@ -325,7 +325,7 @@ class BareMetalNodes(object):
return power_state.RUNNING
except Exception as ex:
self.deactivate_node(node_id)
raise exception.Error(_("Node is unknown error state."))
raise exception.NovaException(_("Node is unknown error state."))
def get_console_output(self, console_log, node_id):
"""

View File

@ -162,7 +162,8 @@ class _DiskImage(object):
self.handlers.remove('loop')
if not self.handlers:
raise exception.Error(_('no capable image handler configured'))
msg = _('no capable image handler configured')
raise exception.NovaException(msg)
@property
def errors(self):
@ -175,7 +176,8 @@ class _DiskImage(object):
for cls in (loop.Mount, nbd.Mount, guestfs.Mount):
if cls.mode == mode:
return cls
raise exception.Error(_("unknown disk image handler: %s") % mode)
msg = _("unknown disk image handler: %s") % mode
raise exception.NovaException(msg)
def mount(self):
"""Mount a disk image, using the object attributes.
@ -186,7 +188,7 @@ class _DiskImage(object):
contains any diagnostics.
"""
if self._mounter:
raise exception.Error(_('image already mounted'))
raise exception.NovaException(_('image already mounted'))
if not self.mount_dir:
self.mount_dir = tempfile.mkdtemp()
@ -242,7 +244,7 @@ def inject_data(image,
finally:
img.umount()
else:
raise exception.Error(img.errors)
raise exception.NovaException(img.errors)
def inject_files(image, files, partition=None, use_cow=False):
@ -255,7 +257,7 @@ def inject_files(image, files, partition=None, use_cow=False):
finally:
img.umount()
else:
raise exception.Error(img.errors)
raise exception.NovaException(img.errors)
def setup_container(image, container_dir=None, use_cow=False):
@ -271,7 +273,7 @@ def setup_container(image, container_dir=None, use_cow=False):
if img.mount():
return img
else:
raise exception.Error(img.errors)
raise exception.NovaException(img.errors)
except Exception, exn:
LOG.exception(_('Failed to mount filesystem: %s'), exn)
@ -403,7 +405,7 @@ def _set_passwd(username, admin_passwd, passwd_file, shadow_file):
:param passwd_file: path to the passwd file
:param shadow_file: path to the shadow password file
:returns: nothing
:raises: exception.Error(), IOError()
:raises: exception.NovaException(), IOError()
"""
salt_set = ('abcdefghijklmnopqrstuvwxyz'
@ -439,7 +441,7 @@ def _set_passwd(username, admin_passwd, passwd_file, shadow_file):
break
if not found:
msg = _('User %(username)s not found in password file.')
raise exception.Error(msg % username)
raise exception.NovaException(msg % username)
# update password in the shadow file.It's an error if the
# the user doesn't exist.
@ -455,7 +457,7 @@ def _set_passwd(username, admin_passwd, passwd_file, shadow_file):
s_file.close()
if not found:
msg = _('User %(username)s not found in shadow file.')
raise exception.Error(msg % username)
raise exception.NovaException(msg % username)
s_file = open(shadow_file, 'wb')
for entry in new_shadow:
s_file.write(entry)

View File

@ -990,7 +990,8 @@ class LibvirtConnection(driver.ComputeDriver):
continue
break
else:
raise exception.Error(_("Guest does not have a console available"))
msg = _("Guest does not have a console available")
raise exception.NovaException(msg)
self._chown_console_log_for_instance(instance['name'])
data = self._flush_libvirt_console(pty)
@ -1708,7 +1709,7 @@ class LibvirtConnection(driver.ComputeDriver):
msg = _("Error from libvirt while looking up %(instance_name)s: "
"[Error Code %(error_code)s] %(ex)s") % locals()
raise exception.Error(msg)
raise exception.NovaException(msg)
def get_info(self, instance):
"""Retrieve information from libvirt for a specific instance name.
@ -1947,7 +1948,7 @@ class LibvirtConnection(driver.ComputeDriver):
# But ... we can at least give the user a nice message
method = getattr(self._conn, 'getVersion', None)
if method is None:
raise exception.Error(_("libvirt version is too old"
raise exception.NovaException(_("libvirt version is too old"
" (does not support getVersion)"))
# NOTE(justinsb): If we wanted to get the version, we could:
# method = getattr(libvirt, 'getVersion', None)
@ -2162,7 +2163,7 @@ class LibvirtConnection(driver.ComputeDriver):
timeout_count.pop()
if len(timeout_count) == 0:
msg = _('Timeout migrating for %s. nwfilter not found.')
raise exception.Error(msg % instance_ref.name)
raise exception.NovaException(msg % instance_ref.name)
time.sleep(1)
def live_migration(self, ctxt, instance_ref, dest,

View File

@ -160,8 +160,8 @@ class LibvirtISCSIVolumeDriver(LibvirtVolumeDriver):
tries = 0
while not os.path.exists(host_device):
if tries >= FLAGS.num_iscsi_scan_tries:
raise exception.Error(_("iSCSI device not found at %s") %
(host_device))
raise exception.NovaException(_("iSCSI device not found at %s")
% (host_device))
LOG.warn(_("ISCSI volume not yet found at: %(mount_device)s. "
"Will rescan & retry. Try number: %(tries)s") %

View File

@ -128,10 +128,9 @@ class ManagedObject(object):
for elem in self.propSet:
if elem.name == attr:
return elem.val
raise exception.Error(_("Property %(attr)s not set for the managed "
"object %(objName)s") %
{'attr': attr,
'objName': self.objName})
msg = _("Property %(attr)s not set for the managed object %(name)s")
raise exception.NovaException(msg % {'attr': attr,
'name': self.objName})
class DataObject(object):
@ -498,7 +497,7 @@ class FakeVim(object):
s = self._session
self._session = None
if s not in _db_content['session']:
raise exception.Error(
raise exception.NovaException(
_("Logging out a session that is invalid or already logged "
"out: %s") % s)
del _db_content['session'][s]

View File

@ -96,21 +96,21 @@ class GlanceWriteThread(object):
# If the state is killed, then raise an exception.
elif image_status == "killed":
self.stop()
exc_msg = (_("Glance image %s is in killed state") %
self.image_id)
LOG.error(exc_msg)
self.done.send_exception(exception.Error(exc_msg))
msg = (_("Glance image %s is in killed state") %
self.image_id)
LOG.error(msg)
self.done.send_exception(exception.NovaException(msg))
elif image_status in ["saving", "queued"]:
greenthread.sleep(GLANCE_POLL_INTERVAL)
else:
self.stop()
exc_msg = _("Glance image "
msg = _("Glance image "
"%(image_id)s is in unknown state "
"- %(state)s") % {
"image_id": self.image_id,
"state": image_status}
LOG.error(exc_msg)
self.done.send_exception(exception.Error(exc_msg))
LOG.error(msg)
self.done.send_exception(exception.NovaException(msg))
except Exception, exc:
self.stop()
self.done.send_exception(exc)

View File

@ -128,7 +128,7 @@ def get_vlanid_and_vswitch_for_portgroup(session, pg_name):
excep = _("ESX SOAP server returned an empty port group "
"for the host system in its response")
LOG.exception(excep)
raise exception.Error(excep)
raise exception.NovaException(excep)
port_grps_on_host = port_grps_on_host_ret.HostPortGroup
for p_gp in port_grps_on_host:
if p_gp.spec.name == pg_name:
@ -165,6 +165,6 @@ def create_port_group(session, pg_name, vswitch_name, vlan_id=0):
# concerned with the port group being created, which is done
# by the other call, we can ignore the exception.
if error_util.FAULT_ALREADY_EXISTS not in exc.fault_list:
raise exception.Error(exc)
raise exception.NovaException(exc)
LOG.debug(_("Created Port Group with name %s on "
"the ESX host") % pg_name)

View File

@ -125,7 +125,7 @@ class VMWareVMOps(object):
if data_store_name is None:
msg = _("Couldn't get a local Datastore reference")
LOG.error(msg, instance=instance)
raise exception.Error(msg)
raise exception.NovaException(msg)
data_store_name = _get_datastore_ref()

View File

@ -75,7 +75,7 @@ def start_transfer(read_file_handle, data_size, write_file_handle=None,
# Log and raise the exception.
LOG.exception(exc)
raise exception.Error(exc)
raise exception.NovaException(exc)
finally:
# No matter what, try closing the read and write handles, if it so
# applies.

View File

@ -276,7 +276,7 @@ class VMWareAPISession(object):
except Exception, excep:
LOG.critical(_("In vmwareapi:_create_session, "
"got this exception: %s") % excep)
raise exception.Error(excep)
raise exception.NovaException(excep)
def __del__(self):
"""Logs-out the session."""
@ -404,7 +404,7 @@ class VMWareAPISession(object):
action["error"] = error_info
LOG.warn(_("Task [%(task_name)s] %(task_ref)s "
"status: error %(error_info)s") % locals())
done.send_exception(exception.Error(error_info))
done.send_exception(exception.NovaException(error_info))
db.instance_action_create(context.get_admin_context(), action)
except Exception, excep:
LOG.warn(_("In vmwareapi:_poll_task, Got this error %s") % excep)

View File

@ -321,7 +321,7 @@ def get_record(table, ref):
def check_for_session_leaks():
if len(_db_content['session']) > 0:
raise exception.Error('Sessions have leaked: %s' %
raise exception.NovaException('Sessions have leaked: %s' %
_db_content['session'])
@ -583,7 +583,7 @@ class SessionBase(object):
s = self._session
self._session = None
if s not in _db_content['session']:
raise exception.Error(
raise exception.NovaException(
"Logging out a session that is invalid or already logged "
"out: %s" % s)
del _db_content['session'][s]

View File

@ -374,8 +374,8 @@ class VMHelper(xenapi.HelperBase):
if vbd_rec['userdevice'] == '0':
vdi_rec = session.call_xenapi("VDI.get_record", vbd_rec['VDI'])
return vbd_rec['VDI'], vdi_rec
raise exception.Error(_("No primary VDI found for %(vm_ref)s") %
locals())
raise exception.NovaException(_("No primary VDI found for %(vm_ref)s")
% locals())
@classmethod
def create_snapshot(cls, session, instance, vm_ref, label):
@ -851,7 +851,7 @@ class VMHelper(xenapi.HelperBase):
elif (image_type in (ImageType.KERNEL, ImageType.RAMDISK) and
vdi_size > FLAGS.max_kernel_ramdisk_size):
max_size = FLAGS.max_kernel_ramdisk_size
raise exception.Error(
raise exception.NovaException(
_("Kernel/Ramdisk image is too large: %(vdi_size)d bytes, "
"max %(max_size)d bytes") % locals())
@ -972,8 +972,8 @@ class VMHelper(xenapi.HelperBase):
# 4. ISO
is_pv = False
else:
raise exception.Error(_("Unknown image format %(disk_image_type)s")
% locals())
msg = _("Unknown image format %(disk_image_type)s") % locals()
raise exception.NovaException(msg)
return is_pv
@ -1424,7 +1424,7 @@ def _wait_for_vhd_coalesce(session, instance, sr_ref, vdi_ref,
msg = (_("VHD coalesce attempts exceeded (%(max_attempts)d)"
", giving up...") % locals())
raise exception.Error(msg)
raise exception.NovaException(msg)
def remap_vbd_dev(dev):

View File

@ -58,7 +58,7 @@ class VolumeOps(object):
def delete_volume_for_sm(self, vdi_uuid):
vdi_ref = self._session.call_xenapi("VDI.get_by_uuid", vdi_uuid)
if vdi_ref is None:
raise exception.Error(_('Could not find VDI ref'))
raise exception.NovaException(_('Could not find VDI ref'))
vm_utils.VMHelper.destroy_vdi(self._session, vdi_ref)
@ -67,10 +67,10 @@ class VolumeOps(object):
sr_ref = volume_utils.VolumeHelper.create_sr(self._session,
label, params)
if sr_ref is None:
raise exception.Error(_('Could not create SR'))
raise exception.NovaException(_('Could not create SR'))
sr_rec = self._session.call_xenapi("SR.get_record", sr_ref)
if sr_rec is None:
raise exception.Error(_('Could not retrieve SR record'))
raise exception.NovaException(_('Could not retrieve SR record'))
return sr_rec['uuid']
# Checks if sr has already been introduced to this host
@ -84,7 +84,7 @@ class VolumeOps(object):
sr_ref = volume_utils.VolumeHelper.introduce_sr(self._session,
sr_uuid, label, params)
if sr_ref is None:
raise exception.Error(_('Could not introduce SR'))
raise exception.NovaException(_('Could not introduce SR'))
return sr_ref
def is_sr_on_host(self, sr_uuid):
@ -106,7 +106,7 @@ class VolumeOps(object):
volume_utils.VolumeHelper.forget_sr(self._session, sr_uuid)
except volume_utils.StorageError, exc:
LOG.exception(exc)
raise exception.Error(_('Could not forget SR'))
raise exception.NovaException(_('Could not forget SR'))
def attach_volume(self, connection_info, instance_name, mountpoint):
"""Attach volume storage to VM instance"""

View File

@ -103,7 +103,7 @@ class VolumeDriver(object):
run_as_root=True)
volume_groups = out.split()
if not FLAGS.volume_group in volume_groups:
raise exception.Error(_("volume group %s doesn't exist")
raise exception.NovaException(_("volume group %s doesn't exist")
% FLAGS.volume_group)
def _create_volume(self, volume_name, sizestr):
@ -381,7 +381,7 @@ class ISCSIDriver(VolumeDriver):
location = self._do_iscsi_discovery(volume)
if not location:
raise exception.Error(_("Could not find iSCSI export "
raise exception.NovaException(_("Could not find iSCSI export "
" for volume %s") %
(volume['name']))
@ -502,7 +502,7 @@ class RBDDriver(VolumeDriver):
(stdout, stderr) = self._execute('rados', 'lspools')
pools = stdout.split("\n")
if not FLAGS.rbd_pool in pools:
raise exception.Error(_("rbd has no pool %s") %
raise exception.NovaException(_("rbd has no pool %s") %
FLAGS.rbd_pool)
def create_volume(self, volume):
@ -576,9 +576,10 @@ class SheepdogDriver(VolumeDriver):
# use it and just check if 'running' is in the output.
(out, err) = self._execute('collie', 'cluster', 'info')
if not 'running' in out.split():
raise exception.Error(_("Sheepdog is not working: %s") % out)
msg = _("Sheepdog is not working: %s") % out
raise exception.NovaException(msg)
except exception.ProcessExecutionError:
raise exception.Error(_("Sheepdog is not working"))
raise exception.NovaException(_("Sheepdog is not working"))
def create_volume(self, volume):
"""Creates a sheepdog volume"""

View File

@ -152,9 +152,10 @@ class VolumeManager(manager.SchedulerDependentManager):
context = context.elevated()
volume_ref = self.db.volume_get(context, volume_id)
if volume_ref['attach_status'] == "attached":
raise exception.Error(_("Volume is still attached"))
raise exception.NovaException(_("Volume is still attached"))
if volume_ref['host'] != self.host:
raise exception.Error(_("Volume is not local to this node"))
msg = _("Volume is not local to this node")
raise exception.NovaException(msg)
self._reset_stats()
try:

View File

@ -77,7 +77,7 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
name = request.Name
reason = response.Reason
msg = _('API %(name)sfailed: %(reason)s')
raise exception.Error(msg % locals())
raise exception.NovaException(msg % locals())
def _create_client(self, wsdl_url, login, password, hostname, port):
"""
@ -106,7 +106,7 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
'netapp_storage_service']
for flag in required_flags:
if not getattr(FLAGS, flag, None):
raise exception.Error(_('%s is not set') % flag)
raise exception.NovaException(_('%s is not set') % flag)
def do_setup(self, context):
"""
@ -156,7 +156,7 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
events = self._get_job_progress(job_id)
for event in events:
if event.EventStatus == 'error':
raise exception.Error(_('Job failed: %s') %
raise exception.NovaException(_('Job failed: %s') %
(event.ErrorMessage))
if event.EventType == 'job-end':
return events
@ -237,7 +237,8 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
AssumeConfirmation=True)
except (suds.WebFault, Exception):
server.DatasetEditRollback(EditLockId=lock_id)
raise exception.Error(_('Failed to provision dataset member'))
msg = _('Failed to provision dataset member')
raise exception.NovaException(msg)
lun_id = None
@ -249,7 +250,8 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
lun_id = event.ProgressLunInfo.LunPathId
if not lun_id:
raise exception.Error(_('No LUN was created by the provision job'))
msg = _('No LUN was created by the provision job')
raise exception.NovaException(msg)
def _remove_destroy(self, name, project):
"""
@ -258,8 +260,8 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
"""
lun_id = self._get_lun_id(name, project)
if not lun_id:
raise exception.Error(_("Failed to find LUN ID for volume %s") %
(name))
msg = _("Failed to find LUN ID for volume %s") % (name)
raise exception.NovaException(msg)
member = self.client.factory.create('DatasetMemberParameter')
member.ObjectNameOrId = lun_id
@ -278,7 +280,7 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
except (suds.WebFault, Exception):
server.DatasetEditRollback(EditLockId=lock_id)
msg = _('Failed to remove and delete dataset member')
raise exception.Error(msg)
raise exception.NovaException(msg)
def create_volume(self, volume):
"""Driver entry point for creating a new volume"""
@ -431,7 +433,7 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
lun_id = self._get_lun_id(name, project)
if not lun_id:
msg = _("Failed to find LUN ID for volume %s")
raise exception.Error(msg % name)
raise exception.NovaException(msg % name)
return {'provider_location': lun_id}
def ensure_export(self, context, volume):
@ -601,29 +603,29 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
lun_id = volume['provider_location']
if not lun_id:
msg = _("No LUN ID for volume %s")
raise exception.Error(msg % volume['name'])
raise exception.NovaException(msg % volume['name'])
lun = self._get_lun_details(lun_id)
if not lun:
msg = _('Failed to get LUN details for LUN ID %s')
raise exception.Error(msg % lun_id)
raise exception.NovaException(msg % lun_id)
lun_num = self._ensure_initiator_mapped(lun.HostId, lun.LunPath,
initiator_name)
host = self._get_host_details(lun.HostId)
if not host:
msg = _('Failed to get host details for host ID %s')
raise exception.Error(msg % lun.HostId)
raise exception.NovaException(msg % lun.HostId)
portal = self._get_target_portal_for_host(host.HostId,
host.HostAddress)
if not portal:
msg = _('Failed to get target portal for filer: %s')
raise exception.Error(msg % host.HostName)
raise exception.NovaException(msg % host.HostName)
iqn = self._get_iqn_for_host(host.HostId)
if not iqn:
msg = _('Failed to get target IQN for filer: %s')
raise exception.Error(msg % host.HostName)
raise exception.NovaException(msg % host.HostName)
properties = {}
properties['target_discovered'] = False
@ -655,11 +657,11 @@ class NetAppISCSIDriver(driver.ISCSIDriver):
lun_id = volume['provider_location']
if not lun_id:
msg = _('No LUN ID for volume %s')
raise exception.Error(msg % (volume['name']))
raise exception.NovaException(msg % (volume['name']))
lun = self._get_lun_details(lun_id)
if not lun:
msg = _('Failed to get LUN details for LUN ID %s')
raise exception.Error(msg % (lun_id))
raise exception.NovaException(msg % (lun_id))
self._ensure_initiator_unmapped(lun.HostId, lun.LunPath,
initiator_name)

View File

@ -111,7 +111,8 @@ class SanISCSIDriver(nova.volume.driver.ISCSIDriver):
username=FLAGS.san_login,
pkey=privatekey)
else:
raise exception.Error(_("Specify san_password or san_private_key"))
msg = _("Specify san_password or san_private_key")
raise exception.NovaException(msg)
return ssh
def _execute(self, *cmd, **kwargs):
@ -149,12 +150,12 @@ class SanISCSIDriver(nova.volume.driver.ISCSIDriver):
"""Returns an error if prerequisites aren't met."""
if not self.run_local:
if not (FLAGS.san_password or FLAGS.san_private_key):
raise exception.Error(_('Specify san_password or '
raise exception.NovaException(_('Specify san_password or '
'san_private_key'))
# The san_ip must always be set, because we use it for the target
if not (FLAGS.san_ip):
raise exception.Error(_("san_ip must be set"))
raise exception.NovaException(_("san_ip must be set"))
def _collect_lines(data):
@ -225,7 +226,8 @@ class SolarisISCSIDriver(SanISCSIDriver):
if "View Entry:" in out:
return True
raise exception.Error("Cannot parse list-view output: %s" % (out))
msg = _("Cannot parse list-view output: %s") % (out)
raise exception.NovaException()
def _get_target_groups(self):
"""Gets list of target groups from host."""
@ -459,7 +461,7 @@ class HpSanISCSIDriver(SanISCSIDriver):
msg = (_("Malformed response to CLIQ command "
"%(verb)s %(cliq_args)s. Result=%(out)s") %
locals())
raise exception.Error(msg)
raise exception.NovaException(msg)
result_code = response_node.attrib.get("result")
@ -467,7 +469,7 @@ class HpSanISCSIDriver(SanISCSIDriver):
msg = (_("Error running CLIQ command %(verb)s %(cliq_args)s. "
" Result=%(out)s") %
locals())
raise exception.Error(msg)
raise exception.NovaException(msg)
return result_xml
@ -497,7 +499,7 @@ class HpSanISCSIDriver(SanISCSIDriver):
msg = (_("Unexpected number of virtual ips for cluster "
" %(cluster_name)s. Result=%(_xml)s") %
locals())
raise exception.Error(msg)
raise exception.NovaException(msg)
def _cliq_get_volume_info(self, volume_name):
"""Gets the volume info, including IQN"""
@ -600,7 +602,7 @@ class HpSanISCSIDriver(SanISCSIDriver):
def local_path(self, volume):
# TODO(justinsb): Is this needed here?
raise exception.Error(_("local_path not supported"))
raise exception.NovaException(_("local_path not supported"))
def initialize_connection(self, volume, connector):
"""Assigns the volume to a server.

View File

@ -59,7 +59,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
except Exception as ex:
LOG.debug(_("Failed to create sr %s...continuing") %
str(backend_ref['id']))
raise exception.Error(_('Create failed'))
raise exception.NovaException(_('Create failed'))
LOG.debug(_('SR UUID of new SR is: %s') % sr_uuid)
try:
@ -68,7 +68,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
dict(sr_uuid=sr_uuid))
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to update db"))
raise exception.NovaException(_("Failed to update db"))
else:
# sr introduce, if not already done
@ -88,7 +88,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
self._create_storage_repo(context, backend)
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_('Failed to reach backend %d')
raise exception.NovaException(_('Failed to reach backend %d')
% backend['id'])
def __init__(self, *args, **kwargs):
@ -97,7 +97,8 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
# This driver leverages Xen storage manager, and hence requires
# hypervisor to be Xen
if FLAGS.connection_type != 'xenapi':
raise exception.Error(_('XenSMDriver requires xenapi connection'))
msg = _('XenSMDriver requires xenapi connection')
raise exception.NovaException(msg)
url = FLAGS.xenapi_connection_url
username = FLAGS.xenapi_connection_username
@ -107,7 +108,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
self._volumeops = volumeops.VolumeOps(session)
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to initiate session"))
raise exception.NovaException(_("Failed to initiate session"))
super(XenSMDriver, self).__init__(execute=utils.execute,
sync_exec=utils.execute,
@ -151,10 +152,11 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
self.db.sm_volume_create(self.ctxt, sm_vol_rec)
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to update volume in db"))
msg = _("Failed to update volume in db")
raise exception.NovaException(msg)
else:
raise exception.Error(_('Unable to create volume'))
raise exception.NovaException(_('Unable to create volume'))
def delete_volume(self, volume):
@ -168,13 +170,13 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
self._volumeops.delete_volume_for_sm(vol_rec['vdi_uuid'])
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to delete vdi"))
raise exception.NovaException(_("Failed to delete vdi"))
try:
self.db.sm_volume_delete(self.ctxt, volume['id'])
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to delete volume in db"))
raise exception.NovaException(_("Failed to delete volume in db"))
def local_path(self, volume):
return str(volume['id'])
@ -207,7 +209,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
volume['id']))
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to find volume in db"))
raise exception.NovaException(_("Failed to find volume in db"))
# Keep the volume id key consistent with what ISCSI driver calls it
xensm_properties['volume_id'] = xensm_properties['id']
@ -218,7 +220,7 @@ class XenSMDriver(nova.volume.driver.VolumeDriver):
xensm_properties['backend_id'])
except Exception as ex:
LOG.exception(ex)
raise exception.Error(_("Failed to find backend in db"))
raise exception.NovaException(_("Failed to find backend in db"))
params = self._convert_config_params(backend_conf['config_params'])