Wiki source code of libvirt

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

Show last authors
1 {{toc/}}
2
3 # Graceful shutdown of virtual machines / domains when shutting down libvirtd
4
5 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:
6
7 ```python
8 #!/usr/bin/python
9
10 import libvirt
11 import time
12 import sys
13
14 conn = libvirt.open("qemu:///system")
15 if conn == None:
16 print "Failed to open connection"
17 sys.exit(1)
18
19 domainIDs = conn.listDomainsID()
20
21 for id in domainIDs:
22 dom = conn.lookupByID(id)
23 if (dom == None):
24 continue
25 dom.shutdown()
26
27 # Wait up to 4 minutes
28 shutdownTimeOut = 240
29
30 while conn.numOfDomains() > 0 and (time.time() - startTime) < shutdownTimeOut:
31 time.sleep(2)
32
33 if conn.numOfDomains > 0:
34 sys.exit(2)
35 ```
36
37 This script has to be integrated into the stop and restart part of the `/etc/init.d/libvirt-bin` init script:
38
39 ```bash
40 # …stop or restart section…
41 if running ; then
42 echo -n "Stopping libvirt virtual machines..."
43 /usr/local/bin/libvirt-shutdown-domains || true
44 echo " done"
45 fi
46 ```
47
48 # Converting OVA images for use with libvirt
49
50 OVA images can be [imported](https://www.redhat.com/en/blog/importing-vms-kvm-virt-v2v) into libvirt using the `virt-v2v` utility (from the `libguestfs-tools` Ubuntu package).
51
52 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.
53
54 ```bash
55 virt-v2v -i ova /path/to/source.ova -o local -of qcow2 -os /path/to/destination/dir
56 ```
57
58 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`.