libvirt

Version 3.1 by Sebastian Marsching on 2022/03/27 14:17

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:

if running ; then
               echo -n "Stopping libvirt virtual machines..."
                /usr/local/bin/libvirt-shutdown-domains || true
               echo " done"
       fi