Category Archives: Libvirt

List domain disks using Python-Libvirt

Short piece of code to return an array of DiskInfo tuple consisting of disk’s format , driver type and source file etc. The DiskInfo tuple is a user defined tuple to allow easy access to all info about a disk device.

import libvirt
import sys
from xml.etree import ElementTree
from xml.dom import minidom
from collections import namedtuple

DiskInfo = namedtuple('DiskInfo', ['device', 'source_file', 'format'])
#Return a list of block devices used by the domain
def get_target_devices(dom):

   #Create a XML tree from the domain XML description.
   tree=ElementTree.fromstring(dom.XMLDesc(0))
  
   #The list of block device names.
   devices=[]
  
   #Iterate through all disk of the domain.
   for target in tree.findall("devices/disk"):
       #Within each disk found, get the source file 
       #for ex. /var/lib/libvirt/images/vmdisk01.qcow2
       for src in target.findall("source"):
               file=src.get("file")
       
       #The driver type: For ex: qcow2/raw
       for src in target.findall("driver"):
                   type=src.get("type")
       
       #Target device like: vda/vdb etc.
       for src in target.findall("target"):
                   dev=src.get("dev")
       
       #Make them all into a tuple
       Disk = DiskInfo(dev, file, type)
       
       #Check if we have already found the device name for this domain.
       if not Disk in devices:
              devices.append(Disk)
             
   #Completed device name list.
   return devices
     

Here dom is the dom returned after call to conn.lookupByName or equivalent function.

Calling function was:

for dev in get_target_devices(dom):
            print( "Processing Disk: %s",dev)

Libvirt and Python Connect to Hypervisor

These are short posts on how to connect to qemu/KVM via libvirt using Python binding. Ability to talk to the hypervisor helps in various automation tasks. In this post, we show how to connect to hypervisor and display domain details. Its assumed that you have Qemu/KVM and have installed libvirt-python package. If not, its yum install libvirt-python to install it.

import libvirt
import sys

#Open a readonly connection to libvirt
conn = libvirt.openReadOnly(None)

if conn == None:
    Logger.critical( 'Could not connect to the hypervisor')
    sys.exit(1)
try:
    dom = conn.lookupByName("centos_vm")
except:
    Logger.critical( 'Could not find the domain')
    sys.exit(1)
print ("Domain : id %d running %s state = %d" % (dom.ID(), dom.OSType(), dom.state()[0]))
print (dom.info())

Output

Domain 0: id -1 running hvm state = 5
[5, 2097152L, 0L, 2, 0L]

From libvirt source code:

# virDomainState (dom.state()[0])
VIR_DOMAIN_NOSTATE     = 0 # no state
VIR_DOMAIN_RUNNING     = 1 # the domain is running
VIR_DOMAIN_BLOCKED     = 2 # the domain is blocked on resource
VIR_DOMAIN_PAUSED      = 3 # the domain is paused by user
VIR_DOMAIN_SHUTDOWN    = 4 # the domain is being shut down
VIR_DOMAIN_SHUTOFF     = 5 # the domain is shut off
VIR_DOMAIN_CRASHED     = 6 # the domain is crashed
VIR_DOMAIN_PMSUSPENDED = 7 # the domain is suspended by guest power management
More Help

Run this command to print out the entire libvirt API.

python -c "import libvirt; help(libvirt)" > help.txt

Other ways to display state names:

domain_state_name = {  libvirt.VIR_DOMAIN_NOSTATE     : "no state",
                       libvirt.VIR_DOMAIN_RUNNING     : "running",
                       libvirt.VIR_DOMAIN_BLOCKED     : "idle",
                       libvirt.VIR_DOMAIN_PAUSED      : "paused",
                       libvirt.VIR_DOMAIN_SHUTDOWN    : "in shutdown",
                       libvirt.VIR_DOMAIN_SHUTOFF     : "shut off",
                       libvirt.VIR_DOMAIN_CRASHED     : "crashed",
                       libvirt.VIR_DOMAIN_PMSUSPENDED : "suspended by PM" }

print("Current State:", domain_state_name[dom.state()[0]])

References

http://www.ibm.com/developerworks/library/os-python-kvm-scripting1/