Rebased to trunk rev 1035.

This commit is contained in:
Masanori Itoh
2011-04-29 22:25:28 +09:00
31 changed files with 709 additions and 375 deletions
+1 -3
View File
@@ -322,9 +322,7 @@ class Executor(wsgi.Application):
except exception.InstanceNotFound as ex:
LOG.info(_('InstanceNotFound raised: %s'), unicode(ex),
context=context)
ec2_id = ec2utils.id_to_ec2_id(ex.instance_id)
message = _('Instance %s not found') % ec2_id
return self._error(req, context, type(ex).__name__, message)
return self._error(req, context, type(ex).__name__, ex.message)
except exception.VolumeNotFound as ex:
LOG.info(_('VolumeNotFound raised: %s'), unicode(ex),
context=context)
+6 -8
View File
@@ -61,8 +61,7 @@ def _gen_key(context, user_id, key_name):
# creation before creating key_pair
try:
db.key_pair_get(context, user_id, key_name)
raise exception.Duplicate(_("The key_pair %s already exists")
% key_name)
raise exception.KeyPairExists(key_name=key_name)
except exception.NotFound:
pass
private_key, public_key, fingerprint = crypto.generate_key_pair()
@@ -909,11 +908,11 @@ class CloudController(object):
try:
internal_id = ec2utils.ec2_id_to_id(ec2_id)
return self.image_service.show(context, internal_id)
except exception.NotFound:
except ValueError:
try:
return self.image_service.show_by_name(context, ec2_id)
except exception.NotFound:
raise exception.NotFound(_('Image %s not found') % ec2_id)
raise exception.ImageNotFound(image_id=ec2_id)
def _format_image(self, image):
"""Convert from format defined by BaseImageService to S3 format."""
@@ -957,8 +956,7 @@ class CloudController(object):
try:
image = self._get_image(context, ec2_id)
except exception.NotFound:
raise exception.NotFound(_('Image %s not found') %
ec2_id)
raise exception.ImageNotFound(image_id=ec2_id)
images.append(image)
else:
images = self.image_service.detail(context)
@@ -992,7 +990,7 @@ class CloudController(object):
try:
image = self._get_image(context, image_id)
except exception.NotFound:
raise exception.NotFound(_('Image %s not found') % image_id)
raise exception.ImageNotFound(image_id=image_id)
result = {'imageId': image_id, 'launchPermission': []}
if image['is_public']:
result['launchPermission'].append({'group': 'all'})
@@ -1015,7 +1013,7 @@ class CloudController(object):
try:
image = self._get_image(context, image_id)
except exception.NotFound:
raise exception.NotFound(_('Image %s not found') % image_id)
raise exception.ImageNotFound(image_id=image_id)
internal_id = image['id']
del(image['id'])
+1 -4
View File
@@ -21,10 +21,7 @@ from nova import exception
def ec2_id_to_id(ec2_id):
"""Convert an ec2 ID (i-[base 16 number]) to an instance id (int)"""
try:
return int(ec2_id.split('-')[-1], 16)
except ValueError:
raise exception.NotFound(_("Id %s Not Found") % ec2_id)
return int(ec2_id.split('-')[-1], 16)
def id_to_ec2_id(instance_id, template='i-%08x'):
+1 -1
View File
@@ -124,7 +124,7 @@ def get_image_id_from_image_hash(image_service, context, image_hash):
"should have numerical format") % image_id
LOG.error(msg)
raise Exception(msg)
raise exception.NotFound(image_hash)
raise exception.ImageNotFound(image_id=image_hash)
def get_id_from_href(href):
+2 -4
View File
@@ -573,14 +573,12 @@ class Controller(common.OpenstackController):
try:
kernel_id = image_meta['properties']['kernel_id']
except KeyError:
raise exception.NotFound(
_("Kernel not found for image %(image_id)s") % locals())
raise exception.KernelNotFoundForImage(image_id=image_id)
try:
ramdisk_id = image_meta['properties']['ramdisk_id']
except KeyError:
raise exception.NotFound(
_("Ramdisk not found for image %(image_id)s") % locals())
raise exception.RamdiskNotFoundForImage(image_id=image_id)
return kernel_id, ramdisk_id
+7 -14
View File
@@ -81,7 +81,7 @@ class DbDriver(object):
user_ref = db.user_create(context.get_admin_context(), values)
return self._db_user_to_auth_user(user_ref)
except exception.Duplicate, e:
raise exception.Duplicate(_('User %s already exists') % name)
raise exception.UserExists(user=name)
def _db_user_to_auth_user(self, user_ref):
return {'id': user_ref['id'],
@@ -103,9 +103,7 @@ class DbDriver(object):
"""Create a project"""
manager = db.user_get(context.get_admin_context(), manager_uid)
if not manager:
raise exception.NotFound(_("Project can't be created because "
"manager %s doesn't exist")
% manager_uid)
raise exception.UserNotFound(user_id=manager_uid)
# description is a required attribute
if description is None:
@@ -119,9 +117,7 @@ class DbDriver(object):
for member_uid in member_uids:
member = db.user_get(context.get_admin_context(), member_uid)
if not member:
raise exception.NotFound(_("Project can't be created "
"because user %s doesn't exist")
% member_uid)
raise exception.UserNotFound(user_id=member_uid)
members.add(member)
values = {'id': name,
@@ -132,8 +128,7 @@ class DbDriver(object):
try:
project = db.project_create(context.get_admin_context(), values)
except exception.Duplicate:
raise exception.Duplicate(_("Project can't be created because "
"project %s already exists") % name)
raise exception.ProjectExists(project=name)
for member in members:
db.project_add_member(context.get_admin_context(),
@@ -154,9 +149,7 @@ class DbDriver(object):
if manager_uid:
manager = db.user_get(context.get_admin_context(), manager_uid)
if not manager:
raise exception.NotFound(_("Project can't be modified because "
"manager %s doesn't exist") %
manager_uid)
raise exception.UserNotFound(user_id=manager_uid)
values['project_manager'] = manager['id']
if description:
values['description'] = description
@@ -244,8 +237,8 @@ class DbDriver(object):
def _validate_user_and_project(self, user_id, project_id):
user = db.user_get(context.get_admin_context(), user_id)
if not user:
raise exception.NotFound(_('User "%s" not found') % user_id)
raise exception.UserNotFound(user_id=user_id)
project = db.project_get(context.get_admin_context(), project_id)
if not project:
raise exception.NotFound(_('Project "%s" not found') % project_id)
raise exception.ProjectNotFound(project_id=project_id)
return user, project
+19 -40
View File
@@ -171,7 +171,7 @@ class LdapDriver(object):
def create_user(self, name, access_key, secret_key, is_admin):
"""Create a user"""
if self.__user_exists(name):
raise exception.Duplicate(_("LDAP user %s already exists") % name)
raise exception.LDAPUserExists(user=name)
if FLAGS.ldap_user_modify_only:
if self.__ldap_user_exists(name):
# Retrieve user by name
@@ -202,8 +202,7 @@ class LdapDriver(object):
self.conn.modify_s(self.__uid_to_dn(name), attr)
return self.get_user(name)
else:
raise exception.NotFound(_("LDAP object for %s doesn't exist")
% name)
raise exception.LDAPUserNotFound(user_id=name)
else:
attr = [
('objectclass', ['person',
@@ -226,12 +225,9 @@ class LdapDriver(object):
description=None, member_uids=None):
"""Create a project"""
if self.__project_exists(name):
raise exception.Duplicate(_("Project can't be created because "
"project %s already exists") % name)
raise exception.ProjectExists(project=name)
if not self.__user_exists(manager_uid):
raise exception.NotFound(_("Project can't be created because "
"manager %s doesn't exist")
% manager_uid)
raise exception.LDAPUserNotFound(user_id=manager_uid)
manager_dn = self.__uid_to_dn(manager_uid)
# description is a required attribute
if description is None:
@@ -240,9 +236,7 @@ class LdapDriver(object):
if member_uids is not None:
for member_uid in member_uids:
if not self.__user_exists(member_uid):
raise exception.NotFound(_("Project can't be created "
"because user %s doesn't exist")
% member_uid)
raise exception.LDAPUserNotFound(user_id=member_uid)
members.append(self.__uid_to_dn(member_uid))
# always add the manager as a member because members is required
if not manager_dn in members:
@@ -265,9 +259,7 @@ class LdapDriver(object):
attr = []
if manager_uid:
if not self.__user_exists(manager_uid):
raise exception.NotFound(_("Project can't be modified because "
"manager %s doesn't exist")
% manager_uid)
raise exception.LDAPUserNotFound(user_id=manager_uid)
manager_dn = self.__uid_to_dn(manager_uid)
attr.append((self.ldap.MOD_REPLACE, LdapDriver.project_attribute,
manager_dn))
@@ -347,7 +339,7 @@ class LdapDriver(object):
def delete_user(self, uid):
"""Delete a user"""
if not self.__user_exists(uid):
raise exception.NotFound(_("User %s doesn't exist") % uid)
raise exception.LDAPUserNotFound(user_id=uid)
self.__remove_from_all(uid)
if FLAGS.ldap_user_modify_only:
# Delete attributes
@@ -471,15 +463,12 @@ class LdapDriver(object):
description, member_uids=None):
"""Create a group"""
if self.__group_exists(group_dn):
raise exception.Duplicate(_("Group can't be created because "
"group %s already exists") % name)
raise exception.LDAPGroupExists(group=name)
members = []
if member_uids is not None:
for member_uid in member_uids:
if not self.__user_exists(member_uid):
raise exception.NotFound(_("Group can't be created "
"because user %s doesn't exist")
% member_uid)
raise exception.LDAPUserNotFound(user_id=member_uid)
members.append(self.__uid_to_dn(member_uid))
dn = self.__uid_to_dn(uid)
if not dn in members:
@@ -494,8 +483,7 @@ class LdapDriver(object):
def __is_in_group(self, uid, group_dn):
"""Check if user is in group"""
if not self.__user_exists(uid):
raise exception.NotFound(_("User %s can't be searched in group "
"because the user doesn't exist") % uid)
raise exception.LDAPUserNotFound(user_id=uid)
if not self.__group_exists(group_dn):
return False
res = self.__find_object(group_dn,
@@ -506,29 +494,23 @@ class LdapDriver(object):
def __add_to_group(self, uid, group_dn):
"""Add user to group"""
if not self.__user_exists(uid):
raise exception.NotFound(_("User %s can't be added to the group "
"because the user doesn't exist") % uid)
raise exception.LDAPUserNotFound(user_id=uid)
if not self.__group_exists(group_dn):
raise exception.NotFound(_("The group at dn %s doesn't exist") %
group_dn)
raise exception.LDAPGroupNotFound(group_id=group_dn)
if self.__is_in_group(uid, group_dn):
raise exception.Duplicate(_("User %(uid)s is already a member of "
"the group %(group_dn)s") % locals())
raise exception.LDAPMembershipExists(uid=uid, group_dn=group_dn)
attr = [(self.ldap.MOD_ADD, 'member', self.__uid_to_dn(uid))]
self.conn.modify_s(group_dn, attr)
def __remove_from_group(self, uid, group_dn):
"""Remove user from group"""
if not self.__group_exists(group_dn):
raise exception.NotFound(_("The group at dn %s doesn't exist")
% group_dn)
raise exception.LDAPGroupNotFound(group_id=group_dn)
if not self.__user_exists(uid):
raise exception.NotFound(_("User %s can't be removed from the "
"group because the user doesn't exist")
% uid)
raise exception.LDAPUserNotFound(user_id=uid)
if not self.__is_in_group(uid, group_dn):
raise exception.NotFound(_("User %s is not a member of the group")
% uid)
raise exception.LDAPGroupMembershipNotFound(user_id=uid,
group_id=group_dn)
# NOTE(vish): remove user from group and any sub_groups
sub_dns = self.__find_group_dns_with_member(group_dn, uid)
for sub_dn in sub_dns:
@@ -548,9 +530,7 @@ class LdapDriver(object):
def __remove_from_all(self, uid):
"""Remove user from all roles and projects"""
if not self.__user_exists(uid):
raise exception.NotFound(_("User %s can't be removed from all "
"because the user doesn't exist")
% uid)
raise exception.LDAPUserNotFound(user_id=uid)
role_dns = self.__find_group_dns_with_member(
FLAGS.role_project_subtree, uid)
for role_dn in role_dns:
@@ -563,8 +543,7 @@ class LdapDriver(object):
def __delete_group(self, group_dn):
"""Delete Group"""
if not self.__group_exists(group_dn):
raise exception.NotFound(_("Group at dn %s doesn't exist")
% group_dn)
raise exception.LDAPGroupNotFound(group_id=group_dn)
self.conn.delete_s(group_dn)
def __delete_roles(self, project_dn):
+6 -8
View File
@@ -270,8 +270,7 @@ class AuthManager(object):
LOG.debug('user: %r', user)
if user is None:
LOG.audit(_("Failed authorization for access key %s"), access_key)
raise exception.NotFound(_('No user found for access key %s')
% access_key)
raise exception.AccessKeyNotFound(access_key=access_key)
# NOTE(vish): if we stop using project name as id we need better
# logic to find a default project for user
@@ -285,8 +284,7 @@ class AuthManager(object):
uname = user.name
LOG.audit(_("failed authorization: no project named %(pjid)s"
" (user=%(uname)s)") % locals())
raise exception.NotFound(_('No project called %s could be found')
% project_id)
raise exception.ProjectNotFound(project_id=project_id)
if not self.is_admin(user) and not self.is_project_member(user,
project):
uname = user.name
@@ -295,8 +293,8 @@ class AuthManager(object):
pjid = project.id
LOG.audit(_("Failed authorization: user %(uname)s not admin"
" and not member of project %(pjname)s") % locals())
raise exception.NotFound(_('User %(uid)s is not a member of'
' project %(pjid)s') % locals())
raise exception.ProjectMembershipNotFound(project_id=pjid,
user_id=uid)
if check_type == 's3':
sign = signer.Signer(user.secret.encode())
expected_signature = sign.s3_authorization(headers, verb, path)
@@ -430,9 +428,9 @@ class AuthManager(object):
@param project: Project in which to add local role.
"""
if role not in FLAGS.allowed_roles:
raise exception.NotFound(_("The %s role can not be found") % role)
raise exception.UserRoleNotFound(role_id=role)
if project is not None and role in FLAGS.global_roles:
raise exception.NotFound(_("The %s role is global only") % role)
raise exception.GlobalRoleNotAllowed(role_id=role)
uid = User.safe_id(user)
pid = Project.safe_id(project)
if project:
+4 -4
View File
@@ -507,8 +507,8 @@ class API(base.Base):
migration_ref = self.db.migration_get_by_instance_and_status(context,
instance_id, 'finished')
if not migration_ref:
raise exception.NotFound(_("No finished migrations found for "
"instance"))
raise exception.MigrationNotFoundByStatus(instance_id=instance_id,
status='finished')
params = {'migration_id': migration_ref['id']}
self._cast_compute_message('revert_resize', context, instance_id,
@@ -522,8 +522,8 @@ class API(base.Base):
migration_ref = self.db.migration_get_by_instance_and_status(context,
instance_id, 'finished')
if not migration_ref:
raise exception.NotFound(_("No finished migrations found for "
"instance"))
raise exception.MigrationNotFoundByStatus(instance_id=instance_id,
status='finished')
instance_ref = self.db.instance_get(context, instance_id)
params = {'migration_id': migration_ref['id']}
self._cast_compute_message('confirm_resize', context, instance_id,
+2 -3
View File
@@ -829,7 +829,7 @@ class ComputeManager(manager.SchedulerDependentManager):
"""
tmp_file = os.path.join(FLAGS.instances_path, filename)
if not os.path.exists(tmp_file):
raise exception.NotFound(_('%s not found') % tmp_file)
raise exception.FileNotFound(file_path=tmp_file)
@exception.wrap_exception
def cleanup_shared_storage_test_file(self, context, filename):
@@ -869,8 +869,7 @@ class ComputeManager(manager.SchedulerDependentManager):
# Getting fixed ips
fixed_ip = self.db.instance_get_fixed_address(context, instance_id)
if not fixed_ip:
msg = _("%(instance_id)s(%(ec2_id)s) does not have fixed_ip.")
raise exception.NotFound(msg % locals())
raise exception.NoFixedIpsFoundForInstance(instance_id=instance_id)
# If any volume is mounted, prepare here.
if not instance_ref['volumes']:
+2 -4
View File
@@ -90,8 +90,7 @@ class VMRCConsole(object):
vm_ds_path_name = ds_path_name
break
if vm_ref is None:
raise exception.NotFound(_('instance - %s not present') %
instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
json_data = json.dumps({'vm_id': vm_ds_path_name,
'username': username,
'password': password})
@@ -125,8 +124,7 @@ class VMRCSessionConsole(VMRCConsole):
if vm.propSet[0].val == instance_name:
vm_ref = vm.obj
if vm_ref is None:
raise exception.NotFound(_('instance - %s not present') %
instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
virtual_machine_ticket = \
vim_session._call_method(
vim_session._get_vim(),
+64 -75
View File
@@ -137,7 +137,7 @@ def service_get(context, service_id, session=None):
first()
if not result:
raise exception.NotFound(_('No service for id %s') % service_id)
raise exception.ServiceNotFound(service_id=service_id)
return result
@@ -196,8 +196,7 @@ def service_get_all_compute_by_host(context, host):
all()
if not result:
raise exception.NotFound(_("%s does not exist or is not "
"a compute node.") % host)
raise exception.ComputeHostNotFound(host=host)
return result
@@ -284,8 +283,7 @@ def service_get_by_args(context, host, binary):
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No service for %(host)s, %(binary)s')
% locals())
raise exception.HostBinaryNotFound(host=host, binary=binary)
return result
@@ -323,7 +321,7 @@ def compute_node_get(context, compute_id, session=None):
first()
if not result:
raise exception.NotFound(_('No computeNode for id %s') % compute_id)
raise exception.ComputeHostNotFound(host=compute_id)
return result
@@ -359,7 +357,7 @@ def certificate_get(context, certificate_id, session=None):
first()
if not result:
raise exception.NotFound('No certificate for id %s' % certificate_id)
raise exception.CertificateNotFound(certificate_id=certificate_id)
return result
@@ -578,7 +576,7 @@ def floating_ip_get_by_address(context, address, session=None):
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound('No floating ip for address %s' % address)
raise exception.FloatingIpNotFound(fixed_ip=address)
return result
@@ -686,7 +684,7 @@ def fixed_ip_get_all(context, session=None):
session = get_session()
result = session.query(models.FixedIp).all()
if not result:
raise exception.NotFound(_('No fixed ips defined'))
raise exception.NoFloatingIpsDefined()
return result
@@ -702,7 +700,7 @@ def fixed_ip_get_all_by_host(context, host=None):
all()
if not result:
raise exception.NotFound(_('No fixed ips for this host defined'))
raise exception.NoFloatingIpsDefinedForHost(host=host)
return result
@@ -718,7 +716,7 @@ def fixed_ip_get_by_address(context, address, session=None):
options(joinedload('instance')).\
first()
if not result:
raise exception.NotFound(_('No floating ip for address %s') % address)
raise exception.FloatingIpNotFound(fixed_ip=address)
if is_user_context(context):
authorize_project_context(context, result.instance.project_id)
@@ -739,7 +737,7 @@ def fixed_ip_get_all_by_instance(context, instance_id):
filter_by(instance_id=instance_id).\
filter_by(deleted=False)
if not rv:
raise exception.NotFound(_('No address for instance %s') % instance_id)
raise exception.NoFloatingIpsFoundForInstance(instance_id=instance_id)
return rv
@@ -818,17 +816,17 @@ def instance_destroy(context, instance_id):
with session.begin():
session.query(models.Instance).\
filter_by(id=instance_id).\
update({'deleted': 1,
update({'deleted': True,
'deleted_at': datetime.datetime.utcnow(),
'updated_at': literal_column('updated_at')})
session.query(models.SecurityGroupInstanceAssociation).\
filter_by(instance_id=instance_id).\
update({'deleted': 1,
update({'deleted': True,
'deleted_at': datetime.datetime.utcnow(),
'updated_at': literal_column('updated_at')})
session.query(models.InstanceMetadata).\
filter_by(instance_id=instance_id).\
update({'deleted': 1,
update({'deleted': True,
'deleted_at': datetime.datetime.utcnow(),
'updated_at': literal_column('updated_at')})
@@ -862,9 +860,7 @@ def instance_get(context, instance_id, session=None):
filter_by(deleted=False).\
first()
if not result:
raise exception.InstanceNotFound(_('Instance %s not found')
% instance_id,
instance_id)
raise exception.InstanceNotFound(instance_id=instance_id)
return result
@@ -1133,8 +1129,7 @@ def key_pair_get(context, user_id, name, session=None):
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('no keypair for user %(user_id)s,'
' name %(name)s') % locals())
raise exception.KeypairNotFound(user_id=user_id, name=name)
return result
@@ -1260,7 +1255,7 @@ def network_get(context, network_id, session=None):
filter_by(deleted=False).\
first()
if not result:
raise exception.NotFound(_('No network for id %s') % network_id)
raise exception.NetworkNotFound(network_id=network_id)
return result
@@ -1270,7 +1265,7 @@ def network_get_all(context):
session = get_session()
result = session.query(models.Network)
if not result:
raise exception.NotFound(_('No networks defined'))
raise exception.NoNetworksFound()
return result
@@ -1299,7 +1294,7 @@ def network_get_by_bridge(context, bridge):
first()
if not result:
raise exception.NotFound(_('No network for bridge %s') % bridge)
raise exception.NetworkNotFoundForBridge(bridge=bridge)
return result
@@ -1310,8 +1305,7 @@ def network_get_by_cidr(context, cidr):
filter_by(cidr=cidr).first()
if not result:
raise exception.NotFound(_('Network with cidr %s does not exist') %
cidr)
raise exception.NetworkNotFoundForCidr(cidr=cidr)
return result
@@ -1325,7 +1319,7 @@ def network_get_by_instance(_context, instance_id):
filter_by(deleted=False).\
first()
if not rv:
raise exception.NotFound(_('No network for instance %s') % instance_id)
raise exception.NetworkNotFoundForInstance(instance_id=instance_id)
return rv
@@ -1338,7 +1332,7 @@ def network_get_all_by_instance(_context, instance_id):
filter_by(instance_id=instance_id).\
filter_by(deleted=False)
if not rv:
raise exception.NotFound(_('No network for instance %s') % instance_id)
raise exception.NetworkNotFoundForInstance(instance_id=instance_id)
return rv
@@ -1352,7 +1346,7 @@ def network_set_host(context, network_id, host_id):
with_lockmode('update').\
first()
if not network_ref:
raise exception.NotFound(_('No network for id %s') % network_id)
raise exception.NetworkNotFound(network_id=network_id)
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
@@ -1477,7 +1471,7 @@ def auth_token_get(context, token_hash, session=None):
filter_by(deleted=can_read_deleted(context)).\
first()
if not tk:
raise exception.NotFound(_('Token %s does not exist') % token_hash)
raise exception.AuthTokenNotFound(token=token_hash)
return tk
@@ -1511,7 +1505,7 @@ def quota_get(context, project_id, session=None):
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No quota for project_id %s') % project_id)
raise exception.ProjectQuotaNotFound(project_id=project_id)
return result
@@ -1666,8 +1660,7 @@ def volume_get(context, volume_id, session=None):
filter_by(deleted=False).\
first()
if not result:
raise exception.VolumeNotFound(_('Volume %s not found') % volume_id,
volume_id)
raise exception.VolumeNotFound(volume_id=volume_id)
return result
@@ -1699,7 +1692,7 @@ def volume_get_all_by_instance(context, instance_id):
filter_by(deleted=False).\
all()
if not result:
raise exception.NotFound(_('No volume for instance %s') % instance_id)
raise exception.VolumeNotFoundForInstance(instance_id=instance_id)
return result
@@ -1724,8 +1717,7 @@ def volume_get_instance(context, volume_id):
options(joinedload('instance')).\
first()
if not result:
raise exception.VolumeNotFound(_('Volume %s not found') % volume_id,
volume_id)
raise exception.VolumeNotFound(volume_id=volume_id)
return result.instance
@@ -1737,8 +1729,7 @@ def volume_get_shelf_and_blade(context, volume_id):
filter_by(volume_id=volume_id).\
first()
if not result:
raise exception.NotFound(_('No export device found for volume %s') %
volume_id)
raise exception.ExportDeviceNotFoundForVolume(volume_id=volume_id)
return (result.shelf_id, result.blade_id)
@@ -1750,8 +1741,7 @@ def volume_get_iscsi_target_num(context, volume_id):
filter_by(volume_id=volume_id).\
first()
if not result:
raise exception.NotFound(_('No target id found for volume %s') %
volume_id)
raise exception.ISCSITargetNotFoundForVolume(volume_id=volume_id)
return result.target_num
@@ -1795,8 +1785,8 @@ def security_group_get(context, security_group_id, session=None):
options(joinedload_all('rules')).\
first()
if not result:
raise exception.NotFound(_("No security group with id %s") %
security_group_id)
raise exception.SecurityGroupNotFound(
security_group_id=security_group_id)
return result
@@ -1811,9 +1801,8 @@ def security_group_get_by_name(context, project_id, group_name):
options(joinedload_all('instances')).\
first()
if not result:
raise exception.NotFound(
_('No security group named %(group_name)s'
' for project: %(project_id)s') % locals())
raise exception.SecurityGroupNotFoundForProject(project_id=project_id,
security_group_id=group_name)
return result
@@ -1914,8 +1903,8 @@ def security_group_rule_get(context, security_group_rule_id, session=None):
filter_by(id=security_group_rule_id).\
first()
if not result:
raise exception.NotFound(_("No secuity group rule with id %s") %
security_group_rule_id)
raise exception.SecurityGroupNotFoundForRule(
rule_id=security_group_rule_id)
return result
@@ -1988,7 +1977,7 @@ def user_get(context, id, session=None):
first()
if not result:
raise exception.NotFound(_('No user for id %s') % id)
raise exception.UserNotFound(user_id=id)
return result
@@ -2004,7 +1993,7 @@ def user_get_by_access_key(context, access_key, session=None):
first()
if not result:
raise exception.NotFound(_('No user for access key %s') % access_key)
raise exception.AccessKeyNotFound(access_key=access_key)
return result
@@ -2069,7 +2058,7 @@ def project_get(context, id, session=None):
first()
if not result:
raise exception.NotFound(_("No project with id %s") % id)
raise exception.ProjectNotFound(project_id=id)
return result
@@ -2090,7 +2079,7 @@ def project_get_by_user(context, user_id):
options(joinedload_all('projects')).\
first()
if not user:
raise exception.NotFound(_('Invalid user_id %s') % user_id)
raise exception.UserNotFound(user_id=user_id)
return user.projects
@@ -2230,8 +2219,7 @@ def migration_get(context, id, session=None):
result = session.query(models.Migration).\
filter_by(id=id).first()
if not result:
raise exception.NotFound(_("No migration found with id %s")
% id)
raise exception.MigrationNotFound(migration_id=id)
return result
@@ -2242,8 +2230,8 @@ def migration_get_by_instance_and_status(context, instance_id, status):
filter_by(instance_id=instance_id).\
filter_by(status=status).first()
if not result:
raise exception.NotFound(_("No migration found for instance "
"%(instance_id)s with status %(status)s") % locals())
raise exception.MigrationNotFoundByStatus(instance_id=instance_id,
status=status)
return result
@@ -2264,8 +2252,7 @@ def console_pool_get(context, pool_id):
filter_by(id=pool_id).\
first()
if not result:
raise exception.NotFound(_("No console pool with id %(pool_id)s")
% locals())
raise exception.ConsolePoolNotFound(pool_id=pool_id)
return result
@@ -2281,9 +2268,9 @@ def console_pool_get_by_host_type(context, compute_host, host,
options(joinedload('consoles')).\
first()
if not result:
raise exception.NotFound(_('No console pool of type %(console_type)s '
'for compute host %(compute_host)s '
'on proxy host %(host)s') % locals())
raise exception.ConsolePoolNotFoundForHostType(host=host,
console_type=console_type,
compute_host=compute_host)
return result
@@ -2321,8 +2308,8 @@ def console_get_by_pool_instance(context, pool_id, instance_id):
options(joinedload('pool')).\
first()
if not result:
raise exception.NotFound(_('No console for instance %(instance_id)s '
'in pool %(pool_id)s') % locals())
raise exception.ConsoleNotFoundInPoolForInstance(pool_id=pool_id,
instance_id=instance_id)
return result
@@ -2343,9 +2330,11 @@ def console_get(context, console_id, instance_id=None):
query = query.filter_by(instance_id=instance_id)
result = query.options(joinedload('pool')).first()
if not result:
idesc = (_("on instance %s") % instance_id) if instance_id else ""
raise exception.NotFound(_("No console with id %(console_id)s"
" %(idesc)s") % locals())
if instance_id:
raise exception.ConsoleNotFoundForInstance(console_id=console_id,
instance_id=instance_id)
else:
raise exception.ConsoleNotFound(console_id=console_id)
return result
@@ -2384,7 +2373,7 @@ def instance_type_get_all(context, inactive=False):
inst_dict[i['name']] = dict(i)
return inst_dict
else:
raise exception.NotFound
raise exception.NoInstanceTypesFound()
@require_context
@@ -2395,7 +2384,7 @@ def instance_type_get_by_id(context, id):
filter_by(id=id).\
first()
if not inst_type:
raise exception.NotFound(_("No instance type with id %s") % id)
raise exception.InstanceTypeNotFound(instance_type=id)
else:
return dict(inst_type)
@@ -2408,7 +2397,7 @@ def instance_type_get_by_name(context, name):
filter_by(name=name).\
first()
if not inst_type:
raise exception.NotFound(_("No instance type with name %s") % name)
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
else:
return dict(inst_type)
@@ -2421,7 +2410,7 @@ def instance_type_get_by_flavor_id(context, id):
filter_by(flavorid=int(id)).\
first()
if not inst_type:
raise exception.NotFound(_("No flavor with flavorid %s") % id)
raise exception.FlavorNotFound(flavor_id=id)
else:
return dict(inst_type)
@@ -2434,7 +2423,7 @@ def instance_type_destroy(context, name):
filter_by(name=name)
records = instance_type_ref.update(dict(deleted=True))
if records == 0:
raise exception.NotFound
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
else:
return instance_type_ref
@@ -2449,7 +2438,7 @@ def instance_type_purge(context, name):
filter_by(name=name)
records = instance_type_ref.delete()
if records == 0:
raise exception.NotFound
raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
else:
return instance_type_ref
@@ -2470,7 +2459,7 @@ def zone_update(context, zone_id, values):
session = get_session()
zone = session.query(models.Zone).filter_by(id=zone_id).first()
if not zone:
raise exception.NotFound(_("No zone with id %(zone_id)s") % locals())
raise exception.ZoneNotFound(zone_id=zone_id)
zone.update(values)
zone.save()
return zone
@@ -2490,7 +2479,7 @@ def zone_get(context, zone_id):
session = get_session()
result = session.query(models.Zone).filter_by(id=zone_id).first()
if not result:
raise exception.NotFound(_("No zone with id %(zone_id)s") % locals())
raise exception.ZoneNotFound(zone_id=zone_id)
return result
@@ -2524,7 +2513,7 @@ def instance_metadata_delete(context, instance_id, key):
filter_by(instance_id=instance_id).\
filter_by(key=key).\
filter_by(deleted=False).\
update({'deleted': 1,
update({'deleted': True,
'deleted_at': datetime.datetime.utcnow(),
'updated_at': literal_column('updated_at')})
@@ -2540,8 +2529,8 @@ def instance_metadata_get_item(context, instance_id, key):
first()
if not meta_result:
raise exception.NotFound(_('Invalid metadata key for instance %s') %
instance_id)
raise exception.InstanceMetadataNotFound(metadata_key=key,
instance_id=instance_id)
return meta_result
+309 -4
View File
@@ -71,10 +71,6 @@ class VolumeNotFound(NotFound):
super(VolumeNotFound, self).__init__(message)
class Duplicate(Error):
pass
class NotAuthorized(Error):
pass
@@ -163,6 +159,10 @@ class InstanceNotSuspended(Invalid):
message = _("Instance %(instance_id)s is not suspended.")
class InstanceNotInRescueMode(Invalid):
message = _("Instance %(instance_id)s is not in rescue mode")
class InstanceSuspendFailure(Invalid):
message = _("Failed to suspend instance") + ": %(reason)s"
@@ -226,5 +226,310 @@ class InvalidVLANPortGroup(Invalid):
"is %(actual)s.")
class InvalidDiskFormat(Invalid):
message = _("Disk format %(disk_format)s is not acceptable")
class ImageUnacceptable(Invalid):
message = _("Image %(image_id)s is unacceptable") + ": %(reason)s"
class InstanceUnacceptable(Invalid):
message = _("Instance %(instance_id)s is unacceptable") + ": %(reason)s"
class NotFound(NovaException):
message = _("Resource could not be found.")
def __init__(self, *args, **kwargs):
super(NotFound, self).__init__(**kwargs)
class InstanceNotFound(NotFound):
message = _("Instance %(instance_id)s could not be found.")
class VolumeNotFound(NotFound):
message = _("Volume %(volume_id)s could not be found.")
class VolumeNotFoundForInstance(VolumeNotFound):
message = _("Volume not found for instance %(instance_id)s.")
class ExportDeviceNotFoundForVolume(NotFound):
message = _("No export device found for volume %(volume_id)s.")
class ISCSITargetNotFoundForVolume(NotFound):
message = _("No target id found for volume %(volume_id)s.")
class DiskNotFound(NotFound):
message = _("No disk at %(location)s")
class ImageNotFound(NotFound):
message = _("Image %(image_id)s could not be found.")
class KernelNotFoundForImage(ImageNotFound):
message = _("Kernel not found for image %(image_id)s.")
class RamdiskNotFoundForImage(ImageNotFound):
message = _("Ramdisk not found for image %(image_id)s.")
class UserNotFound(NotFound):
message = _("User %(user_id)s could not be found.")
class ProjectNotFound(NotFound):
message = _("Project %(project_id)s could not be found.")
class ProjectMembershipNotFound(NotFound):
message = _("User %(user_id)s is not a member of project %(project_id)s.")
class UserRoleNotFound(NotFound):
message = _("Role %(role_id)s could not be found.")
class StorageRepositoryNotFound(NotFound):
message = _("Cannot find SR to read/write VDI.")
class NetworkNotFound(NotFound):
message = _("Network %(network_id)s could not be found.")
class NetworkNotFoundForBridge(NetworkNotFound):
message = _("Network could not be found for bridge %(bridge)s")
class NetworkNotFoundForCidr(NetworkNotFound):
message = _("Network could not be found with cidr %(cidr)s.")
class NetworkNotFoundForInstance(NetworkNotFound):
message = _("Network could not be found for instance %(instance_id)s.")
class NoNetworksFound(NotFound):
message = _("No networks defined.")
class DatastoreNotFound(NotFound):
message = _("Could not find the datastore reference(s) which the VM uses.")
class NoFixedIpsFoundForInstance(NotFound):
message = _("Instance %(instance_id)s has zero fixed ips.")
class FloatingIpNotFound(NotFound):
message = _("Floating ip not found for fixed address %(fixed_ip)s.")
class NoFloatingIpsDefined(NotFound):
message = _("Zero floating ips could be found.")
class NoFloatingIpsDefinedForHost(NoFloatingIpsDefined):
message = _("Zero floating ips defined for host %(host)s.")
class NoFloatingIpsDefinedForInstance(NoFloatingIpsDefined):
message = _("Zero floating ips defined for instance %(instance_id)s.")
class KeypairNotFound(NotFound):
message = _("Keypair %(keypair_name)s not found for user %(user_id)s")
class CertificateNotFound(NotFound):
message = _("Certificate %(certificate_id)s not found.")
class ServiceNotFound(NotFound):
message = _("Service %(service_id)s could not be found.")
class HostNotFound(NotFound):
message = _("Host %(host)s could not be found.")
class ComputeHostNotFound(HostNotFound):
message = _("Compute host %(host)s could not be found.")
class HostBinaryNotFound(NotFound):
message = _("Could not find binary %(binary)s on host %(host)s.")
class AuthTokenNotFound(NotFound):
message = _("Auth token %(token)s could not be found.")
class AccessKeyNotFound(NotFound):
message = _("Access Key %(access_key)s could not be found.")
class QuotaNotFound(NotFound):
message = _("Quota could not be found")
class ProjectQuotaNotFound(QuotaNotFound):
message = _("Quota for project %(project_id)s could not be found.")
class SecurityGroupNotFound(NotFound):
message = _("Security group %(security_group_id)s not found.")
class SecurityGroupNotFoundForProject(SecurityGroupNotFound):
message = _("Security group %(security_group_id)s not found "
"for project %(project_id)s.")
class SecurityGroupNotFoundForRule(SecurityGroupNotFound):
message = _("Security group with rule %(rule_id)s not found.")
class MigrationNotFound(NotFound):
message = _("Migration %(migration_id)s could not be found.")
class MigrationNotFoundByStatus(MigrationNotFound):
message = _("Migration not found for instance %(instance_id)s "
"with status %(status)s.")
class ConsolePoolNotFound(NotFound):
message = _("Console pool %(pool_id)s could not be found.")
class ConsolePoolNotFoundForHostType(NotFound):
message = _("Console pool of type %(console_type)s "
"for compute host %(compute_host)s "
"on proxy host %(host)s not found.")
class ConsoleNotFound(NotFound):
message = _("Console %(console_id)s could not be found.")
class ConsoleNotFoundForInstance(ConsoleNotFound):
message = _("Console for instance %(instance_id)s could not be found.")
class ConsoleNotFoundInPoolForInstance(ConsoleNotFound):
message = _("Console for instance %(instance_id)s "
"in pool %(pool_id)s could not be found.")
class NoInstanceTypesFound(NotFound):
message = _("Zero instance types found.")
class InstanceTypeNotFound(NotFound):
message = _("Instance type %(instance_type_id)s could not be found.")
class InstanceTypeNotFoundByName(InstanceTypeNotFound):
message = _("Instance type with name %(instance_type_name)s "
"could not be found.")
class FlavorNotFound(NotFound):
message = _("Flavor %(flavor_id)s could not be found.")
class ZoneNotFound(NotFound):
message = _("Zone %(zone_id)s could not be found.")
class InstanceMetadataNotFound(NotFound):
message = _("Instance %(instance_id)s has no metadata with "
"key %(metadata_key)s.")
class LDAPObjectNotFound(NotFound):
message = _("LDAP object could not be found")
class LDAPUserNotFound(LDAPObjectNotFound):
message = _("LDAP user %(user_id)s could not be found.")
class LDAPGroupNotFound(LDAPObjectNotFound):
message = _("LDAP group %(group_id)s could not be found.")
class LDAPGroupMembershipNotFound(NotFound):
message = _("LDAP user %(user_id)s is not a member of group %(group_id)s.")
class FileNotFound(NotFound):
message = _("File %(file_path)s could not be found.")
class NoFilesFound(NotFound):
message = _("Zero files could be found.")
class SwitchNotFoundForNetworkAdapter(NotFound):
message = _("Virtual switch associated with the "
"network adapter %(adapter)s not found.")
class NetworkAdapterNotFound(NotFound):
message = _("Network adapter %(adapter)s could not be found.")
class ClassNotFound(NotFound):
message = _("Class %(class_name)s could not be found")
class NotAllowed(NovaException):
message = _("Action not allowed.")
class GlobalRoleNotAllowed(NotAllowed):
message = _("Unable to use global role %(role_id)s")
#TODO(bcwaldon): EOL this exception!
class Duplicate(NovaException):
pass
class KeyPairExists(Duplicate):
message = _("Key pair %(key_name)s already exists.")
class UserExists(Duplicate):
message = _("User %(user)s already exists.")
class LDAPUserExists(UserExists):
message = _("LDAP user %(user)s already exists.")
class LDAPGroupExists(Duplicate):
message = _("LDAP group %(group)s already exists.")
class LDAPMembershipExists(Duplicate):
message = _("User %(uid)s is already a member of "
"the group %(group_dn)s")
class ProjectExists(Duplicate):
message = _("Project %(project)s already exists.")
class InstanceExists(Duplicate):
message = _("Instance %(name)s already exists.")
+5 -5
View File
@@ -72,7 +72,7 @@ class FakeImageService(service.BaseImageService):
return copy.deepcopy(image)
LOG.warn('Unable to find image id %s. Have images: %s',
image_id, self.images)
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
def create(self, context, data):
"""Store the image data and return the new image id.
@@ -89,24 +89,24 @@ class FakeImageService(service.BaseImageService):
def update(self, context, image_id, data):
"""Replace the contents of the given image with the new data.
:raises: NotFound if the image does not exist.
:raises: ImageNotFound if the image does not exist.
"""
image_id = int(image_id)
if not self.images.get(image_id):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
self.images[image_id] = copy.deepcopy(data)
def delete(self, context, image_id):
"""Delete the given image.
:raises: NotFound if the image does not exist.
:raises: ImageNotFound if the image does not exist.
"""
image_id = int(image_id)
removed = self.images.pop(image_id, None)
if not removed:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
def delete_all(self):
"""Clears out all images."""
+8 -8
View File
@@ -86,10 +86,10 @@ class GlanceImageService(service.BaseImageService):
try:
image_meta = self.client.get_image_meta(image_id)
except glance_exception.NotFound:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
if not self._is_image_available(context, image_meta):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
base_image_meta = self._translate_to_base(image_meta)
return base_image_meta
@@ -102,14 +102,14 @@ class GlanceImageService(service.BaseImageService):
for image_meta in image_metas:
if name == image_meta.get('name'):
return image_meta
raise exception.NotFound
raise exception.ImageNotFound(image_id=name)
def get(self, context, image_id, data):
"""Calls out to Glance for metadata and data and writes data."""
try:
image_meta, image_chunks = self.client.get_image(image_id)
except glance_exception.NotFound:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
for chunk in image_chunks:
data.write(chunk)
@@ -142,7 +142,7 @@ class GlanceImageService(service.BaseImageService):
def update(self, context, image_id, image_meta, data=None):
"""Replace the contents of the given image with the new data.
:raises: NotFound if the image does not exist.
:raises: ImageNotFound if the image does not exist.
"""
# NOTE(vish): show is to check if image is available
@@ -150,7 +150,7 @@ class GlanceImageService(service.BaseImageService):
try:
image_meta = self.client.update_image(image_id, image_meta, data)
except glance_exception.NotFound:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
base_image_meta = self._translate_to_base(image_meta)
return base_image_meta
@@ -158,7 +158,7 @@ class GlanceImageService(service.BaseImageService):
def delete(self, context, image_id):
"""Delete the given image.
:raises: NotFound if the image does not exist.
:raises: ImageNotFound if the image does not exist.
"""
# NOTE(vish): show is to check if image is available
@@ -166,7 +166,7 @@ class GlanceImageService(service.BaseImageService):
try:
result = self.client.delete_image(image_id)
except glance_exception.NotFound:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
return result
def delete_all(self):
+7 -7
View File
@@ -86,10 +86,10 @@ class LocalImageService(service.BaseImageService):
with open(self._path_to(image_id)) as metadata_file:
image_meta = json.load(metadata_file)
if not self._is_image_available(context, image_meta):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
return image_meta
except (IOError, ValueError):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
def show_by_name(self, context, name):
"""Returns a dict containing image data for the given name."""
@@ -102,7 +102,7 @@ class LocalImageService(service.BaseImageService):
image = cantidate
break
if image is None:
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
return image
def get(self, context, image_id, data):
@@ -113,7 +113,7 @@ class LocalImageService(service.BaseImageService):
with open(self._path_to(image_id, 'image')) as image_file:
shutil.copyfileobj(image_file, data)
except (IOError, ValueError):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
return metadata
def create(self, context, metadata, data=None):
@@ -143,13 +143,13 @@ class LocalImageService(service.BaseImageService):
with open(self._path_to(image_id), 'w') as metadata_file:
json.dump(metadata, metadata_file)
except (IOError, ValueError):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
return metadata
def delete(self, context, image_id):
"""Delete the given image.
:raises: NotFound if the image does not exist.
:raises: ImageNotFound if the image does not exist.
"""
# NOTE(vish): show is to check if image is available
@@ -157,7 +157,7 @@ class LocalImageService(service.BaseImageService):
try:
shutil.rmtree(self._path_to(image_id, None))
except (IOError, ValueError):
raise exception.NotFound
raise exception.ImageNotFound(image_id=image_id)
def delete_all(self):
"""Clears out all images in local directory."""
+2 -5
View File
@@ -52,16 +52,13 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None):
# Check if the vlan_interface physical network adapter exists on the host
if not network_utils.check_if_vlan_interface_exists(session,
vlan_interface):
raise exception.NotFound(_("There is no physical network adapter with "
"the name %s on the ESX host") % vlan_interface)
raise exception.NetworkAdapterNotFound(adapter=vlan_interface)
# Get the vSwitch associated with the Physical Adapter
vswitch_associated = network_utils.get_vswitch_for_vlan_interface(
session, vlan_interface)
if vswitch_associated is None:
raise exception.NotFound(_("There is no virtual switch associated "
"with the physical network adapter with name %s") %
vlan_interface)
raise exception.SwicthNotFoundForNetworkAdapter(adapter=vlan_interface)
# Check whether bridge already exists and retrieve the the ref of the
# network whose name_label is "bridge"
network_ref = network_utils.get_network_with_the_name(session, bridge)
+2 -2
View File
@@ -47,8 +47,8 @@ def return_instance_types(context, num=2):
return instance_types
def return_instance_type_not_found(context, flavorid):
raise exception.NotFound()
def return_instance_type_not_found(context, flavor_id):
raise exception.InstanceTypeNotFound(flavor_id=flavor_id)
class FlavorsTest(test.TestCase):
+8 -12
View File
@@ -120,12 +120,11 @@ class SchedulerTestCase(test.TestCase):
dest = 'dummydest'
ctxt = context.get_admin_context()
try:
scheduler.show_host_resources(ctxt, dest)
except exception.NotFound, e:
c1 = (e.message.find(_("does not exist or is not a "
"compute node.")) >= 0)
self.assertTrue(c1)
self.assertRaises(exception.NotFound, scheduler.show_host_resources,
ctxt, dest)
#TODO(bcwaldon): reimplement this functionality
#c1 = (e.message.find(_("does not exist or is not a "
# "compute node.")) >= 0)
def _dic_is_equal(self, dic1, dic2, keys=None):
"""Compares 2 dictionary contents(Helper method)"""
@@ -941,7 +940,7 @@ class FakeRerouteCompute(api.reroute_compute):
def go_boom(self, context, instance):
raise exception.InstanceNotFound("boom message", instance)
raise exception.InstanceNotFound(instance_id=instance)
def found_instance(self, context, instance):
@@ -990,11 +989,8 @@ class ZoneRedirectTest(test.TestCase):
def test_routing_flags(self):
FLAGS.enable_zone_routing = False
decorator = FakeRerouteCompute("foo")
try:
result = decorator(go_boom)(None, None, 1)
self.assertFail(_("Should have thrown exception."))
except exception.InstanceNotFound, e:
self.assertEquals(e.message, 'boom message')
self.assertRaises(exception.InstanceNotFound, decorator(go_boom),
None, None, 1)
def test_get_collection_context_and_id(self):
decorator = api.reroute_compute("foo")
+136 -29
View File
@@ -31,9 +31,7 @@ from nova import test
from nova import utils
from nova.api.ec2 import cloud
from nova.auth import manager
from nova.compute import manager as compute_manager
from nova.compute import power_state
from nova.db.sqlalchemy import models
from nova.virt import libvirt_conn
libvirt = None
@@ -46,6 +44,22 @@ def _concurrency(wait, done, target):
done.send()
def _create_network_info(count=1):
fake = 'fake'
fake_ip = '0.0.0.0/0'
fake_ip_2 = '0.0.0.1/0'
fake_ip_3 = '0.0.0.1/0'
network = {'gateway': fake,
'gateway_v6': fake,
'bridge': fake,
'cidr': fake_ip,
'cidr_v6': fake_ip}
mapping = {'mac': fake,
'ips': [{'ip': fake_ip}, {'ip': fake_ip}],
'ip6s': [{'ip': fake_ip}, {'ip': fake_ip_2}, {'ip': fake_ip_3}]}
return [(network, mapping) for x in xrange(0, count)]
class CacheConcurrencyTestCase(test.TestCase):
def setUp(self):
super(CacheConcurrencyTestCase, self).setUp()
@@ -194,6 +208,37 @@ class LibvirtConnTestCase(test.TestCase):
return db.service_create(context.get_admin_context(), service_ref)
def test_preparing_xml_info(self):
conn = libvirt_conn.LibvirtConnection(True)
instance_ref = db.instance_create(self.context, self.test_instance)
result = conn._prepare_xml_info(instance_ref, False)
self.assertFalse(result['nics'])
result = conn._prepare_xml_info(instance_ref, False,
_create_network_info())
self.assertTrue(len(result['nics']) == 1)
result = conn._prepare_xml_info(instance_ref, False,
_create_network_info(2))
self.assertTrue(len(result['nics']) == 2)
def test_get_nic_for_xml_v4(self):
conn = libvirt_conn.LibvirtConnection(True)
network, mapping = _create_network_info()[0]
self.flags(use_ipv6=False)
params = conn._get_nic_for_xml(network, mapping)['extra_params']
self.assertTrue(params.find('PROJNETV6') == -1)
self.assertTrue(params.find('PROJMASKV6') == -1)
def test_get_nic_for_xml_v6(self):
conn = libvirt_conn.LibvirtConnection(True)
network, mapping = _create_network_info()[0]
self.flags(use_ipv6=True)
params = conn._get_nic_for_xml(network, mapping)['extra_params']
self.assertTrue(params.find('PROJNETV6') > -1)
self.assertTrue(params.find('PROJMASKV6') > -1)
def test_xml_and_uri_no_ramdisk_no_kernel(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data,
@@ -229,6 +274,22 @@ class LibvirtConnTestCase(test.TestCase):
instance_data = dict(self.test_instance)
self._check_xml_and_container(instance_data)
def test_multi_nic(self):
instance_data = dict(self.test_instance)
network_info = _create_network_info(2)
conn = libvirt_conn.LibvirtConnection(True)
instance_ref = db.instance_create(self.context, instance_data)
xml = conn.to_xml(instance_ref, False, network_info)
tree = xml_to_tree(xml)
interfaces = tree.findall("./devices/interface")
self.assertEquals(len(interfaces), 2)
parameters = interfaces[0].findall('./filterref/parameter')
self.assertEquals(interfaces[0].get('type'), 'bridge')
self.assertEquals(parameters[0].get('name'), 'IP')
self.assertEquals(parameters[0].get('value'), '0.0.0.0/0')
self.assertEquals(parameters[1].get('name'), 'DHCPSERVER')
self.assertEquals(parameters[1].get('value'), 'fake')
def _check_xml_and_container(self, instance):
user_context = context.RequestContext(project=self.project,
user=self.user)
@@ -327,19 +388,13 @@ class LibvirtConnTestCase(test.TestCase):
check = (lambda t: t.find('./os/initrd'), None)
check_list.append(check)
parameter = './devices/interface/filterref/parameter'
common_checks = [
(lambda t: t.find('.').tag, 'domain'),
(lambda t: t.find(
'./devices/interface/filterref/parameter').get('name'), 'IP'),
(lambda t: t.find(
'./devices/interface/filterref/parameter').get(
'value'), '10.11.12.13'),
(lambda t: t.findall(
'./devices/interface/filterref/parameter')[1].get(
'name'), 'DHCPSERVER'),
(lambda t: t.findall(
'./devices/interface/filterref/parameter')[1].get(
'value'), '10.0.0.1'),
(lambda t: t.find(parameter).get('name'), 'IP'),
(lambda t: t.find(parameter).get('value'), '10.11.12.13'),
(lambda t: t.findall(parameter)[1].get('name'), 'DHCPSERVER'),
(lambda t: t.findall(parameter)[1].get('value'), '10.0.0.1'),
(lambda t: t.find('./devices/serial/source').get(
'path').split('/')[1], 'console.log'),
(lambda t: t.find('./memory').text, '2097152')]
@@ -651,12 +706,15 @@ class IptablesFirewallTestCase(test.TestCase):
'# Completed on Tue Jan 18 23:47:56 2011',
]
def _create_instance_ref(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'mac_address': '56:12:12:12:12:12',
'instance_type_id': 1})
def test_static_filters(self):
instance_ref = db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'mac_address': '56:12:12:12:12:12',
'instance_type_id': 1})
instance_ref = self._create_instance_ref()
ip = '10.11.12.13'
network_ref = db.project_get_network(self.context,
@@ -767,6 +825,32 @@ class IptablesFirewallTestCase(test.TestCase):
"TCP port 80/81 acceptance rule wasn't added")
db.instance_destroy(admin_ctxt, instance_ref['id'])
def test_filters_for_instance(self):
network_info = _create_network_info()
rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info)
self.assertEquals(len(rulesv4), 2)
self.assertEquals(len(rulesv6), 3)
def multinic_iptables_test(self):
ipv4_rules_per_network = 2
ipv6_rules_per_network = 3
networks_count = 5
instance_ref = self._create_instance_ref()
network_info = _create_network_info(networks_count)
ipv4_len = len(self.fw.iptables.ipv4['filter'].rules)
ipv6_len = len(self.fw.iptables.ipv6['filter'].rules)
inst_ipv4, inst_ipv6 = self.fw.instance_rules(instance_ref,
network_info)
self.fw.add_filters_for_instance(instance_ref, network_info)
ipv4 = self.fw.iptables.ipv4['filter'].rules
ipv6 = self.fw.iptables.ipv6['filter'].rules
ipv4_network_rules = len(ipv4) - len(inst_ipv4) - ipv4_len
ipv6_network_rules = len(ipv6) - len(inst_ipv6) - ipv6_len
self.assertEquals(ipv4_network_rules,
ipv4_rules_per_network * networks_count)
self.assertEquals(ipv6_network_rules,
ipv6_rules_per_network * networks_count)
class NWFilterTestCase(test.TestCase):
def setUp(self):
@@ -848,6 +932,28 @@ class NWFilterTestCase(test.TestCase):
return db.security_group_get_by_name(self.context, 'fake', 'testgroup')
def _create_instance(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'mac_address': '00:A0:C9:14:C8:29',
'instance_type_id': 1})
def _create_instance_type(self, params={}):
"""Create a test instance"""
context = self.context.elevated()
inst = {}
inst['name'] = 'm1.small'
inst['memory_mb'] = '1024'
inst['vcpus'] = '1'
inst['local_gb'] = '20'
inst['flavorid'] = '1'
inst['swap'] = '2048'
inst['rxtx_quota'] = 100
inst['rxtx_cap'] = 200
inst.update(params)
return db.instance_type_create(context, inst)['id']
def test_creates_base_rule_first(self):
# These come pre-defined by libvirt
self.defined_filters = ['no-mac-spoofing',
@@ -876,25 +982,18 @@ class NWFilterTestCase(test.TestCase):
self.fake_libvirt_connection.nwfilterDefineXML = _filterDefineXMLMock
instance_ref = db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'mac_address': '00:A0:C9:14:C8:29',
'instance_type_id': 1})
instance_ref = self._create_instance()
inst_id = instance_ref['id']
ip = '10.11.12.13'
network_ref = db.project_get_network(self.context,
'fake')
fixed_ip = {'address': ip,
'network_id': network_ref['id']}
network_ref = db.project_get_network(self.context, 'fake')
fixed_ip = {'address': ip, 'network_id': network_ref['id']}
admin_ctxt = context.get_admin_context()
db.fixed_ip_create(admin_ctxt, fixed_ip)
db.fixed_ip_update(admin_ctxt, ip, {'allocated': True,
'instance_id': instance_ref['id']})
'instance_id': inst_id})
def _ensure_all_called():
instance_filter = 'nova-instance-%s-%s' % (instance_ref['name'],
@@ -920,3 +1019,11 @@ class NWFilterTestCase(test.TestCase):
_ensure_all_called()
self.teardown_security_group()
db.instance_destroy(admin_ctxt, instance_ref['id'])
def test_create_network_filters(self):
instance_ref = self._create_instance()
network_info = _create_network_info(3)
result = self.fw._create_network_filters(instance_ref,
network_info,
"fake")
self.assertEquals(len(result), 3)
+1 -1
View File
@@ -142,7 +142,7 @@ class VolumeTestCase(test.TestCase):
self.assertEqual(vol['status'], "available")
self.volume.delete_volume(self.context, volume_id)
self.assertRaises(exception.Error,
self.assertRaises(exception.VolumeNotFound,
db.volume_get,
self.context,
volume_id)
+1 -1
View File
@@ -60,7 +60,7 @@ def import_class(import_str):
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError), exc:
LOG.debug(_('Inner Exception: %s'), exc)
raise exception.NotFound(_('Class %s cannot be found') % class_str)
raise exception.ClassNotFound(class_name=class_str)
def import_object(import_str):
+1 -2
View File
@@ -288,8 +288,7 @@ class FakeConnection(driver.ComputeDriver):
knowledge of the instance
"""
if instance_name not in self.instances:
raise exception.NotFound(_("Instance %s Not Found")
% instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
i = self.instances[instance_name]
return {'state': i.state,
'max_mem': 0,
+5 -8
View File
@@ -143,8 +143,7 @@ class HyperVConnection(driver.ComputeDriver):
""" Create a new VM and start it."""
vm = self._lookup(instance.name)
if vm is not None:
raise exception.Duplicate(_('Attempt to create duplicate vm %s') %
instance.name)
raise exception.InstanceExists(name=instance.name)
user = manager.AuthManager().get_user(instance['user_id'])
project = manager.AuthManager().get_project(instance['project_id'])
@@ -368,7 +367,7 @@ class HyperVConnection(driver.ComputeDriver):
"""Reboot the specified instance."""
vm = self._lookup(instance.name)
if vm is None:
raise exception.NotFound('instance not present %s' % instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
self._set_vm_state(instance.name, 'Reboot')
def destroy(self, instance):
@@ -412,7 +411,7 @@ class HyperVConnection(driver.ComputeDriver):
"""Get information about the VM"""
vm = self._lookup(instance_id)
if vm is None:
raise exception.NotFound('instance not present %s' % instance_id)
raise exception.InstanceNotFound(instance_id=instance_id)
vm = self._conn.Msvm_ComputerSystem(ElementName=instance_id)[0]
vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
vmsettings = vm.associators(
@@ -474,14 +473,12 @@ class HyperVConnection(driver.ComputeDriver):
def attach_volume(self, instance_name, device_path, mountpoint):
vm = self._lookup(instance_name)
if vm is None:
raise exception.NotFound('Cannot attach volume to missing %s vm'
% instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
def detach_volume(self, instance_name, mountpoint):
vm = self._lookup(instance_name)
if vm is None:
raise exception.NotFound('Cannot detach volume from missing %s '
% instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
def poll_rescued_instances(self, timeout):
pass
+74 -72
View File
@@ -434,7 +434,7 @@ class LibvirtConnection(driver.ComputeDriver):
mount_device = mountpoint.rpartition("/")[2]
xml = self._get_disk_xml(virt_dom.XMLDesc(0), mount_device)
if not xml:
raise exception.NotFound(_("No disk at %s") % mount_device)
raise exception.DiskNotFound(location=mount_device)
virt_dom.detachDevice(xml)
@exception.wrap_exception
@@ -960,26 +960,16 @@ class LibvirtConnection(driver.ComputeDriver):
mac_id = mapping['mac'].replace(':', '')
if FLAGS.allow_project_net_traffic:
template = "<parameter name=\"%s\"value=\"%s\" />\n"
net, mask = _get_net_and_mask(network['cidr'])
values = [("PROJNET", net), ("PROJMASK", mask)]
if FLAGS.use_ipv6:
net, mask = _get_net_and_mask(network['cidr'])
net_v6, prefixlen_v6 = _get_net_and_prefixlen(
network['cidr_v6'])
extra_params = ("<parameter name=\"PROJNET\" "
"value=\"%s\" />\n"
"<parameter name=\"PROJMASK\" "
"value=\"%s\" />\n"
"<parameter name=\"PROJNETV6\" "
"value=\"%s\" />\n"
"<parameter name=\"PROJMASKV6\" "
"value=\"%s\" />\n") % \
(net, mask, net_v6, prefixlen_v6)
else:
net, mask = _get_net_and_mask(network['cidr'])
extra_params = ("<parameter name=\"PROJNET\" "
"value=\"%s\" />\n"
"<parameter name=\"PROJMASK\" "
"value=\"%s\" />\n") % \
(net, mask)
values.extend([("PROJNETV6", net_v6),
("PROJMASKV6", prefixlen_v6)])
extra_params = "".join([template % value for value in values])
else:
extra_params = "\n"
@@ -997,10 +987,7 @@ class LibvirtConnection(driver.ComputeDriver):
return result
def to_xml(self, instance, rescue=False, network_info=None):
# TODO(termie): cache?
LOG.debug(_('instance %s: starting toXML method'), instance['name'])
def _prepare_xml_info(self, instance, rescue=False, network_info=None):
# TODO(adiantum) remove network_info creation code
# when multinics will be completed
if not network_info:
@@ -1008,8 +995,7 @@ class LibvirtConnection(driver.ComputeDriver):
nics = []
for (network, mapping) in network_info:
nics.append(self._get_nic_for_xml(network,
mapping))
nics.append(self._get_nic_for_xml(network, mapping))
# FIXME(vish): stick this in db
inst_type_id = instance['instance_type_id']
inst_type = instance_types.get_instance_type(inst_type_id)
@@ -1041,10 +1027,14 @@ class LibvirtConnection(driver.ComputeDriver):
xml_info['ramdisk'] = xml_info['basepath'] + "/ramdisk"
xml_info['disk'] = xml_info['basepath'] + "/disk"
return xml_info
def to_xml(self, instance, rescue=False, network_info=None):
# TODO(termie): cache?
LOG.debug(_('instance %s: starting toXML method'), instance['name'])
xml_info = self._prepare_xml_info(instance, rescue, network_info)
xml = str(Template(self.libvirt_xml, searchList=[xml_info]))
LOG.debug(_('instance %s: finished toXML method'),
instance['name'])
LOG.debug(_('instance %s: finished toXML method'), instance['name'])
return xml
def _lookup_by_name(self, instance_name):
@@ -1846,10 +1836,6 @@ class NWFilterFirewall(FirewallDriver):
"""
if not network_info:
network_info = _get_network_info(instance)
if instance['image_id'] == str(FLAGS.vpn_image_id):
base_filter = 'nova-vpn'
else:
base_filter = 'nova-base'
ctxt = context.get_admin_context()
@@ -1861,41 +1847,59 @@ class NWFilterFirewall(FirewallDriver):
'nova-base-ipv6',
'nova-allow-dhcp-server']
if FLAGS.use_ipv6:
networks = [network for (network, _m) in network_info if
network['gateway_v6']]
if networks:
instance_secgroup_filter_children.\
append('nova-allow-ra-server')
for security_group in \
db.security_group_get_by_instance(ctxt, instance['id']):
self.refresh_security_group_rules(security_group['id'])
instance_secgroup_filter_children += [('nova-secgroup-%s' %
security_group['id'])]
instance_secgroup_filter_children.append('nova-secgroup-%s' %
security_group['id'])
self._define_filter(
self._filter_container(instance_secgroup_filter_name,
instance_secgroup_filter_children))
for (network, mapping) in network_info:
network_filters = self.\
_create_network_filters(instance, network_info,
instance_secgroup_filter_name)
for (name, children) in network_filters:
self._define_filters(name, children)
def _create_network_filters(self, instance, network_info,
instance_secgroup_filter_name):
if instance['image_id'] == str(FLAGS.vpn_image_id):
base_filter = 'nova-vpn'
else:
base_filter = 'nova-base'
result = []
for (_n, mapping) in network_info:
nic_id = mapping['mac'].replace(':', '')
instance_filter_name = self._instance_filter_name(instance, nic_id)
instance_filter_children = \
[base_filter, instance_secgroup_filter_name]
if FLAGS.use_ipv6:
gateway_v6 = network['gateway_v6']
if gateway_v6:
instance_secgroup_filter_children += \
['nova-allow-ra-server']
instance_filter_children = [base_filter,
instance_secgroup_filter_name]
if FLAGS.allow_project_net_traffic:
instance_filter_children += ['nova-project']
instance_filter_children.append('nova-project')
if FLAGS.use_ipv6:
instance_filter_children += ['nova-project-v6']
instance_filter_children.append('nova-project-v6')
self._define_filter(
self._filter_container(instance_filter_name,
instance_filter_children))
result.append((instance_filter_name, instance_filter_children))
return
return result
def _define_filters(self, filter_name, filter_children):
self._define_filter(self._filter_container(filter_name,
filter_children))
def refresh_security_group_rules(self, security_group_id):
return self._define_filter(
@@ -1997,34 +2001,21 @@ class IptablesFirewallDriver(FirewallDriver):
self.add_filters_for_instance(instance, network_info)
self.iptables.apply()
def add_filters_for_instance(self, instance, network_info=None):
if not network_info:
network_info = _get_network_info(instance)
chain_name = self._instance_chain_name(instance)
def _create_filter(self, ips, chain_name):
return ['-d %s -j $%s' % (ip, chain_name) for ip in ips]
self.iptables.ipv4['filter'].add_chain(chain_name)
def _filters_for_instance(self, chain_name, network_info):
ips_v4 = [ip['ip'] for (_n, mapping) in network_info
for ip in mapping['ips']]
ipv4_rules = self._create_filter(ips_v4, chain_name)
ips_v4 = [ip['ip'] for (_, mapping) in network_info
for ip in mapping['ips']]
ips_v6 = [ip['ip'] for (_n, mapping) in network_info
for ip in mapping['ip6s']]
for ipv4_address in ips_v4:
self.iptables.ipv4['filter'].add_rule('local',
'-d %s -j $%s' %
(ipv4_address, chain_name))
if FLAGS.use_ipv6:
self.iptables.ipv6['filter'].add_chain(chain_name)
ips_v6 = [ip['ip'] for (_, mapping) in network_info
for ip in mapping['ip6s']]
for ipv6_address in ips_v6:
self.iptables.ipv6['filter'].add_rule('local',
'-d %s -j $%s' %
(ipv6_address,
chain_name))
ipv4_rules, ipv6_rules = self.instance_rules(instance, network_info)
ipv6_rules = self._create_filter(ips_v6, chain_name)
return ipv4_rules, ipv6_rules
def _add_filters(self, chain_name, ipv4_rules, ipv6_rules):
for rule in ipv4_rules:
self.iptables.ipv4['filter'].add_rule(chain_name, rule)
@@ -2032,6 +2023,17 @@ class IptablesFirewallDriver(FirewallDriver):
for rule in ipv6_rules:
self.iptables.ipv6['filter'].add_rule(chain_name, rule)
def add_filters_for_instance(self, instance, network_info=None):
chain_name = self._instance_chain_name(instance)
if FLAGS.use_ipv6:
self.iptables.ipv6['filter'].add_chain(chain_name)
self.iptables.ipv4['filter'].add_chain(chain_name)
ipv4_rules, ipv6_rules = self._filters_for_instance(chain_name,
network_info)
self._add_filters('local', ipv4_rules, ipv6_rules)
ipv4_rules, ipv6_rules = self.instance_rules(instance, network_info)
self._add_filters(chain_name, ipv4_rules, ipv6_rules)
def remove_filters_for_instance(self, instance):
chain_name = self._instance_chain_name(instance)
+4 -5
View File
@@ -387,12 +387,11 @@ def _add_file(file_path):
def _remove_file(file_path):
"""Removes a file reference from the db."""
if _db_content.get("files") is None:
raise exception.NotFound(_("No files have been added yet"))
raise exception.NoFilesFound()
# Check if the remove is for a single file object or for a folder
if file_path.find(".vmdk") != -1:
if file_path not in _db_content.get("files"):
raise exception.NotFound(_("File- '%s' is not there in the "
"datastore") % file_path)
raise exception.FileNotFound(file_path=file_path)
_db_content.get("files").remove(file_path)
else:
# Removes the files in the folder and the folder too from the db
@@ -579,7 +578,7 @@ class FakeVim(object):
"""Searches the datastore for a file."""
ds_path = kwargs.get("datastorePath")
if _db_content.get("files", None) is None:
raise exception.NotFound(_("No files have been added yet"))
raise exception.NoFilesFound()
for file in _db_content.get("files"):
if file.find(ds_path) != -1:
task_mdo = create_task(method, "success")
@@ -591,7 +590,7 @@ class FakeVim(object):
"""Creates a directory in the datastore."""
ds_path = kwargs.get("name")
if _db_content.get("files", None) is None:
raise exception.NotFound(_("No files have been added yet"))
raise exception.NoFilesFound()
_db_content["files"].append(ds_path)
def _set_power_state(self, method, vm_ref, pwr_state="poweredOn"):
+10 -20
View File
@@ -100,8 +100,7 @@ class VMWareVMOps(object):
"""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref:
raise exception.Duplicate(_("Attempted to create a VM with a name"
" %s, but that already exists on the host") % instance.name)
raise exception.InstanceExists(name=instance.name)
client_factory = self._session._get_vim().client.factory
service_content = self._session._get_vim().get_service_content()
@@ -116,8 +115,7 @@ class VMWareVMOps(object):
network_utils.get_network_with_the_name(self._session,
net_name)
if network_ref is None:
raise exception.NotFound(_("Network with the name '%s' doesn't"
" exist on the ESX host") % net_name)
raise exception.NetworkNotFoundForBridge(bridge=net_name)
_check_if_network_bridge_exists()
@@ -337,8 +335,7 @@ class VMWareVMOps(object):
"""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
client_factory = self._session._get_vim().client.factory
service_content = self._session._get_vim().get_service_content()
@@ -388,8 +385,7 @@ class VMWareVMOps(object):
"VirtualMachine",
"datastore")
if not ds_ref_ret:
raise exception.NotFound(_("Failed to get the datastore "
"reference(s) which the VM uses"))
raise exception.DatastoreNotFound()
ds_ref = ds_ref_ret.ManagedObjectReference[0]
ds_browser = vim_util.get_dynamic_property(
self._session._get_vim(),
@@ -480,8 +476,7 @@ class VMWareVMOps(object):
"""Reboot a VM instance."""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
lst_properties = ["summary.guest.toolsStatus", "runtime.powerState",
"summary.guest.toolsRunningStatus"]
props = self._session._call_method(vim_util, "get_object_properties",
@@ -605,8 +600,7 @@ class VMWareVMOps(object):
"""Suspend the specified instance."""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
pwr_state = self._session._call_method(vim_util,
"get_dynamic_property", vm_ref,
@@ -630,8 +624,7 @@ class VMWareVMOps(object):
"""Resume the specified instance."""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
pwr_state = self._session._call_method(vim_util,
"get_dynamic_property", vm_ref,
@@ -651,8 +644,7 @@ class VMWareVMOps(object):
"""Return data about the VM instance."""
vm_ref = self._get_vm_ref_from_the_name(instance_name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
lst_properties = ["summary.config.numCpu",
"summary.config.memorySizeMB",
@@ -688,8 +680,7 @@ class VMWareVMOps(object):
"""Return snapshot of console."""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
param_list = {"id": str(vm_ref)}
base_url = "%s://%s/screen?%s" % (self._session._scheme,
self._session._host_ip,
@@ -717,8 +708,7 @@ class VMWareVMOps(object):
"""
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.NotFound(_("instance - %s not present") %
instance.name)
raise exception.InstanceNotFound(instance_id=instance.id)
network = db.network_get_by_instance(context.get_admin_context(),
instance['id'])
mac_addr = instance.mac_address
+3 -6
View File
@@ -506,9 +506,7 @@ class VMHelper(HelperBase):
try:
return glance_disk_format2nova_type[disk_format]
except KeyError:
raise exception.NotFound(
_("Unrecognized disk_format '%(disk_format)s'")
% locals())
raise exception.InvalidDiskFormat(disk_format=disk_format)
def determine_from_instance():
if instance.kernel_id:
@@ -643,8 +641,7 @@ class VMHelper(HelperBase):
if n == 0:
return None
elif n > 1:
raise exception.Duplicate(_('duplicate name found: %s') %
name_label)
raise exception.InstanceExists(name=name_label)
else:
return vm_refs[0]
@@ -853,7 +850,7 @@ def safe_find_sr(session):
"""
sr_ref = find_sr(session)
if sr_ref is None:
raise exception.NotFound(_('Cannot find SR to read/write VDI'))
raise exception.StorageRepositoryNotFound()
return sr_ref
+5 -9
View File
@@ -127,8 +127,7 @@ class VMOps(object):
instance_name = instance.name
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is not None:
raise exception.Duplicate(_('Attempted to create'
' non-unique name %s') % instance_name)
raise exception.InstanceExists(name=instance_name)
#ensure enough free memory is available
if not VMHelper.ensure_free_mem(self._session, instance):
@@ -260,8 +259,7 @@ class VMOps(object):
instance_name = instance_or_vm.name
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is None:
raise exception.NotFound(
_('Instance not present %s') % instance_name)
raise exception.InstanceNotFound(instance_id=instance_obj.id)
return vm_ref
def _acquire_bootlock(self, vm):
@@ -578,9 +576,8 @@ class VMOps(object):
if not (instance.kernel_id and instance.ramdisk_id):
# 2. We only have kernel xor ramdisk
raise exception.NotFound(
_("Instance %(instance_id)s has a kernel or ramdisk but not "
"both" % locals()))
raise exception.InstanceUnacceptable(instance_id=instance_id,
reason=_("instance has a kernel or ramdisk but not both"))
# 3. We have both kernel and ramdisk
(kernel, ramdisk) = VMHelper.lookup_kernel_ramdisk(self._session,
@@ -721,8 +718,7 @@ class VMOps(object):
"%s-rescue" % instance.name)
if not rescue_vm_ref:
raise exception.NotFound(_(
"Instance is not in Rescue Mode: %s" % instance.name))
raise exception.InstanceNotInRescueMode(instance_id=instance.id)
original_vm_ref = VMHelper.lookup(self._session, instance.name)
instance._rescue = False
+2 -4
View File
@@ -45,8 +45,7 @@ class VolumeOps(object):
# Before we start, check that the VM exists
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is None:
raise exception.NotFound(_('Instance %s not found')
% instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
# NOTE: No Resource Pool concept so far
LOG.debug(_("Attach_volume: %(instance_name)s, %(device_path)s,"
" %(mountpoint)s") % locals())
@@ -98,8 +97,7 @@ class VolumeOps(object):
# Before we start, check that the VM exists
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is None:
raise exception.NotFound(_('Instance %s not found')
% instance_name)
raise exception.InstanceNotFound(instance_id=instance_name)
# Detach VBD from VM
LOG.debug(_("Detach_volume: %(instance_name)s, %(mountpoint)s")
% locals())
+11 -7
View File
@@ -25,14 +25,18 @@ import sys
from setuptools import find_packages
from setuptools.command.sdist import sdist
# In order to run the i18n commands for compiling and
# installing message catalogs, we use DistUtilsExtra.
# Don't make this a hard requirement, but warn that
# i18n commands won't be available if DistUtilsExtra is
# not installed...
try:
import DistUtilsExtra.auto
from DistUtilsExtra.auto import setup
except ImportError:
print >> sys.stderr, 'To build nova you need '\
'https://launchpad.net/python-distutils-extra'
sys.exit(1)
assert DistUtilsExtra.auto.__version__ >= '2.18',\
'needs DistUtilsExtra.auto >= 2.18'
from setuptools import setup
print "Warning: DistUtilsExtra required to use i18n builders. "
print "To build nova with support for message catalogs, you need "
print " https://launchpad.net/python-distutils-extra >= 2.18"
gettext.install('nova', unicode=1)
@@ -102,7 +106,7 @@ def find_data_files(destdir, srcdir):
package_data += [(destdir, files)]
return package_data
DistUtilsExtra.auto.setup(name='nova',
setup(name='nova',
version=version.canonical_version_string(),
description='cloud computing fabric controller',
author='OpenStack',