Friday, October 2, 2009

Python Libvirt Example

Just like block device statistics can be retrieved from libvirt guest domains, network interface statistics can also be retrieved. The main modification is that the XML data comes from a different element and a different method on the domain is invoked. Here is an example of how network interface statistics are retrieved from libvirt.
#Example; Libvirt network stats.

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

#Function to return a list of network devices used.
def get_target_devices(dom):
#Create a XML tree from the domain XML description.
tree=ElementTree.fromstring(dom.XMLDesc(0))

#The list of network device names.
devices=[]

#Iterate through all network interface target elements of the domain.
for target in tree.findall("devices/interface/target"):
#Get the device name.
dev=target.get("dev")

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

#Completed device name list.
return devices

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

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

#Initialize our interface stat counters.
rx_bytes=0
rx_packets=0
rx_errs=0
rx_drop=0
tx_bytes=0
tx_packets=0
tx_errs=0
tx_drop=0

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

#Update the interface stat counters
rx_bytes+=stats[0]
rx_packets+=stats[1]
rx_errs+=stats[2]
rx_drop+=stats[3]
tx_bytes+=stats[4]
tx_packets+=stats[5]
tx_errs+=stats[6]
tx_drop+=stats[7]

#Display the results for this domain.
print "\n%s Interface Stats"%(dom.UUIDString())
print "Read Bytes: %s"%(rx_bytes)
print "Read Packets: %s"%(rx_packets)
print "Read Errors: %s"%(rx_errs)
print "Read Drops: %s"%(rx_drop)
print "Written Bytes: %s"%(tx_bytes)
print "Written Packets: %s"%(tx_packets)
print "Write Errors: %s"%(tx_errs)
print "Write Drops: %s"%(tx_drop)

1 comment :

  1. You are awesome! Excellent work!!! Keep it up!!

    ReplyDelete