libvirt

Version 9.1 by Sebastian Marsching on 2022/07/17 14:20

Graceful shutdown of virtual machines / domains when shutting down libvirtd

When libvirtd is stopped, all virtual machines are destroyed. There is a little script that does a shutdown of all virtual machines before stopping libvirtd:

#!/usr/bin/python

import libvirt
import time
import sys

conn = libvirt.open("qemu:///system")
if conn == None:
   print "Failed to open connection"
    sys.exit(1)

domainIDs = conn.listDomainsID()

for id in domainIDs:
    dom = conn.lookupByID(id)
   if (dom == None):
       continue
    dom.shutdown()

# Wait up to 4 minutes
shutdownTimeOut = 240

while conn.numOfDomains() > 0 and (time.time() - startTime) < shutdownTimeOut:
    time.sleep(2)

if conn.numOfDomains > 0:
  sys.exit(2)

This script has to be integrated into the stop and restart part of the /etc/init.d/libvirt-bin init script:

# …stop or restart section…
       if running ; then
               echo -n "Stopping libvirt virtual machines..."
                /usr/local/bin/libvirt-shutdown-domains || true
               echo " done"
       fi

Converting OVA images for use with libvirt

OVA images can be imported into libvirt using the virt-v2v utility (from the libguestfs-tools Ubuntu package).

They can be imported directly using the libvirt output method, but I prefer only generating the necessary files, using the local output method. This way, I can easily adjust the VM settings before importing them into libvirt.

virt-v2v -i ova /path/to/source.ova -o local -of qcow2 -os /path/to/destination/dir

This will create an XML file with the VM configuration and a QCOW2 file for each disk in  /path/to/destination/dir. The XML file can be adjusted and then imported using virsh define.