Convert nova.compute.* to use instance dot notation

nova.compute.* should use instance objects with the field access
dot notation everywhere. Essentially we use instance.key instead
of instance['key']. Needed to rework some of the test cases to get
them working. This change depends on:
Ib2288f2e6dadde9b31946a6f353111d8b4779a0b

Change-Id: I17914226e412e66b3de7681799dcf1690f590683
This commit is contained in:
Davanum Srinivas 2015-02-20 14:40:24 -05:00
parent 53e7fdd0c0
commit 171e5f8b12
16 changed files with 187 additions and 167 deletions

View File

@ -177,24 +177,24 @@ def check_instance_state(vm_state=None, task_state=(None,),
def outer(f):
@functools.wraps(f)
def inner(self, context, instance, *args, **kw):
if vm_state is not None and instance['vm_state'] not in vm_state:
if vm_state is not None and instance.vm_state not in vm_state:
raise exception.InstanceInvalidState(
attr='vm_state',
instance_uuid=instance['uuid'],
state=instance['vm_state'],
instance_uuid=instance.uuid,
state=instance.vm_state,
method=f.__name__)
if (task_state is not None and
instance['task_state'] not in task_state):
instance.task_state not in task_state):
raise exception.InstanceInvalidState(
attr='task_state',
instance_uuid=instance['uuid'],
state=instance['task_state'],
instance_uuid=instance.uuid,
state=instance.task_state,
method=f.__name__)
if must_have_launched and not instance['launched_at']:
if must_have_launched and not instance.launched_at:
raise exception.InstanceInvalidState(
attr='launched_at',
instance_uuid=instance['uuid'],
state=instance['launched_at'],
instance_uuid=instance.uuid,
state=instance.launched_at,
method=f.__name__)
return f(self, context, instance, *args, **kw)
@ -205,8 +205,8 @@ def check_instance_state(vm_state=None, task_state=(None,),
def check_instance_host(function):
@functools.wraps(function)
def wrapped(self, context, instance, *args, **kwargs):
if not instance['host']:
raise exception.InstanceNotReady(instance_id=instance['uuid'])
if not instance.host:
raise exception.InstanceNotReady(instance_id=instance.uuid)
return function(self, context, instance, *args, **kwargs)
return wrapped
@ -214,8 +214,8 @@ def check_instance_host(function):
def check_instance_lock(function):
@functools.wraps(function)
def inner(self, context, instance, *args, **kwargs):
if instance['locked'] and not context.is_admin:
raise exception.InstanceIsLocked(instance_uuid=instance['uuid'])
if instance.locked and not context.is_admin:
raise exception.InstanceIsLocked(instance_uuid=instance.uuid)
return function(self, context, instance, *args, **kwargs)
return inner
@ -314,19 +314,19 @@ class API(base.Base):
def _validate_cell(self, instance, method):
if self.cell_type != 'api':
return
cell_name = instance['cell_name']
cell_name = instance.cell_name
if not cell_name:
raise exception.InstanceUnknownCell(
instance_uuid=instance['uuid'])
instance_uuid=instance.uuid)
if self._cell_read_only(cell_name):
raise exception.InstanceInvalidState(
attr="vm_state",
instance_uuid=instance['uuid'],
instance_uuid=instance.uuid,
state="temporary_readonly",
method=method)
def _record_action_start(self, context, instance, action):
objects.InstanceAction.action_start(context, instance['uuid'],
objects.InstanceAction.action_start(context, instance.uuid,
action, want_result=False)
def _check_injected_file_quota(self, context, injected_files):
@ -624,8 +624,8 @@ class API(base.Base):
def _apply_instance_name_template(self, context, instance, index):
params = {
'uuid': instance['uuid'],
'name': instance['display_name'],
'uuid': instance.uuid,
'name': instance.display_name,
'count': index + 1,
}
try:
@ -634,7 +634,7 @@ class API(base.Base):
except (KeyError, TypeError):
LOG.exception(_LE('Failed to set instance name using '
'multi_instance_display_name_template.'))
new_name = instance['display_name']
new_name = instance.display_name
instance.display_name = new_name
if not instance.get('hostname', None):
instance.hostname = utils.sanitize_hostname(new_name)
@ -1298,7 +1298,7 @@ class API(base.Base):
hostname = None
if display_name is None:
display_name = self._default_display_name(instance['uuid'])
display_name = self._default_display_name(instance.uuid)
instance.display_name = display_name
if hostname is None and num_instances == 1:
@ -1322,7 +1322,7 @@ class API(base.Base):
if not instance.obj_attr_is_set('uuid'):
# Generate the instance_uuid here so we can use it
# for additional setup before creating the DB entry.
instance['uuid'] = str(uuid.uuid4())
instance.uuid = str(uuid.uuid4())
instance.launch_index = index
instance.vm_state = vm_states.BUILDING
@ -1346,15 +1346,15 @@ class API(base.Base):
if not instance.obj_attr_is_set('system_metadata'):
instance.system_metadata = {}
# Make sure we have the dict form that we need for instance_update.
instance['system_metadata'] = utils.instance_sys_meta(instance)
instance.system_metadata = utils.instance_sys_meta(instance)
system_meta = utils.get_system_metadata_from_image(
image, instance_type)
# In case we couldn't find any suitable base_image
system_meta.setdefault('image_base_image_ref', instance['image_ref'])
system_meta.setdefault('image_base_image_ref', instance.image_ref)
instance['system_metadata'].update(system_meta)
instance.system_metadata.update(system_meta)
self.security_group_api.populate_security_groups(instance,
security_groups)
@ -1401,7 +1401,7 @@ class API(base.Base):
instance.destroy()
self._create_block_device_mapping(
instance_type, instance['uuid'], block_device_mapping)
instance_type, instance.uuid, block_device_mapping)
return instance
@ -1501,7 +1501,7 @@ class API(base.Base):
# Update the instance record and send a state update notification
# if task or vm state changed
old_ref, instance_ref = self.db.instance_update_and_get_original(
context, instance['uuid'], kwargs)
context, instance.uuid, kwargs)
notifications.send_update(context, old_ref,
instance_ref, service="api")
@ -1630,7 +1630,7 @@ class API(base.Base):
# in soft-delete vm_state have already had quotas
# decremented. More details:
# https://bugs.launchpad.net/nova/+bug/1333145
if instance['vm_state'] == vm_states.SOFT_DELETED:
if instance.vm_state == vm_states.SOFT_DELETED:
quotas.rollback()
cb(context, instance, bdms,
@ -1769,12 +1769,12 @@ class API(base.Base):
orig_host = instance.host
try:
if instance.vm_state == vm_states.SHELVED_OFFLOADED:
instance['host'] = instance._system_metadata.get(
instance.host = instance._system_metadata.get(
'shelved_host')
self.network_api.deallocate_for_instance(elevated,
instance)
finally:
instance['host'] = orig_host
instance.host = orig_host
# cleanup volumes
for bdm in bdms:
@ -2181,7 +2181,7 @@ class API(base.Base):
"""
if extra_properties is None:
extra_properties = {}
instance_uuid = instance['uuid']
instance_uuid = instance.uuid
properties = {
'instance_uuid': instance_uuid,
@ -2218,12 +2218,12 @@ class API(base.Base):
image_meta['name'] = name
image_meta['is_public'] = False
properties = image_meta['properties']
if instance['root_device_name']:
properties['root_device_name'] = instance['root_device_name']
if instance.root_device_name:
properties['root_device_name'] = instance.root_device_name
properties.update(extra_properties or {})
quiesced = False
if instance['vm_state'] == vm_states.ACTIVE:
if instance.vm_state == vm_states.ACTIVE:
try:
self.compute_rpcapi.quiesce_instance(context, instance)
quiesced = True
@ -2238,7 +2238,7 @@ class API(base.Base):
context=context, instance=instance)
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance['uuid'])
context, instance.uuid)
mapping = []
for bdm in bdms:
@ -2301,17 +2301,17 @@ class API(base.Base):
def reboot(self, context, instance, reboot_type):
"""Reboot the given instance."""
if (reboot_type == 'SOFT' and
(instance['vm_state'] not in vm_states.ALLOW_SOFT_REBOOT)):
(instance.vm_state not in vm_states.ALLOW_SOFT_REBOOT)):
raise exception.InstanceInvalidState(
attr='vm_state',
instance_uuid=instance['uuid'],
state=instance['vm_state'],
instance_uuid=instance.uuid,
state=instance.vm_state,
method='soft reboot')
if reboot_type == 'SOFT' and instance['task_state'] is not None:
if reboot_type == 'SOFT' and instance.task_state is not None:
raise exception.InstanceInvalidState(
attr='task_state',
instance_uuid=instance['uuid'],
state=instance['task_state'],
instance_uuid=instance.uuid,
state=instance.task_state,
method='reboot')
expected_task_state = [None]
if reboot_type == 'HARD':
@ -2659,11 +2659,11 @@ class API(base.Base):
filter_properties = {'ignore_hosts': []}
if not CONF.allow_resize_to_same_host:
filter_properties['ignore_hosts'].append(instance['host'])
filter_properties['ignore_hosts'].append(instance.host)
# Here when flavor_id is None, the process is considered as migrate.
if (not flavor_id and not CONF.allow_migrate_to_same_host):
filter_properties['ignore_hosts'].append(instance['host'])
filter_properties['ignore_hosts'].append(instance.host)
if self.cell_type == 'api':
# Commit reservations early and create migration record.
@ -2702,7 +2702,7 @@ class API(base.Base):
image_id = None
if not self.is_volume_backed_instance(context, instance):
name = '%s-shelved' % instance['display_name']
name = '%s-shelved' % instance.display_name
image_meta = self._create_image(context, instance, name,
'snapshot')
image_id = image_meta['id']
@ -2876,7 +2876,7 @@ class API(base.Base):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type,
connect_info['host'], connect_info['port'],
connect_info['internal_access_path'], instance['uuid'])
connect_info['internal_access_path'], instance.uuid)
return {'url': connect_info['access_url']}
@ -2896,7 +2896,7 @@ class API(base.Base):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type,
connect_info['host'], connect_info['port'],
connect_info['internal_access_path'], instance['uuid'])
connect_info['internal_access_path'], instance.uuid)
return {'url': connect_info['access_url']}
@ -2916,7 +2916,7 @@ class API(base.Base):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type,
connect_info['host'], connect_info['port'],
connect_info['internal_access_path'], instance['uuid'])
connect_info['internal_access_path'], instance.uuid)
return {'url': connect_info['access_url']}
@ -2937,7 +2937,7 @@ class API(base.Base):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type,
connect_info['host'], connect_info['port'],
connect_info['internal_access_path'], instance['uuid'])
connect_info['internal_access_path'], instance.uuid)
return {'url': connect_info['access_url']}
@check_instance_host
@ -2988,7 +2988,7 @@ class API(base.Base):
@wrap_check_policy
def get_lock(self, context, instance):
"""Return the boolean state of given instance's lock."""
return self.get(context, instance['uuid'])['locked']
return self.get(context, instance.uuid)['locked']
@wrap_check_policy
@check_instance_lock
@ -3071,7 +3071,7 @@ class API(base.Base):
raise exception.InvalidVolume(reason=msg)
# The caller likely got the instance from volume['instance_uuid']
# in the first place, but let's sanity check.
if volume['instance_uuid'] != instance['uuid']:
if volume['instance_uuid'] != instance.uuid:
raise exception.VolumeUnattached(volume_id=volume['id'])
self._detach_volume(context, instance, volume)
@ -3086,7 +3086,7 @@ class API(base.Base):
raise exception.VolumeUnattached(volume_id=old_volume['id'])
# The caller likely got the instance from volume['instance_uuid']
# in the first place, but let's sanity check.
if old_volume['instance_uuid'] != instance['uuid']:
if old_volume['instance_uuid'] != instance.uuid:
msg = _("Old volume is attached to a different instance.")
raise exception.InvalidVolume(reason=msg)
if new_volume['attach_status'] == 'attached':
@ -3134,7 +3134,7 @@ class API(base.Base):
@wrap_check_policy
def get_instance_metadata(self, context, instance):
"""Get all metadata associated with an instance."""
rv = self.db.instance_metadata_get(context, instance['uuid'])
rv = self.db.instance_metadata_get(context, instance.uuid)
return dict(rv.iteritems())
def get_all_instance_metadata(self, context, search_filts):
@ -3212,16 +3212,16 @@ class API(base.Base):
for instance in instances:
check_policy(context, 'get_instance_faults', instance)
uuids = [instance['uuid'] for instance in instances]
uuids = [instance.uuid for instance in instances]
return self.db.instance_fault_get_by_instance_uuids(context, uuids)
def is_volume_backed_instance(self, context, instance, bdms=None):
if not instance['image_ref']:
if not instance.image_ref:
return True
if bdms is None:
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance['uuid'])
context, instance.uuid)
root_bdm = bdms.root_bdm()
if not root_bdm:
@ -3492,11 +3492,11 @@ class InstanceActionAPI(base.Base):
def actions_get(self, context, instance):
return objects.InstanceActionList.get_by_instance_uuid(
context, instance['uuid'])
context, instance.uuid)
def action_get_by_request_id(self, context, instance, request_id):
return objects.InstanceAction.get_by_request_id(
context, instance['uuid'], request_id)
context, instance.uuid, request_id)
def action_events_get(self, context, instance, action_id):
return objects.InstanceActionEventList.get_by_action(
@ -4144,9 +4144,9 @@ class SecurityGroupAPI(base.Base, security_group_base.SecurityGroupBase):
context, id, columns_to_join=['instances'])
for instance in security_group['instances']:
if instance['host'] is not None:
if instance.host is not None:
self.security_group_rpcapi.refresh_instance_security_rules(
context, instance['host'], instance)
context, instance.host, instance)
def trigger_members_refresh(self, context, group_ids):
"""Called when a security group gains a new or loses a member.
@ -4175,14 +4175,14 @@ class SecurityGroupAPI(base.Base, security_group_base.SecurityGroupBase):
instances = {}
for security_group in security_groups:
for instance in security_group['instances']:
if instance['uuid'] not in instances:
instances[instance['uuid']] = instance
if instance.uuid not in instances:
instances[instance.uuid] = instance
# ..then we send a request to refresh the rules for each instance.
for instance in instances.values():
if instance['host']:
if instance.host:
self.security_group_rpcapi.refresh_instance_security_rules(
context, instance['host'], instance)
context, instance.host, instance)
def get_instance_security_groups(self, context, instance_uuid,
detailed=False):

View File

@ -171,16 +171,16 @@ class ComputeCellsAPI(compute_api.API):
self._cell_type = 'api'
def _cast_to_cells(self, context, instance, method, *args, **kwargs):
instance_uuid = instance['uuid']
cell_name = instance['cell_name']
instance_uuid = instance.uuid
cell_name = instance.cell_name
if not cell_name:
raise exception.InstanceUnknownCell(instance_uuid=instance_uuid)
self.cells_rpcapi.cast_compute_api_method(context, cell_name,
method, instance_uuid, *args, **kwargs)
def _call_to_cells(self, context, instance, method, *args, **kwargs):
instance_uuid = instance['uuid']
cell_name = instance['cell_name']
instance_uuid = instance.uuid
cell_name = instance.cell_name
if not cell_name:
raise exception.InstanceUnknownCell(instance_uuid=instance_uuid)
return self.cells_rpcapi.call_compute_api_method(context, cell_name,
@ -208,11 +208,11 @@ class ComputeCellsAPI(compute_api.API):
def update(self, context, instance, **kwargs):
"""Update an instance."""
cell_name = instance['cell_name']
cell_name = instance.cell_name
if cell_name and self._cell_read_only(cell_name):
raise exception.InstanceInvalidState(
attr="vm_state",
instance_uuid=instance['uuid'],
instance_uuid=instance.uuid,
state="temporary_readonly",
method='update')
rv = super(ComputeCellsAPI, self).update(context,
@ -239,12 +239,12 @@ class ComputeCellsAPI(compute_api.API):
self._handle_cell_delete(context, instance, delete_types.DELETE)
def _handle_cell_delete(self, context, instance, delete_type):
if not instance['cell_name']:
if not instance.cell_name:
self.cells_rpcapi.instance_delete_everywhere(context,
instance, delete_type)
bdms = block_device.legacy_mapping(
self.db.block_device_mapping_get_all_by_instance(
context, instance['uuid']))
context, instance.uuid))
# NOTE(danms): If we try to delete an instance with no cell,
# there isn't anything to salvage, so we can hard-delete here.
super(ComputeCellsAPI, self)._local_delete(context, instance, bdms,
@ -354,8 +354,8 @@ class ComputeCellsAPI(compute_api.API):
@check_instance_cell
def get_vnc_console(self, context, instance, console_type):
"""Get a url to a VNC Console."""
if not instance['host']:
raise exception.InstanceNotReady(instance_id=instance['uuid'])
if not instance.host:
raise exception.InstanceNotReady(instance_id=instance.uuid)
connect_info = self._call_to_cells(context, instance,
'get_vnc_connect_info', console_type)
@ -363,15 +363,15 @@ class ComputeCellsAPI(compute_api.API):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type, connect_info['host'],
connect_info['port'], connect_info['internal_access_path'],
instance['uuid'])
instance.uuid)
return {'url': connect_info['access_url']}
@wrap_check_policy
@check_instance_cell
def get_spice_console(self, context, instance, console_type):
"""Get a url to a SPICE Console."""
if not instance['host']:
raise exception.InstanceNotReady(instance_id=instance['uuid'])
if not instance.host:
raise exception.InstanceNotReady(instance_id=instance.uuid)
connect_info = self._call_to_cells(context, instance,
'get_spice_connect_info', console_type)
@ -379,15 +379,15 @@ class ComputeCellsAPI(compute_api.API):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type, connect_info['host'],
connect_info['port'], connect_info['internal_access_path'],
instance['uuid'])
instance.uuid)
return {'url': connect_info['access_url']}
@wrap_check_policy
@check_instance_cell
def get_rdp_console(self, context, instance, console_type):
"""Get a url to a RDP Console."""
if not instance['host']:
raise exception.InstanceNotReady(instance_id=instance['uuid'])
if not instance.host:
raise exception.InstanceNotReady(instance_id=instance.uuid)
connect_info = self._call_to_cells(context, instance,
'get_rdp_connect_info', console_type)
@ -395,15 +395,15 @@ class ComputeCellsAPI(compute_api.API):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type, connect_info['host'],
connect_info['port'], connect_info['internal_access_path'],
instance['uuid'])
instance.uuid)
return {'url': connect_info['access_url']}
@wrap_check_policy
@check_instance_cell
def get_serial_console(self, context, instance, console_type):
"""Get a url to a serial console."""
if not instance['host']:
raise exception.InstanceNotReady(instance_id=instance['uuid'])
if not instance.host:
raise exception.InstanceNotReady(instance_id=instance.uuid)
connect_info = self._call_to_cells(context, instance,
'get_serial_console_connect_info', console_type)
@ -411,7 +411,7 @@ class ComputeCellsAPI(compute_api.API):
self.consoleauth_rpcapi.authorize_console(context,
connect_info['token'], console_type, connect_info['host'],
connect_info['port'], connect_info['internal_access_path'],
instance['uuid'])
instance.uuid)
return {'url': connect_info['access_url']}
@check_instance_cell

View File

@ -750,7 +750,7 @@ class ResourceTracker(object):
self.ext_resources_handler.reset_resources(resources, self.driver)
for instance in instances:
if instance['vm_state'] != vm_states.DELETED:
if instance.vm_state != vm_states.DELETED:
self._update_usage_from_instance(context, resources, instance)
def _find_orphaned_instances(self):

View File

@ -59,10 +59,10 @@ def _compute_host(host, instance):
return host
if not instance:
raise exception.NovaException(_('No compute host specified'))
if not instance['host']:
if not instance.host:
raise exception.NovaException(_('Unable to find host for '
'Instance %s') % instance['uuid'])
return instance['host']
'Instance %s') % instance.uuid)
return instance.host
class ComputeAPI(object):

View File

@ -31,7 +31,6 @@ from nova.i18n import _LW
from nova.network import model as network_model
from nova import notifications
from nova import objects
from nova.objects import base as obj_base
from nova import rpc
from nova import utils
from nova.virt import driver
@ -99,7 +98,7 @@ def add_instance_fault_from_exc(context, instance, fault, exc_info=None):
fault_obj = objects.InstanceFault(context=context)
fault_obj.host = CONF.host
fault_obj.instance_uuid = instance['uuid']
fault_obj.instance_uuid = instance.uuid
fault_obj.update(exception_to_dict(fault))
code = fault_obj.code
fault_obj.details = _get_fault_details(exc_info, code)
@ -384,16 +383,9 @@ def notify_about_host_update(context, event_suffix, host_payload):
def get_nw_info_for_instance(instance):
if isinstance(instance, obj_base.NovaObject):
if instance.info_cache is None:
return network_model.NetworkInfo.hydrate([])
return instance.info_cache.network_info
# FIXME(comstud): Transitional while we convert to objects.
info_cache = instance['info_cache'] or {}
nw_info = info_cache.get('network_info') or []
if not isinstance(nw_info, network_model.NetworkInfo):
nw_info = network_model.NetworkInfo.hydrate(nw_info)
return nw_info
if instance.info_cache is None:
return network_model.NetworkInfo.hydrate([])
return instance.info_cache.network_info
def has_audit_been_run(context, conductor, host, timestamp=None):

View File

@ -43,7 +43,7 @@ def get_from_instance(instance):
:returns: canonicalized vm mode for the instance
"""
mode = instance['vm_mode']
mode = instance.vm_mode
return canonicalize(mode)

View File

@ -3051,7 +3051,7 @@ class InstanceActionsSampleJsonTest(ApiSampleTestBaseV2):
super(InstanceActionsSampleJsonTest, self).setUp()
self.actions = fake_server_actions.FAKE_ACTIONS
self.events = fake_server_actions.FAKE_EVENTS
self.instance = test_utils.get_test_instance()
self.instance = test_utils.get_test_instance(obj=True)
def fake_server_action_get_by_request_id(context, uuid, request_id):
return copy.deepcopy(self.actions[uuid][request_id])
@ -3068,7 +3068,8 @@ class InstanceActionsSampleJsonTest(ApiSampleTestBaseV2):
def fake_get(self, context, instance_uuid, expected_attrs=None,
want_objects=True):
return {'uuid': instance_uuid}
return fake_instance.fake_instance_obj(
None, **{'uuid': instance_uuid})
self.stubs.Set(db, 'action_get_by_request_id',
fake_server_action_get_by_request_id)

View File

@ -18,6 +18,7 @@ import copy
from nova.compute import api as compute_api
from nova import db
from nova.tests.functional.v3 import api_sample_base
from nova.tests.unit import fake_instance
from nova.tests.unit import fake_server_actions
from nova.tests.unit import utils as test_utils
@ -29,7 +30,7 @@ class ServerActionsSampleJsonTest(api_sample_base.ApiSampleTestBaseV3):
super(ServerActionsSampleJsonTest, self).setUp()
self.actions = fake_server_actions.FAKE_ACTIONS
self.events = fake_server_actions.FAKE_EVENTS
self.instance = test_utils.get_test_instance()
self.instance = test_utils.get_test_instance(obj=True)
def fake_instance_action_get_by_request_id(context, uuid, request_id):
return copy.deepcopy(self.actions[uuid][request_id])
@ -44,8 +45,10 @@ class ServerActionsSampleJsonTest(api_sample_base.ApiSampleTestBaseV3):
def fake_instance_get_by_uuid(context, instance_id):
return self.instance
def fake_get(self, context, instance_uuid, **kwargs):
return {'uuid': instance_uuid}
def fake_get(self, context, instance_uuid, expected_attrs=None,
want_objects=True):
return fake_instance.fake_instance_obj(
None, **{'uuid': instance_uuid})
self.stubs.Set(db, 'action_get_by_request_id',
fake_instance_action_get_by_request_id)

View File

@ -141,7 +141,8 @@ class InstanceActionsTestV21(test.NoDBTestCase):
return objects.Instance(uuid=instance_uuid)
def fake_instance_get_by_uuid(context, instance_id, use_slave=False):
return {'name': 'fake', 'project_id': context.project_id}
return fake_instance.fake_instance_obj(None,
**{'name': 'fake', 'project_id': context.project_id})
self.stubs.Set(compute_api.API, 'get', fake_get)
self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid)

View File

@ -280,6 +280,9 @@ class BaseTestCase(test.TestCase):
fake.restore_nodes()
super(BaseTestCase, self).tearDown()
def _fake_instance(self, updates):
return fake_instance.fake_instance_obj(None, **updates)
def _create_fake_instance_obj(self, params=None, type_name='m1.tiny',
services=False):
flavor = flavors.get_flavor_by_name(type_name)
@ -8850,12 +8853,14 @@ class ComputeAPITestCase(BaseTestCase):
self.compute_api.delete(self.context, instance)
def test_attach_volume_invalid(self):
instance = fake_instance.fake_instance_obj(None, **{
'locked': False, 'vm_state': vm_states.ACTIVE,
'task_state': None,
'launched_at': timeutils.utcnow()})
self.assertRaises(exception.InvalidDevicePath,
self.compute_api.attach_volume,
self.context,
{'locked': False, 'vm_state': vm_states.ACTIVE,
'task_state': None,
'launched_at': timeutils.utcnow()},
instance,
None,
'/invalid')
@ -8870,20 +8875,24 @@ class ComputeAPITestCase(BaseTestCase):
self.stubs.Set(cinder.API, 'check_attach', fake)
self.stubs.Set(cinder.API, 'reserve_volume', fake)
instance = fake_instance.fake_instance_obj(None, **{
'uuid': 'fake_uuid', 'locked': False,
'vm_state': vm_states.RESCUED})
self.assertRaises(exception.InstanceInvalidState,
self.compute_api.attach_volume,
self.context,
{'uuid': 'fake_uuid', 'locked': False,
'vm_state': vm_states.RESCUED},
instance,
None,
'/dev/vdb')
def test_no_attach_volume_in_suspended_state(self):
instance = fake_instance.fake_instance_obj(None, **{
'uuid': 'fake_uuid', 'locked': False,
'vm_state': vm_states.SUSPENDED})
self.assertRaises(exception.InstanceInvalidState,
self.compute_api.attach_volume,
self.context,
{'uuid': 'fake_uuid', 'locked': False,
'vm_state': vm_states.SUSPENDED},
instance,
{'id': 'fake-volume-id'},
'/dev/vdb')
@ -8919,15 +8928,15 @@ class ComputeAPITestCase(BaseTestCase):
def test_vnc_console(self):
# Make sure we can a vnc console for an instance.
fake_instance = {'uuid': 'fake_uuid',
'host': 'fake_compute_host'}
fake_instance = self._fake_instance(
{'uuid': 'fake_uuid', 'host': 'fake_compute_host'})
fake_console_type = "novnc"
fake_connect_info = {'token': 'fake_token',
'console_type': fake_console_type,
'host': 'fake_console_host',
'port': 'fake_console_port',
'internal_access_path': 'fake_access_path',
'instance_uuid': fake_instance['uuid'],
'instance_uuid': fake_instance.uuid,
'access_url': 'fake_console_url'}
rpcapi = compute_rpcapi.ComputeAPI
@ -8958,15 +8967,15 @@ class ComputeAPITestCase(BaseTestCase):
def test_spice_console(self):
# Make sure we can a spice console for an instance.
fake_instance = {'uuid': 'fake_uuid',
'host': 'fake_compute_host'}
fake_instance = self._fake_instance(
{'uuid': 'fake_uuid', 'host': 'fake_compute_host'})
fake_console_type = "spice-html5"
fake_connect_info = {'token': 'fake_token',
'console_type': fake_console_type,
'host': 'fake_console_host',
'port': 'fake_console_port',
'internal_access_path': 'fake_access_path',
'instance_uuid': fake_instance['uuid'],
'instance_uuid': fake_instance.uuid,
'access_url': 'fake_console_url'}
rpcapi = compute_rpcapi.ComputeAPI
@ -8997,15 +9006,15 @@ class ComputeAPITestCase(BaseTestCase):
def test_rdp_console(self):
# Make sure we can a rdp console for an instance.
fake_instance = {'uuid': 'fake_uuid',
'host': 'fake_compute_host'}
fake_instance = self._fake_instance({'uuid': 'fake_uuid',
'host': 'fake_compute_host'})
fake_console_type = "rdp-html5"
fake_connect_info = {'token': 'fake_token',
'console_type': fake_console_type,
'host': 'fake_console_host',
'port': 'fake_console_port',
'internal_access_path': 'fake_access_path',
'instance_uuid': fake_instance['uuid'],
'instance_uuid': fake_instance.uuid,
'access_url': 'fake_console_url'}
rpcapi = compute_rpcapi.ComputeAPI
@ -9036,15 +9045,15 @@ class ComputeAPITestCase(BaseTestCase):
def test_serial_console(self):
# Make sure we can get a serial proxy url for an instance.
fake_instance = {'uuid': 'fake_uuid',
'host': 'fake_compute_host'}
fake_instance = self._fake_instance({'uuid': 'fake_uuid',
'host': 'fake_compute_host'})
fake_console_type = 'serial'
fake_connect_info = {'token': 'fake_token',
'console_type': fake_console_type,
'host': 'fake_serial_host',
'port': 'fake_tcp_port',
'internal_access_path': 'fake_access_path',
'instance_uuid': fake_instance['uuid'],
'instance_uuid': fake_instance.uuid,
'access_url': 'fake_access_url'}
rpcapi = compute_rpcapi.ComputeAPI
@ -9074,8 +9083,8 @@ class ComputeAPITestCase(BaseTestCase):
self.context, instance, 'serial')
def test_console_output(self):
fake_instance = {'uuid': 'fake_uuid',
'host': 'fake_compute_host'}
fake_instance = self._fake_instance({'uuid': 'fake_uuid',
'host': 'fake_compute_host'})
fake_tail_length = 699
fake_console_output = 'fake console output'
@ -9247,44 +9256,44 @@ class ComputeAPITestCase(BaseTestCase):
def test_detach_invalid_volume(self):
# Ensure exception is raised while detaching an un-attached volume
instance = {'uuid': 'uuid1',
fake_instance = self._fake_instance({'uuid': 'uuid1',
'locked': False,
'launched_at': timeutils.utcnow(),
'vm_state': vm_states.ACTIVE,
'task_state': None}
'task_state': None})
volume = {'id': 1, 'attach_status': 'detached'}
self.assertRaises(exception.InvalidVolume,
self.compute_api.detach_volume, self.context,
instance, volume)
fake_instance, volume)
def test_detach_unattached_volume(self):
# Ensure exception is raised when volume's idea of attached
# instance doesn't match.
instance = {'uuid': 'uuid1',
fake_instance = self._fake_instance({'uuid': 'uuid1',
'locked': False,
'launched_at': timeutils.utcnow(),
'vm_state': vm_states.ACTIVE,
'task_state': None}
'task_state': None})
volume = {'id': 1, 'attach_status': 'in-use',
'instance_uuid': 'uuid2'}
self.assertRaises(exception.VolumeUnattached,
self.compute_api.detach_volume, self.context,
instance, volume)
fake_instance, volume)
def test_detach_suspended_instance_fails(self):
instance = {'uuid': 'uuid1',
fake_instance = self._fake_instance({'uuid': 'uuid1',
'locked': False,
'launched_at': timeutils.utcnow(),
'vm_state': vm_states.SUSPENDED,
'task_state': None}
'task_state': None})
volume = {'id': 1, 'attach_status': 'in-use',
'instance_uuid': 'uuid2'}
self.assertRaises(exception.InstanceInvalidState,
self.compute_api.detach_volume, self.context,
instance, volume)
fake_instance, volume)
def test_detach_volume_libvirt_is_down(self):
# Ensure rollback during detach if libvirt goes down

View File

@ -1753,11 +1753,12 @@ class _ComputeAPIUnitTestMixIn(object):
raise AttributeError # Random exception
# Should fail if VM state is not valid
instance = {'vm_state': vm_states.BUILDING,
instance = fake_instance.fake_instance_obj(None, **{
'vm_state': vm_states.BUILDING,
'launched_at': timeutils.utcnow(),
'locked': False,
'availability_zone': 'fake_az',
'uuid': 'fake'}
'uuid': 'fake'})
volumes = {}
old_volume_id = uuidutils.generate_uuid()
volumes[old_volume_id] = {'id': old_volume_id,
@ -2320,7 +2321,8 @@ class _ComputeAPIUnitTestMixIn(object):
return self.fake_image['id']
def test_resize_with_disabled_auto_disk_config_fails(self):
fake_inst = self._create_instance_with_disabled_disk_config()
fake_inst = self._create_instance_with_disabled_disk_config(
object=True)
self.assertRaises(exception.AutoDiskConfigDisabledByImage,
self.compute_api.resize,

View File

@ -809,12 +809,6 @@ class ComputeUtilsGetNWInfo(test.NoDBTestCase):
result = compute_utils.get_nw_info_for_instance(inst)
self.assertEqual(jsonutils.dumps([]), result.json())
def test_instance_dict_none_info_cache(self):
inst = fake_instance.fake_db_instance(info_cache=None)
self.assertIsNone(inst['info_cache'])
result = compute_utils.get_nw_info_for_instance(inst)
self.assertEqual(jsonutils.dumps([]), result.json())
class ComputeUtilsGetRebootTypes(test.NoDBTestCase):
def setUp(self):

View File

@ -52,7 +52,8 @@ class ComputeRpcAPITestCase(test.NoDBTestCase):
def test_serialized_instance_has_name(self):
self.assertIn('name', self.fake_instance)
def _test_compute_api(self, method, rpc_method, **kwargs):
def _test_compute_api(self, method, rpc_method,
assert_dict=False, **kwargs):
ctxt = context.RequestContext('fake_user', 'fake_project')
rpcapi = kwargs.pop('rpcapi_class', compute_rpcapi.ComputeAPI)()
@ -77,6 +78,10 @@ class ComputeRpcAPITestCase(test.NoDBTestCase):
expected_kwargs.pop('host', None)
expected_kwargs.pop('destination', None)
if assert_dict:
expected_kwargs['instance'] = jsonutils.to_primitive(
expected_kwargs['instance'])
cast_and_call = ['confirm_resize', 'stop_instance']
if rpc_method == 'call' and method in cast_and_call:
if method == 'confirm_resize':
@ -227,7 +232,8 @@ class ComputeRpcAPITestCase(test.NoDBTestCase):
def test_get_instance_diagnostics(self):
self._test_compute_api('get_instance_diagnostics', 'call',
instance=self.fake_instance, version='3.31')
assert_dict=True, instance=self.fake_instance_obj,
version='3.31')
def test_get_vnc_console(self):
self._test_compute_api('get_vnc_console', 'call',
@ -246,7 +252,7 @@ class ComputeRpcAPITestCase(test.NoDBTestCase):
def test_get_serial_console(self):
self._test_compute_api('get_serial_console', 'call',
instance=self.fake_instance, console_type='serial',
instance=self.fake_instance_obj, console_type='serial',
version='3.34')
def test_validate_console_port(self):
@ -521,7 +527,7 @@ class ComputeRpcAPITestCase(test.NoDBTestCase):
def test_volume_snapshot_create(self):
self._test_compute_api('volume_snapshot_create', 'cast',
instance=self.fake_instance, volume_id='fake_id',
instance=self.fake_instance_obj, volume_id='fake_id',
create_info={}, version='3.6')
def test_volume_snapshot_delete(self):

View File

@ -19,6 +19,7 @@ from nova.compute import stats
from nova.compute import task_states
from nova.compute import vm_states
from nova import test
from nova.tests.unit import fake_instance
class StatsTestCase(test.NoDBTestCase):
@ -26,6 +27,9 @@ class StatsTestCase(test.NoDBTestCase):
super(StatsTestCase, self).setUp()
self.stats = stats.Stats()
def _fake_object(self, updates):
return fake_instance.fake_instance_obj(None, **updates)
def _create_instance(self, values=None):
instance = {
"os_type": "Linux",
@ -37,7 +41,7 @@ class StatsTestCase(test.NoDBTestCase):
}
if values:
instance.update(values)
return instance
return self._fake_object(instance)
def test_os_type_count(self):
os_type = "Linux"
@ -77,7 +81,7 @@ class StatsTestCase(test.NoDBTestCase):
"vcpus": 3,
"uuid": "12-34-56-78-90",
}
self.stats.update_stats_for_instance(instance)
self.stats.update_stats_for_instance(self._fake_object(instance))
instance = {
"os_type": "FreeBSD",
@ -87,7 +91,7 @@ class StatsTestCase(test.NoDBTestCase):
"vcpus": 1,
"uuid": "23-45-67-89-01",
}
self.stats.update_stats_for_instance(instance)
self.stats.update_stats_for_instance(self._fake_object(instance))
instance = {
"os_type": "Linux",
@ -98,7 +102,7 @@ class StatsTestCase(test.NoDBTestCase):
"uuid": "34-56-78-90-12",
}
self.stats.update_stats_for_instance(instance)
self.stats.update_stats_for_instance(self._fake_object(instance))
instance = {
"os_type": "Linux",
@ -109,7 +113,7 @@ class StatsTestCase(test.NoDBTestCase):
"uuid": "34-56-78-90-13",
}
self.stats.update_stats_for_instance(instance)
self.stats.update_stats_for_instance(self._fake_object(instance))
instance = {
"os_type": "Linux",
@ -120,7 +124,7 @@ class StatsTestCase(test.NoDBTestCase):
"uuid": "34-56-78-90-14",
}
self.stats.update_stats_for_instance(instance)
self.stats.update_stats_for_instance(self._fake_object(instance))
self.assertEqual(4, self.stats.num_os_type("Linux"))
self.assertEqual(1, self.stats.num_os_type("FreeBSD"))

View File

@ -15,33 +15,37 @@
from nova.compute import vm_mode
from nova import exception
from nova import test
from nova.tests.unit import fake_instance
class ComputeVMModeTest(test.NoDBTestCase):
def _fake_object(self, updates):
return fake_instance.fake_instance_obj(None, **updates)
def test_case(self):
inst = dict(vm_mode="HVM")
inst = self._fake_object(dict(vm_mode="HVM"))
mode = vm_mode.get_from_instance(inst)
self.assertEqual(mode, "hvm")
def test_legacy_pv(self):
inst = dict(vm_mode="pv")
inst = self._fake_object(dict(vm_mode="pv"))
mode = vm_mode.get_from_instance(inst)
self.assertEqual(mode, "xen")
def test_legacy_hv(self):
inst = dict(vm_mode="hv")
inst = self._fake_object(dict(vm_mode="hv"))
mode = vm_mode.get_from_instance(inst)
self.assertEqual(mode, "hvm")
def test_bogus(self):
inst = dict(vm_mode="wibble")
inst = self._fake_object(dict(vm_mode="wibble"))
self.assertRaises(exception.Invalid,
vm_mode.get_from_instance,
inst)
def test_good(self):
inst = dict(vm_mode="hvm")
inst = self._fake_object(dict(vm_mode="hvm"))
mode = vm_mode.get_from_instance(inst)
self.assertEqual(mode, "hvm")

View File

@ -35,6 +35,7 @@ from nova import context
from nova import exception
from nova import objects
from nova import test
from nova.tests.unit import fake_instance
from nova.tests.unit.objects import test_flavor
from nova.tests.unit.virt.xenapi import stubs
from nova.tests.unit.virt.xenapi import test_xenapi
@ -1586,38 +1587,41 @@ class CreateVmTestCase(VMUtilsTestBase):
class DetermineVmModeTestCase(VMUtilsTestBase):
def _fake_object(self, updates):
return fake_instance.fake_instance_obj(None, **updates)
def test_determine_vm_mode_returns_xen_mode(self):
instance = {"vm_mode": "xen"}
instance = self._fake_object({"vm_mode": "xen"})
self.assertEqual(vm_mode.XEN,
vm_utils.determine_vm_mode(instance, None))
def test_determine_vm_mode_returns_hvm_mode(self):
instance = {"vm_mode": "hvm"}
instance = self._fake_object({"vm_mode": "hvm"})
self.assertEqual(vm_mode.HVM,
vm_utils.determine_vm_mode(instance, None))
def test_determine_vm_mode_returns_xen_for_linux(self):
instance = {"vm_mode": None, "os_type": "linux"}
instance = self._fake_object({"vm_mode": None, "os_type": "linux"})
self.assertEqual(vm_mode.XEN,
vm_utils.determine_vm_mode(instance, None))
def test_determine_vm_mode_returns_hvm_for_windows(self):
instance = {"vm_mode": None, "os_type": "windows"}
instance = self._fake_object({"vm_mode": None, "os_type": "windows"})
self.assertEqual(vm_mode.HVM,
vm_utils.determine_vm_mode(instance, None))
def test_determine_vm_mode_returns_hvm_by_default(self):
instance = {"vm_mode": None, "os_type": None}
instance = self._fake_object({"vm_mode": None, "os_type": None})
self.assertEqual(vm_mode.HVM,
vm_utils.determine_vm_mode(instance, None))
def test_determine_vm_mode_returns_xen_for_VHD(self):
instance = {"vm_mode": None, "os_type": None}
instance = self._fake_object({"vm_mode": None, "os_type": None})
self.assertEqual(vm_mode.XEN,
vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK_VHD))
def test_determine_vm_mode_returns_xen_for_DISK(self):
instance = {"vm_mode": None, "os_type": None}
instance = self._fake_object({"vm_mode": None, "os_type": None})
self.assertEqual(vm_mode.XEN,
vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK))