Wiki source code of libvirt
Version 8.2 by Sebastian Marsching on 2022/03/27 14:20
Show last authors
author | version | line-number | content |
---|---|---|---|
1 | # Graceful shutdown of virtual machines / domains when shutting down libvirtd | ||
2 | |||
3 | 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: | ||
4 | |||
5 | ```python | ||
6 | #!/usr/bin/python | ||
7 | |||
8 | import libvirt | ||
9 | import time | ||
10 | import sys | ||
11 | |||
12 | conn = libvirt.open("qemu:///system") | ||
13 | if conn == None: | ||
14 | print "Failed to open connection" | ||
15 | sys.exit(1) | ||
16 | |||
17 | domainIDs = conn.listDomainsID() | ||
18 | |||
19 | for id in domainIDs: | ||
20 | dom = conn.lookupByID(id) | ||
21 | if (dom == None): | ||
22 | continue | ||
23 | dom.shutdown() | ||
24 | |||
25 | # Wait up to 4 minutes | ||
26 | shutdownTimeOut = 240 | ||
27 | |||
28 | while conn.numOfDomains() > 0 and (time.time() - startTime) < shutdownTimeOut: | ||
29 | time.sleep(2) | ||
30 | |||
31 | if conn.numOfDomains > 0: | ||
32 | sys.exit(2) | ||
33 | ``` | ||
34 | |||
35 | This script has to be integrated into the stop and restart part of the `/etc/init.d/libvirt-bin` init script: | ||
36 | |||
37 | ```bash | ||
38 | # …stop or restart section… | ||
39 | if running ; then | ||
40 | echo -n "Stopping libvirt virtual machines..." | ||
41 | /usr/local/bin/libvirt-shutdown-domains || true | ||
42 | echo " done" | ||
43 | fi | ||
44 | |||
45 | ``` |