Thursday, September 10, 2009

Python Libvirt Example

The libvirt virtualization library is a programming API used to manage virtual machines with a variety of hypervisors. There are several language bindings available for the libvirt library including Python. Within a given Python application that uses the libvirt library, the application can potentially control every virtual machine running on the host if used correctly. Libvirt also has the ability to assume control of remote hypervisors.

Virtual machines, or guest domains, have primary disks and potentially secondary disks attached to them. These block devices and even be added to a running virtual machine. But just like a physical host, it helps to know exactly how the virtual block devices for a given virtual machine are being utilized. This way, potential problems may be addressed before they occur. Libvirt provides the ability retrieve such statistics for these devices. Here is a Python example of how to do this.
#Example; Libvirt block stats.

#We need libvirt and ElementTree.
import libvirt
from xml.etree import ElementTree

#Function to return a list of block devices used.
def get_target_devices(dom):
#Create a XML tree from the domain XML description.

#The list of block device names.

#Iterate through all disk target elements of the domain.
for target in tree.findall("devices/disk/target"):
#Get the device name.

#Check if we have already found the device name for this domain.
if not dev in devices:

#Completed device name list.
return devices

if __name__=="__main__":
#Connect to some hypervisor."qemu:///system")

#Iterate through all available domains.
for id in conn.listDomainsID():
#Initialize the domain object.

#Initialize our block stat counters.

#Iterate through each device name used by this domain.
for dev in get_target_devices(dom):
#Retrieve the block stats for this device used by this domain.

#Update the block stat counters

#display the results for this domain.
print "\n%s Block Stats"%(dom.UUIDString())
print "Read Requests: %s"%(rreq)
print "Read Bytes: %s"%(rbytes)
print "Write Requests: %s"%(wreq)
print "Written Bytes: %s"%(wbytes)

1 comment :

  1. Just what I needed for my code. I was trying to find a way to iterate through the disk target elements in a domain.

    Thanks much,
    Kyle W.