~ubuntu-branches/ubuntu/raring/nova/raring-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: 2013-01-11 13:06:56 UTC
  • mto: This revision was merged to the branch mainline in revision 96.
  • Revision ID: package-import@ubuntu.com-20130111130656-z9mceux6qpkqomma
Tags: upstream-2013.1~g2
ImportĀ upstreamĀ versionĀ 2013.1~g2

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
import copy
19
19
import errno
20
20
import eventlet
 
21
import fixtures
21
22
import json
22
23
import mox
23
24
import os
31
32
from nova.api.ec2 import cloud
32
33
from nova.compute import instance_types
33
34
from nova.compute import power_state
 
35
from nova.compute import task_states
34
36
from nova.compute import vm_mode
35
37
from nova.compute import vm_states
36
38
from nova import context
47
49
import nova.tests.image.fake
48
50
from nova.tests import matchers
49
51
from nova import utils
 
52
from nova import version
50
53
from nova.virt.disk import api as disk
51
54
from nova.virt import driver
52
55
from nova.virt import fake
56
59
from nova.virt.libvirt import driver as libvirt_driver
57
60
from nova.virt.libvirt import firewall
58
61
from nova.virt.libvirt import imagebackend
59
 
from nova.virt.libvirt import snapshots
60
62
from nova.virt.libvirt import utils as libvirt_utils
61
63
from nova.virt.libvirt import volume
62
64
from nova.virt.libvirt import volume_nfs
70
72
 
71
73
 
72
74
CONF = cfg.CONF
73
 
CONF.import_opt('compute_manager', 'nova.config')
 
75
CONF.import_opt('compute_manager', 'nova.service')
74
76
CONF.import_opt('host', 'nova.config')
75
77
CONF.import_opt('my_ip', 'nova.config')
 
78
CONF.import_opt('base_dir_name', 'nova.virt.libvirt.imagecache')
76
79
LOG = logging.getLogger(__name__)
77
80
 
78
81
_fake_network_info = fake_network.fake_get_instance_nw_info
80
83
_ipv4_like = fake_network.ipv4_like
81
84
 
82
85
 
83
 
def _concurrency(wait, done, target):
 
86
def _concurrency(signal, wait, done, target):
 
87
    signal.send()
84
88
    wait.wait()
85
89
    done.send()
86
90
 
403
407
        self.assertEqual(tree.find('./auth/secret').get('uuid'), flags_uuid)
404
408
        libvirt_driver.disconnect_volume(connection_info, mount_device)
405
409
 
406
 
    def test_libvirt_lxc_volume(self):
407
 
        self.stubs.Set(os.path, 'exists', lambda x: True)
408
 
        libvirt_driver = volume.LibvirtISCSIVolumeDriver(self.fake_conn)
409
 
        name = 'volume-00000001'
410
 
        location = '10.0.2.15:3260'
411
 
        iqn = 'iqn.2010-10.org.openstack:%s' % name
412
 
        vol = {'id': 1, 'name': name}
413
 
        connection_info = self.iscsi_connection(vol, location, iqn)
414
 
        mount_device = "vde"
415
 
        conf = libvirt_driver.connect_volume(connection_info, mount_device)
416
 
        tree = conf.format_dom()
417
 
        dev_str = '/dev/disk/by-path/ip-%s-iscsi-%s-lun-1' % (location, iqn)
418
 
        self.assertEqual(tree.get('type'), 'block')
419
 
        self.assertEqual(tree.find('./source').get('dev'), dev_str)
420
 
        libvirt_driver.disconnect_volume(connection_info, mount_device)
421
 
 
422
410
    def test_libvirt_nfs_driver(self):
423
411
        # NOTE(vish) exists is to make driver assume connecting worked
424
412
        mnt_base = '/mnt'
473
461
        self.stubs.Set(os.path, 'exists', fake_exists)
474
462
        self.stubs.Set(utils, 'execute', fake_execute)
475
463
        self.stubs.Set(imagebackend.disk, 'extend', fake_extend)
476
 
        imagebackend.libvirt_utils = fake_libvirt_utils
 
464
        self.useFixture(fixtures.MonkeyPatch(
 
465
            'nova.virt.libvirt.imagebackend.libvirt_utils',
 
466
            fake_libvirt_utils))
477
467
 
478
468
    def tearDown(self):
479
 
        imagebackend.libvirt_utils = libvirt_utils
480
 
 
481
469
        # Make sure the lock_path for this test is cleaned up
482
470
        if os.path.exists(self.lock_path):
483
471
            shutil.rmtree(self.lock_path)
489
477
        backend = imagebackend.Backend(False)
490
478
        wait1 = eventlet.event.Event()
491
479
        done1 = eventlet.event.Event()
 
480
        sig1 = eventlet.event.Event()
492
481
        thr1 = eventlet.spawn(backend.image('instance', 'name').cache,
493
 
                _concurrency, 'fname', None, wait=wait1, done=done1)
 
482
                _concurrency, 'fname', None,
 
483
                signal=sig1, wait=wait1, done=done1)
 
484
        eventlet.sleep(0)
 
485
        # Thread 1 should run before thread 2.
 
486
        sig1.wait()
 
487
 
494
488
        wait2 = eventlet.event.Event()
495
489
        done2 = eventlet.event.Event()
 
490
        sig2 = eventlet.event.Event()
496
491
        thr2 = eventlet.spawn(backend.image('instance', 'name').cache,
497
 
                _concurrency, 'fname', None, wait=wait2, done=done2)
 
492
                _concurrency, 'fname', None,
 
493
                signal=sig2, wait=wait2, done=done2)
 
494
 
498
495
        wait2.send()
499
496
        eventlet.sleep(0)
500
497
        try:
514
511
        backend = imagebackend.Backend(False)
515
512
        wait1 = eventlet.event.Event()
516
513
        done1 = eventlet.event.Event()
 
514
        sig1 = eventlet.event.Event()
517
515
        thr1 = eventlet.spawn(backend.image('instance', 'name').cache,
518
 
                _concurrency, 'fname2', None, wait=wait1, done=done1)
 
516
                _concurrency, 'fname2', None,
 
517
                signal=sig1, wait=wait1, done=done1)
 
518
        eventlet.sleep(0)
 
519
        # Thread 1 should run before thread 2.
 
520
        sig1.wait()
 
521
 
519
522
        wait2 = eventlet.event.Event()
520
523
        done2 = eventlet.event.Event()
 
524
        sig2 = eventlet.event.Event()
521
525
        thr2 = eventlet.spawn(backend.image('instance', 'name').cache,
522
 
                _concurrency, 'fname1', None, wait=wait2, done=done2)
 
526
                _concurrency, 'fname1', None,
 
527
                signal=sig2, wait=wait2, done=done2)
 
528
        eventlet.sleep(0)
 
529
        # Wait for thread 2 to start.
 
530
        sig2.wait()
 
531
 
523
532
        wait2.send()
524
533
        eventlet.sleep(0)
525
534
        try:
558
567
        self.flags(instances_path='')
559
568
        self.flags(libvirt_snapshots_directory='')
560
569
        self.call_libvirt_dependant_setup = False
561
 
        libvirt_driver.libvirt_utils = fake_libvirt_utils
562
 
        snapshots.libvirt_utils = fake_libvirt_utils
 
570
        self.useFixture(fixtures.MonkeyPatch(
 
571
            'nova.virt.libvirt.driver.libvirt_utils',
 
572
            fake_libvirt_utils))
 
573
        self.useFixture(fixtures.MonkeyPatch(
 
574
            'nova.virt.libvirt.snapshots.libvirt_utils',
 
575
            fake_libvirt_utils))
563
576
 
564
577
        def fake_extend(image, size):
565
578
            pass
568
581
 
569
582
        nova.tests.image.fake.stub_out_image_service(self.stubs)
570
583
        self.test_instance = {
 
584
                'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310',
571
585
                'memory_kb': '1024000',
572
586
                'basepath': '/some/path',
573
587
                'bridge_name': 'br100',
580
594
                'instance_type_id': '5'}  # m1.small
581
595
 
582
596
    def tearDown(self):
583
 
        libvirt_driver.libvirt_utils = libvirt_utils
584
597
        nova.tests.image.fake.FakeImageService_reset()
585
598
        super(LibvirtConnTestCase, self).tearDown()
586
599
 
615
628
        service_ref = {'host': kwargs.get('host', 'dummy'),
616
629
                       'binary': 'nova-compute',
617
630
                       'topic': 'compute',
618
 
                       'report_count': 0,
619
 
                       'availability_zone': 'zone'}
 
631
                       'report_count': 0}
620
632
 
621
633
        return db.service_create(context.get_admin_context(), service_ref)
622
634
 
647
659
                                    _fake_network_info(self.stubs, 1),
648
660
                                    None, None)
649
661
        self.assertEquals(cfg.acpi, True)
 
662
        self.assertEquals(cfg.apic, True)
650
663
        self.assertEquals(cfg.memory, 1024 * 1024 * 2)
651
664
        self.assertEquals(cfg.vcpus, 1)
652
665
        self.assertEquals(cfg.os_type, vm_mode.HVM)
997
1010
                                expect_ramdisk=False, rescue=instance_data)
998
1011
 
999
1012
    def test_xml_uuid(self):
1000
 
        instance_data = dict(self.test_instance)
1001
 
        self._check_xml_and_uuid(instance_data)
 
1013
        self._check_xml_and_uuid({"disk_format": "raw"})
1002
1014
 
1003
1015
    def test_lxc_container_and_uri(self):
1004
1016
        instance_data = dict(self.test_instance)
1044
1056
        libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
1045
1057
        libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 2
1046
1058
        libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
 
1059
        libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
1047
1060
 
1048
1061
        self.mox.ReplayAll()
1049
1062
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1051
1064
        # Only one should be listed, since domain with ID 0 must be skiped
1052
1065
        self.assertEquals(len(instances), 1)
1053
1066
 
 
1067
    def test_list_defined_instances(self):
 
1068
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
 
1069
        libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
 
1070
        libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
 
1071
        libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0]
 
1072
        libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [1]
 
1073
 
 
1074
        self.mox.ReplayAll()
 
1075
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
1076
        instances = conn.list_instances()
 
1077
        # Only one defined domain should be listed
 
1078
        self.assertEquals(len(instances), 1)
 
1079
 
1054
1080
    def test_list_instances_when_instance_deleted(self):
1055
1081
 
1056
1082
        def fake_lookup(instance_name):
1060
1086
        libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
1061
1087
        libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
1062
1088
        libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
 
1089
        libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
1063
1090
 
1064
1091
        self.mox.ReplayAll()
1065
1092
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1174
1201
        libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4)
1175
1202
        libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
1176
1203
        libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
 
1204
        libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
1177
1205
 
1178
1206
        self.mox.ReplayAll()
1179
1207
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1181
1209
        self.assertEqual(devices, ['vda', 'vdb'])
1182
1210
 
1183
1211
    def test_snapshot_in_ami_format(self):
 
1212
        expected_calls = [
 
1213
            {'args': (),
 
1214
             'kwargs':
 
1215
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1216
            {'args': (),
 
1217
             'kwargs':
 
1218
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1219
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1220
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1221
 
1184
1222
        self.flags(libvirt_snapshots_directory='./')
1185
1223
 
1186
1224
        # Start test
1210
1248
        self.mox.ReplayAll()
1211
1249
 
1212
1250
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1213
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1251
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1252
                      func_call_matcher.call)
1214
1253
 
1215
1254
        snapshot = image_service.show(context, recv_meta['id'])
 
1255
        self.assertIsNone(func_call_matcher.match())
 
1256
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1216
1257
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1217
1258
        self.assertEquals(snapshot['status'], 'active')
1218
1259
        self.assertEquals(snapshot['disk_format'], 'ami')
1219
1260
        self.assertEquals(snapshot['name'], snapshot_name)
1220
1261
 
1221
1262
    def test_lxc_snapshot_in_ami_format(self):
 
1263
        expected_calls = [
 
1264
            {'args': (),
 
1265
             'kwargs':
 
1266
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1267
            {'args': (),
 
1268
             'kwargs':
 
1269
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1270
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1271
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1272
 
1222
1273
        self.flags(libvirt_snapshots_directory='./',
1223
1274
                   libvirt_type='lxc')
1224
1275
 
1249
1300
        self.mox.ReplayAll()
1250
1301
 
1251
1302
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1252
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1303
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1304
                      func_call_matcher.call)
1253
1305
 
1254
1306
        snapshot = image_service.show(context, recv_meta['id'])
 
1307
        self.assertIsNone(func_call_matcher.match())
1255
1308
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1256
1309
        self.assertEquals(snapshot['status'], 'active')
1257
1310
        self.assertEquals(snapshot['disk_format'], 'ami')
1258
1311
        self.assertEquals(snapshot['name'], snapshot_name)
1259
1312
 
1260
1313
    def test_snapshot_in_raw_format(self):
 
1314
        expected_calls = [
 
1315
            {'args': (),
 
1316
             'kwargs':
 
1317
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1318
            {'args': (),
 
1319
             'kwargs':
 
1320
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1321
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1322
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1323
 
1261
1324
        self.flags(libvirt_snapshots_directory='./')
1262
1325
 
1263
1326
        # Start test
1288
1351
        self.mox.ReplayAll()
1289
1352
 
1290
1353
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1291
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1354
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1355
                      func_call_matcher.call)
1292
1356
 
1293
1357
        snapshot = image_service.show(context, recv_meta['id'])
 
1358
        self.assertIsNone(func_call_matcher.match())
1294
1359
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1295
1360
        self.assertEquals(snapshot['status'], 'active')
1296
1361
        self.assertEquals(snapshot['disk_format'], 'raw')
1297
1362
        self.assertEquals(snapshot['name'], snapshot_name)
1298
1363
 
1299
1364
    def test_lxc_snapshot_in_raw_format(self):
 
1365
        expected_calls = [
 
1366
            {'args': (),
 
1367
             'kwargs':
 
1368
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1369
            {'args': (),
 
1370
             'kwargs':
 
1371
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1372
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1373
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1374
 
1300
1375
        self.flags(libvirt_snapshots_directory='./',
1301
1376
                   libvirt_type='lxc')
1302
1377
 
1328
1403
        self.mox.ReplayAll()
1329
1404
 
1330
1405
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1331
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1406
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1407
                      func_call_matcher.call)
1332
1408
 
1333
1409
        snapshot = image_service.show(context, recv_meta['id'])
 
1410
        self.assertIsNone(func_call_matcher.match())
1334
1411
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1335
1412
        self.assertEquals(snapshot['status'], 'active')
1336
1413
        self.assertEquals(snapshot['disk_format'], 'raw')
1337
1414
        self.assertEquals(snapshot['name'], snapshot_name)
1338
1415
 
1339
1416
    def test_snapshot_in_qcow2_format(self):
 
1417
        expected_calls = [
 
1418
            {'args': (),
 
1419
             'kwargs':
 
1420
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1421
            {'args': (),
 
1422
             'kwargs':
 
1423
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1424
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1425
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1426
 
1340
1427
        self.flags(snapshot_image_format='qcow2',
1341
1428
                   libvirt_snapshots_directory='./')
1342
1429
 
1363
1450
        self.mox.ReplayAll()
1364
1451
 
1365
1452
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1366
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1453
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1454
                      func_call_matcher.call)
1367
1455
 
1368
1456
        snapshot = image_service.show(context, recv_meta['id'])
 
1457
        self.assertIsNone(func_call_matcher.match())
1369
1458
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1370
1459
        self.assertEquals(snapshot['status'], 'active')
1371
1460
        self.assertEquals(snapshot['disk_format'], 'qcow2')
1372
1461
        self.assertEquals(snapshot['name'], snapshot_name)
1373
1462
 
1374
1463
    def test_lxc_snapshot_in_qcow2_format(self):
 
1464
        expected_calls = [
 
1465
            {'args': (),
 
1466
             'kwargs':
 
1467
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1468
            {'args': (),
 
1469
             'kwargs':
 
1470
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1471
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1472
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1473
 
1375
1474
        self.flags(snapshot_image_format='qcow2',
1376
1475
                   libvirt_snapshots_directory='./',
1377
1476
                   libvirt_type='lxc')
1399
1498
        self.mox.ReplayAll()
1400
1499
 
1401
1500
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1402
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1501
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1502
                      func_call_matcher.call)
1403
1503
 
1404
1504
        snapshot = image_service.show(context, recv_meta['id'])
 
1505
        self.assertIsNone(func_call_matcher.match())
1405
1506
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1406
1507
        self.assertEquals(snapshot['status'], 'active')
1407
1508
        self.assertEquals(snapshot['disk_format'], 'qcow2')
1408
1509
        self.assertEquals(snapshot['name'], snapshot_name)
1409
1510
 
1410
1511
    def test_snapshot_no_image_architecture(self):
 
1512
        expected_calls = [
 
1513
            {'args': (),
 
1514
             'kwargs':
 
1515
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1516
            {'args': (),
 
1517
             'kwargs':
 
1518
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1519
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1520
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1521
 
1411
1522
        self.flags(libvirt_snapshots_directory='./')
1412
1523
 
1413
1524
        # Start test
1437
1548
        self.mox.ReplayAll()
1438
1549
 
1439
1550
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1440
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1551
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1552
                      func_call_matcher.call)
1441
1553
 
1442
1554
        snapshot = image_service.show(context, recv_meta['id'])
 
1555
        self.assertIsNone(func_call_matcher.match())
1443
1556
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1444
1557
        self.assertEquals(snapshot['status'], 'active')
1445
1558
        self.assertEquals(snapshot['name'], snapshot_name)
1446
1559
 
1447
1560
    def test_lxc_snapshot_no_image_architecture(self):
 
1561
        expected_calls = [
 
1562
            {'args': (),
 
1563
             'kwargs':
 
1564
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1565
            {'args': (),
 
1566
             'kwargs':
 
1567
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1568
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1569
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1570
 
1448
1571
        self.flags(libvirt_snapshots_directory='./',
1449
1572
                   libvirt_type='lxc')
1450
1573
 
1475
1598
        self.mox.ReplayAll()
1476
1599
 
1477
1600
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1478
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1601
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1602
                      func_call_matcher.call)
1479
1603
 
1480
1604
        snapshot = image_service.show(context, recv_meta['id'])
 
1605
        self.assertIsNone(func_call_matcher.match())
1481
1606
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1482
1607
        self.assertEquals(snapshot['status'], 'active')
1483
1608
        self.assertEquals(snapshot['name'], snapshot_name)
1484
1609
 
1485
1610
    def test_snapshot_no_original_image(self):
 
1611
        expected_calls = [
 
1612
            {'args': (),
 
1613
             'kwargs':
 
1614
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1615
            {'args': (),
 
1616
             'kwargs':
 
1617
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1618
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1619
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1620
 
1486
1621
        self.flags(libvirt_snapshots_directory='./')
1487
1622
 
1488
1623
        # Start test
1508
1643
        self.mox.ReplayAll()
1509
1644
 
1510
1645
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
1511
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1646
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1647
                      func_call_matcher.call)
1512
1648
 
1513
1649
        snapshot = image_service.show(context, recv_meta['id'])
 
1650
        self.assertIsNone(func_call_matcher.match())
1514
1651
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1515
1652
        self.assertEquals(snapshot['status'], 'active')
1516
1653
        self.assertEquals(snapshot['name'], snapshot_name)
1517
1654
 
1518
1655
    def test_lxc_snapshot_no_original_image(self):
 
1656
        expected_calls = [
 
1657
            {'args': (),
 
1658
             'kwargs':
 
1659
                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},
 
1660
            {'args': (),
 
1661
             'kwargs':
 
1662
                 {'task_state': task_states.IMAGE_UPLOADING,
 
1663
                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
 
1664
        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
 
1665
 
1519
1666
        self.flags(libvirt_snapshots_directory='./',
1520
1667
                   libvirt_type='lxc')
1521
1668
 
1542
1689
        self.mox.ReplayAll()
1543
1690
 
1544
1691
        conn = libvirt_driver.LibvirtDriver(False)
1545
 
        conn.snapshot(self.context, instance_ref, recv_meta['id'])
 
1692
        conn.snapshot(self.context, instance_ref, recv_meta['id'],
 
1693
                      func_call_matcher.call)
1546
1694
 
1547
1695
        snapshot = image_service.show(context, recv_meta['id'])
 
1696
        self.assertIsNone(func_call_matcher.match())
1548
1697
        self.assertEquals(snapshot['properties']['image_state'], 'available')
1549
1698
        self.assertEquals(snapshot['status'], 'active')
1550
1699
        self.assertEquals(snapshot['name'], snapshot_name)
1557
1706
        self.assertRaises(exception.VolumeDriverNotFound,
1558
1707
                          conn.attach_volume,
1559
1708
                          {"driver_volume_type": "badtype"},
1560
 
                           "fake",
1561
 
                           "/dev/fake")
 
1709
                          {"name": "fake-instance"},
 
1710
                          "/dev/fake")
1562
1711
 
1563
1712
    def test_multi_nic(self):
1564
1713
        instance_data = dict(self.test_instance)
1786
1935
            check_list.append(check)
1787
1936
 
1788
1937
            if hypervisor_type in ['qemu', 'kvm']:
 
1938
                xpath = "./sysinfo/system/entry"
 
1939
                check = (lambda t: t.findall(xpath)[0].get("name"),
 
1940
                         "manufacturer")
 
1941
                check_list.append(check)
 
1942
                check = (lambda t: t.findall(xpath)[0].text,
 
1943
                         version.vendor_string())
 
1944
                check_list.append(check)
 
1945
 
 
1946
                check = (lambda t: t.findall(xpath)[1].get("name"),
 
1947
                         "product")
 
1948
                check_list.append(check)
 
1949
                check = (lambda t: t.findall(xpath)[1].text,
 
1950
                         version.product_string())
 
1951
                check_list.append(check)
 
1952
 
 
1953
                check = (lambda t: t.findall(xpath)[2].get("name"),
 
1954
                         "version")
 
1955
                check_list.append(check)
 
1956
                check = (lambda t: t.findall(xpath)[2].text,
 
1957
                         version.version_string_with_package())
 
1958
                check_list.append(check)
 
1959
 
 
1960
                check = (lambda t: t.findall(xpath)[3].get("name"),
 
1961
                         "serial")
 
1962
                check_list.append(check)
 
1963
                check = (lambda t: t.findall(xpath)[3].text,
 
1964
                         "cef19ce0-0ca2-11df-855d-b19fbce37686")
 
1965
                check_list.append(check)
 
1966
 
 
1967
                check = (lambda t: t.findall(xpath)[4].get("name"),
 
1968
                         "uuid")
 
1969
                check_list.append(check)
 
1970
                check = (lambda t: t.findall(xpath)[4].text,
 
1971
                         instance['uuid'])
 
1972
                check_list.append(check)
 
1973
 
 
1974
            if hypervisor_type in ['qemu', 'kvm']:
1789
1975
                check = (lambda t: t.findall('./devices/serial')[0].get(
1790
1976
                        'type'), 'file')
1791
1977
                check_list.append(check)
1971
2157
 
1972
2158
        self.mox.StubOutWithMock(conn, '_compare_cpu')
1973
2159
 
1974
 
        conn._compare_cpu("asdf").AndRaise(exception.InvalidCPUInfo)
 
2160
        conn._compare_cpu("asdf").AndRaise(exception.InvalidCPUInfo(
 
2161
                                              reason='foo')
 
2162
                                           )
1975
2163
 
1976
2164
        self.mox.ReplayAll()
1977
2165
        self.assertRaises(exception.InvalidCPUInfo,
2014
2202
        conn.check_can_live_migrate_source(self.context, instance_ref,
2015
2203
                                           dest_check_data)
2016
2204
 
 
2205
    def test_check_can_live_migrate_source_vol_backed_works_correctly(self):
 
2206
        instance_ref = db.instance_create(self.context, self.test_instance)
 
2207
        dest_check_data = {"filename": "file",
 
2208
                           "block_migration": False,
 
2209
                           "disk_over_commit": False,
 
2210
                           "disk_available_mb": 1024,
 
2211
                           "is_volume_backed": True}
 
2212
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2213
        self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
 
2214
        conn._check_shared_storage_test_file("file").AndReturn(False)
 
2215
        self.mox.ReplayAll()
 
2216
        ret = conn.check_can_live_migrate_source(self.context, instance_ref,
 
2217
                                                 dest_check_data)
 
2218
        self.assertTrue(type(ret) == dict)
 
2219
        self.assertTrue('is_shared_storage' in ret)
 
2220
 
 
2221
    def test_check_can_live_migrate_source_vol_backed_fails(self):
 
2222
        instance_ref = db.instance_create(self.context, self.test_instance)
 
2223
        dest_check_data = {"filename": "file",
 
2224
                           "block_migration": False,
 
2225
                           "disk_over_commit": False,
 
2226
                           "disk_available_mb": 1024,
 
2227
                           "is_volume_backed": False}
 
2228
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2229
        self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
 
2230
        conn._check_shared_storage_test_file("file").AndReturn(False)
 
2231
        self.mox.ReplayAll()
 
2232
        self.assertRaises(exception.InvalidSharedStorage,
 
2233
                          conn.check_can_live_migrate_source, self.context,
 
2234
                          instance_ref, dest_check_data)
 
2235
 
2017
2236
    def test_check_can_live_migrate_dest_fail_shared_storage_with_blockm(self):
2018
2237
        instance_ref = db.instance_create(self.context, self.test_instance)
2019
2238
        dest_check_data = {"filename": "file",
2089
2308
                            _bandwidth).AndRaise(libvirt.libvirtError('ERR'))
2090
2309
 
2091
2310
        def fake_lookup(instance_name):
2092
 
            if instance_name == instance_ref.name:
 
2311
            if instance_name == instance_ref['name']:
2093
2312
                return vdmock
2094
2313
 
2095
2314
        self.create_fake_libvirt_mock(lookupByName=fake_lookup)
2142
2361
        result = conn.pre_live_migration(c, inst_ref, vol, nw_info)
2143
2362
        self.assertEqual(result, None)
2144
2363
 
 
2364
    def test_pre_live_migration_vol_backed_works_correctly_mocked(self):
 
2365
        # Creating testdata, using temp dir.
 
2366
        with utils.tempdir() as tmpdir:
 
2367
            self.flags(instances_path=tmpdir)
 
2368
            vol = {'block_device_mapping': [
 
2369
                  {'connection_info': 'dummy', 'mount_device': '/dev/sda'},
 
2370
                  {'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
 
2371
            conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2372
 
 
2373
            class FakeNetworkInfo():
 
2374
                def fixed_ips(self):
 
2375
                    return ["test_ip_addr"]
 
2376
            inst_ref = db.instance_create(self.context, self.test_instance)
 
2377
            c = context.get_admin_context()
 
2378
            nw_info = FakeNetworkInfo()
 
2379
            # Creating mocks
 
2380
            self.mox.StubOutWithMock(conn, "volume_driver_method")
 
2381
            for v in vol['block_device_mapping']:
 
2382
                conn.volume_driver_method('connect_volume',
 
2383
                                          v['connection_info'],
 
2384
                                          v['mount_device'].
 
2385
                                                    rpartition("/")[2])
 
2386
            self.mox.StubOutWithMock(conn, 'plug_vifs')
 
2387
            conn.plug_vifs(mox.IsA(inst_ref), nw_info)
 
2388
            self.mox.ReplayAll()
 
2389
            migrate_data = {'is_shared_storage': False,
 
2390
                            'is_volume_backed': True,
 
2391
                            'block_migration': False
 
2392
                            }
 
2393
            ret = conn.pre_live_migration(c, inst_ref, vol, nw_info,
 
2394
                                          migrate_data)
 
2395
            self.assertEqual(ret, None)
 
2396
            self.assertTrue(os.path.exists('%s/%s/' %
 
2397
                           (tmpdir, inst_ref.name)))
 
2398
        db.instance_destroy(self.context, inst_ref['uuid'])
 
2399
 
2145
2400
    def test_pre_block_migration_works_correctly(self):
2146
2401
        # Replace instances_path since this testcase creates tmpfile
2147
2402
        with utils.tempdir() as tmpdir:
2175
2430
                                     dummyjson)
2176
2431
 
2177
2432
            self.assertTrue(os.path.exists('%s/%s/' %
2178
 
                                           (tmpdir, instance_ref.name)))
 
2433
                                           (tmpdir, instance_ref['name'])))
2179
2434
 
2180
2435
        db.instance_destroy(self.context, instance_ref['uuid'])
2181
2436
 
2198
2453
        vdmock.XMLDesc(0).AndReturn(dummyxml)
2199
2454
 
2200
2455
        def fake_lookup(instance_name):
2201
 
            if instance_name == instance_ref.name:
 
2456
            if instance_name == instance_ref['name']:
2202
2457
                return vdmock
2203
2458
        self.create_fake_libvirt_mock(lookupByName=fake_lookup)
2204
2459
 
2218
2473
               "cluster_size: 2097152\n"
2219
2474
               "backing file: /test/dummy (actual path: /backing/file)\n")
2220
2475
 
 
2476
        self.mox.StubOutWithMock(os.path, "exists")
 
2477
        os.path.exists('/test/disk.local').AndReturn(True)
 
2478
 
2221
2479
        self.mox.StubOutWithMock(utils, "execute")
2222
2480
        utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
2223
2481
                      '/test/disk.local').AndReturn((ret, ''))
2224
2482
 
2225
2483
        self.mox.ReplayAll()
2226
2484
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2227
 
        info = conn.get_instance_disk_info(instance_ref.name)
 
2485
        info = conn.get_instance_disk_info(instance_ref['name'])
2228
2486
        info = jsonutils.loads(info)
2229
2487
        self.assertEquals(info[0]['type'], 'raw')
2230
2488
        self.assertEquals(info[0]['path'], '/test/disk')
2294
2552
        conn.spawn(self.context, instance, None, [], 'herp',
2295
2553
                       network_info=network_info)
2296
2554
 
2297
 
        path = os.path.join(CONF.instances_path, instance.name)
 
2555
        path = os.path.join(CONF.instances_path, instance['name'])
2298
2556
        if os.path.isdir(path):
2299
2557
            shutil.rmtree(path)
2300
2558
 
2303
2561
            shutil.rmtree(os.path.join(CONF.instances_path,
2304
2562
                                       CONF.base_dir_name))
2305
2563
 
 
2564
    def test_spawn_without_image_meta(self):
 
2565
        self.create_image_called = False
 
2566
 
 
2567
        def fake_none(*args, **kwargs):
 
2568
            return
 
2569
 
 
2570
        def fake_create_image(*args, **kwargs):
 
2571
            self.create_image_called = True
 
2572
 
 
2573
        def fake_get_info(instance):
 
2574
            return {'state': power_state.RUNNING}
 
2575
 
 
2576
        instance_ref = self.test_instance
 
2577
        instance_ref['image_ref'] = 1
 
2578
        instance = db.instance_create(self.context, instance_ref)
 
2579
 
 
2580
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2581
        self.stubs.Set(conn, 'to_xml', fake_none)
 
2582
        self.stubs.Set(conn, '_create_image', fake_create_image)
 
2583
        self.stubs.Set(conn, '_create_domain_and_network', fake_none)
 
2584
        self.stubs.Set(conn, 'get_info', fake_get_info)
 
2585
 
 
2586
        conn.spawn(self.context, instance, None, [], None)
 
2587
        self.assertFalse(self.create_image_called)
 
2588
 
 
2589
        conn.spawn(self.context,
 
2590
                   instance,
 
2591
                   {'id': instance['image_ref']},
 
2592
                   [],
 
2593
                   None)
 
2594
        self.assertTrue(self.create_image_called)
 
2595
 
2306
2596
    def test_get_console_output_file(self):
 
2597
        fake_libvirt_utils.files['console.log'] = '01234567890'
2307
2598
 
2308
2599
        with utils.tempdir() as tmpdir:
2309
2600
            self.flags(instances_path=tmpdir)
2313
2604
            instance = db.instance_create(self.context, instance_ref)
2314
2605
 
2315
2606
            console_dir = (os.path.join(tmpdir, instance['name']))
2316
 
            os.mkdir(console_dir)
2317
2607
            console_log = '%s/console.log' % (console_dir)
2318
 
            f = open(console_log, "w")
2319
 
            f.write("foo")
2320
 
            f.close()
2321
2608
            fake_dom_xml = """
2322
2609
                <domain type='kvm'>
2323
2610
                    <devices>
2337
2624
 
2338
2625
            self.create_fake_libvirt_mock()
2339
2626
            libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
2340
 
            libvirt_driver.libvirt_utils = fake_libvirt_utils
2341
2627
 
2342
2628
            conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2343
 
            output = conn.get_console_output(instance)
2344
 
            self.assertEquals("foo", output)
 
2629
 
 
2630
            try:
 
2631
                prev_max = libvirt_driver.MAX_CONSOLE_BYTES
 
2632
                libvirt_driver.MAX_CONSOLE_BYTES = 5
 
2633
                output = conn.get_console_output(instance)
 
2634
            finally:
 
2635
                libvirt_driver.MAX_CONSOLE_BYTES = prev_max
 
2636
 
 
2637
            self.assertEquals('67890', output)
2345
2638
 
2346
2639
    def test_get_console_output_pty(self):
 
2640
        fake_libvirt_utils.files['pty'] = '01234567890'
2347
2641
 
2348
2642
        with utils.tempdir() as tmpdir:
2349
2643
            self.flags(instances_path=tmpdir)
2353
2647
            instance = db.instance_create(self.context, instance_ref)
2354
2648
 
2355
2649
            console_dir = (os.path.join(tmpdir, instance['name']))
2356
 
            os.mkdir(console_dir)
2357
2650
            pty_file = '%s/fake_pty' % (console_dir)
2358
 
            f = open(pty_file, "w")
2359
 
            f.write("foo")
2360
 
            f.close()
2361
2651
            fake_dom_xml = """
2362
2652
                <domain type='kvm'>
2363
2653
                    <devices>
2376
2666
                return FakeVirtDomain(fake_dom_xml)
2377
2667
 
2378
2668
            def _fake_flush(self, fake_pty):
2379
 
                with open(fake_pty, 'r') as fp:
2380
 
                    return fp.read()
 
2669
                return 'foo'
 
2670
 
 
2671
            def _fake_append_to_file(self, data, fpath):
 
2672
                return 'pty'
2381
2673
 
2382
2674
            self.create_fake_libvirt_mock()
2383
2675
            libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
2384
2676
            libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush
2385
 
            libvirt_driver.libvirt_utils = fake_libvirt_utils
 
2677
            libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file
2386
2678
 
2387
2679
            conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2388
 
            output = conn.get_console_output(instance)
2389
 
            self.assertEquals("foo", output)
 
2680
 
 
2681
            try:
 
2682
                prev_max = libvirt_driver.MAX_CONSOLE_BYTES
 
2683
                libvirt_driver.MAX_CONSOLE_BYTES = 5
 
2684
                output = conn.get_console_output(instance)
 
2685
            finally:
 
2686
                libvirt_driver.MAX_CONSOLE_BYTES = prev_max
 
2687
 
 
2688
            self.assertEquals('67890', output)
2390
2689
 
2391
2690
    def test_get_host_ip_addr(self):
2392
2691
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2455
2754
 
2456
2755
    def test_immediate_delete(self):
2457
2756
        def fake_lookup_by_name(instance_name):
2458
 
            raise exception.InstanceNotFound()
 
2757
            raise exception.InstanceNotFound(instance_id=instance_name)
2459
2758
 
2460
2759
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2461
2760
        self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
2463
2762
        instance = db.instance_create(self.context, self.test_instance)
2464
2763
        conn.destroy(instance, {})
2465
2764
 
 
2765
    def test_destroy_removes_disk(self):
 
2766
        instance = {"name": "instancename", "id": "instanceid",
 
2767
                    "uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
 
2768
 
 
2769
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
 
2770
                                 '_undefine_domain')
 
2771
        libvirt_driver.LibvirtDriver._undefine_domain(instance)
 
2772
        self.mox.StubOutWithMock(shutil, "rmtree")
 
2773
        shutil.rmtree(os.path.join(CONF.instances_path, instance['name']))
 
2774
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_cleanup_lvm')
 
2775
        libvirt_driver.LibvirtDriver._cleanup_lvm(instance)
 
2776
 
 
2777
        # Start test
 
2778
        self.mox.ReplayAll()
 
2779
 
 
2780
        def fake_destroy(instance):
 
2781
            pass
 
2782
 
 
2783
        def fake_os_path_exists(path):
 
2784
            return True
 
2785
 
 
2786
        def fake_unplug_vifs(instance, network_info):
 
2787
            pass
 
2788
 
 
2789
        def fake_unfilter_instance(instance, network_info):
 
2790
            pass
 
2791
 
 
2792
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2793
 
 
2794
        self.stubs.Set(conn, '_destroy', fake_destroy)
 
2795
        self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
 
2796
        self.stubs.Set(conn.firewall_driver,
 
2797
                       'unfilter_instance', fake_unfilter_instance)
 
2798
        self.stubs.Set(os.path, 'exists', fake_os_path_exists)
 
2799
        conn.destroy(instance, [])
 
2800
 
 
2801
    def test_destroy_not_removes_disk(self):
 
2802
        instance = {"name": "instancename", "id": "instanceid",
 
2803
                    "uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
 
2804
 
 
2805
        self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
 
2806
                                 '_undefine_domain')
 
2807
        libvirt_driver.LibvirtDriver._undefine_domain(instance)
 
2808
 
 
2809
        # Start test
 
2810
        self.mox.ReplayAll()
 
2811
 
 
2812
        def fake_destroy(instance):
 
2813
            pass
 
2814
 
 
2815
        def fake_os_path_exists(path):
 
2816
            return True
 
2817
 
 
2818
        def fake_unplug_vifs(instance, network_info):
 
2819
            pass
 
2820
 
 
2821
        def fake_unfilter_instance(instance, network_info):
 
2822
            pass
 
2823
 
 
2824
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
2825
 
 
2826
        self.stubs.Set(conn, '_destroy', fake_destroy)
 
2827
        self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
 
2828
        self.stubs.Set(conn.firewall_driver,
 
2829
                       'unfilter_instance', fake_unfilter_instance)
 
2830
        self.stubs.Set(os.path, 'exists', fake_os_path_exists)
 
2831
        conn.destroy(instance, [], None, False)
 
2832
 
2466
2833
    def test_destroy_undefines(self):
2467
2834
        mock = self.mox.CreateMock(libvirt.virDomain)
2468
2835
        mock.destroy()
2558
2925
            return mock
2559
2926
 
2560
2927
        def fake_get_info(instance_name):
2561
 
            raise exception.InstanceNotFound()
 
2928
            raise exception.InstanceNotFound(instance_id=instance_name)
2562
2929
 
2563
2930
        conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
2564
2931
        self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
2577
2944
        self.stubs.Set(conn, 'list_instances', list_instances)
2578
2945
 
2579
2946
        def get_info(instance_name):
2580
 
            raise exception.InstanceNotFound()
 
2947
            raise exception.InstanceNotFound(instance_id='fake')
2581
2948
        self.stubs.Set(conn, 'get_instance_disk_info', get_info)
2582
2949
 
2583
2950
        result = conn.get_disk_available_least()
3181
3548
      ':POSTROUTING ACCEPT [5063:386098]',
3182
3549
    ]
3183
3550
 
 
3551
    in_mangle_rules = [
 
3552
        '# Generated by iptables-save v1.4.12 on Tue Dec 18 15:50:25 201;',
 
3553
        '*mangle',
 
3554
        ':PREROUTING ACCEPT [241:39722]',
 
3555
        ':INPUT ACCEPT [230:39282]',
 
3556
        ':FORWARD ACCEPT [0:0]',
 
3557
        ':OUTPUT ACCEPT [266:26558]',
 
3558
        ':POSTROUTING ACCEPT [267:26590]',
 
3559
        '-A POSTROUTING -o virbr0 -p udp -m udp --dport 68 -j CHECKSUM '
 
3560
        '--checksum-fill',
 
3561
        'COMMIT',
 
3562
        '# Completed on Tue Dec 18 15:50:25 2012',
 
3563
    ]
 
3564
 
3184
3565
    in_filter_rules = [
3185
3566
      '# Generated by iptables-save v1.4.4 on Mon Dec  6 11:54:13 2010',
3186
3567
      '*filter',
3282
3663
                return '\n'.join(self.in_filter_rules), None
3283
3664
            if cmd == ('iptables-save', '-c', '-t', 'nat'):
3284
3665
                return '\n'.join(self.in_nat_rules), None
 
3666
            if cmd == ('iptables-save', '-c', '-t', 'mangle'):
 
3667
                return '\n'.join(self.in_mangle_rules), None
3285
3668
            if cmd == ('iptables-restore', '-c',):
3286
3669
                lines = process_input.split('\n')
3287
3670
                if '*filter' in lines:
3621
4004
        self.security_group = self.setup_and_return_security_group()
3622
4005
 
3623
4006
        db.instance_add_security_group(self.context, inst_uuid,
3624
 
                                       self.security_group.id)
 
4007
                                       self.security_group['id'])
3625
4008
        instance = db.instance_get(self.context, inst_id)
3626
4009
 
3627
4010
        network_info = _fake_network_info(self.stubs, 1)
3638
4021
                break
3639
4022
        _ensure_all_called(mac, allow_dhcp)
3640
4023
        db.instance_remove_security_group(self.context, inst_uuid,
3641
 
                                          self.security_group.id)
 
4024
                                          self.security_group['id'])
3642
4025
        self.teardown_security_group()
3643
4026
        db.instance_destroy(context.get_admin_context(), instance_ref['uuid'])
3644
4027
 
3656
4039
        self.security_group = self.setup_and_return_security_group()
3657
4040
 
3658
4041
        db.instance_add_security_group(self.context, inst_uuid,
3659
 
                                       self.security_group.id)
 
4042
                                       self.security_group['id'])
3660
4043
 
3661
4044
        instance = db.instance_get(self.context, inst_id)
3662
4045
 
3693
4076
        libvirt_utils.create_image('qcow2', '/some/stuff', '1234567891234')
3694
4077
 
3695
4078
    def test_create_cow_image(self):
 
4079
        self.mox.StubOutWithMock(os.path, 'exists')
3696
4080
        self.mox.StubOutWithMock(utils, 'execute')
3697
4081
        rval = ('', '')
 
4082
        os.path.exists('/some/path').AndReturn(True)
3698
4083
        utils.execute('env', 'LC_ALL=C', 'LANG=C',
3699
4084
                      'qemu-img', 'info', '/some/path').AndReturn(rval)
3700
4085
        utils.execute('qemu-img', 'create', '-f', 'qcow2',
3707
4092
    def test_pick_disk_driver_name(self):
3708
4093
        type_map = {'kvm': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
3709
4094
                    'qemu': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
3710
 
                    'xen': ([True, 'phy'], [False, 'tap'], [None, 'tap']),
 
4095
                    'xen': ([True, 'phy'], [False, 'file'], [None, 'file']),
3711
4096
                    'uml': ([True, None], [False, None], [None, None]),
3712
4097
                    'lxc': ([True, None], [False, None], [None, None])}
3713
4098
 
3718
4103
                self.assertEquals(result, expected_result)
3719
4104
 
3720
4105
    def test_get_disk_size(self):
 
4106
        self.mox.StubOutWithMock(os.path, 'exists')
3721
4107
        self.mox.StubOutWithMock(utils, 'execute')
 
4108
        os.path.exists('/some/path').AndReturn(True)
3722
4109
        utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
3723
4110
                      '/some/path').AndReturn(('''image: 00000001
3724
4111
file format: raw
3877
4264
                        "backing file: /foo/bar/baz\n"
3878
4265
                        "...: ...\n"), ''
3879
4266
 
 
4267
        def return_true(*args, **kwargs):
 
4268
            return True
 
4269
 
3880
4270
        self.stubs.Set(utils, 'execute', fake_execute)
 
4271
        self.stubs.Set(os.path, 'exists', return_true)
3881
4272
 
3882
4273
        out = libvirt_utils.get_disk_backing_file('')
3883
4274
        self.assertEqual(out, 'baz')
3990
4381
        self.stubs.Set(utils, 'execute', fake_execute)
3991
4382
 
3992
4383
        ins_ref = self._create_instance()
3993
 
        """ dest is different host case """
 
4384
        # dest is different host case
3994
4385
        out = self.libvirtconnection.migrate_disk_and_power_off(
3995
4386
               None, ins_ref, '10.0.0.2', None, None)
3996
4387
        self.assertEquals(out, disk_info_text)
3997
4388
 
3998
 
        """ dest is same host case """
 
4389
        # dest is same host case
3999
4390
        out = self.libvirtconnection.migrate_disk_and_power_off(
4000
4391
               None, ins_ref, '10.0.0.1', None, None)
4001
4392
        self.assertEquals(out, disk_info_text)
4012
4403
        self.stubs.Set(self.libvirtconnection, 'get_info',
4013
4404
                       fake_get_info)
4014
4405
 
4015
 
        """ instance not found case """
 
4406
        # instance not found case
4016
4407
        self.assertRaises(exception.NotFound,
4017
4408
                self.libvirtconnection._wait_for_running,
4018
4409
                    {'name': 'not_found',
4019
4410
                     'uuid': 'not_found_uuid'})
4020
4411
 
4021
 
        """ instance is running case """
 
4412
        # instance is running case
4022
4413
        self.assertRaises(utils.LoopingCallDone,
4023
4414
                self.libvirtconnection._wait_for_running,
4024
4415
                    {'name': 'running',
4025
4416
                     'uuid': 'running_uuid'})
4026
4417
 
4027
 
        """ else case """
 
4418
        # else case
4028
4419
        self.libvirtconnection._wait_for_running({'name': 'else',
4029
4420
                                                  'uuid': 'other_uuid'})
4030
4421
 
4056
4447
                      block_device_info=None):
4057
4448
            pass
4058
4449
 
4059
 
        def fake_create_domain(xml):
 
4450
        def fake_create_domain(xml, inst_name=''):
4060
4451
            return None
4061
4452
 
4062
4453
        def fake_enable_hairpin(instance):
4102
4493
        def fake_plug_vifs(instance, network_info):
4103
4494
            pass
4104
4495
 
4105
 
        def fake_create_domain(xml):
 
4496
        def fake_create_domain(xml, inst_name=''):
4106
4497
            return None
4107
4498
 
4108
4499
        def fake_enable_hairpin(instance):
4199
4590
                                            _fake_network_info(self.stubs, 1))
4200
4591
 
4201
4592
 
 
4593
class LibvirtVolumeUsageTestCase(test.TestCase):
 
4594
    """Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver
 
4595
       .get_all_volume_usage"""
 
4596
 
 
4597
    def setUp(self):
 
4598
        super(LibvirtVolumeUsageTestCase, self).setUp()
 
4599
        self.conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
 
4600
        self.c = context.get_admin_context()
 
4601
 
 
4602
        # creating instance
 
4603
        inst = {}
 
4604
        inst['uuid'] = '875a8070-d0b9-4949-8b31-104d125c9a64'
 
4605
        self.ins_ref = db.instance_create(self.c, inst)
 
4606
 
 
4607
        # verify bootable volume device path also
 
4608
        self.bdms = [{'volume_id': 1,
 
4609
                      'device_name': '/dev/vde'},
 
4610
                     {'volume_id': 2,
 
4611
                      'device_name': 'vda'}]
 
4612
 
 
4613
    def test_get_all_volume_usage(self):
 
4614
        def fake_block_stats(instance_name, disk):
 
4615
            return (169L, 688640L, 0L, 0L, -1L)
 
4616
 
 
4617
        self.stubs.Set(self.conn, 'block_stats', fake_block_stats)
 
4618
        vol_usage = self.conn.get_all_volume_usage(self.c,
 
4619
              [dict(instance=self.ins_ref, instance_bdms=self.bdms)])
 
4620
 
 
4621
        expected_usage = [{'volume': 1,
 
4622
                           'instance': self.ins_ref,
 
4623
                           'rd_bytes': 688640L, 'wr_req': 0L,
 
4624
                           'flush_operations': -1L, 'rd_req': 169L,
 
4625
                           'wr_bytes': 0L},
 
4626
                           {'volume': 2,
 
4627
                            'instance': self.ins_ref,
 
4628
                            'rd_bytes': 688640L, 'wr_req': 0L,
 
4629
                            'flush_operations': -1L, 'rd_req': 169L,
 
4630
                            'wr_bytes': 0L}]
 
4631
        self.assertEqual(vol_usage, expected_usage)
 
4632
 
 
4633
    def test_get_all_volume_usage_device_not_found(self):
 
4634
        def fake_lookup(instance_name):
 
4635
            raise libvirt.libvirtError('invalid path')
 
4636
 
 
4637
        self.stubs.Set(self.conn, '_lookup_by_name', fake_lookup)
 
4638
        vol_usage = self.conn.get_all_volume_usage(self.c,
 
4639
              [dict(instance=self.ins_ref, instance_bdms=self.bdms)])
 
4640
        self.assertEqual(vol_usage, [])
 
4641
 
 
4642
 
4202
4643
class LibvirtNonblockingTestCase(test.TestCase):
4203
4644
    """Test libvirt_nonblocking option"""
4204
4645