[libvirt] API calls to get interfaces and block devices

Ruben Kerkhof ruben at rubenkerkhof.com
Fri Apr 11 15:59:42 UTC 2014


Hi Cole,

On Fri, Apr 11, 2014 at 2:50 PM, Cole Robinson <crobinso at redhat.com> wrote:
> On 04/11/2014 07:14 AM, Ruben Kerkhof wrote:
>> Hi all,
>>
>> I have a few python scripts which use the libvirt api to get interface and block device statistics.
>> What has been bugging me for a while now that is that there’s no high level api to get a list of all interfaces or block devices for a vm.
>> The list can be retrieved from the xml with a bit of Xpath magic, but this seems to me to break the nice abstraction layer libvirt provides.
>> Ideally, I don’t have to do anything with xml, and add dependencies on xml parsers to my code.
>>
>> I’ve seen examples of code doing this, for example the collectd libvirt plugin, but there must be many others.
>>
>> Can I kindly ask for such an API? Unfortunately I don’t have the skills to code this up myself.
>>
>
> It's an unavoidable fact that XML is part of the libvirt API. Going down the
> route of providing APIs that return bits and pieces of the XML is a slippery
> slope and increases libvirt maintenance burden.
>
> python has a native XML library. To do what you want is pretty straight
> forward once you understand the concepts. For example this prints every
> interface mac address for the VM 'f20':
>
>
> import xml.etree.ElementTree as ET
> import libvirt
>
> conn = libvirt.open("qemu:///system")
> dom = conn.lookupByName("f20")
> xml = dom.XMLDesc(0)
>
> root = ET.fromstring(xml)
> ifaces = root.findall("./devices/interface/mac")
> for iface in ifaces:
>     print iface.attrib["address"]

You're right, it's not that hard.
I've been using something like the following code for a while now:

def get_interfaces(dom):
    interfaces = {}
    tree = ElementTree.fromstring(dom.XMLDesc(0))

    for interface in tree.findall("devices/interface"):
        target = interface.find("target")
        if target is None: continue
        dev = target.get("dev")
        mac = interface.find("mac").get("address")
        if not dev in interfaces:
            interfaces[dev] = mac
    return interfaces

Kind regards,

Ruben




More information about the libvir-list mailing list