Module 11 · Lesson 54 of 107

libvirt, the domain XML and virsh

Describe a QEMU/KVM guest in domain XML, validate its definition, and use virsh to inspect and control its lifecycle.

  • Beginner to advanced
  • 10 min read
  • 28 min lab
What you will need

Ubuntu 24.04 on an x86-64 host or VM with KVM available, access to the libvirt system connection, virsh, virt-xml-validate, and a writable disposable qcow2 copy of a BIOS-bootable Linux guest with a serial login

Your place in the module
By the end you can 4 objectives
  • Select the intended local or remote libvirt connection URI.
  • Validate a domain XML file and identify its boot, CPU, memory, and device settings.
  • Script a VM lifecycle from definition through snapshot and verified shutdown.
  • Trace a virsh operation through the libvirt QEMU driver to the QEMU monitor.
Video coming soonlibvirt, the domain XML and virsh
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The MMIO and PCI transport drivers
  • The platform or PCI driver registers a child device on the virtio bus.
  • Legacy MMIO activates a queue through QueuePFN, while modern MMIO supplies separate queue addresses and sets QueueReady.
  • Modern virtio PCI capabilities describe BAR regions, and MSI-X mappings associate configuration changes and queues with interrupt vectors.
01

Choose the connection and follow the request

4 min read

The last lessons built VMMs by hand. This lesson answers libvirt, the management layer that describes a VM in XML and drives QEMU through virsh and QMP.

Suppose an Ubuntu test host needs to boot the same Linux guest after every kernel build. The automation needs a stable guest name, a serial console for boot messages, and a way to tell when the guest has finished shutting down. KVM exposes the VM and vCPU interfaces used by a VMM. Libvirt supplies the management interface the test script needs. A script can save the guest definition once, start it by name, and check its state through the same connection. The KVM API

Libvirt provides a common API with drivers for different backends. The QEMU driver manages QEMU guests, including guests that use KVM acceleration. The Xen driver manages Xen domains, the LXC driver manages Linux containers, and the bhyve driver targets bhyve on FreeBSD. Those names describe the scope of the driver model. This lesson uses the QEMU driver on Ubuntu. Many operations have common names across drivers, while the available devices and lifecycle operations depend on the backend.

virsh is a command-line client of libvirt. On a host using the monolithic daemon layout, libvirtd receives management requests and loads the relevant driver. Libvirt also supports a modular layout in which virtqemud serves the QEMU driver. A local client can connect through a Unix domain socket. Socket access and libvirt authorization determine what the caller can do. virsh reports errors returned by libvirt, including failures to connect, define a domain, or start a QEMU process. unix(7)

bash
virsh -c qemu:///system list --all
virsh -c qemu+ssh://operator@lab-host/system list --all

The first URI selects the local QEMU system instance. The empty host field appears between qemu:// and /system. The second selects that instance on lab-host, with SSH as the transport and operator as the remote account. Substitute a reachable host and an authorized account to use it. Paths inside domain XML, such as a disk image path, refer to files on the virtualization host. For remote use, an image on the client must already be available to the remote host at the path the XML specifies.

Keep -c qemu:///system explicit in scripts so every invocation uses the same inventory. For example, qemu:///session selects a per-user QEMU instance with its own domain definitions. If a guest you just defined seems to have disappeared, confirm the URI and run list --all. Plain list shows active domains, which include paused guests. Adding --all includes inactive definitions.

Once a guest is running under QEMU, the libvirt driver communicates with it through a monitor connection. is designed for programs. A QMP client negotiates capabilities before issuing normal commands. A status query has an execute field. Replies carry a return or error field, and events can arrive independently. HMP, the Human Monitor Protocol, is a text interface with commands such as info status and output intended for human readers. qmp-shell is a QEMU utility for interacting with a QMP socket, for example when you launch a disposable QEMU instance with its own monitor. For a libvirt-managed guest, you can issue a read-only monitor query via libvirt.

bash
virsh -c qemu:///system qemu-monitor-command m11-lab \
  '{"execute":"query-status"}'

Here virsh passes the query to libvirt, and the QEMU driver sends it on its existing monitor connection. For regular lifecycle operations, use the dedicated virsh commands. Libvirt starts the QEMU process when you run start. During runtime it can issue QMP commands for operations such as pausing the guest and use monitor events to track state changes. A direct monitor command that changes device state can leave the live machine different from what libvirt tracks.

Controlling a QEMU guestvirshselects a connection URILibvirt daemonserves management requestsQEMU driverlaunches and tracks QEMUQEMU processserves the QMP monitorQMP replies and events return to libvirtvirshselects a connection URILibvirt daemonserves management requestsQEMU driverlaunches and tracks QEMUQEMU processserves the QMP monitorQMP replies and events return tolibvirt
A virsh request reaches the libvirt QEMU driver, which manages the host QEMU process and its monitor
02

Describe the machine in domain XML

4 min read

A can have a persistent definition, a running instance, or both. The root <domain> element selects the virtualization type. Here type="kvm" requests a QEMU guest with KVM acceleration. Libvirt can generate a UUID when you supply a new definition without one. The domain name must be unique within the connection's inventory. Use a dedicated name and disk copy so repeated tests address the same guest and its own data.

The following example assumes an x86-64 host with KVM available and a disposable, BIOS-bootable Linux image already installed for a virtio disk. Save the XML as m11-lab.xml. Substitute the absolute path to your disk copy. The system QEMU process needs permission to open that file for writing, including access through its parent directories and any host security policy. Use virsh -c qemu:///system domcapabilities to inspect the machine, firmware, and CPU possibilities exposed by your host.

xml
<domain type='kvm'>
  <name>m11-lab</name>
  <memory unit='MiB'>1024</memory>
  <currentMemory unit='MiB'>1024</currentMemory>
  <vcpu current='1'>2</vcpu>
  <os>
    <type arch='x86_64' machine='q35'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
  </features>
  <cpu mode='host-model'>
    <topology sockets='1' cores='2' threads='1'/>
  </cpu>
  <clock offset='utc'/>
  <devices>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/var/lib/libvirt/images/m11-lab.qcow2'/>
      <target dev='vda' bus='virtio'/>
    </disk>
    <interface type='user'>
      <model type='virtio'/>
    </interface>
    <graphics type='vnc' autoport='yes' listen='127.0.0.1'/>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <rng model='virtio'>
      <backend model='random'>/dev/urandom</backend>
    </rng>
  </devices>
</domain>

Read <os> as the guest's boot configuration. The <type> element specifies the guest architecture and machine model. Here q35 selects an x86 machine with a PCI Express root complex. <boot dev='hd'/> asks the firmware to try the hard disk. For a UEFI-installed disk, use a suitable UEFI configuration. <os firmware='efi'> requests automatic firmware selection from the host's installed firmware. An explicit <loader> can instead identify a suitable firmware binary. With a read-only flash loader and writable firmware variables, the domain can also have an <nvram> configuration. The disk's installed bootloader and the VM's firmware mode must agree.

The <cpu> mode controls what the guest sees. host-model asks libvirt to select a guest CPU model and features close to the host's capabilities. host-passthrough exposes the host CPU as directly as the hypervisor allows. A guest using host-passthrough can be sensitive to differences between hosts, so check compatibility before moving it. <topology> describes the guest-visible sockets, cores, and threads. In this example their product is two, matching the maximum in <vcpu>. The current attribute starts the guest with one enabled vCPU. Guest topology and host CPU placement are separate settings.

<memory> sets the configured maximum memory allocation at boot, and <currentMemory> sets the initial allocation target. They can be equal, as they are here. Use explicit units so that a value copied into another definition stays unambiguous. <clock offset='utc'/> configures the guest's hardware clock relative to UTC. Under <features>, <acpi/> enables ACPI, which can let the guest handle a virtual power-button event. <apic/> enables the x86 APIC feature. Optional <hyperv> settings expose selected Hyper-V enlightenments, and optional <kvm> settings control selected KVM-specific features, such as hiding the KVM signature from standard discovery with <hidden state='on'/>. This guest uses only the two features shown.

The entries under <devices> describe what the guest can use and which host resources back those devices. Here the disk uses an existing qcow2 file and a virtio disk target. The interface presents a virtio NIC with user-mode networking, so this example needs no named libvirt network. The VNC server listens on host loopback and supplies a graphical display independently of the serial terminal. <serial> provides a host pseudo-terminal for the first serial port, and <console> exposes that port through the libvirt console API. The RNG supplies guest entropy from the host backend shown. For the serial login, prepare the guest to send kernel messages to ttyS0 with console=ttyS0 on its kernel command line and run a login service on that terminal. The host XML supplies the port, while the guest decides what to write to it.

Validate the XML before defining it. virt-xml-validate m11-lab.xml domain checks the file against the domain schema. virsh define --validate m11-lab.xml asks libvirt to validate the XML as it saves the definition. Schema validation can catch an invalid element or attribute. Starting the VM also depends on host resources, such as KVM, readable firmware, and a writable disk. A successful validation establishes the structure of the document. A successful boot establishes that the selected machine can use the resources you gave it.

Domain XML structuredomainname and virtualization typeosmachine, firmware, bootcpu and vcpumodel, topology, countMemory settingsboot maximum and initial allocationclockguest clock offsetfeaturesACPI, APIC, Hyper-V, KVMdevicesdisk, network, display, console, RNGdomainname and virtualization typeosmachine, firmware, bootcpu and vcpumodel, topology, countMemory settingsboot maximum and initialallocationclockguest clock offsetfeaturesACPI, APIC, Hyper-V, KVMdevicesdisk, network, display,console, RNG
A domain definition groups the guest's boot settings, CPU, memory, features, clock, and devices
03

Control the live guest and verify its state

4 min read

define registers a persistent domain. start boots that definition. dominfo gives a summary with fields such as state, vCPU count, and memory. domstats reports named statistics, including state, CPU, and memory groups when the driver supplies them. For a running guest, dumpxml shows the live XML and dumpxml --inactive shows the saved configuration for the next boot. Libvirt can add generated information, such as the UUID and device addresses. edit opens the persistent definition in an editor and applies the saved XML to that definition.

Specify which configuration you mean when a command offers that choice. attach-device and detach-device take an XML file describing the device. For example, attach-device m11-lab extra-disk.xml --live requests hotplug with a <disk> description on a running guest. detach-device can use that same description to identify the device. Use --config for a persistent change, or request both --live and --config where supported. Success depends on the device, driver, and guest. Check the appropriate XML view after each operation, especially when removal completes asynchronously.

setvcpus m11-lab 2 --config sets the count for the next boot within the configured maximum. The --live form requests a vCPU change on the running guest where supported. memtune m11-lab queries host-side memory tuning parameters. With options such as --hard-limit, it can set limits on host memory use for the domain. That limit must account for QEMU overhead as well as guest RAM. The <memory> and <currentMemory> elements describe the memory allocation the VM starts with.

Use suspend to pause guest execution and resume to continue it. A paused VM remains active and retains its resources. reboot requests a guest restart, and shutdown requests an orderly poweroff. Both depend on the available control mechanism and the guest's response. For example, an ACPI shutdown request needs the guest to act on the virtual power-button event. destroy forces the running VM to stop and can lose pending writes. Its persistent definition remains available for another start.

snapshot-create requests a snapshot. You can pass a snapshot XML file, distinct from the domain XML, to name the result. The example requests a snapshot of a running VM with a single writable qcow2 disk and BIOS firmware. Use snapshot-list to confirm that libvirt recorded it. migrate requests a move to another host. For example, virsh -c qemu:///system migrate --live m11-lab qemu+ssh://operator@lab-host/system requests a live move to that destination. It requires a prepared destination, compatible guest settings, and access to the necessary storage. A working SSH connection alone establishes only management connectivity.

A persistent domain's lifecycleShut offRunningPausedTransitionsstartShut offRunningsuspendRunningPausedresumePausedRunningguest shutdown completesRunningShut offShut offRunningPausedTransitionsstartShut offRunningsuspendRunningPausedresumePausedRunningguest shutdown completesRunningShut off
A persistent guest can remain defined while its running state changes

The script below assumes a fresh lab domain name and runs from the directory containing m11-lab.xml. At the console, wait for the guest's serial login prompt, then press Ctrl+] to return to the host shell. Leaving the console keeps the guest running. The script proceeds to the snapshot after the console session ends, so observing the login prompt is the manual boot check. The shutdown loop checks state for up to roughly a minute, plus the time spent on the queries. Its fixed locale makes the state comparison predictable.

bash
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
vm=m11-lab
v=(virsh -c qemu:///system)

virt-xml-validate m11-lab.xml domain
"${v[@]}" define --validate m11-lab.xml
"${v[@]}" start "$vm"
"${v[@]}" console "$vm"

cat > m11-snapshot.xml <<'XML'
<domainsnapshot>
  <name>serial-boot</name>
</domainsnapshot>
XML
"${v[@]}" snapshot-create "$vm" m11-snapshot.xml
"${v[@]}" snapshot-list "$vm"
"${v[@]}" shutdown "$vm"

for ((attempt=0; attempt<30; attempt++)); do
  state=$("${v[@]}" domstate "$vm")
  if [[ $state == 'shut off' ]]; then
    "${v[@]}" list --all
    exit 0
  fi
  sleep 2
done
printf '%s\n' "Timed out waiting for $vm to shut off" >&2
exit 1

If an operation fails after start, inspect the guest state before rerunning the script. If the snapshot already exists, use a fresh snapshot name for another run. On a shutdown timeout, dominfo and the serial console can help you determine whether the guest is still booting, waiting for input, or unable to handle the shutdown request. The final list --all lets you see that the stopped domain still has a persistent definition.

The disk file in the definition persists across starts and shutdowns. The next lesson, qcow2 and backing chains, explains how a guest's disk can read from a base image while recording its writes in a separate file.

Key takeaways

  • A libvirt connection URI selects a driver, a host, and a management instance.
  • A persistent domain has a saved definition, and a running domain also has live configuration.
  • A successful shutdown request can precede the guest reaching the shut off state.
  • The libvirt QEMU driver uses QMP to control and inspect running QEMU processes.
Reflect
  1. Explain to a colleague, in two sentences: select the intended local or remote libvirt connection URI.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close