"Fossies" - the Fresh Open Source Software Archive

Member "nova-18.2.3/nova/tests/unit/virt/libvirt/test_driver.py" (10 Oct 2019, 1040791 Bytes) of package /linux/misc/openstack/nova-18.2.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "test_driver.py": 18.2.2_vs_18.2.3.

    1 #    Copyright 2010 OpenStack Foundation
    2 #    Copyright 2012 University Of Minho
    3 #
    4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
    5 #    not use this file except in compliance with the License. You may obtain
    6 #    a copy of the License at
    7 #
    8 #         http://www.apache.org/licenses/LICENSE-2.0
    9 #
   10 #    Unless required by applicable law or agreed to in writing, software
   11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
   12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   13 #    License for the specific language governing permissions and limitations
   14 #    under the License.
   15 
   16 import binascii
   17 from collections import deque
   18 from collections import OrderedDict
   19 import contextlib
   20 import copy
   21 import datetime
   22 import errno
   23 import glob
   24 import os
   25 import random
   26 import re
   27 import shutil
   28 import signal
   29 import threading
   30 import time
   31 import unittest
   32 
   33 from castellan import key_manager
   34 import ddt
   35 import eventlet
   36 from eventlet import greenthread
   37 import fixtures
   38 from lxml import etree
   39 import mock
   40 from mox3 import mox
   41 from os_brick import encryptors
   42 from os_brick import exception as brick_exception
   43 from os_brick.initiator import connector
   44 import os_vif
   45 from oslo_concurrency import lockutils
   46 from oslo_concurrency import processutils
   47 from oslo_config import cfg
   48 from oslo_serialization import jsonutils
   49 from oslo_service import loopingcall
   50 from oslo_utils import encodeutils
   51 from oslo_utils import fileutils
   52 from oslo_utils import fixture as utils_fixture
   53 from oslo_utils import units
   54 from oslo_utils import uuidutils
   55 from oslo_utils import versionutils
   56 import six
   57 from six.moves import builtins
   58 from six.moves import range
   59 
   60 from nova.api.metadata import base as instance_metadata
   61 from nova.api.openstack.placement.objects import resource_provider as rp_object
   62 from nova.compute import manager
   63 from nova.compute import power_state
   64 from nova.compute import provider_tree
   65 from nova.compute import task_states
   66 from nova.compute import vm_states
   67 import nova.conf
   68 from nova import context
   69 from nova.db import api as db
   70 from nova import exception
   71 from nova.network import model as network_model
   72 from nova import objects
   73 from nova.objects import block_device as block_device_obj
   74 from nova.objects import fields
   75 from nova.objects import migrate_data as migrate_data_obj
   76 from nova.objects import virtual_interface as obj_vif
   77 from nova.pci import manager as pci_manager
   78 from nova.pci import utils as pci_utils
   79 import nova.privsep.fs
   80 import nova.privsep.libvirt
   81 from nova import rc_fields
   82 from nova import test
   83 from nova.tests.unit import fake_block_device
   84 from nova.tests.unit import fake_diagnostics
   85 from nova.tests.unit import fake_flavor
   86 from nova.tests.unit import fake_instance
   87 from nova.tests.unit import fake_network
   88 import nova.tests.unit.image.fake
   89 from nova.tests.unit import matchers
   90 from nova.tests.unit.objects import test_diagnostics
   91 from nova.tests.unit.objects import test_pci_device
   92 from nova.tests.unit.objects import test_vcpu_model
   93 from nova.tests.unit.virt.libvirt import fake_imagebackend
   94 from nova.tests.unit.virt.libvirt import fake_libvirt_utils
   95 from nova.tests.unit.virt.libvirt import fakelibvirt
   96 from nova.tests import uuidsentinel as uuids
   97 from nova import utils
   98 from nova import version
   99 from nova.virt import block_device as driver_block_device
  100 from nova.virt import driver
  101 from nova.virt import fake
  102 from nova.virt import firewall as base_firewall
  103 from nova.virt import hardware
  104 from nova.virt.image import model as imgmodel
  105 from nova.virt import images
  106 from nova.virt.libvirt import blockinfo
  107 from nova.virt.libvirt import config as vconfig
  108 from nova.virt.libvirt import driver as libvirt_driver
  109 from nova.virt.libvirt import firewall
  110 from nova.virt.libvirt import guest as libvirt_guest
  111 from nova.virt.libvirt import host
  112 from nova.virt.libvirt import imagebackend
  113 from nova.virt.libvirt import imagecache
  114 from nova.virt.libvirt import migration as libvirt_migrate
  115 from nova.virt.libvirt.storage import dmcrypt
  116 from nova.virt.libvirt.storage import lvm
  117 from nova.virt.libvirt.storage import rbd_utils
  118 from nova.virt.libvirt import utils as libvirt_utils
  119 from nova.virt.libvirt.volume import volume as volume_drivers
  120 
  121 
  122 CONF = nova.conf.CONF
  123 
  124 _fake_network_info = fake_network.fake_get_instance_nw_info
  125 
  126 _fake_NodeDevXml = \
  127     {"pci_0000_04_00_3": """
  128         <device>
  129         <name>pci_0000_04_00_3</name>
  130         <parent>pci_0000_00_01_1</parent>
  131         <driver>
  132             <name>igb</name>
  133         </driver>
  134         <capability type='pci'>
  135             <domain>0</domain>
  136             <bus>4</bus>
  137             <slot>0</slot>
  138             <function>3</function>
  139             <product id='0x1521'>I350 Gigabit Network Connection</product>
  140             <vendor id='0x8086'>Intel Corporation</vendor>
  141             <capability type='virt_functions'>
  142               <address domain='0x0000' bus='0x04' slot='0x10' function='0x3'/>
  143               <address domain='0x0000' bus='0x04' slot='0x10' function='0x7'/>
  144               <address domain='0x0000' bus='0x04' slot='0x11' function='0x3'/>
  145               <address domain='0x0000' bus='0x04' slot='0x11' function='0x7'/>
  146             </capability>
  147         </capability>
  148       </device>""",
  149     "pci_0000_04_10_7": """
  150       <device>
  151          <name>pci_0000_04_10_7</name>
  152          <parent>pci_0000_00_01_1</parent>
  153          <driver>
  154          <name>igbvf</name>
  155          </driver>
  156          <capability type='pci'>
  157           <domain>0</domain>
  158           <bus>4</bus>
  159           <slot>16</slot>
  160           <function>7</function>
  161           <product id='0x1520'>I350 Ethernet Controller Virtual Function
  162             </product>
  163           <vendor id='0x8086'>Intel Corporation</vendor>
  164           <capability type='phys_function'>
  165              <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
  166           </capability>
  167           <capability type='virt_functions'>
  168           </capability>
  169         </capability>
  170     </device>""",
  171     "pci_0000_04_11_7": """
  172       <device>
  173          <name>pci_0000_04_11_7</name>
  174          <parent>pci_0000_00_01_1</parent>
  175          <driver>
  176          <name>igbvf</name>
  177          </driver>
  178          <capability type='pci'>
  179           <domain>0</domain>
  180           <bus>4</bus>
  181           <slot>17</slot>
  182           <function>7</function>
  183           <product id='0x1520'>I350 Ethernet Controller Virtual Function
  184             </product>
  185           <vendor id='0x8086'>Intel Corporation</vendor>
  186           <numa node='0'/>
  187           <capability type='phys_function'>
  188              <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
  189           </capability>
  190           <capability type='virt_functions'>
  191           </capability>
  192         </capability>
  193     </device>""",
  194     "pci_0000_04_00_1": """
  195     <device>
  196       <name>pci_0000_04_00_1</name>
  197       <path>/sys/devices/pci0000:00/0000:00:02.0/0000:04:00.1</path>
  198       <parent>pci_0000_00_02_0</parent>
  199       <driver>
  200         <name>mlx5_core</name>
  201       </driver>
  202       <capability type='pci'>
  203         <domain>0</domain>
  204         <bus>4</bus>
  205         <slot>0</slot>
  206         <function>1</function>
  207         <product id='0x1013'>MT27700 Family [ConnectX-4]</product>
  208         <vendor id='0x15b3'>Mellanox Technologies</vendor>
  209         <iommuGroup number='15'>
  210           <address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
  211           <address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
  212         </iommuGroup>
  213         <numa node='0'/>
  214         <pci-express>
  215           <link validity='cap' port='0' speed='8' width='16'/>
  216           <link validity='sta' speed='8' width='16'/>
  217         </pci-express>
  218       </capability>
  219     </device>""",
  220     # libvirt  >= 1.3.0 nodedev-dumpxml
  221     "pci_0000_03_00_0": """
  222     <device>
  223         <name>pci_0000_03_00_0</name>
  224         <path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.0</path>
  225         <parent>pci_0000_00_02_0</parent>
  226         <driver>
  227         <name>mlx5_core</name>
  228         </driver>
  229         <capability type='pci'>
  230         <domain>0</domain>
  231         <bus>3</bus>
  232         <slot>0</slot>
  233         <function>0</function>
  234         <product id='0x1013'>MT27700 Family [ConnectX-4]</product>
  235         <vendor id='0x15b3'>Mellanox Technologies</vendor>
  236         <capability type='virt_functions' maxCount='16'>
  237           <address domain='0x0000' bus='0x03' slot='0x00' function='0x2'/>
  238           <address domain='0x0000' bus='0x03' slot='0x00' function='0x3'/>
  239           <address domain='0x0000' bus='0x03' slot='0x00' function='0x4'/>
  240           <address domain='0x0000' bus='0x03' slot='0x00' function='0x5'/>
  241         </capability>
  242         <iommuGroup number='15'>
  243           <address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
  244           <address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
  245         </iommuGroup>
  246         <numa node='0'/>
  247         <pci-express>
  248           <link validity='cap' port='0' speed='8' width='16'/>
  249           <link validity='sta' speed='8' width='16'/>
  250         </pci-express>
  251       </capability>
  252     </device>""",
  253     "pci_0000_03_00_1": """
  254     <device>
  255       <name>pci_0000_03_00_1</name>
  256       <path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.1</path>
  257       <parent>pci_0000_00_02_0</parent>
  258       <driver>
  259         <name>mlx5_core</name>
  260       </driver>
  261       <capability type='pci'>
  262         <domain>0</domain>
  263         <bus>3</bus>
  264         <slot>0</slot>
  265         <function>1</function>
  266         <product id='0x1013'>MT27700 Family [ConnectX-4]</product>
  267         <vendor id='0x15b3'>Mellanox Technologies</vendor>
  268         <capability type='virt_functions' maxCount='16'/>
  269         <iommuGroup number='15'>
  270           <address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
  271           <address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
  272         </iommuGroup>
  273         <numa node='0'/>
  274         <pci-express>
  275           <link validity='cap' port='0' speed='8' width='16'/>
  276           <link validity='sta' speed='8' width='16'/>
  277         </pci-express>
  278       </capability>
  279     </device>""",
  280     "net_enp2s2_02_9a_a1_37_be_54": """
  281     <device>
  282       <name>net_enp2s2_02_9a_a1_37_be_54</name>
  283       <path>/sys/devices/pci0000:00/0000:00:02.0/0000:02:02.0/net/enp2s2</path>
  284       <parent>pci_0000_04_11_7</parent>
  285       <capability type='net'>
  286         <interface>enp2s2</interface>
  287         <address>02:9a:a1:37:be:54</address>
  288         <link state='down'/>
  289         <feature name='rx'/>
  290         <feature name='tx'/>
  291         <feature name='sg'/>
  292         <feature name='tso'/>
  293         <feature name='gso'/>
  294         <feature name='gro'/>
  295         <feature name='rxvlan'/>
  296         <feature name='txvlan'/>
  297         <capability type='80203'/>
  298       </capability>
  299     </device>""",
  300      "pci_0000_06_00_0": """
  301     <device>
  302       <name>pci_0000_06_00_0</name>
  303       <path>/sys/devices/pci0000:00/0000:00:06.0</path>
  304       <parent></parent>
  305       <driver>
  306         <name>nvidia</name>
  307       </driver>
  308       <capability type="pci">
  309         <domain>0</domain>
  310         <bus>10</bus>
  311         <slot>1</slot>
  312         <function>5</function>
  313         <product id="0x0FFE">GRID M60-0B</product>
  314         <vendor id="0x10DE">Nvidia</vendor>
  315         <numa node="8"/>
  316         <capability type='mdev_types'>
  317           <type id='nvidia-11'>
  318             <name>GRID M60-0B</name>
  319             <deviceAPI>vfio-pci</deviceAPI>
  320             <availableInstances>16</availableInstances>
  321           </type>
  322         </capability>
  323       </capability>
  324     </device>""",
  325      "mdev_4b20d080_1b54_4048_85b3_a6a62d165c01": """
  326     <device>
  327       <name>mdev_4b20d080_1b54_4048_85b3_a6a62d165c01</name>
  328       <path>/sys/devices/pci0000:00/0000:00:02.0/4b20d080-1b54-4048-85b3-a6a62d165c01</path>
  329       <parent>pci_0000_00_02_0</parent>
  330       <driver>
  331         <name>vfio_mdev</name>
  332       </driver>
  333       <capability type='mdev'>
  334         <type id='nvidia-11'/>
  335         <iommuGroup number='12'/>
  336       </capability>
  337     </device>
  338     """,
  339     }
  340 
  341 _fake_cpu_info = {
  342     "arch": "test_arch",
  343     "model": "test_model",
  344     "vendor": "test_vendor",
  345     "topology": {
  346         "sockets": 1,
  347         "cores": 8,
  348         "threads": 16
  349     },
  350     "features": ["feature1", "feature2"]
  351 }
  352 
  353 eph_default_ext = utils.get_hash_str(nova.privsep.fs._DEFAULT_FILE_SYSTEM)[:7]
  354 
  355 _fake_qemu64_cpu_feature = """
  356 <cpu mode='custom' match='exact'>
  357   <model fallback='forbid'>qemu64</model>
  358   <feature policy='require' name='svm'/>
  359   <feature policy='require' name='lm'/>
  360   <feature policy='require' name='nx'/>
  361   <feature policy='require' name='syscall'/>
  362   <feature policy='require' name='cx16'/>
  363   <feature policy='require' name='pni'/>
  364   <feature policy='require' name='sse2'/>
  365   <feature policy='require' name='sse'/>
  366   <feature policy='require' name='fxsr'/>
  367   <feature policy='require' name='mmx'/>
  368   <feature policy='require' name='clflush'/>
  369   <feature policy='require' name='pse36'/>
  370   <feature policy='require' name='pat'/>
  371   <feature policy='require' name='cmov'/>
  372   <feature policy='require' name='mca'/>
  373   <feature policy='require' name='pge'/>
  374   <feature policy='require' name='mtrr'/>
  375   <feature policy='require' name='sep'/>
  376   <feature policy='require' name='apic'/>
  377   <feature policy='require' name='cx8'/>
  378   <feature policy='require' name='mce'/>
  379   <feature policy='require' name='pae'/>
  380   <feature policy='require' name='msr'/>
  381   <feature policy='require' name='tsc'/>
  382   <feature policy='require' name='pse'/>
  383   <feature policy='require' name='de'/>
  384   <feature policy='require' name='fpu'/>
  385 </cpu>
  386 """
  387 
  388 _fake_broadwell_cpu_feature = """
  389 <cpu mode='custom' match='exact'>
  390   <model fallback='forbid'>Broadwell-noTSX</model>
  391   <vendor>Intel</vendor>
  392   <feature policy='require' name='smap'/>
  393   <feature policy='require' name='adx'/>
  394   <feature policy='require' name='rdseed'/>
  395   <feature policy='require' name='invpcid'/>
  396   <feature policy='require' name='erms'/>
  397   <feature policy='require' name='bmi2'/>
  398   <feature policy='require' name='smep'/>
  399   <feature policy='require' name='avx2'/>
  400   <feature policy='require' name='bmi1'/>
  401   <feature policy='require' name='fsgsbase'/>
  402   <feature policy='require' name='3dnowprefetch'/>
  403   <feature policy='require' name='lahf_lm'/>
  404   <feature policy='require' name='lm'/>
  405   <feature policy='require' name='rdtscp'/>
  406   <feature policy='require' name='nx'/>
  407   <feature policy='require' name='syscall'/>
  408   <feature policy='require' name='avx'/>
  409   <feature policy='require' name='xsave'/>
  410   <feature policy='require' name='aes'/>
  411   <feature policy='require' name='tsc-deadline'/>
  412   <feature policy='require' name='popcnt'/>
  413   <feature policy='require' name='movbe'/>
  414   <feature policy='require' name='x2apic'/>
  415   <feature policy='require' name='sse4.2'/>
  416   <feature policy='require' name='sse4.1'/>
  417   <feature policy='require' name='pcid'/>
  418   <feature policy='require' name='cx16'/>
  419   <feature policy='require' name='fma'/>
  420   <feature policy='require' name='ssse3'/>
  421   <feature policy='require' name='pclmuldq'/>
  422   <feature policy='require' name='pni'/>
  423   <feature policy='require' name='sse2'/>
  424   <feature policy='require' name='sse'/>
  425   <feature policy='require' name='fxsr'/>
  426   <feature policy='require' name='mmx'/>
  427   <feature policy='require' name='clflush'/>
  428   <feature policy='require' name='pse36'/>
  429   <feature policy='require' name='pat'/>
  430   <feature policy='require' name='cmov'/>
  431   <feature policy='require' name='mca'/>
  432   <feature policy='require' name='pge'/>
  433   <feature policy='require' name='mtrr'/>
  434   <feature policy='require' name='sep'/>
  435   <feature policy='require' name='apic'/>
  436   <feature policy='require' name='cx8'/>
  437   <feature policy='require' name='mce'/>
  438   <feature policy='require' name='pae'/>
  439   <feature policy='require' name='msr'/>
  440   <feature policy='require' name='tsc'/>
  441   <feature policy='require' name='pse'/>
  442   <feature policy='require' name='de'/>
  443   <feature policy='require' name='fpu'/>
  444 </cpu>
  445 """
  446 
  447 
  448 def eph_name(size):
  449     return ('ephemeral_%(size)s_%(ext)s' %
  450             {'size': size, 'ext': eph_default_ext})
  451 
  452 
  453 def fake_disk_info_byname(instance, type='qcow2'):
  454     """Return instance_disk_info corresponding accurately to the properties of
  455     the given Instance object. The info is returned as an OrderedDict of
  456     name->disk_info for each disk.
  457 
  458     :param instance: The instance we're generating fake disk_info for.
  459     :param type: libvirt's disk type.
  460     :return: disk_info
  461     :rtype: OrderedDict
  462     """
  463     instance_dir = os.path.join(CONF.instances_path, instance.uuid)
  464 
  465     def instance_path(name):
  466         return os.path.join(instance_dir, name)
  467 
  468     disk_info = OrderedDict()
  469 
  470     # root disk
  471     if (instance.image_ref is not None and
  472             instance.image_ref != uuids.fake_volume_backed_image_ref):
  473         cache_name = imagecache.get_cache_fname(instance.image_ref)
  474         disk_info['disk'] = {
  475             'type': type,
  476             'path': instance_path('disk'),
  477             'virt_disk_size': instance.flavor.root_gb * units.Gi,
  478             'backing_file': cache_name,
  479             'disk_size': instance.flavor.root_gb * units.Gi,
  480             'over_committed_disk_size': 0}
  481 
  482     swap_mb = instance.flavor.swap
  483     if swap_mb > 0:
  484         disk_info['disk.swap'] = {
  485             'type': type,
  486             'path': instance_path('disk.swap'),
  487             'virt_disk_size': swap_mb * units.Mi,
  488             'backing_file': 'swap_%s' % swap_mb,
  489             'disk_size': swap_mb * units.Mi,
  490             'over_committed_disk_size': 0}
  491 
  492     eph_gb = instance.flavor.ephemeral_gb
  493     if eph_gb > 0:
  494         disk_info['disk.local'] = {
  495             'type': type,
  496             'path': instance_path('disk.local'),
  497             'virt_disk_size': eph_gb * units.Gi,
  498             'backing_file': eph_name(eph_gb),
  499             'disk_size': eph_gb * units.Gi,
  500             'over_committed_disk_size': 0}
  501 
  502     if instance.config_drive:
  503         disk_info['disk.config'] = {
  504             'type': 'raw',
  505             'path': instance_path('disk.config'),
  506             'virt_disk_size': 1024,
  507             'backing_file': '',
  508             'disk_size': 1024,
  509             'over_committed_disk_size': 0}
  510 
  511     return disk_info
  512 
  513 
  514 def fake_diagnostics_object(with_cpus=False, with_disks=False, with_nic=False):
  515     diag_dict = {'config_drive': False,
  516                  'driver': 'libvirt',
  517                  'hypervisor': 'kvm',
  518                  'hypervisor_os': 'linux',
  519                  'memory_details': {'maximum': 2048, 'used': 1234},
  520                  'state': 'running',
  521                  'uptime': 10}
  522 
  523     if with_cpus:
  524         diag_dict['cpu_details'] = []
  525         for id, t in enumerate([15340000000, 1640000000,
  526                                 3040000000, 1420000000]):
  527             diag_dict['cpu_details'].append({'id': id, 'time': t})
  528 
  529     if with_disks:
  530         diag_dict['disk_details'] = []
  531         for i in range(2):
  532             diag_dict['disk_details'].append(
  533                 {'read_bytes': 688640,
  534                  'read_requests': 169,
  535                  'write_bytes': 0,
  536                  'write_requests': 0,
  537                  'errors_count': 1})
  538 
  539     if with_nic:
  540         diag_dict['nic_details'] = [
  541             {'mac_address': '52:54:00:a4:38:38',
  542              'rx_drop': 0,
  543              'rx_errors': 0,
  544              'rx_octets': 4408,
  545              'rx_packets': 82,
  546              'tx_drop': 0,
  547              'tx_errors': 0,
  548              'tx_octets': 0,
  549              'tx_packets': 0}]
  550 
  551     return fake_diagnostics.fake_diagnostics_obj(**diag_dict)
  552 
  553 
  554 def fake_disk_info_json(instance, type='qcow2'):
  555     """Return fake instance_disk_info corresponding accurately to the
  556     properties of the given Instance object.
  557 
  558     :param instance: The instance we're generating fake disk_info for.
  559     :param type: libvirt's disk type.
  560     :return: JSON representation of instance_disk_info for all disks.
  561     :rtype: str
  562     """
  563     disk_info = fake_disk_info_byname(instance, type)
  564     return jsonutils.dumps(disk_info.values())
  565 
  566 
  567 def get_injection_info(network_info=None, admin_pass=None, files=None):
  568     return libvirt_driver.InjectionInfo(
  569         network_info=network_info, admin_pass=admin_pass, files=files)
  570 
  571 
  572 def _concurrency(signal, wait, done, target, is_block_dev=False):
  573     signal.send()
  574     wait.wait()
  575     done.send()
  576 
  577 
  578 class FakeVirtDomain(object):
  579 
  580     def __init__(self, fake_xml=None, uuidstr=None, id=None, name=None,
  581                  info=None):
  582         if uuidstr is None:
  583             uuidstr = uuids.fake
  584         self.uuidstr = uuidstr
  585         self.id = id
  586         self.domname = name
  587         self._info = info or (
  588             [power_state.RUNNING, 2048 * units.Mi,
  589              1234 * units.Mi, None, None])
  590         if fake_xml:
  591             self._fake_dom_xml = fake_xml
  592         else:
  593             self._fake_dom_xml = """
  594                 <domain type='kvm'>
  595                     <name>testinstance1</name>
  596                     <devices>
  597                         <disk type='file'>
  598                             <source file='filename'/>
  599                         </disk>
  600                     </devices>
  601                 </domain>
  602             """
  603 
  604     def name(self):
  605         if self.domname is None:
  606             return "fake-domain %s" % self
  607         else:
  608             return self.domname
  609 
  610     def ID(self):
  611         return self.id
  612 
  613     def info(self):
  614         return self._info
  615 
  616     def create(self):
  617         pass
  618 
  619     def managedSave(self, *args):
  620         pass
  621 
  622     def createWithFlags(self, launch_flags):
  623         pass
  624 
  625     def XMLDesc(self, flags):
  626         return self._fake_dom_xml
  627 
  628     def UUIDString(self):
  629         return self.uuidstr
  630 
  631     def attachDeviceFlags(self, xml, flags):
  632         pass
  633 
  634     def attachDevice(self, xml):
  635         pass
  636 
  637     def detachDeviceFlags(self, xml, flags):
  638         pass
  639 
  640     def snapshotCreateXML(self, xml, flags):
  641         pass
  642 
  643     def blockCommit(self, disk, base, top, bandwidth=0, flags=0):
  644         pass
  645 
  646     def blockRebase(self, disk, base, bandwidth=0, flags=0):
  647         pass
  648 
  649     def blockJobInfo(self, path, flags):
  650         pass
  651 
  652     def blockJobAbort(self, path, flags):
  653         pass
  654 
  655     def resume(self):
  656         pass
  657 
  658     def destroy(self):
  659         pass
  660 
  661     def fsFreeze(self, disks=None, flags=0):
  662         pass
  663 
  664     def fsThaw(self, disks=None, flags=0):
  665         pass
  666 
  667     def isActive(self):
  668         return True
  669 
  670     def isPersistent(self):
  671         return True
  672 
  673     def undefine(self):
  674         return True
  675 
  676 
  677 class CacheConcurrencyTestCase(test.NoDBTestCase):
  678     def setUp(self):
  679         super(CacheConcurrencyTestCase, self).setUp()
  680 
  681         self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
  682 
  683         # utils.synchronized() will create the lock_path for us if it
  684         # doesn't already exist. It will also delete it when it's done,
  685         # which can cause race conditions with the multiple threads we
  686         # use for tests. So, create the path here so utils.synchronized()
  687         # won't delete it out from under one of the threads.
  688         self.lock_path = os.path.join(CONF.instances_path, 'locks')
  689         fileutils.ensure_tree(self.lock_path)
  690 
  691         def fake_exists(fname):
  692             basedir = os.path.join(CONF.instances_path,
  693                                    CONF.image_cache_subdirectory_name)
  694             if fname == basedir or fname == self.lock_path:
  695                 return True
  696             return False
  697 
  698         self.stub_out('os.path.exists', fake_exists)
  699         self.stub_out('nova.utils.execute', lambda *a, **kw: None)
  700         self.stub_out('nova.virt.disk.api.extend',
  701                       lambda image, size, use_cow=False: None)
  702         self.useFixture(fixtures.MonkeyPatch(
  703             'nova.virt.libvirt.imagebackend.libvirt_utils',
  704             fake_libvirt_utils))
  705 
  706     def _fake_instance(self, uuid):
  707         return objects.Instance(id=1, uuid=uuid)
  708 
  709     def test_same_fname_concurrency(self):
  710         # Ensures that the same fname cache runs at a sequentially.
  711         uuid = uuids.fake
  712 
  713         backend = imagebackend.Backend(False)
  714         wait1 = eventlet.event.Event()
  715         done1 = eventlet.event.Event()
  716         sig1 = eventlet.event.Event()
  717         thr1 = eventlet.spawn(backend.by_name(self._fake_instance(uuid),
  718                                               'name').cache,
  719                 _concurrency, 'fname', None,
  720                 signal=sig1, wait=wait1, done=done1)
  721         eventlet.sleep(0)
  722         # Thread 1 should run before thread 2.
  723         sig1.wait()
  724 
  725         wait2 = eventlet.event.Event()
  726         done2 = eventlet.event.Event()
  727         sig2 = eventlet.event.Event()
  728         thr2 = eventlet.spawn(backend.by_name(self._fake_instance(uuid),
  729                                               'name').cache,
  730                 _concurrency, 'fname', None,
  731                 signal=sig2, wait=wait2, done=done2)
  732 
  733         wait2.send()
  734         eventlet.sleep(0)
  735         try:
  736             self.assertFalse(done2.ready())
  737         finally:
  738             wait1.send()
  739         done1.wait()
  740         eventlet.sleep(0)
  741         self.assertTrue(done2.ready())
  742         # Wait on greenthreads to assert they didn't raise exceptions
  743         # during execution
  744         thr1.wait()
  745         thr2.wait()
  746 
  747     def test_different_fname_concurrency(self):
  748         # Ensures that two different fname caches are concurrent.
  749         uuid = uuids.fake
  750 
  751         backend = imagebackend.Backend(False)
  752         wait1 = eventlet.event.Event()
  753         done1 = eventlet.event.Event()
  754         sig1 = eventlet.event.Event()
  755         thr1 = eventlet.spawn(backend.by_name(self._fake_instance(uuid),
  756                                               'name').cache,
  757                 _concurrency, 'fname2', None,
  758                 signal=sig1, wait=wait1, done=done1)
  759         eventlet.sleep(0)
  760         # Thread 1 should run before thread 2.
  761         sig1.wait()
  762 
  763         wait2 = eventlet.event.Event()
  764         done2 = eventlet.event.Event()
  765         sig2 = eventlet.event.Event()
  766         thr2 = eventlet.spawn(backend.by_name(self._fake_instance(uuid),
  767                                               'name').cache,
  768                 _concurrency, 'fname1', None,
  769                 signal=sig2, wait=wait2, done=done2)
  770         eventlet.sleep(0)
  771         # Wait for thread 2 to start.
  772         sig2.wait()
  773 
  774         wait2.send()
  775         tries = 0
  776         while not done2.ready() and tries < 10:
  777             eventlet.sleep(0)
  778             tries += 1
  779         try:
  780             self.assertTrue(done2.ready())
  781         finally:
  782             wait1.send()
  783             eventlet.sleep(0)
  784         # Wait on greenthreads to assert they didn't raise exceptions
  785         # during execution
  786         thr1.wait()
  787         thr2.wait()
  788 
  789 
  790 class FakeInvalidVolumeDriver(object):
  791     def __init__(self, *args, **kwargs):
  792         raise brick_exception.InvalidConnectorProtocol('oops!')
  793 
  794 
  795 class FakeConfigGuestDisk(object):
  796     def __init__(self, *args, **kwargs):
  797         self.source_type = None
  798         self.driver_cache = None
  799 
  800 
  801 class FakeConfigGuest(object):
  802     def __init__(self, *args, **kwargs):
  803         self.driver_cache = None
  804 
  805 
  806 class FakeNodeDevice(object):
  807     def __init__(self, fakexml):
  808         self.xml = fakexml
  809 
  810     def XMLDesc(self, flags):
  811         return self.xml
  812 
  813 
  814 def _create_test_instance():
  815     flavor = objects.Flavor(memory_mb=2048,
  816                             swap=0,
  817                             vcpu_weight=None,
  818                             root_gb=10,
  819                             id=2,
  820                             name=u'm1.small',
  821                             ephemeral_gb=20,
  822                             rxtx_factor=1.0,
  823                             flavorid=u'1',
  824                             vcpus=2,
  825                             extra_specs={})
  826     return {
  827         'id': 1,
  828         'uuid': uuids.instance,
  829         'memory_kb': '1024000',
  830         'basepath': '/some/path',
  831         'bridge_name': 'br100',
  832         'display_name': "Acme webserver",
  833         'vcpus': 2,
  834         'project_id': 'fake',
  835         'bridge': 'br101',
  836         'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
  837         'root_gb': 10,
  838         'ephemeral_gb': 20,
  839         'instance_type_id': '5',  # m1.small
  840         'extra_specs': {},
  841         'system_metadata': {
  842             'image_disk_format': 'raw'
  843         },
  844         'flavor': flavor,
  845         'new_flavor': None,
  846         'old_flavor': None,
  847         'pci_devices': objects.PciDeviceList(),
  848         'numa_topology': None,
  849         'config_drive': None,
  850         'vm_mode': None,
  851         'kernel_id': None,
  852         'ramdisk_id': None,
  853         'os_type': 'linux',
  854         'user_id': '838a72b0-0d54-4827-8fd6-fb1227633ceb',
  855         'ephemeral_key_uuid': None,
  856         'vcpu_model': None,
  857         'host': 'fake-host',
  858         'task_state': None,
  859         'vm_state': None,
  860         'trusted_certs': None
  861     }
  862 
  863 
  864 @ddt.ddt
  865 class LibvirtConnTestCase(test.NoDBTestCase,
  866                           test_diagnostics.DiagnosticsComparisonMixin):
  867 
  868     REQUIRES_LOCKING = True
  869 
  870     _EPHEMERAL_20_DEFAULT = eph_name(20)
  871 
  872     def setUp(self):
  873         super(LibvirtConnTestCase, self).setUp()
  874         self.user_id = 'fake'
  875         self.project_id = 'fake'
  876         self.context = context.get_admin_context()
  877         temp_dir = self.useFixture(fixtures.TempDir()).path
  878         self.flags(instances_path=temp_dir,
  879                    firewall_driver=None)
  880         self.flags(snapshots_directory=temp_dir, group='libvirt')
  881         self.useFixture(fixtures.MonkeyPatch(
  882             'nova.virt.libvirt.driver.libvirt_utils',
  883             fake_libvirt_utils))
  884 
  885         self.flags(sysinfo_serial="hardware", group="libvirt")
  886 
  887         # normally loaded during nova-compute startup
  888         os_vif.initialize()
  889 
  890         self.useFixture(fixtures.MonkeyPatch(
  891             'nova.virt.libvirt.imagebackend.libvirt_utils',
  892             fake_libvirt_utils))
  893 
  894         self.stub_out('nova.virt.disk.api.extend',
  895                       lambda image, size, use_cow=False: None)
  896 
  897         self.stub_out('nova.virt.libvirt.imagebackend.Image.'
  898                       'resolve_driver_format',
  899                       imagebackend.Image._get_driver_format)
  900 
  901         self.stub_out('nova.compute.utils.get_machine_ips', lambda: [])
  902 
  903         self.useFixture(fakelibvirt.FakeLibvirtFixture())
  904         self.test_instance = _create_test_instance()
  905         self.test_image_meta = {
  906             "disk_format": "raw",
  907         }
  908         self.image_service = nova.tests.unit.image.fake.stub_out_image_service(
  909                 self)
  910         self.device_xml_tmpl = """
  911         <domain type='kvm'>
  912           <devices>
  913             <disk type='block' device='disk'>
  914               <driver name='qemu' type='raw' cache='none'/>
  915               <source dev='{device_path}'/>
  916               <target bus='virtio' dev='vdb'/>
  917               <serial>58a84f6d-3f0c-4e19-a0af-eb657b790657</serial>
  918               <address type='pci' domain='0x0' bus='0x0' slot='0x04' \
  919               function='0x0'/>
  920             </disk>
  921           </devices>
  922         </domain>
  923         """
  924 
  925     def relpath(self, path):
  926         return os.path.relpath(path, CONF.instances_path)
  927 
  928     def tearDown(self):
  929         nova.tests.unit.image.fake.FakeImageService_reset()
  930         super(LibvirtConnTestCase, self).tearDown()
  931 
  932     def test_driver_capabilities(self):
  933         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
  934         self.assertTrue(drvr.capabilities['has_imagecache'],
  935                         'Driver capabilities for \'has_imagecache\' '
  936                         'is invalid')
  937         self.assertTrue(drvr.capabilities['supports_evacuate'],
  938                         'Driver capabilities for \'supports_evacuate\' '
  939                         'is invalid')
  940         self.assertFalse(drvr.capabilities['supports_migrate_to_same_host'],
  941                          'Driver capabilities for '
  942                          '\'supports_migrate_to_same_host\' is invalid')
  943         self.assertTrue(drvr.capabilities['supports_attach_interface'],
  944                         'Driver capabilities for '
  945                         '\'supports_attach_interface\' '
  946                         'is invalid')
  947         self.assertTrue(drvr.capabilities['supports_extend_volume'],
  948                         'Driver capabilities for '
  949                         '\'supports_extend_volume\' '
  950                         'is invalid')
  951         self.assertFalse(drvr.requires_allocation_refresh,
  952                          'Driver does not need allocation refresh')
  953         self.assertTrue(drvr.capabilities['supports_trusted_certs'],
  954                         'Driver capabilities for '
  955                         '\'supports_trusted_certs\' '
  956                         'is invalid')
  957 
  958     def create_fake_libvirt_mock(self, **kwargs):
  959         """Defining mocks for LibvirtDriver(libvirt is not used)."""
  960 
  961         # A fake libvirt.virConnect
  962         class FakeLibvirtDriver(object):
  963             def defineXML(self, xml):
  964                 return FakeVirtDomain()
  965 
  966         # Creating mocks
  967         fake = FakeLibvirtDriver()
  968         # Customizing above fake if necessary
  969         for key, val in kwargs.items():
  970             fake.__setattr__(key, val)
  971 
  972         self.stub_out('nova.virt.libvirt.driver.LibvirtDriver._conn', fake)
  973         self.stub_out('nova.virt.libvirt.host.Host.get_connection',
  974                       lambda x: fake)
  975 
  976     def fake_lookup(self, instance_name):
  977         return FakeVirtDomain()
  978 
  979     def fake_execute(self, *args, **kwargs):
  980         open(args[-1], "a").close()
  981 
  982     def _create_service(self, **kwargs):
  983         service_ref = {'host': kwargs.get('host', 'dummy'),
  984                        'disabled': kwargs.get('disabled', False),
  985                        'binary': 'nova-compute',
  986                        'topic': 'compute',
  987                        'report_count': 0}
  988 
  989         return objects.Service(**service_ref)
  990 
  991     def _get_pause_flag(self, drvr, network_info, power_on=True,
  992                           vifs_already_plugged=False):
  993         timeout = CONF.vif_plugging_timeout
  994 
  995         events = []
  996         if (drvr._conn_supports_start_paused and
  997             utils.is_neutron() and
  998             not vifs_already_plugged and
  999             power_on and timeout):
 1000             events = drvr._get_neutron_events(network_info)
 1001 
 1002         return bool(events)
 1003 
 1004     def test_public_api_signatures(self):
 1005         baseinst = driver.ComputeDriver(None)
 1006         inst = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1007         self.assertPublicAPISignatures(baseinst, inst)
 1008 
 1009     def test_legacy_block_device_info(self):
 1010         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1011         self.assertFalse(drvr.need_legacy_block_device_info)
 1012 
 1013     @mock.patch.object(host.Host, "has_min_version")
 1014     def test_min_version_start_ok(self, mock_version):
 1015         mock_version.return_value = True
 1016         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1017         drvr.init_host("dummyhost")
 1018 
 1019     @mock.patch.object(host.Host, "has_min_version")
 1020     def test_min_version_start_abort(self, mock_version):
 1021         mock_version.return_value = False
 1022         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1023         self.assertRaises(exception.NovaException,
 1024                           drvr.init_host,
 1025                           "dummyhost")
 1026 
 1027     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1028                        return_value=versionutils.convert_version_to_int(
 1029                             libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) - 1)
 1030     @mock.patch.object(libvirt_driver.LOG, 'warning')
 1031     def test_next_min_version_deprecation_warning(self, mock_warning,
 1032                                                   mock_get_libversion):
 1033         # Skip test if there's no currently planned new min version
 1034         if (versionutils.convert_version_to_int(
 1035                 libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
 1036             versionutils.convert_version_to_int(
 1037                 libvirt_driver.MIN_LIBVIRT_VERSION)):
 1038             self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
 1039 
 1040         # Test that a warning is logged if the libvirt version is less than
 1041         # the next required minimum version.
 1042         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1043         drvr.init_host("dummyhost")
 1044         # assert that the next min version is in a warning message
 1045         expected_arg = {'version': versionutils.convert_version_to_str(
 1046             versionutils.convert_version_to_int(
 1047                 libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
 1048         version_arg_found = False
 1049         for call in mock_warning.call_args_list:
 1050             if call[0][1] == expected_arg:
 1051                 version_arg_found = True
 1052                 break
 1053         self.assertTrue(version_arg_found)
 1054 
 1055     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1056                        return_value=versionutils.convert_version_to_int(
 1057                             libvirt_driver.NEXT_MIN_QEMU_VERSION) - 1)
 1058     @mock.patch.object(libvirt_driver.LOG, 'warning')
 1059     def test_next_min_qemu_version_deprecation_warning(self, mock_warning,
 1060                                                        mock_get_libversion):
 1061         # Skip test if there's no currently planned new min version
 1062         if (versionutils.convert_version_to_int(
 1063                 libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
 1064             versionutils.convert_version_to_int(
 1065                 libvirt_driver.MIN_QEMU_VERSION)):
 1066             self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
 1067 
 1068         # Test that a warning is logged if the libvirt version is less than
 1069         # the next required minimum version.
 1070         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1071         drvr.init_host("dummyhost")
 1072         # assert that the next min version is in a warning message
 1073         expected_arg = {'version': versionutils.convert_version_to_str(
 1074             versionutils.convert_version_to_int(
 1075                 libvirt_driver.NEXT_MIN_QEMU_VERSION))}
 1076         version_arg_found = False
 1077         for call in mock_warning.call_args_list:
 1078             if call[0][1] == expected_arg:
 1079                 version_arg_found = True
 1080                 break
 1081         self.assertTrue(version_arg_found)
 1082 
 1083     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1084                        return_value=versionutils.convert_version_to_int(
 1085                             libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))
 1086     @mock.patch.object(libvirt_driver.LOG, 'warning')
 1087     def test_next_min_version_ok(self, mock_warning, mock_get_libversion):
 1088         # Skip test if there's no currently planned new min version
 1089 
 1090         if (versionutils.convert_version_to_int(
 1091                 libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
 1092             versionutils.convert_version_to_int(
 1093                 libvirt_driver.MIN_LIBVIRT_VERSION)):
 1094             self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
 1095 
 1096         # Test that a warning is not logged if the libvirt version is greater
 1097         # than or equal to NEXT_MIN_LIBVIRT_VERSION.
 1098         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1099         drvr.init_host("dummyhost")
 1100         # assert that the next min version is in a warning message
 1101         expected_arg = {'version': versionutils.convert_version_to_str(
 1102             versionutils.convert_version_to_int(
 1103                 libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
 1104         version_arg_found = False
 1105         for call in mock_warning.call_args_list:
 1106             if call[0][1] == expected_arg:
 1107                 version_arg_found = True
 1108                 break
 1109         self.assertFalse(version_arg_found)
 1110 
 1111     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1112                        return_value=versionutils.convert_version_to_int(
 1113                             libvirt_driver.NEXT_MIN_QEMU_VERSION))
 1114     @mock.patch.object(libvirt_driver.LOG, 'warning')
 1115     def test_next_min_qemu_version_ok(self, mock_warning, mock_get_libversion):
 1116         # Skip test if there's no currently planned new min version
 1117 
 1118         if (versionutils.convert_version_to_int(
 1119                 libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
 1120             versionutils.convert_version_to_int(
 1121                 libvirt_driver.MIN_QEMU_VERSION)):
 1122             self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
 1123 
 1124         # Test that a warning is not logged if the libvirt version is greater
 1125         # than or equal to NEXT_MIN_QEMU_VERSION.
 1126         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1127         drvr.init_host("dummyhost")
 1128         # assert that the next min version is in a warning message
 1129         expected_arg = {'version': versionutils.convert_version_to_str(
 1130             versionutils.convert_version_to_int(
 1131                 libvirt_driver.NEXT_MIN_QEMU_VERSION))}
 1132         version_arg_found = False
 1133         for call in mock_warning.call_args_list:
 1134             if call[0][1] == expected_arg:
 1135                 version_arg_found = True
 1136                 break
 1137         self.assertFalse(version_arg_found)
 1138 
 1139     # NOTE(sdague): python2.7 and python3.5 have different behaviors
 1140     # when it comes to comparing against the sentinel, so
 1141     # has_min_version is needed to pass python3.5.
 1142     @mock.patch.object(nova.virt.libvirt.host.Host, "has_min_version",
 1143                        return_value=True)
 1144     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1145                        return_value=mock.sentinel.qemu_version)
 1146     def test_qemu_image_version(self, mock_get_libversion, min_ver):
 1147         """Test that init_host sets qemu image version
 1148 
 1149         A sentinel is used here so that we aren't chasing this value
 1150         against minimums that get raised over time.
 1151         """
 1152         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1153         drvr.init_host("dummyhost")
 1154         self.assertEqual(images.QEMU_VERSION, mock.sentinel.qemu_version)
 1155 
 1156     @mock.patch.object(fields.Architecture, "from_host",
 1157                        return_value=fields.Architecture.PPC64)
 1158     def test_min_version_ppc_ok(self, mock_arch):
 1159         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1160         drvr.init_host("dummyhost")
 1161 
 1162     @mock.patch.object(fields.Architecture, "from_host",
 1163                        return_value=fields.Architecture.S390X)
 1164     def test_min_version_s390_ok(self, mock_arch):
 1165         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1166         drvr.init_host("dummyhost")
 1167 
 1168     def test_file_backed_memory_support_called(self):
 1169         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1170         with mock.patch.object(drvr,
 1171                 '_check_file_backed_memory_support') as mock_check_fb_support:
 1172             drvr.init_host("dummyhost")
 1173             self.assertTrue(mock_check_fb_support.called)
 1174 
 1175     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1176                        return_value=versionutils.convert_version_to_int(
 1177                            libvirt_driver.MIN_LIBVIRT_FILE_BACKED_VERSION))
 1178     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1179                        return_value=versionutils.convert_version_to_int(
 1180                            libvirt_driver.MIN_QEMU_FILE_BACKED_VERSION))
 1181     def test_min_version_file_backed_ok(self, mock_libv, mock_qemu):
 1182         self.flags(file_backed_memory=1024, group='libvirt')
 1183         self.flags(ram_allocation_ratio=1.0)
 1184         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1185         drvr._check_file_backed_memory_support()
 1186 
 1187     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1188                        return_value=versionutils.convert_version_to_int(
 1189                            libvirt_driver.MIN_LIBVIRT_FILE_BACKED_VERSION) - 1)
 1190     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1191                        return_value=versionutils.convert_version_to_int(
 1192                            libvirt_driver.MIN_QEMU_FILE_BACKED_VERSION))
 1193     def test_min_version_file_backed_old_libvirt(self, mock_libv, mock_qemu):
 1194         self.flags(file_backed_memory=1024, group="libvirt")
 1195         self.flags(ram_allocation_ratio=1.0)
 1196         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1197         self.assertRaises(exception.InternalError,
 1198                           drvr._check_file_backed_memory_support)
 1199 
 1200     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1201                        return_value=versionutils.convert_version_to_int(
 1202                            libvirt_driver.MIN_LIBVIRT_FILE_BACKED_VERSION))
 1203     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1204                        return_value=versionutils.convert_version_to_int(
 1205                            libvirt_driver.MIN_QEMU_FILE_BACKED_VERSION) - 1)
 1206     def test_min_version_file_backed_old_qemu(self, mock_libv, mock_qemu):
 1207         self.flags(file_backed_memory=1024, group="libvirt")
 1208         self.flags(ram_allocation_ratio=1.0)
 1209         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1210         self.assertRaises(exception.InternalError,
 1211                           drvr._check_file_backed_memory_support)
 1212 
 1213     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
 1214                        return_value=versionutils.convert_version_to_int(
 1215                            libvirt_driver.MIN_LIBVIRT_FILE_BACKED_VERSION))
 1216     @mock.patch.object(fakelibvirt.Connection, 'getVersion',
 1217                        return_value=versionutils.convert_version_to_int(
 1218                            libvirt_driver.MIN_QEMU_FILE_BACKED_VERSION))
 1219     def test_min_version_file_backed_bad_ram_allocation_ratio(self, mock_libv,
 1220                                                      mock_qemu):
 1221         self.flags(file_backed_memory=1024, group="libvirt")
 1222         self.flags(ram_allocation_ratio=1.5)
 1223         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1224         self.assertRaises(exception.InternalError,
 1225                           drvr._check_file_backed_memory_support)
 1226 
 1227     def _do_test_parse_migration_flags(self, lm_expected=None,
 1228                                        bm_expected=None):
 1229         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1230         drvr._parse_migration_flags()
 1231 
 1232         if lm_expected is not None:
 1233             self.assertEqual(lm_expected, drvr._live_migration_flags)
 1234         if bm_expected is not None:
 1235             self.assertEqual(bm_expected, drvr._block_migration_flags)
 1236 
 1237     def test_parse_live_migration_flags_default(self):
 1238         self._do_test_parse_migration_flags(
 1239             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1240                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1241                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1242                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
 1243 
 1244     def test_parse_live_migration_flags(self):
 1245         self._do_test_parse_migration_flags(
 1246             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1247                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1248                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1249                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
 1250 
 1251     def test_parse_block_migration_flags_default(self):
 1252         self._do_test_parse_migration_flags(
 1253             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1254                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1255                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1256                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1257                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1258                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1259 
 1260     def test_parse_block_migration_flags(self):
 1261         self._do_test_parse_migration_flags(
 1262             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1263                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1264                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1265                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1266                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1267 
 1268     def test_parse_migration_flags_p2p_xen(self):
 1269         self.flags(virt_type='xen', group='libvirt')
 1270         self._do_test_parse_migration_flags(
 1271             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1272                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1273                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
 1274             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1275                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1276                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1277                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1278 
 1279     def test_live_migration_tunnelled_true(self):
 1280         self.flags(live_migration_tunnelled=True, group='libvirt')
 1281         self._do_test_parse_migration_flags(
 1282             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1283                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1284                          libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1285                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1286                          libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED),
 1287             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1288                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1289                          libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1290                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1291                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
 1292                          libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED))
 1293 
 1294     @mock.patch.object(host.Host, 'has_min_version', return_value=True)
 1295     def test_live_migration_permit_postcopy_true(self, host):
 1296         self.flags(live_migration_permit_post_copy=True, group='libvirt')
 1297         self._do_test_parse_migration_flags(
 1298             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1299                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1300                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1301                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1302                          libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
 1303             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1304                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1305                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1306                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1307                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
 1308                          libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
 1309 
 1310     @mock.patch.object(host.Host, 'has_min_version', return_value=True)
 1311     def test_live_migration_permit_auto_converge_true(self, host):
 1312         self.flags(live_migration_permit_auto_converge=True, group='libvirt')
 1313         self._do_test_parse_migration_flags(
 1314             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1315                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1316                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1317                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1318                          libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
 1319             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1320                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1321                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1322                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1323                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
 1324                          libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
 1325 
 1326     @mock.patch.object(host.Host, 'has_min_version', return_value=True)
 1327     def test_live_migration_permit_auto_converge_and_post_copy_true(self,
 1328                                                                     host):
 1329         self.flags(live_migration_permit_auto_converge=True, group='libvirt')
 1330         self.flags(live_migration_permit_post_copy=True, group='libvirt')
 1331         self._do_test_parse_migration_flags(
 1332             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1333                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1334                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1335                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1336                          libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
 1337             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1338                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1339                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1340                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1341                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
 1342                          libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
 1343 
 1344     @mock.patch.object(host.Host, 'has_min_version', return_value=False)
 1345     def test_live_migration_auto_converge_and_post_copy_true_old_libvirt(
 1346             self, min_ver):
 1347         self.flags(live_migration_permit_auto_converge=True, group='libvirt')
 1348         self.flags(live_migration_permit_post_copy=True, group='libvirt')
 1349 
 1350         self._do_test_parse_migration_flags(
 1351             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1352                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1353                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1354                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1355                          libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
 1356             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1357                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1358                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1359                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1360                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
 1361                          libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
 1362 
 1363         min_ver.assert_called_with(
 1364             lv_ver=libvirt_driver.MIN_LIBVIRT_POSTCOPY_VERSION)
 1365 
 1366     @mock.patch.object(host.Host, 'has_min_version', return_value=False)
 1367     def test_live_migration_permit_postcopy_true_old_libvirt(self, host):
 1368         self.flags(live_migration_permit_post_copy=True, group='libvirt')
 1369 
 1370         self._do_test_parse_migration_flags(
 1371             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1372                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1373                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1374                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
 1375             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1376                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1377                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1378                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1379                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1380 
 1381     def test_live_migration_permit_postcopy_false(self):
 1382         self._do_test_parse_migration_flags(
 1383             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1384                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1385                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1386                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
 1387             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1388                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1389                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1390                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1391                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1392 
 1393     def test_live_migration_permit_autoconverge_false(self):
 1394         self._do_test_parse_migration_flags(
 1395             lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1396                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1397                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1398                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
 1399             bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
 1400                          libvirt_driver.libvirt.VIR_MIGRATE_PERSIST_DEST |
 1401                          libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
 1402                          libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
 1403                          libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
 1404 
 1405     @mock.patch('nova.utils.get_image_from_system_metadata')
 1406     @mock.patch.object(host.Host,
 1407                        'has_min_version', return_value=True)
 1408     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1409     def test_set_admin_password(self, mock_get_guest, ver, mock_image):
 1410         self.flags(virt_type='kvm', group='libvirt')
 1411         instance = objects.Instance(**self.test_instance)
 1412         mock_image.return_value = {"properties": {
 1413             "hw_qemu_guest_agent": "yes"}}
 1414         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1415         mock_get_guest.return_value = mock_guest
 1416 
 1417         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1418         drvr.set_admin_password(instance, "123")
 1419 
 1420         mock_guest.set_user_password.assert_called_once_with("root", "123")
 1421 
 1422     @mock.patch('nova.objects.Instance.save')
 1423     @mock.patch('oslo_serialization.base64.encode_as_text')
 1424     @mock.patch('nova.api.metadata.password.convert_password')
 1425     @mock.patch('nova.crypto.ssh_encrypt_text')
 1426     @mock.patch('nova.utils.get_image_from_system_metadata')
 1427     @mock.patch.object(host.Host,
 1428                        'has_min_version', return_value=True)
 1429     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1430     def test_set_admin_password_saves_sysmeta(self, mock_get_guest,
 1431                                               ver, mock_image, mock_encrypt,
 1432                                               mock_convert, mock_encode,
 1433                                               mock_save):
 1434         self.flags(virt_type='kvm', group='libvirt')
 1435         instance = objects.Instance(**self.test_instance)
 1436         # Password will only be saved in sysmeta if the key_data is present
 1437         instance.key_data = 'ssh-rsa ABCFEFG'
 1438         mock_image.return_value = {"properties": {
 1439             "hw_qemu_guest_agent": "yes"}}
 1440         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1441         mock_get_guest.return_value = mock_guest
 1442         mock_convert.return_value = {'password_0': 'converted-password'}
 1443 
 1444         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1445         drvr.set_admin_password(instance, "123")
 1446 
 1447         mock_guest.set_user_password.assert_called_once_with("root", "123")
 1448         mock_encrypt.assert_called_once_with(instance.key_data, '123')
 1449         mock_encode.assert_called_once_with(mock_encrypt.return_value)
 1450         mock_convert.assert_called_once_with(None, mock_encode.return_value)
 1451         self.assertEqual('converted-password',
 1452                          instance.system_metadata['password_0'])
 1453         mock_save.assert_called_once_with()
 1454 
 1455     @mock.patch.object(host.Host,
 1456                        'has_min_version', return_value=True)
 1457     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1458     def test_set_admin_password_parallels(self, mock_get_guest, ver):
 1459         self.flags(virt_type='parallels', group='libvirt')
 1460         instance = objects.Instance(**self.test_instance)
 1461         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1462         mock_get_guest.return_value = mock_guest
 1463 
 1464         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1465         drvr.set_admin_password(instance, "123")
 1466 
 1467         mock_guest.set_user_password.assert_called_once_with("root", "123")
 1468 
 1469     @mock.patch('nova.utils.get_image_from_system_metadata')
 1470     @mock.patch.object(host.Host,
 1471                        'has_min_version', return_value=True)
 1472     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1473     def test_set_admin_password_windows(self, mock_get_guest, ver, mock_image):
 1474         self.flags(virt_type='kvm', group='libvirt')
 1475         instance = objects.Instance(**self.test_instance)
 1476         instance.os_type = "windows"
 1477         mock_image.return_value = {"properties": {
 1478             "hw_qemu_guest_agent": "yes"}}
 1479         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1480         mock_get_guest.return_value = mock_guest
 1481 
 1482         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1483         drvr.set_admin_password(instance, "123")
 1484 
 1485         mock_guest.set_user_password.assert_called_once_with(
 1486             "Administrator", "123")
 1487 
 1488     @mock.patch('nova.utils.get_image_from_system_metadata')
 1489     @mock.patch.object(host.Host,
 1490                        'has_min_version', return_value=True)
 1491     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1492     def test_set_admin_password_image(self, mock_get_guest, ver, mock_image):
 1493         self.flags(virt_type='kvm', group='libvirt')
 1494         instance = objects.Instance(**self.test_instance)
 1495         mock_image.return_value = {"properties": {
 1496             "hw_qemu_guest_agent": "yes",
 1497             "os_admin_user": "foo"
 1498         }}
 1499         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1500         mock_get_guest.return_value = mock_guest
 1501 
 1502         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1503         drvr.set_admin_password(instance, "123")
 1504 
 1505         mock_guest.set_user_password.assert_called_once_with("foo", "123")
 1506 
 1507     @mock.patch('nova.utils.get_image_from_system_metadata')
 1508     @mock.patch.object(host.Host,
 1509                        'has_min_version', return_value=True)
 1510     def test_set_admin_password_bad_hyp(self, mock_svc, mock_image):
 1511         self.flags(virt_type='lxc', group='libvirt')
 1512         instance = objects.Instance(**self.test_instance)
 1513         mock_image.return_value = {"properties": {
 1514             "hw_qemu_guest_agent": "yes"}}
 1515         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1516         self.assertRaises(exception.SetAdminPasswdNotSupported,
 1517                           drvr.set_admin_password, instance, "123")
 1518 
 1519     @mock.patch.object(host.Host,
 1520                        'has_min_version', return_value=True)
 1521     def test_set_admin_password_guest_agent_not_running(self, mock_svc):
 1522         self.flags(virt_type='kvm', group='libvirt')
 1523         instance = objects.Instance(**self.test_instance)
 1524         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1525         self.assertRaises(exception.QemuGuestAgentNotEnabled,
 1526                           drvr.set_admin_password, instance, "123")
 1527 
 1528     @mock.patch('nova.utils.get_image_from_system_metadata')
 1529     @mock.patch.object(host.Host,
 1530                        'has_min_version', return_value=True)
 1531     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1532     def test_set_admin_password_error(self, mock_get_guest, ver, mock_image):
 1533         self.flags(virt_type='kvm', group='libvirt')
 1534         instance = objects.Instance(**self.test_instance)
 1535         mock_image.return_value = {"properties": {
 1536             "hw_qemu_guest_agent": "yes"}}
 1537         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1538         mock_guest.set_user_password.side_effect = (
 1539             fakelibvirt.libvirtError("error"))
 1540         mock_get_guest.return_value = mock_guest
 1541 
 1542         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1543         with mock.patch.object(
 1544                 drvr, '_save_instance_password_if_sshkey_present') as save_p:
 1545             self.assertRaises(exception.NovaException,
 1546                               drvr.set_admin_password, instance, "123")
 1547             save_p.assert_not_called()
 1548 
 1549     @mock.patch('nova.utils.get_image_from_system_metadata')
 1550     @mock.patch.object(host.Host,
 1551                        'has_min_version', return_value=True)
 1552     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1553     def test_set_admin_password_error_with_unicode(
 1554             self, mock_get_guest, ver, mock_image):
 1555         self.flags(virt_type='kvm', group='libvirt')
 1556         instance = objects.Instance(**self.test_instance)
 1557         mock_image.return_value = {"properties": {
 1558             "hw_qemu_guest_agent": "yes"}}
 1559         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1560         mock_guest.set_user_password.side_effect = (
 1561                 fakelibvirt.libvirtError(
 1562                     b"failed: \xe9\x94\x99\xe8\xaf\xaf\xe3\x80\x82"))
 1563         mock_get_guest.return_value = mock_guest
 1564 
 1565         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1566         self.assertRaises(exception.NovaException,
 1567                           drvr.set_admin_password, instance, "123")
 1568 
 1569     @mock.patch('nova.utils.get_image_from_system_metadata')
 1570     @mock.patch.object(host.Host,
 1571                        'has_min_version', return_value=True)
 1572     @mock.patch('nova.virt.libvirt.host.Host.get_guest')
 1573     def test_set_admin_password_not_implemented(
 1574             self, mock_get_guest, ver, mock_image):
 1575         self.flags(virt_type='kvm', group='libvirt')
 1576         instance = objects.Instance(**self.test_instance)
 1577         mock_image.return_value = {"properties": {
 1578             "hw_qemu_guest_agent": "yes"}}
 1579         mock_guest = mock.Mock(spec=libvirt_guest.Guest)
 1580         not_implemented = fakelibvirt.make_libvirtError(
 1581                 fakelibvirt.libvirtError,
 1582                 "Guest agent disappeared while executing command",
 1583                 error_code=fakelibvirt.VIR_ERR_AGENT_UNRESPONSIVE)
 1584         mock_guest.set_user_password.side_effect = not_implemented
 1585         mock_get_guest.return_value = mock_guest
 1586 
 1587         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1588         self.assertRaises(NotImplementedError,
 1589                           drvr.set_admin_password, instance, "123")
 1590 
 1591     @mock.patch.object(objects.Service, 'save')
 1592     @mock.patch.object(objects.Service, 'get_by_compute_host')
 1593     def test_set_host_enabled_with_disable(self, mock_svc, mock_save):
 1594         # Tests disabling an enabled host.
 1595         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1596         svc = self._create_service(host='fake-mini')
 1597         mock_svc.return_value = svc
 1598         drvr._set_host_enabled(False)
 1599         self.assertTrue(svc.disabled)
 1600         mock_save.assert_called_once_with()
 1601 
 1602     @mock.patch.object(objects.Service, 'save')
 1603     @mock.patch.object(objects.Service, 'get_by_compute_host')
 1604     def test_set_host_enabled_with_enable(self, mock_svc, mock_save):
 1605         # Tests enabling a disabled host.
 1606         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1607         svc = self._create_service(disabled=True, host='fake-mini')
 1608         mock_svc.return_value = svc
 1609         drvr._set_host_enabled(True)
 1610         # since disabled_reason is not set and not prefixed with "AUTO:",
 1611         # service should not be enabled.
 1612         mock_save.assert_not_called()
 1613         self.assertTrue(svc.disabled)
 1614 
 1615     @mock.patch.object(objects.Service, 'save')
 1616     @mock.patch.object(objects.Service, 'get_by_compute_host')
 1617     def test_set_host_enabled_with_enable_state_enabled(self, mock_svc,
 1618                                                         mock_save):
 1619         # Tests enabling an enabled host.
 1620         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1621         svc = self._create_service(disabled=False, host='fake-mini')
 1622         mock_svc.return_value = svc
 1623         drvr._set_host_enabled(True)
 1624         self.assertFalse(svc.disabled)
 1625         mock_save.assert_not_called()
 1626 
 1627     @mock.patch.object(objects.Service, 'save')
 1628     @mock.patch.object(objects.Service, 'get_by_compute_host')
 1629     def test_set_host_enabled_with_disable_state_disabled(self, mock_svc,
 1630                                                           mock_save):
 1631         # Tests disabling a disabled host.
 1632         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1633         svc = self._create_service(disabled=True, host='fake-mini')
 1634         mock_svc.return_value = svc
 1635         drvr._set_host_enabled(False)
 1636         mock_save.assert_not_called()
 1637         self.assertTrue(svc.disabled)
 1638 
 1639     def test_set_host_enabled_swallows_exceptions(self):
 1640         # Tests that set_host_enabled will swallow exceptions coming from the
 1641         # db_api code so they don't break anything calling it, e.g. the
 1642         # _get_new_connection method.
 1643         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1644         with mock.patch.object(db, 'service_get_by_compute_host') as db_mock:
 1645             # Make db.service_get_by_compute_host raise NovaException; this
 1646             # is more robust than just raising ComputeHostNotFound.
 1647             db_mock.side_effect = exception.NovaException
 1648             drvr._set_host_enabled(False)
 1649 
 1650     @mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
 1651     def test_prepare_pci_device(self, mock_lookup):
 1652 
 1653         pci_devices = [dict(hypervisor_name='xxx')]
 1654 
 1655         self.flags(virt_type='xen', group='libvirt')
 1656 
 1657         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1658         conn = drvr._host.get_connection()
 1659 
 1660         mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
 1661         drvr._prepare_pci_devices_for_use(pci_devices)
 1662 
 1663     @mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
 1664     @mock.patch.object(fakelibvirt.virNodeDevice, "dettach")
 1665     def test_prepare_pci_device_exception(self, mock_detach, mock_lookup):
 1666 
 1667         pci_devices = [dict(hypervisor_name='xxx',
 1668                             id='id1',
 1669                             instance_uuid='uuid')]
 1670 
 1671         self.flags(virt_type='xen', group='libvirt')
 1672         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1673         conn = drvr._host.get_connection()
 1674 
 1675         mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
 1676         mock_detach.side_effect = fakelibvirt.libvirtError("xxxx")
 1677 
 1678         self.assertRaises(exception.PciDevicePrepareFailed,
 1679                           drvr._prepare_pci_devices_for_use, pci_devices)
 1680 
 1681     @mock.patch.object(host.Host, "has_min_version", return_value=False)
 1682     def test_device_metadata(self, mock_version):
 1683         xml = """
 1684         <domain>
 1685           <name>dummy</name>
 1686           <uuid>32dfcb37-5af1-552b-357c-be8c3aa38310</uuid>
 1687             <memory>1048576</memory>
 1688               <vcpu>1</vcpu>
 1689             <os>
 1690                 <type arch='x86_64' machine='pc-i440fx-2.4'>hvm</type>
 1691             </os>
 1692           <devices>
 1693             <disk type='block' device='disk'>
 1694               <driver name='qemu' type='qcow2'/>
 1695               <source dev='/dev/mapper/generic'/>
 1696               <target dev='sda' bus='scsi'/>
 1697              <address type='drive' controller='0' bus='0' target='0' unit='0'/>
 1698             </disk>
 1699             <disk type='block' device='disk'>
 1700               <driver name='qemu' type='qcow2'/>
 1701               <source dev='/dev/mapper/generic-1'/>
 1702               <target dev='hda' bus='ide'/>
 1703              <address type='drive' controller='0' bus='1' target='0' unit='0'/>
 1704             </disk>
 1705             <disk type='block' device='disk'>
 1706               <driver name='qemu' type='qcow2'/>
 1707               <source dev='/dev/mapper/generic-2'/>
 1708               <target dev='hdb' bus='ide'/>
 1709              <address type='drive' controller='0' bus='1' target='1' unit='1'/>
 1710             </disk>
 1711             <disk type='block' device='disk'>
 1712               <driver name='qemu' type='qcow2'/>
 1713               <source dev='/dev/mapper/aa1'/>
 1714               <target dev='sdb' bus='usb'/>
 1715             </disk>
 1716             <disk type='block' device='disk'>
 1717               <driver name='qemu' type='qcow2'/>
 1718               <source dev='/var/lib/libvirt/images/centos'/>
 1719               <backingStore/>
 1720               <target dev='vda' bus='virtio'/>
 1721               <boot order='1'/>
 1722               <alias name='virtio-disk0'/>
 1723               <address type='pci' domain='0x0000' bus='0x00' slot='0x09'
 1724               function='0x0'/>
 1725             </disk>
 1726             <disk type='file' device='disk'>
 1727                 <driver name='qemu' type='qcow2' cache='none'/>
 1728                 <source file='/var/lib/libvirt/images/generic.qcow2'/>
 1729                 <target dev='vdb' bus='virtio'/>
 1730                 <address type='virtio-mmio'/>
 1731             </disk>
 1732             <disk type='file' device='disk'>
 1733                 <driver name='qemu' type='qcow2'/>
 1734                 <source file='/var/lib/libvirt/images/test.qcow2'/>
 1735                 <backingStore/>
 1736                 <target dev='vdc' bus='virtio'/>
 1737                 <alias name='virtio-disk1'/>
 1738                 <address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0000'/>
 1739             </disk>
 1740             <interface type='network'>
 1741               <mac address='52:54:00:f6:35:8f'/>
 1742               <source network='default'/>
 1743               <model type='virtio'/>
 1744               <address type='pci' domain='0x0000' bus='0x00' slot='0x03'
 1745               function='0x0'/>
 1746             </interface>
 1747             <interface type='network'>
 1748               <mac address='51:5a:2c:a4:5e:1b'/>
 1749               <source network='default'/>
 1750               <model type='virtio'/>
 1751               <address type='pci' domain='0x0000' bus='0x00' slot='0x04'
 1752               function='0x1'/>
 1753             </interface>
 1754             <interface type='network'>
 1755               <mac address='fa:16:3e:d1:28:e4'/>
 1756               <source network='default'/>
 1757               <model type='virtio'/>
 1758               <address type='virtio-mmio'/>
 1759             </interface>
 1760             <interface type='network'>
 1761                 <mac address='52:54:00:14:6f:50'/>
 1762                 <source network='default' bridge='virbr0'/>
 1763                 <target dev='vnet0'/>
 1764                 <model type='virtio'/>
 1765                 <alias name='net0'/>
 1766                 <address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0001'/>
 1767             </interface>
 1768             <hostdev mode="subsystem" type="pci" managed="yes">
 1769                 <source>
 1770                     <address bus="0x06" domain="0x0000" function="0x1"
 1771                     slot="0x00"/>
 1772                 </source>
 1773             </hostdev>
 1774           </devices>
 1775         </domain>"""
 1776 
 1777         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1778         dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
 1779         guest = libvirt_guest.Guest(dom)
 1780 
 1781         instance_ref = objects.Instance(**self.test_instance)
 1782         bdms = block_device_obj.block_device_make_list_from_dicts(
 1783             self.context, [
 1784                 fake_block_device.FakeDbBlockDeviceDict(
 1785                     {'id': 1,
 1786                      'source_type': 'volume', 'destination_type': 'volume',
 1787                      'device_name': '/dev/sda', 'tag': "db",
 1788                      'volume_id': uuids.volume_1}),
 1789                 fake_block_device.FakeDbBlockDeviceDict(
 1790                     {'id': 2,
 1791                      'source_type': 'volume', 'destination_type': 'volume',
 1792                      'device_name': '/dev/hda', 'tag': "nfvfunc1",
 1793                      'volume_id': uuids.volume_2}),
 1794                 fake_block_device.FakeDbBlockDeviceDict(
 1795                     {'id': 3,
 1796                      'source_type': 'volume', 'destination_type': 'volume',
 1797                      'device_name': '/dev/sdb', 'tag': "nfvfunc2",
 1798                      'volume_id': uuids.volume_3}),
 1799                 fake_block_device.FakeDbBlockDeviceDict(
 1800                     {'id': 4,
 1801                      'source_type': 'volume', 'destination_type': 'volume',
 1802                      'device_name': '/dev/hdb',
 1803                      'volume_id': uuids.volume_4}),
 1804                 fake_block_device.FakeDbBlockDeviceDict(
 1805                     {'id': 5,
 1806                      'source_type': 'volume', 'destination_type': 'volume',
 1807                      'device_name': '/dev/vda', 'tag': "nfvfunc3",
 1808                      'volume_id': uuids.volume_5}),
 1809                 fake_block_device.FakeDbBlockDeviceDict(
 1810                     {'id': 6,
 1811                      'source_type': 'volume', 'destination_type': 'volume',
 1812                      'device_name': '/dev/vdb', 'tag': "nfvfunc4",
 1813                      'volume_id': uuids.volume_6}),
 1814                 fake_block_device.FakeDbBlockDeviceDict(
 1815                     {'id': 7,
 1816                      'source_type': 'volume', 'destination_type': 'volume',
 1817                      'device_name': '/dev/vdc', 'tag': "nfvfunc5",
 1818                      'volume_id': uuids.volume_7}),
 1819             ]
 1820         )
 1821         vif = obj_vif.VirtualInterface(context=self.context)
 1822         vif.address = '52:54:00:f6:35:8f'
 1823         vif.network_id = 123
 1824         vif.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
 1825         vif.uuid = '12ec4b21-ef22-6c21-534b-ba3e3ab3a311'
 1826         vif.tag = 'mytag1'
 1827 
 1828         vif1 = obj_vif.VirtualInterface(context=self.context)
 1829         vif1.address = '51:5a:2c:a4:5e:1b'
 1830         vif1.network_id = 123
 1831         vif1.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
 1832         vif1.uuid = 'abec4b21-ef22-6c21-534b-ba3e3ab3a312'
 1833 
 1834         vif2 = obj_vif.VirtualInterface(context=self.context)
 1835         vif2.address = 'fa:16:3e:d1:28:e4'
 1836         vif2.network_id = 123
 1837         vif2.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
 1838         vif2.uuid = '645686e4-7086-4eab-8c2f-c41f017a1b16'
 1839         vif2.tag = 'mytag2'
 1840 
 1841         vif3 = obj_vif.VirtualInterface(context=self.context)
 1842         vif3.address = '52:54:00:14:6f:50'
 1843         vif3.network_id = 123
 1844         vif3.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
 1845         vif3.uuid = '99cc3604-782d-4a32-a27c-bc33ac56ce86'
 1846         vif3.tag = 'mytag3'
 1847 
 1848         vif4 = obj_vif.VirtualInterface(context=self.context)
 1849         vif4.address = 'da:d1:f2:91:95:c1'
 1850         vif4.tag = 'pf_tag'
 1851 
 1852         vifs = [vif, vif1, vif2, vif3, vif4]
 1853 
 1854         network_info = _fake_network_info(self, 4)
 1855         network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT_PHYSICAL
 1856         network_info[0]['address'] = "51:5a:2c:a4:5e:1b"
 1857         network_info[0]['details'] = dict(vlan='2145')
 1858         network_info[0]['profile'] = dict(trusted='true')
 1859         instance_ref.info_cache = objects.InstanceInfoCache(
 1860             network_info=network_info)
 1861 
 1862         with test.nested(
 1863             mock.patch('nova.objects.VirtualInterfaceList'
 1864                        '.get_by_instance_uuid', return_value=vifs),
 1865             mock.patch('nova.objects.BlockDeviceMappingList'
 1866                        '.get_by_instance_uuid', return_value=bdms),
 1867             mock.patch('nova.virt.libvirt.host.Host.get_guest',
 1868                        return_value=guest),
 1869             mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc',
 1870                               return_value=xml),
 1871             mock.patch.object(pci_utils, 'get_mac_by_pci_address',
 1872                               return_value='da:d1:f2:91:95:c1')):
 1873             metadata_obj = drvr._build_device_metadata(self.context,
 1874                                                        instance_ref)
 1875             metadata = metadata_obj.devices
 1876             self.assertEqual(11, len(metadata))
 1877             self.assertIsInstance(metadata[0],
 1878                                   objects.DiskMetadata)
 1879             self.assertIsInstance(metadata[0].bus,
 1880                                   objects.SCSIDeviceBus)
 1881             self.assertEqual(['db'], metadata[0].tags)
 1882             self.assertEqual(uuids.volume_1, metadata[0].serial)
 1883             self.assertFalse(metadata[0].bus.obj_attr_is_set('address'))
 1884             self.assertEqual(['nfvfunc1'], metadata[1].tags)
 1885             self.assertEqual(uuids.volume_2, metadata[1].serial)
 1886             self.assertIsInstance(metadata[1],
 1887                                   objects.DiskMetadata)
 1888             self.assertIsInstance(metadata[1].bus,
 1889                                   objects.IDEDeviceBus)
 1890             self.assertEqual(['nfvfunc1'], metadata[1].tags)
 1891             self.assertFalse(metadata[1].bus.obj_attr_is_set('address'))
 1892             self.assertIsInstance(metadata[2],
 1893                                   objects.DiskMetadata)
 1894             self.assertIsInstance(metadata[2].bus,
 1895                                   objects.USBDeviceBus)
 1896             self.assertEqual(['nfvfunc2'], metadata[2].tags)
 1897             self.assertEqual(uuids.volume_3, metadata[2].serial)
 1898             self.assertFalse(metadata[2].bus.obj_attr_is_set('address'))
 1899             self.assertIsInstance(metadata[3],
 1900                                   objects.DiskMetadata)
 1901             self.assertIsInstance(metadata[3].bus,
 1902                                   objects.PCIDeviceBus)
 1903             self.assertEqual(['nfvfunc3'], metadata[3].tags)
 1904             # NOTE(artom) We're not checking volume 4 because it's not tagged
 1905             # and only tagged devices appear in the metadata
 1906             self.assertEqual(uuids.volume_5, metadata[3].serial)
 1907             self.assertEqual('0000:00:09.0', metadata[3].bus.address)
 1908             self.assertIsInstance(metadata[4],
 1909                                   objects.DiskMetadata)
 1910             self.assertEqual(['nfvfunc4'], metadata[4].tags)
 1911             self.assertEqual(uuids.volume_6, metadata[4].serial)
 1912             self.assertIsInstance(metadata[5],
 1913                                   objects.DiskMetadata)
 1914             self.assertEqual(['nfvfunc5'], metadata[5].tags)
 1915             self.assertEqual(uuids.volume_7, metadata[5].serial)
 1916             self.assertIsInstance(metadata[6],
 1917                                   objects.NetworkInterfaceMetadata)
 1918             self.assertIsInstance(metadata[6].bus,
 1919                                   objects.PCIDeviceBus)
 1920             self.assertEqual(['mytag1'], metadata[6].tags)
 1921             self.assertEqual('0000:00:03.0', metadata[6].bus.address)
 1922             self.assertFalse(metadata[6].vf_trusted)
 1923 
 1924             # Make sure that interface with vlan is exposed to the metadata
 1925             self.assertIsInstance(metadata[7],
 1926                                   objects.NetworkInterfaceMetadata)
 1927             self.assertEqual('51:5a:2c:a4:5e:1b', metadata[7].mac)
 1928             self.assertEqual(2145, metadata[7].vlan)
 1929             self.assertTrue(metadata[7].vf_trusted)
 1930             self.assertIsInstance(metadata[8],
 1931                                   objects.NetworkInterfaceMetadata)
 1932             self.assertEqual(['mytag2'], metadata[8].tags)
 1933             self.assertFalse(metadata[8].vf_trusted)
 1934             self.assertIsInstance(metadata[9],
 1935                                   objects.NetworkInterfaceMetadata)
 1936             self.assertEqual(['mytag3'], metadata[9].tags)
 1937             self.assertFalse(metadata[9].vf_trusted)
 1938             self.assertIsInstance(metadata[10],
 1939                                   objects.NetworkInterfaceMetadata)
 1940             self.assertEqual(['pf_tag'], metadata[10].tags)
 1941             self.assertEqual('da:d1:f2:91:95:c1', metadata[10].mac)
 1942             self.assertEqual('0000:06:00.1', metadata[10].bus.address)
 1943 
 1944     @mock.patch.object(host.Host, 'get_connection')
 1945     @mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
 1946     def test_detach_pci_devices(self, mocked_get_xml_desc, mock_conn):
 1947 
 1948         fake_domXML1_with_pci = (
 1949             """<domain> <devices>
 1950             <disk type='file' device='disk'>
 1951             <driver name='qemu' type='qcow2' cache='none'/>
 1952             <source file='xxx'/>
 1953             <target dev='vda' bus='virtio'/>
 1954             <alias name='virtio-disk0'/>
 1955             <address type='pci' domain='0x0000' bus='0x00'
 1956             slot='0x04' function='0x0'/>
 1957             </disk>
 1958             <hostdev mode="subsystem" type="pci" managed="yes">
 1959             <source>
 1960             <address function="0x1" slot="0x10" domain="0x0001"
 1961              bus="0x04"/>
 1962             </source>
 1963             </hostdev></devices></domain>""")
 1964 
 1965         fake_domXML1_without_pci = (
 1966             """<domain> <devices>
 1967             <disk type='file' device='disk'>
 1968             <driver name='qemu' type='qcow2' cache='none'/>
 1969             <source file='xxx'/>
 1970             <target dev='vda' bus='virtio'/>
 1971             <alias name='virtio-disk0'/>
 1972             <address type='pci' domain='0x0001' bus='0x00'
 1973             slot='0x04' function='0x0'/>
 1974             </disk></devices></domain>""")
 1975 
 1976         pci_device_info = {'compute_node_id': 1,
 1977                            'instance_uuid': 'uuid',
 1978                            'address': '0001:04:10.1'}
 1979         pci_device = objects.PciDevice(**pci_device_info)
 1980         pci_devices = [pci_device]
 1981         mocked_get_xml_desc.return_value = fake_domXML1_without_pci
 1982 
 1983         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 1984         dom = fakelibvirt.Domain(
 1985             drvr._get_connection(), fake_domXML1_with_pci, False)
 1986         guest = libvirt_guest.Guest(dom)
 1987         drvr._detach_pci_devices(guest, pci_devices)
 1988 
 1989     @mock.patch.object(host.Host, 'get_connection')
 1990     @mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
 1991     def test_detach_pci_devices_timeout(self, mocked_get_xml_desc, mock_conn):
 1992 
 1993         fake_domXML1_with_pci = (
 1994             """<domain> <devices>
 1995             <disk type='file' device='disk'>
 1996             <driver name='qemu' type='qcow2' cache='none'/>
 1997             <source file='xxx'/>
 1998             <target dev='vda' bus='virtio'/>
 1999             <alias name='virtio-disk0'/>
 2000             <address type='pci' domain='0x0000' bus='0x00'
 2001             slot='0x04' function='0x0'/>
 2002             </disk>
 2003             <hostdev mode="subsystem" type="pci" managed="yes">
 2004             <source>
 2005             <address function="0x1" slot="0x10" domain="0x0001"
 2006              bus="0x04"/>
 2007             </source>
 2008             </hostdev></devices></domain>""")
 2009 
 2010         pci_device_info = {'compute_node_id': 1,
 2011                            'instance_uuid': 'uuid',
 2012                            'address': '0001:04:10.1'}
 2013         pci_device = objects.PciDevice(**pci_device_info)
 2014         pci_devices = [pci_device]
 2015         mocked_get_xml_desc.return_value = fake_domXML1_with_pci
 2016 
 2017         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2018         dom = fakelibvirt.Domain(
 2019             drvr._get_connection(), fake_domXML1_with_pci, False)
 2020         guest = libvirt_guest.Guest(dom)
 2021         self.assertRaises(exception.PciDeviceDetachFailed,
 2022                           drvr._detach_pci_devices, guest, pci_devices)
 2023 
 2024     @mock.patch.object(connector, 'get_connector_properties')
 2025     def test_get_connector(self, fake_get_connector):
 2026         initiator = 'fake.initiator.iqn'
 2027         ip = 'fakeip'
 2028         host = 'fakehost'
 2029         wwpns = ['100010604b019419']
 2030         wwnns = ['200010604b019419']
 2031         self.flags(my_ip=ip)
 2032         self.flags(host=host)
 2033 
 2034         expected = {
 2035             'ip': ip,
 2036             'initiator': initiator,
 2037             'host': host,
 2038             'wwpns': wwpns,
 2039             'wwnns': wwnns
 2040         }
 2041         volume = {
 2042             'id': 'fake'
 2043         }
 2044 
 2045         # TODO(walter-boring) add the fake in os-brick
 2046         fake_get_connector.return_value = expected
 2047         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2048         result = drvr.get_volume_connector(volume)
 2049         self.assertThat(expected, matchers.DictMatches(result))
 2050 
 2051     @mock.patch.object(connector, 'get_connector_properties')
 2052     def test_get_connector_storage_ip(self, fake_get_connector):
 2053         ip = '100.100.100.100'
 2054         storage_ip = '101.101.101.101'
 2055         self.flags(my_block_storage_ip=storage_ip, my_ip=ip)
 2056         volume = {
 2057             'id': 'fake'
 2058         }
 2059         expected = {
 2060             'ip': storage_ip
 2061         }
 2062         # TODO(walter-boring) add the fake in os-brick
 2063         fake_get_connector.return_value = expected
 2064         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2065         result = drvr.get_volume_connector(volume)
 2066         self.assertEqual(storage_ip, result['ip'])
 2067 
 2068     def test_lifecycle_event_registration(self):
 2069         calls = []
 2070 
 2071         def fake_registerErrorHandler(*args, **kwargs):
 2072             calls.append('fake_registerErrorHandler')
 2073 
 2074         def fake_get_host_capabilities(**args):
 2075             cpu = vconfig.LibvirtConfigGuestCPU()
 2076             cpu.arch = fields.Architecture.ARMV7
 2077 
 2078             caps = vconfig.LibvirtConfigCaps()
 2079             caps.host = vconfig.LibvirtConfigCapsHost()
 2080             caps.host.cpu = cpu
 2081             calls.append('fake_get_host_capabilities')
 2082             return caps
 2083 
 2084         @mock.patch.object(fakelibvirt, 'registerErrorHandler',
 2085                            side_effect=fake_registerErrorHandler)
 2086         @mock.patch.object(host.Host, "get_capabilities",
 2087                             side_effect=fake_get_host_capabilities)
 2088         def test_init_host(get_host_capabilities, register_error_handler):
 2089             drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2090             drvr.init_host("test_host")
 2091 
 2092         test_init_host()
 2093         # NOTE(dkliban): Will fail if get_host_capabilities is called before
 2094         # registerErrorHandler
 2095         self.assertEqual(['fake_registerErrorHandler',
 2096                           'fake_get_host_capabilities'], calls)
 2097 
 2098     def test_sanitize_log_to_xml(self):
 2099         # setup fake data
 2100         data = {'auth_password': 'scrubme'}
 2101         bdm = [{'connection_info': {'data': data}}]
 2102         bdi = {'block_device_mapping': bdm}
 2103 
 2104         # Tests that the parameters to the _get_guest_xml method
 2105         # are sanitized for passwords when logged.
 2106         def fake_debug(*args, **kwargs):
 2107             if 'auth_password' in args[0]:
 2108                 self.assertNotIn('scrubme', args[0])
 2109 
 2110         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2111         conf = mock.Mock()
 2112         with test.nested(
 2113             mock.patch.object(libvirt_driver.LOG, 'debug',
 2114                               side_effect=fake_debug),
 2115             mock.patch.object(drvr, '_get_guest_config', return_value=conf)
 2116         ) as (
 2117             debug_mock, conf_mock
 2118         ):
 2119             drvr._get_guest_xml(self.context, self.test_instance,
 2120                                 network_info={}, disk_info={},
 2121                                 image_meta={}, block_device_info=bdi)
 2122             # we don't care what the log message is, we just want to make sure
 2123             # our stub method is called which asserts the password is scrubbed
 2124             self.assertTrue(debug_mock.called)
 2125 
 2126     @mock.patch.object(time, "time")
 2127     def test_get_guest_config(self, time_mock):
 2128         time_mock.return_value = 1234567.89
 2129 
 2130         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2131 
 2132         test_instance = copy.deepcopy(self.test_instance)
 2133         test_instance["display_name"] = "purple tomatoes"
 2134         test_instance['system_metadata']['owner_project_name'] = 'sweetshop'
 2135         test_instance['system_metadata']['owner_user_name'] = 'cupcake'
 2136 
 2137         ctxt = context.RequestContext(project_id=123,
 2138                                       project_name="aubergine",
 2139                                       user_id=456,
 2140                                       user_name="pie")
 2141 
 2142         flavor = objects.Flavor(name='m1.small',
 2143                                 memory_mb=6,
 2144                                 vcpus=28,
 2145                                 root_gb=496,
 2146                                 ephemeral_gb=8128,
 2147                                 swap=33550336,
 2148                                 extra_specs={})
 2149         instance_ref = objects.Instance(**test_instance)
 2150         instance_ref.flavor = flavor
 2151         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2152 
 2153         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2154                                             instance_ref,
 2155                                             image_meta)
 2156 
 2157         cfg = drvr._get_guest_config(instance_ref,
 2158                                      _fake_network_info(self, 1),
 2159                                      image_meta, disk_info,
 2160                                      context=ctxt)
 2161 
 2162         self.assertEqual(cfg.uuid, instance_ref["uuid"])
 2163         self.assertEqual(2, len(cfg.features))
 2164         self.assertIsInstance(cfg.features[0],
 2165                               vconfig.LibvirtConfigGuestFeatureACPI)
 2166         self.assertIsInstance(cfg.features[1],
 2167                               vconfig.LibvirtConfigGuestFeatureAPIC)
 2168         self.assertEqual(cfg.memory, 6 * units.Ki)
 2169         self.assertEqual(cfg.vcpus, 28)
 2170         self.assertEqual(cfg.os_type, fields.VMMode.HVM)
 2171         self.assertEqual(cfg.os_boot_dev, ["hd"])
 2172         self.assertIsNone(cfg.os_root)
 2173         self.assertEqual(len(cfg.devices), 10)
 2174         self.assertIsInstance(cfg.devices[0],
 2175                               vconfig.LibvirtConfigGuestDisk)
 2176         self.assertIsInstance(cfg.devices[1],
 2177                               vconfig.LibvirtConfigGuestDisk)
 2178         self.assertIsInstance(cfg.devices[2],
 2179                               vconfig.LibvirtConfigGuestDisk)
 2180         self.assertIsInstance(cfg.devices[3],
 2181                               vconfig.LibvirtConfigGuestInterface)
 2182         self.assertIsInstance(cfg.devices[4],
 2183                               vconfig.LibvirtConfigGuestSerial)
 2184         self.assertIsInstance(cfg.devices[5],
 2185                               vconfig.LibvirtConfigGuestSerial)
 2186         self.assertIsInstance(cfg.devices[6],
 2187                               vconfig.LibvirtConfigGuestInput)
 2188         self.assertIsInstance(cfg.devices[7],
 2189                               vconfig.LibvirtConfigGuestGraphics)
 2190         self.assertIsInstance(cfg.devices[8],
 2191                               vconfig.LibvirtConfigGuestVideo)
 2192         self.assertIsInstance(cfg.devices[9],
 2193                               vconfig.LibvirtConfigMemoryBalloon)
 2194         self.assertEqual(len(cfg.metadata), 1)
 2195         self.assertIsInstance(cfg.metadata[0],
 2196                               vconfig.LibvirtConfigGuestMetaNovaInstance)
 2197         self.assertEqual(version.version_string_with_package(),
 2198                          cfg.metadata[0].package)
 2199         self.assertEqual("purple tomatoes",
 2200                          cfg.metadata[0].name)
 2201         self.assertEqual(1234567.89,
 2202                          cfg.metadata[0].creationTime)
 2203         self.assertEqual("image",
 2204                          cfg.metadata[0].roottype)
 2205         self.assertEqual(str(instance_ref["image_ref"]),
 2206                          cfg.metadata[0].rootid)
 2207 
 2208         self.assertIsInstance(cfg.metadata[0].owner,
 2209                               vconfig.LibvirtConfigGuestMetaNovaOwner)
 2210         self.assertEqual("838a72b0-0d54-4827-8fd6-fb1227633ceb",
 2211                          cfg.metadata[0].owner.userid)
 2212         self.assertEqual("cupcake",
 2213                          cfg.metadata[0].owner.username)
 2214         self.assertEqual("fake",
 2215                          cfg.metadata[0].owner.projectid)
 2216         self.assertEqual("sweetshop",
 2217                          cfg.metadata[0].owner.projectname)
 2218 
 2219         self.assertIsInstance(cfg.metadata[0].flavor,
 2220                               vconfig.LibvirtConfigGuestMetaNovaFlavor)
 2221         self.assertEqual("m1.small",
 2222                          cfg.metadata[0].flavor.name)
 2223         self.assertEqual(6,
 2224                          cfg.metadata[0].flavor.memory)
 2225         self.assertEqual(28,
 2226                          cfg.metadata[0].flavor.vcpus)
 2227         self.assertEqual(496,
 2228                          cfg.metadata[0].flavor.disk)
 2229         self.assertEqual(8128,
 2230                          cfg.metadata[0].flavor.ephemeral)
 2231         self.assertEqual(33550336,
 2232                          cfg.metadata[0].flavor.swap)
 2233 
 2234     def test_get_guest_config_q35(self):
 2235         self.flags(virt_type="kvm",
 2236                    group='libvirt')
 2237 
 2238         TEST_AMOUNT_OF_PCIE_SLOTS = 8
 2239         CONF.set_override("num_pcie_ports", TEST_AMOUNT_OF_PCIE_SLOTS,
 2240                 group='libvirt')
 2241 
 2242         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2243         instance_ref = objects.Instance(**self.test_instance)
 2244         image_meta = objects.ImageMeta.from_dict({
 2245             "disk_format": "raw",
 2246             "properties": {"hw_machine_type":
 2247                            "pc-q35-test"}})
 2248 
 2249         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2250                                             instance_ref,
 2251                                             image_meta)
 2252 
 2253         cfg = drvr._get_guest_config(instance_ref,
 2254                                      _fake_network_info(self, 1),
 2255                                      image_meta, disk_info)
 2256 
 2257         num_ports = 0
 2258         for device in cfg.devices:
 2259             try:
 2260                 if (device.root_name == 'controller' and
 2261                         device.model == 'pcie-root-port'):
 2262                     num_ports += 1
 2263             except AttributeError:
 2264                 pass
 2265 
 2266         self.assertEqual(TEST_AMOUNT_OF_PCIE_SLOTS, num_ports)
 2267 
 2268     def test_get_guest_config_pcie_i440fx(self):
 2269         self.flags(virt_type="kvm",
 2270                    group='libvirt')
 2271 
 2272         TEST_AMOUNT_OF_PCIE_SLOTS = 8
 2273         CONF.set_override("num_pcie_ports", TEST_AMOUNT_OF_PCIE_SLOTS,
 2274                 group='libvirt')
 2275 
 2276         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2277         instance_ref = objects.Instance(**self.test_instance)
 2278         image_meta = objects.ImageMeta.from_dict({
 2279             "disk_format": "raw",
 2280             "properties": {"hw_machine_type":
 2281                            "pc-i440fx-test"}})
 2282 
 2283         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2284                                             instance_ref,
 2285                                             image_meta)
 2286 
 2287         cfg = drvr._get_guest_config(instance_ref,
 2288                                      _fake_network_info(self, 1),
 2289                                      image_meta, disk_info)
 2290 
 2291         num_ports = 0
 2292         for device in cfg.devices:
 2293             try:
 2294                 if (device.root_name == 'controller' and
 2295                         device.model == 'pcie-root-port'):
 2296                     num_ports += 1
 2297             except AttributeError:
 2298                 pass
 2299 
 2300         # i440fx is not pcie machine so there should be no pcie ports
 2301         self.assertEqual(0, num_ports)
 2302 
 2303     def test_get_guest_config_missing_ownership_info(self):
 2304         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2305 
 2306         test_instance = copy.deepcopy(self.test_instance)
 2307 
 2308         ctxt = context.RequestContext(project_id=123,
 2309                                       project_name="aubergine",
 2310                                       user_id=456,
 2311                                       user_name="pie")
 2312 
 2313         flavor = objects.Flavor(name='m1.small',
 2314                                 memory_mb=6,
 2315                                 vcpus=28,
 2316                                 root_gb=496,
 2317                                 ephemeral_gb=8128,
 2318                                 swap=33550336,
 2319                                 extra_specs={})
 2320         instance_ref = objects.Instance(**test_instance)
 2321         instance_ref.flavor = flavor
 2322         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2323 
 2324         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2325                                             instance_ref,
 2326                                             image_meta)
 2327 
 2328         cfg = drvr._get_guest_config(instance_ref,
 2329                                      _fake_network_info(self, 1),
 2330                                      image_meta, disk_info,
 2331                                      context=ctxt)
 2332         self.assertEqual("N/A",
 2333                          cfg.metadata[0].owner.username)
 2334         self.assertEqual("N/A",
 2335                          cfg.metadata[0].owner.projectname)
 2336 
 2337     def test_get_guest_config_lxc(self):
 2338         self.flags(virt_type='lxc', group='libvirt')
 2339         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2340         instance_ref = objects.Instance(**self.test_instance)
 2341         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2342         cfg = drvr._get_guest_config(instance_ref,
 2343                                      _fake_network_info(self, 1),
 2344                                      image_meta, {'mapping': {}})
 2345         self.assertEqual(instance_ref["uuid"], cfg.uuid)
 2346         self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
 2347         self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
 2348         self.assertEqual(fields.VMMode.EXE, cfg.os_type)
 2349         self.assertEqual("/sbin/init", cfg.os_init_path)
 2350         self.assertEqual("console=tty0 console=ttyS0 console=hvc0",
 2351                          cfg.os_cmdline)
 2352         self.assertIsNone(cfg.os_root)
 2353         self.assertEqual(3, len(cfg.devices))
 2354         self.assertIsInstance(cfg.devices[0],
 2355                               vconfig.LibvirtConfigGuestFilesys)
 2356         self.assertIsInstance(cfg.devices[1],
 2357                               vconfig.LibvirtConfigGuestInterface)
 2358         self.assertIsInstance(cfg.devices[2],
 2359                               vconfig.LibvirtConfigGuestConsole)
 2360 
 2361     def test_get_guest_config_lxc_with_id_maps(self):
 2362         self.flags(virt_type='lxc', group='libvirt')
 2363         self.flags(uid_maps=['0:1000:100'], group='libvirt')
 2364         self.flags(gid_maps=['0:1000:100'], group='libvirt')
 2365         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2366         instance_ref = objects.Instance(**self.test_instance)
 2367         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2368         cfg = drvr._get_guest_config(instance_ref,
 2369                                      _fake_network_info(self, 1),
 2370                                      image_meta, {'mapping': {}})
 2371         self.assertEqual(instance_ref["uuid"], cfg.uuid)
 2372         self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
 2373         self.assertEqual(instance_ref.vcpus, cfg.vcpus)
 2374         self.assertEqual(fields.VMMode.EXE, cfg.os_type)
 2375         self.assertEqual("/sbin/init", cfg.os_init_path)
 2376         self.assertEqual("console=tty0 console=ttyS0 console=hvc0",
 2377                          cfg.os_cmdline)
 2378         self.assertIsNone(cfg.os_root)
 2379         self.assertEqual(3, len(cfg.devices))
 2380         self.assertIsInstance(cfg.devices[0],
 2381                               vconfig.LibvirtConfigGuestFilesys)
 2382         self.assertIsInstance(cfg.devices[1],
 2383                               vconfig.LibvirtConfigGuestInterface)
 2384         self.assertIsInstance(cfg.devices[2],
 2385                               vconfig.LibvirtConfigGuestConsole)
 2386         self.assertEqual(len(cfg.idmaps), 2)
 2387         self.assertIsInstance(cfg.idmaps[0],
 2388                               vconfig.LibvirtConfigGuestUIDMap)
 2389         self.assertIsInstance(cfg.idmaps[1],
 2390                               vconfig.LibvirtConfigGuestGIDMap)
 2391 
 2392     @mock.patch.object(
 2393         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2394     def test_get_guest_config_numa_host_instance_fits(self, is_able):
 2395         instance_ref = objects.Instance(**self.test_instance)
 2396         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2397         flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
 2398                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2399                                 extra_specs={})
 2400         instance_ref.flavor = flavor
 2401 
 2402         caps = vconfig.LibvirtConfigCaps()
 2403         caps.host = vconfig.LibvirtConfigCapsHost()
 2404         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2405         caps.host.cpu.arch = fields.Architecture.X86_64
 2406         caps.host.topology = fakelibvirt.NUMATopology()
 2407 
 2408         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2409         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2410                                             instance_ref,
 2411                                             image_meta)
 2412 
 2413         with test.nested(
 2414                 mock.patch.object(host.Host, 'has_min_version',
 2415                                   return_value=True),
 2416                 mock.patch.object(host.Host, "get_capabilities",
 2417                                   return_value=caps)):
 2418             cfg = drvr._get_guest_config(instance_ref, [],
 2419                                          image_meta, disk_info)
 2420             self.assertIsNone(cfg.cpuset)
 2421             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2422             self.assertIsNone(cfg.cpu.numa)
 2423 
 2424     @mock.patch.object(
 2425         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2426     def test_get_guest_config_numa_host_instance_no_fit(self, is_able):
 2427         instance_ref = objects.Instance(**self.test_instance)
 2428         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2429         flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
 2430                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2431                                 extra_specs={})
 2432         instance_ref.flavor = flavor
 2433 
 2434         caps = vconfig.LibvirtConfigCaps()
 2435         caps.host = vconfig.LibvirtConfigCapsHost()
 2436         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2437         caps.host.cpu.arch = fields.Architecture.X86_64
 2438         caps.host.topology = fakelibvirt.NUMATopology()
 2439 
 2440         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2441         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2442                                             instance_ref,
 2443                                             image_meta)
 2444 
 2445         with test.nested(
 2446                 mock.patch.object(host.Host, "get_capabilities",
 2447                                   return_value=caps),
 2448                 mock.patch.object(
 2449                     hardware, 'get_vcpu_pin_set', return_value=set([3])),
 2450                 mock.patch.object(random, 'choice'),
 2451                 mock.patch.object(drvr, '_has_numa_support',
 2452                                   return_value=False)
 2453             ) as (get_host_cap_mock,
 2454                   get_vcpu_pin_set_mock, choice_mock,
 2455                   _has_numa_support_mock):
 2456             cfg = drvr._get_guest_config(instance_ref, [],
 2457                                          image_meta, disk_info)
 2458             self.assertFalse(choice_mock.called)
 2459             self.assertEqual(set([3]), cfg.cpuset)
 2460             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2461             self.assertIsNone(cfg.cpu.numa)
 2462 
 2463     def _test_get_guest_memory_backing_config(
 2464             self, host_topology, inst_topology, numatune):
 2465         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2466         with mock.patch.object(
 2467                 drvr, "_get_host_numa_topology",
 2468                 return_value=host_topology):
 2469             return drvr._get_guest_memory_backing_config(
 2470                 inst_topology, numatune, {})
 2471 
 2472     @mock.patch.object(host.Host,
 2473                        'has_min_version', return_value=True)
 2474     def test_get_guest_memory_backing_config_large_success(self, mock_version):
 2475         host_topology = objects.NUMATopology(
 2476             cells=[
 2477                 objects.NUMACell(
 2478                     id=3, cpuset=set([1]), siblings=[set([1])], memory=1024,
 2479                     mempages=[
 2480                         objects.NUMAPagesTopology(size_kb=4, total=2000,
 2481                                                   used=0),
 2482                         objects.NUMAPagesTopology(size_kb=2048, total=512,
 2483                                                   used=0),
 2484                         objects.NUMAPagesTopology(size_kb=1048576, total=0,
 2485                                                   used=0),
 2486                     ])])
 2487         inst_topology = objects.InstanceNUMATopology(cells=[
 2488             objects.InstanceNUMACell(
 2489                 id=3, cpuset=set([0, 1]), memory=1024, pagesize=2048)])
 2490 
 2491         numa_tune = vconfig.LibvirtConfigGuestNUMATune()
 2492         numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
 2493         numa_tune.memnodes[0].cellid = 0
 2494         numa_tune.memnodes[0].nodeset = [3]
 2495 
 2496         result = self._test_get_guest_memory_backing_config(
 2497             host_topology, inst_topology, numa_tune)
 2498         self.assertEqual(1, len(result.hugepages))
 2499         self.assertEqual(2048, result.hugepages[0].size_kb)
 2500         self.assertEqual([0], result.hugepages[0].nodeset)
 2501 
 2502     @mock.patch.object(host.Host,
 2503                        'has_min_version', return_value=True)
 2504     def test_get_guest_memory_backing_config_smallest(self, mock_version):
 2505         host_topology = objects.NUMATopology(
 2506             cells=[
 2507                 objects.NUMACell(
 2508                     id=3, cpuset=set([1]), siblings=[set([1])], memory=1024,
 2509                     mempages=[
 2510                         objects.NUMAPagesTopology(size_kb=4, total=2000,
 2511                                                   used=0),
 2512                         objects.NUMAPagesTopology(size_kb=2048, total=512,
 2513                                                   used=0),
 2514                         objects.NUMAPagesTopology(size_kb=1048576, total=0,
 2515                                                   used=0),
 2516                     ])])
 2517         inst_topology = objects.InstanceNUMATopology(cells=[
 2518             objects.InstanceNUMACell(
 2519                 id=3, cpuset=set([0, 1]), memory=1024, pagesize=4)])
 2520 
 2521         numa_tune = vconfig.LibvirtConfigGuestNUMATune()
 2522         numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
 2523         numa_tune.memnodes[0].cellid = 0
 2524         numa_tune.memnodes[0].nodeset = [3]
 2525 
 2526         result = self._test_get_guest_memory_backing_config(
 2527             host_topology, inst_topology, numa_tune)
 2528         self.assertIsNone(result)
 2529 
 2530     def test_get_guest_memory_backing_config_realtime(self):
 2531         flavor = {"extra_specs": {
 2532             "hw:cpu_realtime": "yes",
 2533             "hw:cpu_policy": "dedicated"
 2534         }}
 2535         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2536         membacking = drvr._get_guest_memory_backing_config(
 2537             None, None, flavor)
 2538         self.assertTrue(membacking.locked)
 2539         self.assertFalse(membacking.sharedpages)
 2540 
 2541     def test_get_guest_memory_backing_config_file_backed(self):
 2542         self.flags(file_backed_memory=1024, group="libvirt")
 2543 
 2544         result = self._test_get_guest_memory_backing_config(
 2545             None, None, None
 2546         )
 2547         self.assertTrue(result.sharedaccess)
 2548         self.assertTrue(result.filesource)
 2549         self.assertTrue(result.allocateimmediate)
 2550 
 2551     @mock.patch.object(fakelibvirt.Connection, 'getVersion')
 2552     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
 2553     def test_get_guest_memory_backing_config_file_backed_discard(self,
 2554             mock_lib_version, mock_version):
 2555         self.flags(file_backed_memory=1024, group='libvirt')
 2556 
 2557         mock_lib_version.return_value = versionutils.convert_version_to_int(
 2558             libvirt_driver.MIN_LIBVIRT_FILE_BACKED_DISCARD_VERSION)
 2559         mock_version.return_value = versionutils.convert_version_to_int(
 2560             libvirt_driver.MIN_QEMU_FILE_BACKED_DISCARD_VERSION)
 2561 
 2562         result = self._test_get_guest_memory_backing_config(
 2563             None, None, None
 2564         )
 2565         self.assertTrue(result.discard)
 2566 
 2567     @mock.patch.object(fakelibvirt.Connection, 'getVersion')
 2568     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
 2569     def test_get_guest_memory_backing_config_file_backed_discard_libvirt(self,
 2570             mock_lib_version, mock_version):
 2571         self.flags(file_backed_memory=1024, group='libvirt')
 2572 
 2573         mock_lib_version.return_value = versionutils.convert_version_to_int(
 2574             libvirt_driver.MIN_LIBVIRT_FILE_BACKED_DISCARD_VERSION) - 1
 2575         mock_version.return_value = versionutils.convert_version_to_int(
 2576             libvirt_driver.MIN_QEMU_FILE_BACKED_DISCARD_VERSION)
 2577 
 2578         result = self._test_get_guest_memory_backing_config(
 2579             None, None, None
 2580         )
 2581         self.assertFalse(result.discard)
 2582 
 2583     @mock.patch.object(fakelibvirt.Connection, 'getVersion')
 2584     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
 2585     def test_get_guest_memory_backing_config_file_backed_discard_qemu(self,
 2586             mock_lib_version, mock_version):
 2587         self.flags(file_backed_memory=1024, group='libvirt')
 2588 
 2589         mock_lib_version.return_value = versionutils.convert_version_to_int(
 2590             libvirt_driver.MIN_LIBVIRT_FILE_BACKED_DISCARD_VERSION)
 2591         mock_version.return_value = versionutils.convert_version_to_int(
 2592             libvirt_driver.MIN_QEMU_FILE_BACKED_DISCARD_VERSION) - 1
 2593 
 2594         result = self._test_get_guest_memory_backing_config(
 2595             None, None, None
 2596         )
 2597         self.assertFalse(result.discard)
 2598 
 2599     def test_get_guest_memory_backing_config_file_backed_hugepages(self):
 2600         self.flags(file_backed_memory=1024, group="libvirt")
 2601         host_topology = objects.NUMATopology(
 2602             cells=[
 2603                 objects.NUMACell(
 2604                     id=3, cpuset=set([1]), siblings=[set([1])], memory=1024,
 2605                     mempages=[
 2606                         objects.NUMAPagesTopology(size_kb=4, total=2000,
 2607                                                   used=0),
 2608                         objects.NUMAPagesTopology(size_kb=2048, total=512,
 2609                                                   used=0),
 2610                         objects.NUMAPagesTopology(size_kb=1048576, total=0,
 2611                                                   used=0),
 2612                     ])])
 2613         inst_topology = objects.InstanceNUMATopology(cells=[
 2614             objects.InstanceNUMACell(
 2615                 id=3, cpuset=set([0, 1]), memory=1024, pagesize=2048)])
 2616 
 2617         numa_tune = vconfig.LibvirtConfigGuestNUMATune()
 2618         numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
 2619         numa_tune.memnodes[0].cellid = 0
 2620         numa_tune.memnodes[0].nodeset = [3]
 2621 
 2622         self.assertRaises(exception.MemoryPagesUnsupported,
 2623                           self._test_get_guest_memory_backing_config,
 2624                           host_topology, inst_topology, numa_tune)
 2625 
 2626     @mock.patch.object(
 2627         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2628     def test_get_guest_config_numa_host_instance_pci_no_numa_info(
 2629             self, is_able):
 2630         instance_ref = objects.Instance(**self.test_instance)
 2631         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2632         flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
 2633                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2634                                 extra_specs={})
 2635         instance_ref.flavor = flavor
 2636 
 2637         caps = vconfig.LibvirtConfigCaps()
 2638         caps.host = vconfig.LibvirtConfigCapsHost()
 2639         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2640         caps.host.cpu.arch = fields.Architecture.X86_64
 2641         caps.host.topology = fakelibvirt.NUMATopology()
 2642 
 2643         conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2644         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2645                                             instance_ref,
 2646                                             image_meta)
 2647         pci_device_info = dict(test_pci_device.fake_db_dev)
 2648         pci_device_info.update(compute_node_id=1,
 2649                                label='fake',
 2650                                status=fields.PciDeviceStatus.AVAILABLE,
 2651                                address='0000:00:00.1',
 2652                                instance_uuid=None,
 2653                                request_id=None,
 2654                                extra_info={},
 2655                                numa_node=None)
 2656         pci_device = objects.PciDevice(**pci_device_info)
 2657 
 2658         with test.nested(
 2659                 mock.patch.object(host.Host, 'has_min_version',
 2660                                   return_value=True),
 2661                 mock.patch.object(
 2662                     host.Host, "get_capabilities", return_value=caps),
 2663                 mock.patch.object(
 2664                     hardware, 'get_vcpu_pin_set', return_value=set([3])),
 2665                 mock.patch.object(host.Host, 'get_online_cpus',
 2666                                   return_value=set(range(8))),
 2667                 mock.patch.object(pci_manager, "get_instance_pci_devs",
 2668                                   return_value=[pci_device])):
 2669             cfg = conn._get_guest_config(instance_ref, [],
 2670                                          image_meta, disk_info)
 2671             self.assertEqual(set([3]), cfg.cpuset)
 2672             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2673             self.assertIsNone(cfg.cpu.numa)
 2674 
 2675     @mock.patch.object(
 2676         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2677     def test_get_guest_config_numa_host_instance_2pci_no_fit(self, is_able):
 2678         instance_ref = objects.Instance(**self.test_instance)
 2679         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2680         flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
 2681                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2682                                 extra_specs={})
 2683         instance_ref.flavor = flavor
 2684 
 2685         caps = vconfig.LibvirtConfigCaps()
 2686         caps.host = vconfig.LibvirtConfigCapsHost()
 2687         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2688         caps.host.cpu.arch = fields.Architecture.X86_64
 2689         caps.host.topology = fakelibvirt.NUMATopology()
 2690 
 2691         conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2692         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2693                                             instance_ref,
 2694                                             image_meta)
 2695         pci_device_info = dict(test_pci_device.fake_db_dev)
 2696         pci_device_info.update(compute_node_id=1,
 2697                                label='fake',
 2698                                status=fields.PciDeviceStatus.AVAILABLE,
 2699                                address='0000:00:00.1',
 2700                                instance_uuid=None,
 2701                                request_id=None,
 2702                                extra_info={},
 2703                                numa_node=1)
 2704         pci_device = objects.PciDevice(**pci_device_info)
 2705         pci_device_info.update(numa_node=0, address='0000:00:00.2')
 2706         pci_device2 = objects.PciDevice(**pci_device_info)
 2707         with test.nested(
 2708                 mock.patch.object(
 2709                     host.Host, "get_capabilities", return_value=caps),
 2710                 mock.patch.object(
 2711                     hardware, 'get_vcpu_pin_set', return_value=set([3])),
 2712                 mock.patch.object(random, 'choice'),
 2713                 mock.patch.object(pci_manager, "get_instance_pci_devs",
 2714                                   return_value=[pci_device, pci_device2]),
 2715                 mock.patch.object(conn, '_has_numa_support',
 2716                                   return_value=False)
 2717             ) as (get_host_cap_mock,
 2718                   get_vcpu_pin_set_mock, choice_mock, pci_mock,
 2719                   _has_numa_support_mock):
 2720             cfg = conn._get_guest_config(instance_ref, [],
 2721                                          image_meta, disk_info)
 2722             self.assertFalse(choice_mock.called)
 2723             self.assertEqual(set([3]), cfg.cpuset)
 2724             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2725             self.assertIsNone(cfg.cpu.numa)
 2726 
 2727     @mock.patch.object(fakelibvirt.Connection, 'getType')
 2728     @mock.patch.object(fakelibvirt.Connection, 'getVersion')
 2729     @mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
 2730     @mock.patch.object(host.Host, 'get_capabilities')
 2731     @mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled')
 2732     def _test_get_guest_config_numa_unsupported(self, fake_lib_version,
 2733                                                 fake_version, fake_type,
 2734                                                 fake_arch, exception_class,
 2735                                                 pagesize, mock_host,
 2736                                                 mock_caps, mock_lib_version,
 2737                                                 mock_version, mock_type):
 2738         instance_topology = objects.InstanceNUMATopology(
 2739                     cells=[objects.InstanceNUMACell(
 2740                         id=0, cpuset=set([0]),
 2741                         memory=1024, pagesize=pagesize)])
 2742         instance_ref = objects.Instance(**self.test_instance)
 2743         instance_ref.numa_topology = instance_topology
 2744         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2745         flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
 2746                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2747                                 extra_specs={})
 2748         instance_ref.flavor = flavor
 2749 
 2750         caps = vconfig.LibvirtConfigCaps()
 2751         caps.host = vconfig.LibvirtConfigCapsHost()
 2752         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2753         caps.host.cpu.arch = fake_arch
 2754         caps.host.topology = fakelibvirt.NUMATopology()
 2755 
 2756         mock_type.return_value = fake_type
 2757         mock_version.return_value = fake_version
 2758         mock_lib_version.return_value = fake_lib_version
 2759         mock_caps.return_value = caps
 2760 
 2761         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2762         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2763                                             instance_ref,
 2764                                             image_meta)
 2765 
 2766         self.assertRaises(exception_class,
 2767                           drvr._get_guest_config,
 2768                           instance_ref, [],
 2769                           image_meta, disk_info)
 2770 
 2771     def test_get_guest_config_numa_other_arch_qemu(self):
 2772         self.flags(virt_type='kvm', group='libvirt')
 2773 
 2774         self._test_get_guest_config_numa_unsupported(
 2775             versionutils.convert_version_to_int(
 2776                 libvirt_driver.MIN_LIBVIRT_VERSION),
 2777             versionutils.convert_version_to_int(
 2778                 libvirt_driver.MIN_QEMU_VERSION),
 2779             host.HV_DRIVER_QEMU,
 2780             fields.Architecture.S390,
 2781             exception.NUMATopologyUnsupported,
 2782             None)
 2783 
 2784     def test_get_guest_config_numa_xen(self):
 2785         self.flags(virt_type='xen', group='libvirt')
 2786         self._test_get_guest_config_numa_unsupported(
 2787             versionutils.convert_version_to_int(
 2788                 libvirt_driver.MIN_LIBVIRT_VERSION),
 2789             versionutils.convert_version_to_int((4, 5, 0)),
 2790             'XEN',
 2791             fields.Architecture.X86_64,
 2792             exception.NUMATopologyUnsupported,
 2793             None)
 2794 
 2795     @mock.patch.object(
 2796         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2797     def test_get_guest_config_numa_host_instance_fit_w_cpu_pinset(
 2798             self, is_able):
 2799         instance_ref = objects.Instance(**self.test_instance)
 2800         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2801         flavor = objects.Flavor(memory_mb=1024, vcpus=2, root_gb=496,
 2802                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2803                                 extra_specs={})
 2804         instance_ref.flavor = flavor
 2805 
 2806         caps = vconfig.LibvirtConfigCaps()
 2807         caps.host = vconfig.LibvirtConfigCapsHost()
 2808         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2809         caps.host.cpu.arch = fields.Architecture.X86_64
 2810         caps.host.topology = fakelibvirt.NUMATopology(kb_mem=4194304)
 2811 
 2812         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2813         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2814                                             instance_ref,
 2815                                             image_meta)
 2816 
 2817         with test.nested(
 2818                 mock.patch.object(host.Host, 'has_min_version',
 2819                                   return_value=True),
 2820                 mock.patch.object(host.Host, "get_capabilities",
 2821                                   return_value=caps),
 2822                 mock.patch.object(
 2823                     hardware, 'get_vcpu_pin_set', return_value=set([2, 3])),
 2824                 mock.patch.object(host.Host, 'get_online_cpus',
 2825                                   return_value=set(range(8)))
 2826                 ) as (has_min_version_mock, get_host_cap_mock,
 2827                         get_vcpu_pin_set_mock, get_online_cpus_mock):
 2828             cfg = drvr._get_guest_config(instance_ref, [],
 2829                                          image_meta, disk_info)
 2830             # NOTE(ndipanov): we make sure that pin_set was taken into account
 2831             # when choosing viable cells
 2832             self.assertEqual(set([2, 3]), cfg.cpuset)
 2833             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2834             self.assertIsNone(cfg.cpu.numa)
 2835 
 2836     @mock.patch.object(
 2837         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2838     def test_get_guest_config_non_numa_host_instance_topo(self, is_able):
 2839         instance_topology = objects.InstanceNUMATopology(
 2840                     cells=[objects.InstanceNUMACell(
 2841                         id=0, cpuset=set([0]), memory=1024),
 2842                            objects.InstanceNUMACell(
 2843                         id=1, cpuset=set([2]), memory=1024)])
 2844         instance_ref = objects.Instance(**self.test_instance)
 2845         instance_ref.numa_topology = instance_topology
 2846         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2847         flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
 2848                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2849                                 extra_specs={})
 2850         instance_ref.flavor = flavor
 2851 
 2852         caps = vconfig.LibvirtConfigCaps()
 2853         caps.host = vconfig.LibvirtConfigCapsHost()
 2854         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2855         caps.host.cpu.arch = fields.Architecture.X86_64
 2856         caps.host.topology = None
 2857 
 2858         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2859         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2860                                             instance_ref,
 2861                                             image_meta)
 2862 
 2863         with test.nested(
 2864                 mock.patch.object(
 2865                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 2866                     return_value=instance_topology),
 2867                 mock.patch.object(host.Host, 'has_min_version',
 2868                                   return_value=True),
 2869                 mock.patch.object(host.Host, "get_capabilities",
 2870                                   return_value=caps)):
 2871             cfg = drvr._get_guest_config(instance_ref, [],
 2872                                          image_meta, disk_info)
 2873             self.assertIsNone(cfg.cpuset)
 2874             self.assertEqual(0, len(cfg.cputune.vcpupin))
 2875             self.assertIsNone(cfg.numatune)
 2876             self.assertIsNotNone(cfg.cpu.numa)
 2877             for instance_cell, numa_cfg_cell in zip(
 2878                     instance_topology.cells, cfg.cpu.numa.cells):
 2879                 self.assertEqual(instance_cell.id, numa_cfg_cell.id)
 2880                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 2881                 self.assertEqual(instance_cell.memory * units.Ki,
 2882                                  numa_cfg_cell.memory)
 2883 
 2884     @mock.patch.object(
 2885         host.Host, "is_cpu_control_policy_capable", return_value=True)
 2886     def test_get_guest_config_numa_host_instance_topo(self, is_able):
 2887         instance_topology = objects.InstanceNUMATopology(
 2888                     cells=[objects.InstanceNUMACell(
 2889                         id=1, cpuset=set([0, 1]), memory=1024, pagesize=None),
 2890                            objects.InstanceNUMACell(
 2891                                id=2, cpuset=set([2, 3]), memory=1024,
 2892                                pagesize=None)])
 2893         instance_ref = objects.Instance(**self.test_instance)
 2894         instance_ref.numa_topology = instance_topology
 2895         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2896         flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
 2897                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2898                                 extra_specs={})
 2899         instance_ref.flavor = flavor
 2900 
 2901         caps = vconfig.LibvirtConfigCaps()
 2902         caps.host = vconfig.LibvirtConfigCapsHost()
 2903         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2904         caps.host.cpu.arch = fields.Architecture.X86_64
 2905         caps.host.topology = fakelibvirt.NUMATopology()
 2906 
 2907         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2908         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2909                                             instance_ref,
 2910                                             image_meta)
 2911 
 2912         with test.nested(
 2913                 mock.patch.object(
 2914                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 2915                     return_value=instance_topology),
 2916                 mock.patch.object(host.Host, 'has_min_version',
 2917                                   return_value=True),
 2918                 mock.patch.object(host.Host, "get_capabilities",
 2919                                   return_value=caps),
 2920                 mock.patch.object(
 2921                     hardware, 'get_vcpu_pin_set',
 2922                     return_value=set([2, 3, 4, 5])),
 2923                 mock.patch.object(host.Host, 'get_online_cpus',
 2924                                   return_value=set(range(8))),
 2925                 ):
 2926             cfg = drvr._get_guest_config(instance_ref, [],
 2927                                          image_meta, disk_info)
 2928             self.assertIsNone(cfg.cpuset)
 2929             # Test that the pinning is correct and limited to allowed only
 2930             self.assertEqual(0, cfg.cputune.vcpupin[0].id)
 2931             self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[0].cpuset)
 2932             self.assertEqual(1, cfg.cputune.vcpupin[1].id)
 2933             self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[1].cpuset)
 2934             self.assertEqual(2, cfg.cputune.vcpupin[2].id)
 2935             self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[2].cpuset)
 2936             self.assertEqual(3, cfg.cputune.vcpupin[3].id)
 2937             self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[3].cpuset)
 2938             self.assertIsNotNone(cfg.cpu.numa)
 2939 
 2940             self.assertIsInstance(cfg.cputune.emulatorpin,
 2941                                   vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
 2942             self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
 2943 
 2944             for instance_cell, numa_cfg_cell, index in zip(
 2945                     instance_topology.cells,
 2946                     cfg.cpu.numa.cells,
 2947                     range(len(instance_topology.cells))):
 2948                 self.assertEqual(index, numa_cfg_cell.id)
 2949                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 2950                 self.assertEqual(instance_cell.memory * units.Ki,
 2951                                  numa_cfg_cell.memory)
 2952 
 2953             allnodes = [cell.id for cell in instance_topology.cells]
 2954             self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
 2955             self.assertEqual("strict", cfg.numatune.memory.mode)
 2956 
 2957             for instance_cell, memnode, index in zip(
 2958                     instance_topology.cells,
 2959                     cfg.numatune.memnodes,
 2960                     range(len(instance_topology.cells))):
 2961                 self.assertEqual(index, memnode.cellid)
 2962                 self.assertEqual([instance_cell.id], memnode.nodeset)
 2963                 self.assertEqual("strict", memnode.mode)
 2964 
 2965     def test_get_guest_config_numa_host_instance_topo_reordered(self):
 2966         instance_topology = objects.InstanceNUMATopology(
 2967                     cells=[objects.InstanceNUMACell(
 2968                         id=3, cpuset=set([0, 1]), memory=1024),
 2969                            objects.InstanceNUMACell(
 2970                         id=0, cpuset=set([2, 3]), memory=1024)])
 2971         instance_ref = objects.Instance(**self.test_instance)
 2972         instance_ref.numa_topology = instance_topology
 2973         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 2974         flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
 2975                                 ephemeral_gb=8128, swap=33550336, name='fake',
 2976                                 extra_specs={})
 2977         instance_ref.flavor = flavor
 2978 
 2979         caps = vconfig.LibvirtConfigCaps()
 2980         caps.host = vconfig.LibvirtConfigCapsHost()
 2981         caps.host.cpu = vconfig.LibvirtConfigCPU()
 2982         caps.host.cpu.arch = fields.Architecture.X86_64
 2983         caps.host.topology = fakelibvirt.NUMATopology()
 2984 
 2985         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 2986         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 2987                                             instance_ref,
 2988                                             image_meta)
 2989 
 2990         with test.nested(
 2991                 mock.patch.object(
 2992                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 2993                     return_value=instance_topology),
 2994                 mock.patch.object(host.Host, 'has_min_version',
 2995                                   return_value=True),
 2996                 mock.patch.object(host.Host, "get_capabilities",
 2997                                   return_value=caps),
 2998                 mock.patch.object(host.Host, 'get_online_cpus',
 2999                                   return_value=set(range(8))),
 3000                 ):
 3001             cfg = drvr._get_guest_config(instance_ref, [],
 3002                                          image_meta, disk_info)
 3003             self.assertIsNone(cfg.cpuset)
 3004             # Test that the pinning is correct and limited to allowed only
 3005             self.assertEqual(0, cfg.cputune.vcpupin[0].id)
 3006             self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[0].cpuset)
 3007             self.assertEqual(1, cfg.cputune.vcpupin[1].id)
 3008             self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[1].cpuset)
 3009             self.assertEqual(2, cfg.cputune.vcpupin[2].id)
 3010             self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[2].cpuset)
 3011             self.assertEqual(3, cfg.cputune.vcpupin[3].id)
 3012             self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[3].cpuset)
 3013             self.assertIsNotNone(cfg.cpu.numa)
 3014 
 3015             self.assertIsInstance(cfg.cputune.emulatorpin,
 3016                                   vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
 3017             self.assertEqual(set([0, 1, 6, 7]), cfg.cputune.emulatorpin.cpuset)
 3018 
 3019             for index, (instance_cell, numa_cfg_cell) in enumerate(zip(
 3020                     instance_topology.cells,
 3021                     cfg.cpu.numa.cells)):
 3022                 self.assertEqual(index, numa_cfg_cell.id)
 3023                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 3024                 self.assertEqual(instance_cell.memory * units.Ki,
 3025                                  numa_cfg_cell.memory)
 3026                 self.assertIsNone(numa_cfg_cell.memAccess)
 3027 
 3028             allnodes = set([cell.id for cell in instance_topology.cells])
 3029             self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
 3030             self.assertEqual("strict", cfg.numatune.memory.mode)
 3031 
 3032             for index, (instance_cell, memnode) in enumerate(zip(
 3033                     instance_topology.cells,
 3034                     cfg.numatune.memnodes)):
 3035                 self.assertEqual(index, memnode.cellid)
 3036                 self.assertEqual([instance_cell.id], memnode.nodeset)
 3037                 self.assertEqual("strict", memnode.mode)
 3038 
 3039     def test_get_guest_config_numa_host_instance_topo_cpu_pinning(self):
 3040         instance_topology = objects.InstanceNUMATopology(
 3041                     cells=[objects.InstanceNUMACell(
 3042                         id=1, cpuset=set([0, 1]), memory=1024,
 3043                         cpu_pinning={0: 24, 1: 25}),
 3044                            objects.InstanceNUMACell(
 3045                         id=0, cpuset=set([2, 3]), memory=1024,
 3046                         cpu_pinning={2: 0, 3: 1})])
 3047         instance_ref = objects.Instance(**self.test_instance)
 3048         instance_ref.numa_topology = instance_topology
 3049         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3050         flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
 3051                                 ephemeral_gb=8128, swap=33550336, name='fake',
 3052                                 extra_specs={})
 3053         instance_ref.flavor = flavor
 3054 
 3055         caps = vconfig.LibvirtConfigCaps()
 3056         caps.host = vconfig.LibvirtConfigCapsHost()
 3057         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3058         caps.host.cpu.arch = fields.Architecture.X86_64
 3059         caps.host.topology = fakelibvirt.NUMATopology(
 3060             sockets_per_cell=4, cores_per_socket=3, threads_per_core=2)
 3061 
 3062         conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3063         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3064                                             instance_ref,
 3065                                             image_meta)
 3066 
 3067         with test.nested(
 3068                 mock.patch.object(
 3069                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3070                     return_value=instance_topology),
 3071                 mock.patch.object(host.Host, 'has_min_version',
 3072                                   return_value=True),
 3073                 mock.patch.object(host.Host, "get_capabilities",
 3074                                   return_value=caps),
 3075                 mock.patch.object(host.Host, 'get_online_cpus',
 3076                                   return_value=set(range(8))),
 3077                 ):
 3078             cfg = conn._get_guest_config(instance_ref, [],
 3079                                          image_meta, disk_info)
 3080             self.assertIsNone(cfg.cpuset)
 3081             # Test that the pinning is correct and limited to allowed only
 3082             self.assertEqual(0, cfg.cputune.vcpupin[0].id)
 3083             self.assertEqual(set([24]), cfg.cputune.vcpupin[0].cpuset)
 3084             self.assertEqual(1, cfg.cputune.vcpupin[1].id)
 3085             self.assertEqual(set([25]), cfg.cputune.vcpupin[1].cpuset)
 3086             self.assertEqual(2, cfg.cputune.vcpupin[2].id)
 3087             self.assertEqual(set([0]), cfg.cputune.vcpupin[2].cpuset)
 3088             self.assertEqual(3, cfg.cputune.vcpupin[3].id)
 3089             self.assertEqual(set([1]), cfg.cputune.vcpupin[3].cpuset)
 3090             self.assertIsNotNone(cfg.cpu.numa)
 3091 
 3092             # Emulator must be pinned to union of cfg.cputune.vcpupin[*].cpuset
 3093             self.assertIsInstance(cfg.cputune.emulatorpin,
 3094                                   vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
 3095             self.assertEqual(set([0, 1, 24, 25]),
 3096                              cfg.cputune.emulatorpin.cpuset)
 3097 
 3098             for i, (instance_cell, numa_cfg_cell) in enumerate(zip(
 3099                     instance_topology.cells, cfg.cpu.numa.cells)):
 3100                 self.assertEqual(i, numa_cfg_cell.id)
 3101                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 3102                 self.assertEqual(instance_cell.memory * units.Ki,
 3103                                  numa_cfg_cell.memory)
 3104                 self.assertIsNone(numa_cfg_cell.memAccess)
 3105 
 3106             allnodes = set([cell.id for cell in instance_topology.cells])
 3107             self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
 3108             self.assertEqual("strict", cfg.numatune.memory.mode)
 3109 
 3110             for i, (instance_cell, memnode) in enumerate(zip(
 3111                     instance_topology.cells, cfg.numatune.memnodes)):
 3112                 self.assertEqual(i, memnode.cellid)
 3113                 self.assertEqual([instance_cell.id], memnode.nodeset)
 3114                 self.assertEqual("strict", memnode.mode)
 3115 
 3116     def test_get_guest_config_numa_host_mempages_shared(self):
 3117         instance_topology = objects.InstanceNUMATopology(
 3118             cells=[
 3119                 objects.InstanceNUMACell(
 3120                     id=1, cpuset=set([0, 1]),
 3121                     memory=1024, pagesize=2048),
 3122                 objects.InstanceNUMACell(
 3123                     id=2, cpuset=set([2, 3]),
 3124                     memory=1024, pagesize=2048)])
 3125         instance_ref = objects.Instance(**self.test_instance)
 3126         instance_ref.numa_topology = instance_topology
 3127         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3128         flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
 3129                                 ephemeral_gb=8128, swap=33550336, name='fake',
 3130                                 extra_specs={})
 3131         instance_ref.flavor = flavor
 3132 
 3133         caps = vconfig.LibvirtConfigCaps()
 3134         caps.host = vconfig.LibvirtConfigCapsHost()
 3135         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3136         caps.host.cpu.arch = fields.Architecture.X86_64
 3137         caps.host.topology = fakelibvirt.NUMATopology()
 3138         for i, cell in enumerate(caps.host.topology.cells):
 3139             cell.mempages = fakelibvirt.create_mempages(
 3140                 [(4, 1024 * i), (2048, i)])
 3141 
 3142         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3143         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3144                                             instance_ref,
 3145                                             image_meta)
 3146 
 3147         with test.nested(
 3148                 mock.patch.object(
 3149                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3150                     return_value=instance_topology),
 3151                 mock.patch.object(host.Host, 'has_min_version',
 3152                                   return_value=True),
 3153                 mock.patch.object(host.Host, "get_capabilities",
 3154                                   return_value=caps),
 3155                 mock.patch.object(
 3156                     hardware, 'get_vcpu_pin_set',
 3157                     return_value=set([2, 3, 4, 5])),
 3158                 mock.patch.object(host.Host, 'get_online_cpus',
 3159                                   return_value=set(range(8))),
 3160                 ):
 3161             cfg = drvr._get_guest_config(instance_ref, [],
 3162                                          image_meta, disk_info)
 3163 
 3164             for instance_cell, numa_cfg_cell, index in zip(
 3165                     instance_topology.cells,
 3166                     cfg.cpu.numa.cells,
 3167                     range(len(instance_topology.cells))):
 3168                 self.assertEqual(index, numa_cfg_cell.id)
 3169                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 3170                 self.assertEqual(instance_cell.memory * units.Ki,
 3171                                  numa_cfg_cell.memory)
 3172                 self.assertEqual("shared", numa_cfg_cell.memAccess)
 3173 
 3174             allnodes = [cell.id for cell in instance_topology.cells]
 3175             self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
 3176             self.assertEqual("strict", cfg.numatune.memory.mode)
 3177 
 3178             for instance_cell, memnode, index in zip(
 3179                     instance_topology.cells,
 3180                     cfg.numatune.memnodes,
 3181                     range(len(instance_topology.cells))):
 3182                 self.assertEqual(index, memnode.cellid)
 3183                 self.assertEqual([instance_cell.id], memnode.nodeset)
 3184                 self.assertEqual("strict", memnode.mode)
 3185 
 3186             self.assertEqual(0, len(cfg.cputune.vcpusched))
 3187             self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
 3188 
 3189     def test_get_guest_config_numa_host_instance_cpu_pinning_realtime(self):
 3190         instance_topology = objects.InstanceNUMATopology(
 3191             cells=[
 3192                 objects.InstanceNUMACell(
 3193                     id=2, cpuset=set([0, 1]),
 3194                     memory=1024, pagesize=2048),
 3195                 objects.InstanceNUMACell(
 3196                     id=3, cpuset=set([2, 3]),
 3197                     memory=1024, pagesize=2048)])
 3198         instance_ref = objects.Instance(**self.test_instance)
 3199         instance_ref.numa_topology = instance_topology
 3200         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3201         flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
 3202                                 ephemeral_gb=8128, swap=33550336, name='fake',
 3203                                 extra_specs={
 3204                                     "hw:cpu_realtime": "yes",
 3205                                     "hw:cpu_policy": "dedicated",
 3206                                     "hw:cpu_realtime_mask": "^0-1"
 3207                                 })
 3208         instance_ref.flavor = flavor
 3209 
 3210         caps = vconfig.LibvirtConfigCaps()
 3211         caps.host = vconfig.LibvirtConfigCapsHost()
 3212         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3213         caps.host.cpu.arch = fields.Architecture.X86_64
 3214         caps.host.topology = fakelibvirt.NUMATopology()
 3215         for i, cell in enumerate(caps.host.topology.cells):
 3216             cell.mempages = fakelibvirt.create_mempages(
 3217                 [(4, 1024 * i), (2048, i)])
 3218 
 3219         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3220         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3221                                             instance_ref,
 3222                                             image_meta)
 3223 
 3224         with test.nested(
 3225                 mock.patch.object(
 3226                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3227                     return_value=instance_topology),
 3228                 mock.patch.object(host.Host, 'has_min_version',
 3229                                   return_value=True),
 3230                 mock.patch.object(host.Host, "get_capabilities",
 3231                                   return_value=caps),
 3232                 mock.patch.object(
 3233                     hardware, 'get_vcpu_pin_set',
 3234                     return_value=set([4, 5, 6, 7])),
 3235                 mock.patch.object(host.Host, 'get_online_cpus',
 3236                                   return_value=set(range(8))),
 3237                 ):
 3238             cfg = drvr._get_guest_config(instance_ref, [],
 3239                                          image_meta, disk_info)
 3240 
 3241             for instance_cell, numa_cfg_cell, index in zip(
 3242                     instance_topology.cells,
 3243                     cfg.cpu.numa.cells,
 3244                     range(len(instance_topology.cells))):
 3245                 self.assertEqual(index, numa_cfg_cell.id)
 3246                 self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
 3247                 self.assertEqual(instance_cell.memory * units.Ki,
 3248                                  numa_cfg_cell.memory)
 3249                 self.assertEqual("shared", numa_cfg_cell.memAccess)
 3250 
 3251             allnodes = [cell.id for cell in instance_topology.cells]
 3252             self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
 3253             self.assertEqual("strict", cfg.numatune.memory.mode)
 3254 
 3255             for instance_cell, memnode, index in zip(
 3256                     instance_topology.cells,
 3257                     cfg.numatune.memnodes,
 3258                     range(len(instance_topology.cells))):
 3259                 self.assertEqual(index, memnode.cellid)
 3260                 self.assertEqual([instance_cell.id], memnode.nodeset)
 3261                 self.assertEqual("strict", memnode.mode)
 3262 
 3263             self.assertEqual(1, len(cfg.cputune.vcpusched))
 3264             self.assertEqual("fifo", cfg.cputune.vcpusched[0].scheduler)
 3265 
 3266             # Ensure vCPUs 0-1 are pinned on host CPUs 4-5 and 2-3 are
 3267             # set on host CPUs 6-7 according the realtime mask ^0-1
 3268             self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[0].cpuset)
 3269             self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[1].cpuset)
 3270             self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[2].cpuset)
 3271             self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[3].cpuset)
 3272 
 3273             # We ensure that emulator threads are pinned on host CPUs
 3274             # 4-5 which are "normal" vCPUs
 3275             self.assertEqual(set([4, 5]), cfg.cputune.emulatorpin.cpuset)
 3276 
 3277             # We ensure that the vCPUs RT are 2-3 set to the host CPUs
 3278             # which are 6, 7
 3279             self.assertEqual(set([2, 3]), cfg.cputune.vcpusched[0].vcpus)
 3280 
 3281     def test_get_guest_config_numa_host_instance_isolated_emulthreads(self):
 3282         instance_topology = objects.InstanceNUMATopology(
 3283             emulator_threads_policy=(
 3284                 fields.CPUEmulatorThreadsPolicy.ISOLATE),
 3285             cells=[
 3286                 objects.InstanceNUMACell(
 3287                     id=0, cpuset=set([0, 1]),
 3288                     memory=1024, pagesize=2048,
 3289                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3290                     cpu_pinning={0: 4, 1: 5},
 3291                     cpuset_reserved=set([6])),
 3292                 objects.InstanceNUMACell(
 3293                     id=1, cpuset=set([2, 3]),
 3294                     memory=1024, pagesize=2048,
 3295                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3296                     cpu_pinning={2: 7, 3: 8})])
 3297 
 3298         instance_ref = objects.Instance(**self.test_instance)
 3299         instance_ref.numa_topology = instance_topology
 3300         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3301 
 3302         caps = vconfig.LibvirtConfigCaps()
 3303         caps.host = vconfig.LibvirtConfigCapsHost()
 3304         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3305         caps.host.cpu.arch = "x86_64"
 3306         caps.host.topology = fakelibvirt.NUMATopology()
 3307 
 3308         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3309         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3310                                             instance_ref, image_meta)
 3311 
 3312         with test.nested(
 3313                 mock.patch.object(
 3314                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3315                     return_value=instance_topology),
 3316                 mock.patch.object(host.Host, 'has_min_version',
 3317                                   return_value=True),
 3318                 mock.patch.object(host.Host, "get_capabilities",
 3319                                   return_value=caps),
 3320                 mock.patch.object(
 3321                     hardware, 'get_vcpu_pin_set',
 3322                     return_value=set([4, 5, 6, 7, 8])),
 3323                 mock.patch.object(host.Host, 'get_online_cpus',
 3324                                   return_value=set(range(10))),
 3325                 ):
 3326             cfg = drvr._get_guest_config(instance_ref, [],
 3327                                          image_meta, disk_info)
 3328 
 3329             self.assertEqual(set([6]), cfg.cputune.emulatorpin.cpuset)
 3330             self.assertEqual(set([4]), cfg.cputune.vcpupin[0].cpuset)
 3331             self.assertEqual(set([5]), cfg.cputune.vcpupin[1].cpuset)
 3332             self.assertEqual(set([7]), cfg.cputune.vcpupin[2].cpuset)
 3333             self.assertEqual(set([8]), cfg.cputune.vcpupin[3].cpuset)
 3334 
 3335     def test_get_guest_config_numa_host_instance_shared_emulthreads_err(
 3336             self):
 3337         self.flags(cpu_shared_set="48-50", group="compute")
 3338         instance_topology = objects.InstanceNUMATopology(
 3339             emulator_threads_policy=(
 3340                 fields.CPUEmulatorThreadsPolicy.SHARE),
 3341             cells=[
 3342                 objects.InstanceNUMACell(
 3343                     id=0, cpuset=set([0, 1]),
 3344                     memory=1024, pagesize=2048,
 3345                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3346                     cpu_pinning={0: 4, 1: 5},
 3347                     cpuset_reserved=set([6])),
 3348                 objects.InstanceNUMACell(
 3349                     id=1, cpuset=set([2, 3]),
 3350                     memory=1024, pagesize=2048,
 3351                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3352                     cpu_pinning={2: 7, 3: 8})])
 3353 
 3354         instance_ref = objects.Instance(**self.test_instance)
 3355         instance_ref.numa_topology = instance_topology
 3356         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3357 
 3358         caps = vconfig.LibvirtConfigCaps()
 3359         caps.host = vconfig.LibvirtConfigCapsHost()
 3360         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3361         caps.host.cpu.arch = "x86_64"
 3362         caps.host.topology = fakelibvirt.NUMATopology()
 3363 
 3364         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3365         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3366                                             instance_ref, image_meta)
 3367 
 3368         with test.nested(
 3369                 mock.patch.object(
 3370                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3371                     return_value=instance_topology),
 3372                 mock.patch.object(host.Host, 'has_min_version',
 3373                                   return_value=True),
 3374                 mock.patch.object(host.Host, "get_capabilities",
 3375                                   return_value=caps),
 3376                 mock.patch.object(
 3377                     hardware, 'get_vcpu_pin_set',
 3378                     return_value=set([4, 5, 6, 7, 8])),
 3379                 mock.patch.object(host.Host, 'get_online_cpus',
 3380                                   return_value=set(range(10))),
 3381                 ):
 3382             # pCPUs [48-50] are not online
 3383             self.assertRaises(exception.Invalid, drvr._get_guest_config,
 3384                               instance_ref, [], image_meta, disk_info)
 3385 
 3386     def test_get_guest_config_numa_host_instance_shared_emulator_threads(
 3387             self):
 3388         self.flags(cpu_shared_set="48-50", group="compute")
 3389         instance_topology = objects.InstanceNUMATopology(
 3390             emulator_threads_policy=(
 3391                 fields.CPUEmulatorThreadsPolicy.SHARE),
 3392             cells=[
 3393                 objects.InstanceNUMACell(
 3394                     id=0, cpuset=set([0, 1]),
 3395                     memory=1024, pagesize=2048,
 3396                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3397                     cpu_pinning={0: 4, 1: 5},
 3398                     cpuset_reserved=set([6])),
 3399                 objects.InstanceNUMACell(
 3400                     id=1, cpuset=set([2, 3]),
 3401                     memory=1024, pagesize=2048,
 3402                     cpu_policy=fields.CPUAllocationPolicy.DEDICATED,
 3403                     cpu_pinning={2: 7, 3: 8})])
 3404 
 3405         instance_ref = objects.Instance(**self.test_instance)
 3406         instance_ref.numa_topology = instance_topology
 3407         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3408 
 3409         caps = vconfig.LibvirtConfigCaps()
 3410         caps.host = vconfig.LibvirtConfigCapsHost()
 3411         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3412         caps.host.cpu.arch = "x86_64"
 3413         caps.host.topology = fakelibvirt.NUMATopology()
 3414 
 3415         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3416         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3417                                             instance_ref, image_meta)
 3418 
 3419         with test.nested(
 3420                 mock.patch.object(
 3421                     objects.InstanceNUMATopology, "get_by_instance_uuid",
 3422                     return_value=instance_topology),
 3423                 mock.patch.object(host.Host, 'has_min_version',
 3424                                   return_value=True),
 3425                 mock.patch.object(host.Host, "get_capabilities",
 3426                                   return_value=caps),
 3427                 mock.patch.object(
 3428                     hardware, 'get_vcpu_pin_set',
 3429                     return_value=set([4, 5, 6, 7, 8])),
 3430                 mock.patch.object(host.Host, 'get_online_cpus',
 3431                                   return_value=set(list(range(10)) +
 3432                                                    [48, 50])),
 3433                 ):
 3434             cfg = drvr._get_guest_config(instance_ref, [],
 3435                                          image_meta, disk_info)
 3436 
 3437             # cpu_shared_set is configured with [48, 49, 50] but only
 3438             # [48, 50] are online.
 3439             self.assertEqual(set([48, 50]), cfg.cputune.emulatorpin.cpuset)
 3440             self.assertEqual(set([4]), cfg.cputune.vcpupin[0].cpuset)
 3441             self.assertEqual(set([5]), cfg.cputune.vcpupin[1].cpuset)
 3442             self.assertEqual(set([7]), cfg.cputune.vcpupin[2].cpuset)
 3443             self.assertEqual(set([8]), cfg.cputune.vcpupin[3].cpuset)
 3444 
 3445     def test_get_cpu_numa_config_from_instance(self):
 3446         topology = objects.InstanceNUMATopology(cells=[
 3447             objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
 3448             objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
 3449         ])
 3450         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3451         conf = drvr._get_cpu_numa_config_from_instance(topology, True)
 3452 
 3453         self.assertIsInstance(conf, vconfig.LibvirtConfigGuestCPUNUMA)
 3454         self.assertEqual(0, conf.cells[0].id)
 3455         self.assertEqual(set([1, 2]), conf.cells[0].cpus)
 3456         self.assertEqual(131072, conf.cells[0].memory)
 3457         self.assertEqual("shared", conf.cells[0].memAccess)
 3458         self.assertEqual(1, conf.cells[1].id)
 3459         self.assertEqual(set([3, 4]), conf.cells[1].cpus)
 3460         self.assertEqual(131072, conf.cells[1].memory)
 3461         self.assertEqual("shared", conf.cells[1].memAccess)
 3462 
 3463     def test_get_cpu_numa_config_from_instance_none(self):
 3464         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3465         conf = drvr._get_cpu_numa_config_from_instance(None, False)
 3466         self.assertIsNone(conf)
 3467 
 3468     @mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
 3469                        return_value=True)
 3470     def test_get_memnode_numa_config_from_instance(self, mock_numa):
 3471         instance_topology = objects.InstanceNUMATopology(cells=[
 3472             objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
 3473             objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
 3474             objects.InstanceNUMACell(id=16, cpuset=set([5, 6]), memory=128)
 3475         ])
 3476 
 3477         host_topology = objects.NUMATopology(
 3478             cells=[
 3479                 objects.NUMACell(
 3480                     id=0, cpuset=set([1, 2]), siblings=[set([1]), set([2])],
 3481                     memory=1024, mempages=[]),
 3482                 objects.NUMACell(
 3483                     id=1, cpuset=set([3, 4]), siblings=[set([3]), set([4])],
 3484                     memory=1024, mempages=[]),
 3485                 objects.NUMACell(
 3486                     id=16, cpuset=set([5, 6]), siblings=[set([5]), set([6])],
 3487                     memory=1024, mempages=[])])
 3488 
 3489         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3490         with test.nested(
 3491                 mock.patch.object(drvr, "_get_host_numa_topology",
 3492                                   return_value=host_topology)):
 3493             guest_numa_config = drvr._get_guest_numa_config(instance_topology,
 3494                 flavor={}, allowed_cpus=[1, 2, 3, 4, 5, 6], image_meta={})
 3495             self.assertEqual(2, guest_numa_config.numatune.memnodes[2].cellid)
 3496             self.assertEqual([16],
 3497                 guest_numa_config.numatune.memnodes[2].nodeset)
 3498             self.assertEqual(set([5, 6]),
 3499                 guest_numa_config.numaconfig.cells[2].cpus)
 3500 
 3501     @mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
 3502                        return_value=True)
 3503     @mock.patch.object(host.Host, "get_capabilities")
 3504     def test_does_not_want_hugepages(self, mock_caps, mock_numa):
 3505         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3506         instance_topology = objects.InstanceNUMATopology(
 3507             cells=[
 3508                 objects.InstanceNUMACell(
 3509                     id=1, cpuset=set([0, 1]),
 3510                     memory=1024, pagesize=4),
 3511                 objects.InstanceNUMACell(
 3512                     id=2, cpuset=set([2, 3]),
 3513                     memory=1024, pagesize=4)])
 3514 
 3515         caps = vconfig.LibvirtConfigCaps()
 3516         caps.host = vconfig.LibvirtConfigCapsHost()
 3517         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3518         caps.host.cpu.arch = fields.Architecture.X86_64
 3519         caps.host.topology = fakelibvirt.NUMATopology()
 3520 
 3521         mock_caps.return_value = caps
 3522 
 3523         host_topology = drvr._get_host_numa_topology()
 3524 
 3525         self.assertFalse(drvr._wants_hugepages(None, None))
 3526         self.assertFalse(drvr._wants_hugepages(host_topology, None))
 3527         self.assertFalse(drvr._wants_hugepages(None, instance_topology))
 3528         self.assertFalse(drvr._wants_hugepages(host_topology,
 3529                                                instance_topology))
 3530 
 3531     @mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
 3532                        return_value=True)
 3533     @mock.patch.object(host.Host, "get_capabilities")
 3534     def test_does_want_hugepages(self, mock_caps, mock_numa):
 3535         for arch in [fields.Architecture.I686,
 3536                      fields.Architecture.X86_64,
 3537                      fields.Architecture.AARCH64,
 3538                      fields.Architecture.PPC64LE,
 3539                      fields.Architecture.PPC64]:
 3540             self._test_does_want_hugepages(mock_caps, mock_numa, arch)
 3541 
 3542     def _test_does_want_hugepages(self, mock_caps, mock_numa, architecture):
 3543         self.flags(reserved_huge_pages=[
 3544             {'node': 0, 'size': 2048, 'count': 128},
 3545             {'node': 1, 'size': 2048, 'count': 1},
 3546             {'node': 3, 'size': 2048, 'count': 64}])
 3547         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3548         instance_topology = objects.InstanceNUMATopology(
 3549             cells=[
 3550                 objects.InstanceNUMACell(
 3551                     id=1, cpuset=set([0, 1]),
 3552                     memory=1024, pagesize=2048),
 3553                 objects.InstanceNUMACell(
 3554                     id=2, cpuset=set([2, 3]),
 3555                     memory=1024, pagesize=2048)])
 3556 
 3557         caps = vconfig.LibvirtConfigCaps()
 3558         caps.host = vconfig.LibvirtConfigCapsHost()
 3559         caps.host.cpu = vconfig.LibvirtConfigCPU()
 3560         caps.host.cpu.arch = architecture
 3561         caps.host.topology = fakelibvirt.NUMATopology()
 3562         for i, cell in enumerate(caps.host.topology.cells):
 3563             cell.mempages = fakelibvirt.create_mempages(
 3564                 [(4, 1024 * i), (2048, i)])
 3565 
 3566         mock_caps.return_value = caps
 3567 
 3568         host_topology = drvr._get_host_numa_topology()
 3569         self.assertEqual(128, host_topology.cells[0].mempages[1].reserved)
 3570         self.assertEqual(1, host_topology.cells[1].mempages[1].reserved)
 3571         self.assertEqual(0, host_topology.cells[2].mempages[1].reserved)
 3572         self.assertEqual(64, host_topology.cells[3].mempages[1].reserved)
 3573 
 3574         self.assertTrue(drvr._wants_hugepages(host_topology,
 3575                                               instance_topology))
 3576 
 3577     def test_get_guest_config_clock(self):
 3578         self.flags(virt_type='kvm', group='libvirt')
 3579         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3580         instance_ref = objects.Instance(**self.test_instance)
 3581         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3582         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3583                                             instance_ref,
 3584                                             image_meta)
 3585         hpet_map = {
 3586             fields.Architecture.X86_64: True,
 3587             fields.Architecture.I686: True,
 3588             fields.Architecture.PPC: False,
 3589             fields.Architecture.PPC64: False,
 3590             fields.Architecture.ARMV7: False,
 3591             fields.Architecture.AARCH64: False,
 3592             }
 3593 
 3594         for guestarch, expect_hpet in hpet_map.items():
 3595             with mock.patch.object(libvirt_driver.libvirt_utils,
 3596                                    'get_arch',
 3597                                    return_value=guestarch):
 3598                 cfg = drvr._get_guest_config(instance_ref, [],
 3599                                              image_meta,
 3600                                              disk_info)
 3601                 self.assertIsInstance(cfg.clock,
 3602                                       vconfig.LibvirtConfigGuestClock)
 3603                 self.assertEqual(cfg.clock.offset, "utc")
 3604                 self.assertIsInstance(cfg.clock.timers[0],
 3605                                       vconfig.LibvirtConfigGuestTimer)
 3606                 self.assertIsInstance(cfg.clock.timers[1],
 3607                                       vconfig.LibvirtConfigGuestTimer)
 3608                 self.assertEqual(cfg.clock.timers[0].name, "pit")
 3609                 self.assertEqual(cfg.clock.timers[0].tickpolicy,
 3610                                       "delay")
 3611                 self.assertEqual(cfg.clock.timers[1].name, "rtc")
 3612                 self.assertEqual(cfg.clock.timers[1].tickpolicy,
 3613                                       "catchup")
 3614                 if expect_hpet:
 3615                     self.assertEqual(3, len(cfg.clock.timers))
 3616                     self.assertIsInstance(cfg.clock.timers[2],
 3617                                           vconfig.LibvirtConfigGuestTimer)
 3618                     self.assertEqual('hpet', cfg.clock.timers[2].name)
 3619                     self.assertFalse(cfg.clock.timers[2].present)
 3620                 else:
 3621                     self.assertEqual(2, len(cfg.clock.timers))
 3622 
 3623     @mock.patch.object(libvirt_utils, 'get_arch')
 3624     def test_get_guest_config_windows_timer(self, mock_get_arch):
 3625         mock_get_arch.return_value = fields.Architecture.I686
 3626         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3627         instance_ref = objects.Instance(**self.test_instance)
 3628         instance_ref['os_type'] = 'windows'
 3629         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3630 
 3631         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3632                                             instance_ref,
 3633                                             image_meta)
 3634         cfg = drvr._get_guest_config(instance_ref,
 3635                                      _fake_network_info(self, 1),
 3636                                      image_meta, disk_info)
 3637 
 3638         self.assertIsInstance(cfg.clock,
 3639                               vconfig.LibvirtConfigGuestClock)
 3640         self.assertEqual(cfg.clock.offset, "localtime")
 3641 
 3642         self.assertEqual(4, len(cfg.clock.timers), cfg.clock.timers)
 3643         self.assertEqual("pit", cfg.clock.timers[0].name)
 3644         self.assertEqual("rtc", cfg.clock.timers[1].name)
 3645         self.assertEqual("hpet", cfg.clock.timers[2].name)
 3646         self.assertFalse(cfg.clock.timers[2].present)
 3647         self.assertEqual("hypervclock", cfg.clock.timers[3].name)
 3648         self.assertTrue(cfg.clock.timers[3].present)
 3649 
 3650         self.assertEqual(3, len(cfg.features))
 3651         self.assertIsInstance(cfg.features[0],
 3652                               vconfig.LibvirtConfigGuestFeatureACPI)
 3653         self.assertIsInstance(cfg.features[1],
 3654                               vconfig.LibvirtConfigGuestFeatureAPIC)
 3655         self.assertIsInstance(cfg.features[2],
 3656                               vconfig.LibvirtConfigGuestFeatureHyperV)
 3657 
 3658     @mock.patch.object(host.Host, 'has_min_version')
 3659     def test_get_guest_config_windows_hyperv_feature2(self, mock_version):
 3660         mock_version.return_value = True
 3661         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3662         instance_ref = objects.Instance(**self.test_instance)
 3663         instance_ref['os_type'] = 'windows'
 3664         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3665 
 3666         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3667                                             instance_ref,
 3668                                             image_meta)
 3669         cfg = drvr._get_guest_config(instance_ref,
 3670                                      _fake_network_info(self, 1),
 3671                                      image_meta, disk_info)
 3672 
 3673         self.assertIsInstance(cfg.clock,
 3674                               vconfig.LibvirtConfigGuestClock)
 3675         self.assertEqual(cfg.clock.offset, "localtime")
 3676 
 3677         self.assertEqual(3, len(cfg.features))
 3678         self.assertIsInstance(cfg.features[0],
 3679                               vconfig.LibvirtConfigGuestFeatureACPI)
 3680         self.assertIsInstance(cfg.features[1],
 3681                               vconfig.LibvirtConfigGuestFeatureAPIC)
 3682         self.assertIsInstance(cfg.features[2],
 3683                               vconfig.LibvirtConfigGuestFeatureHyperV)
 3684 
 3685         self.assertTrue(cfg.features[2].relaxed)
 3686         self.assertTrue(cfg.features[2].spinlocks)
 3687         self.assertEqual(8191, cfg.features[2].spinlock_retries)
 3688         self.assertTrue(cfg.features[2].vapic)
 3689 
 3690     def test_get_guest_config_with_two_nics(self):
 3691         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3692         instance_ref = objects.Instance(**self.test_instance)
 3693         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3694 
 3695         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3696                                             instance_ref,
 3697                                             image_meta)
 3698         cfg = drvr._get_guest_config(instance_ref,
 3699                                      _fake_network_info(self, 2),
 3700                                      image_meta, disk_info)
 3701         self.assertEqual(2, len(cfg.features))
 3702         self.assertIsInstance(cfg.features[0],
 3703                               vconfig.LibvirtConfigGuestFeatureACPI)
 3704         self.assertIsInstance(cfg.features[1],
 3705                               vconfig.LibvirtConfigGuestFeatureAPIC)
 3706         self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
 3707         self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
 3708         self.assertEqual(cfg.os_type, fields.VMMode.HVM)
 3709         self.assertEqual(cfg.os_boot_dev, ["hd"])
 3710         self.assertIsNone(cfg.os_root)
 3711         self.assertEqual(len(cfg.devices), 10)
 3712         self.assertIsInstance(cfg.devices[0],
 3713                               vconfig.LibvirtConfigGuestDisk)
 3714         self.assertIsInstance(cfg.devices[1],
 3715                               vconfig.LibvirtConfigGuestDisk)
 3716         self.assertIsInstance(cfg.devices[2],
 3717                               vconfig.LibvirtConfigGuestInterface)
 3718         self.assertIsInstance(cfg.devices[3],
 3719                               vconfig.LibvirtConfigGuestInterface)
 3720         self.assertIsInstance(cfg.devices[4],
 3721                               vconfig.LibvirtConfigGuestSerial)
 3722         self.assertIsInstance(cfg.devices[5],
 3723                               vconfig.LibvirtConfigGuestSerial)
 3724         self.assertIsInstance(cfg.devices[6],
 3725                               vconfig.LibvirtConfigGuestInput)
 3726         self.assertIsInstance(cfg.devices[7],
 3727                               vconfig.LibvirtConfigGuestGraphics)
 3728         self.assertIsInstance(cfg.devices[8],
 3729                               vconfig.LibvirtConfigGuestVideo)
 3730         self.assertIsInstance(cfg.devices[9],
 3731                               vconfig.LibvirtConfigMemoryBalloon)
 3732 
 3733     def test_get_guest_config_bug_1118829(self):
 3734         self.flags(virt_type='uml', group='libvirt')
 3735         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3736         instance_ref = objects.Instance(**self.test_instance)
 3737 
 3738         disk_info = {'disk_bus': 'virtio',
 3739                      'cdrom_bus': 'ide',
 3740                      'mapping': {u'vda': {'bus': 'virtio',
 3741                                           'type': 'disk',
 3742                                           'dev': u'vda'},
 3743                                  'root': {'bus': 'virtio',
 3744                                           'type': 'disk',
 3745                                           'dev': 'vda'}}}
 3746 
 3747         # NOTE(jdg): For this specific test leave this blank
 3748         # This will exercise the failed code path still,
 3749         # and won't require fakes and stubs of the iscsi discovery
 3750         block_device_info = {}
 3751         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3752         drvr._get_guest_config(instance_ref, [], image_meta, disk_info,
 3753                                None, block_device_info)
 3754         self.assertEqual(instance_ref['root_device_name'], '/dev/vda')
 3755 
 3756     def test_get_guest_config_with_root_device_name(self):
 3757         self.flags(virt_type='uml', group='libvirt')
 3758         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3759         instance_ref = objects.Instance(**self.test_instance)
 3760         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3761 
 3762         block_device_info = {'root_device_name': '/dev/vdb'}
 3763         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3764                                             instance_ref,
 3765                                             image_meta,
 3766                                             block_device_info)
 3767         cfg = drvr._get_guest_config(instance_ref, [],
 3768                                      image_meta, disk_info,
 3769                                      None, block_device_info)
 3770         self.assertEqual(0, len(cfg.features))
 3771         self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
 3772         self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
 3773         self.assertEqual(cfg.os_type, "uml")
 3774         self.assertEqual(cfg.os_boot_dev, [])
 3775         self.assertEqual(cfg.os_root, '/dev/vdb')
 3776         self.assertEqual(len(cfg.devices), 3)
 3777         self.assertIsInstance(cfg.devices[0],
 3778                               vconfig.LibvirtConfigGuestDisk)
 3779         self.assertIsInstance(cfg.devices[1],
 3780                               vconfig.LibvirtConfigGuestDisk)
 3781         self.assertIsInstance(cfg.devices[2],
 3782                               vconfig.LibvirtConfigGuestConsole)
 3783 
 3784     def test_has_uefi_support_not_supported_arch(self):
 3785         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3786         self._stub_host_capabilities_cpu_arch(fields.Architecture.ALPHA)
 3787         self.assertFalse(drvr._has_uefi_support())
 3788 
 3789     @mock.patch('os.path.exists', return_value=False)
 3790     def test_has_uefi_support_with_no_loader_existed(self, mock_exist):
 3791         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3792         self.assertFalse(drvr._has_uefi_support())
 3793 
 3794     @mock.patch('os.path.exists', return_value=True)
 3795     def test_has_uefi_support(self, mock_has_version):
 3796         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3797 
 3798         self._stub_host_capabilities_cpu_arch(fields.Architecture.X86_64)
 3799 
 3800         with mock.patch.object(drvr._host,
 3801                                'has_min_version', return_value=True):
 3802             self.assertTrue(drvr._has_uefi_support())
 3803 
 3804     def test_get_guest_config_with_uefi(self):
 3805         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3806 
 3807         image_meta = objects.ImageMeta.from_dict({
 3808             "disk_format": "raw",
 3809             "properties": {"hw_firmware_type": "uefi"}})
 3810         instance_ref = objects.Instance(**self.test_instance)
 3811 
 3812         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3813                                             instance_ref,
 3814                                             image_meta)
 3815         with mock.patch.object(drvr, "_has_uefi_support",
 3816                                return_value=True) as mock_support:
 3817             cfg = drvr._get_guest_config(instance_ref, [],
 3818                                          image_meta, disk_info)
 3819             mock_support.assert_called_once_with()
 3820             self.assertEqual(cfg.os_loader_type, "pflash")
 3821 
 3822     def test_get_guest_config_with_block_device(self):
 3823         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3824 
 3825         instance_ref = objects.Instance(**self.test_instance)
 3826         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3827         conn_info = {'driver_volume_type': 'fake', 'data': {}}
 3828         bdms = block_device_obj.block_device_make_list_from_dicts(
 3829             self.context, [
 3830                 fake_block_device.FakeDbBlockDeviceDict(
 3831                     {'id': 1,
 3832                      'source_type': 'volume', 'destination_type': 'volume',
 3833                      'device_name': '/dev/vdc'}),
 3834                 fake_block_device.FakeDbBlockDeviceDict(
 3835                     {'id': 2,
 3836                      'source_type': 'volume', 'destination_type': 'volume',
 3837                      'device_name': '/dev/vdd'}),
 3838             ]
 3839         )
 3840         info = {'block_device_mapping': driver_block_device.convert_volumes(
 3841             bdms
 3842         )}
 3843         info['block_device_mapping'][0]['connection_info'] = conn_info
 3844         info['block_device_mapping'][1]['connection_info'] = conn_info
 3845 
 3846         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3847                                             instance_ref,
 3848                                             image_meta,
 3849                                             info)
 3850         with mock.patch.object(
 3851                 driver_block_device.DriverVolumeBlockDevice, 'save'
 3852         ) as mock_save:
 3853             cfg = drvr._get_guest_config(instance_ref, [],
 3854                                          image_meta, disk_info,
 3855                                          None, info)
 3856             self.assertIsInstance(cfg.devices[2],
 3857                                   vconfig.LibvirtConfigGuestDisk)
 3858             self.assertEqual(cfg.devices[2].target_dev, 'vdc')
 3859             self.assertIsInstance(cfg.devices[3],
 3860                                   vconfig.LibvirtConfigGuestDisk)
 3861             self.assertEqual(cfg.devices[3].target_dev, 'vdd')
 3862             mock_save.assert_called_with()
 3863 
 3864     def test_get_guest_config_lxc_with_attached_volume(self):
 3865         self.flags(virt_type='lxc', group='libvirt')
 3866         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3867 
 3868         instance_ref = objects.Instance(**self.test_instance)
 3869         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3870         conn_info = {'driver_volume_type': 'fake', 'data': {}}
 3871         bdms = block_device_obj.block_device_make_list_from_dicts(
 3872             self.context, [
 3873               fake_block_device.FakeDbBlockDeviceDict(
 3874                     {'id': 1,
 3875                      'source_type': 'volume', 'destination_type': 'volume',
 3876                      'boot_index': 0}),
 3877               fake_block_device.FakeDbBlockDeviceDict(
 3878                     {'id': 2,
 3879                      'source_type': 'volume', 'destination_type': 'volume',
 3880                     }),
 3881               fake_block_device.FakeDbBlockDeviceDict(
 3882                     {'id': 3,
 3883                      'source_type': 'volume', 'destination_type': 'volume',
 3884                     }),
 3885            ]
 3886         )
 3887         info = {'block_device_mapping': driver_block_device.convert_volumes(
 3888             bdms
 3889         )}
 3890 
 3891         info['block_device_mapping'][0]['connection_info'] = conn_info
 3892         info['block_device_mapping'][1]['connection_info'] = conn_info
 3893         info['block_device_mapping'][2]['connection_info'] = conn_info
 3894         info['block_device_mapping'][0]['mount_device'] = '/dev/vda'
 3895         info['block_device_mapping'][1]['mount_device'] = '/dev/vdc'
 3896         info['block_device_mapping'][2]['mount_device'] = '/dev/vdd'
 3897         with mock.patch.object(
 3898                 driver_block_device.DriverVolumeBlockDevice, 'save'
 3899         ) as mock_save:
 3900             disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3901                                                 instance_ref,
 3902                                                 image_meta,
 3903                                                 info)
 3904             cfg = drvr._get_guest_config(instance_ref, [],
 3905                                          image_meta, disk_info,
 3906                                          None, info)
 3907             self.assertIsInstance(cfg.devices[1],
 3908                                   vconfig.LibvirtConfigGuestDisk)
 3909             self.assertEqual(cfg.devices[1].target_dev, 'vdc')
 3910             self.assertIsInstance(cfg.devices[2],
 3911                                   vconfig.LibvirtConfigGuestDisk)
 3912             self.assertEqual(cfg.devices[2].target_dev, 'vdd')
 3913             mock_save.assert_called_with()
 3914 
 3915     def test_get_guest_config_with_configdrive(self):
 3916         # It's necessary to check if the architecture is power, because
 3917         # power doesn't have support to ide, and so libvirt translate
 3918         # all ide calls to scsi
 3919 
 3920         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3921         instance_ref = objects.Instance(**self.test_instance)
 3922         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 3923 
 3924         # make configdrive.required_by() return True
 3925         instance_ref['config_drive'] = True
 3926 
 3927         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3928                                             instance_ref,
 3929                                             image_meta)
 3930         cfg = drvr._get_guest_config(instance_ref, [],
 3931                                      image_meta, disk_info)
 3932 
 3933         # Pick the first drive letter on the bus that is available
 3934         # as the config drive. Delete the last device hardcode as
 3935         # the config drive here.
 3936 
 3937         expect = {"ppc": "sda", "ppc64": "sda",
 3938                     "ppc64le": "sda", "aarch64": "sda"}
 3939         disk = expect.get(blockinfo.libvirt_utils.get_arch({}), "hda")
 3940         self.assertIsInstance(cfg.devices[2],
 3941                               vconfig.LibvirtConfigGuestDisk)
 3942         self.assertEqual(cfg.devices[2].target_dev, disk)
 3943 
 3944     def test_get_guest_config_default_with_virtio_scsi_bus(self):
 3945         self._test_get_guest_config_with_virtio_scsi_bus()
 3946 
 3947     @mock.patch.object(rbd_utils.RBDDriver, 'get_mon_addrs')
 3948     @mock.patch.object(rbd_utils, 'rbd')
 3949     def test_get_guest_config_rbd_with_virtio_scsi_bus(
 3950             self, mock_rdb, mock_get_mon_addrs):
 3951         self.flags(images_type='rbd', group='libvirt')
 3952         mock_get_mon_addrs.return_value = ("host", 9876)
 3953         self._test_get_guest_config_with_virtio_scsi_bus()
 3954 
 3955     def _test_get_guest_config_with_virtio_scsi_bus(self):
 3956         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3957 
 3958         image_meta = objects.ImageMeta.from_dict({
 3959             "disk_format": "raw",
 3960             "properties": {"hw_scsi_model": "virtio-scsi",
 3961                            "hw_disk_bus": "scsi"}})
 3962         instance_ref = objects.Instance(**self.test_instance)
 3963 
 3964         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 3965                                             instance_ref,
 3966                                             image_meta,
 3967                                             [])
 3968         cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
 3969         self.assertIsInstance(cfg.devices[0],
 3970                          vconfig.LibvirtConfigGuestDisk)
 3971         self.assertEqual(0, cfg.devices[0].device_addr.unit)
 3972         self.assertIsInstance(cfg.devices[1],
 3973                          vconfig.LibvirtConfigGuestDisk)
 3974         self.assertEqual(1, cfg.devices[1].device_addr.unit)
 3975         self.assertIsInstance(cfg.devices[2],
 3976                          vconfig.LibvirtConfigGuestController)
 3977         self.assertEqual(cfg.devices[2].model, 'virtio-scsi')
 3978 
 3979     def test_get_guest_config_with_virtio_scsi_bus_bdm(self):
 3980         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 3981 
 3982         image_meta = objects.ImageMeta.from_dict({
 3983             "disk_format": "raw",
 3984             "properties": {"hw_scsi_model": "virtio-scsi",
 3985                            "hw_disk_bus": "scsi"}})
 3986         instance_ref = objects.Instance(**self.test_instance)
 3987         conn_info = {'driver_volume_type': 'fake', 'data': {}}
 3988         bdms = block_device_obj.block_device_make_list_from_dicts(
 3989             self.context, [
 3990                 fake_block_device.FakeDbBlockDeviceDict(
 3991                     {'id': 1,
 3992                      'source_type': 'volume', 'destination_type': 'volume',
 3993                      'device_name': '/dev/sdc', 'disk_bus': 'scsi'}),
 3994                 fake_block_device.FakeDbBlockDeviceDict(
 3995                     {'id': 2,
 3996                      'source_type': 'volume', 'destination_type': 'volume',
 3997                      'device_name': '/dev/sdd', 'disk_bus': 'scsi'}),
 3998                 ]
 3999         )
 4000         bd_info = {
 4001             'block_device_mapping': driver_block_device.convert_volumes(bdms)}
 4002         bd_info['block_device_mapping'][0]['connection_info'] = conn_info
 4003         bd_info['block_device_mapping'][1]['connection_info'] = conn_info
 4004 
 4005         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 4006                                             instance_ref,
 4007                                             image_meta,
 4008                                             bd_info)
 4009         with mock.patch.object(
 4010                 driver_block_device.DriverVolumeBlockDevice, 'save'
 4011         ) as mock_save:
 4012             cfg = drvr._get_guest_config(instance_ref, [], image_meta,
 4013                     disk_info, [], bd_info)
 4014             self.assertIsInstance(cfg.devices[2],
 4015                              vconfig.LibvirtConfigGuestDisk)
 4016             self.assertEqual(cfg.devices[2].target_dev, 'sdc')
 4017             self.assertEqual(cfg.devices[2].target_bus, 'scsi')
 4018             self.assertEqual(2, cfg.devices[2].device_addr.unit)
 4019             self.assertIsInstance(cfg.devices[3],
 4020                              vconfig.LibvirtConfigGuestDisk)
 4021             self.assertEqual(cfg.devices[3].target_dev, 'sdd')
 4022             self.assertEqual(cfg.devices[3].target_bus, 'scsi')
 4023             self.assertEqual(3, cfg.devices[3].device_addr.unit)
 4024             self.assertIsInstance(cfg.devices[4],
 4025                              vconfig.LibvirtConfigGuestController)
 4026             self.assertEqual(cfg.devices[4].model, 'virtio-scsi')
 4027             mock_save.assert_called_with()
 4028 
 4029     def test_get_guest_config_one_scsi_volume_with_configdrive(self):
 4030         """Tests that the unit attribute is only incremented for block devices
 4031         that have a scsi bus. Unit numbering should begin at 0 since we are not
 4032         booting from volume.
 4033         """
 4034         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 4035 
 4036         image_meta = objects.ImageMeta.from_dict({
 4037             "disk_format": "raw",
 4038             "properties": {"hw_scsi_model": "virtio-scsi",
 4039                            "hw_disk_bus": "scsi"}})
 4040         instance_ref = objects.Instance(**self.test_instance)
 4041         instance_ref.config_drive = 'True'
 4042         conn_info = {'driver_volume_type': 'fake'}
 4043         bdms = block_device_obj.block_device_make_list_from_dicts(
 4044             self.context, [
 4045                 fake_block_device.FakeDbBlockDeviceDict(
 4046                     {'id': 1,
 4047                      'source_type': 'volume', 'destination_type': 'volume',
 4048                      'device_name': '/dev/sdc', 'disk_bus': 'scsi'}),
 4049                 ]
 4050         )
 4051         bd_info = {
 4052             'block_device_mapping': driver_block_device.convert_volumes(bdms)}
 4053         bd_info['block_device_mapping'][0]['connection_info'] = conn_info
 4054 
 4055         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 4056                                             instance_ref,
 4057                                             image_meta,
 4058                                             bd_info)
 4059         with mock.patch.object(
 4060                 driver_block_device.DriverVolumeBlockDevice, 'save'):
 4061             cfg = drvr._get_guest_config(instance_ref, [], image_meta,
 4062                     disk_info, [], bd_info)
 4063 
 4064             # The device order is determined by the order that devices are
 4065             # appended in _get_guest_storage_config in the driver.
 4066 
 4067             # The first device will be the instance's local disk (since we're
 4068             # not booting from volume). It should begin unit numbering at 0.
 4069             self.assertIsInstance(cfg.devices[0],
 4070                                   vconfig.LibvirtConfigGuestDisk)
 4071             self.assertIn('disk', cfg.devices[0].source_path)
 4072             self.assertEqual('sda', cfg.devices[0].target_dev)
 4073             self.assertEqual('scsi', cfg.devices[0].target_bus)
 4074             self.assertEqual(0, cfg.devices[0].device_addr.unit)
 4075 
 4076             # The second device will be the ephemeral disk
 4077             # (the flavor in self.test_instance has ephemeral_gb > 0).
 4078             # It should have the next unit number of 1.
 4079             self.assertIsInstance(cfg.devices[1],
 4080                                   vconfig.LibvirtConfigGuestDisk)
 4081             self.assertIn('disk.local', cfg.devices[1].source_path)
 4082             self.assertEqual('sdb', cfg.devices[1].target_dev)
 4083             self.assertEqual('scsi', cfg.devices[1].target_bus)
 4084             self.assertEqual(1, cfg.devices[1].device_addr.unit)
 4085 
 4086             # This is the config drive. It should not have unit number set.
 4087             self.assertIsInstance(cfg.devices[2],
 4088                                   vconfig.LibvirtConfigGuestDisk)
 4089             self.assertIn('disk.config', cfg.devices[2].source_path)
 4090             self.assertEqual('hda', cfg.devices[2].target_dev)
 4091             self.assertEqual('ide', cfg.devices[2].target_bus)
 4092             self.assertIsNone(cfg.devices[2].device_addr)
 4093 
 4094             # And this is the attached volume.
 4095             self.assertIsInstance(cfg.devices[3],
 4096                                   vconfig.LibvirtConfigGuestDisk)
 4097             self.assertEqual('sdc', cfg.devices[3].target_dev)
 4098             self.assertEqual('scsi', cfg.devices[3].target_bus)
 4099             self.assertEqual(2, cfg.devices[3].device_addr.unit)
 4100 
 4101     def test_get_guest_config_boot_from_volume_with_configdrive(self):
 4102         """Tests that the unit attribute is only incremented for block devices
 4103         that have a scsi bus and that the bootable volume in a boot-from-volume
 4104         scenario always has the unit set to 0.
 4105         """
 4106         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 4107 
 4108         image_meta = objects.ImageMeta.from_dict({
 4109             "disk_format": "raw",
 4110             "properties": {"hw_scsi_model": "virtio-scsi",
 4111                            "hw_disk_bus": "scsi"}})
 4112         instance_ref = objects.Instance(**self.test_instance)
 4113         instance_ref.config_drive = 'True'
 4114         conn_info = {'driver_volume_type': 'fake'}
 4115         bdms = block_device_obj.block_device_make_list_from_dicts(
 4116             self.context, [
 4117                 # This is the boot volume (boot_index = 0).
 4118                 fake_block_device.FakeDbBlockDeviceDict(
 4119                     {'id': 1,
 4120                      'source_type': 'volume', 'destination_type': 'volume',
 4121                      'device_name': '/dev/sda', 'boot_index': 0}),
 4122                 # This is just another attached volume.
 4123                 fake_block_device.FakeDbBlockDeviceDict(
 4124                     {'id': 2,
 4125                      'source_type': 'volume', 'destination_type': 'volume',
 4126                      'device_name': '/dev/sdc', 'disk_bus': 'scsi'}),
 4127                 ]
 4128         )
 4129         bd_info = {
 4130             'block_device_mapping': driver_block_device.convert_volumes(bdms)}
 4131         bd_info['block_device_mapping'][0]['connection_info'] = conn_info
 4132         bd_info['block_device_mapping'][1]['connection_info'] = conn_info
 4133 
 4134         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 4135                                             instance_ref,
 4136                                             image_meta,
 4137                                             bd_info)
 4138         with mock.patch.object(
 4139                 driver_block_device.DriverVolumeBlockDevice, 'save'):
 4140             cfg = drvr._get_guest_config(instance_ref, [], image_meta,
 4141                     disk_info, [], bd_info)
 4142 
 4143             # The device order is determined by the order that devices are
 4144             # appended in _get_guest_storage_config in the driver.
 4145 
 4146             # The first device will be the ephemeral disk
 4147             # (the flavor in self.test_instance has ephemeral_gb > 0).
 4148             # It should begin unit numbering at 1 because 0 is reserved for the
 4149             # boot volume for boot-from-volume.
 4150             self.assertIsInstance(cfg.devices[0],
 4151                                   vconfig.LibvirtConfigGuestDisk)
 4152             self.assertIn('disk.local', cfg.devices[0].source_path)
 4153             self.assertEqual('sdb', cfg.devices[0].target_dev)
 4154             self.assertEqual('scsi', cfg.devices[0].target_bus)
 4155             self.assertEqual(1, cfg.devices[0].device_addr.unit)
 4156 
 4157             # The second device will be the config drive. It should not have a
 4158             # unit number set.
 4159             self.assertIsInstance(cfg.devices[1],
 4160                                   vconfig.LibvirtConfigGuestDisk)
 4161             self.assertIn('disk.config', cfg.devices[1].source_path)
 4162             self.assertEqual('hda', cfg.devices[1].target_dev)
 4163             self.assertEqual('ide', cfg.devices[1].target_bus)
 4164             self.assertIsNone(cfg.devices[1].device_addr)
 4165 
 4166             # The third device will be the boot volume. It should have a
 4167             # unit number of 0.
 4168             self.assertIsInstance(cfg.devices[2],
 4169                                   vconfig.LibvirtConfigGuestDisk)
 4170             self.assertEqual('sda', cfg.devices[2].target_dev)
 4171             self.assertEqual('scsi', cfg.devices[2].target_bus)
 4172             self.assertEqual(0, cfg.devices[2].device_addr.unit)
 4173 
 4174             # The fourth device will be the other attached volume.
 4175             self.assertIsInstance(cfg.devices[3],
 4176                                   vconfig.LibvirtConfigGuestDisk)
 4177             self.assertEqual('sdc', cfg.devices[3].target_dev)
 4178             self.assertEqual('scsi', cfg.devices[3].target_bus)
 4179             self.assertEqual(2, cfg.devices[3].device_addr.unit)
 4180 
 4181     def _get_guest_config_with_graphics(self):
 4182         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 4183         instance_ref = objects.Instance(**self.test_instance)
 4184         image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
 4185 
 4186         disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
 4187                                             instance_ref,
 4188                                             image_meta)
 4189         cfg = drvr._get_guest_config(instance_ref, [],
 4190                                      image_meta, disk_info)
 4191         return cfg
 4192 
 4193     def test_get_guest_config_with_vnc(self):
 4194         self.flags(enabled=True,
 4195                    server_listen='10.0.0.1',
 4196                    keymap='en-ie',
 4197                    group='vnc')
 4198         self.flags(virt_type='kvm', group='libvirt')
 4199         self.flags(pointer_model='ps2mouse')
 4200         self.flags(enabled=False, group='spice')
 4201 
 4202         cfg = self._get_guest_config_with_graphics()
 4203 
 4204         self.assertEqual(len(cfg.devices), 7)
 4205         self.assertIsInstance(cfg.devices[0],
 4206                               vconfig.LibvirtConfigGuestDisk)
 4207         self.assertIsInstance(cfg.devices[1],
 4208                               vconfig.LibvirtConfigGuestDisk)
 4209         self.assertIsInstance(cfg.devices[2],
 4210                               vconfig.LibvirtConfigGuestSerial)
 4211         self.assertIsInstance(cfg.devices[3],
 4212                               vconfig.LibvirtConfigGuestSerial)
 4213         self.assertIsInstance(cfg.devices[4],
 4214                               vconfig.LibvirtConfigGuestGraphics)
 4215         self.assertIsInstance(cfg.devices[5],
 4216                               vconfig.LibvirtConfigGuestVideo)
 4217         self.assertIsInstance(cfg.devices[6],
 4218                               vconfig.LibvirtConfigMemoryBalloon)
 4219 
 4220         self.assertEqual(cfg.devices[4].type, 'vnc')
 4221         self.assertEqual(cfg.devices[4].keymap, 'en-ie')
 4222         self.assertEqual(cfg.devices[4].listen, '10.0.0.1')
 4223 
 4224     def test_get_guest_config_with_vnc_and_tablet(self):
 4225         self.flags(enabled=True, group='vnc')
 4226         self.flags(virt_type='kvm',
 4227                    use_usb_tablet=True,
 4228                    group='libvirt')
 4229         self.flags(enabled=False, group='spice')
 4230 
 4231         cfg = self._get_guest_config_with_graphics()
 4232 
 4233         self.assertEqual(len(cfg.devices), 8)
 4234         self.assertIsInstance(cfg.devices[0],
 4235                               vconfig.LibvirtConfigGuestDisk)
 4236         self.assertIsInstance(cfg.devices[1],
 4237                               vconfig.LibvirtConfigGuestDisk)
 4238         self.assertIsInstance(cfg.devices[2],
 4239                               vconfig.LibvirtConfigGuestSerial)
 4240         self.assertIsInstance(cfg.devices[3],
 4241                               vconfig.LibvirtConfigGuestSerial)
 4242         self.assertIsInstance(cfg.devices[4],
 4243                               vconfig.LibvirtConfigGuestInput)
 4244         self.assertIsInstance(cfg.devices[5],
 4245                               vconfig.LibvirtConfigGuestGraphics)
 4246         self.assertIsInstance(cfg.devices[6],
 4247                               vconfig.LibvirtConfigGuestVideo)
 4248         self.assertIsInstance(cfg.devices[7],
 4249                               vconfig.LibvirtConfigMemoryBalloon)
 4250 
 4251         self.assertEqual(cfg.devices[4].type, "tablet")
 4252         self.assertEqual(cfg.devices[5].type, "vnc")
 4253 
 4254     def test_get_guest_config_with_spice_and_tablet(self):
 4255         self.flags(enabled=False, group='vnc')
 4256         self.flags(virt_type='kvm',
 4257                    use_usb_tablet=True,
 4258                    group='libvirt')
 4259         self.flags(enabled=True,
 4260                    agent_enabled=False,
 4261                    server_listen='10.0.0.1',
 4262                    keymap='en-ie',
 4263                    group='spice')
 4264 
 4265         cfg = self._get_guest_config_with_graphics()
 4266 
 4267         self.assertEqual(len(cfg.devices), 8)
 4268         self.assertIsInstance(cfg.devices[0],
 4269                               vconfig.LibvirtConfigGuestDisk)
 4270         self.assertIsInstance(cfg.devices[1],
 4271                               vconfig.LibvirtConfigGuestDisk)
 4272         self.assertIsInstance(cfg.devices[2],
 4273                               vconfig.LibvirtConfigGuestSerial)
 4274         self.assertIsInstance(cfg.devices[3],
 4275                               vconfig.LibvirtConfigGuestSerial)
 4276         self.assertIsInstance(cfg.devices[4],
 4277                               vconfig.LibvirtConfigGuestInput)
 4278         self.assertIsInstance(cfg.devices[5],
 4279                               vconfig.LibvirtConfigGuestGraphics)
 4280         self.assertIsInstance(cfg.devices[6],
 4281                               vconfig.LibvirtConfigGuestVideo)
 4282         self.assertIsInstance(cfg.devices[7],
 4283                               vconfig.LibvirtConfigMemoryBalloon)
 4284 
 4285         self.assertEqual(cfg.devices[4].type, 'tablet')
 4286         self.assertEqual(cfg.devices[5].type, 'spice')
 4287         self.assertEqual(cfg.devices[5].keymap, 'en-ie')
 4288         self.assertEqual(cfg.devices[5].listen, '10.0.0.1')
 4289 
 4290     def test_get_guest_config_with_spice_and_agent(self):
 4291         self.flags(enabled=False, group='vnc')
 4292         self.flags(virt_type='kvm',
 4293                    use_usb_tablet=True,
 4294                    group='libvirt')
 4295         self.flags(enabled=True,
 4296                    agent_enabled=True,
 4297                    group='spice')
 4298 
 4299         cfg = self._get_guest_config_with_graphics()
 4300 
 4301         expect = {"ppc": "vga", "ppc64": "vga",
 4302                   "ppc64le": "vga", "aarch64": "virtio"}
 4303         video_type = expect.get(blockinfo.libvirt_utils.get_arch({}), "qxl")
 4304         self.assertEqual(len(cfg.devices), 8)
 4305         self.assertIsInstance(cfg.devices[0],
 4306                               vconfig.LibvirtConfigGuestDisk)
 4307         self.assertIsInstance(cfg.devices[1],
 4308                               vconfig.LibvirtConfigGuestDisk)
 4309         self.assertIsInstance(cfg.devices[2],
 4310                               vconfig.LibvirtConfigGuestSerial)
 4311         self.assertIsInstance(cfg.devices[3],
 4312                               vconfig.LibvirtConfigGuestSerial)
 4313         self.assertIsInstance(cfg.devices[4],
 4314                               vconfig.LibvirtConfigGuestChannel)
 4315         self.assertIsInstance(cfg.devices[5],
 4316                               vconfig.LibvirtConfigGuestGraphics)
 4317         self.assertIsInstance(cfg.devices[6],
 4318                               vconfig.LibvirtConfigGuestVideo)
 4319         self.assertIsInstance(cfg.devices[7],
 4320                               vconfig.LibvirtConfigMemoryBalloon)
 4321 
 4322         self.assertEqual(cfg.devices[4].target_name, "com.redhat.spice.0")
 4323         self.assertEqual(cfg.devices[4].type, 'spicevmc')
 4324         self.assertEqual(cfg.devices[5].type, "spice")
 4325         self.assertEqual(cfg.devices[6].type, video_type)
 4326 
 4327     def test_get_guest_config_with_vnc_no_keymap(self):
 4328         self.flags(virt_type='kvm', group='libvirt')
 4329         self.flags(enabled=True, keymap=None, group='vnc')
 4330         self.flags(enabled=False, group='spice')
 4331 
 4332         cfg = self._get_guest_config_with_graphics()
 4333 
 4334         for device in cfg.devices:
 4335             if device.root_name == 'graphics':
 4336                 self.assertIsInstance(device,
 4337                                       vconfig.LibvirtConfigGuestGraphics)
 4338                 self.assertEqual('vnc', device.type)
 4339                 self.assertIsNone(device.keymap)
 4340 
 4341     def test_get_guest_config_with_spice_no_keymap(self):
 4342         self.flags(virt_type='kvm', group='libvirt')
 4343         self.flags(enabled=True, keymap=None, group='spice')
 4344         self.flags(enabled=False, group='vnc')
 4345 
 4346         cfg = self._get_guest_config_with_graphics()
 4347 
 4348         for device in cfg.devices:
 4349             if device.root_name == 'graphics':
 4350                 self.assertIsInstance(device,
 4351                                       vconfig.LibvirtConfigGuestGraphics)
 4352                 self.assertEqual('spice', device.type)
 4353                 self.assertIsNone(device.keymap)
 4354 
 4355     @mock.patch.object(host.Host, 'get_guest')
 4356     @mock.patch.object(libvirt_driver.LibvirtDriver,
 4357                        '_get_serial_ports_from_guest')
 4358     @mock.patch('nova.console.serial.acquire_port')
 4359     @mock.patch('nova.virt.hardware.get_number_of_serial_ports',
 4360                 return_value=1)
 4361     @mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',)
 4362     def test_create_serial_console_devices_based_on_arch(self, mock_get_arch,
 4363                                                          mock_get_port_number,
 4364                                                          mock_acquire_port,
 4365                                                          mock_ports,
 4366                                                          mock_guest):
 4367         self.flags(enabled=True, group='serial_console')
 4368         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 4369         instance = objects.Instance(**self.test_instance)
 4370 
 4371         expected = {
 4372           fields.Architecture.X86_64: vconfig.LibvirtConfigGuestSerial,
 4373           fields.Architecture.S390: vconfig.LibvirtConfigGuestConsole,
 4374           fields.Architecture.S390X: vconfig.LibvirtConfigGuestConsole}
 4375 
 4376         for guest_arch, device_type in expected.items():
 4377             mock_get_arch.return_value = guest_arch
 4378             guest = vconfig.LibvirtConfigGuest()
 4379 
 4380             drvr._create_consoles(virt_type="kvm", guest_cfg=guest,
 4381                                   instance=instance, flavor={},
 4382                                   image_meta={})
 4383             self.assertEqual(2, len(guest.devices))
 4384             console_device = guest.devices[0]
 4385             self.assertIsInstance(console_device, device_type)
 4386             self.assertEqual("tcp", console_device.type)
 4387 
 4388     @mock.patch.object(host.Host, 'get_guest')
 4389     @mock.patch.object(libvirt_driver.LibvirtDriver,
 4390                        '_get_serial_ports_from_guest')
 4391     @mock.patch('nova.virt.hardware.get_number_of_serial_ports',
 4392                 return_value=4)
 4393     @mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',
 4394                        side_effect=[fields.Architecture.X86_64,
 4395                                     fields.Architecture.S390,
 4396                                     fields.Architecture.S390X])
 4397     def test_create_serial_console_devices_with_limit_exceeded_based_on_arch(
 4398             self, mock_get_arch, mock_get_port_number, mock_ports, mock_guest):
 4399         self.flags(enabled=True, group='serial_console')
 4400         self.flags(virt_type="qemu", group='libvirt')
 4401         flavor = 'fake_flavor'
 4402         image_meta = objects.ImageMeta()
 4403         drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
 4404         guest = vconfig.LibvirtConfigGuest()
 4405         instance = objects.Instance(**self.test_instance)
 4406         self.assertRaises(exception.SerialPortNumberLimitExceeded,
 4407                           drvr._create_consoles,
 4408                           "kvm", guest, instance, flavor, image_meta)
 4409         mock_get_arch.assert_called_with(image_meta)
 4410         mock_get_port_number.assert_called_with(flavor,
 4411                                                 image_meta)
 4412 
 4413         drvr._create_consoles("kvm", guest, instance, flavor, image_meta)
 4414         mock_get_arch.assert_called_with(image_meta