Tag Archives: disks

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.
   #The list of block device names.
   #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"):
       #The driver type: For ex: qcow2/raw
       for src in target.findall("driver"):
       #Target device like: vda/vdb etc.
       for src in target.findall("target"):
       #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:
   #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)