def setUp(self): super(JobInfoTestCase, self).setUp() self.useFixture(fakelibvirt.FakeLibvirtFixture()) self.conn = fakelibvirt.openAuth("qemu:///system", [[], lambda: True]) xml = ("<domain type='kvm'>" " <name>instance-0000000a</name>" "</domain>") self.dom = self.conn.createXML(xml, 0) self.guest = libvirt_guest.Guest(self.dom) libvirt_guest.JobInfo._have_job_stats = True
def list_guests(self, only_running=True, only_guests=True): """Get a list of Guest objects for nova instances :param only_running: True to only return running instances :param only_guests: True to filter out any host domain (eg Dom-0) See method "list_instance_domains" for more information. :returns: list of Guest objects """ return [libvirt_guest.Guest(dom) for dom in self.list_instance_domains( only_running=only_running, only_guests=only_guests)]
def test_enable_hairpin(self, mock_get_interfaces, mock_execute): mock_get_interfaces.return_value = ["vnet0", "vnet1"] guest = libvirt_guest.Guest(mock.MagicMock()) guest.enable_hairpin() mock_execute.assert_has_calls([ mock.call( 'tee', '/sys/class/net/vnet0/brport/hairpin_mode', run_as_root=True, process_input='1', check_exit_code=[0, 1]), mock.call( 'tee', '/sys/class/net/vnet1/brport/hairpin_mode', run_as_root=True, process_input='1', check_exit_code=[0, 1])])
def test_detach_device_persistent_live(self): domain = mock.Mock(spec=fakelibvirt.virDomain) conf = mock.Mock(spec=vconfig.LibvirtConfigGuestDevice) conf.to_xml.return_value = "</xml>" guest = libvirt_guest.Guest(domain) guest.detach_device(conf, persistent=True, live=True) domain.detachDeviceFlags.assert_called_once_with( "</xml>", flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def setUp(self): super(GuestTestCase, self).setUp() self.useFixture(nova_fixtures.LibvirtFixture()) self.host = host.Host("qemu:///system") self.context = context.get_admin_context() self.domain = mock.Mock(spec=fakelibvirt.virDomain) self.guest = libvirt_guest.Guest(self.domain) # Make RetryDecorator not actually sleep on retries self.useFixture(service_fixture.SleepFixture())
def get_guest(self, instance): """Retrieve libvirt guest object for an instance. All libvirt error handling should be handled in this method and relevant nova exceptions should be raised in response. :param instance: a nova.objects.Instance object :returns: a nova.virt.libvirt.Guest object :raises exception.InstanceNotFound: The domain was not found :raises exception.InternalError: A libvirt error occurred """ return libvirt_guest.Guest(self.get_domain(instance))
def _event_lifecycle_callback(conn, dom, event, detail, opaque): """Receives lifecycle events from libvirt. NB: this method is executing in a native thread, not an eventlet coroutine. It can only invoke other libvirt APIs, or use self._queue_event(). Any use of logging APIs in particular is forbidden. """ self = opaque uuid = dom.UUIDString() transition = None if event == libvirt.VIR_DOMAIN_EVENT_STOPPED: transition = virtevent.EVENT_LIFECYCLE_STOPPED elif event == libvirt.VIR_DOMAIN_EVENT_STARTED: transition = virtevent.EVENT_LIFECYCLE_STARTED elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED: if detail == libvirt.VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: transition = virtevent.EVENT_LIFECYCLE_POSTCOPY_STARTED elif detail == libvirt.VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: # VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED is also sent when live # migration of the guest fails, so we cannot simply rely # on the event itself but need to check if the job itself was # successful. # NOTE(mriedem): The job check logic here is copied from # LibvirtDriver._live_migration_monitor. guest = libvirt_guest.Guest(dom) info = guest.get_job_info() if info.type == libvirt.VIR_DOMAIN_JOB_NONE: # Either still running, or failed or completed, # lets untangle the mess. info.type = libvirt_migrate.find_job_type(guest, instance=None, logging_ok=False) if info.type == libvirt.VIR_DOMAIN_JOB_COMPLETED: transition = virtevent.EVENT_LIFECYCLE_MIGRATION_COMPLETED else: # Failed or some other status we don't know about, so just # opt to report the guest is paused. transition = virtevent.EVENT_LIFECYCLE_PAUSED else: transition = virtevent.EVENT_LIFECYCLE_PAUSED elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED: transition = virtevent.EVENT_LIFECYCLE_RESUMED if transition is not None: self._queue_event(virtevent.LifecycleEvent(uuid, transition))
def test_get_interfaces(self): dom = mock.Mock(spec=fakelibvirt.virDomain) dom.XMLDesc.return_value = """ <domain> <devices> <interface type="network"> <target dev="vnet0"/> </interface> <interface type="network"> <target dev="vnet1"/> </interface> </devices> </domain>""" guest = libvirt_guest.Guest(dom) self.assertEqual(["vnet0", "vnet1"], guest.get_interfaces())
def get_memory_mb_used(self): """Get the used memory size(MB) of physical computer. :returns: the total usage of memory(MB). """ if sys.platform.upper() not in ['LINUX2', 'LINUX3']: return 0 with open('/proc/meminfo') as fp: m = fp.read().split() idx1 = m.index('MemFree:') idx2 = m.index('Buffers:') idx3 = m.index('Cached:') if CONF.libvirt.virt_type == 'xen': used = 0 for dom in self.list_instance_domains(only_guests=False): try: # TODO(sahid): we should have method list_guests() # which returns Guest's objects guest = libvirt_guest.Guest(dom) # TODO(sahid): Use get_info... dom_mem = int(guest._get_domain_info(self)[2]) except libvirt.libvirtError as e: LOG.warn( _LW("couldn't obtain the memory from domain:" " %(uuid)s, exception: %(ex)s") % { "uuid": dom.UUIDString(), "ex": e }) continue # skip dom0 if dom.ID() != 0: used += dom_mem else: # the mem reported by dom0 is be greater of what # it is being used used += (dom_mem - (int(m[idx1 + 1]) + int(m[idx2 + 1]) + int(m[idx3 + 1]))) # Convert it to MB return used / units.Ki else: avail = (int(m[idx1 + 1]) + int(m[idx2 + 1]) + int(m[idx3 + 1])) # Convert it to MB return self.get_memory_mb_total() - avail / units.Ki
def test_get_disk_xml(self): dom_xml = """ <domain type="kvm"> <devices> <disk type="file"> <source file="disk1_file"/> <target dev="vda" bus="virtio"/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk> <disk type="block"> <source dev="/path/to/dev/1"/> <target dev="vdb" bus="virtio" serial="1234"/> </disk> </devices> </domain> """ diska_xml = """<disk type="file" device="disk"> <source file="disk1_file"/> <target bus="virtio" dev="vda"/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk>""" diskb_xml = """<disk type="block" device="disk"> <source dev="/path/to/dev/1"/> <target bus="virtio" dev="vdb"/> </disk>""" dom = mock.MagicMock() dom.XMLDesc.return_value = dom_xml guest = libvirt_guest.Guest(dom) # NOTE(gcb): etree.tostring(node) returns an extra line with # some white spaces, need to strip it. actual_diska_xml = guest.get_disk('vda').to_xml() self.assertXmlEqual(diska_xml, actual_diska_xml) actual_diskb_xml = guest.get_disk('vdb').to_xml() self.assertXmlEqual(diskb_xml, actual_diskb_xml) self.assertIsNone(guest.get_disk('vdc')) dom.XMLDesc.assert_has_calls([mock.call(0)] * 3)
def test_find_disk_lxc(self): self.useFixture(fakelibvirt.FakeLibvirtFixture()) xml = """ <domain type='lxc'> <os> <type>exe</type> </os> <devices> <filesystem type="mount"> <source dir="/myhome/rootfs"/> <target dir="/"/> </filesystem> </devices> </domain> """ virt_dom = mock.Mock(XMLDesc=mock.Mock(return_value=xml)) guest = libvirt_guest.Guest(virt_dom) disk_path, format = libvirt_utils.find_disk(guest) self.assertEqual('/myhome/disk', disk_path) self.assertIsNone(format)
def test_find_disk_parallels(self): self.useFixture(fakelibvirt.FakeLibvirtFixture()) xml = """ <domain type='parallels'> <os> <type>exe</type> </os> <devices> <filesystem type='file'>" <driver format='ploop' type='ploop'/>" <source file='/test/disk'/>" <target dir='/'/> </filesystem>" </devices> </domain> """ virt_dom = mock.Mock(XMLDesc=mock.Mock(return_value=xml)) guest = libvirt_guest.Guest(virt_dom) disk_path, format = libvirt_utils.find_disk(guest) self.assertEqual('/test/disk', disk_path) self.assertEqual('ploop', format)
def test_find_disk_block_device(self): self.useFixture(fakelibvirt.FakeLibvirtFixture()) xml = """ <domain type='kvm'> <os> <type>linux</type> </os> <devices> <disk type="block" device="disk"> <driver name="qemu" type="raw"/> <source dev="/dev/nova-vg/hello"/> <target bus="ide" dev="/dev/hda"/> </disk> </devices> </domain> """ virt_dom = mock.Mock(XMLDesc=mock.Mock(return_value=xml)) guest = libvirt_guest.Guest(virt_dom) disk_path, format = libvirt_utils.find_disk(guest) self.assertEqual('/dev/nova-vg/hello', disk_path) self.assertEqual('raw', format)
def test_find_disk_file_device(self): self.useFixture(fakelibvirt.FakeLibvirtFixture()) xml = """ <domain type='kvm'> <os> <type>linux</type> </os> <devices> <disk type="file" device="disk"> <driver name="qemu" type="qcow2" cache="none" io="native"/> <source file="/tmp/hello"/> <target bus="ide" dev="/dev/hda"/> </disk> </devices> </domain> """ virt_dom = mock.Mock(XMLDesc=mock.Mock(return_value=xml)) guest = libvirt_guest.Guest(virt_dom) disk_path, format = libvirt_utils.find_disk(guest) self.assertEqual('/tmp/hello', disk_path) self.assertEqual('qcow2', format)
def test_find_disk_rbd(self): self.useFixture(fakelibvirt.FakeLibvirtFixture()) xml = """ <domain type='kvm'> <os> <type>linux</type> </os> <devices> <disk type="network" device="disk"> <driver name="qemu" type="raw"/> <source name="pool/image" protocol="rbd"> <host name="1.2.3.4" port="456"/> </source> <target bus="virtio" dev="/dev/vda"/> </disk> </devices> </domain> """ virt_dom = mock.Mock(XMLDesc=mock.Mock(return_value=xml)) guest = libvirt_guest.Guest(virt_dom) disk_path, format = libvirt_utils.find_disk(guest) self.assertEqual('rbd:pool/image', disk_path) self.assertEqual('raw', format)
def test_has_persistent_configuration(self): domain = mock.Mock(spec=fakelibvirt.virDomain) guest = libvirt_guest.Guest(domain) self.assertTrue(guest.has_persistent_configuration()) domain.isPersistent.assert_called_once_with()
def test_get_interfaces_exception(self): dom = mock.Mock(spec=fakelibvirt.virDomain) dom.XMLDesc.return_value = "<bad xml>" guest = libvirt_guest.Guest(dom) self.assertEqual([], guest.get_interfaces())
def test_get_xml_desc(self): domain = mock.Mock(spec=fakelibvirt.virDomain) guest = libvirt_guest.Guest(domain) guest.get_xml_desc() domain.XMLDesc.assert_called_once_with(flags=0)