From 1b508d80dd76810f6183df50b9d9b324831875be Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Wed, 16 Feb 2011 12:01:22 +0000 Subject: First commit for xenapi-vlan-networking. Totally untested --- nova/network/manager.py | 1 + nova/virt/xenapi/network_utils.py | 17 +++++++++++++++-- nova/virt/xenapi/vm_utils.py | 1 + nova/virt/xenapi/vmops.py | 15 +++++++++++++-- 4 files changed, 30 insertions(+), 4 deletions(-) (limited to 'nova') diff --git a/nova/network/manager.py b/nova/network/manager.py index 8eb9f041b..6ba0f2e18 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -499,6 +499,7 @@ class VlanManager(NetworkManager): def setup_compute_network(self, context, instance_id): """Sets up matching network for compute hosts.""" network_ref = db.network_get_by_instance(context, instance_id) + #TODO: the xenapi driver will create a xenserver network if necessary here self.driver.ensure_vlan_bridge(network_ref['vlan'], network_ref['bridge']) diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index c0406d8f0..4c2a81260 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -28,7 +28,20 @@ class NetworkHelper(HelperBase): """ The class that wraps the helper methods together. """ - + + + @classmethod + def find_network_with_name_label(cls,session,name_label): + networks = session.call_xenapi('network.get_by_name_label', name_label) + if len(networks) == 1: + return networks.keys()[0] + elif len(networks) > 1: + raise Exception(_('Found non-unique network' + ' for name_label %s') % name_label) + else: + return None + + @classmethod def find_network_with_bridge(cls, session, bridge): """Return the network on which the bridge is attached, if found.""" @@ -40,4 +53,4 @@ class NetworkHelper(HelperBase): raise Exception(_('Found non-unique network' ' for bridge %s') % bridge) else: - raise Exception(_('Found no network for bridge %s') % bridge) + raise Exception(_('Found no network for bridge %s') % bridge) diff --git a/nova/virt/xenapi/vm_utils.py b/nova/virt/xenapi/vm_utils.py index f5c19099a..76257946e 100644 --- a/nova/virt/xenapi/vm_utils.py +++ b/nova/virt/xenapi/vm_utils.py @@ -204,6 +204,7 @@ class VMHelper(HelperBase): VIF reference.""" vif_rec = {} vif_rec['device'] = '0' + #network_ref should be the appropriate reference (network with VLAN) vif_rec['network'] = network_ref vif_rec['VM'] = vm_ref vif_rec['MAC'] = mac_address diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index fe95d881b..b5c5e082e 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -67,10 +67,21 @@ class VMOps(object): raise exception.Duplicate(_('Attempted to create' ' non-unique name %s') % instance.name) + #this will return the bridge name in nova db bridge = db.network_get_by_instance(context.get_admin_context(), instance['id'])['bridge'] - network_ref = \ - NetworkHelper.find_network_with_bridge(self._session, bridge) + + #this will return the appropriate network + #TODO: avoid unnecessary call to find_network_with_bridge + #when VLAN manager is being used (and not just use an if) + network_ref = None + try: + network_ref = \ + NetworkHelper.find_network_with_bridge(self._session, bridge) + except: + #try to get name with name_label + network_ref = \ + NetworkHelper.find_network_with_name_label(self._session,bridge) user = AuthManager().get_user(instance.user_id) project = AuthManager().get_project(instance.project_id) -- cgit From 01e340f98765cc434624b3b4da49447f950f07ae Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Wed, 16 Feb 2011 17:16:31 +0000 Subject: First commit of working code --- nova/network/linux_net.py | 1 + nova/virt/xenapi/network_utils.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'nova') diff --git a/nova/network/linux_net.py b/nova/network/linux_net.py index c1cbff7d8..f5efac0ae 100644 --- a/nova/network/linux_net.py +++ b/nova/network/linux_net.py @@ -291,6 +291,7 @@ def update_dhcp(context, network_id): if a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance """ + LOG.debug("ENTERING update_dhcp - DHCP script:%s",FLAGS.dhcpbridge) network_ref = db.network_get(context, network_id) conffile = _dhcp_file(network_ref['bridge'], 'conf') diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index 4c2a81260..8f7806e6c 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -34,7 +34,7 @@ class NetworkHelper(HelperBase): def find_network_with_name_label(cls,session,name_label): networks = session.call_xenapi('network.get_by_name_label', name_label) if len(networks) == 1: - return networks.keys()[0] + return networks[0] elif len(networks) > 1: raise Exception(_('Found non-unique network' ' for name_label %s') % name_label) -- cgit From 441beee908d2534c4fa1d85523dbc87770efeb17 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Thu, 17 Feb 2011 16:54:42 +0000 Subject: Supporting networks with multiple PIFs. pep8 fixes unit tests passed --- nova/network/linux_net.py | 1 - nova/network/manager.py | 2 +- nova/network/xenapi_net.py | 130 ++++++++++++++++++++++++++++++++++++++ nova/virt/xenapi/network_utils.py | 12 ++-- nova/virt/xenapi/vmops.py | 11 ++-- 5 files changed, 142 insertions(+), 14 deletions(-) create mode 100644 nova/network/xenapi_net.py (limited to 'nova') diff --git a/nova/network/linux_net.py b/nova/network/linux_net.py index f5efac0ae..c1cbff7d8 100644 --- a/nova/network/linux_net.py +++ b/nova/network/linux_net.py @@ -291,7 +291,6 @@ def update_dhcp(context, network_id): if a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance """ - LOG.debug("ENTERING update_dhcp - DHCP script:%s",FLAGS.dhcpbridge) network_ref = db.network_get(context, network_id) conffile = _dhcp_file(network_ref['bridge'], 'conf') diff --git a/nova/network/manager.py b/nova/network/manager.py index 6ba0f2e18..85209e69f 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -499,7 +499,7 @@ class VlanManager(NetworkManager): def setup_compute_network(self, context, instance_id): """Sets up matching network for compute hosts.""" network_ref = db.network_get_by_instance(context, instance_id) - #TODO: the xenapi driver will create a xenserver network if necessary here + #xenapi driver will create a xen network if necessary here self.driver.ensure_vlan_bridge(network_ref['vlan'], network_ref['bridge']) diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py new file mode 100644 index 000000000..289dbd71f --- /dev/null +++ b/nova/network/xenapi_net.py @@ -0,0 +1,130 @@ +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +""" +Implements vlans, bridges, and iptables rules using linux utilities. +""" + +import os + +from nova import db +from nova import exception +from nova import flags +from nova import log as logging +from nova import utils +from nova.virt.xenapi_conn import XenAPISession +from nova.virt.xenapi.network_utils import NetworkHelper + +LOG = logging.getLogger("nova.xenapi_net") + +FLAGS = flags.FLAGS +flags.DEFINE_string('vlan_interface', 'eth0', + 'network device for vlans') + + +def metadata_forward(): + pass + + +def init_host(): + pass + + +def bind_floating_ip(floating_ip, check_exit_code=True): + pass + + +def unbind_floating_ip(floating_ip): + pass + + +def ensure_vlan_forward(public_ip, port, private_ip): + pass + + +def ensure_floating_forward(floating_ip, fixed_ip): + pass + + +def remove_floating_forward(floating_ip, fixed_ip): + pass + + +def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): + """Create a vlan and bridge unless they already exist""" + #open xenapi session + url = FLAGS.xenapi_connection_url + username = FLAGS.xenapi_connection_username + password = FLAGS.xenapi_connection_password + session = XenAPISession(url, username, password) + #check whether bridge already exists + #retrieve network whose name_label is "bridge" + network_ref = NetworkHelper.find_network_with_name_label(session, bridge) + if network_ref == None: + #if bridge does not exists + #1 - create network + description = "network for nova bridge %s" % bridge + network_rec = { + 'name_label': bridge, + 'name_description': description, + 'other_config': {}, + } + network_ref = session.call_xenapi('network.create', network_rec) + #2 - find PIF for VLAN + expr = 'field "device" = "%s" and \ + field "VLAN" = "-1"' % FLAGS.vlan_interface + pifs = session.call_xenapi('PIF.get_all_records_where', expr) + pif_ref = None + #multiple PIF are ok: we are dealing with a pool + if len(pifs) == 0: + raise Exception( + _('Found no PID for device %s') % FLAGS.vlan_interface) + #3 - create vlan for network + for pif_ref in pifs.keys(): + session.call_xenapi('VLAN.create', pif_ref, + str(vlan_num), network_ref) + else: + #check VLAN tag is appropriate + network_rec = session.call_xenapi('network.get_record', network_ref) + #retrieve PIFs from network + for pif_ref in network_rec['PIFs']: + #retrieve VLAN from PIF + pif_rec = session.call_xenapi('PIF.get_record', pif_ref) + pif_vlan = int(pif_rec['VLAN']) + #raise an exception if VLAN <> vlan_num + if pif_vlan != vlan_num: + raise Exception(_("PIF %(pif_rec['uuid'])s for network " + "%(bridge)s has VLAN id %(pif_vlan)d." + "Expected %(vlan_num)d") % locals()) + + +def ensure_vlan(vlan_num): + pass + + +def ensure_bridge(bridge, interface, net_attrs=None): + pass + + +def get_dhcp_hosts(context, network_id): + pass + + +def update_dhcp(context, network_id): + pass + + +def update_ra(context, network_id): + pass diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index 8f7806e6c..c4ee8a6be 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -28,10 +28,9 @@ class NetworkHelper(HelperBase): """ The class that wraps the helper methods together. """ - - + @classmethod - def find_network_with_name_label(cls,session,name_label): + def find_network_with_name_label(cls, session, name_label): networks = session.call_xenapi('network.get_by_name_label', name_label) if len(networks) == 1: return networks[0] @@ -39,9 +38,8 @@ class NetworkHelper(HelperBase): raise Exception(_('Found non-unique network' ' for name_label %s') % name_label) else: - return None - - + return None + @classmethod def find_network_with_bridge(cls, session, bridge): """Return the network on which the bridge is attached, if found.""" @@ -53,4 +51,4 @@ class NetworkHelper(HelperBase): raise Exception(_('Found non-unique network' ' for bridge %s') % bridge) else: - raise Exception(_('Found no network for bridge %s') % bridge) + raise Exception(_('Found no network for bridge %s') % bridge) diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index b5c5e082e..a0dbd1411 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -70,18 +70,19 @@ class VMOps(object): #this will return the bridge name in nova db bridge = db.network_get_by_instance(context.get_admin_context(), instance['id'])['bridge'] - + #this will return the appropriate network #TODO: avoid unnecessary call to find_network_with_bridge #when VLAN manager is being used (and not just use an if) - network_ref = None - try: + network_ref = None + try: network_ref = \ NetworkHelper.find_network_with_bridge(self._session, bridge) except: - #try to get name with name_label + #try to get name with name_label network_ref = \ - NetworkHelper.find_network_with_name_label(self._session,bridge) + NetworkHelper.find_network_with_name_label(self._session, + bridge) user = AuthManager().get_user(instance.user_id) project = AuthManager().get_project(instance.project_id) -- cgit From e263a37f83ec5f8a1d81b0f4ec7a91464b2bc022 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Mon, 21 Feb 2011 11:02:19 +0000 Subject: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NOVA-CORE DEVELOPERS SHOULD NOT REVIEW THIS MERGE PROPOSAL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is for Citrix OpenStack team only. We propose for merge into a cache of lp:nova to generate diffs for our internal peer review. --- nova/virt/xenapi/vmops.py | 1 + 1 file changed, 1 insertion(+) (limited to 'nova') diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 9bd671045..09f5a1c94 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -141,6 +141,7 @@ class VMOps(object): #this will return the appropriate network #TODO(salvatore-orlando): avoid unnecessary call to #find_network_with_bridge when VLAN manager is being used + network_ref = None try: network_ref = \ -- cgit From cb30c80c922a09ccca18645670ea5b1cdc70f1f2 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Fri, 4 Mar 2011 12:31:59 +0000 Subject: fixed wrong local variable name in vmops --- nova/virt/xenapi/vmops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nova') diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index a7838dbba..417f40da8 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -519,7 +519,7 @@ class VMOps(object): NetworkHelper.find_network_with_name_label(self._session, bridge) if network_ref: - VMHelper.create_vif(self._session, vm_ref, + VMHelper.create_vif(self._session, vm_opaque_ref, network_ref, instance.mac_address) -- cgit From c4142835981eb9b2d5a55517d975dbda029986e2 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Tue, 8 Mar 2011 10:09:34 +0000 Subject: Removed excess comment lines --- nova/network/manager.py | 1 - nova/network/xenapi_net.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'nova') diff --git a/nova/network/manager.py b/nova/network/manager.py index 05d677bc9..b36dd59cf 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -518,7 +518,6 @@ class VlanManager(NetworkManager): def setup_compute_network(self, context, instance_id): """Sets up matching network for compute hosts.""" network_ref = db.network_get_by_instance(context, instance_id) - #xenapi driver will create a xen network if necessary here self.driver.ensure_vlan_bridge(network_ref['vlan'], network_ref['bridge']) diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index d31a1352f..314638bcd 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -31,7 +31,7 @@ LOG = logging.getLogger("nova.xenapi_net") FLAGS = flags.FLAGS flags.DEFINE_string('vlan_interface', 'eth0', - 'network device for vlans') + 'Physical network interface for vlans') def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): -- cgit From 977fc1be4ea8af93b63975c5538462a776fbe168 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Fri, 11 Mar 2011 11:42:42 +0000 Subject: Moved vlan_interface flag in network.manager removed needless carriage return in vm_ops --- nova/network/linux_net.py | 5 ++--- nova/network/manager.py | 3 +++ nova/network/xenapi_net.py | 5 ----- nova/tests/test_xenapi.py | 12 ++++++++++++ nova/virt/xenapi/vmops.py | 3 +-- 5 files changed, 18 insertions(+), 10 deletions(-) (limited to 'nova') diff --git a/nova/network/linux_net.py b/nova/network/linux_net.py index 535ce87bc..6dcecdadb 100644 --- a/nova/network/linux_net.py +++ b/nova/network/linux_net.py @@ -41,13 +41,12 @@ flags.DEFINE_string('dhcpbridge_flagfile', flags.DEFINE_string('dhcp_domain', 'novalocal', 'domain to use for building the hostnames') - +#flags.DEFINE_string('vlan_interface', 'eth0', +# 'network device for vlans') flags.DEFINE_string('networks_path', '$state_path/networks', 'Location to keep network config files') flags.DEFINE_string('public_interface', 'eth0', 'Interface for public IP addresses') -flags.DEFINE_string('vlan_interface', 'eth0', - 'network device for vlans') flags.DEFINE_string('dhcpbridge', _bin_file('nova-dhcpbridge'), 'location of nova-dhcpbridge') flags.DEFINE_string('routing_source_ip', '$my_ip', diff --git a/nova/network/manager.py b/nova/network/manager.py index b36dd59cf..15ce36940 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -85,6 +85,8 @@ flags.DEFINE_string('fixed_range', '10.0.0.0/8', 'Fixed IP address block') flags.DEFINE_string('fixed_range_v6', 'fd00::/48', 'Fixed IPv6 address block') flags.DEFINE_integer('cnt_vpn_clients', 0, 'Number of addresses reserved for vpn clients') +flags.DEFINE_string('vlan_interface', 'eth0', + 'network device for vlans') flags.DEFINE_string('network_driver', 'nova.network.linux_net', 'Driver to use for network creation') flags.DEFINE_bool('update_dhcp_on_disassociate', False, @@ -517,6 +519,7 @@ class VlanManager(NetworkManager): def setup_compute_network(self, context, instance_id): """Sets up matching network for compute hosts.""" + LOG.debug("ENTERING SETUP COMPUTE NETWORK") network_ref = db.network_get_by_instance(context, instance_id) self.driver.ensure_vlan_bridge(network_ref['vlan'], network_ref['bridge']) diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index 314638bcd..01889f94d 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -29,11 +29,6 @@ from nova.virt.xenapi.network_utils import NetworkHelper LOG = logging.getLogger("nova.xenapi_net") -FLAGS = flags.FLAGS -flags.DEFINE_string('vlan_interface', 'eth0', - 'Physical network interface for vlans') - - def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): """Create a vlan and bridge unless they already exist""" #open xenapi session diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 7f437c2b8..0f3b9ce20 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -38,6 +38,8 @@ from nova.tests.db import fakes as db_fakes from nova.tests.xenapi import stubs from nova.tests.glance import stubs as glance_stubs +from nova import log as LOG + FLAGS = flags.FLAGS @@ -297,6 +299,16 @@ class XenAPIVMTestCase(test.TestCase): glance_stubs.FakeGlance.IMAGE_KERNEL, glance_stubs.FakeGlance.IMAGE_RAMDISK) + def test_spawn_vlanmanager(self): + self.flags(xenapi_image_service = 'glance', + network_manager='nova.network.manager.VlanManager', + network_driver='nova.network.xenapi_net') + LOG.debug("Self.network:%s",self.network) + self._test_spawn(glance_stubs.FakeGlance.IMAGE_MACHINE, + glance_stubs.FakeGlance.IMAGE_KERNEL, + glance_stubs.FakeGlance.IMAGE_RAMDISK) + pass + def tearDown(self): super(XenAPIVMTestCase, self).tearDown() self.manager.delete_project(self.project) diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 9140774c5..66df3c28e 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -236,8 +236,7 @@ class VMOps(object): """Create snapshot from a running VM instance :param instance: instance to be snapshotted - :param image_id: id of - image to upload to + :param image_id: id of image to upload to Steps involved in a XenServer snapshot: -- cgit From bb52b51d0e4f9b297dcc489562f38d1647e10856 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Wed, 16 Mar 2011 12:34:39 +0000 Subject: Adding unit test --- nova/network/manager.py | 2 ++ nova/network/xenapi_net.py | 3 +++ nova/tests/db/fakes.py | 45 +++++++++++++++++++++++++++---- nova/tests/test_xenapi.py | 22 ++++++++++++--- nova/virt/xenapi/fake.py | 67 ++++++++++++++++++++++++++++++++++++++++++---- nova/virt/xenapi/vmops.py | 2 +- 6 files changed, 127 insertions(+), 14 deletions(-) (limited to 'nova') diff --git a/nova/network/manager.py b/nova/network/manager.py index 4baea482b..3b53d5d05 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -115,6 +115,7 @@ class NetworkManager(manager.Manager): timeout_fixed_ips = True def __init__(self, network_driver=None, *args, **kwargs): + LOG.debug("INIT - network driver:%s", network_driver) if not network_driver: network_driver = FLAGS.network_driver self.driver = utils.import_object(network_driver) @@ -520,6 +521,7 @@ class VlanManager(NetworkManager): def setup_compute_network(self, context, instance_id): """Sets up matching network for compute hosts.""" LOG.debug("ENTERING SETUP COMPUTE NETWORK") + LOG.debug("DRIVER:%s",self.driver) network_ref = db.network_get_by_instance(context, instance_id) self.driver.ensure_vlan_bridge(network_ref['vlan'], network_ref['bridge']) diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index 01889f94d..49214764e 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -29,9 +29,12 @@ from nova.virt.xenapi.network_utils import NetworkHelper LOG = logging.getLogger("nova.xenapi_net") +FLAGS = flags.FLAGS + def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): """Create a vlan and bridge unless they already exist""" #open xenapi session + LOG.debug("ENTERING ensure_vlan_bridge in xenapi net") url = FLAGS.xenapi_connection_url username = FLAGS.xenapi_connection_username password = FLAGS.xenapi_connection_password diff --git a/nova/tests/db/fakes.py b/nova/tests/db/fakes.py index d760dc456..88daa82c3 100644 --- a/nova/tests/db/fakes.py +++ b/nova/tests/db/fakes.py @@ -23,8 +23,9 @@ from nova import db from nova import test from nova import utils +from nova import log as LOG -def stub_out_db_instance_api(stubs): +def stub_out_db_instance_api(stubs, injected=True): """ Stubs out the db API for creating Instances """ INSTANCE_TYPES = { @@ -36,6 +37,29 @@ def stub_out_db_instance_api(stubs): 'm1.xlarge': dict(memory_mb=16384, vcpus=8, local_gb=160, flavorid=5)} + flat_network_fields = { + 'id': 'fake_flat', + 'bridge': 'xenbr0', + 'label': 'fake_flat_network', + 'netmask': '255.255.255.0', + 'gateway': '10.0.0.1', + 'broadcast': '10.0.0.255', + 'dns': '10.0.0.2', + 'ra_server': None, + 'injected': injected} + + vlan_network_fields = { + 'id': 'fake_vlan', + 'bridge': 'br111', + 'label': 'fake_vlan_network', + 'netmask': '255.255.255.0', + 'gateway': '10.0.0.1', + 'broadcast': '10.0.0.255', + 'dns': '10.0.0.2', + 'ra_server': None, + 'vlan': 111, + 'injected': False} + class FakeModel(object): """ Stubs out for model """ def __init__(self, values): @@ -81,12 +105,23 @@ def stub_out_db_instance_api(stubs): return FakeModel(base_options) def fake_network_get_by_instance(context, instance_id): - fields = { - 'bridge': 'xenbr0', - } - return FakeModel(fields) + #even instance numbers are on vlan networks + if instance_id % 2 == 0: + return FakeModel(vlan_network_fields) + else: + return FakeModel(flat_network_fields) + + def fake_network_get_all_by_instance(context, instance_id): + l = [] + #even instance numbers are on vlan networks + if instance_id % 2 == 0: + l.append(FakeModel(vlan_network_fields)) + else: + l.append(FakeModel(flat_network_fields)) + return l stubs.Set(db, 'instance_create', fake_instance_create) stubs.Set(db, 'network_get_by_instance', fake_network_get_by_instance) + stubs.Set(db, 'network_get_all_by_instance', fake_network_get_all_by_instance) stubs.Set(db, 'instance_type_get_all', fake_instance_type_get_all) stubs.Set(db, 'instance_type_get_by_name', fake_instance_type_get_by_name) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 26fad39d1..2cdc84882 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -165,6 +165,7 @@ class XenAPIVMTestCase(test.TestCase): FLAGS.xenapi_connection_password = 'test_pass' xenapi_fake.reset() xenapi_fake.create_local_srs() + xenapi_fake.create_local_pifs() db_fakes.stub_out_db_instance_api(self.stubs) xenapi_fake.create_network('fake', FLAGS.flat_network_bridge) stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) @@ -252,6 +253,9 @@ class XenAPIVMTestCase(test.TestCase): # Check that the VM is running according to XenAPI. self.assertEquals(vm['power_state'], 'Running') + + # Check that VM network is consistent with nova network + LOG.debug("VM INFO - NETWORK:%s", vm_info) def _test_spawn(self, image_id, kernel_id, ramdisk_id, instance_type="m1.large"): @@ -301,13 +305,25 @@ class XenAPIVMTestCase(test.TestCase): def test_spawn_vlanmanager(self): self.flags(xenapi_image_service = 'glance', - network_manager='nova.network.manager.VlanManager', - network_driver='nova.network.xenapi_net') + network_manager = 'nova.network.manager.VlanManager', + network_driver = 'nova.network.xenapi_net', + vlan_interface = 'fake0') LOG.debug("Self.network:%s",self.network) + LOG.debug("network driver:%s",FLAGS.network_driver) + fake_instance_id = 2 + network_bk=self.network + #ensure we use xenapi_net driver + self.network = utils.import_object(FLAGS.network_manager) + self.network.setup_compute_network(None, fake_instance_id) self._test_spawn(glance_stubs.FakeGlance.IMAGE_MACHINE, glance_stubs.FakeGlance.IMAGE_KERNEL, glance_stubs.FakeGlance.IMAGE_RAMDISK) - pass + url = FLAGS.xenapi_connection_url + username = FLAGS.xenapi_connection_username + password = FLAGS.xenapi_connection_password + session = xenapi_conn.XenAPISession(url, username, password) + + self.network = network_bk def tearDown(self): super(XenAPIVMTestCase, self).tearDown() diff --git a/nova/virt/xenapi/fake.py b/nova/virt/xenapi/fake.py index ba12d4d3a..2e8cd9c5c 100644 --- a/nova/virt/xenapi/fake.py +++ b/nova/virt/xenapi/fake.py @@ -61,7 +61,7 @@ from nova import log as logging _CLASSES = ['host', 'network', 'session', 'SR', 'VBD',\ - 'PBD', 'VDI', 'VIF', 'VM', 'task'] + 'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task'] _db_content = {} @@ -103,7 +103,6 @@ def create_vm(name_label, status, 'is_control_domain': is_control_domain, }) - def destroy_vm(vm_ref): vm_rec = _db_content['VM'][vm_ref] @@ -178,6 +177,12 @@ def create_task(name_label): }) +def create_local_pifs(): + """Adds a PIF for each to the local database with VLAN=-1. + Do this one per host.""" + for host_ref in _db_content['host'].keys(): + _create_local_pif(host_ref) + def create_local_srs(): """Create an SR that looks like the one created on the local disk by default by the XenServer installer. Do this one per host.""" @@ -204,8 +209,18 @@ def _create_local_sr(host_ref): _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] return sr_ref +def _create_local_pif(host_ref): + pif_ref= _create_object('PIF', { + 'name-label': 'Fake PIF', + 'MAC': '00:11:22:33:44:55', + 'physical': True, + 'VLAN': -1, + 'device': 'fake0', + 'host_uuid': host_ref, + }) def _create_object(table, obj): + LOG.debug("ENTERING _create_object:%s", obj) ref = str(uuid.uuid4()) obj['uuid'] = str(uuid.uuid4()) _db_content[table][ref] = obj @@ -228,6 +243,24 @@ def _create_sr(table, obj): return sr_ref +def _create_vlan(pif_ref, vlan_num, network_ref): + LOG.debug("ENTERING FAKE CREATE VLAN") + pif_rec = get_record('PIF', pif_ref) + vlan_pif_ref = _create_object('PIF', { + 'name-label': 'Fake VLAN PIF', + 'MAC': '00:11:22:33:44:55', + 'physical': True, + 'VLAN': vlan_num, + 'device': pif_rec['device'], + 'host_uuid': pif_rec['host_uuid'], + }) + return _create_object('VLAN', { + 'tagged-pif': pif_ref, + 'untagged-pif': vlan_pif_ref, + 'tag': vlan_num + }) + + def get_all(table): return _db_content[table].keys() @@ -235,7 +268,6 @@ def get_all(table): def get_all_records(table): return _db_content[table] - def get_record(table, ref): if ref in _db_content[table]: return _db_content[table].get(ref) @@ -286,6 +318,26 @@ class SessionBase(object): rec['currently_attached'] = False rec['device'] = '' + def PIF_get_all_records_where(self, _1,_2): + # TODO (salvatore-orlando):filter table on _2 + return _db_content['PIF'] + + def VM_get_xenstore_data(self, _1, vm_ref): + return _db_content['VM'][vm_ref].get('xenstore_data', '') + + def VM_remove_from_xenstore_data(self, _1, vm_ref, key): + db_ref = _db_content['VM'][vm_ref] + if not 'xenstore_data' in db_ref: + return + db_ref['xenstore_data'][key] = None + + + def VM_add_to_xenstore_data(self, _1, 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 host_compute_free_memory(self, _1, ref): #Always return 12GB available return 12 * 1024 * 1024 * 1024 @@ -431,12 +483,17 @@ class SessionBase(object): def _create(self, name, params): self._check_session(params) is_sr_create = name == 'SR.create' + LOG.debug("NAME:%s",name) + is_vlan_create = name == 'VLAN.create' # Storage Repositories have a different API - expected = is_sr_create and 10 or 2 + expected = is_sr_create and 10 or is_vlan_create and 4 or 2 self._check_arg_count(params, expected) (cls, _) = name.split('.') ref = is_sr_create and \ - _create_sr(cls, params) or _create_object(cls, params[1]) + _create_sr(cls, params) or \ + is_vlan_create and \ + _create_vlan(params[1],params[2],params[3]) or \ + _create_object(cls, params[1]) # Call hook to provide any fixups needed (ex. creating backrefs) after_hook = 'after_%s_create' % cls diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 0813c3db4..4bfef20f3 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -772,7 +772,7 @@ class VMOps(object): if network_ref: try: device = "1" if instance._rescue else "0" - except AttributeError: + except (AttributeError, KeyError): device = "0" VMHelper.create_vif( -- cgit From f0bb48fc2f2e7d9326c51b4b57e73e0258930909 Mon Sep 17 00:00:00 2001 From: Salvatore Orlando Date: Wed, 23 Mar 2011 09:34:34 +0000 Subject: removed excess debug line --- nova/virt/xenapi/network_utils.py | 1 - 1 file changed, 1 deletion(-) (limited to 'nova') diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index 52ad0e1a5..546f6bea9 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -28,7 +28,6 @@ class NetworkHelper(HelperBase): """ The class that wraps the helper methods together. """ - @classmethod def find_network_with_name_label(cls, session, name_label): networks = session.call_xenapi('network.get_by_name_label', name_label) -- cgit From 8957914ad9dd7691b2a43d977d845e00f7dd48c4 Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Mon, 28 Mar 2011 10:54:29 +0100 Subject: addressed termies review (first round) --- nova/network/xenapi_net.py | 26 +++---- nova/tests/db/fakes.py | 8 +- nova/tests/fake_utils.py | 11 +-- nova/tests/fake_utils.py.moved | 106 --------------------------- nova/tests/test_xenapi.py | 37 +++++----- nova/virt/xenapi/network_utils.py | 2 +- nova/virt/xenapi/vmops.py | 149 ++++++++++++++++++++++---------------- 7 files changed, 125 insertions(+), 214 deletions(-) delete mode 100644 nova/tests/fake_utils.py.moved (limited to 'nova') diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index 1725a4b7a..7a9da8046 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -35,19 +35,19 @@ FLAGS = flags.FLAGS def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): - """Create a vlan and bridge unless they already exist""" - #open xenapi session + """Create a vlan and bridge unless they already exist.""" + # Open xenapi session LOG.debug("ENTERING ensure_vlan_bridge in xenapi net") url = FLAGS.xenapi_connection_url username = FLAGS.xenapi_connection_username password = FLAGS.xenapi_connection_password session = XenAPISession(url, username, password) - #check whether bridge already exists - #retrieve network whose name_label is "bridge" + # Check whether bridge already exists + # Retrieve network whose name_label is "bridge" network_ref = NetworkHelper.find_network_with_name_label(session, bridge) if network_ref == None: - #if bridge does not exists - #1 - create network + # If bridge does not exists + # 1 - create network description = "network for nova bridge %s" % bridge network_rec = { 'name_label': bridge, @@ -55,28 +55,28 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): 'other_config': {}, } network_ref = session.call_xenapi('network.create', network_rec) - #2 - find PIF for VLAN + # 2 - find PIF for VLAN expr = 'field "device" = "%s" and \ field "VLAN" = "-1"' % FLAGS.vlan_interface pifs = session.call_xenapi('PIF.get_all_records_where', expr) pif_ref = None - #multiple PIF are ok: we are dealing with a pool + # Multiple PIF are ok: we are dealing with a pool if len(pifs) == 0: raise Exception( _('Found no PIF for device %s') % FLAGS.vlan_interface) - #3 - create vlan for network + # 3 - create vlan for network for pif_ref in pifs.keys(): session.call_xenapi('VLAN.create', pif_ref, str(vlan_num), network_ref) else: - #check VLAN tag is appropriate + # Check VLAN tag is appropriate network_rec = session.call_xenapi('network.get_record', network_ref) - #retrieve PIFs from network + # Retrieve PIFs from network for pif_ref in network_rec['PIFs']: - #retrieve VLAN from PIF + # Retrieve VLAN from PIF pif_rec = session.call_xenapi('PIF.get_record', pif_ref) pif_vlan = int(pif_rec['VLAN']) - #raise an exception if VLAN <> vlan_num + # Raise an exception if VLAN <> vlan_num if pif_vlan != vlan_num: raise Exception(_("PIF %(pif_rec['uuid'])s for network " "%(bridge)s has VLAN id %(pif_vlan)d. " diff --git a/nova/tests/db/fakes.py b/nova/tests/db/fakes.py index 05a47d4c9..f7610aa56 100644 --- a/nova/tests/db/fakes.py +++ b/nova/tests/db/fakes.py @@ -25,7 +25,7 @@ from nova import utils def stub_out_db_instance_api(stubs, injected=True): - """ Stubs out the db API for creating Instances """ + """Stubs out the db API for creating Instances.""" INSTANCE_TYPES = { 'm1.tiny': dict(memory_mb=512, @@ -91,7 +91,7 @@ def stub_out_db_instance_api(stubs, injected=True): 'network_id': 'fake_flat'} class FakeModel(object): - """ Stubs out for model """ + """Stubs out for model.""" def __init__(self, values): self.values = values @@ -111,7 +111,7 @@ def stub_out_db_instance_api(stubs, injected=True): return INSTANCE_TYPES[name] def fake_network_get_by_instance(context, instance_id): - #even instance numbers are on vlan networks + # Even instance numbers are on vlan networks if instance_id % 2 == 0: return FakeModel(vlan_network_fields) else: @@ -119,7 +119,7 @@ def stub_out_db_instance_api(stubs, injected=True): return FakeModel(network_fields) def fake_network_get_all_by_instance(context, instance_id): - #even instance numbers are on vlan networks + # Even instance numbers are on vlan networks if instance_id % 2 == 0: return [FakeModel(vlan_network_fields)] else: diff --git a/nova/tests/fake_utils.py b/nova/tests/fake_utils.py index 823c775cb..23996ba95 100644 --- a/nova/tests/fake_utils.py +++ b/nova/tests/fake_utils.py @@ -14,8 +14,7 @@ # License for the specific language governing permissions and limitations # under the License. -"""This modules stubs out functions in nova.utils -""" +"""This modules stubs out functions in nova.utils.""" import re import types @@ -42,22 +41,20 @@ def fake_execute_clear_log(): def fake_execute_set_repliers(repliers): - """Allows the client to configure replies to commands""" + """Allows the client to configure replies to commands.""" global _fake_execute_repliers _fake_execute_repliers = repliers def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs): """A reply handler for commands that haven't been added to the reply - list. Returns empty strings for stdout and stderr - """ + list. Returns empty strings for stdout and stderr.""" return '', '' def fake_execute(*cmd_parts, **kwargs): """This function stubs out execute, optionally executing - a preconfigued function to return expected data - """ + a preconfigued function to return expected data.""" global _fake_execute_repliers process_input = kwargs.get('process_input', None) diff --git a/nova/tests/fake_utils.py.moved b/nova/tests/fake_utils.py.moved deleted file mode 100644 index 8982f50be..000000000 --- a/nova/tests/fake_utils.py.moved +++ /dev/null @@ -1,106 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright (c) 2011 Citrix Systems, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""This modules stubs out functions in nova.utils -""" - -import re -import types - -from eventlet import greenthread - -from nova import exception -from nova import log as logging -from nova import utils - -LOG = logging.getLogger('nova.tests.fake_utils') - -_fake_execute_repliers = [] -_fake_execute_log = [] - - -def fake_execute_get_log(): - global _fake_execute_log - return _fake_execute_log - - -def fake_execute_clear_log(): - global _fake_execute_log - _fake_execute_log = [] - - -def fake_execute_set_repliers(repliers): - """Allows the client to configure replies to commands""" - global _fake_execute_repliers - _fake_execute_repliers = repliers - - -def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs): - """A reply handler for commands that haven't been added to the reply - list. Returns empty strings for stdout and stderr - """ - return '', '' - - -def fake_execute(*cmd, **kwargs): - """This function stubs out execute, optionally executing - a preconfigued function to return expected data - """ - global _fake_execute_repliers - - process_input = kwargs.get('process_input', None) - addl_env = kwargs.get('addl_env', None) - check_exit_code = kwargs.get('check_exit_code', 0) - cmd_map = map(str, cmd) - cmd_str = ' '.join(cmd_map) - - LOG.debug(_("Faking execution of cmd (subprocess): %s"), cmd_str) - _fake_execute_log.append(cmd_str) - - reply_handler = fake_execute_default_reply_handler - - for fake_replier in _fake_execute_repliers: - if re.match(fake_replier[0], cmd_str): - reply_handler = fake_replier[1] - LOG.debug(_('Faked command matched %s') % fake_replier[0]) - break - - if isinstance(reply_handler, types.StringTypes): - # If the reply handler is a string, return it as stdout - reply = reply_handler, '' - else: - try: - # Alternative is a function, so call it - reply = reply_handler(cmd, - process_input=process_input, - addl_env=addl_env, - check_exit_code=check_exit_code) - except exception.ProcessExecutionError as e: - LOG.debug(_('Faked command raised an exception %s' % str(e))) - raise - - LOG.debug(_("Reply to faked command is stdout='%(0)s' stderr='%(1)s'") % - {'0': reply[0], '1': reply[1]}) - - # Replicate the sleep call in the real function - greenthread.sleep(0) - return reply - - -def stub_out_utils_execute(stubs): - fake_execute_set_repliers([]) - fake_execute_clear_log() - stubs.Set(utils, 'execute', fake_execute) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index f91f37d4b..6ec0525a7 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -15,7 +15,7 @@ # under the License. """ -Test suite for XenAPI +Test suite for XenAPI. """ import functools @@ -66,7 +66,7 @@ def stub_vm_utils_with_vdi_attached_here(function, should_return=True): class XenAPIVolumeTestCase(test.TestCase): """ - Unit tests for Volume operations + Unit tests for Volume operations. """ def setUp(self): super(XenAPIVolumeTestCase, self).setUp() @@ -76,7 +76,6 @@ class XenAPIVolumeTestCase(test.TestCase): FLAGS.xenapi_connection_url = 'test_url' FLAGS.xenapi_connection_password = 'test_pass' db_fakes.stub_out_db_instance_api(self.stubs) - #db_fakes.stub_out_db_network_api(self.stubs) stubs.stub_out_get_target(self.stubs) xenapi_fake.reset() self.values = {'id': 1, @@ -102,7 +101,7 @@ class XenAPIVolumeTestCase(test.TestCase): return db.volume_create(self.context, vol) def test_create_iscsi_storage(self): - """ This shows how to test helper classes' methods """ + """This shows how to test helper classes' methods.""" stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeTests) session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass') helper = volume_utils.VolumeHelper @@ -117,7 +116,7 @@ class XenAPIVolumeTestCase(test.TestCase): db.volume_destroy(context.get_admin_context(), vol['id']) def test_parse_volume_info_raise_exception(self): - """ This shows how to test helper classes' methods """ + """This shows how to test helper classes' methods.""" stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeTests) session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass') helper = volume_utils.VolumeHelper @@ -131,7 +130,7 @@ class XenAPIVolumeTestCase(test.TestCase): db.volume_destroy(context.get_admin_context(), vol['id']) def test_attach_volume(self): - """ This shows how to test Ops classes' methods """ + """This shows how to test Ops classes' methods.""" stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeTests) conn = xenapi_conn.get_connection(False) volume = self._create_volume() @@ -150,7 +149,7 @@ class XenAPIVolumeTestCase(test.TestCase): check() def test_attach_volume_raise_exception(self): - """ This shows how to test when exceptions are raised """ + """This shows how to test when exceptions are raised.""" stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeFailedTests) conn = xenapi_conn.get_connection(False) @@ -174,7 +173,7 @@ def reset_network(*args): class XenAPIVMTestCase(test.TestCase): """ - Unit tests for VM operations + Unit tests for VM operations. """ def setUp(self): super(XenAPIVMTestCase, self).setUp() @@ -475,21 +474,21 @@ class XenAPIVMTestCase(test.TestCase): network_manager='nova.network.manager.VlanManager', network_driver='nova.network.xenapi_net', vlan_interface='fake0') - #reset network table + # Reset network table xenapi_fake.reset_table('network') - #instance id = 2 will use vlan network (see db/fakes.py) + # Instance id = 2 will use vlan network (see db/fakes.py) fake_instance_id = 2 network_bk = self.network - #ensure we use xenapi_net driver + # Ensure we use xenapi_net driver self.network = utils.import_object(FLAGS.network_manager) self.network.setup_compute_network(None, fake_instance_id) self._test_spawn(glance_stubs.FakeGlance.IMAGE_MACHINE, glance_stubs.FakeGlance.IMAGE_KERNEL, glance_stubs.FakeGlance.IMAGE_RAMDISK, instance_id=fake_instance_id) - #TODO(salvatore-orlando): a complete test here would require - #a check for making sure the bridge for the VM's VIF is - #consistent with bridge specified in nova db + # TODO(salvatore-orlando): a complete test here would require + # A check for making sure the bridge for the VM's VIF is + # consistent with bridge specified in nova db self.network = network_bk def test_spawn_with_network_qos(self): @@ -521,7 +520,7 @@ class XenAPIVMTestCase(test.TestCase): self.stubs.UnsetAll() def _create_instance(self): - """Creates and spawns a test instance""" + """Creates and spawns a test instance.""" stubs.stubout_loopingcall_start(self.stubs) values = { 'id': 1, @@ -540,7 +539,7 @@ class XenAPIVMTestCase(test.TestCase): class XenAPIDiffieHellmanTestCase(test.TestCase): """ - Unit tests for Diffie-Hellman code + Unit tests for Diffie-Hellman code. """ def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() @@ -566,7 +565,7 @@ class XenAPIDiffieHellmanTestCase(test.TestCase): class XenAPIMigrateInstance(test.TestCase): """ - Unit test for verifying migration-related actions + Unit test for verifying migration-related actions. """ def setUp(self): @@ -623,7 +622,7 @@ class XenAPIMigrateInstance(test.TestCase): class XenAPIDetermineDiskImageTestCase(test.TestCase): """ - Unit tests for code that detects the ImageType + Unit tests for code that detects the ImageType. """ def setUp(self): super(XenAPIDetermineDiskImageTestCase, self).setUp() @@ -644,7 +643,7 @@ class XenAPIDetermineDiskImageTestCase(test.TestCase): def test_instance_disk(self): """ - If a kernel is specified then the image type is DISK (aka machine) + If a kernel is specified then the image type is DISK (aka machine). """ FLAGS.xenapi_image_service = 'objectstore' self.fake_instance.image_id = glance_stubs.FakeGlance.IMAGE_MACHINE diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index 546f6bea9..94d8e5199 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -44,7 +44,7 @@ class NetworkHelper(HelperBase): """ Return the network on which the bridge is attached, if found. The bridge is defined in the nova db and can be found either in the - 'bridge' or 'name_label' fields of the XenAPI network record + 'bridge' or 'name_label' fields of the XenAPI network record. """ expr = 'field "name__label" = "%s" or ' \ 'field "bridge" = "%s"' % (bridge, bridge) diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 52e1f9eba..9b18ac732 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -58,7 +58,7 @@ class VMOps(object): VMHelper.XenAPI = self.XenAPI def list_instances(self): - """List VM instances""" + """List VM instances.""" # TODO(justinsb): Should we just always use the details method? # Seems to be the same number of API calls.. vm_refs = [] @@ -69,7 +69,7 @@ class VMOps(object): return vm_refs def list_instances_detail(self): - """List VM instances, returning InstanceInfo objects""" + """List VM instances, returning InstanceInfo objects.""" instance_infos = [] for vm_ref in self._session.get_xenapi().VM.get_all(): vm_rec = self._session.get_xenapi().VM.get_record(vm_ref) @@ -119,11 +119,11 @@ class VMOps(object): self._spawn(instance, vm_ref) def spawn_rescue(self, instance): - """Spawn a rescue instance""" + """Spawn a rescue instance.""" self.spawn(instance) def _create_vm(self, instance, vdi_uuid, network_info=None): - """Create VM instance""" + """Create VM instance.""" instance_name = instance.name vm_ref = VMHelper.lookup(self._session, instance_name) if vm_ref is not None: @@ -180,7 +180,7 @@ class VMOps(object): return vm_ref def _spawn(self, instance, vm_ref): - """Spawn a new instance""" + """Spawn a new instance.""" LOG.debug(_('Starting VM %s...'), vm_ref) self._start(instance, vm_ref) instance_name = instance.name @@ -236,7 +236,8 @@ class VMOps(object): return timer.start(interval=0.5, now=True) def _get_vm_opaque_ref(self, instance_or_vm): - """Refactored out the common code of many methods that receive either + """ + Refactored out the common code of many methods that receive either a vm name or a vm instance, and want a vm instance in return. """ # if instance_or_vm is a string it must be opaque ref or instance name @@ -264,21 +265,22 @@ class VMOps(object): return vm_ref def _acquire_bootlock(self, vm): - """Prevent an instance from booting""" + """Prevent an instance from booting.""" self._session.call_xenapi( "VM.set_blocked_operations", vm, {"start": ""}) def _release_bootlock(self, vm): - """Allow an instance to boot""" + """Allow an instance to boot.""" self._session.call_xenapi( "VM.remove_from_blocked_operations", vm, "start") def snapshot(self, instance, image_id): - """Create snapshot from a running VM instance + """ + Create snapshot from a running VM instance :param instance: instance to be snapshotted :param image_id: id of image to upload to @@ -330,11 +332,12 @@ class VMOps(object): return def migrate_disk_and_power_off(self, instance, dest): - """Copies a VHD from one host machine to another + """ + Copies a VHD from one host machine to another - :param instance: the instance that owns the VHD in question - :param dest: the destination host machine - :param disk_type: values are 'primary' or 'cow' + :param instance: the instance that owns the VHD in question. + :param dest: the destination host machine. + :param disk_type: values are 'primary' or 'cow'. """ vm_ref = VMHelper.lookup(self._session, instance.name) @@ -383,7 +386,7 @@ class VMOps(object): return {'base_copy': base_copy_uuid, 'cow': cow_uuid} def link_disks(self, instance, base_copy_uuid, cow_uuid): - """Links the base copy VHD to the COW via the XAPI plugin""" + """Links the base copy VHD to the COW via the XAPI plugin.""" vm_ref = VMHelper.lookup(self._session, instance.name) new_base_copy_uuid = str(uuid.uuid4()) new_cow_uuid = str(uuid.uuid4()) @@ -404,7 +407,7 @@ class VMOps(object): return new_cow_uuid def resize_instance(self, instance, vdi_uuid): - """Resize a running instance by changing it's RAM and disk size """ + """Resize a running instance by changing it's RAM and disk size.""" #TODO(mdietz): this will need to be adjusted for swap later #The new disk size must be in bytes @@ -418,13 +421,14 @@ class VMOps(object): LOG.debug(_("Resize instance %s complete") % (instance.name)) def reboot(self, instance): - """Reboot VM instance""" + """Reboot VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.clean_reboot', vm_ref) self._session.wait_for_task(task, instance.id) def set_admin_password(self, instance, new_pass): - """Set the root/admin password on the VM instance. This is done via + """ + Set the root/admin password on the VM instance. This is done via an agent running on the VM. Communication between nova and the agent is done via writing xenstore records. Since communication is done over the XenAPI RPC calls, we need to encrypt the password. We're using a @@ -462,7 +466,8 @@ class VMOps(object): return resp_dict['message'] def inject_file(self, instance, path, contents): - """Write a file to the VM instance. The path to which it is to be + """ + Write a file to the VM instance. The path to which it is to be written and the contents of the file need to be supplied; both will be base64-encoded to prevent errors with non-ASCII characters being transmitted. If the agent does not support file injection, or the user @@ -487,7 +492,7 @@ class VMOps(object): return resp_dict['message'] def _shutdown(self, instance, vm_ref, hard=True): - """Shutdown an instance""" + """Shutdown an instance.""" state = self.get_info(instance['name'])['state'] if state == power_state.SHUTDOWN: instance_name = instance.name @@ -511,11 +516,11 @@ class VMOps(object): LOG.exception(exc) def _shutdown_rescue(self, rescue_vm_ref): - """Shutdown a rescue instance""" + """Shutdown a rescue instance.""" self._session.call_xenapi("Async.VM.hard_shutdown", rescue_vm_ref) def _destroy_vdis(self, instance, vm_ref): - """Destroys all VDIs associated with a VM""" + """Destroys all VDIs associated with a VM.""" instance_id = instance.id LOG.debug(_("Destroying VDIs for Instance %(instance_id)s") % locals()) @@ -532,7 +537,7 @@ class VMOps(object): LOG.exception(exc) def _destroy_rescue_vdis(self, rescue_vm_ref): - """Destroys all VDIs associated with a rescued VM""" + """Destroys all VDIs associated with a rescued VM.""" vdi_refs = VMHelper.lookup_vm_vdis(self._session, rescue_vm_ref) for vdi_ref in vdi_refs: try: @@ -541,7 +546,7 @@ class VMOps(object): continue def _destroy_rescue_vbds(self, rescue_vm_ref): - """Destroys all VBDs tied to a rescue VM""" + """Destroys all VBDs tied to a rescue VM.""" vbd_refs = self._session.get_xenapi().VM.get_VBDs(rescue_vm_ref) for vbd_ref in vbd_refs: vbd_rec = self._session.get_xenapi().VBD.get_record(vbd_ref) @@ -589,7 +594,7 @@ class VMOps(object): LOG.debug(_("kernel/ramdisk files removed")) def _destroy_vm(self, instance, vm_ref): - """Destroys a VM record""" + """Destroys a VM record.""" instance_id = instance.id try: task = self._session.call_xenapi('Async.VM.destroy', vm_ref) @@ -600,7 +605,7 @@ class VMOps(object): LOG.debug(_("Instance %(instance_id)s VM destroyed") % locals()) def _destroy_rescue_instance(self, rescue_vm_ref): - """Destroy a rescue instance""" + """Destroy a rescue instance.""" self._destroy_rescue_vbds(rescue_vm_ref) self._shutdown_rescue(rescue_vm_ref) self._destroy_rescue_vdis(rescue_vm_ref) @@ -624,10 +629,10 @@ class VMOps(object): """ Destroys VM instance by performing: - 1. A shutdown if requested - 2. Destroying associated VDIs - 3. Destroying kernel and ramdisk files (if necessary) - 4. Destroying that actual VM record + 1. A shutdown if requested. + 2. Destroying associated VDIs. + 3. Destroying kernel and ramdisk files (if necessary). + 4. Destroying that actual VM record. """ if vm_ref is None: LOG.warning(_("VM is not present, skipping destroy...")) @@ -650,36 +655,36 @@ class VMOps(object): callback(ret) def pause(self, instance, callback): - """Pause VM instance""" + """Pause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.pause', vm_ref) self._wait_with_callback(instance.id, task, callback) def unpause(self, instance, callback): - """Unpause VM instance""" + """Unpause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.unpause', vm_ref) self._wait_with_callback(instance.id, task, callback) def suspend(self, instance, callback): - """suspend the specified instance""" + """Suspend the specified instance""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.suspend', vm_ref) self._wait_with_callback(instance.id, task, callback) def resume(self, instance, callback): - """resume the specified instance""" + """Resume the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.resume', vm_ref, False, True) self._wait_with_callback(instance.id, task, callback) def rescue(self, instance, callback): - """Rescue the specified instance - - shutdown the instance VM - - set 'bootlock' to prevent the instance from starting in rescue - - spawn a rescue VM (the vm name-label will be instance-N-rescue) - + """ + Rescue the specified instance + - shutdown the instance VM. + - set 'bootlock' to prevent the instance from starting in rescue. + - spawn a rescue VM (the vm name-label will be instance-N-rescue). """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) @@ -703,9 +708,9 @@ class VMOps(object): def unrescue(self, instance, callback): """Unrescue the specified instance - - unplug the instance VM's disk from the rescue VM - - teardown the rescue VM - - release the bootlock to allow the instance VM to start + - unplug the instance VM's disk from the rescue VM. + - teardown the rescue VM. + - release the bootlock to allow the instance VM to start. """ rescue_vm_ref = VMHelper.lookup(self._session, @@ -723,7 +728,8 @@ class VMOps(object): self._start(instance, original_vm_ref) def poll_rescued_instances(self, timeout): - """Look for expirable rescued instances + """ + Look for expirable rescued instances - forcibly exit rescue mode for any instances that have been in rescue mode for >= the provided timeout """ @@ -761,30 +767,30 @@ class VMOps(object): False) def get_info(self, instance): - """Return data about VM instance""" + """Return data about VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.get_xenapi().VM.get_record(vm_ref) return VMHelper.compile_info(vm_rec) def get_diagnostics(self, instance): - """Return data about VM diagnostics""" + """Return data about VM diagnostics.""" vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.get_xenapi().VM.get_record(vm_ref) return VMHelper.compile_diagnostics(self._session, vm_rec) def get_console_output(self, instance): - """Return snapshot of console""" + """Return snapshot of console.""" # TODO: implement this to fix pylint! return 'FAKE CONSOLE OUTPUT of instance' def get_ajax_console(self, instance): - """Return link to instance's ajax console""" + """Return link to instance's ajax console.""" # TODO: implement this! return 'http://fakeajaxconsole/fake_url' # TODO(tr3buchet) - remove this function after nova multi-nic def _get_network_info(self, instance): - """creates network info list for instance""" + """Creates network info list for instance.""" admin_context = context.get_admin_context() IPs = db.fixed_ip_get_all_by_instance(admin_context, instance['id']) @@ -826,7 +832,7 @@ class VMOps(object): def inject_network_info(self, instance, vm_ref, network_info): """ Generate the network info and make calls to place it into the - xenstore and the xenstore param list + xenstore and the xenstore param list. """ logging.debug(_("injecting network info to xs for vm: |%s|"), vm_ref) @@ -847,7 +853,7 @@ class VMOps(object): pass def create_vifs(self, vm_ref, network_info): - """Creates vifs for an instance""" + """Creates vifs for an instance.""" logging.debug(_("creating vif(s) for vm: |%s|"), vm_ref) # this function raises if vm_ref is not a vm_opaque_ref @@ -872,7 +878,8 @@ class VMOps(object): args, vm_ref) def list_from_xenstore(self, vm, path): - """Runs the xenstore-ls command to get a listing of all records + """ + Runs the xenstore-ls command to get a listing of all records from 'path' downward. Returns a dict with the sub-paths as keys, and the value stored in those paths as values. If nothing is found at that path, returns None. @@ -881,7 +888,8 @@ class VMOps(object): return json.loads(ret) def read_from_xenstore(self, vm, path): - """Returns the value stored in the xenstore record for the given VM + """ + Returns the value stored in the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the read process. """ @@ -897,7 +905,8 @@ class VMOps(object): return ret def write_to_xenstore(self, vm, path, value): - """Writes the passed value to the xenstore record for the given VM + """ + Writes the passed value to the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the write process. """ @@ -905,7 +914,8 @@ class VMOps(object): {'value': json.dumps(value)}) def clear_xenstore(self, vm, path): - """Deletes the VM's xenstore record for the specified path. + """ + Deletes the VM's xenstore record for the specified path. If there is no such record, the request is ignored. """ self._make_xenstore_call('delete_record', vm, path) @@ -922,7 +932,8 @@ class VMOps(object): def _make_plugin_call(self, plugin, method, vm, path, addl_args=None, vm_ref=None): - """Abstracts out the process of calling a method of a xenapi plugin. + """ + Abstracts out the process of calling a method of a xenapi plugin. Any errors raised by the plugin will in turn raise a RuntimeError here. """ instance_id = vm.id @@ -952,7 +963,8 @@ class VMOps(object): return ret def add_to_xenstore(self, vm, path, key, value): - """Adds the passed key/value pair to the xenstore record for + """ + Adds the passed key/value pair to the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the write process. """ @@ -965,7 +977,8 @@ class VMOps(object): self.write_to_xenstore(vm, path, current) def remove_from_xenstore(self, vm, path, key_or_keys): - """Takes either a single key or a list of keys and removes + """ + Takes either a single key or a list of keys and removes them from the xenstoreirecord data for the given VM. If the key doesn't exist, the request is ignored. """ @@ -992,7 +1005,8 @@ class VMOps(object): ###### names to distinguish them. (dabo) ######################################################################## def read_partial_from_param_xenstore(self, instance_or_vm, key_prefix): - """Returns a dict of all the keys in the xenstore parameter record + """ + Returns a dict of all the keys in the xenstore parameter record for the given instance that begin with the key_prefix. """ data = self.read_from_param_xenstore(instance_or_vm) @@ -1003,7 +1017,8 @@ class VMOps(object): return data def read_from_param_xenstore(self, instance_or_vm, keys=None): - """Returns the xenstore parameter record data for the specified VM + """ + Returns the xenstore parameter record data for the specified VM instance as a dict. Accepts an optional key or list of keys; if a value for 'keys' is passed, the returned dict is filtered to only return the values for those keys. @@ -1025,9 +1040,11 @@ class VMOps(object): return ret def add_to_param_xenstore(self, instance_or_vm, key, val): - """Takes a key/value pair and adds it to the xenstore parameter + """ + Takes a key/value pair and adds it to the xenstore parameter record for the given vm instance. If the key exists in xenstore, - it is overwritten""" + it is overwritten + """ vm_ref = self._get_vm_opaque_ref(instance_or_vm) self.remove_from_param_xenstore(instance_or_vm, key) jsonval = json.dumps(val) @@ -1035,7 +1052,8 @@ class VMOps(object): (vm_ref, key, jsonval)) def write_to_param_xenstore(self, instance_or_vm, mapping): - """Takes a dict and writes each key/value pair to the xenstore + """ + Takes a dict and writes each key/value pair to the xenstore parameter record for the given vm instance. Any existing data for those keys is overwritten. """ @@ -1043,7 +1061,8 @@ class VMOps(object): self.add_to_param_xenstore(instance_or_vm, k, v) def remove_from_param_xenstore(self, instance_or_vm, key_or_keys): - """Takes either a single key or a list of keys and removes + """ + Takes either a single key or a list of keys and removes them from the xenstore parameter record data for the given VM. If the key doesn't exist, the request is ignored. """ @@ -1069,7 +1088,8 @@ def _runproc(cmd): class SimpleDH(object): - """This class wraps all the functionality needed to implement + """ + This class wraps all the functionality needed to implement basic Diffie-Hellman-Merkle key exchange in Python. It features intelligent defaults for the prime and base numbers needed for the calculation, while allowing you to supply your own. It requires that @@ -1078,7 +1098,8 @@ class SimpleDH(object): is not available, a RuntimeError will be raised. """ def __init__(self, prime=None, base=None, secret=None): - """You can specify the values for prime and base if you wish; + """ + You can specify the values for prime and base if you wish; otherwise, reasonable default values will be used. """ if prime is None: -- cgit From df946c08acba6fe1234b13f04d3c46c3973647c2 Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Mon, 28 Mar 2011 11:52:28 +0100 Subject: addressed termie's review (second round) --- nova/network/xenapi_net.py | 14 ++-- nova/tests/test_xenapi.py | 2 +- nova/virt/xenapi/fake.py | 156 +++++++++++++++++++++------------------------ nova/virt/xenapi/vmops.py | 2 +- 4 files changed, 82 insertions(+), 92 deletions(-) (limited to 'nova') diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index 7a9da8046..8603fd842 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -49,11 +49,9 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): # If bridge does not exists # 1 - create network description = "network for nova bridge %s" % bridge - network_rec = { - 'name_label': bridge, + network_rec = {'name_label': bridge, 'name_description': description, - 'other_config': {}, - } + 'other_config': {}} network_ref = session.call_xenapi('network.create', network_rec) # 2 - find PIF for VLAN expr = 'field "device" = "%s" and \ @@ -66,8 +64,10 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): _('Found no PIF for device %s') % FLAGS.vlan_interface) # 3 - create vlan for network for pif_ref in pifs.keys(): - session.call_xenapi('VLAN.create', pif_ref, - str(vlan_num), network_ref) + session.call_xenapi('VLAN.create', + pif_ref, + str(vlan_num), + network_ref) else: # Check VLAN tag is appropriate network_rec = session.call_xenapi('network.get_record', network_ref) @@ -76,7 +76,7 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): # Retrieve VLAN from PIF pif_rec = session.call_xenapi('PIF.get_record', pif_ref) pif_vlan = int(pif_rec['VLAN']) - # Raise an exception if VLAN <> vlan_num + # Raise an exception if VLAN != vlan_num if pif_vlan != vlan_num: raise Exception(_("PIF %(pif_rec['uuid'])s for network " "%(bridge)s has VLAN id %(pif_vlan)d. " diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 6ec0525a7..9fdd1feeb 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -487,7 +487,7 @@ class XenAPIVMTestCase(test.TestCase): glance_stubs.FakeGlance.IMAGE_RAMDISK, instance_id=fake_instance_id) # TODO(salvatore-orlando): a complete test here would require - # A check for making sure the bridge for the VM's VIF is + # a check for making sure the bridge for the VM's VIF is # consistent with bridge specified in nova db self.network = network_bk diff --git a/nova/virt/xenapi/fake.py b/nova/virt/xenapi/fake.py index 6d17a642e..d084c725f 100644 --- a/nova/virt/xenapi/fake.py +++ b/nova/virt/xenapi/fake.py @@ -78,7 +78,10 @@ def reset(): for c in _CLASSES: _db_content[c] = {} create_host('fake') - create_vm('fake', 'Running', is_a_template=False, is_control_domain=True) + create_vm('fake', + 'Running', + is_a_template=False, + is_control_domain=True) def reset_table(table): @@ -88,26 +91,23 @@ def reset_table(table): def create_host(name_label): - return _create_object('host', { - 'name_label': name_label, - }) + return _create_object('host', + {'name_label': name_label}) def create_network(name_label, bridge): - return _create_object('network', { - 'name_label': name_label, - 'bridge': bridge, - }) + return _create_object('network', + {'name_label': name_label, + 'bridge': bridge}) def create_vm(name_label, status, is_a_template=False, is_control_domain=False): - return _create_object('VM', { - 'name_label': name_label, - 'power-state': status, - 'is_a_template': is_a_template, - 'is_control_domain': is_control_domain, - }) + return _create_object('VM', + {'name_label': name_label, + 'power-state': status, + 'is_a_template': is_a_template, + 'is_control_domain': is_control_domain}) def destroy_vm(vm_ref): @@ -129,27 +129,24 @@ def destroy_vdi(vdi_ref): def create_vdi(name_label, read_only, sr_ref, sharable): - return _create_object('VDI', { - 'name_label': name_label, - 'read_only': read_only, - 'SR': sr_ref, - 'type': '', - 'name_description': '', - 'sharable': sharable, - 'other_config': {}, - 'location': '', - 'xenstore_data': '', - 'sm_config': {}, - 'VBDs': {}, - }) + return _create_object('VDI', + {'name_label': name_label, + 'read_only': read_only, + 'SR': sr_ref, + 'type': '', + 'name_description': '', + 'sharable': sharable, + 'other_config': {}, + 'location': '', + 'xenstore_data': '', + 'sm_config': {}, + 'VBDs': {}}) def create_vbd(vm_ref, vdi_ref): - vbd_rec = { - 'VM': vm_ref, - 'VDI': vdi_ref, - 'currently_attached': False, - } + vbd_rec = {'VM': vm_ref, + 'VDI': vdi_ref, + 'currently_attached': False} vbd_ref = _create_object('VBD', vbd_rec) after_VBD_create(vbd_ref, vbd_rec) return vbd_ref @@ -175,19 +172,17 @@ def after_VM_create(vm_ref, vm_rec): def create_pbd(config, host_ref, sr_ref, attached): - return _create_object('PBD', { - 'device-config': config, - 'host': host_ref, - 'SR': sr_ref, - 'currently-attached': attached, - }) + return _create_object('PBD', + {'device-config': config, + 'host': host_ref, + 'SR': sr_ref, + 'currently-attached': attached}) def create_task(name_label): - return _create_object('task', { - 'name_label': name_label, - 'status': 'pending', - }) + return _create_object('task', + {'name_label': name_label, + 'status': 'pending'}) def create_local_pifs(): @@ -205,34 +200,32 @@ def create_local_srs(): def _create_local_sr(host_ref): - sr_ref = _create_object('SR', { - 'name_label': 'Local storage', - 'type': 'lvm', - 'content_type': 'user', - 'shared': False, - 'physical_size': str(1 << 30), - 'physical_utilisation': str(0), - 'virtual_allocation': str(0), - 'other_config': { - 'i18n-original-value-name_label': 'Local storage', - 'i18n-key': 'local-storage', - }, - 'VDIs': [] - }) + sr_ref = \ + _create_object('SR', + {'name_label': 'Local storage', + 'type': 'lvm', + 'content_type': 'user', + 'shared': False, + 'physical_size': str(1 << 30), + 'physical_utilisation': str(0), + 'virtual_allocation': str(0), + 'other_config': {'i18n-original-value-name_label': \ + 'Local storage', + 'i18n-key': 'local-storage'}, + 'VDIs': []}) pbd_ref = create_pbd('', host_ref, sr_ref, True) _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] return sr_ref def _create_local_pif(host_ref): - pif_ref = _create_object('PIF', { - 'name-label': 'Fake PIF', - 'MAC': '00:11:22:33:44:55', - 'physical': True, - 'VLAN': -1, - 'device': 'fake0', - 'host_uuid': host_ref, - }) + pif_ref = _create_object('PIF', + {'name-label': 'Fake PIF', + 'MAC': '00:11:22:33:44:55', + 'physical': True, + 'VLAN': -1, + 'device': 'fake0', + 'host_uuid': host_ref}) def _create_object(table, obj): @@ -260,19 +253,17 @@ def _create_sr(table, obj): def _create_vlan(pif_ref, vlan_num, network_ref): pif_rec = get_record('PIF', pif_ref) - vlan_pif_ref = _create_object('PIF', { - 'name-label': 'Fake VLAN PIF', - 'MAC': '00:11:22:33:44:55', - 'physical': True, - 'VLAN': vlan_num, - 'device': pif_rec['device'], - 'host_uuid': pif_rec['host_uuid'], - }) - return _create_object('VLAN', { - 'tagged-pif': pif_ref, - 'untagged-pif': vlan_pif_ref, - 'tag': vlan_num, - }) + vlan_pif_ref = _create_object('PIF', + {'name-label': 'Fake VLAN PIF', + 'MAC': '00:11:22:33:44:55', + 'physical': True, + 'VLAN': vlan_num, + 'device': pif_rec['device'], + 'host_uuid': pif_rec['host_uuid']}) + return _create_object('VLAN', + {'tagged-pif': pif_ref, + 'untagged-pif': vlan_pif_ref, + 'tag': vlan_num}) def get_all(table): @@ -334,7 +325,7 @@ class SessionBase(object): rec['device'] = '' def PIF_get_all_records_where(self, _1, _2): - # TODO (salvatore-orlando):filter table on _2 + # TODO (salvatore-orlando): filter table on _2 return _db_content['PIF'] def VM_get_xenstore_data(self, _1, vm_ref): @@ -347,7 +338,7 @@ class SessionBase(object): db_ref['xenstore_data'][key] = None def network_get_all_records_where(self, _1, _2): - # TODO (salvatore-orlando):filter table on _2 + # TODO (salvatore-orlando): filter table on _2 return _db_content['network'] def VM_add_to_xenstore_data(self, _1, vm_ref, key, value): @@ -385,10 +376,9 @@ class SessionBase(object): def _login(self, method, params): self._session = str(uuid.uuid4()) - _db_content['session'][self._session] = { - 'uuid': str(uuid.uuid4()), - 'this_host': _db_content['host'].keys()[0], - } + _db_content['session'][self._session] = \ + {'uuid': str(uuid.uuid4()), + 'this_host': _db_content['host'].keys()[0]} def _logout(self): s = self._session diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 9b18ac732..08046318e 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -338,6 +338,7 @@ class VMOps(object): :param instance: the instance that owns the VHD in question. :param dest: the destination host machine. :param disk_type: values are 'primary' or 'cow'. + """ vm_ref = VMHelper.lookup(self._session, instance.name) @@ -711,7 +712,6 @@ class VMOps(object): - unplug the instance VM's disk from the rescue VM. - teardown the rescue VM. - release the bootlock to allow the instance VM to start. - """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) -- cgit From 184fa8239d54d20ff294cdb019d07989ed3d6c4d Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Mon, 28 Mar 2011 12:08:43 +0100 Subject: addressed termies review (third round) --- nova/tests/db/fakes.py | 63 ++++++++++++++++++++++------------------------- nova/tests/test_xenapi.py | 26 +++++++++---------- nova/virt/xenapi/fake.py | 2 +- nova/virt/xenapi/vmops.py | 3 ++- 4 files changed, 46 insertions(+), 48 deletions(-) (limited to 'nova') diff --git a/nova/tests/db/fakes.py b/nova/tests/db/fakes.py index f7610aa56..7ddfe377a 100644 --- a/nova/tests/db/fakes.py +++ b/nova/tests/db/fakes.py @@ -56,39 +56,36 @@ def stub_out_db_instance_api(stubs, injected=True): flavorid=5, rxtx_cap=5)} - flat_network_fields = { - 'id': 'fake_flat', - 'bridge': 'xenbr0', - 'label': 'fake_flat_network', - 'netmask': '255.255.255.0', - 'cidr_v6': 'fe80::a00:0/120', - 'netmask_v6': '120', - 'gateway': '10.0.0.1', - 'gateway_v6': 'fe80::a00:1', - 'broadcast': '10.0.0.255', - 'dns': '10.0.0.2', - 'ra_server': None, - 'injected': injected} - - vlan_network_fields = { - 'id': 'fake_vlan', - 'bridge': 'br111', - 'label': 'fake_vlan_network', - 'netmask': '255.255.255.0', - 'cidr_v6': 'fe80::a00:0/120', - 'netmask_v6': '120', - 'gateway': '10.0.0.1', - 'gateway_v6': 'fe80::a00:1', - 'broadcast': '10.0.0.255', - 'dns': '10.0.0.2', - 'ra_server': None, - 'vlan': 111, - 'injected': False} - - fixed_ip_fields = { - 'address': '10.0.0.3', - 'address_v6': 'fe80::a00:3', - 'network_id': 'fake_flat'} + flat_network_fields = {'id': 'fake_flat', + 'bridge': 'xenbr0', + 'label': 'fake_flat_network', + 'netmask': '255.255.255.0', + 'cidr_v6': 'fe80::a00:0/120', + 'netmask_v6': '120', + 'gateway': '10.0.0.1', + 'gateway_v6': 'fe80::a00:1', + 'broadcast': '10.0.0.255', + 'dns': '10.0.0.2', + 'ra_server': None, + 'injected': injected} + + vlan_network_fields = {'id': 'fake_vlan', + 'bridge': 'br111', + 'label': 'fake_vlan_network', + 'netmask': '255.255.255.0', + 'cidr_v6': 'fe80::a00:0/120', + 'netmask_v6': '120', + 'gateway': '10.0.0.1', + 'gateway_v6': 'fe80::a00:1', + 'broadcast': '10.0.0.255', + 'dns': '10.0.0.2', + 'ra_server': None, + 'vlan': 111, + 'injected': False} + + fixed_ip_fields = {'address': '10.0.0.3', + 'address_v6': 'fe80::a00:3', + 'network_id': 'fake_flat'} class FakeModel(object): """Stubs out for model.""" diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 9fdd1feeb..bc1469223 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -287,19 +287,19 @@ class XenAPIVMTestCase(test.TestCase): key = 'vm-data/networking/aabbccddeeff' xenstore_value = xenstore_data[key] tcpip_data = ast.literal_eval(xenstore_value) - self.assertEquals(tcpip_data, { - 'label': 'fake_flat_network', - 'broadcast': '10.0.0.255', - 'ips': [{'ip': '10.0.0.3', - 'netmask':'255.255.255.0', - 'enabled':'1'}], - 'ip6s': [{'ip': 'fe80::a8bb:ccff:fedd:eeff', - 'netmask': '120', - 'enabled': '1', - 'gateway': 'fe80::a00:1'}], - 'mac': 'aa:bb:cc:dd:ee:ff', - 'dns': ['10.0.0.2'], - 'gateway': '10.0.0.1'}) + self.assertEquals(tcpip_data, + {'label': 'fake_flat_network', + 'broadcast': '10.0.0.255', + 'ips': [{'ip': '10.0.0.3', + 'netmask':'255.255.255.0', + 'enabled':'1'}], + 'ip6s': [{'ip': 'fe80::a8bb:ccff:fedd:eeff', + 'netmask': '120', + 'enabled': '1', + 'gateway': 'fe80::a00:1'}], + 'mac': 'aa:bb:cc:dd:ee:ff', + 'dns': ['10.0.0.2'], + 'gateway': '10.0.0.1'}) def check_vm_params_for_windows(self): self.assertEquals(self.vm['platform']['nx'], 'true') diff --git a/nova/virt/xenapi/fake.py b/nova/virt/xenapi/fake.py index d084c725f..d79312a60 100644 --- a/nova/virt/xenapi/fake.py +++ b/nova/virt/xenapi/fake.py @@ -60,7 +60,7 @@ from nova import exception from nova import log as logging -_CLASSES = ['host', 'network', 'session', 'SR', 'VBD',\ +_CLASSES = ['host', 'network', 'session', 'SR', 'VBD', \ 'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task'] _db_content = {} diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 08046318e..147419f90 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -668,7 +668,7 @@ class VMOps(object): self._wait_with_callback(instance.id, task, callback) def suspend(self, instance, callback): - """Suspend the specified instance""" + """Suspend the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) task = self._session.call_xenapi('Async.VM.suspend', vm_ref) self._wait_with_callback(instance.id, task, callback) @@ -686,6 +686,7 @@ class VMOps(object): - shutdown the instance VM. - set 'bootlock' to prevent the instance from starting in rescue. - spawn a rescue VM (the vm name-label will be instance-N-rescue). + """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) -- cgit From 14337b0a31c8f04d8044e234eb295b41a9a9c5ce Mon Sep 17 00:00:00 2001 From: Brian Waldon Date: Mon, 28 Mar 2011 14:02:53 -0400 Subject: adding shared_ip_groups testing; replacing all shared_ip_groups contoller code with HTTPNotImplemented; moving shared_ip_groups controller to APIRouterV10 --- nova/api/openstack/__init__.py | 8 +++--- nova/api/openstack/shared_ip_groups.py | 6 ++--- nova/tests/api/openstack/test_shared_ip_groups.py | 30 ++++++++++++++++++++--- 3 files changed, 34 insertions(+), 10 deletions(-) (limited to 'nova') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index 8fabbce8e..cf53ffcd6 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -119,10 +119,6 @@ class APIRouter(wsgi.Router): mapper.resource("image", "images", controller=images.Controller(), collection={'detail': 'GET'}) - mapper.resource("shared_ip_group", "shared_ip_groups", - collection={'detail': 'GET'}, - controller=shared_ip_groups.Controller()) - _limits = limits.LimitsController() mapper.resource("limit", "limits", controller=_limits) @@ -141,6 +137,10 @@ class APIRouterV10(APIRouter): controller=flavors.ControllerV10(), collection={'detail': 'GET'}) + mapper.resource("shared_ip_group", "shared_ip_groups", + collection={'detail': 'GET'}, + controller=shared_ip_groups.Controller()) + class APIRouterV11(APIRouter): """Define routes specific to OpenStack API V1.1.""" diff --git a/nova/api/openstack/shared_ip_groups.py b/nova/api/openstack/shared_ip_groups.py index 5d78f9377..ee7991d7f 100644 --- a/nova/api/openstack/shared_ip_groups.py +++ b/nova/api/openstack/shared_ip_groups.py @@ -42,11 +42,11 @@ class Controller(wsgi.Controller): def index(self, req): """ Returns a list of Shared IP Groups for the user """ - return dict(sharedIpGroups=[]) + raise faults.Fault(exc.HTTPNotImplemented()) def show(self, req, id): """ Shows in-depth information on a specific Shared IP Group """ - return _translate_keys({}) + raise faults.Fault(exc.HTTPNotImplemented()) def update(self, req, id): """ You can't update a Shared IP Group """ @@ -58,7 +58,7 @@ class Controller(wsgi.Controller): def detail(self, req): """ Returns a complete list of Shared IP Groups """ - return _translate_detail_keys({}) + raise faults.Fault(exc.HTTPNotImplemented()) def create(self, req): """ Creates a new Shared IP group """ diff --git a/nova/tests/api/openstack/test_shared_ip_groups.py b/nova/tests/api/openstack/test_shared_ip_groups.py index b4de2ef41..c2bd7e45a 100644 --- a/nova/tests/api/openstack/test_shared_ip_groups.py +++ b/nova/tests/api/openstack/test_shared_ip_groups.py @@ -16,25 +16,49 @@ # under the License. import stubout +import webob from nova import test from nova.api.openstack import shared_ip_groups +from nova.tests.api.openstack import fakes class SharedIpGroupsTest(test.TestCase): def setUp(self): super(SharedIpGroupsTest, self).setUp() self.stubs = stubout.StubOutForTesting() + fakes.FakeAuthManager.reset_fake_data() + fakes.FakeAuthDatabase.data = {} + fakes.stub_out_auth(self.stubs) def tearDown(self): self.stubs.UnsetAll() super(SharedIpGroupsTest, self).tearDown() def test_get_shared_ip_groups(self): - pass + req = webob.Request.blank('/v1.0/shared_ip_groups') + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 501) def test_create_shared_ip_group(self): - pass + req = webob.Request.blank('/v1.0/shared_ip_groups') + req.method = 'POST' + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 501) + + def test_update_shared_ip_group(self): + req = webob.Request.blank('/v1.0/shared_ip_groups/12') + req.method = 'PUT' + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 501) def test_delete_shared_ip_group(self): - pass + req = webob.Request.blank('/v1.0/shared_ip_groups/12') + req.method = 'DELETE' + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 501) + + def test_deprecated_v11(self): + req = webob.Request.blank('/v1.1/shared_ip_groups') + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 404) -- cgit From c1ed5fc3dfeecef281df45cd2e6779fa21c63bf5 Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Mon, 28 Mar 2011 22:00:17 +0100 Subject: style fixes --- nova/network/xenapi_net.py | 6 ++++-- nova/tests/fake_utils.py | 14 ++++++++++---- nova/tests/test_xenapi.py | 28 +++++++--------------------- nova/virt/xenapi/fake.py | 28 ++++++++++++++-------------- 4 files changed, 35 insertions(+), 41 deletions(-) (limited to 'nova') diff --git a/nova/network/xenapi_net.py b/nova/network/xenapi_net.py index 8603fd842..9a99602d9 100644 --- a/nova/network/xenapi_net.py +++ b/nova/network/xenapi_net.py @@ -27,7 +27,7 @@ from nova import flags from nova import log as logging from nova import utils from nova.virt.xenapi_conn import XenAPISession -from nova.virt.xenapi.network_utils import NetworkHelper +from nova.virt.xenapi import network_utils LOG = logging.getLogger("nova.xenapi_net") @@ -44,7 +44,9 @@ def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): session = XenAPISession(url, username, password) # Check whether bridge already exists # Retrieve network whose name_label is "bridge" - network_ref = NetworkHelper.find_network_with_name_label(session, bridge) + network_ref = network_utils.NetworkHelper.find_network_with_name_label( + session, + bridge) if network_ref == None: # If bridge does not exists # 1 - create network diff --git a/nova/tests/fake_utils.py b/nova/tests/fake_utils.py index 23996ba95..be59970c9 100644 --- a/nova/tests/fake_utils.py +++ b/nova/tests/fake_utils.py @@ -47,14 +47,20 @@ def fake_execute_set_repliers(repliers): def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs): - """A reply handler for commands that haven't been added to the reply - list. Returns empty strings for stdout and stderr.""" + """A reply handler for commands that haven't been added to the reply list. + + Returns empty strings for stdout and stderr. + + """ return '', '' def fake_execute(*cmd_parts, **kwargs): - """This function stubs out execute, optionally executing - a preconfigued function to return expected data.""" + """This function stubs out execute. + + It optionally executes a preconfigued function to return expected data. + + """ global _fake_execute_repliers process_input = kwargs.get('process_input', None) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index bc1469223..17e3f55e9 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -14,9 +14,7 @@ # License for the specific language governing permissions and limitations # under the License. -""" -Test suite for XenAPI. -""" +"""Test suite for XenAPI.""" import functools import os @@ -65,9 +63,7 @@ def stub_vm_utils_with_vdi_attached_here(function, should_return=True): class XenAPIVolumeTestCase(test.TestCase): - """ - Unit tests for Volume operations. - """ + """Unit tests for Volume operations.""" def setUp(self): super(XenAPIVolumeTestCase, self).setUp() self.stubs = stubout.StubOutForTesting() @@ -172,9 +168,7 @@ def reset_network(*args): class XenAPIVMTestCase(test.TestCase): - """ - Unit tests for VM operations. - """ + """Unit tests for VM operations.""" def setUp(self): super(XenAPIVMTestCase, self).setUp() self.manager = manager.AuthManager() @@ -538,9 +532,7 @@ class XenAPIVMTestCase(test.TestCase): class XenAPIDiffieHellmanTestCase(test.TestCase): - """ - Unit tests for Diffie-Hellman code. - """ + """Unit tests for Diffie-Hellman code.""" def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() self.alice = SimpleDH() @@ -564,9 +556,7 @@ class XenAPIDiffieHellmanTestCase(test.TestCase): class XenAPIMigrateInstance(test.TestCase): - """ - Unit test for verifying migration-related actions. - """ + """Unit test for verifying migration-related actions.""" def setUp(self): super(XenAPIMigrateInstance, self).setUp() @@ -621,9 +611,7 @@ class XenAPIMigrateInstance(test.TestCase): class XenAPIDetermineDiskImageTestCase(test.TestCase): - """ - Unit tests for code that detects the ImageType. - """ + """Unit tests for code that detects the ImageType.""" def setUp(self): super(XenAPIDetermineDiskImageTestCase, self).setUp() glance_stubs.stubout_glance_client(self.stubs, @@ -642,9 +630,7 @@ class XenAPIDetermineDiskImageTestCase(test.TestCase): self.assertEqual(disk_type, dt) def test_instance_disk(self): - """ - If a kernel is specified then the image type is DISK (aka machine). - """ + """If a kernel is specified, the image type is DISK (aka machine).""" FLAGS.xenapi_image_service = 'objectstore' self.fake_instance.image_id = glance_stubs.FakeGlance.IMAGE_MACHINE self.fake_instance.kernel_id = glance_stubs.FakeGlance.IMAGE_KERNEL diff --git a/nova/virt/xenapi/fake.py b/nova/virt/xenapi/fake.py index d79312a60..4434dbf0b 100644 --- a/nova/virt/xenapi/fake.py +++ b/nova/virt/xenapi/fake.py @@ -60,7 +60,7 @@ from nova import exception from nova import log as logging -_CLASSES = ['host', 'network', 'session', 'SR', 'VBD', \ +_CLASSES = ['host', 'network', 'session', 'SR', 'VBD', 'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task'] _db_content = {} @@ -200,19 +200,19 @@ def create_local_srs(): def _create_local_sr(host_ref): - sr_ref = \ - _create_object('SR', - {'name_label': 'Local storage', - 'type': 'lvm', - 'content_type': 'user', - 'shared': False, - 'physical_size': str(1 << 30), - 'physical_utilisation': str(0), - 'virtual_allocation': str(0), - 'other_config': {'i18n-original-value-name_label': \ - 'Local storage', - 'i18n-key': 'local-storage'}, - 'VDIs': []}) + sr_ref = _create_object( + 'SR', + {'name_label': 'Local storage', + 'type': 'lvm', + 'content_type': 'user', + 'shared': False, + 'physical_size': str(1 << 30), + 'physical_utilisation': str(0), + 'virtual_allocation': str(0), + 'other_config': { + 'i18n-original-value-name_label': 'Local storage', + 'i18n-key': 'local-storage'}, + 'VDIs': []}) pbd_ref = create_pbd('', host_ref, sr_ref, True) _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] return sr_ref -- cgit From cd81e06c19893b44568a8cef37a1de30b726e236 Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Mon, 28 Mar 2011 22:25:11 +0100 Subject: fix docstrings --- nova/virt/xenapi/vmops.py | 61 +++++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 28 deletions(-) (limited to 'nova') diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 147419f90..a9514bd61 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -279,8 +279,7 @@ class VMOps(object): "start") def snapshot(self, instance, image_id): - """ - Create snapshot from a running VM instance + """Create snapshot from a running VM instance. :param instance: instance to be snapshotted :param image_id: id of image to upload to @@ -300,6 +299,7 @@ class VMOps(object): 3. Push-to-glance: Once coalesced, we call a plugin on the XenServer that will bundle the VHDs together and then push the bundle into Glance. + """ template_vm_ref = None try: @@ -332,8 +332,7 @@ class VMOps(object): return def migrate_disk_and_power_off(self, instance, dest): - """ - Copies a VHD from one host machine to another + """Copies a VHD from one host machine to another. :param instance: the instance that owns the VHD in question. :param dest: the destination host machine. @@ -428,13 +427,14 @@ class VMOps(object): self._session.wait_for_task(task, instance.id) def set_admin_password(self, instance, new_pass): - """ - Set the root/admin password on the VM instance. This is done via - an agent running on the VM. Communication between nova and the agent - is done via writing xenstore records. Since communication is done over - the XenAPI RPC calls, we need to encrypt the password. We're using a - simple Diffie-Hellman class instead of the more advanced one in - M2Crypto for compatibility with the agent code. + """Set the root/admin password on the VM instance. + + This is done via an agent running on the VM. Communication between nova + and the agent is done via writing xenstore records. Since communication + is done over the XenAPI RPC calls, we need to encrypt the password. + We're using a simple Diffie-Hellman class instead of the more advanced + one in M2Crypto for compatibility with the agent code. + """ # Need to uniquely identify this request. transaction_id = str(uuid.uuid4()) @@ -467,12 +467,14 @@ class VMOps(object): return resp_dict['message'] def inject_file(self, instance, path, contents): - """ - Write a file to the VM instance. The path to which it is to be - written and the contents of the file need to be supplied; both will - be base64-encoded to prevent errors with non-ASCII characters being - transmitted. If the agent does not support file injection, or the user - has disabled it, a NotImplementedError will be raised. + """Write a file to the VM instance. + + The path to which it is to be written and the contents of the file + need to be supplied; both will be base64-encoded to prevent errors + with non-ASCII characters being transmitted. If the agent does not + support file injection, or the user has disabled it, a + NotImplementedError will be raised. + """ # Files/paths must be base64-encoded for transmission to agent b64_path = base64.b64encode(path) @@ -556,8 +558,7 @@ class VMOps(object): VMHelper.destroy_vbd(self._session, vbd_ref) def _destroy_kernel_ramdisk(self, instance, vm_ref): - """ - Three situations can occur: + """Three situations can occur: 1. We have neither a ramdisk nor a kernel, in which case we are a RAW image and can omit this step @@ -567,6 +568,7 @@ class VMOps(object): 3. We have both, in which case we safely remove both the kernel and the ramdisk. + """ instance_id = instance.id if not instance.kernel_id and not instance.ramdisk_id: @@ -614,11 +616,11 @@ class VMOps(object): self._session.call_xenapi("Async.VM.destroy", rescue_vm_ref) def destroy(self, instance): - """ - Destroy VM instance + """Destroy VM instance. This is the method exposed by xenapi_conn.destroy(). The rest of the destroy_* methods are internal. + """ instance_id = instance.id LOG.info(_("Destroying VM for Instance %(instance_id)s") % locals()) @@ -627,13 +629,13 @@ class VMOps(object): def _destroy(self, instance, vm_ref, shutdown=True, destroy_kernel_ramdisk=True): - """ - Destroys VM instance by performing: + """Destroys VM instance by performing: 1. A shutdown if requested. 2. Destroying associated VDIs. 3. Destroying kernel and ramdisk files (if necessary). 4. Destroying that actual VM record. + """ if vm_ref is None: LOG.warning(_("VM is not present, skipping destroy...")) @@ -681,8 +683,8 @@ class VMOps(object): self._wait_with_callback(instance.id, task, callback) def rescue(self, instance, callback): - """ - Rescue the specified instance + """Rescue the specified instance. + - shutdown the instance VM. - set 'bootlock' to prevent the instance from starting in rescue. - spawn a rescue VM (the vm name-label will be instance-N-rescue). @@ -709,10 +711,12 @@ class VMOps(object): self._session.call_xenapi("Async.VBD.plug", rescue_vbd_ref) def unrescue(self, instance, callback): - """Unrescue the specified instance + """Unrescue the specified instance. + - unplug the instance VM's disk from the rescue VM. - teardown the rescue VM. - release the bootlock to allow the instance VM to start. + """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) @@ -729,10 +733,11 @@ class VMOps(object): self._start(instance, original_vm_ref) def poll_rescued_instances(self, timeout): - """ - Look for expirable rescued instances + """Look for expirable rescued instances. + - forcibly exit rescue mode for any instances that have been in rescue mode for >= the provided timeout + """ last_ran = self.poll_rescue_last_ran if not last_ran: -- cgit From 73f05da6400fe7f4324cf98c7d0706fb68a62870 Mon Sep 17 00:00:00 2001 From: Armando Migliaccio Date: Tue, 29 Mar 2011 11:20:16 +0100 Subject: sorted pep8 errors that were introduced during previous fixes --- nova/virt/xenapi/vmops.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'nova') diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index a9514bd61..c96c35a6e 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -430,7 +430,7 @@ class VMOps(object): """Set the root/admin password on the VM instance. This is done via an agent running on the VM. Communication between nova - and the agent is done via writing xenstore records. Since communication + and the agent is done via writing xenstore records. Since communication is done over the XenAPI RPC calls, we need to encrypt the password. We're using a simple Diffie-Hellman class instead of the more advanced one in M2Crypto for compatibility with the agent code. @@ -467,12 +467,12 @@ class VMOps(object): return resp_dict['message'] def inject_file(self, instance, path, contents): - """Write a file to the VM instance. + """Write a file to the VM instance. The path to which it is to be written and the contents of the file need to be supplied; both will be base64-encoded to prevent errors with non-ASCII characters being transmitted. If the agent does not - support file injection, or the user has disabled it, a + support file injection, or the user has disabled it, a NotImplementedError will be raised. """ -- cgit