~ubuntu-branches/ubuntu/quantal/nova/quantal-proposed

« back to all changes in this revision

Viewing changes to nova/tests/test_libvirt.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short
  • Date: 2012-08-16 14:04:11 UTC
  • mto: This revision was merged to the branch mainline in revision 84.
  • Revision ID: package-import@ubuntu.com-20120816140411-0mr4n241wmk30t9l
Tags: upstream-2012.2~f3
ImportĀ upstreamĀ versionĀ 2012.2~f3

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
2
#
3
3
#    Copyright 2010 OpenStack LLC
 
4
#    Copyright 2012 University Of Minho
4
5
#
5
6
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
6
7
#    not use this file except in compliance with the License. You may obtain
17
18
import copy
18
19
import errno
19
20
import eventlet
 
21
import json
20
22
import mox
21
23
import os
22
24
import re
29
31
from nova.api.ec2 import cloud
30
32
from nova.compute import instance_types
31
33
from nova.compute import power_state
 
34
from nova.compute import rpcapi as compute_rpcapi
 
35
from nova.compute import utils as compute_utils
 
36
from nova.compute import vm_mode
32
37
from nova.compute import vm_states
33
38
from nova import context
34
39
from nova import db
42
47
from nova.tests import fake_network
43
48
import nova.tests.image.fake
44
49
from nova import utils
 
50
from nova.virt.disk import api as disk
45
51
from nova.virt import driver
46
52
from nova.virt import firewall as base_firewall
47
53
from nova.virt import images
51
57
from nova.virt.libvirt import imagebackend
52
58
from nova.virt.libvirt import utils as libvirt_utils
53
59
from nova.virt.libvirt import volume
 
60
from nova.virt.libvirt import volume_nfs
54
61
from nova.volume import driver as volume_driver
55
62
 
56
63
 
57
64
try:
58
65
    import libvirt
59
 
    libvirt_driver.libvirt = libvirt
60
66
except ImportError:
61
 
    # TODO(sdague): there should be a cleaner way to handle this
62
 
    # in the case where libvirt python isn't installed
63
 
    libvirt_driver.libvirt = ""
64
 
    libvirt = None
 
67
    import nova.tests.fakelibvirt as libvirt
 
68
libvirt_driver.libvirt = libvirt
65
69
 
66
70
 
67
71
FLAGS = flags.FLAGS
324
328
        libvirt_driver.disconnect_volume(connection_info, mount_device)
325
329
        connection_info = vol_driver.terminate_connection(vol, self.connr)
326
330
 
 
331
    def test_libvirt_nfs_driver(self):
 
332
        # NOTE(vish) exists is to make driver assume connecting worked
 
333
        mnt_base = '/mnt'
 
334
        self.flags(nfs_mount_point_base=mnt_base)
 
335
 
 
336
        libvirt_driver = volume_nfs.NfsVolumeDriver(self.fake_conn)
 
337
        export_string = '192.168.1.1:/nfs/share1'
 
338
        name = 'volume-00001'
 
339
        export_mnt_base = os.path.join(mnt_base,
 
340
                libvirt_driver.get_hash_str(export_string))
 
341
        file_path = os.path.join(export_mnt_base, name)
 
342
 
 
343
        connection_info = {'data': {'export': export_string, 'name': name}}
 
344
        mount_device = "vde"
 
345
        conf = libvirt_driver.connect_volume(connection_info, mount_device)
 
346
        tree = conf.format_dom()
 
347
        self.assertEqual(tree.get('type'), 'file')
 
348
        self.assertEqual(tree.find('./source').get('file'), file_path)
 
349
        libvirt_driver.disconnect_volume(connection_info, mount_device)
 
350
 
 
351
        expected_commands = [
 
352
            ('stat', export_mnt_base),
 
353
            ('mount', '-t', 'nfs', export_string, export_mnt_base)]
 
354
        self.assertEqual(self.executes, expected_commands)
 
355
 
327
356
 
328
357
class CacheConcurrencyTestCase(test.TestCase):
329
358
    def setUp(self):
406
435
        return ""
407
436
 
408
437
 
409
 
def missing_libvirt():
410
 
    return libvirt is None
411
 
 
412
 
 
413
438
class LibvirtConnTestCase(test.TestCase):
414
439
 
415
440
    def setUp(self):
416
441
        super(LibvirtConnTestCase, self).setUp()
417
 
        libvirt_driver._late_load_cheetah()
418
442
        self.flags(fake_call=True)
419
443
        self.user_id = 'fake'
420
444
        self.project_id = 'fake'
421
445
        self.context = context.get_admin_context()
422
446
        self.flags(instances_path='')
 
447
        self.flags(libvirt_snapshots_directory='')
423
448
        self.call_libvirt_dependant_setup = False
424
449
        libvirt_driver.libvirt_utils = fake_libvirt_utils
425
450
 
511
536
        self.assertEquals(cfg.acpi, True)
512
537
        self.assertEquals(cfg.memory, 1024 * 1024 * 2)
513
538
        self.assertEquals(cfg.vcpus, 1)
514
 
        self.assertEquals(cfg.os_type, "hvm")
 
539
        self.assertEquals(cfg.os_type, vm_mode.HVM)
515
540
        self.assertEquals(cfg.os_boot_dev, "hd")
516
541
        self.assertEquals(cfg.os_root, None)
517
542
        self.assertEquals(len(cfg.devices), 7)
555
580
        self.assertEquals(cfg.acpi, True)
556
581
        self.assertEquals(cfg.memory, 1024 * 1024 * 2)
557
582
        self.assertEquals(cfg.vcpus, 1)
558
 
        self.assertEquals(cfg.os_type, "hvm")
 
583
        self.assertEquals(cfg.os_type, vm_mode.HVM)
559
584
        self.assertEquals(cfg.os_boot_dev, "hd")
560
585
        self.assertEquals(cfg.os_root, None)
561
586
        self.assertEquals(len(cfg.devices), 8)
615
640
        self.assertEquals(cfg.devices[3].target_dev, 'vdd')
616
641
 
617
642
    def test_get_guest_cpu_config_none(self):
618
 
        conn = libvirt_driver.LibvirtDriver(True)
619
 
        instance_ref = db.instance_create(self.context, self.test_instance)
620
 
 
621
 
        conf = conn.get_guest_config(instance_ref,
622
 
                                    _fake_network_info(self.stubs, 1),
623
 
                                    None, None)
624
 
        self.assertEquals(conf.cpu, None)
625
 
 
626
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
 
643
        self.flags(libvirt_cpu_mode="none")
 
644
        conn = libvirt_driver.LibvirtDriver(True)
 
645
        instance_ref = db.instance_create(self.context, self.test_instance)
 
646
 
 
647
        conf = conn.get_guest_config(instance_ref,
 
648
                                    _fake_network_info(self.stubs, 1),
 
649
                                    None, None)
 
650
        self.assertEquals(conf.cpu, None)
 
651
 
 
652
    def test_get_guest_cpu_config_default_kvm(self):
 
653
        self.flags(libvirt_type="kvm",
 
654
                   libvirt_cpu_mode=None)
 
655
 
 
656
        def get_lib_version_stub(self):
 
657
            return (0 * 1000 * 1000) + (9 * 1000) + 11
 
658
 
 
659
        self.stubs.Set(libvirt.virConnect,
 
660
                       "getLibVersion",
 
661
                       get_lib_version_stub)
 
662
        conn = libvirt_driver.LibvirtDriver(True)
 
663
        instance_ref = db.instance_create(self.context, self.test_instance)
 
664
 
 
665
        conf = conn.get_guest_config(instance_ref,
 
666
                                     _fake_network_info(self.stubs, 1),
 
667
                                     None, None)
 
668
        self.assertEquals(type(conf.cpu),
 
669
                          config.LibvirtConfigGuestCPU)
 
670
        self.assertEquals(conf.cpu.mode, "host-model")
 
671
        self.assertEquals(conf.cpu.model, None)
 
672
 
 
673
    def test_get_guest_cpu_config_default_uml(self):
 
674
        self.flags(libvirt_type="uml",
 
675
                   libvirt_cpu_mode=None)
 
676
 
 
677
        conn = libvirt_driver.LibvirtDriver(True)
 
678
        instance_ref = db.instance_create(self.context, self.test_instance)
 
679
 
 
680
        conf = conn.get_guest_config(instance_ref,
 
681
                                    _fake_network_info(self.stubs, 1),
 
682
                                    None, None)
 
683
        self.assertEquals(conf.cpu, None)
 
684
 
 
685
    def test_get_guest_cpu_config_default_lxc(self):
 
686
        self.flags(libvirt_type="lxc",
 
687
                   libvirt_cpu_mode=None)
 
688
 
 
689
        conn = libvirt_driver.LibvirtDriver(True)
 
690
        instance_ref = db.instance_create(self.context, self.test_instance)
 
691
 
 
692
        conf = conn.get_guest_config(instance_ref,
 
693
                                    _fake_network_info(self.stubs, 1),
 
694
                                    None, None)
 
695
        self.assertEquals(conf.cpu, None)
 
696
 
627
697
    def test_get_guest_cpu_config_host_passthrough_new(self):
628
698
        def get_lib_version_stub(self):
629
699
            return (0 * 1000 * 1000) + (9 * 1000) + 11
643
713
        self.assertEquals(conf.cpu.mode, "host-passthrough")
644
714
        self.assertEquals(conf.cpu.model, None)
645
715
 
646
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
647
716
    def test_get_guest_cpu_config_host_model_new(self):
648
717
        def get_lib_version_stub(self):
649
718
            return (0 * 1000 * 1000) + (9 * 1000) + 11
663
732
        self.assertEquals(conf.cpu.mode, "host-model")
664
733
        self.assertEquals(conf.cpu.model, None)
665
734
 
666
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
667
735
    def test_get_guest_cpu_config_custom_new(self):
668
736
        def get_lib_version_stub(self):
669
737
            return (0 * 1000 * 1000) + (9 * 1000) + 11
684
752
        self.assertEquals(conf.cpu.mode, "custom")
685
753
        self.assertEquals(conf.cpu.model, "Penryn")
686
754
 
 
755
    def test_get_guest_cpu_config_host_passthrough_old(self):
 
756
        def get_lib_version_stub(self):
 
757
            return (0 * 1000 * 1000) + (9 * 1000) + 7
 
758
 
 
759
        self.stubs.Set(libvirt.virConnect, "getLibVersion",
 
760
                       get_lib_version_stub)
 
761
        conn = libvirt_driver.LibvirtDriver(True)
 
762
        instance_ref = db.instance_create(self.context, self.test_instance)
 
763
 
 
764
        self.flags(libvirt_cpu_mode="host-passthrough")
 
765
        self.assertRaises(exception.NovaException,
 
766
                          conn.get_guest_config,
 
767
                          instance_ref,
 
768
                          _fake_network_info(self.stubs, 1),
 
769
                          None, None)
 
770
 
 
771
    def test_get_guest_cpu_config_host_model_old(self):
 
772
        def get_lib_version_stub(self):
 
773
            return (0 * 1000 * 1000) + (9 * 1000) + 7
 
774
 
 
775
        # Ensure we have a predictable host CPU
 
776
        def get_host_capabilities_stub(self):
 
777
            cpu = config.LibvirtConfigGuestCPU()
 
778
            cpu.model = "Opteron_G4"
 
779
            cpu.vendor = "AMD"
 
780
 
 
781
            caps = config.LibvirtConfigCaps()
 
782
            caps.host = config.LibvirtConfigCapsHost()
 
783
            caps.host.cpu = cpu
 
784
            return caps
 
785
 
 
786
        self.stubs.Set(libvirt.virConnect,
 
787
                       "getLibVersion",
 
788
                       get_lib_version_stub)
 
789
        self.stubs.Set(libvirt_driver.LibvirtDriver,
 
790
                       "get_host_capabilities",
 
791
                       get_host_capabilities_stub)
 
792
        conn = libvirt_driver.LibvirtDriver(True)
 
793
        instance_ref = db.instance_create(self.context, self.test_instance)
 
794
 
 
795
        self.flags(libvirt_cpu_mode="host-model")
 
796
        conf = conn.get_guest_config(instance_ref,
 
797
                                     _fake_network_info(self.stubs, 1),
 
798
                                     None, None)
 
799
        self.assertEquals(type(conf.cpu),
 
800
                          config.LibvirtConfigGuestCPU)
 
801
        self.assertEquals(conf.cpu.mode, None)
 
802
        self.assertEquals(conf.cpu.model, "Opteron_G4")
 
803
        self.assertEquals(conf.cpu.vendor, "AMD")
 
804
 
 
805
    def test_get_guest_cpu_config_custom_old(self):
 
806
        def get_lib_version_stub(self):
 
807
            return (0 * 1000 * 1000) + (9 * 1000) + 7
 
808
 
 
809
        self.stubs.Set(libvirt.virConnect,
 
810
                       "getLibVersion",
 
811
                       get_lib_version_stub)
 
812
        conn = libvirt_driver.LibvirtDriver(True)
 
813
        instance_ref = db.instance_create(self.context, self.test_instance)
 
814
 
 
815
        self.flags(libvirt_cpu_mode="custom")
 
816
        self.flags(libvirt_cpu_model="Penryn")
 
817
        conf = conn.get_guest_config(instance_ref,
 
818
                                     _fake_network_info(self.stubs, 1),
 
819
                                     None, None)
 
820
        self.assertEquals(type(conf.cpu),
 
821
                          config.LibvirtConfigGuestCPU)
 
822
        self.assertEquals(conf.cpu.mode, None)
 
823
        self.assertEquals(conf.cpu.model, "Penryn")
 
824
 
687
825
    def test_xml_and_uri_no_ramdisk_no_kernel(self):
688
826
        instance_data = dict(self.test_instance)
689
827
        self._check_xml_and_uri(instance_data,
690
828
                                expect_kernel=False, expect_ramdisk=False)
691
829
 
 
830
    def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self):
 
831
        instance_data = dict(self.test_instance)
 
832
        instance_data.update({'vm_mode': vm_mode.HVM})
 
833
        self._check_xml_and_uri(instance_data, expect_kernel=False,
 
834
                                expect_ramdisk=False, expect_xen_hvm=True)
 
835
 
 
836
    def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self):
 
837
        instance_data = dict(self.test_instance)
 
838
        instance_data.update({'vm_mode': vm_mode.XEN})
 
839
        self._check_xml_and_uri(instance_data, expect_kernel=False,
 
840
                                expect_ramdisk=False, expect_xen_hvm=False,
 
841
                                xen_only=True)
 
842
 
692
843
    def test_xml_and_uri_no_ramdisk(self):
693
844
        instance_data = dict(self.test_instance)
694
845
        instance_data['kernel_id'] = 'aki-deadbeef'
750
901
 
751
902
    def test_xml_disk_bus_virtio(self):
752
903
        self._check_xml_and_disk_bus({"disk_format": "raw"},
753
 
                                     "disk", "virtio")
 
904
                                     None,
 
905
                                     (("disk", "virtio", "vda"),))
754
906
 
755
907
    def test_xml_disk_bus_ide(self):
756
908
        self._check_xml_and_disk_bus({"disk_format": "iso"},
757
 
                                     "cdrom", "ide")
 
909
                                     None,
 
910
                                     (("cdrom", "ide", "hda"),))
 
911
 
 
912
    def test_xml_disk_bus_ide_and_virtio(self):
 
913
        swap = {'device_name': '/dev/vdc',
 
914
                'swap_size': 1}
 
915
        ephemerals = [{'num': 0,
 
916
                       'virtual_name': 'ephemeral0',
 
917
                       'device_name': '/dev/vdb',
 
918
                       'size': 1}]
 
919
        block_device_info = {
 
920
                'swap': swap,
 
921
                'ephemerals': ephemerals}
 
922
 
 
923
        self._check_xml_and_disk_bus({"disk_format": "iso"},
 
924
                                     block_device_info,
 
925
                                     (("cdrom", "ide", "hda"),
 
926
                                      ("disk", "virtio", "vdb"),
 
927
                                      ("disk", "virtio", "vdc")))
758
928
 
759
929
    def test_list_instances(self):
760
930
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
768
938
        # Only one should be listed, since domain with ID 0 must be skiped
769
939
        self.assertEquals(len(instances), 1)
770
940
 
 
941
    def test_list_instances_when_instance_deleted(self):
 
942
 
 
943
        def fake_lookup(instance_name):
 
944
            raise libvirt.libvirtError("we deleted an instance!")
 
945
 
 
946
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
947
        libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
 
948
        libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
 
949
        libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
 
950
 
 
951
        self.mox.ReplayAll()
 
952
        conn = libvirt_driver.LibvirtDriver(False)
 
953
        instances = conn.list_instances()
 
954
        # None should be listed, since we fake deleted the last one
 
955
        self.assertEquals(len(instances), 0)
 
956
 
771
957
    def test_get_all_block_devices(self):
772
958
        xml = [
773
959
            # NOTE(vish): id 0 is skipped
881
1067
        devices = conn.get_disks(conn.list_instances()[0])
882
1068
        self.assertEqual(devices, ['vda', 'vdb'])
883
1069
 
884
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
885
1070
    def test_snapshot_in_ami_format(self):
 
1071
        self.flags(libvirt_snapshots_directory='./')
 
1072
 
886
1073
        # Start test
887
1074
        image_service = nova.tests.image.fake.FakeImageService()
888
1075
 
917
1104
        self.assertEquals(snapshot['disk_format'], 'ami')
918
1105
        self.assertEquals(snapshot['name'], snapshot_name)
919
1106
 
920
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
921
1107
    def test_snapshot_in_raw_format(self):
 
1108
        self.flags(libvirt_snapshots_directory='./')
 
1109
 
922
1110
        # Start test
923
1111
        image_service = nova.tests.image.fake.FakeImageService()
924
1112
 
949
1137
        self.assertEquals(snapshot['disk_format'], 'raw')
950
1138
        self.assertEquals(snapshot['name'], snapshot_name)
951
1139
 
952
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
953
1140
    def test_snapshot_in_qcow2_format(self):
954
 
        self.flags(snapshot_image_format='qcow2')
 
1141
        self.flags(snapshot_image_format='qcow2',
 
1142
                   libvirt_snapshots_directory='./')
955
1143
 
956
1144
        # Start test
957
1145
        image_service = nova.tests.image.fake.FakeImageService()
983
1171
        self.assertEquals(snapshot['disk_format'], 'qcow2')
984
1172
        self.assertEquals(snapshot['name'], snapshot_name)
985
1173
 
986
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
987
1174
    def test_snapshot_no_image_architecture(self):
 
1175
        self.flags(libvirt_snapshots_directory='./')
 
1176
 
988
1177
        # Start test
989
1178
        image_service = nova.tests.image.fake.FakeImageService()
990
1179
 
1019
1208
        self.assertEquals(snapshot['status'], 'active')
1020
1209
        self.assertEquals(snapshot['name'], snapshot_name)
1021
1210
 
1022
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1023
1211
    def test_snapshot_no_original_image(self):
 
1212
        self.flags(libvirt_snapshots_directory='./')
 
1213
 
1024
1214
        # Start test
1025
1215
        image_service = nova.tests.image.fake.FakeImageService()
1026
1216
 
1181
1371
        for disk in disks:
1182
1372
            self.assertEqual(disk.get("cache"), "writethrough")
1183
1373
 
1184
 
    def _check_xml_and_disk_bus(self, image_meta, device_type, bus):
 
1374
    def _check_xml_and_disk_bus(self, image_meta,
 
1375
                                block_device_info, wantConfig):
1185
1376
        user_context = context.RequestContext(self.user_id, self.project_id)
1186
1377
        instance_ref = db.instance_create(user_context, self.test_instance)
1187
1378
        network_info = _fake_network_info(self.stubs, 1)
1188
1379
 
1189
 
        xml = libvirt_driver.LibvirtDriver(True).to_xml(instance_ref,
1190
 
                                                        network_info,
1191
 
                                                        image_meta)
 
1380
        xml = libvirt_driver.LibvirtDriver(True).to_xml(
 
1381
            instance_ref,
 
1382
            network_info,
 
1383
            image_meta,
 
1384
            block_device_info=block_device_info)
1192
1385
        tree = etree.fromstring(xml)
1193
 
        self.assertEqual(tree.find('./devices/disk').get('device'),
1194
 
                         device_type)
1195
 
        self.assertEqual(tree.find('./devices/disk/target').get('bus'), bus)
 
1386
 
 
1387
        got_disks = tree.findall('./devices/disk')
 
1388
        got_disk_targets = tree.findall('./devices/disk/target')
 
1389
        for i in range(len(wantConfig)):
 
1390
            want_device_type = wantConfig[i][0]
 
1391
            want_device_bus = wantConfig[i][1]
 
1392
            want_device_dev = wantConfig[i][2]
 
1393
 
 
1394
            got_device_type = got_disks[i].get('device')
 
1395
            got_device_bus = got_disk_targets[i].get('bus')
 
1396
            got_device_dev = got_disk_targets[i].get('dev')
 
1397
 
 
1398
            self.assertEqual(got_device_type, want_device_type)
 
1399
            self.assertEqual(got_device_bus, want_device_bus)
 
1400
            self.assertEqual(got_device_dev, want_device_dev)
1196
1401
 
1197
1402
    def _check_xml_and_uuid(self, image_meta):
1198
1403
        user_context = context.RequestContext(self.user_id, self.project_id)
1207
1412
                         instance_ref['uuid'])
1208
1413
 
1209
1414
    def _check_xml_and_uri(self, instance, expect_ramdisk, expect_kernel,
1210
 
                           rescue=None):
 
1415
                           rescue=None, expect_xen_hvm=False, xen_only=False):
1211
1416
        user_context = context.RequestContext(self.user_id, self.project_id)
1212
1417
        instance_ref = db.instance_create(user_context, instance)
1213
1418
        network_ref = db.project_get_networks(context.get_admin_context(),
1215
1420
 
1216
1421
        type_uri_map = {'qemu': ('qemu:///system',
1217
1422
                             [(lambda t: t.find('.').get('type'), 'qemu'),
1218
 
                              (lambda t: t.find('./os/type').text, 'hvm'),
 
1423
                              (lambda t: t.find('./os/type').text,
 
1424
                               vm_mode.HVM),
1219
1425
                              (lambda t: t.find('./devices/emulator'), None)]),
1220
1426
                        'kvm': ('qemu:///system',
1221
1427
                             [(lambda t: t.find('.').get('type'), 'kvm'),
1222
 
                              (lambda t: t.find('./os/type').text, 'hvm'),
 
1428
                              (lambda t: t.find('./os/type').text,
 
1429
                               vm_mode.HVM),
1223
1430
                              (lambda t: t.find('./devices/emulator'), None)]),
1224
1431
                        'uml': ('uml:///system',
1225
1432
                             [(lambda t: t.find('.').get('type'), 'uml'),
1226
 
                              (lambda t: t.find('./os/type').text, 'uml')]),
 
1433
                              (lambda t: t.find('./os/type').text,
 
1434
                               vm_mode.UML)]),
1227
1435
                        'xen': ('xen:///',
1228
1436
                             [(lambda t: t.find('.').get('type'), 'xen'),
1229
 
                              (lambda t: t.find('./os/type').text, 'linux')]),
1230
 
                              }
1231
 
 
1232
 
        for hypervisor_type in ['qemu', 'kvm', 'xen']:
 
1437
                              (lambda t: t.find('./os/type').text,
 
1438
                               vm_mode.XEN)])}
 
1439
 
 
1440
        if expect_xen_hvm or xen_only:
 
1441
            hypervisors_to_check = ['xen']
 
1442
        else:
 
1443
            hypervisors_to_check = ['qemu', 'kvm', 'xen']
 
1444
 
 
1445
        if expect_xen_hvm:
 
1446
            type_uri_map = {}
 
1447
            type_uri_map['xen'] = ('xen:///',
 
1448
                                   [(lambda t: t.find('.').get('type'),
 
1449
                                       'xen'),
 
1450
                                    (lambda t: t.find('./os/type').text,
 
1451
                                        vm_mode.HVM)])
 
1452
 
 
1453
        for hypervisor_type in hypervisors_to_check:
1233
1454
            check_list = type_uri_map[hypervisor_type][1]
1234
1455
 
1235
1456
            if rescue:
1243
1464
                check = (lambda t: t.find('./os/kernel'), None)
1244
1465
            check_list.append(check)
1245
1466
 
 
1467
            # Hypervisors that only support vm_mode.HVM should
 
1468
            # not produce configuration that results in kernel
 
1469
            # arguments
 
1470
            if not expect_kernel and hypervisor_type in ['qemu', 'kvm']:
 
1471
                check = (lambda t: t.find('./os/root'), None)
 
1472
                check_list.append(check)
 
1473
                check = (lambda t: t.find('./os/cmdline'), None)
 
1474
                check_list.append(check)
 
1475
 
1246
1476
            if expect_ramdisk:
1247
1477
                check = (lambda t: t.find('./os/initrd').text.split(
1248
1478
                    '/')[1], 'ramdisk' + suffix)
1321
1551
            self.assertEquals(conn.uri, testuri)
1322
1552
        db.instance_destroy(user_context, instance_ref['uuid'])
1323
1553
 
1324
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1325
1554
    def test_ensure_filtering_rules_for_instance_timeout(self):
1326
1555
        """ensure_filtering_fules_for_instance() finishes with timeout."""
1327
1556
        # Preparing mocks
1362
1591
                           fake_none)
1363
1592
            conn.ensure_filtering_rules_for_instance(instance_ref,
1364
1593
                                                     network_info,
1365
 
                                                     time=fake_timer)
 
1594
                                                     time_module=fake_timer)
1366
1595
        except exception.NovaException, e:
1367
1596
            c1 = (0 <= str(e).find('Timeout migrating for'))
1368
1597
        self.assertTrue(c1)
1372
1601
 
1373
1602
        db.instance_destroy(self.context, instance_ref['uuid'])
1374
1603
 
1375
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
 
1604
    def test_check_can_live_migrate_dest_all_pass_with_block_migration(self):
 
1605
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1606
        dest = "fake_host_2"
 
1607
        src = instance_ref['host']
 
1608
        conn = libvirt_driver.LibvirtDriver(False)
 
1609
 
 
1610
        self.mox.StubOutWithMock(conn, '_get_compute_info')
 
1611
        self.mox.StubOutWithMock(conn, 'get_instance_disk_info')
 
1612
        self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
 
1613
        self.mox.StubOutWithMock(conn, '_compare_cpu')
 
1614
 
 
1615
        conn._get_compute_info(self.context, FLAGS.host).AndReturn(
 
1616
                                              {'disk_available_least': 400})
 
1617
        conn.get_instance_disk_info(instance_ref["name"]).AndReturn(
 
1618
                                            '[{"virt_disk_size":2}]')
 
1619
        # _check_cpu_match
 
1620
        conn._get_compute_info(self.context,
 
1621
                               src).AndReturn({'cpu_info': "asdf"})
 
1622
        conn._compare_cpu("asdf")
 
1623
 
 
1624
        # mounted_on_same_shared_storage
 
1625
        filename = "file"
 
1626
        conn._create_shared_storage_test_file().AndReturn(filename)
 
1627
 
 
1628
        self.mox.ReplayAll()
 
1629
        return_value = conn.check_can_live_migrate_destination(self.context,
 
1630
                                instance_ref, True, False)
 
1631
        self.assertDictMatch(return_value,
 
1632
                             {"filename": "file", "block_migration": True})
 
1633
 
 
1634
    def test_check_can_live_migrate_dest_all_pass_no_block_migration(self):
 
1635
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1636
        dest = "fake_host_2"
 
1637
        src = instance_ref['host']
 
1638
        conn = libvirt_driver.LibvirtDriver(False)
 
1639
 
 
1640
        self.mox.StubOutWithMock(conn, '_get_compute_info')
 
1641
        self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
 
1642
        self.mox.StubOutWithMock(conn, '_compare_cpu')
 
1643
 
 
1644
        # _check_cpu_match
 
1645
        conn._get_compute_info(self.context,
 
1646
                               src).AndReturn({'cpu_info': "asdf"})
 
1647
        conn._compare_cpu("asdf")
 
1648
 
 
1649
        # mounted_on_same_shared_storage
 
1650
        filename = "file"
 
1651
        conn._create_shared_storage_test_file().AndReturn(filename)
 
1652
 
 
1653
        self.mox.ReplayAll()
 
1654
        return_value = conn.check_can_live_migrate_destination(self.context,
 
1655
                                instance_ref, False, False)
 
1656
        self.assertDictMatch(return_value,
 
1657
                            {"filename": "file", "block_migration": False})
 
1658
 
 
1659
    def test_check_can_live_migrate_dest_fails_not_enough_disk(self):
 
1660
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1661
        dest = "fake_host_2"
 
1662
        src = instance_ref['host']
 
1663
        conn = libvirt_driver.LibvirtDriver(False)
 
1664
 
 
1665
        self.mox.StubOutWithMock(conn, '_get_compute_info')
 
1666
        self.mox.StubOutWithMock(conn, 'get_instance_disk_info')
 
1667
 
 
1668
        conn._get_compute_info(self.context, FLAGS.host).AndReturn(
 
1669
                                              {'disk_available_least': 0})
 
1670
        conn.get_instance_disk_info(instance_ref["name"]).AndReturn(
 
1671
                                            '[{"virt_disk_size":2}]')
 
1672
 
 
1673
        self.mox.ReplayAll()
 
1674
        self.assertRaises(exception.MigrationError,
 
1675
                          conn.check_can_live_migrate_destination,
 
1676
                          self.context, instance_ref, True, False)
 
1677
 
 
1678
    def test_check_can_live_migrate_dest_incompatible_cpu_raises(self):
 
1679
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1680
        dest = "fake_host_2"
 
1681
        src = instance_ref['host']
 
1682
        conn = libvirt_driver.LibvirtDriver(False)
 
1683
 
 
1684
        self.mox.StubOutWithMock(conn, '_get_compute_info')
 
1685
        self.mox.StubOutWithMock(conn, '_compare_cpu')
 
1686
 
 
1687
        conn._get_compute_info(self.context, src).AndReturn(
 
1688
                {'cpu_info': "asdf"})
 
1689
        conn._compare_cpu("asdf").AndRaise(exception.InvalidCPUInfo)
 
1690
 
 
1691
        self.mox.ReplayAll()
 
1692
        self.assertRaises(exception.InvalidCPUInfo,
 
1693
                          conn.check_can_live_migrate_destination,
 
1694
                          self.context, instance_ref, False, False)
 
1695
 
 
1696
    def test_check_can_live_migrate_dest_fail_space_with_block_migration(self):
 
1697
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1698
        dest = "fake_host_2"
 
1699
        src = instance_ref['host']
 
1700
        conn = libvirt_driver.LibvirtDriver(False)
 
1701
 
 
1702
        self.mox.StubOutWithMock(conn, '_get_compute_info')
 
1703
        self.mox.StubOutWithMock(conn, 'get_instance_disk_info')
 
1704
 
 
1705
        conn._get_compute_info(self.context, FLAGS.host).AndReturn(
 
1706
                                              {'disk_available_least': 0})
 
1707
        conn.get_instance_disk_info(instance_ref["name"]).AndReturn(
 
1708
                                            '[{"virt_disk_size":2}]')
 
1709
 
 
1710
        self.mox.ReplayAll()
 
1711
        self.assertRaises(exception.MigrationError,
 
1712
                          conn.check_can_live_migrate_destination,
 
1713
                          self.context, instance_ref, True, False)
 
1714
 
 
1715
    def test_check_can_live_migrate_dest_cleanup_works_correctly(self):
 
1716
        dest_check_data = {"filename": "file", "block_migration": True}
 
1717
        conn = libvirt_driver.LibvirtDriver(False)
 
1718
 
 
1719
        self.mox.StubOutWithMock(conn, '_cleanup_shared_storage_test_file')
 
1720
        conn._cleanup_shared_storage_test_file("file")
 
1721
 
 
1722
        self.mox.ReplayAll()
 
1723
        conn.check_can_live_migrate_destination_cleanup(self.context,
 
1724
                                                        dest_check_data)
 
1725
 
 
1726
    def test_check_can_live_migrate_source_works_correctly(self):
 
1727
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1728
        dest_check_data = {"filename": "file", "block_migration": True}
 
1729
        conn = libvirt_driver.LibvirtDriver(False)
 
1730
 
 
1731
        self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
 
1732
        conn._check_shared_storage_test_file("file").AndReturn(False)
 
1733
 
 
1734
        self.mox.ReplayAll()
 
1735
        conn.check_can_live_migrate_source(self.context, instance_ref,
 
1736
                                           dest_check_data)
 
1737
 
 
1738
    def test_check_can_live_migrate_dest_fail_shared_storage_with_blockm(self):
 
1739
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1740
        dest_check_data = {"filename": "file", "block_migration": True}
 
1741
        conn = libvirt_driver.LibvirtDriver(False)
 
1742
 
 
1743
        self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
 
1744
        conn._check_shared_storage_test_file("file").AndReturn(True)
 
1745
 
 
1746
        self.mox.ReplayAll()
 
1747
        self.assertRaises(exception.InvalidSharedStorage,
 
1748
                          conn.check_can_live_migrate_source,
 
1749
                          self.context, instance_ref, dest_check_data)
 
1750
 
 
1751
    def test_check_can_live_migrate_no_shared_storage_no_blck_mig_raises(self):
 
1752
        instance_ref = db.instance_create(self.context, self.test_instance)
 
1753
        dest_check_data = {"filename": "file", "block_migration": False}
 
1754
        conn = libvirt_driver.LibvirtDriver(False)
 
1755
 
 
1756
        self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
 
1757
        conn._check_shared_storage_test_file("file").AndReturn(False)
 
1758
 
 
1759
        self.mox.ReplayAll()
 
1760
        self.assertRaises(exception.InvalidSharedStorage,
 
1761
                          conn.check_can_live_migrate_source,
 
1762
                          self.context, instance_ref, dest_check_data)
 
1763
 
1376
1764
    def test_live_migration_raises_exception(self):
1377
1765
        """Confirms recover method is called when exceptions are raised."""
1378
1766
        # Preparing data
1425
1813
        db.volume_destroy(self.context, volume_ref['id'])
1426
1814
        db.instance_destroy(self.context, instance_ref['uuid'])
1427
1815
 
1428
 
    def test_pre_live_migration_works_correctly(self):
1429
 
        """Confirms pre_block_migration works correctly."""
 
1816
    def test_pre_live_migration_works_correctly_mocked(self):
1430
1817
        # Creating testdata
1431
1818
        vol = {'block_device_mapping': [
1432
1819
                  {'connection_info': 'dummy', 'mount_device': '/dev/sda'},
1433
1820
                  {'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
1434
1821
        conn = libvirt_driver.LibvirtDriver(False)
1435
1822
 
 
1823
        class FakeNetworkInfo():
 
1824
            def fixed_ips(self):
 
1825
                return ["test_ip_addr"]
 
1826
 
 
1827
        inst_ref = {'id': 'foo'}
 
1828
        c = context.get_admin_context()
 
1829
        nw_info = FakeNetworkInfo()
 
1830
 
1436
1831
        # Creating mocks
1437
1832
        self.mox.StubOutWithMock(driver, "block_device_info_get_mapping")
1438
1833
        driver.block_device_info_get_mapping(vol
1442
1837
            conn.volume_driver_method('connect_volume',
1443
1838
                                     v['connection_info'],
1444
1839
                                      v['mount_device'].rpartition("/")[2])
 
1840
        self.mox.StubOutWithMock(conn, 'plug_vifs')
 
1841
        conn.plug_vifs(mox.IsA(inst_ref), nw_info)
1445
1842
 
1446
 
        # Starting test
1447
1843
        self.mox.ReplayAll()
1448
 
        self.assertEqual(conn.pre_live_migration(vol), None)
 
1844
        result = conn.pre_live_migration(c, inst_ref, vol, nw_info)
 
1845
        self.assertEqual(result, None)
1449
1846
 
1450
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1451
1847
    def test_pre_block_migration_works_correctly(self):
1452
 
        """Confirms pre_block_migration works correctly."""
1453
1848
        # Replace instances_path since this testcase creates tmpfile
1454
1849
        with utils.tempdir() as tmpdir:
1455
1850
            self.flags(instances_path=tmpdir)
1456
1851
 
1457
1852
            # Test data
1458
1853
            instance_ref = db.instance_create(self.context, self.test_instance)
1459
 
            dummyjson = ('[{"path": "%s/disk", "disk_size": "10737418240",'
1460
 
                         ' "type": "raw", "backing_file": ""}]')
 
1854
            dummy_info = [{'path': '%s/disk' % tmpdir,
 
1855
                           'disk_size': 10737418240,
 
1856
                           'type': 'raw',
 
1857
                           'backing_file': ''},
 
1858
                          {'backing_file': 'otherdisk_1234567',
 
1859
                           'path': '%s/otherdisk' % tmpdir,
 
1860
                           'virt_disk_size': 10737418240}]
 
1861
            dummyjson = json.dumps(dummy_info)
1461
1862
 
1462
 
            # Preparing mocks
1463
1863
            # qemu-img should be mockd since test environment might not have
1464
1864
            # large disk space.
 
1865
            self.mox.StubOutWithMock(imagebackend.Image, 'cache')
 
1866
            imagebackend.Image.cache(context=mox.IgnoreArg(),
 
1867
                                     fn=mox.IgnoreArg(),
 
1868
                                     fname='otherdisk',
 
1869
                                     image_id=123456,
 
1870
                                     project_id='fake',
 
1871
                                     size=10737418240L,
 
1872
                                     user_id=None).AndReturn(None)
1465
1873
            self.mox.ReplayAll()
 
1874
 
1466
1875
            conn = libvirt_driver.LibvirtDriver(False)
1467
1876
            conn.pre_block_migration(self.context, instance_ref,
1468
 
                                     dummyjson % tmpdir)
 
1877
                                     dummyjson)
1469
1878
 
1470
1879
            self.assertTrue(os.path.exists('%s/%s/' %
1471
1880
                                           (tmpdir, instance_ref.name)))
1472
1881
 
1473
1882
        db.instance_destroy(self.context, instance_ref['uuid'])
1474
1883
 
1475
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1476
1884
    def test_get_instance_disk_info_works_correctly(self):
1477
 
        """Confirms pre_block_migration works correctly."""
1478
1885
        # Test data
1479
1886
        instance_ref = db.instance_create(self.context, self.test_instance)
1480
1887
        dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
1487
1894
                    "<target dev='vdb' bus='virtio'/></disk>"
1488
1895
                    "</devices></domain>")
1489
1896
 
1490
 
        ret = ("image: /test/disk\n"
1491
 
               "file format: raw\n"
1492
 
               "virtual size: 20G (21474836480 bytes)\n"
1493
 
               "disk size: 3.1G\n"
1494
 
               "cluster_size: 2097152\n"
1495
 
               "backing file: /test/dummy (actual path: /backing/file)\n")
1496
 
 
1497
1897
        # Preparing mocks
1498
1898
        vdmock = self.mox.CreateMock(libvirt.virDomain)
1499
1899
        self.mox.StubOutWithMock(vdmock, "XMLDesc")
1511
1911
 
1512
1912
        self.mox.StubOutWithMock(os.path, "getsize")
1513
1913
        os.path.getsize('/test/disk').AndReturn((10737418240))
 
1914
        os.path.getsize('/test/disk.local').AndReturn((21474836480))
 
1915
 
 
1916
        ret = ("image: /test/disk\n"
 
1917
               "file format: raw\n"
 
1918
               "virtual size: 20G (21474836480 bytes)\n"
 
1919
               "disk size: 3.1G\n"
 
1920
               "cluster_size: 2097152\n"
 
1921
               "backing file: /test/dummy (actual path: /backing/file)\n")
1514
1922
 
1515
1923
        self.mox.StubOutWithMock(utils, "execute")
1516
 
        utils.execute('qemu-img', 'info',
 
1924
        utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
1517
1925
                      '/test/disk.local').AndReturn((ret, ''))
1518
1926
 
1519
 
        os.path.getsize('/test/disk.local').AndReturn((21474836480))
1520
 
 
1521
1927
        self.mox.ReplayAll()
1522
1928
        conn = libvirt_driver.LibvirtDriver(False)
1523
1929
        info = conn.get_instance_disk_info(instance_ref.name)
1533
1939
 
1534
1940
        db.instance_destroy(self.context, instance_ref['uuid'])
1535
1941
 
1536
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1537
1942
    def test_spawn_with_network_info(self):
1538
1943
        # Preparing mocks
1539
1944
        def fake_none(self, instance):
1560
1965
                       fake_none)
1561
1966
 
1562
1967
        try:
1563
 
            conn.spawn(self.context, instance, None, network_info)
 
1968
            conn.spawn(self.context, instance, None, [], 'herp',
 
1969
                       network_info=network_info)
1564
1970
        except Exception, e:
1565
1971
            # assert that no exception is raised due to sha1 receiving an int
1566
 
            self.assertEqual(-1, str(e.message).find('must be string or buffer'
1567
 
                                                     ', not int'))
1568
 
            count = (0 <= str(e.message).find('Unexpected method call'))
 
1972
            self.assertEqual(-1, unicode(e).find('must be string or buffer'
 
1973
                                                 ', not int'))
 
1974
            self.assertNotIn('Unexpected method call', unicode(e))
1569
1975
 
1570
1976
        path = os.path.join(FLAGS.instances_path, instance.name)
1571
1977
        if os.path.isdir(path):
1649
2055
                return FakeVirtDomain(fake_dom_xml)
1650
2056
 
1651
2057
            def _fake_flush(self, fake_pty):
1652
 
                with open(fake_pty, 'r+') as fp:
 
2058
                with open(fake_pty, 'r') as fp:
1653
2059
                    return fp.read()
1654
2060
 
1655
2061
            self.create_fake_libvirt_mock()
1666
2072
        ip = conn.get_host_ip_addr()
1667
2073
        self.assertEquals(ip, FLAGS.my_ip)
1668
2074
 
1669
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1670
2075
    def test_broken_connection(self):
1671
2076
        for (error, domain) in (
1672
2077
                (libvirt.VIR_ERR_SYSTEM_ERROR, libvirt.VIR_FROM_REMOTE),
1727
2132
        _assert_volume_in_mapping('sdg', False)
1728
2133
        _assert_volume_in_mapping('sdh1', False)
1729
2134
 
1730
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1731
2135
    def test_immediate_delete(self):
1732
2136
        def fake_lookup_by_name(instance_name):
1733
2137
            raise exception.InstanceNotFound()
1738
2142
        instance = db.instance_create(self.context, self.test_instance)
1739
2143
        conn.destroy(instance, {})
1740
2144
 
1741
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1742
2145
    def test_destroy_saved(self):
1743
2146
        """Ensure destroy calls managedSaveRemove for saved instance"""
1744
2147
        mock = self.mox.CreateMock(libvirt.virDomain)
1762
2165
                    "uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
1763
2166
        conn.destroy(instance, [])
1764
2167
 
1765
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1766
2168
    def test_private_destroy(self):
1767
2169
        """Ensure Instance not found skips undefine"""
1768
2170
        mock = self.mox.CreateMock(libvirt.virDomain)
1783
2185
        result = conn._destroy(instance)
1784
2186
        self.assertTrue(result)
1785
2187
 
1786
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
1787
2188
    def test_private_destroy_not_found(self):
1788
2189
        """Ensure Instance not found skips undefine"""
1789
2190
        mock = self.mox.CreateMock(libvirt.virDomain)
1841
2242
            caps.host.cpu = cpu
1842
2243
 
1843
2244
            guest = config.LibvirtConfigGuest()
1844
 
            guest.ostype = "hvm"
 
2245
            guest.ostype = vm_mode.HVM
1845
2246
            guest.arch = "x86_64"
 
2247
            guest.domtype = ["kvm"]
1846
2248
            caps.guests.append(guest)
1847
2249
 
1848
2250
            guest = config.LibvirtConfigGuest()
1849
 
            guest.ostype = "hvm"
 
2251
            guest.ostype = vm_mode.HVM
1850
2252
            guest.arch = "i686"
 
2253
            guest.domtype = ["kvm"]
1851
2254
            caps.guests.append(guest)
1852
2255
 
1853
2256
            return caps
1865
2268
        got = jsonutils.loads(conn.get_cpu_info())
1866
2269
        self.assertEqual(want, got)
1867
2270
 
 
2271
    def test_diagnostic_vcpus_exception(self):
 
2272
        xml = """
 
2273
                <domain type='kvm'>
 
2274
                    <devices>
 
2275
                        <disk type='file'>
 
2276
                            <source file='filename'/>
 
2277
                            <target dev='vda' bus='virtio'/>
 
2278
                        </disk>
 
2279
                        <disk type='block'>
 
2280
                            <source dev='/path/to/dev/1'/>
 
2281
                            <target dev='vdb' bus='virtio'/>
 
2282
                        </disk>
 
2283
                        <interface type='network'>
 
2284
                            <mac address='52:54:00:a4:38:38'/>
 
2285
                            <source network='default'/>
 
2286
                            <target dev='vnet0'/>
 
2287
                        </interface>
 
2288
                    </devices>
 
2289
                </domain>
 
2290
            """
 
2291
 
 
2292
        class DiagFakeDomain(FakeVirtDomain):
 
2293
 
 
2294
            def __init__(self):
 
2295
                super(DiagFakeDomain, self).__init__(fake_xml=xml)
 
2296
 
 
2297
            def vcpus(self):
 
2298
                raise libvirt.libvirtError('vcpus missing')
 
2299
 
 
2300
            def blockStats(self, path):
 
2301
                return (169L, 688640L, 0L, 0L, -1L)
 
2302
 
 
2303
            def interfaceStats(self, path):
 
2304
                return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
 
2305
 
 
2306
            def memoryStats(self):
 
2307
                return {'actual': 220160L, 'rss': 200164L}
 
2308
 
 
2309
            def maxMemory(self):
 
2310
                return 280160L
 
2311
 
 
2312
        def fake_lookup_name(name):
 
2313
            return DiagFakeDomain()
 
2314
 
 
2315
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
2316
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
2317
 
 
2318
        conn = libvirt_driver.LibvirtDriver(False)
 
2319
        actual = conn.get_diagnostics({"name": "testvirt"})
 
2320
        expect = {'vda_read': 688640L,
 
2321
                  'vda_read_req': 169L,
 
2322
                  'vda_write': 0L,
 
2323
                  'vda_write_req': 0L,
 
2324
                  'vda_errors': -1L,
 
2325
                  'vdb_read': 688640L,
 
2326
                  'vdb_read_req': 169L,
 
2327
                  'vdb_write': 0L,
 
2328
                  'vdb_write_req': 0L,
 
2329
                  'vdb_errors': -1L,
 
2330
                  'memory': 280160L,
 
2331
                  'memory-actual': 220160L,
 
2332
                  'memory-rss': 200164L,
 
2333
                  'vnet0_rx': 4408L,
 
2334
                  'vnet0_rx_drop': 0L,
 
2335
                  'vnet0_rx_errors': 0L,
 
2336
                  'vnet0_rx_packets': 82L,
 
2337
                  'vnet0_tx': 0L,
 
2338
                  'vnet0_tx_drop': 0L,
 
2339
                  'vnet0_tx_errors': 0L,
 
2340
                  'vnet0_tx_packets': 0L,
 
2341
                  }
 
2342
        self.assertEqual(actual, expect)
 
2343
 
 
2344
    def test_diagnostic_blockstats_exception(self):
 
2345
        xml = """
 
2346
                <domain type='kvm'>
 
2347
                    <devices>
 
2348
                        <disk type='file'>
 
2349
                            <source file='filename'/>
 
2350
                            <target dev='vda' bus='virtio'/>
 
2351
                        </disk>
 
2352
                        <disk type='block'>
 
2353
                            <source dev='/path/to/dev/1'/>
 
2354
                            <target dev='vdb' bus='virtio'/>
 
2355
                        </disk>
 
2356
                        <interface type='network'>
 
2357
                            <mac address='52:54:00:a4:38:38'/>
 
2358
                            <source network='default'/>
 
2359
                            <target dev='vnet0'/>
 
2360
                        </interface>
 
2361
                    </devices>
 
2362
                </domain>
 
2363
            """
 
2364
 
 
2365
        class DiagFakeDomain(FakeVirtDomain):
 
2366
 
 
2367
            def __init__(self):
 
2368
                super(DiagFakeDomain, self).__init__(fake_xml=xml)
 
2369
 
 
2370
            def vcpus(self):
 
2371
                return ([(0, 1, 15340000000L, 0),
 
2372
                         (1, 1, 1640000000L, 0),
 
2373
                         (2, 1, 3040000000L, 0),
 
2374
                         (3, 1, 1420000000L, 0)],
 
2375
                        [(True, False),
 
2376
                         (True, False),
 
2377
                         (True, False),
 
2378
                         (True, False)])
 
2379
 
 
2380
            def blockStats(self, path):
 
2381
                raise libvirt.libvirtError('blockStats missing')
 
2382
 
 
2383
            def interfaceStats(self, path):
 
2384
                return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
 
2385
 
 
2386
            def memoryStats(self):
 
2387
                return {'actual': 220160L, 'rss': 200164L}
 
2388
 
 
2389
            def maxMemory(self):
 
2390
                return 280160L
 
2391
 
 
2392
        def fake_lookup_name(name):
 
2393
            return DiagFakeDomain()
 
2394
 
 
2395
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
2396
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
2397
 
 
2398
        conn = libvirt_driver.LibvirtDriver(False)
 
2399
        actual = conn.get_diagnostics({"name": "testvirt"})
 
2400
        expect = {'cpu0_time': 15340000000L,
 
2401
                  'cpu1_time': 1640000000L,
 
2402
                  'cpu2_time': 3040000000L,
 
2403
                  'cpu3_time': 1420000000L,
 
2404
                  'memory': 280160L,
 
2405
                  'memory-actual': 220160L,
 
2406
                  'memory-rss': 200164L,
 
2407
                  'vnet0_rx': 4408L,
 
2408
                  'vnet0_rx_drop': 0L,
 
2409
                  'vnet0_rx_errors': 0L,
 
2410
                  'vnet0_rx_packets': 82L,
 
2411
                  'vnet0_tx': 0L,
 
2412
                  'vnet0_tx_drop': 0L,
 
2413
                  'vnet0_tx_errors': 0L,
 
2414
                  'vnet0_tx_packets': 0L,
 
2415
                  }
 
2416
        self.assertEqual(actual, expect)
 
2417
 
 
2418
    def test_diagnostic_interfacestats_exception(self):
 
2419
        xml = """
 
2420
                <domain type='kvm'>
 
2421
                    <devices>
 
2422
                        <disk type='file'>
 
2423
                            <source file='filename'/>
 
2424
                            <target dev='vda' bus='virtio'/>
 
2425
                        </disk>
 
2426
                        <disk type='block'>
 
2427
                            <source dev='/path/to/dev/1'/>
 
2428
                            <target dev='vdb' bus='virtio'/>
 
2429
                        </disk>
 
2430
                        <interface type='network'>
 
2431
                            <mac address='52:54:00:a4:38:38'/>
 
2432
                            <source network='default'/>
 
2433
                            <target dev='vnet0'/>
 
2434
                        </interface>
 
2435
                    </devices>
 
2436
                </domain>
 
2437
            """
 
2438
 
 
2439
        class DiagFakeDomain(FakeVirtDomain):
 
2440
 
 
2441
            def __init__(self):
 
2442
                super(DiagFakeDomain, self).__init__(fake_xml=xml)
 
2443
 
 
2444
            def vcpus(self):
 
2445
                return ([(0, 1, 15340000000L, 0),
 
2446
                         (1, 1, 1640000000L, 0),
 
2447
                         (2, 1, 3040000000L, 0),
 
2448
                         (3, 1, 1420000000L, 0)],
 
2449
                        [(True, False),
 
2450
                         (True, False),
 
2451
                         (True, False),
 
2452
                         (True, False)])
 
2453
 
 
2454
            def blockStats(self, path):
 
2455
                return (169L, 688640L, 0L, 0L, -1L)
 
2456
 
 
2457
            def interfaceStats(self, path):
 
2458
                raise libvirt.libvirtError('interfaceStat missing')
 
2459
 
 
2460
            def memoryStats(self):
 
2461
                return {'actual': 220160L, 'rss': 200164L}
 
2462
 
 
2463
            def maxMemory(self):
 
2464
                return 280160L
 
2465
 
 
2466
        def fake_lookup_name(name):
 
2467
            return DiagFakeDomain()
 
2468
 
 
2469
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
2470
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
2471
 
 
2472
        conn = libvirt_driver.LibvirtDriver(False)
 
2473
        actual = conn.get_diagnostics({"name": "testvirt"})
 
2474
        expect = {'cpu0_time': 15340000000L,
 
2475
                  'cpu1_time': 1640000000L,
 
2476
                  'cpu2_time': 3040000000L,
 
2477
                  'cpu3_time': 1420000000L,
 
2478
                  'vda_read': 688640L,
 
2479
                  'vda_read_req': 169L,
 
2480
                  'vda_write': 0L,
 
2481
                  'vda_write_req': 0L,
 
2482
                  'vda_errors': -1L,
 
2483
                  'vdb_read': 688640L,
 
2484
                  'vdb_read_req': 169L,
 
2485
                  'vdb_write': 0L,
 
2486
                  'vdb_write_req': 0L,
 
2487
                  'vdb_errors': -1L,
 
2488
                  'memory': 280160L,
 
2489
                  'memory-actual': 220160L,
 
2490
                  'memory-rss': 200164L,
 
2491
                  }
 
2492
        self.assertEqual(actual, expect)
 
2493
 
 
2494
    def test_diagnostic_memorystats_exception(self):
 
2495
        xml = """
 
2496
                <domain type='kvm'>
 
2497
                    <devices>
 
2498
                        <disk type='file'>
 
2499
                            <source file='filename'/>
 
2500
                            <target dev='vda' bus='virtio'/>
 
2501
                        </disk>
 
2502
                        <disk type='block'>
 
2503
                            <source dev='/path/to/dev/1'/>
 
2504
                            <target dev='vdb' bus='virtio'/>
 
2505
                        </disk>
 
2506
                        <interface type='network'>
 
2507
                            <mac address='52:54:00:a4:38:38'/>
 
2508
                            <source network='default'/>
 
2509
                            <target dev='vnet0'/>
 
2510
                        </interface>
 
2511
                    </devices>
 
2512
                </domain>
 
2513
            """
 
2514
 
 
2515
        class DiagFakeDomain(FakeVirtDomain):
 
2516
 
 
2517
            def __init__(self):
 
2518
                super(DiagFakeDomain, self).__init__(fake_xml=xml)
 
2519
 
 
2520
            def vcpus(self):
 
2521
                return ([(0, 1, 15340000000L, 0),
 
2522
                         (1, 1, 1640000000L, 0),
 
2523
                         (2, 1, 3040000000L, 0),
 
2524
                         (3, 1, 1420000000L, 0)],
 
2525
                        [(True, False),
 
2526
                         (True, False),
 
2527
                         (True, False),
 
2528
                         (True, False)])
 
2529
 
 
2530
            def blockStats(self, path):
 
2531
                return (169L, 688640L, 0L, 0L, -1L)
 
2532
 
 
2533
            def interfaceStats(self, path):
 
2534
                return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
 
2535
 
 
2536
            def memoryStats(self):
 
2537
                raise libvirt.libvirtError('memoryStats missing')
 
2538
 
 
2539
            def maxMemory(self):
 
2540
                return 280160L
 
2541
 
 
2542
        def fake_lookup_name(name):
 
2543
            return DiagFakeDomain()
 
2544
 
 
2545
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
2546
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
2547
 
 
2548
        conn = libvirt_driver.LibvirtDriver(False)
 
2549
        actual = conn.get_diagnostics({"name": "testvirt"})
 
2550
        expect = {'cpu0_time': 15340000000L,
 
2551
                  'cpu1_time': 1640000000L,
 
2552
                  'cpu2_time': 3040000000L,
 
2553
                  'cpu3_time': 1420000000L,
 
2554
                  'vda_read': 688640L,
 
2555
                  'vda_read_req': 169L,
 
2556
                  'vda_write': 0L,
 
2557
                  'vda_write_req': 0L,
 
2558
                  'vda_errors': -1L,
 
2559
                  'vdb_read': 688640L,
 
2560
                  'vdb_read_req': 169L,
 
2561
                  'vdb_write': 0L,
 
2562
                  'vdb_write_req': 0L,
 
2563
                  'vdb_errors': -1L,
 
2564
                  'memory': 280160L,
 
2565
                  'vnet0_rx': 4408L,
 
2566
                  'vnet0_rx_drop': 0L,
 
2567
                  'vnet0_rx_errors': 0L,
 
2568
                  'vnet0_rx_packets': 82L,
 
2569
                  'vnet0_tx': 0L,
 
2570
                  'vnet0_tx_drop': 0L,
 
2571
                  'vnet0_tx_errors': 0L,
 
2572
                  'vnet0_tx_packets': 0L,
 
2573
                  }
 
2574
        self.assertEqual(actual, expect)
 
2575
 
 
2576
    def test_diagnostic_full(self):
 
2577
        xml = """
 
2578
                <domain type='kvm'>
 
2579
                    <devices>
 
2580
                        <disk type='file'>
 
2581
                            <source file='filename'/>
 
2582
                            <target dev='vda' bus='virtio'/>
 
2583
                        </disk>
 
2584
                        <disk type='block'>
 
2585
                            <source dev='/path/to/dev/1'/>
 
2586
                            <target dev='vdb' bus='virtio'/>
 
2587
                        </disk>
 
2588
                        <interface type='network'>
 
2589
                            <mac address='52:54:00:a4:38:38'/>
 
2590
                            <source network='default'/>
 
2591
                            <target dev='vnet0'/>
 
2592
                        </interface>
 
2593
                    </devices>
 
2594
                </domain>
 
2595
            """
 
2596
 
 
2597
        class DiagFakeDomain(FakeVirtDomain):
 
2598
 
 
2599
            def __init__(self):
 
2600
                super(DiagFakeDomain, self).__init__(fake_xml=xml)
 
2601
 
 
2602
            def vcpus(self):
 
2603
                return ([(0, 1, 15340000000L, 0),
 
2604
                         (1, 1, 1640000000L, 0),
 
2605
                         (2, 1, 3040000000L, 0),
 
2606
                         (3, 1, 1420000000L, 0)],
 
2607
                        [(True, False),
 
2608
                         (True, False),
 
2609
                         (True, False),
 
2610
                         (True, False)])
 
2611
 
 
2612
            def blockStats(self, path):
 
2613
                return (169L, 688640L, 0L, 0L, -1L)
 
2614
 
 
2615
            def interfaceStats(self, path):
 
2616
                return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
 
2617
 
 
2618
            def memoryStats(self):
 
2619
                return {'actual': 220160L, 'rss': 200164L}
 
2620
 
 
2621
            def maxMemory(self):
 
2622
                return 280160L
 
2623
 
 
2624
        def fake_lookup_name(name):
 
2625
            return DiagFakeDomain()
 
2626
 
 
2627
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
2628
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
2629
 
 
2630
        conn = libvirt_driver.LibvirtDriver(False)
 
2631
        actual = conn.get_diagnostics({"name": "testvirt"})
 
2632
        expect = {'cpu0_time': 15340000000L,
 
2633
                  'cpu1_time': 1640000000L,
 
2634
                  'cpu2_time': 3040000000L,
 
2635
                  'cpu3_time': 1420000000L,
 
2636
                  'vda_read': 688640L,
 
2637
                  'vda_read_req': 169L,
 
2638
                  'vda_write': 0L,
 
2639
                  'vda_write_req': 0L,
 
2640
                  'vda_errors': -1L,
 
2641
                  'vdb_read': 688640L,
 
2642
                  'vdb_read_req': 169L,
 
2643
                  'vdb_write': 0L,
 
2644
                  'vdb_write_req': 0L,
 
2645
                  'vdb_errors': -1L,
 
2646
                  'memory': 280160L,
 
2647
                  'memory-actual': 220160L,
 
2648
                  'memory-rss': 200164L,
 
2649
                  'vnet0_rx': 4408L,
 
2650
                  'vnet0_rx_drop': 0L,
 
2651
                  'vnet0_rx_errors': 0L,
 
2652
                  'vnet0_rx_packets': 82L,
 
2653
                  'vnet0_tx': 0L,
 
2654
                  'vnet0_tx_drop': 0L,
 
2655
                  'vnet0_tx_errors': 0L,
 
2656
                  'vnet0_tx_packets': 0L,
 
2657
                  }
 
2658
        self.assertEqual(actual, expect)
 
2659
 
 
2660
    def test_get_instance_capabilities(self):
 
2661
        conn = libvirt_driver.LibvirtDriver(True)
 
2662
 
 
2663
        def get_host_capabilities_stub(self):
 
2664
            caps = config.LibvirtConfigCaps()
 
2665
 
 
2666
            guest = config.LibvirtConfigGuest()
 
2667
            guest.ostype = 'hvm'
 
2668
            guest.arch = 'x86_64'
 
2669
            guest.domtype = ['kvm', 'qemu']
 
2670
            caps.guests.append(guest)
 
2671
 
 
2672
            guest = config.LibvirtConfigGuest()
 
2673
            guest.ostype = 'hvm'
 
2674
            guest.arch = 'i686'
 
2675
            guest.domtype = ['kvm']
 
2676
            caps.guests.append(guest)
 
2677
 
 
2678
            return caps
 
2679
 
 
2680
        self.stubs.Set(libvirt_driver.LibvirtDriver,
 
2681
                       'get_host_capabilities',
 
2682
                       get_host_capabilities_stub)
 
2683
 
 
2684
        want = [('x86_64', 'kvm', 'hvm'),
 
2685
                ('x86_64', 'qemu', 'hvm'),
 
2686
                ('i686', 'kvm', 'hvm')]
 
2687
        got = conn.get_instance_capabilities()
 
2688
        self.assertEqual(want, got)
 
2689
 
1868
2690
 
1869
2691
class HostStateTestCase(test.TestCase):
1870
2692
 
1873
2695
                 '"fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge", '
1874
2696
                 '"mtrr", "sep", "apic"], '
1875
2697
                 '"topology": {"cores": "1", "threads": "1", "sockets": "1"}}')
 
2698
    instance_caps = [("x86_64", "kvm", "hvm"), ("i686", "kvm", "hvm")]
1876
2699
 
1877
2700
    class FakeConnection(object):
1878
2701
        """Fake connection object"""
1907
2730
        def get_hypervisor_hostname(self):
1908
2731
            return 'compute1'
1909
2732
 
 
2733
        def get_host_uptime(self):
 
2734
            return ('10:01:16 up  1:36,  6 users,  '
 
2735
                    'load average: 0.21, 0.16, 0.19')
 
2736
 
1910
2737
        def get_disk_available_least(self):
1911
2738
            return 13091
1912
2739
 
 
2740
        def get_instance_capabilities(self):
 
2741
            return HostStateTestCase.instance_caps
 
2742
 
1913
2743
    def test_update_status(self):
1914
2744
        self.mox.StubOutWithMock(libvirt_driver, 'LibvirtDriver')
1915
2745
        libvirt_driver.LibvirtDriver(True).AndReturn(self.FakeConnection())
1993
2823
      ':FORWARD ACCEPT [0:0]',
1994
2824
      ':OUTPUT ACCEPT [915599:63811649]',
1995
2825
      ':nova-block-ipv4 - [0:0]',
1996
 
      '-A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ',
1997
 
      '-A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED'
 
2826
      '[0:0] -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ',
 
2827
      '[0:0] -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED'
1998
2828
      ',ESTABLISHED -j ACCEPT ',
1999
 
      '-A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ',
2000
 
      '-A FORWARD -i virbr0 -o virbr0 -j ACCEPT ',
2001
 
      '-A FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable ',
2002
 
      '-A FORWARD -i virbr0 -j REJECT --reject-with icmp-port-unreachable ',
 
2829
      '[0:0] -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ',
 
2830
      '[0:0] -A FORWARD -i virbr0 -o virbr0 -j ACCEPT ',
 
2831
      '[0:0] -A FORWARD -o virbr0 -j REJECT '
 
2832
      '--reject-with icmp-port-unreachable ',
 
2833
      '[0:0] -A FORWARD -i virbr0 -j REJECT '
 
2834
      '--reject-with icmp-port-unreachable ',
2003
2835
      'COMMIT',
2004
2836
      '# Completed on Mon Dec  6 11:54:13 2010',
2005
2837
    ]
2079
2911
#        self.fw.add_instance(instance_ref)
2080
2912
        def fake_iptables_execute(*cmd, **kwargs):
2081
2913
            process_input = kwargs.get('process_input', None)
2082
 
            if cmd == ('ip6tables-save', '-t', 'filter'):
 
2914
            if cmd == ('ip6tables-save', '-c', '-t', 'filter'):
2083
2915
                return '\n'.join(self.in6_filter_rules), None
2084
 
            if cmd == ('iptables-save', '-t', 'filter'):
 
2916
            if cmd == ('iptables-save', '-c', '-t', 'filter'):
2085
2917
                return '\n'.join(self.in_filter_rules), None
2086
 
            if cmd == ('iptables-save', '-t', 'nat'):
 
2918
            if cmd == ('iptables-save', '-c', '-t', 'nat'):
2087
2919
                return '\n'.join(self.in_nat_rules), None
2088
 
            if cmd == ('iptables-restore',):
 
2920
            if cmd == ('iptables-restore', '-c',):
2089
2921
                lines = process_input.split('\n')
2090
2922
                if '*filter' in lines:
2091
2923
                    self.out_rules = lines
2092
2924
                return '', ''
2093
 
            if cmd == ('ip6tables-restore',):
 
2925
            if cmd == ('ip6tables-restore', '-c',):
2094
2926
                lines = process_input.split('\n')
2095
2927
                if '*filter' in lines:
2096
2928
                    self.out6_rules = lines
2133
2965
        self.assertTrue(security_group_chain,
2134
2966
                        "The security group chain wasn't added")
2135
2967
 
2136
 
        regex = re.compile('-A .* -j ACCEPT -p icmp -s 192.168.11.0/24')
 
2968
        regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp '
 
2969
                           '-s 192.168.11.0/24')
2137
2970
        self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
2138
2971
                        "ICMP acceptance rule wasn't added")
2139
2972
 
2140
 
        regex = re.compile('-A .* -j ACCEPT -p icmp -m icmp --icmp-type 8'
2141
 
                           ' -s 192.168.11.0/24')
 
2973
        regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp -m icmp '
 
2974
                           '--icmp-type 8 -s 192.168.11.0/24')
2142
2975
        self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
2143
2976
                        "ICMP Echo Request acceptance rule wasn't added")
2144
2977
 
2145
2978
        for ip in network_model.fixed_ips():
2146
2979
            if ip['version'] != 4:
2147
2980
                continue
2148
 
            regex = re.compile('-A .* -j ACCEPT -p tcp -m multiport '
 
2981
            regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp -m multiport '
2149
2982
                               '--dports 80:81 -s %s' % ip['address'])
2150
2983
            self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
2151
2984
                            "TCP port 80/81 acceptance rule wasn't added")
2152
 
            regex = re.compile('-A .* -j ACCEPT -s %s' % ip['address'])
 
2985
            regex = re.compile('\[0\:0\] -A .* -j ACCEPT -s '
 
2986
                               '%s' % ip['address'])
2153
2987
            self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
2154
2988
                            "Protocol/port-less acceptance rule wasn't added")
2155
2989
 
2156
 
        regex = re.compile('-A .* -j ACCEPT -p tcp '
 
2990
        regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp '
2157
2991
                           '-m multiport --dports 80:81 -s 192.168.10.0/24')
2158
2992
        self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
2159
2993
                        "TCP port 80/81 acceptance rule wasn't added")
2206
3040
        self.mox.ReplayAll()
2207
3041
        self.fw.do_refresh_security_group_rules("fake")
2208
3042
 
2209
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
2210
3043
    def test_unfilter_instance_undefines_nwfilter(self):
2211
3044
        admin_ctxt = context.get_admin_context()
2212
3045
 
2491
3324
        self.mox.ReplayAll()
2492
3325
        libvirt_utils.create_cow_image('/some/path', '/the/new/cow')
2493
3326
 
 
3327
    def test_pick_disk_driver_name(self):
 
3328
        type_map = {'kvm': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
 
3329
                    'qemu': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
 
3330
                    'xen': ([True, 'phy'], [False, 'tap'], [None, 'tap']),
 
3331
                    'uml': ([True, None], [False, None], [None, None]),
 
3332
                    'lxc': ([True, None], [False, None], [None, None])}
 
3333
 
 
3334
        for (libvirt_type, checks) in type_map.iteritems():
 
3335
            self.flags(libvirt_type=libvirt_type)
 
3336
            for (is_block_dev, expected_result) in checks:
 
3337
                result = libvirt_utils.pick_disk_driver_name(is_block_dev)
 
3338
                self.assertEquals(result, expected_result)
 
3339
 
2494
3340
    def test_get_disk_size(self):
2495
3341
        self.mox.StubOutWithMock(utils, 'execute')
2496
 
        utils.execute('qemu-img',
2497
 
                      'info',
 
3342
        utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
2498
3343
                      '/some/path').AndReturn(('''image: 00000001
2499
3344
file format: raw
2500
3345
virtual size: 4.4M (4592640 bytes)
2502
3347
 
2503
3348
        # Start test
2504
3349
        self.mox.ReplayAll()
2505
 
        self.assertEquals(libvirt_utils.get_disk_size('/some/path'), 4592640)
 
3350
        self.assertEquals(disk.get_disk_size('/some/path'), 4592640)
2506
3351
 
2507
3352
    def test_copy_image(self):
2508
3353
        dst_fd, dst_path = tempfile.mkstemp()
2568
3413
        self.mox.ReplayAll()
2569
3414
        libvirt_utils.chown('/some/path', 'soren')
2570
3415
 
2571
 
    def test_extract_snapshot(self):
 
3416
    def _do_test_extract_snapshot(self, dest_format='raw', out_format='raw'):
2572
3417
        self.mox.StubOutWithMock(utils, 'execute')
2573
 
        utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', 'raw',
 
3418
        utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', out_format,
2574
3419
                      '-s', 'snap1', '/path/to/disk/image', '/extracted/snap')
2575
3420
 
2576
3421
        # Start test
2577
3422
        self.mox.ReplayAll()
2578
3423
        libvirt_utils.extract_snapshot('/path/to/disk/image', 'qcow2',
2579
 
                                       'snap1', '/extracted/snap', 'raw')
 
3424
                                       'snap1', '/extracted/snap', dest_format)
 
3425
 
 
3426
    def test_extract_snapshot_raw(self):
 
3427
        self._do_test_extract_snapshot()
 
3428
 
 
3429
    def test_extract_snapshot_iso(self):
 
3430
        self._do_test_extract_snapshot(dest_format='iso')
 
3431
 
 
3432
    def test_extract_snapshot_qcow2(self):
 
3433
        self._do_test_extract_snapshot(dest_format='qcow2', out_format='qcow2')
2580
3434
 
2581
3435
    def test_load_file(self):
2582
3436
        dst_fd, dst_path = tempfile.mkstemp()
2650
3504
 
2651
3505
        def fake_execute(*args, **kwargs):
2652
3506
            if with_actual_path:
2653
 
                return ("some\n"
2654
 
                        "output\n"
 
3507
                return ("some: output\n"
2655
3508
                        "backing file: /foo/bar/baz (actual path: /a/b/c)\n"
2656
 
                        "...\n"), ''
 
3509
                        "...: ...\n"), ''
2657
3510
            else:
2658
 
                return ("some\n"
2659
 
                        "output\n"
 
3511
                return ("some: output\n"
2660
3512
                        "backing file: /foo/bar/baz\n"
2661
 
                        "...\n"), ''
 
3513
                        "...: ...\n"), ''
2662
3514
 
2663
3515
        self.stubs.Set(utils, 'execute', fake_execute)
2664
3516
 
2823
3675
                      'local_gb': 10, 'backing_file': '/base/disk.local'}]
2824
3676
        disk_info_text = jsonutils.dumps(disk_info)
2825
3677
 
 
3678
        def fake_can_resize_fs(path, size, use_cow=False):
 
3679
            return False
 
3680
 
2826
3681
        def fake_extend(path, size):
2827
3682
            pass
2828
3683
 
2851
3706
 
2852
3707
        self.flags(use_cow_images=True)
2853
3708
        self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend)
 
3709
        self.stubs.Set(libvirt_driver.disk, 'can_resize_fs',
 
3710
                       fake_can_resize_fs)
2854
3711
        self.stubs.Set(self.libvirtconnection, 'to_xml', fake_to_xml)
2855
3712
        self.stubs.Set(self.libvirtconnection, 'plug_vifs', fake_plug_vifs)
2856
3713
        self.stubs.Set(self.libvirtconnection, '_create_image',
2924
3781
    def tearDown(self):
2925
3782
        super(LibvirtNonblockingTestCase, self).tearDown()
2926
3783
 
2927
 
    @test.skip_if(missing_libvirt(), "Test requires libvirt")
2928
3784
    def test_connection_to_primitive(self):
2929
3785
        """Test bug 962840"""
2930
3786
        import nova.virt.libvirt.driver as libvirt_driver