Skip to content

Commit

Permalink
OS-55: PEP8 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Andy Southgate committed Jan 24, 2011
1 parent c97618e commit cd346a2
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 69 deletions.
17 changes: 9 additions & 8 deletions nova/tests/db/fakes.py
Expand Up @@ -23,6 +23,7 @@
from nova import utils
from nova.compute import instance_types


class FakeModel(object):
""" Stubs out for model """
def __init__(self, values):
Expand All @@ -37,6 +38,7 @@ def __getitem__(self, key):
else:
raise NotImplementedError()


def stub_out_db_instance_api(stubs):
""" Stubs out the db API for creating Instances """

Expand Down Expand Up @@ -67,21 +69,20 @@ def fake_instance_create(values):

stubs.Set(db, 'instance_create', fake_instance_create)

def stub_out_db_network_api(stubs, injected = False):

def stub_out_db_network_api(stubs, injected=False):
"""Stubs out the db API for retrieving networks"""
network_fields = {
'bridge': 'xenbr0',
'injected': injected
}
'bridge': 'xenbr0',
'injected': injected}

if injected:
network_fields.update({
'netmask': '255.255.255.0',
'gateway': '10.0.0.1',
'broadcast': '10.0.0.255',
'dns': '10.0.0.2',
'ra_server': None
})
'ra_server': None})

def fake_network_get_by_instance(context, instance_id):
return FakeModel(network_fields)
Expand All @@ -90,5 +91,5 @@ def fake_instance_get_fixed_address(context, instance_id):
return '10.0.0.3'

stubs.Set(db, 'network_get_by_instance', fake_network_get_by_instance)
stubs.Set(db, 'instance_get_fixed_address', fake_instance_get_fixed_address)

stubs.Set(db, 'instance_get_fixed_address',
fake_instance_get_fixed_address)
19 changes: 9 additions & 10 deletions nova/tests/test_xenapi.py
Expand Up @@ -213,7 +213,7 @@ def check():

check()

def check_vm_record(self, conn, check_injection = False):
def check_vm_record(self, conn, check_injection=False):
instances = conn.list_instances()
self.assertEquals(instances, [1])

Expand Down Expand Up @@ -244,13 +244,13 @@ def check_vm_record(self, conn, check_injection = False):

# Check that the VM is running according to XenAPI.
self.assertEquals(vm['power_state'], 'Running')

if check_injection:
xenstore_data = xenapi_fake.VM_get_xenstore_data(vm_ref)
key_prefix = 'vm-data/vif/22_33_2A_B3_CC_DD/tcpip/'
tcpip_data = dict([(k.replace(key_prefix, ''), v)
for k, v in xenstore_data.iteritems()
if k.startswith(key_prefix) ])
if k.startswith(key_prefix)])

self.assertEquals(tcpip_data, {
'BroadcastAddress/data/0': '10.0.0.255',
Expand All @@ -270,11 +270,10 @@ def check_vm_record(self, conn, check_injection = False):
'NameServer/type': 'string',
'SubnetMask/data/0': '255.255.255.0',
'SubnetMask/name': 'SubnetMask',
'SubnetMask/type': 'multi_sz'
})
'SubnetMask/type': 'multi_sz'})

def _test_spawn(self, image_id, kernel_id, ramdisk_id,
check_injection = False):
check_injection=False):
stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests)
values = {'name': 1,
'id': 1,
Expand All @@ -289,7 +288,7 @@ def _test_spawn(self, image_id, kernel_id, ramdisk_id,
conn = xenapi_conn.get_connection(False)
instance = db.instance_create(values)
conn.spawn(instance)
self.check_vm_record(conn, check_injection = check_injection)
self.check_vm_record(conn, check_injection=check_injection)

def test_spawn_raw_objectstore(self):
FLAGS.xenapi_image_service = 'objectstore'
Expand All @@ -309,9 +308,9 @@ def test_spawn_glance(self):

def test_spawn_netinject(self):
FLAGS.xenapi_image_service = 'glance'
db_fakes.stub_out_db_network_api(self.stubs, injected = True)
self._test_spawn(1, 2, 3, check_injection = True)
db_fakes.stub_out_db_network_api(self.stubs, injected=True)
self._test_spawn(1, 2, 3, check_injection=True)

def tearDown(self):
super(XenAPIVMTestCase, self).tearDown()
self.manager.delete_project(self.project)
Expand Down
10 changes: 5 additions & 5 deletions nova/tests/xenapi/stubs.py
Expand Up @@ -173,20 +173,20 @@ def VM_destroy(self, session_ref, vm_ref):

def VM_get_VIFs(self, session_ref, vm_ref):
return (['0', '1', '2'])

def VIF_get_device(self, session_ref, vif_ref):
return ('1', '0', '2')[int(vif_ref)]

def VIF_get_MAC(self, session_ref, vif_ref):
return (
'11:22:2a:b3:CC:dd',
'22:33:2a:b3:CC:dd',
'44:44:2a:b3:CC:dd'
)[int(vif_ref)]

'44:44:2a:b3:CC:dd')[int(vif_ref)]

def VM_add_to_xenstore_data(self, session_ref, vm_ref, key, value):
fake.VM_add_to_xenstore_data(vm_ref, key, value)


class FakeSessionForVolumeTests(fake.SessionBase):
""" Stubs out a XenAPISession for Volume tests """
def __init__(self, uri):
Expand Down
3 changes: 2 additions & 1 deletion nova/virt/conn_common.py
Expand Up @@ -27,7 +27,8 @@
flags.DEFINE_string('injected_network_template',
utils.abspath('virt/interfaces.template'),
'Template file for injected network')



def get_injectables(inst):
key = str(inst['key_data'])
net = None
Expand Down
2 changes: 2 additions & 0 deletions nova/virt/disk.py
Expand Up @@ -154,6 +154,7 @@ def _allocate_device():
def _free_device(device):
_DEVICES.append(device)


def inject_data_into_fs(fs, key, net, execute):
"""Injects data into a filesystem already mounted by the caller.
Virt connections can call this directly if they mount their fs
Expand All @@ -164,6 +165,7 @@ def inject_data_into_fs(fs, key, net, execute):
if net:
_inject_net_into_fs(net, fs, execute=execute)


def _inject_key_into_fs(key, fs, execute=None):
"""Add the given public ssh key to root's authorized_keys.
Expand Down
9 changes: 7 additions & 2 deletions nova/virt/xenapi/fake.py
Expand Up @@ -148,15 +148,18 @@ def create_vbd(vm_ref, vdi_ref):
after_VBD_create(vbd_ref, vbd_rec)
return vbd_ref


def VM_get_xenstore_data(vm_ref):
return _db_content['VM'][vm_ref].get('xenstore_data', '')



def VM_add_to_xenstore_data(vm_ref, key, value):
db_ref = _db_content['VM'][vm_ref]
if not 'xenstore_data' in db_ref:
db_ref['xenstore_data'] = {}
db_ref['xenstore_data'][key] = value



def after_VBD_create(vbd_ref, vbd_rec):
"""Create read-only fields and backref from VM to VBD when VBD is
created."""
Expand All @@ -169,11 +172,13 @@ def after_VBD_create(vbd_ref, vbd_rec):
vm_name_label = _db_content['VM'][vm_ref]['name_label']
vbd_rec['vm_name_label'] = vm_name_label


def after_VM_create(vm_ref, vm_rec):
"""Create read-only fields in the VM record."""
if 'is_control_domain' not in vm_rec:
vm_rec['is_control_domain'] = False


def create_pbd(config, host_ref, sr_ref, attached):
return _create_object('PBD', {
'device-config': config,
Expand Down
80 changes: 40 additions & 40 deletions nova/virt/xenapi/vm_utils.py
Expand Up @@ -448,20 +448,21 @@ def lookup_vm_vdis(cls, session, vm):
def preconfigure_instance(cls, session, instance, vdi_ref):
"""Makes alterations to the image before launching as part of spawn.
"""

# As mounting the image VDI is expensive, we only want do do it once,
# if at all, so determine whether it's required first, and then do
# everything
mount_required = False
key, net = conn_common.get_injectables(instance)
if key is not None or net is not None:
mount_required = True

if mount_required:

def _mounted_processing(device):
"""Callback which runs with the image VDI attached"""
dev_path = '/dev/'+device+'1' # NB: Partition 1 hardcoded

dev_path = '/dev/' + device + '1' # NB: Partition 1 hardcoded
tmpdir = tempfile.mkdtemp()
try:
# Mount only Linux filesystems, to avoid disturbing
Expand All @@ -478,9 +479,9 @@ def _mounted_processing(device):
else:
try:
# This try block ensures that the umount occurs
xe_update_networking_filename = os.path.join(tmpdir,
'usr', 'sbin', 'xe-update-networking')

xe_update_networking_filename = os.path.join(
tmpdir, 'usr', 'sbin', 'xe-update-networking')
if os.path.isfile(xe_update_networking_filename):
# The presence of the xe-update-networking
# file indicates that this guest agent can
Expand All @@ -489,14 +490,15 @@ def _mounted_processing(device):
# required
LOG.info(_('XenServer tools installed in this '
'image are capable of network injection. '
'Networking files will not be manipulated'))
'Networking files will not be'
'manipulated'))
else:
xe_daemon_filename = os.path.join(tmpdir, 'usr',
'sbin', 'xe-daemon')
xe_daemon_filename = os.path.join(tmpdir,
'usr', 'sbin', 'xe-daemon')
if os.path.isfile(xe_daemon_filename):
LOG.info(_('XenServer tools are present in '
'this image but are not capable of '
'network injection'))
LOG.info(_('XenServer tools are present '
'in this image but are not capable '
'of network injection'))
else:
LOG.info(_('XenServer tools are not '
'installed in this image'))
Expand All @@ -510,33 +512,32 @@ def _mounted_processing(device):
# remove temporary directory
os.rmdir(tmpdir)

with_vdi_attached_here(session, vdi_ref, False, _mounted_processing)

with_vdi_attached_here(session, vdi_ref, False,
_mounted_processing)

@classmethod
def preconfigure_xenstore(cls, session, instance, vm_ref):
"""Sets xenstore values to modify the image behaviour after
VM start.
"""

xenstore_types = {
'BroadcastAddress' : 'multi_sz',
'DefaultGateway' : 'multi_sz',
'EnableDhcp' : 'dword',
'IPAddress' : 'multi_sz',
'NameServer' : 'string',
'SubnetMask' : 'multi_sz'
}

'BroadcastAddress': 'multi_sz',
'DefaultGateway': 'multi_sz',
'EnableDhcp': 'dword',
'IPAddress': 'multi_sz',
'NameServer': 'string',
'SubnetMask': 'multi_sz'}

# Network setup
network_ref = db.network_get_by_instance(
context.get_admin_context(), instance['id'])
if network_ref['injected']:
admin_context = context.get_admin_context()
address = db.instance_get_fixed_address(admin_context,
instance['id'])
xenstore_data = {

xenstore_data = {
# NB: Setting broadcast address is not supported by
# Windows or the Windows guest agent, and will be ignored
# on that platform
Expand All @@ -545,30 +546,29 @@ def preconfigure_xenstore(cls, session, instance, vm_ref):
'IPAddress': address,
'SubnetMask': network_ref['netmask'],
'DefaultGateway': network_ref['gateway'],
'NameServer': network_ref['dns']
}

device_to_configure = 0 # Configure network device 0 in the VM

'NameServer': network_ref['dns']}

device_to_configure = 0 # Configure network device 0 in the VM

vif_refs = session.call_xenapi('VM.get_VIFs', vm_ref)
mac_addr = None

for vif_ref in vif_refs:
device = session.call_xenapi('VIF.get_device', vif_ref)
if str(device) == str(device_to_configure):
mac_addr = session.call_xenapi('VIF.get_MAC', vif_ref)
break

if mac_addr is None:
raise exception.NotFound(_('Networking device %s not found '
'in VM'))

# MAC address must be upper case in the xenstore key,
# with colons replaced by underscores
underscore_mac_addr = mac_addr.replace(':', '_')
xenstore_prefix = ('vm-data/vif/' +
underscore_mac_addr.upper() + '/tcpip/')

for xenstore_key, xenstore_value in xenstore_data.iteritems():
# NB: The xenstore_key part of the instance_key isn't used but
# must be unique. We set it to xenstore_key as a convenient
Expand All @@ -578,15 +578,15 @@ def preconfigure_xenstore(cls, session, instance, vm_ref):
key_type = xenstore_types[xenstore_key]

session.call_xenapi('VM.add_to_xenstore_data', vm_ref,
instance_key+'/name', xenstore_key)
instance_key + '/name', xenstore_key)
session.call_xenapi('VM.add_to_xenstore_data', vm_ref,
instance_key+'/type', key_type)
instance_key + '/type', key_type)
if key_type == 'multi_sz':
session.call_xenapi('VM.add_to_xenstore_data', vm_ref,
instance_key+'/data/0', xenstore_value)
instance_key + '/data/0', xenstore_value)
else:
session.call_xenapi('VM.add_to_xenstore_data', vm_ref,
instance_key+'/data', xenstore_value)
instance_key + '/data', xenstore_value)

@classmethod
def compile_info(cls, record):
Expand Down
6 changes: 3 additions & 3 deletions nova/virt/xenapi/vmops.py
Expand Up @@ -105,14 +105,14 @@ def spawn(self, instance):
if network_ref:
VMHelper.create_vif(self._session, vm_ref,
network_ref, instance.mac_address)

# Alter the image before VM start for, e.g. network injection
VMHelper.preconfigure_instance(self._session, instance, vdi_ref)

# Configure the VM's xenstore data before start for,
# e.g. network configuration
VMHelper.preconfigure_xenstore(self._session, instance, vm_ref)

LOG.debug(_('Starting VM %s...'), vm_ref)
self._session.call_xenapi('VM.start', vm_ref, False, False)
instance_name = instance.name
Expand Down

0 comments on commit cd346a2

Please sign in to comment.