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)