VIRSH(1)

๐ŸŒธ NAME ๐ŸŒธ

virsh โ€” management user interface, bestie. ๐Ÿ’–

โœจ SYNOPSIS โœจ

virsh [OPTION]... [COMMAND_STRING]

virsh [OPTION]... COMMAND [ARG]...

๐Ÿ’– DESCRIPTION ๐Ÿ’–

Okay so virsh is literally the main interface for managing virsh guest domains. The program can be used to create, pause, and shutdown domains. It can also be used to list current domains. Libvirt is a C toolkit to interact with the virtualization capabilities of recent versions of Linux (and other OSes). It is free software available under the GNU Lesser General Public License. Virtualization of the Linux Operating System means the ability to run multiple instances of Operating Systems concurrently on a single hardware system where the basic resources are driven by a Linux instance. The library aims at providing a long term stable C API. It currently supports Xen, QEMU, KVM, LXC, OpenVZ, VirtualBox and VMware ESX. ๐Ÿฆ‹

The basic structure of most virsh usage is:

virsh [OPTION]... <command> <domain> [ARG]...

Where command is one of the commands listed below; domain is the numeric domain id, or the domain name, or the domain UUID; and ARGS are command specific options. There are a few exceptions to this rule in the cases where the command in question acts on all domains, the entire machine, or directly on the xen hypervisor. Those exceptions will be clear for each of those commands. Note: it is permissible to give numeric names to domains, however, doing so will result in a domain that can only be identified by domain id. In other words, if a numeric value is supplied it will be interpreted as a domain id, not as a name. Any command starting with # is treated as a comment and silently ignored, all other unrecognized commands are diagnosed. ๐Ÿ‘€

The virsh program can be used either to run one COMMAND by giving the command and its arguments on the shell command line, or a COMMAND_STRING which is a single shell argument consisting of multiple COMMAND actions and their arguments joined with whitespace and separated by semicolons or newlines between commands, where unquoted backslash-newline pairs are elided. Within COMMAND_STRING, virsh understands the same single, double, and backslash escapes as the shell, although you must add another layer of shell escaping in creating the single shell argument, and any word starting with unquoted # begins a comment that ends at newline. If no command is given in the command line, virsh will then start a minimal interpreter waiting for your commands, and the quit command will then exit the program. ๐Ÿ’…

Okay bestie, the virsh program understands the following OPTIONS: โœจ

  • -c, --connect URI โ€” Connect to the specified URI, as if by the connect command, instead of the default connection.
  • -d, --debug LEVEL โ€” Enable debug messages at integer LEVEL and above. LEVEL can range from 0 to 4 (default). See the documentation of VIRSH_DEBUG environment variable below for the description of each LEVEL.
  • -e, --escape string โ€” Set alternative escape sequence for console command. By default, telnet's ^] is used. Allowed characters when using hat notation are: alphabetic character, @, [, ], ,, ^, _.
  • -h, --help โ€” Ignore all other arguments, and behave as if the help command were given instead.
  • -k, --keepalive-interval INTERVAL โ€” Set an INTERVAL (in seconds) for sending keepalive messages to check whether connection to the server is still alive. Setting the interval to 0 disables client keepalive mechanism.
  • -K, --keepalive-count COUNT โ€” Set a number of times keepalive message can be sent without getting an answer from the server without marking the connection dead. There is no effect to this setting in case the INTERVAL is set to 0.
  • -l, --log FILE โ€” Output logging details to FILE.
  • -q, --quiet โ€” Avoid extra informational messages.
  • -r, --readonly โ€” Make the initial connection read-only, as if by the --readonly option of the connect command.
  • -t, --timing โ€” Output elapsed time information for each command.
  • --no-pkttyagent โ€” Do not register pkttyagent as authentication agent with the polkit system daemon, even if virsh has been started from a terminal.
  • -v, --version[=short] โ€” Ignore all other arguments, and prints the version of the libvirt library virsh is coming from.
  • -V, --version=long โ€” Ignore all other arguments, and prints the version of the libvirt library virsh is coming from and which options and driver are compiled in.

๐Ÿ“ NOTES ๐Ÿ“

Most virsh operations rely upon the libvirt library being able to connect to an already running libvirtd service. This can usually be done using the command service libvirtd start. ๐Ÿซถ

Most virsh commands require root privileges to run due to the communications channels used to talk to the hypervisor. Running as non root will return an error.

Most virsh commands act synchronously, except maybe shutdown, setvcpus and setmem. In those cases the fact that the virsh program returned, may not mean the action is complete and you must poll periodically to detect that the guest completed the operation. โณ

virsh strives for backward compatibility. Although the help command only lists the preferred usage of a command, if an older version of virsh supported an alternate spelling of a command or option (such as --tunnelled instead of --tunneled), then scripts using that older spelling will continue to work. ๐Ÿ‘‘

Several virsh commands take an optionally scaled integer; if no scale is provided, then the default is listed in the command (for historical reasons, some commands default to bytes, while other commands default to kibibytes). The following case-insensitive suffixes can be used to select a specific scale:

b, byte  byte      1
KB       kilobyte  1,000
k, KiB   kibibyte  1,024
MB       megabyte  1,000,000
M, MiB   mebibyte  1,048,576
GB       gigabyte  1,000,000,000
G, GiB   gibibyte  1,073,741,824
TB       terabyte  1,000,000,000,000
T, TiB   tebibyte  1,099,511,627,776
PB       petabyte  1,000,000,000,000,000
P, PiB   pebibyte  1,125,899,906,842,624
EB       exabyte   1,000,000,000,000,000,000
E, EiB   exbibyte  1,152,921,504,606,846,976

๐Ÿงš GENERIC COMMANDS ๐Ÿงš

The following commands are generic i.e. not specific to a domain. ๐Ÿซถ

๐Ÿ’… help

Syntax:

help [command-or-group]

This lists each of the virsh commands. When used without options, all commands are listed, one per line, grouped into related categories, displaying the keyword for each group.

To display only commands for a specific group, give the keyword for that group as an option. For example:

Example 1:

virsh # help host

Host and Hypervisor (help keyword 'host'):
    capabilities                   capabilities
    cpu-models                     show the CPU models for an architecture
    connect                        (re)connect to hypervisor
    freecell                       NUMA free memory
    hostname                       print the hypervisor hostname
    qemu-attach                    Attach to existing QEMU process
    qemu-monitor-command           QEMU Monitor Command
    qemu-agent-command             QEMU Guest Agent Command
    sysinfo                        print the hypervisor sysinfo
    uri                            print the hypervisor canonical URI

To display detailed information for a specific command, give its name as the option instead. For example:

Example 2:

virsh # help list
  NAME
    list - list domains

  SYNOPSIS
    list [--inactive] [--all]

  DESCRIPTION
    Returns list of domains.

  OPTIONS
    --inactive       list inactive domains
    --all            list inactive & active domains

๐Ÿšช quit, exit

Syntax:

quit
exit

quit this interactive terminal. Bye bestie! ๐Ÿ‘‹

๐Ÿท๏ธ version

Syntax:

version [--daemon]

Will print out the major version info about what this built from. If --daemon is specified then the version of the libvirt daemon is included in the output.

Example:

$ virsh version
Compiled against library: libvirt 1.2.3
Using library: libvirt 1.2.3
Using API: QEMU 1.2.3
Running hypervisor: QEMU 2.0.50

$ virsh version --daemon
Compiled against library: libvirt 1.2.3
Using library: libvirt 1.2.3
Using API: QEMU 1.2.3
Running hypervisor: QEMU 2.0.50
Running against daemon: 1.2.6

๐Ÿ“ cd

Syntax:

cd [directory]

Will change current directory to directory. The default directory for the cd command is the home directory or, if there is no HOME variable in the environment, the root directory. ๐Ÿก

๐Ÿ“ pwd

Syntax:

pwd

Will print the current directory. Literally just tells you where you are. ๐Ÿ’ซ

๐Ÿ”Œ connect

Syntax:

connect [URI] [--readonly]

(Re)-Connect to the hypervisor. When the shell is first started, this is automatically run with the URI parameter requested by the -c option on the command line. The URI parameter specifies how to connect to the hypervisor. The URI docs https://libvirt.org/uri.html list the values supported, but the most common are:

  • xen:///system โ€” this is used to connect to the local Xen hypervisor
  • qemu:///system โ€” connect locally as root to the daemon supervising QEMU and KVM domains
  • qemu:///session โ€” connect locally as a normal user to their own set of QEMU and KVM domains
  • lxc:///system โ€” connect to a local linux container

To find the currently used URI, check the uri command documented below.

For remote access see the URI docs https://libvirt.org/uri.html on how to make URIs. The --readonly option allows for read-only connection.

๐Ÿงญ uri

Syntax:

uri

Prints the hypervisor canonical URI, can be useful in shell mode. ๐Ÿงš

๐Ÿ  hostname

Syntax:

hostname

Print the hypervisor hostname.

๐Ÿงพ sysinfo

Syntax:

sysinfo

Print the XML representation of the hypervisor sysinfo, if available.

๐Ÿ–ฅ๏ธ nodeinfo

Syntax:

nodeinfo

Returns basic information about the node, like number and type of CPU, and size of the physical memory.

Use of this command is strongly discouraged as the information provided is not guaranteed to be accurate on all hardware platforms.

The CPU frequency value merely reflects the speed that the first CPU in the machine is currently running at. This speed may vary across CPUs and changes continually as the host OS throttles. โš ๏ธ

Okay so the data structure we use to fetch all this info? Not extensible, bestie. ๐Ÿ˜ญ It only supports global nodes/sockets/cores/threads topology info (and just FYI, sockets/cores/threads are per NUMA node). So if your host CPU has any further groupings โ€” like dies, clusters, whatever โ€” or if the NUMA topology is non-symmetrical, this data structure literally can't faithfully represent the system. In those cases it just reports a fake topology (nodes = 1, sockets = 1, cores = number of host cpus, threads = 1), which only correctly represents the total host CPU count. ๐Ÿ™ˆ

The recommended replacement? Use the capabilities command, which reports the data (everything except frequency) under the /capabilities/host/topology XPath. Slay. โœจ

nodecpumap

Syntax:

nodecpumap [--pretty]

Displays the node's total number of CPUs, the number of online CPUs, and the list of online CPUs.

With --pretty, the online CPUs are printed as a range instead of a list. Cute! ๐ŸŽ€

nodecpustats

Syntax:

nodecpustats [cpu] [--percent]

Returns cpu stats of the node. If you specify cpu, it'll print the specified cpu statistics only. If you throw in --percent, it prints the percentage of each kind of cpu statistics during 1 second. Iconic. ๐Ÿ”ฅ

nodememstats

Syntax:

nodememstats [cell]

Returns memory stats of the node. If you specify cell, it prints the specified cell statistics only. ๐Ÿ’–

nodesevinfo

Syntax:

nodesevinfo

Reports information about the AMD SEV launch security features for the node, if any. Some of this info is also reported in the domain capabilities XML document. Ngl, kinda niche but we love a secure vibe. ๐Ÿฆ‹

nodesuspend

Syntax:

nodesuspend [target] [duration]

Puts the node (host machine) into a system-wide sleep state and schedules the node's Real-Time-Clock interrupt to resume the node after the time duration specified by duration is out. So basically you're telling the whole host to take a nap. ๐Ÿ˜ด

target specifies the state to which the host will be suspended to. It can be:

  • "mem" โ€” suspend to RAM
  • "disk" โ€” suspend to disk
  • "hybrid" โ€” suspend to both RAM and disk

duration specifies the time duration in seconds for which the host has to be suspended. It should be at least 60 seconds. Don't try to make it shorter, okay? The machine needs its beauty sleep. ๐Ÿ’…

node-memory-tune

Syntax:

node-memory-tune [shm-pages-to-scan] [shm-sleep-millisecs] [shm-merge-across-nodes]

Allows you to display or set the node memory parameters. Let's break it down:

  • shm-pages-to-scan โ€” set the number of pages to scan before the shared memory service goes to sleep
  • shm-sleep-millisecs โ€” set the number of millisecs the shared memory service should sleep before the next scan
  • shm-merge-across-nodes โ€” specifies if pages from different numa nodes can be merged. When set to 0, only pages which physically reside in the memory area of the same NUMA node can be merged. When set to 1, pages from all nodes can be merged. Default to 1.
Note: Currently the "shared memory service" only means KSM (Kernel Samepage Merging). Just so you know. ๐Ÿซถ

capabilities

Syntax:

capabilities [--xpath EXPRESSION] [--wrap]

Print an XML document describing the capabilities of the hypervisor we're currently connected to. This includes a section on the host capabilities in terms of CPU and features, plus a set of descriptions for each kind of guest which can be virtualized. For a more complete description see:

https://libvirt.org/formatcaps.html

The XML also shows the NUMA topology information if available. ๐ŸŒˆ

If the --xpath argument provides an XPath expression, it'll be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, but for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. So organized! ๐Ÿ’…

domcapabilities

Syntax:

domcapabilities [virttype] [emulatorbin] [arch] [machine]
                [--xpath EXPRESSION] [--wrap]
                [--disable-deprecated-features]
                [--expand-cpu-features] [--supported-cpu-features]

Print an XML document describing the domain capabilities for the hypervisor we're connected to, using info either sourced from an existing domain or taken from the virsh capabilities output. This is useful if you're about to create a new domain and you're curious if, for instance, it could make use of VFIO by creating a domain for the hypervisor with a specific emulator and architecture. Basically a vibe check for your future VM. ๐Ÿ‘‘

Each hypervisor will have different requirements regarding which options are required and which are optional. A hypervisor can support providing a default value for any of the options. So no cap, it's flexible. โœจ

Now the deets on each option:

  • virttype โ€” specifies the virtualization type used. The value to be used is either from the 'type' attribute of the <domain/> top level element from the domain XML, or the 'type' attribute found within each <guest/> element from the virsh capabilities output.
  • emulatorbin โ€” specifies the path to the emulator. The value to be used is either the <emulator> element in the domain XML or the virsh capabilities output.
  • arch โ€” specifies the architecture to be used for the domain. The value to be used is either the "arch" attribute from the domain's XML <os/> element and <type/> subelement, or the "name" attribute of an <arch/> element from the virsh capabililites output. (Yes, "capabililites" โ€” that's literally what the original says, don't come for me. ๐Ÿ˜ญ)
  • machine โ€” specifies the machine type for the emulator. The value to be used is either the "machine" attribute from the domain's XML <os/> element and <type/> subelement, or one from a list of machines from the virsh capabilities output for a specific architecture and domain type.

For the QEMU hypervisor, a virttype of either 'qemu' or 'kvm' must be supplied along with either the emulatorbin or arch in order to generate output for the default machine. Supplying a machine value will generate output for the specific machine. Periodt. ๐Ÿ’…

If the --xpath argument provides an XPath expression, it'll be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, but for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node.

The --disable-deprecated-features argument will modify the contents of host-model CPU XML, updating the features list with any features flagged as deprecated for the CPU model by the hypervisor. These features will be paired with the "disable" policy.

The --expand-cpu-features option will cause the host-model CPU definition to contain all required CPU features, including those implicitly enabled by the selected CPU model. Without this flag, features that are part of the CPU model itself will not be listed. So it's like the full package. ๐ŸŽ

The --supported-cpu-features option will update the host-model CPU definition with features that are supported on the host, but will not be enabled by default when starting a domain with host-model CPU. Using both --supported-cpu-features and --expand-cpu-features will provide a complete list of features that can be enabled on the host. Chef's kiss. ๐Ÿ‘จโ€๐Ÿณ๐Ÿ’‹

pool-capabilities

Syntax:

pool-capabilities

Print an XML document describing the storage pool capabilities for the connected storage driver. This is useful if you're about to create a new storage pool and need to know the available pool types and supported storage pool source and target volume formats, as well as the required source elements to create the pool. Knowledge is power, bestie. ๐Ÿ“šโœจ

inject-nmi

Syntax:

inject-nmi domain

Inject NMI to the guest. That's it. That's the whole command. Short and slay. ๐Ÿ’…

list

Syntax:

list [--inactive | --all]
     [--managed-save] [--title]
     { [--table] | --name | --id } [--uuid]
     [--persistent] [--transient]
     [--with-managed-save] [--without-managed-save]
     [--autostart] [--no-autostart]
     [--with-snapshot] [--without-snapshot]
     [--with-checkpoint] [--without-checkpoint]
     [--state-running] [--state-paused]
     [--state-shutoff] [--state-other]

Prints information about existing domains. If no options are specified, it prints out information about running domains. Simple as that. ๐Ÿ’–

Example 1:

An example format for the list is as follows:

``virsh`` list
  Id    Name                           State
----------------------------------------------------
  0     Domain-0                       running
  2     fedora                         paused

Name is the name of the domain. ID the domain numeric id. State is the run state (see below). Iykyk. ๐Ÿ‘€

STATES

The State field lists what state each domain is currently in. A domain can be in one of the following possible states:

  • running โ€” The domain is currently running on a CPU. Main character energy. ๐Ÿ”ฅ
  • idle โ€” The domain is idle, and not running or runnable. This can be caused because the domain is waiting on IO (a traditional wait state) or has gone to sleep because there was nothing else for it to do. Mood. ๐Ÿ˜ด
  • paused โ€” The domain has been paused, usually occurring through the administrator running virsh suspend. When in a paused state, the domain will still consume allocated resources like memory, but will not be eligible for scheduling by the hypervisor. So it's like paused but still eating snacks. ๐Ÿ“
  • in shutdown โ€” The domain is in the process of shutting down, i.e. the guest operating system has been notified and should be in the process of stopping its operations gracefully. It's giving "logging off" vibes. ๐Ÿ’…
  • shut off โ€” The domain is not running. Usually this indicates the domain has been shut down completely, or has not been started. Just sitting there. ๐Ÿ’€
  • crashed โ€” The domain has crashed, which is always a violent ending. Usually this state can only occur if the domain has been configured not to restart on crash. Yikes. ๐Ÿ˜ญ
  • pmsuspended โ€” The domain has been suspended by guest power management, e.g. entered into s3 state. Sleepy time. ๐Ÿฆ‹

Normally only active domains are listed. To list inactive domains, specify --inactive or --all to list both active and inactive domains.

Filtering

To further filter the list of domains, you may specify one or more of the filtering flags supported by the list command. These flags are grouped by function. Specifying one or more flags from a group enables the filter group. Note that some combinations of flags may yield no results. Supported filtering flags and groups:

Persistence

Flag --persistent is used to include persistent guests in the returned list. To include transient guests, specify --transient.

Existence of managed save image

To list domains having a managed save image, specify flag --with-managed-save. For domains that don't have a managed save image, specify --without-managed-save.

Domain state

The following filter flags select a domain by its state: --state-running for running domains, --state-paused for paused domains, --state-shutoff for turned off domains, and --state-other for all other states as a fallback.

๐ŸŒธ Autostarting domains ๐ŸŒธ

Wanna see which domains autostart when your host boots up? Just pass the --autostart flag, bestie. And if you wanna see the ones that have that feature turned off, use --no-autostart. That's it, that's the whole vibe. โœจ

๐Ÿฆ‹ Snapshot existence ๐Ÿฆ‹

Domains that have snapshot images can be listed with the --with-snapshot flag, and domains with no snapshot at all show up with --without-snapshot. Filtering, but make it cute. ๐Ÿ’…

๐ŸŽ€ Checkpoint existence ๐ŸŽ€

Same energy, different feature: domains that have checkpoints get listed with --with-checkpoint, and the checkpoint-less ones with --without-checkpoint.

Lowkey important: when you're talking to older servers, this command is forced to use a series of API calls with an inherent race condition. That means a domain might not be listed at all, or might show up more than once if it changed state between calls while the list was being collected. Newer servers don't have this problem, so if you can upgrade, do it. ๐Ÿ˜ญ

If --managed-save is specified, then domains that have managed save state will instead show as saved in the listing. Fair warning: that state is only possible if they're in the shut off state, so you need to specify --inactive or --all to actually list them. This flag is usable only with the default --table output. Also note that this flag does not filter the list of domains โ€” it just changes how they're displayed.

If --name is specified, domain names are printed instead of the table format, one per line. If --uuid is specified, the domain's UUIDs are printed instead of names. If --id is specified, then the domain's IDs are printed instead of names. But here's the fun part: it's possible to combine --name, --uuid and --id to select only the desired fields for printing. ๐Ÿซถ

The --table flag specifies that the legacy table-formatted output should be used, but it is mutually exclusive with --name and --id. It's the default, and it will be used if neither of --name, --uuid or --id is specified. If neither --name nor --uuid is specified, but --id is, then only active domains are listed โ€” even with the --all parameter โ€” because otherwise the output would just contain a bunch of lines with just -1. Nobody wants that. ๐Ÿ’€ If --table is combined with --uuid, then the domain UUID is printed as an extra column.

If --title is specified, then the short domain description (the title) is printed in an extra column. This flag is usable only with the default --table output.

Example 2:

$ virsh list --title
  Id    Name        State      Title
 -------------------------------------------
  0     Domain-0    running    Mailserver 1
  2     fedora      paused

๐Ÿงš freecell ๐Ÿงš

Syntax:

freecell [{ [--cellno] cellno | --all }]

This one prints the available amount of memory on the machine, or within a NUMA cell, depending on what you ask for. The freecell command can give you one of three different displays of available memory on the machine, based on the options you specify:

  • With no options, it displays the total free memory on the machine.
  • With the --all option, it displays the free memory in each cell and the total free memory on the machine.
  • Finally, with a numeric argument, or with --cellno plus a cell number, it will display the free memory for the specified cell only.

Three moods, one command. Iconic. โœจ

๐Ÿ’œ freepages ๐Ÿ’œ

Syntax:

freepages [{ [--cellno] cellno [--pagesize] pagesize |     --all }]

Prints the available amount of pages within a NUMA cell. cellno refers to the NUMA cell you're interested in. pagesize is a scaled integer (see the NOTES section above, bestie โ€” don't say I didn't warn you). Alternatively, if --all is used, info on each possible combination of NUMA cell and page size is printed out.

๐ŸŒˆ allocpages ๐ŸŒˆ

Syntax:

allocpages [--pagesize] pagesize [--pagecount] pagecount [[--cellno] cellno] [--add] [--all]

This one changes the size of the pages pool of pagesize on the host โ€” so yeah, it's doing actual stuff, not just reading. If --add is specified, then pagecount pages are added into the pool. But if --add wasn't specified, then pagecount is taken as the new absolute size of the pool (which totally may be used to free some pages and size the pool down). The cellno modifier can be used to narrow the modification down to a single host NUMA cell. And on the other end of the spectrum lies --all, which executes the modification on all NUMA cells. Go big or go single-cell, no in-between. ๐Ÿ’…


๐Ÿ”ฅ cpu-baseline ๐Ÿ”ฅ

Syntax:

cpu-baseline FILE [--features] [--migratable]

Computes the baseline CPU that will be supported by all host CPUs given in <file>. (See the hypervisor-cpu-baseline command if you want a CPU that can be provided by a specific hypervisor โ€” different question, different command, iykyk.)

The list of host CPUs is built by extracting all <cpu> elements from the <file>. So the <file> can contain either a set of <cpu> elements separated by new lines, or even a set of complete <capabilities> elements printed by the capabilities command. Flexible. ๐ŸŽ€

If --features is specified, then the resulting XML description will explicitly include all features that make up the CPU โ€” without this option, features that are part of the CPU model will not be listed in the XML description. If --migratable is specified, features that block migration will not be included in the resulting CPU. Migration-friendly CPU, we love to see it.

โญ cpu-compare โญ

Syntax:

cpu-compare FILE [--error] [--validate]

Compares the CPU definition from the XML <file> with the host CPU. (See the hypervisor-cpu-compare command for comparing the CPU definition with the CPU which a specific hypervisor is able to provide on the host โ€” yes, those are different things, stay with me.)

The XML <file> may contain either a host or a guest CPU definition:

  • The host CPU definition is the <cpu> element and its contents as printed by the capabilities command.
  • The guest CPU definition is the <cpu> element and its contents from a domain XML definition, or the CPU definition created from the host CPU model found in domain capabilities XML (printed by the domcapabilities command).

In addition to the <cpu> element itself, this command accepts full domain XML, capabilities XML, or domain capabilities XML containing the CPU definition. For more information on guest CPU definition see: https://libvirt.org/formatdomain.html#elementsCPU.

If --error is specified, the command will return an error when the given CPU is incompatible with the host CPU, and a message providing more details about the incompatibility will be printed out. If --validate is specified, it validates the format of the XML document against an internal RNG schema. Validation girlies, rise. ๐Ÿ™ˆ

๐Ÿ‘‘ cpu-models ๐Ÿ‘‘

Syntax:

cpu-models arch

Prints the list of CPU models known by libvirt for the specified architecture. Now, whether a specific hypervisor is able to create a domain which uses any of the printed CPU models is a separate question โ€” that one can be answered by looking at the domain capabilities XML returned by the domcapabilities command. โœจ

Moreover, for some architectures libvirt does not know any CPU models, and the usable CPU models are only limited by the hypervisor. This command will print that all CPU models are accepted for these architectures, and the actual list of supported CPU models can be checked in the domain capabilities XML.

๐Ÿฆ‹ hypervisor-cpu-compare ๐Ÿฆ‹

Syntax:

hypervisor-cpu-compare FILE [virttype] [emulator] [arch] [machine] [--error] [--validate]

Compares the CPU definition from the XML <file> with the CPU the hypervisor is able to provide on the host. (This is different from cpu-compare, which compares the CPU definition with the host CPU without considering any specific hypervisor and its abilities. Two different vibes, fr fr.)

The XML FILE should contain a guest CPU definition: either the <cpu> element and its contents from a domain XML definition, or a CPU definition created from the host CPU model found in the <mode name="host-model"> element in the domain capabilities XML (printed by the domcapabilities command). Heads up: the <mode name="host-model"> element itself, or even its <cpu> parent element found in domain capabilities XML, is not accepted. The element has to be transformed into an actual CPU definition first. For more information on guest CPU definition see: https://libvirt.org/formatdomain.html#elementsCPU.

Alternatively, this command will automatically extract the CPU definition when provided with a full domain or domain capabilities XML. Convenient! ๐Ÿซถ

For historical reasons the XML FILE may also contain a host CPU definition, but such usage is strongly discouraged as it will most likely provide incorrect results. Like, don't. ๐Ÿ˜ญ

The virttype option specifies the virtualization type (usable in the 'type' attribute of the <domain> top level element from the domain XML). emulator specifies the path to the emulator, arch specifies the CPU architecture, and machine specifies the machine type. If --error is specified, the command will return an error when the given CPU is incompatible with the host CPU, and a message providing more details about the incompatibility will be printed out. If --validate is specified, it validates the format of the XML document against an internal RNG schema.

๐ŸŽ€ hypervisor-cpu-baseline ๐ŸŽ€

Syntax:

hypervisor-cpu-baseline [FILE] [virttype] [emulator] [arch] [machine]
   [--features] [--migratable] [--ignore-host] [model]

Computes a baseline CPU which will be compatible with all CPUs defined in an XML FILE. This command must be called on one of the hosts described in FILE. Calling it on another host results in undefined behavior, because the computed CPU model is influenced by the hypervisor (the result may use an unexpected CPU model, or some features may be disabled even though they are supported on all input CPUs). The undefined behavior can be avoided using the --ignore-host option (see below). ๐Ÿ‘€

This is different from cpu-baseline, which does not consider any hypervisor abilities when computing the baseline CPU.

As an alternative for FILE, in case the XML would only contain a CPU model with no additional features, the CPU model name itself can be passed as model. Exactly one of FILE and model must be used โ€” pick a lane, bestie.

The XML FILE should contain guest CPU definitions created from the host CPU model found in the <mode name="host-model"> element of domain capabilities XMLs (printed by the domcapabilities command on each host). The <mode name="host-model"> elements themselves, or even their <cpu> parent elements found in domain capabilities XMLs, are not accepted. The elements have to be transformed into actual CPU definitions.

Alternatively, this command will automatically extract the CPU definitions when provided with domain capabilities XMLs.

For historical reasons the XML FILE may also contain host CPU definitions, but such usage is strongly discouraged as it will most likely provide incorrect results. Same warning as before, same energy. ๐Ÿ’€

When FILE contains only a single CPU definition, the command will print the same CPU with restrictions imposed by the capabilities of the hypervisor. Specifically: running the virsh hypervisor-cpu-baseline command with no additional options on the result of virsh domcapabilities will transform the host CPU model from domain capabilities XML to a form directly usable in domain XML. Running the command with model (or FILE containing just a single CPU definition with a model and no feature elements) which is marked as unusable in virsh domcapabilities will provide a list of features that block this CPU model from being usable. Diagnostics but make it glam. โœจ

--virttype sets the virtualization type (the kind of thing that goes in the 'type' attribute of the <domain> top-level element in the domain XML, iykyk). --emulator gives the path to the emulator, --arch gives the CPU architecture, and --machine gives the machine type. If you pass --features, the resulting XML description will explicitly include all the features that make up the CPU โ€” without it, features that are part of the CPU model just won't show up in the XML description at all, lowkey invisible ๐Ÿ’…. If you pass --migratable, features that block migration will not be included in the resulting CPU. And if you pass --ignore-host and FILE contains more than one CPU, the command won't consider hypervisor abilities when computing the baseline โ€” with this option, baseline can be safely computed on any host, even hosts that aren't described in FILE. Slay, portability ๐Ÿฆ‹

โœจ hypervisor-cpu-models โœจ

Syntax:

   hypervisor-cpu-models [--virttype virttype] [--emulator emulator]
      [--arch arch] [--machine machine] [--all]

Prints the list of CPU models the hypervisor knows about for the specified architecture. Real talk though: it is not guaranteed that a listed CPU will actually run on the host. To figure out CPU model compatibility with the host, go see virsh hypervisor-cpu-baseline and virsh hypervisor-cpu-compare ๐Ÿซถ

The virttype option specifies the virtualization type (usable in the 'type' attribute of the <domain> top level element from the domain XML). emulator specifies the path to the emulator, arch specifies the CPU architecture, and machine specifies the machine type.

By default, only the models that the hypervisor claims are "usable" on the host get reported. The --all option reports every CPU model known to the hypervisor, including the ones that aren't supported on the hypervisor at all (like, say, newer generation models) ๐Ÿ‘€


๐Ÿ‘‘ DOMAIN COMMANDS ๐Ÿ‘‘

These commands manipulate domains directly โ€” and like we said earlier, most of them take domain as the first parameter. You can specify the domain as a short integer, a name, or a full UUID. Choose your fighter ๐Ÿ’–

๐ŸŽ€ autostart ๐ŸŽ€

Syntax:

   autostart [--disable] [--once] domain

Configures a domain to be automatically started at each boot of the host. The --once option configures the domain to be started only on the next boot of the host.

The --disable option disables the corresponding autostarting. No autostart for you ๐Ÿ™ˆ

Heads up bestie: autostart configured via --once is independent from autostart configured without it. Enabling either of them will cause the VM to be started on the next boot of the host. So like, they stack, but they're separate things โ€” periodt.

๐Ÿ’… blkdeviotune ๐Ÿ’…

Syntax:

   blkdeviotune domain device [[--config] [--live] | [--current]]
      [[total-bytes-sec] | [read-bytes-sec] [write-bytes-sec]]
      [[total-iops-sec] | [read-iops-sec] [write-iops-sec]]
      [[total-bytes-sec-max] | [read-bytes-sec-max] [write-bytes-sec-max]]
      [[total-iops-sec-max] | [read-iops-sec-max] [write-iops-sec-max]]
      [[total-bytes-sec-max-length] |
       [read-bytes-sec-max-length] [write-bytes-sec-max-length]]
      [[total-iops-sec-max-length] |
       [read-iops-sec-max-length] [write-iops-sec-max-length]]
      [size-iops-sec] [group-name]

Sets or queries the block disk I/O parameters for a block device of a domain. device specifies a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain โ€” and yeah, you can peep domblklist for listing these names ๐Ÿ”ฅ

If no limit is specified, it just queries the current I/O limits setting. Otherwise, it alters the limits with these flags:

  • --total-bytes-sec โ€” total throughput limit as a scaled integer; the default is bytes per second if you don't give a suffix.
  • --read-bytes-sec โ€” read throughput limit as a scaled integer; default bytes per second if no suffix.
  • --write-bytes-sec โ€” write throughput limit as a scaled integer; default bytes per second if no suffix.
  • --total-iops-sec โ€” total I/O operations limit per second.
  • --read-iops-sec โ€” read I/O operations limit per second.
  • --write-iops-sec โ€” write I/O operations limit per second.
  • --total-bytes-sec-max โ€” maximum total throughput limit as a scaled integer; default bytes per second if no suffix.
  • --read-bytes-sec-max โ€” maximum read throughput limit as a scaled integer; default bytes per second if no suffix.
  • --write-bytes-sec-max โ€” maximum write throughput limit as a scaled integer; default bytes per second if no suffix.
  • --total-iops-sec-max โ€” maximum total I/O operations limit per second.
  • --read-iops-sec-max โ€” maximum read I/O operations limit per second.
  • --write-iops-sec-max โ€” maximum write I/O operations limit per second.
  • --total-bytes-sec-max-length โ€” duration in seconds to allow the maximum total throughput limit.
  • --read-bytes-sec-max-length โ€” duration in seconds to allow the maximum read throughput limit.
  • --write-bytes-sec-max-length โ€” duration in seconds to allow the maximum write throughput limit.
  • --total-iops-sec-max-length โ€” duration in seconds to allow the maximum total I/O operations limit.
  • --read-iops-sec-max-length โ€” duration in seconds to allow the maximum read I/O operations limit.
  • --write-iops-sec-max-length โ€” duration in seconds to allow the maximum write I/O operations limit.
  • --size-iops-sec โ€” size I/O operations limit per second.
  • --group-name โ€” group name to share I/O quota between multiple drives. For a QEMU domain, if no name is provided, then the default is to have a single group for each device.
Ngl, older versions of virsh only accepted these options with underscore instead of dash, as in --total_bytes_sec. So if you're time-traveling to an old box, that's why it's screaming at you ๐Ÿ˜ญ

Bytes and iops values are independent, but setting only one value (like --read-bytes-sec) resets the other two in that category to unlimited. An explicit 0 also clears any limit. And a non-zero value for a given total cannot be mixed with non-zero values for read or write โ€” pick a lane, bestie ๐Ÿšซ

It's up to the hypervisor to determine how to handle the length values. For the QEMU hypervisor, if an I/O limit value or maximum value is set, then the default value of 1 second will be displayed. Supplying a 0 will reset the value back to the default.

If --live is specified, affect a running guest. If --config is specified, affect the next start of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. When setting the disk io parameters, both --live and --config flags may be given, but --current is exclusive. For querying, only one of --live, --config or --current can be specified. If no flag is specified, behavior is different depending on hypervisor ๐Ÿ‘€

๐ŸŒธ domthrottlegroupset ๐ŸŒธ

Syntax:

   domthrottlegroupset domain group-name [[--config] [--live] | [--current]]
      [[total-bytes-sec] | [read-bytes-sec] [write-bytes-sec]]
      [[total-iops-sec] | [read-iops-sec] [write-iops-sec]]
      [[total-bytes-sec-max] | [read-bytes-sec-max] [write-bytes-sec-max]]
      [[total-iops-sec-max] | [read-iops-sec-max] [write-iops-sec-max]]
      [[total-bytes-sec-max-length] |
       [read-bytes-sec-max-length] [write-bytes-sec-max-length]]
      [[total-iops-sec-max-length] |
       [read-iops-sec-max-length] [write-iops-sec-max-length]]
      [size-iops-sec]

Adds or updates a throttle group against a specific domain. group-name specifies a unique throttle group name, which defines the limit and will be referenced by drives ๐ŸŽฏ

If no limit is specified, it defaults them all as zeros โ€” which will fail, so like, don't do that ๐Ÿ™ˆ Otherwise, set limits with these flags:

  • --total-bytes-sec โ€” total throughput limit as a scaled integer; the default is bytes per second if no suffix is specified.
  • --read-bytes-sec โ€” read throughput limit as a scaled integer; default bytes per second if no suffix.
  • --write-bytes-sec โ€” write throughput limit as a scaled integer; default bytes per second if no suffix.
  • --total-iops-sec โ€” total I/O operations limit per second.
  • --read-iops-sec โ€” read I/O operations limit per second.
  • --write-iops-sec โ€” write I/O operations limit per second.
  • --total-bytes-sec-max โ€” maximum total throughput limit as a scaled integer; default bytes per second if no suffix.
  • --read-bytes-sec-max โ€” maximum read throughput limit as a scaled integer; default bytes per second if no suffix.
  • --write-bytes-sec-max โ€” maximum write throughput limit as a scaled integer; default bytes per second if no suffix.
  • --total-iops-sec-max โ€” maximum total I/O operations limit per second.
  • --read-iops-sec-max โ€” maximum read I/O operations limit per second.
  • --write-iops-sec-max โ€” maximum write I/O operations limit per second.
  • --total-bytes-sec-max-length โ€” duration in seconds to allow the maximum total throughput limit.
  • --read-bytes-sec-max-length โ€” duration in seconds to allow the maximum read throughput limit.
  • --write-bytes-sec-max-length โ€” duration in seconds to allow the maximum write throughput limit.
  • --total-iops-sec-max-length โ€” duration in seconds to allow the maximum total I/O operations limit.
  • --read-iops-sec-max-length โ€” duration in seconds to allow the maximum read I/O operations limit.
  • --write-iops-sec-max-length โ€” duration in seconds to allow the maximum write I/O operations limit.
  • --size-iops-sec โ€” size I/O operations limit per second.

Bytes and iops values are independent, but setting only one value (like --read-bytes-sec) resets the other two in that category to unlimited. An explicit 0 also clears any limit. And a non-zero value for a given total cannot be mixed with non-zero values for read or write. Consistency is the vibe โœจ

It's up to the hypervisor to determine how to handle the length values. For the QEMU hypervisor, if an I/O limit value or maximum value is set, then the default value of 1 second will be displayed. Supplying a 0 will reset the value back to the default.

If --live is specified, affect a running guest. If --config is specified, affect the next start of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. When setting the disk io parameters with both --live and --config specified, both live configuration and config are updated while setting the description โ€” but --current is exclusive. If no flag is specified, behavior is different depending on hypervisor ๐Ÿซถ

๐Ÿฆ‹ domthrottlegroupdel ๐Ÿฆ‹

Syntax:

   domthrottlegroupdel domain group-name [[--config] [--live] | [--current]]

If a Throttlegroup is currently referenced by a disk resource, then trying to remove it will fail โ€” like, it's in use, bestie, hands off ๐Ÿ˜ค. And if the group-name doesn't even exist? Error. Obviously. ๐Ÿ’€

--live means affect a running guest. If the guest isn't running, you get an error, sorry ๐Ÿซ . --config affects the next start of a persistent guest. And --current is basically "you pick" โ€” it's equivalent to either --live or --config, depending on the current state of the guest. Slay, adaptive ๐Ÿ’…


โœจ domthrottlegroupinfo โœจ

Syntax, bestie:

domthrottlegroupinfo domain group-name [[--config] [--live] | [--current]]

This one displays domain Throttlegroup info โ€” including the I/O limits setting, which is the whole point ๐ŸŽ€.

--live โ†’ grab the Throttlegroup data from the running guest. Guest not running? Error, returned to you, boom ๐Ÿ’ฅ. --config โ†’ grab the Throttlegroup data from the next start of a persistent guest. --current, or if you specify neither --live nor --config, โ†’ grab the Throttlegroup data based on the current guest state, which can be either live or offline. And lowkey important ๐Ÿ‘€: if you specify both --live and --config, the --config option takes precedence when getting the current description. Noted, periodt.


๐Ÿฆ‹ domthrottlegrouplist ๐Ÿฆ‹

Syntax:

domthrottlegrouplist domain [--inactive]

Prints a whole table showing the names of all throttle groups associated with domain ๐Ÿ“‹โœจ. And if you throw in --inactive, it queries the Throttlegroup data that'll be used on the next boot, rather than the ones currently in use by a running domain. Sneak peek energy ๐Ÿ”ฎ


๐Ÿ’œ blkiotune ๐Ÿ’œ

Syntax:

blkiotune domain [--weight weight] [--device-weights device-weights]
   [--device-read-iops-sec device-read-iops-sec]
   [--device-write-iops-sec device-write-iops-sec]
   [--device-read-bytes-sec device-read-bytes-sec]
   [--device-write-bytes-sec device-write-bytes-sec]
   [[--config] [--live] | [--current]]

Display or set the blkio parameters, your choice ๐ŸŽ›๏ธ. QEMU/KVM supports --weight. --weight lives in the range [100, 1000]. But after kernel 2.6.39, the value could be in the range [10, 1000] โ€” glow-up for the kernel, glow-up for your range ๐ŸŒˆ.

device-weights is a single string listing one or more device/weight pairs, formatted like this:

/path/to/device,weight,/path/to/device,weight

Each weight is in the range [100, 1000], or [10, 1000] after kernel 2.6.39, or the value 0 to remove that device from per-device listings ๐Ÿ‘‹. Only the devices listed in the string get modified โ€” any existing per-device weights for other devices stay exactly as they were. No collateral damage ๐Ÿซถ.

device-read-iops-sec is a single string listing one or more device/read_iops_sec pairs, in the format:

/path/to/device,read_iops_sec,/path/to/device,read_iops_sec

Each read_iops_sec is a number whose type is unsigned int, and value 0 removes that device from the per-device listing. Only the devices listed in the string are modified; any existing per-device read_iops_sec for other devices remain unchanged ๐Ÿงš.

device-write-iops-sec is a single string listing one or more device/write_iops_sec pairs, in the format:

/path/to/device,write_iops_sec,/path/to/device,write_iops_sec

Each write_iops_sec is a number whose type is unsigned int, value 0 to remove that device from the per-device listing. Only the devices listed in the string are modified; any existing per-device write_iops_sec for other devices remain unchanged โœจ.

device-read-bytes-sec is a single string listing one or more device/read_bytes_sec pairs, in the format:

/path/to/device,read_bytes_sec,/path/to/device,read_bytes_sec

Each read_bytes_sec is a number whose type is unsigned long long, value 0 to remove that device from the per-device listing. Only the devices listed in the string are modified; any existing per-device read_bytes_sec for other devices remain unchanged ๐Ÿ’ซ.

device-write-bytes-sec is a single string listing one or more device/write_bytes_sec pairs, in the format:

/path/to/device,write_bytes_sec,/path/to/device,write_bytes_sec

Each write_bytes_sec is a number whose type is unsigned long long, value 0 to remove that device from the per-device listing. Only the devices listed in the string are modified; any existing per-device write_bytes_sec for other devices remain unchanged ๐ŸŒธ.

Ok so the flag rules, listen up ๐Ÿ‘‚: if --live is specified, affect a running guest. If --config is specified, affect the next start of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive โ€” pick a lane ๐Ÿ’…. And if no flag is specified, the behavior is different depending on hypervisor. iykyk ๐Ÿคทโ€โ™€๏ธ

๐Ÿ”ฅ blockcommit ๐Ÿ”ฅ

Syntax:

blockcommit domain path [bandwidth] [--bytes] [base]
   [--shallow] [top] [--delete] [--keep-relative]
   [--wait [--async] [--verbose]] [--timeout seconds]
   [--active] [{--pivot | --keep-overlay}]

This one reduces the length of a backing image chain by committing changes at the top of the chain (snapshot or delta files) into backing images ๐Ÿ”—โžก๏ธ๐Ÿ“ฆ. By default, it attempts to flatten the entire chain. If base and/or top are specified as files within the backing chain, then the operation is constrained to committing just that portion of the chain. And --shallow can be used instead of base to specify the immediate backing file of the resulting top image to be committed ๐ŸŽฏ.

Heads up, this is the spicy part ๐ŸŒถ๏ธ: the files being committed are rendered invalid, possibly as soon as the operation starts. Using the --delete flag will attempt to remove these invalidated files at the successful completion of the commit operation. And when --keep-relative is used, the backing file paths will be kept relative ๐Ÿซถ.

When top is omitted or specified as the active image, it's also possible to specify --active to trigger a two-phase active commit ๐Ÿ‘‘:

  1. Phase one โ€” top is copied into base, and the job can only be canceled, with top still containing data not yet in base.
  2. Phase two โ€” top and base remain identical until a call to blockjob with the --abort flag (keeping top as the active image that tracks changes from that point in time) or the --pivot flag (making base the new active image and invalidating top).

By default, this command returns as soon as possible, and data for the entire disk is committed in the background โ€” progress can be checked with blockjob ๐Ÿ‘€. However, if --wait is specified, then this command will block until the operation completes (or, for --active, enters the second phase), or until the operation is canceled because the optional timeout in seconds elapses or SIGINT is sent (usually with Ctrl+C) ๐Ÿ˜ญ.

Using --verbose along with --wait will produce periodic status updates ๐Ÿ“Š. If job cancellation is triggered, --async will return control to the user as fast as possible โ€” otherwise the command may continue to block a little while longer until the job is done cleaning up. And, iconic shortcut alert ๐Ÿšจ: using --pivot is shorthand for combining --active --wait with an automatic blockjob --pivot; using --keep-overlay is shorthand for combining --active --wait with an automatic blockjob --abort. Two-for-one, we love to see it ๐Ÿ’–.

path specifies the fully-qualified path of the disk โ€” it corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (see also domblklist for listing these names ๐Ÿ‘€). bandwidth specifies the copying bandwidth limit in MiB/s, although for QEMU it may be non-zero only for an online domain. For further info on the bandwidth argument, see the corresponding section for the blockjob command ๐Ÿ“š.


๐ŸŒˆ blockcopy ๐ŸŒˆ

Syntax:

blockcopy domain path { dest [format] [--blockdev] | --xml file }
   [--shallow] [--reuse-external] [bandwidth]
   [--wait [--async] [--verbose]] [{--pivot | --finish}]
   [--timeout seconds] [granularity] [buf-size] [--bytes]
   [--transient-job] [--synchronous-writes] [--dest-is-zero] [--print-xml]

Copies a disk backing image chain to a destination ๐Ÿ“€โžก๏ธ๐Ÿ“€. Either dest as the destination file name, or --xml with the name of an XML file containing a top-level <disk> element describing the destination, must be present โ€” one of them, no skipping โœ‹.

Also, if dest is given, format should be specified to declare the format of the destination. If format is omitted, then libvirt will reuse the format of the source, or โ€” with --reuse-external โ€” will be forced to probe the destination format, which could be a potential security hole โš ๏ธ๐Ÿ’€. Fr fr, be careful there.

The command supports --raw as a boolean flag synonym for --format=raw. When using dest, the destination is treated as a regular file unless --blockdev is used to signal that it's a block device ๐Ÿงฑ. By default, this command flattens the entire chain; but if --shallow is specified, the copy shares the backing chain.

If --reuse-external is specified, then the destination must exist and have sufficient space to hold the copy. If --shallow is used in conjunction with --reuse-external, then the pre-created image must have guest-visible contents identical to the guest-visible contents of the backing file of the original image โœจ. This may be used to modify the backing file names on the destination ๐ŸŽ€.

By default, the copy job runs in the background and consists of two phases ๐Ÿ•:

  • Initially, the job must copy all data from the source, and during this phase the job can only be canceled to revert back to the source disk, with no guarantees about the destination ๐Ÿ˜ฌ.
  • After this phase completes, both the source and the destination remain mirrored until a call to blockjob with the --abort and --pivot flags pivots over to the copy โ€” or a call without --pivot leaves the destination as a faithful copy of that point in time ๐Ÿ“ธ.

However, if --wait is specified, then this command will block until the mirroring phase begins, or it'll cancel the operation if the optional timeout in seconds elapses or SIGINT is sent (usually with Ctrl+C) ๐Ÿ˜ญ.

Using --verbose along with --wait will produce periodic status updates ๐Ÿ“ˆ. Using --pivot (similar to blockjob --pivot) or --finish (similar to blockjob --abort) implies --wait, and will additionally end the job cleanly rather than leaving things in the mirroring phase โœจ. If job cancellation is triggered by timeout or by --finish, --async will return control to the user as fast as possible โ€” otherwise the command may continue to block a little while longer until the job has actually cancelled ๐Ÿซ .


bestie so path is the fully-qualified path of the disk, and bandwidth is the copying bandwidth limit in MiB/s. Now listen โ€” if you specify a negative value, it gets interpreted as an unsigned long long value that might be essentially unlimited, but more likely would just overflow ๐Ÿ˜ญ so it's safer to use 0 for that purpose. For the whole scoop on the bandwidth argument, see the corresponding section for the blockjob command.

Specifying granularity lets you fine-tune the granularity that gets copied when a dirty region is detected. Larger values trigger less I/O overhead but may end up copying more data overall (the default value is usually correct, fr). Also hypervisors may restrict this to be a power of two or fall within a certain range. Specifying buf-size controls how much data can be simultaneously in-flight during the copy โ€” larger values use more memory but may allow faster completion (again, the default value is usually correct ๐Ÿ’…).

--transient-job lets you say "bestie I do not require the job to be recovered if the VM crashes or is turned off before the job completes." This flag removes the restriction of copy jobs to transient domains if that restriction is applied by the hypervisor.

If --synchronous-writes is specified, the block job will wait for guest writes to be propagated both to the original image and to the destination of the copy, so it's guaranteed that the job converges if the destination storage is slower. Heads up though: this may impact performance of writes while the blockjob is running ๐Ÿซถ

If --dest-is-zero is specified, the hypervisor may assume that the target image was already cleared (any offset reads 0x00 bytes) and thus may skip clearing it. Cheat code energy โœจ

If --print-xml is specified, then the XML used to start the block copy job is printed instead of starting the job.

๐ŸŒˆ blockjob

Syntax:

blockjob domain path { [--abort] [--async] [--pivot] |
   [--info] [--raw] [--bytes] | [bandwidth] }

Manage active block operations. There are three mutually-exclusive modes: --info, bandwidth, and --abort. --async and --pivot imply abort mode; --raw implies info mode; and if no mode was given, --info mode is assumed.

path specifies the fully-qualified path of the disk; it corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (see also domblklist for listing these names).

In --abort mode, the active job on the specified disk will be aborted. If --async is also specified, this command will return immediately rather than waiting for the cancellation to complete. If --pivot is specified, this requests that an active copy or active commit job be pivoted over to the new image.

In --info mode, the active job information on the specified disk will be printed. By default, the output is a single human-readable summary line โ€” and bestie, this format may change in future versions ๐Ÿ˜ฌ Adding --raw lists each field of the struct, in a stable format. If the --bytes flag is set, then the command errors out if the server could not supply bytes/s resolution; when omitting the flag, raw output is listed in MiB/s and human-readable output automatically selects the best resolution supported by the server.

bandwidth can be used to set the bandwidth limit for the active job in MiB/s. If --bytes is specified then the bandwidth value is interpreted in bytes/s. Specifying a negative value is interpreted as an unsigned long value or essentially unlimited. The hypervisor can choose whether to reject the value or convert it to the maximum value allowed. Optionally a scaled positive number may be used as bandwidth (see NOTES above). Using --bytes with a scaled value permits a finer granularity to be selected. A scaled value used without --bytes will be rounded down to MiB/s. Note that --bytes may be unsupported by the hypervisor.

Note that the progress reported for blockjobs corresponding to a pull-mode backup doesn't report progress of the backup but rather usage of temporary space required for the backup. iykyk ๐Ÿ’€

๐Ÿฆ‹ blockpull

Syntax:

blockpull domain path [bandwidth] [--bytes] [base]
   [--wait [--verbose] [--timeout seconds] [--async]]
   [--keep-relative]

Populate a disk from its backing image chain. By default, this command flattens the entire chain; but if base is specified, containing the name of one of the backing files in the chain, then that file becomes the new backing file and only the intermediate portion of the chain is pulled. Once all requested data from the backing image chain has been pulled, the disk no longer depends on that portion of the backing chain. slay ๐Ÿ’…

By default, this command returns as soon as possible, and data for the entire disk is pulled in the background; the progress of the operation can be checked with blockjob. However, if --wait is specified, then this command will block until the operation completes, or cancel the operation if the optional timeout in seconds elapses or SIGINT is sent (usually with Ctrl+C). Using --verbose along with --wait will produce periodic status updates. If job cancellation is triggered, --async will return control to the user as fast as possible โ€” otherwise the command may continue to block a little while longer until the job is done cleaning up.

Using the --keep-relative flag will keep the backing chain names relative.

path specifies the fully-qualified path of the disk; it corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (see also domblklist for listing these names). bandwidth specifies copying bandwidth limit in MiB/s. For further information on the bandwidth argument see the corresponding section for the blockjob command.

๐ŸŽ€ blockresize

Syntax:

blockresize domain path ([size] | [--capacity]) [--extend]

Resize a block device of domain while the domain is running. path specifies the absolute path of the block device; it corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (see also domblklist for listing these names).

The --extend flag instructs the hypervisor to ensure that the new size isn't smaller than the old size, thus preventing (accidental) shrinking of the block device which may lead to data loss. Users are encouraged to always use this flag unless communicating with an older hypervisor. seriously, use it ๐Ÿ™ˆ

For image formats without metadata (raw) stored inside fixed-size storage (e.g. block devices) the --capacity flag can be used to resize the device to the full size of the backing device.

size is a scaled integer (see NOTES above) which defaults to KiB (blocks of 1024 bytes) if there is no suffix. You must use a suffix of "B" to get bytes โ€” and note that for historical reasons, this differs from vol-resize which defaults to bytes without a suffix. iconic inconsistency, no notes ๐Ÿ’€

๐ŸŒธ console

Syntax:

console domain [devname] [--safe] [--force] [--resume]

Connect the virtual serial console for the guest. The optional devname parameter refers to the device alias of an alternate console, serial or parallel device configured for the guest. If omitted, the primary console will be opened.

If the flag --safe is specified, the connection is only attempted if the driver supports safe console handling. This flag specifies that the server has to ensure exclusive access to console devices. Optionally the --force flag may be specified, requesting to disconnect any existing sessions, such as in a case of a broken connection. rude but valid โœจ

If the flag --resume is specified then the guest is resumed after connecting to the console.

๐Ÿ“ cpu-stats

Syntax:

cpu-stats domain [--total] [start] [count]

Provide cpu statistics information of a domain. The domain should be running. Default it shows stats for all CPUs, and a total. Use --total for only the total stats, start for only the per-cpu stats of the CPUs from start, count for only count CPUs' stats.

๐Ÿ‘‘ create

Syntax:

create FILE [--console] [--paused] [--autodestroy]
   [--pass-fds N,M,...] [--validate] [--reset-nvram]

Create a domain from an XML <file>. Optionally, the --validate option can be passed to validate the format of the input XML file against an internal RNG schema (identical to using virt-xml-validate(1) tool). Domains created using this command are going to be either transient (temporary ones that will vanish once destroyed) or existing persistent guests that will run with one-time use configuration, leaving the persistent XML untouched (this can come handy during automated testing of various configurations all based on the original XML). See the example below for usage demonstration.

The domain will be paused if the --paused option is used and supported by the driver; otherwise it will be running. If --console is requested, attach to the console after creation. If --autodestroy is requested, then the guest will be automatically destroyed when virsh closes its connection to libvirt, or otherwise exits.

If --pass-fds is specified, the argument is a comma separated list of open file descriptors which should be passed on into the guest. The file descriptors will be re-numbered in the guest, starting from 3. This is only supported with container based virtualization.

If --reset-nvram is specified, any existing NVRAM/varstore file will be deleted and re-initialized from its pristine template.

Example:

  1. prepare a template from an existing domain (skip directly to 3a if writing one from scratch)
# virsh dumpxml <domain> > domain.xml
  1. edit the template using an editor of your choice and:

a. DO CHANGE! <name> and <uuid> (<uuid> can also be removed), or

b. DON'T CHANGE! either <name> or <uuid>

# $EDITOR domain.xml
  1. create a domain from domain.xml, depending on whether following 2a or 2b respectively:

a. the domain is going to be transient

b. an existing persistent guest will run with a modified one-time configuration

# virsh create domain.xml

๐Ÿ’œ define

Syntax:

define FILE [--validate]

Define a domain from an XML <file>. Optionally, the format of the input XML file can be validated against an internal RNG schema with --validate (identical to using virt-xml-validate(1) tool). The domain definition is registered but not started. If the domain is already running, the changes will take effect on the next boot.

๐Ÿงš desc

Syntax:

desc domain [[--live] [--config] |
   [--current]] [--title] [--edit] [--new-desc
   New description or title message]

...okay so real talk, this one is doing double duty โ€” it shows or modifies the description and title of a domain. And these are literally just user fields, bestie โ€” you can stash arbitrary textual data in there so you can actually tell your domains apart instead of playing "which one is i-2b9f" at 3am ๐Ÿ˜ญ. The title is supposed to be short, but ngl nothing enforces that, live your truth. (See also metadata that works with XML based domain metadata โ€” that's a whole other vibe.)

The flags --live or --config pick whether this command is messing with the live definition or the persistent one. And here's the spicy bit ๐Ÿ‘€ โ€” if you pass both --live and --config, then --config takes precedence when getting the current description, and both the live configuration and the config get updated when setting the description. --current is exclusive and it's implied if you didn't specify any of these three.

Flag --edit means an editor opens up with the contents of the current description or title, and whatever you save gets written back afterwards. Iconic, honestly. โœจ

Flag --title flips the operation over to the title field instead of the description.

And if you pass neither --edit nor --new-desc, the note or description just gets displayed instead of modified. Reading is free, babes.


destroy ๐Ÿ’€

Syntax:

destroy domain [--graceful] [--remove-logs]

This one immediately terminates the domain domain. Like, immediately immediately. It does not give the guest OS any chance to react โ€” it's the equivalent of ripping the power cord out of a physical machine, no cap. In most cases you'll want to use the shutdown command instead, bestie, please.

But here's the thing โ€” this does not delete any storage volumes used by the guest ๐Ÿซถ, and if the domain is persistent, it can be restarted later.

If domain is transient, then the metadata of any snapshots will be lost once the guest stops running ๐Ÿ˜ญ โ€” but the snapshot contents still exist, and a new domain with the same name and UUID can restore the snapshot metadata with snapshot-create. Same energy for checkpoints: their metadata will be lost, but they can be restored with checkpoint-create.

  • --graceful โ€” don't resort to extreme measures (e.g. SIGKILL) when the guest doesn't stop after a reasonable timeout; return an error instead. Very demure, very mindful.
  • --remove-logs โ€” remove per domain log files. Heads up though: not all deployment configuration can be supported. In case of QEMU the flag is only supported if virlogd is used to handle QEMU process output. Otherwise the flag is just... ignored ๐Ÿ™ˆ.

domblkerror ๐Ÿงฑ

Syntax:

domblkerror domain

Shows errors on block devices. This one comes in clutch when domstate says a domain was paused due to I/O error โ€” domblkerror then lists all block devices in the error state plus the error seen on each of them. Detective mode ๐Ÿ”.


domblkinfo ๐Ÿ“

Syntax:

domblkinfo domain [block-device --all] [--human]

Gets block device size info for a domain. A block-device corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (see also domblklist for listing these names ๐Ÿ‘€).

  • --human โ€” output comes out human readable, because raw bytes are giving "1.7 billion" and nobody wants that.
  • --all โ€” output becomes a table showing all block devices size info associated with domain.

And watch out: the --all option takes precedence over the others. It said what it said ๐Ÿ’….


domblklist ๐Ÿ“‹

Syntax:

domblklist domain [--inactive] [--details]

Prints a table showing the brief info of all block devices hanging out with domain.

  • --inactive โ€” query the block devices that will be used on the next boot, rather than the ones currently in use by a running domain.
  • --details โ€” also print the disk type and device value.

Other contexts that need a block device name (like domblkinfo or snapshot-create for disk snapshots) will accept either target or unique source names printed by this command. Convenient? Obsessed. ๐Ÿ’–


domblkstat ๐Ÿ“Š

Syntax:

domblkstat domain [block-device] [--human]

Get device block stats for a running domain. A block-device corresponds to a unique target name (<target dev='name'/>) or source file (<source file='name'/>) for one of the disk devices attached to domain (again, domblklist lists these names for you). On a LXC or QEMU domain, omitting the block-device gives you device block stats summarily for the entire domain ๐ŸŒˆ.

Use --human for a more human readable output.

Availability of these fields is hypervisor-dependent, so unsupported fields are just missing from the output, and other fields may show up if you're talking to a newer version of libvirtd. Not a bug, it's a feature vibe.

Explanation of fields (they appear in the following order):

  • rd_req โ€” count of read operations
  • rd_bytes โ€” count of read bytes
  • wr_req โ€” count of write operations
  • wr_bytes โ€” count of written bytes
  • errs โ€” error count
  • flush_operations โ€” count of flush operations
  • rd_total_times โ€” total time read operations took (ns)
  • wr_total_times โ€” total time write operations took (ns)
  • flush_total_times โ€” total time flush operations took (ns)
  • <-- other fields provided by hypervisor -->

domblkthreshold ๐Ÿšจ

Syntax:

domblkthreshold domain dev threshold

Sets the threshold value for delivering the block-threshold event. dev specifies the disk device target or backing chain element of the given device using the 'target[1]' syntax ๐ŸŽฏ. threshold is a scaled value of the offset โ€” and if the block device should write beyond that offset, the event gets delivered. Like a little alarm bell for your disk, iykyk.


domcontrol ๐ŸŽ›๏ธ

Syntax:

domcontrol domain

Returns the state of the interface to the VMM that's used to control a domain. And for states other than "ok" or "error", the command also prints the number of seconds elapsed since the control interface entered its current state. Time stamp energy โฑ๏ธ.


domdirtyrate-calc ๐Ÿงฎ

Syntax:

domdirtyrate-calc <domain> [--seconds <sec>]
   --mode=[page-sampling | dirty-bitmap | dirty-ring]

Calculates an active domain's memory dirty rate โ€” which is exactly what you'd wanna know when deciding whether it's proper to be migrated out or not ๐Ÿ‘‘. The seconds parameter lets you calculate the dirty rate over a specific time, which currently allows 60s at most, and it defaults to 1s if missing.

These three modes โ€” page-sampling, dirty-bitmap, and dirty-ring โ€” are mutually exclusive and alternative when you specify the calculation mode, and page-sampling is the default mode if missing. The calculated dirty rate info is then available by calling domstats --dirtyrate. Slay.


domdisplay ๐Ÿ–ฅ๏ธ

Syntax:

domdisplay domain [--include-password] [[--type] type] [--all]

Outputs a URI you can use to connect to the graphical display of the domain via VNC, SPICE or RDP. You pick the particular graphical display type with the type parameter (e.g. "vnc", "spice", "rdp").

  • --include-password โ€” the SPICE channel password gets included in the URI ๐Ÿ”‘
  • --all โ€” show all possible graphical displays, since a VM could totally have more than one ๐ŸŒธ

domdisplay-reload ๐Ÿ”„

Syntax:

domdisplay-reload <domain> [--type <type>]

Reloads the domain's graphical display โ€” specifically, it reloads its TLS certificates without restarting the domain. Main character energy, no downtime ๐Ÿ’…. type can be any constant from the virDomainGraphicsReloadType enum. By default any supported type is reloaded (so far only VNC).


domfsfreeze ๐ŸงŠ

Syntax:

domfsfreeze domain [[--mountpoint] mountpoint...]

Freezes mounted filesystems within a running domain to prepare for consistent snapshots. Yes, like putting them on ice ๐ŸงŠ.

The --mountpoint option takes a parameter mountpoint, which is a mount point path of the filesystem to be frozen. And it can occur multiple times, so go wild. If this is not specified, every mounted filesystem is frozen.

Note: the snapshot-create command has a --quiesce option to freeze and thaw the filesystems automatically to keep snapshots consistent. domfsfreeze is only needed when a user wants to utilize the native snapshot features of storage devices not supported by libvirt.

domfsinfo ๐Ÿ“‚

Syntax:

domfsinfo domain

Shows a list of mounted filesystems within the running domain. The list contains mountpoints, names of a mounted device in the guest, filesystem types, and unique target names used in the domain XML (<target dev='name'/>). The full receipt, basically ๐Ÿงพ.

Note: this command requires a guest agent configured and running in the domain's guest OS. No agent, no info, sorry babe ๐Ÿ™ˆ.

domfsthaw ๐Ÿ”ฅ

Syntax:

domfsthaw domain [[--mountpoint] mountpoint...]

Thaws mounted filesystems within a running domain โ€” the ones that were frozen by domfsfreeze. Un-ice them ๐Ÿ”ฅ.

The --mountpoint option takes a parameter mountpoint, which is a mount point path of the filesystem to be thawed. This option can occur multiple times. If this is not specified, every mounted filesystem is thawed.


domfstrim ๐Ÿ—‘๏ธ

Syntax:

domfstrim domain [--minimum bytes] [--mountpoint mountPoint]

Issues a fstrim command on all mounted filesystems within a running domain, and it discards blocks which are not in use by the filesystem. Bye bye, garbage ๐Ÿ—‘๏ธ.

If --minimum bytes is specified, it tells the guest kernel the length of a contiguous free range โ€” anything smaller than this may be ignored (this is a hint and the guest may not respect it). And by increasing this value, the fstrim operation will complete more quickly for filesystems with badly fragmented free space, although not all blocks will be discarded. The default value is zero, meaning "discard every free block". Also, if you only want to trim one mount point, you can specify it via the optional --mountpoint parameter. Considerate ๐ŸŽ€.


domhostname ๐Ÿ 

Syntax:

domhostname domain [--source lease|agent]

Returns the hostname of a domain, if the hypervisor makes it available (if it doesn't... well ๐Ÿ’€).

The --source argument specifies what data source to use for the hostnames โ€” currently 'lease' to read DHCP leases, or 'agent' to query the guest OS via an agent. If unspecified, the driver returns the default method available (some drivers support only one type of source, so it's not like you have options everywhere).


domid ๐Ÿ†”

Syntax:

domid domain-name-or-uuid

Converts a domain name (or UUID) to a domain id. Small command, huge service. Periodt.


Syntax:

domif-getlink domain interface-device [--config]

Queries the link state of the domain's virtual interface. If --config is specified, it queries the persistent configuration โ€” and for compatibility purposes, --persistent is an alias of --config (yes, both names, same energy).

interface-device can be the interface's target name or the MAC address.


Syntax:

domif-setlink domain interface-device state [--config] [--print-xml]

Modifies the link state of the domain's virtual interface. Possible values for state are "up" and "down" โ€” that's it, that's the whole menu.

If --config is specified, only the persistent configuration of the domain is modified. For compatibility purposes, --persistent is an alias of --config. And interface-device can be the interface's target name or the MAC address.

If --print-xml is specified, then the XML used to update the interface is printed instead. Show me the receipts ๐Ÿ“œ.


domifaddr ๐ŸŒ

Syntax:

domifaddr domain [interface] [--full]
   [--source lease|agent|arp]

okay so this one gets a list of the interfaces of a running domain, all their IPs and MAC addresses, and honestly it's giving main character energy ๐Ÿ’… โ€” or you can limit the output to just one interface if you pass interface. Lowkey important: interface is driver dependent, bestie. It might be the name inside the guest OS, or the name you'd see in the domain XML. And heads up โ€” under some hypervisors (notably QEMU) the whole command may require a guest agent to be configured for the domain you're querying ๐Ÿ™ˆ.

If --full is specified, the interface name and MAC address are always displayed when the interface has multiple IP addresses or aliases โœจ. Otherwise, only the interface name and MAC address are displayed for the first name and MAC address, with - for the others that use the same name and MAC address.

The --source argument says what data source to use for the addresses, and currently your options are 'lease' to read DHCP leases, 'agent' to query the guest OS via an agent, or 'arp' to get IP from host's arp tables ๐ŸŒˆ. If unspecified, 'lease' is the default, no cap.


backup-begin ๐ŸŽฌ

Syntax:

backup-begin domain [backupxml] [checkpointxml] [--reuse-external]
    [--preserve-domain-on-shutdown]

Begin a new backup job, bestie โ€” we're doing this ๐Ÿ’–. If backupxml is omitted, this defaults to a full backup using a push model to filenames generated by libvirt. Supplying XML lets you fine-tune stuff like requesting an incremental backup relative to an earlier checkpoint, controlling which disks participate or which filenames are involved, or requesting the use of a pull model backup. The backup-dumpxml command shows any resulting values assigned by libvirt ๐Ÿ‘‘. For more info on backup XML, see: https://libvirt.org/formatbackup.html

If --reuse-external is used, it instructs libvirt to reuse temporary and output files provided by the user in backupxml โ™ป๏ธ.

When the --preserve-domain-on-shutdown flag is used, libvirt will not terminate the VM if the guest OS shuts down while the backup is running. The VM will instead be kept in VIR_DOMAIN_PAUSED state until the backup job finishes. The vm can also be resumed in order to boot again ๐Ÿซถ.

If checkpointxml is specified, a second file with a top-level element of domaincheckpoint is used to create a simultaneous checkpoint, for doing a later incremental backup relative to the time the backup was created. See checkpoint-create for more details on checkpoints.

This command returns as soon as possible, and the backup job runs in the background ๐Ÿƒโ€โ™€๏ธ. The progress of a push model backup can be checked with domjobinfo or by waiting for an event with event (the progress of a pull model backup is under the control of whatever third party connects to the NBD export, iykyk). The job is ended with domjobabort.

backup-dumpxml ๐Ÿ“œ

Syntax:

backup-dumpxml [--xpath EXPRESSION] [--wrap] domain

Output XML describing the current backup job, periodt.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed โœจ. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node ๐ŸŽ€.

domiflist ๐Ÿงš

Syntax:

domiflist domain [--inactive]

Print a table showing the brief information of all virtual interfaces associated with domain. If --inactive is specified, query the virtual interfaces that will be used on the next boot, rather than those currently in use by a running domain ๐Ÿ’ค. Other contexts that require a MAC address of a virtual interface (such as detach-interface or domif-setlink) will accept the MAC address printed by this command ๐Ÿ‘‘.

domifstat ๐Ÿ“Š

Syntax:

domifstat domain interface-device

Get network interface stats for a running domain. The network interface stats are only available for interfaces that have a physical source interface ๐Ÿซ . This does not include, for example, a 'user' interface type, since it is a virtual LAN with NAT to the outside world. interface-device can be the interface target by name or MAC address. Please note: for an unmanaged ethernet type, returned stats might have RX/TX swapped ๐Ÿ’€ โ€” yeah, literally swapped, watch out.

domiftune ๐ŸŽš๏ธ

Syntax:

domiftune domain interface-device [[--config] [--live] | [--current]]
   [*--inbound average,peak,burst,floor*]
   [*--outbound average,peak,burst*]

Set or query the domain's network interface's bandwidth parameters ๐Ÿ’…. interface-device can be the interface's target name (<target dev='name'/>), or the MAC address.

If no --inbound or --outbound is specified, this command will query and show the bandwidth settings. Otherwise, it will set the inbound or outbound bandwidth. average,peak,burst,floor is the same as in command attach-interface. Values for average, peak and floor are expressed in kiB per second, while burst is expressed in kiB in a single burst at peak speed, as described in the Network XML documentation at https://libvirt.org/formatnetwork.html#quality-of-service โœจ.

To clear inbound or outbound settings, use --inbound or --outbound respectfully with average value of zero ๐Ÿงผ.

If --live is specified, affect a running guest. If --config is specified, affect the next start of a persistent guest. If --current is specified, it is equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive ๐Ÿšซ. If no flag is specified, behavior is different depending on hypervisor โ€” iykyk.

domifannounce ๐Ÿ“ข

Syntax

domifannounce domain [interface-device] [parameters]

Request that a domain inject "gratuitous" ARP responses into the outbound data stream of a specific network interface of the domain โ€” or, if no interface-device is given, inject ARP responses on the outbound data stream of all interfaces of the domain ๐ŸŒˆ. This can be helpful to re-sync network switches in the broadcast domain of said interfaces when the network topology has changed. This is usually done automatically when a domain is started, or after it has migrated (for example, that is the behavior of QEMU), but a more complicated setup where the topology changes around an already active domain (or possibly all the plumbing isn't yet connected and passing traffic at the time the automatic announcement takes place) might benefit from a manually triggered announce ๐Ÿ‘‘.

The optional parameters are:

  • --initial n โ€” initial delay before first announcement (milliseconds) default: 50
  • --max n โ€” maximum delay between announcements (milliseconds) default: 550
  • --rounds n โ€” total number of announcements default: 5
  • --step n โ€” increment added to delay (milliseconds) after each announcement default 50

dominfo ๐Ÿ”

Syntax:

dominfo domain

Returns basic information about the domain. That's it, that's the whole vibe ๐ŸŽ€.

domjobabort ๐Ÿ›‘

Syntax:

domjobabort domain [--postcopy]

Abort the currently running domain job. Bye bestie ๐Ÿ‘‹.

When the job to be aborted is a migration which entered post-copy mode, it cannot be aborted, because none of the hosts involved in migration has a complete state of the domain ๐Ÿ’€. Optional --postcopy can be used to interrupt such migration, although doing so may effectively suspend the domain until the migration is resumed (see also --postcopy-resume option of migrate) ๐Ÿ™ˆ.

domjobinfo ๐Ÿ“ˆ

Syntax:

domjobinfo domain [--completed [--keep-completed]] [--anystats] [--rawstats]

Returns information about jobs running on a domain. --completed tells virsh to return information about a recently finished job. Statistics of a completed job are automatically destroyed once read (unless --keep-completed is used) or when libvirtd is restarted ๐Ÿซ .

Normally only statistics for running and successful completed jobs are printed. --anystats can be used to also display statistics for failed jobs ๐Ÿ’”.

In case --rawstats is used, all fields are printed as received from the server, without any attempts to interpret the data ๐Ÿ‘€. The "Job type:" field is special, since it's reported by the API and not part of stats.

Note that time information returned for completed migrations may be completely irrelevant unless both source and destination hosts have synchronized time (i.e., NTP daemon is running on both of them) โฐ.

domlaunchsecinfo ๐Ÿ”

Syntax:

domlaunchsecinfo domain

Returns information about the launch security parameters associated with a running domain.

The set of parameters reported will vary depending on which type of launch security protection is active ๐ŸŒธ. If none is active, no parameters will be reported.

domsetlaunchsecstate ๐Ÿ”’

Syntax:

domsetlaunchsecstate domain --secrethdr hdr-filename
    --secret secret-filename [--set-address address]

Set a launch security secret in the guest's memory ๐Ÿง โœจ. The guest must have a launchSecurity type enabled in its configuration and be in a paused state. On success, the guest can be transitioned to a running state. On failure, the guest should be destroyed ๐Ÿ’€ โ€” no cap, that's the rule.

--secrethdr specifies a filename containing the base64-encoded secret header. The header includes artifacts needed by the hypervisor firmware to recover the plain text of the launch secret. --secret specifies the filename containing the base64-encoded encrypted launch secret ๐Ÿ”.

The --set-address option can be used to specify a physical address within the guest's memory to set the secret. If not specified, the address will be determined by the hypervisor ๐Ÿซถ.

dommemstat ๐Ÿง 

Syntax:

dommemstat domain [--period seconds] [[--config] [--live] | [--current]]

Get memory stats for a running domain ๐Ÿ“Š.

Availability of these fields depends on hypervisor. Unsupported fields are missing from the output. Other fields may appear if communicating with a newer version of libvirtd โœจ.

Explanation of fields, bestie:

  • swap_in โ€” The amount of data read from swap space (in KiB)
  • swap_out โ€” The amount of memory written out to swap space (in KiB)
  • major_fault โ€” The number of page faults where disk IO was required
  • minor_fault โ€” The number of other page faults
  • unused โ€” The amount of memory left unused by the system (in KiB)
  • available โ€” The amount of usable memory as seen by the domain (in KiB)
  • actual โ€” Current balloon value (in KiB)
  • rss โ€” Resident Set Size of the running domain's process (in KiB)
  • usable โ€” The amount of memory which can be reclaimed by balloon without causing host swapping (in KiB)
  • last-update โ€” Timestamp of the last update of statistics (in seconds)
  • disk_caches โ€” The amount of memory that can be reclaimed without additional I/O, typically disk caches (in KiB)
  • hugetlb_pgalloc โ€” The number of successful huge page allocations initiated from within the domain
  • hugetlb_pgfail โ€” the number of huge page allocations that failed, counted from inside the domain ๐Ÿซ 

Okay so now the balloon tea โ˜๏ธ: for QEMU/KVM with a memory balloon, if you set the optional --period to something bigger than 0 (it's in seconds), the balloon driver will hand over extra statistics, and those show up in the next dommemstat runs. Set --period to 0 and the balloon driver stops collecting โ€” but heads up, it does not wipe the stats already sitting in the balloon driver. This whole thing needs at least QEMU/KVM 1.5 running on the host, no cap.

The --live, --config, and --current flags are only valid when you're using the --period option, and their whole job is setting the collection period for the balloon driver. --live = only the running guest's collection period gets touched. --config = affects the next start of a persistent guest. --current = equivalent to either --live or --config, depending on what state the guest is in right now.

You can pass both --live and --config together ๐Ÿ’… but --current is exclusive โ€” it does not share the aux cord. And if you pass no flag at all, the behavior changes depending on the guest state.


๐Ÿท๏ธ domname

Syntax:

domname domain-id-or-uuid

Converts a domain Id (or UUID) into the domain name. That's it, that's the whole gig โœจ


๐Ÿ˜ด dompmsuspend

Syntax:

dompmsuspend domain target [--duration]

Suspends a running domain into one of these states โ€” these are your possible target values, bestie:

  • mem โ€” the equivalent of the S3 ACPI state
  • disk โ€” the equivalent of the S4 ACPI state
  • hybrid โ€” RAM gets saved to disk but the power is not cut

The --duration argument says how many seconds to wait before the domain gets woken up after being suspended (peep dompmwakeup too ๐Ÿ‘€). Default is 0, which means unlimited suspend time. (Real talk: this feature isn't currently supported by any hypervisor driver, so just use 0.)

Note that this command requires a guest agent configured and running inside the domain's guest OS. No agent, no vibes.
โš ๏ธ Beware โ€” at least for QEMU, the domain's process gets terminated when the disk target is used, and a brand new process gets launched when libvirt is asked to wake the domain back up. Because of that, any runtime changes โ€” device hotplug, memory settings, all of it โ€” are lost unless you made those changes with the --config flag. Reactive, not proactive ๐Ÿ’€

โฐ dompmwakeup

Syntax:

dompmwakeup domain

Wakes a domain up from the pmsuspended state (whether it got suspended by dompmsuspend or from the guest itself). It injects a wakeup into the guest that's sitting in pmsuspended state instead of waiting around for the previously requested duration (if there even was one) to tick down. And fun fact: this operation doesn't necessarily fail if the domain is already running. It said "not necessarily," so don't come for me ๐ŸŒธ


โœ๏ธ domrename

Syntax:

domrename domain new-name

Renames a domain. It switches the current domain name over to the new name you put in the second argument. Iconic, lowkey.

Note: the domain must be inactive. Inactive. Asleep. Not running. Periodt.

๐Ÿ” domstate

Syntax:

domstate domain [--reason]

Returns state info about a domain. And --reason tells virsh to also print the reason for that state โ€” the why behind the what ๐Ÿงš


๐Ÿ“Š domstats

Syntax:

domstats [--raw] [--enforce] [--backing] [--nowait] [--state]
   [--cpu-total] [--balloon] [--vcpu] [--interface]
   [--block] [--perf] [--iothread] [--memory] [--dirtyrate] [--vm]
   [[--list-active] [--list-inactive]
    [--list-persistent] [--list-transient] [--list-running]y
    [--list-paused] [--list-shutoff] [--list-other]] | [domain ...]

Gets statistics for multiple domains, or literally all of them. No argument at all? You get every available statistic for every domain. Full send ๐Ÿ”ฅ

The list of domains to gather stats for can be limited either by listing the domains as a space separated list, or by specifying one of the filtering flags --list-NNN. (You can't combine the two approaches โ€” pick a lane, bestie.)

By default some of the returned fields may get converted into more human-friendly values by a set of pretty-printers. Want to suppress that? That's what --raw is for ๐ŸŽ€

The individual statistics groups are selectable via specific flags. By default all supported statistics groups are returned. The supported statistics groups flags are: --state, --cpu-total, --balloon, --vcpu, --interface, --block, --perf, --iothread, --memory, --dirtyrate, --vm.

Note that โ€” depending on the hypervisor type and version, or the domain state โ€” not all of the following statistics may be returned. It's giving "results may vary," and that's just how it is ๐Ÿ˜ญ

When you select the --state group, these fields come back:

  • state.state โ€” state of the VM, returned as a number from the virDomainState enum
  • state.reason โ€” reason for entering the given state, returned as an int from the virDomain*Reason enum matching that state

--cpu-total returns:

  • cpu.time โ€” total cpu time spent for this domain, in nanoseconds
  • cpu.user โ€” user cpu time spent, in nanoseconds
  • cpu.system โ€” system cpu time spent, in nanoseconds
  • cpu.haltpoll.success.time โ€” cpu halt polling success time spent, in nanoseconds
  • cpu.haltpoll.fail.time โ€” cpu halt polling fail time spent, in nanoseconds
  • cpu.cache.monitor.count โ€” the number of cache monitors for this domain
  • cpu.cache.monitor.<num>.name โ€” the name of cache monitor <num>
  • cpu.cache.monitor.<num>.vcpus โ€” vcpu list of cache monitor <num>
  • cpu.cache.monitor.<num>.bank.count โ€” the number of cache banks in cache monitor <num>
  • cpu.cache.monitor.<num>.bank.<index>.id โ€” host allocated cache id for bank <index> in cache monitor <num>
  • cpu.cache.monitor.<num>.bank.<index>.bytes โ€” the number of bytes of last level cache that the domain is using on cache bank <index>

--balloon returns:

  • balloon.current โ€” the memory in KiB currently used
  • balloon.maximum โ€” the maximum memory in KiB allowed
  • balloon.swap_in โ€” the amount of data read from swap space (in KiB)
  • balloon.swap_out โ€” the amount of memory written out to swap space (in KiB)
  • balloon.major_fault โ€” the number of page faults when disk IO was required
  • balloon.minor_fault โ€” the number of other page faults
  • balloon.unused โ€” the amount of memory left unused by the system (in KiB)
  • balloon.available โ€” the amount of usable memory as seen by the domain (in KiB)
  • balloon.rss โ€” Resident Set Size of the running domain's process (in KiB)
  • balloon.usable โ€” the amount of memory which can be reclaimed by balloon without causing host swapping (in KiB)
  • balloon.last-update โ€” timestamp of the last update of statistics (in seconds)
  • balloon.disk_caches โ€” the amount of memory that can be reclaimed without additional I/O, typically disk (in KiB)
  • balloon.hugetlb_pgalloc โ€” the number of successful huge page allocations from inside the domain via virtio balloon
  • balloon.hugetlb_pgfail โ€” the number of failed huge page allocations from inside the domain via virtio balloon

--vcpu returns:

  • vcpu.current โ€” current number of online virtual CPUs
  • vcpu.maximum โ€” maximum number of online virtual CPUs
  • vcpu.<num>.state โ€” state of the virtual CPU <num>, as a number from the virVcpuState enum
  • vcpu.<num>.time โ€” virtual cpu time spent by virtual CPU <num> (in nanoseconds)
  • vcpu.<num>.wait โ€” time the vCPU <num> thread was waiting in the runqueue because the scheduler has something else running ahead of it (in nanoseconds); requires CONFIG_SCHED_INFO on Linux
  • vcpu.<num>.halted โ€” virtual CPU <num> is halted: yes or no (may indicate the processor is idle or even disabled, depending on the architecture)
  • vcpu.<num>.delay โ€” time the vCPU <num> thread was waiting in the runqueue because the scheduler has something else running ahead of it (in nanoseconds). Exposed to the VM as a steal time.

This group of statistics also reports extra hypervisor-originating per-vCPU stats. The hypervisor-specific statistics in this group follow this naming scheme:

vcpu.<num>.$NAME.$TYPE

$NAME  name of the statistics field provided by the hypervisor

$TYPE  Type of the value. The following types are returned:

       cur    current instant value

       sum    aggregate value

       max    peak value

The returned value may be either an unsigned long long or a boolean. The meaning is hypervisor specific. Please see the disclaimer for the --vm group, which also consists of hypervisor-specific stats ๐Ÿ‘‘ (yes, the disclaimer is in another castle, keep reading later parts).

--interface returns:

  • net.count โ€” number of network interfaces on this domain
  • net.<num>.name โ€” name of the interface <num>
  • net.<num>.rx.bytes โ€” number of bytes received
  • net.<num>.rx.pkts โ€” number of packets received
  • net.<num>.rx.errs โ€” number of receive errors
  • net.<num>.rx.drop โ€” number of receive packets dropped
  • net.<num>.tx.bytes โ€” number of bytes transmitted
  • net.<num>.tx.pkts โ€” number of packets transmitted
  • net.<num>.tx.errs โ€” number of transmission errors
  • net.<num>.tx.drop โ€” number of transmit packets dropped

--perf returns the statistics of all enabled perf events:

  • perf.cmt โ€” the cache usage in Byte currently used
  • perf.mbmt โ€” total system bandwidth from one level of cache
  • perf.mbml โ€” bandwidth of memory traffic for a memory controller
  • perf.cpu_cycles โ€” the count of cpu cycles (total/elapsed)
  • perf.instructions โ€” the count of instructions
  • perf.cache_references โ€” the count of cache hits
  • perf.cache_misses โ€” the count of caches misses
  • perf.branch_instructions โ€” the count of branch instructions
  • perf.branch_misses โ€” the count of branch misses
  • perf.bus_cycles โ€” the count of bus cycles
  • perf.stalled_cycles_frontend โ€” the count of stalled frontend cpu cycles
  • perf.stalled_cycles_backend โ€” the count of stalled backend cpu cycles
  • perf.ref_cpu_cycles โ€” the count of ref cpu cycles
  • perf.cpu_clock โ€” the count of cpu clock time
  • perf.task_clock โ€” the count of task clock time
  • perf.page_faults โ€” the count of page faults
  • perf.context_switches โ€” the count of context switches
  • perf.cpu_migrations โ€” the count of cpu migrations
  • perf.page_faults_min โ€” the count of minor page faults
  • perf.page_faults_maj โ€” the count of major page faults
  • perf.alignment_faults โ€” the count of alignment faults
  • perf.emulation_faults โ€” the count of emulation faults

See the perf command for more details about each event ๐Ÿงšโ€โ™€๏ธ

--block returns information about the disks associated with each domain. Using the --backing flag extends this information to cover all the resources in the backing chain, instead of the default behavior of limiting the info to the active layer for each guest disk. What you get listed:

  • block.count โ€” number of block devices being listed
  • block.<num>.name โ€” name of the target of the block device <num> (the same name for multiple entries if --backing is present)
  • block.<num>.backingIndex โ€” when --backing is present, matches up with the <backingStore> index listed in the domain XML for backing files
  • block.<num>.path โ€” the file source of block device num, like if it's a local file or a block device ๐Ÿ—‚๏ธ
    • block.<num>.rd.reqs โ€” how many read requests happened
    • block.<num>.rd.bytes โ€” how many bytes got read
    • block.<num>.rd.times โ€” total time in ns spent on reads
    • block.<num>.wr.reqs โ€” number of write requests
    • block.<num>.wr.bytes โ€” number of bytes written
    • block.<num>.wr.times โ€” total time (ns) spent on writes
    • block.<num>.fl.reqs โ€” total flush requests
    • block.<num>.fl.times โ€” total time (ns) spent flushing the cache
    • block.<num>.errors โ€” Xen only bestie: this one's the 'oo_req' value
    • block.<num>.allocation โ€” offset of the highest written sector, in bytes
    • block.<num>.capacity โ€” logical size of the source file, in bytes
    • block.<num>.physical โ€” physical size of the source file, in bytes
    • block.<num>.threshold โ€” the threshold in bytes for delivering the VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD event. Peep domblkthreshold for the deets ๐Ÿ‘€
    • block.<num>.limits.request_alignment โ€” alignment requirement for requests, in bytes
    • block.<num>.limits.discard_max โ€” max number of bytes you can discard at once
    • block.<num>.limits.discard_alignment โ€” optimal alignment for discard requests, in bytes
    • block.<num>.limits.write_zeroes_max โ€” max number of bytes that can be zeroed out at once
    • block.<num>.limits.write_zeroes_alignment โ€” optimal alignment for write_zeroes requests, in bytes
    • block.<num>.limits.transfer_optimal โ€” optimal transfer length, in bytes
    • block.<num>.limits.transfer_max โ€” maximal transfer length, in bytes
    • block.<num>.limits.transfer_hw_max โ€” maximal hardware transfer length of requests that bypass the kernel IO scheduler, in bytes
    • block.<num>.limits.iov_max โ€” maximum number of scatter/gather elements
    • block.<num>.limits.iov_hw_max โ€” maximal number of scatter/gather elements of requests bypassing the kernel IO scheduler
    • block.<num>.limits.memory_alignment_minimal โ€” memory alignment in bytes so no bounce buffer is needed
    • block.<num>.limits.memory_alignment_optimal โ€” memory alignment in bytes that gets used for bounce buffers
    • block.<num>.timed_group.count โ€” number of blocks of timed group statistics
    • block.<num>.timed_group.<num>.interval_length โ€” the time interval in seconds that the stats in this group were collected over
    • block.<num>.timed_group.<num>.rd_latency_min โ€” minimum latency of read operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.rd_latency_max โ€” maximum latency of read operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.rd_latency_avg โ€” average latency of read operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.wr_latency_min โ€” minimum latency of write operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.wr_latency_max โ€” maximum latency of write operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.wr_latency_avg โ€” average latency of write operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.zone_append_latency_min โ€” minimum latency of zone append operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.zone_append_latency_max โ€” maximum latency of zone append operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.zone_append_latency_avg โ€” average latency of zone append operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.flush_latency_min โ€” minimum latency of flush operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.flush_latency_max โ€” maximum latency of flush operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.flush_latency_avg โ€” average latency of flush operations in the defined interval, in nanoseconds
    • block.<num>.timed_group.<num>.rd_queue_depth_avg โ€” average number of pending read operations in the defined interval
    • block.<num>.timed_group.<num>.wr_queue_depth_avg โ€” average number of pending write operations in the defined interval
    • block.<num>.timed_group.<num>.zone_append_queue_depth_avg โ€” average number of pending zone append operations in the defined interval
    • block.<num>.latency_histogram.<type>.bin.count โ€” number of bins in the latency histogram. <type> is one of read, write, zone_append, or flush ๐Ÿ“Š
    • block.<num>.latency_histogram.<type>.bin.<num>.start โ€” start boundary of a latency histogram bin, in nanoseconds, of the given operation duration
    • block.<num>.latency_histogram.<type>.bin.<num>.value โ€” current number of events that match the given bin and type

--iothread gives you the tea on IOThreads on the running guest, if the hypervisor supports it ๐Ÿงต

The "poll-max-ns" for each thread is the maximum nanoseconds each polling interval is allowed to take. A polling interval is basically a window of time a thread gets to process data before the guest hands its CPU quantum back to the host. Set it too small and the IOThread won't run long enough on a CPU to actually process anything ๐Ÿ˜ญ set it too high and it'll hog way too much CPU time per IOThread, so the other threads on that CPU get no time. Also, the polling interval is not available for statistical purposes, so don't go looking for it.

  • iothread.count โ€” the maximum number of IOThreads in the following list, as an unsigned int. Every IOThread in the list uses its own iothread_id value as the <id>. There may be fewer <id> entries than the iothread.count value if the polling values aren't supported, just so you know.
    • iothread.<id>.poll-max-ns โ€” maximum polling time in nanoseconds used by the <id> IOThread. A value of 0 (zero) means polling is disabled.
    • iothread.<id>.poll-grow โ€” the polling time grow value. A value of 0 (zero) means growth is managed by the hypervisor.
    • iothread.<id>.poll-shrink โ€” the polling time shrink value. A value of (zero) means shrink is managed by the hypervisor.
    • iothread.<id>.poll-weight โ€” the polling weight shift value. A value of 0 (zero) means the hypervisor's default weight gets used.

--memory returns:

  • memory.bandwidth.monitor.count โ€” how many memory bandwidth monitors this domain has
  • memory.bandwidth.monitor.<num>.name โ€” the name of monitor num
  • memory.bandwidth.monitor.<num>.vcpus โ€” the vcpu list of monitor num
  • memory.bandwidth.monitor.<num>.node.count โ€” the number of memory controllers in monitor num
  • memory.bandwidth.monitor.<num>.node.<index>.id โ€” host allocated memory controller id for controller index of monitor num
  • memory.bandwidth.monitor.<num>.node.<index>.bytes.local โ€” the accumulative bytes consumed by @vcpus passing through the memory controller in the same processor that the scheduled host CPU belongs to
  • memory.bandwidth.monitor.<num>.node.<index>.bytes.total โ€” the total bytes consumed by @vcpus passing through all memory controllers, local or remote ๐ŸŒˆ

--dirtyrate returns:

  • dirtyrate.calc_status โ€” the status of the last memory dirty rate calculation, returned as a number from the virDomainDirtyRateStatus enum
  • dirtyrate.calc_start_time โ€” the start time of the last memory dirty rate calculation
  • dirtyrate.calc_period โ€” the period of the last memory dirty rate calculation
  • dirtyrate.megabytes_per_second โ€” the calculated memory dirty rate in MiB/s
  • dirtyrate.calc_mode โ€” the calculation mode used for the last measurement (page-sampling/dirty-bitmap/dirty-ring)
  • dirtyrate.vcpu.<num>.megabytes_per_second โ€” the calculated memory dirty rate for a virtual cpu, in MiB/s

--vm returns:

The --vm option lets you report hypervisor-specific statistics. The naming and meaning of the fields is entirely up to the hypervisor, no cap.

The stats in this group follow this naming scheme:

vm.$NAME.$TYPE
  • $NAME โ€” name of the statistics field provided by the hypervisor
  • $TYPE โ€” the type of the value. These are the types you can get back:
    • cur โ€” current instant value
    • sum โ€” aggregate value
    • max โ€” peak value

The returned value may be either an unsigned long long or a boolean.

WARNING: the stats reported in this group are runtime-collected and hypervisor originated, so they fall outside the usual stable API policies of libvirt ๐Ÿ’€ Libvirt can't guarantee that stats reported from an outside source will still be there in future hypervisor versions, or that the naming or meaning will stay consistent. That said, changes to existing fields are expected to be rare.

Picking a specific statistics group doesn't guarantee that the daemon actually supports that group of stats. The --enforce flag forces the command to fail if the daemon doesn't support the group you selected.

When collecting stats, libvirtd may wait a hot minute if there's already another job running on that domain, just so it can finish. That can cause unnecessary delay in delivering your stats ๐Ÿ˜ด using --nowait suppresses that behaviour. Downside though: some statistics might be missing for that domain.


๐Ÿ•ฐ๏ธ domtime

Syntax:

domtime domain { [--now] [--pretty] [--sync] [--time time] }

Gets or sets the domain's system time. Run it with no arguments (just the domain) and it prints out the domain's current system time. The --pretty modifier makes it print in a way more human readable form, slay โœจ

When --time time is specified, the domain's time isn't gotten, it's set instead. The --now modifier acts like an alias for --time $now, meaning it sets the time that's currently on the host virsh is running at. In both cases (setting and getting), the time is in seconds relative to the Epoch of 1970-01-01 in UTC โฐ The --sync modifies the set behavior a lil bit: the time passed is ignored, but the time to set is read from the domain's RTC instead. Just a heads up, some hypervisors may need a guest agent configured in order to get or set the guest time, so don't come for me if it doesn't work ๐Ÿ™ˆ

๐Ÿ†” domuuid

Syntax:

domuuid domain-name-or-id

Converts a domain name or id to the domain UUID. Iconic little converter, honestly.

๐Ÿ”„ domxml-from-native

Syntax:

domxml-from-native format config

Converts the file config, in the native guest configuration format named by format, into a domain XML format. Here's the format tea by hypervisor:

  • For QEMU/KVM, the format argument must be qemu-argv
  • For Xen, the format argument may be xen-xm, xen-xl, or xen-sxpr
  • For LXC, the format argument must be lxc-tools
  • For VMware/ESX, the format argument must be vmware-vmx
  • For the Bhyve hypervisor, the format argument must be bhyve-argv

No mixing and matching bestie, the format has to be one of those exact ones ๐Ÿ’…

๐Ÿ’… domxml-to-native

domxml-to-native format { [--xml] xml | --domain domain-name-or-id-or-uuid }

Okay so this one is the glow-up translator bestie โœจ โ€” it takes your xml file and converts it into the native guest configuration format named by format. Or, if you're feeling fancy, you can point at an existing --domain instead and it'll convert that. The xml and --domain arguments are mutually exclusive (pick one, queen, you can't have both ๐Ÿซถ). Wanna know what format values you can use? Go peek at domxml-from-native โ€” it's giving the same energy, just the other direction.


๐Ÿ’€ dump

dump domain corefilepath [--bypass-cache]
   { [--live] | [--crash] | [--reset] }
   [--verbose] [--memory-only] [--format string]

This one dumps the core of a domain to a file so you can analyze it later โ€” it's giving forensics chic ๐Ÿ”.

  • If --live is specified, the domain continues to run until the core dump is complete โ€” no pausing up front, she keeps going ๐Ÿ’…
  • If --crash is specified, the domain gets halted with a crashed status, rather than merely being left in a paused state
  • If --reset is specified, the domain is reset after a successful dump
  • If --bypass-cache is specified, the save will avoid the file system cache โ€” although ngl this may slow down the operation ๐Ÿ˜ญ
  • If --memory-only is specified, the file is an elf file, and it will only include the domain's memory and cpu common register value. This is super useful if the domain uses host devices directly ๐Ÿซถ
  • --format string is used to specify the format of the 'memory-only' dump, and string can be one of: elf, kdump-zlib (kdump-compressed format with zlib-compressed), kdump-lzo (kdump-compressed format with lzo-compressed), kdump-snappy (kdump-compressed format with snappy-compressed), win-dmp (Windows full crashdump format)
โš ๏ธ Heads up bestie: those three switches --live, --crash, and --reset are mutually exclusive. Pick one, periodt.

The progress may be monitored using the domjobinfo virsh command and canceled with the domjobabort command (sent by another virsh instance). Another option is to send SIGINT (usually with Ctrl+C) to the virsh process running the dump command. --verbose displays the progress of dump ๐Ÿ’–

NOTE: Some hypervisors may require you to manually ensure proper permissions on the file and path specified by the corefilepath argument. Not me forgetting the chmod... ๐Ÿ™ˆ
NOTE: Crash dump in the old kvmdump format is being obsolete and cannot be loaded and processed by the crash utility since its version 6.1.0. A --memory-only option is required in order to produce a valid ELF file which can later be processed by the crash utility. So like, use it, or the crash utility will simply not vibe with your file ๐Ÿ’€

๐Ÿฆ‹ dumpxml

dumpxml [--inactive] [--security-info] [--update-cpu] [--migratable]
        [--xpath EXPRESSION] [--wrap] domain

Outputs the domain information as an XML dump to stdout โ€” and this format can be used by the create command, iykyk ๐ŸŒˆ. Additional options affecting the XML dump may be used, and honestly they're all iconic:

  • --inactive tells virsh to dump the domain configuration that will be used on the next start of the domain, as opposed to the current domain configuration
  • --security-info will also include security sensitive information in the XML dump ๐Ÿ”
  • --update-cpu updates domain CPU requirements according to the host CPU
  • --migratable lets you request an XML that's suitable for migrations โ€” i.e., compatible with older libvirt releases and possibly amended with internal run-time options. This option may automatically enable other options (--update-cpu, --security-info, ...) as necessary. She's a self-sufficient main character fr fr ๐Ÿ‘‘

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document โ€” however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node ๐ŸŽ€


โœจ edit

edit domain

Edit the XML configuration file for a domain โ€” this affects the next boot of the guest, so don't come crying to me when your running domain hasn't changed yet ๐Ÿ’…

It's equivalent to:

virsh dumpxml --inactive --security-info domain > domain.xml
vi domain.xml (or make changes with your other text editor)
virsh define domain.xml

...except that it does some error checking. Honestly? The error checking is the whole point. That's the slay ๐Ÿซถ

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi.


๐ŸŒธ emulatorpin

emulatorpin domain [cpulist] [[--live] [--config]  | [--current]]

Query or change the pinning of a domain's emulator threads to host physical CPUs ๐Ÿงš

See vcpupin for cpulist.

  • --live โ†’ affect a running guest
  • --config โ†’ affect the next start of a persistent guest
  • --current โ†’ equivalent to either --live or --config, depending on the current state of the guest

Both --live and --config flags may be given if cpulist is present, but --current is exclusive (she does not share the spotlight ๐Ÿ’…). If no flag is specified, behavior is different depending on hypervisor โ€” yes, mysterious, we know ๐Ÿ˜ญ


โญ event

event {[domain] { event | --all } [--loop] [--timeout seconds] [--timestamp] | --list}

Wait for a class of domain events to occur, and print appropriate details of events as they happen ๐Ÿฆ‹ The events can optionally be filtered by domain.

Using --list as the only argument will provide a list of possible event values known by this client โ€” although ngl the connection might not allow registering for all these events. It's also possible to use --all instead of event to register for all possible event types at once, which is very main character energy ๐Ÿ‘‘

By default this command is one-shot and returns success once an event occurs โ€” you can send SIGINT (usually via Ctrl+C) to quit immediately. If --timeout is specified, the command gives up waiting for events after seconds have elapsed. With --loop, the command prints all events until a timeout or interrupt key ๐ŸŽ€

When --timestamp is used, a human-readable timestamp will be printed before the event. Cute AND useful ๐Ÿ’–


๐ŸŒˆ await

await <domain> --condition <string> [--timeout seconds]

Wait until the --condition for <domain> is satisfied. Uses events for efficient state updates โ€” so it's not just sitting there spinning, she's got systems โœจ

Supported conditions:

  • domain-inactive โ€” the domain is or becomes inactive
  • guest-agent-available โ€” the guest agent inside the guest connects and becomes available for commands (which usually means that the guest has booted) ๐ŸŽ€

If --timeout is specified, the command gives up waiting for the condition to be satisfied after seconds have elapsed. If SIGINT is delivered to virsh (usually via Ctrl+C) the wait is given up immediately. In non-interactive mode virsh will return '2' if either of those cases happen โ€” instead of '1', which means an actual error happened. Yes the numbers matter bestie, don't mix them up ๐Ÿ’€


๐Ÿ”ฅ get-user-sshkeys

get-user-sshkeys domain user

Prints the SSH authorized keys for the given user in the guest domain ๐Ÿ”‘ Please note that an entry in the file has internal structure as defined by sshd(8) โ€” and virsh/libvirt handles keys as opaque strings, i.e. it does not interpret them. So don't expect her to read your keys, she just passes them along ๐Ÿซถ


๐Ÿ’œ guest-agent-timeout

guest-agent-timeout domain [--timeout value]

Sets how long to wait for a response from guest agent commands โณ By default, agent commands block forever waiting for a response (which is honestly so patient of them). value must be a positive value (wait for the given amount of seconds) or one of these:

  • -2 โ€” block forever waiting for a result (used when --timeout is omitted)
  • -1 โ€” reset timeout to the default value (currently defined as 5 seconds in the libvirt daemon)
  • 0 โ€” do not wait at all

In all guest-agent based APIs, when a timeout happens โ€” if an actual command was sent to the guest agent โ€” the returned error code will be VIR_ERR_AGENT_COMMAND_TIMEOUT. Iconic error code honestly ๐Ÿ’…


๐Ÿ‘‘ guestinfo

guestinfo domain [--user] [--os] [--timezone] [--hostname] [--filesystem]
   [--disk] [--interface] [--devices]

Prints information about the guest from the point of view of the guest agent ๐Ÿงš Note that this command requires a guest agent to be configured and running in the domain's guest OS โ€” no agent, no tea, no info ๐Ÿ˜ญ

When run without any arguments, this command prints all information types that are supported by the guest agent at that point, omitting unavailable ones. Success is always reported in this case ๐Ÿ’–

You can limit the types of information returned by specifying one or more flags. Available information type flags are --user, --os, --timezone, --hostname, --filesystem, --disk, --interface, --load and --devices. If an explicitly requested information type is not supported by the guest agent at that point, the process will provide an exit code of 1 ๐Ÿ’€

Note that depending on the hypervisor type and the version of the guest agent running within the domain, not all of the following information may be returned. It's giving "results may vary" โœจ

When selecting the --user information type, the following fields may be returned:

  • user.count โ€” the number of active users on this domain
  • user.<num>.name โ€” username of user <num>
  • user.<num>.domain โ€” domain of the user <num> (may only be present on certain guest types)
  • user.<num>.login-time โ€” the login time of user <num> in milliseconds since the epoch

--os returns:

  • os.id โ€” a string identifying the operating system
  • os.name โ€” the name of the operating system
  • os.pretty-name โ€” a pretty name for the operating system (she's pretty AND she has a pretty name ๐ŸŽ€)
  • os.version โ€” the version of the operating system
  • os.version-id โ€” the version id of the operating system
  • os.kernel-release โ€” the release of the operating system kernel
  • os.kernel-version โ€” the version of the operating system kernel
  • os.machine โ€” the machine hardware name
  • os.variant โ€” a specific variant or edition of the operating system
  • os.variant-id โ€” the id for a specific variant or edition of the operating system

--timezone returns:

  • timezone.name โ€” the name of the timezone
  • timezone.offset โ€” the offset to UTC in seconds

--hostname returns:

  • hostname โ€” the hostname of the domain

--filesystem returns:

  • fs.count โ€” the number of filesystems defined on this domain
  • fs.<num>.mountpoint โ€” the path to the mount point for filesystem <num>
  • fs.<num>.name โ€” device name in the guest (e.g. sda1) for filesystem <num>
  • fs.<num>.fstype โ€” the type of filesystem <num>
  • fs.<num>.total-bytes โ€” the total size of filesystem <num>
  • fs.<num>.used-bytes โ€” the number of bytes used in filesystem <num>
  • fs.<num>.disk.count โ€” the number of disks targeted by filesystem <num>
  • fs.<num>.disk.<num>.alias โ€” the device alias of disk <num> (e.g. sda)
  • fs.<num>.disk.<num>.serial โ€” the serial number of disk <num>
  • fs.<num>.disk.<num>.device โ€” the device node of disk <num>

--disk returns:

  • disk.count โ€” the number of disks defined on this domain
  • disk.<num>.name โ€” device node (Linux) or device UNC (Windows)
  • disk.<num>.partition โ€” whether this is a partition or disk
  • disk.<num>.dependency.count โ€” the number of device dependencies
  • disk.<num>.dependency.<num>.name โ€” a dependency name
  • disk.<num>.serial โ€” optional disk serial number
  • disk.<num>.alias โ€” the device alias of the disk (e.g. sda)
  • disk.<num>.guest_alias โ€” optional alias assigned to the disk
  • disk.<num>.guest_bus โ€” the bus type, as told to us by the guest itself ๐Ÿซถ

๐Ÿฆ‹ --interface spills the tea on

  • if.count โ€” how many interfaces this domain has defined, total ๐Ÿ’…
  • if.<num>.name โ€” the name inside the guest (think eth0) for interface num ๐ŸŽ€
  • if.<num>.hwaddr โ€” the hardware address in the guest for interface num โœจ
  • if.<num>.addr.count โ€” how many IP addresses interface num is holding ๐ŸŒธ
  • if.<num>.addr.<num1>.type โ€” the IP address type of addr num1 (like ipv4) ๐Ÿ’–
  • if.<num>.addr.<num1>.addr โ€” the actual IP address of addr num1 โญ
  • if.<num>.addr.<num1>.prefix โ€” the prefix of the IP address of addr num1 ๐ŸŒˆ

๐Ÿ“ --load is literally just vibe checks

  • load.1m โ€” average load in the guest over the last 1 minute ๐Ÿ”ฅ
  • load.5m โ€” average load in the guest over the last 5 minutes ๐Ÿ”ฅ
  • load.15m โ€” average load in the guest over the last 15 minutes ๐Ÿ”ฅ

๐Ÿงš --devices said "let me introduce you to everyone"

  • device.count โ€” the number of devices we're actually returning info for ๐Ÿ‘‘
  • device.<num>.driverName โ€” the name of the driver tied to that device ๐Ÿ’œ
  • device.<num>.driverDate โ€” driver release date, in seconds since the epoch โญ
  • device.<num>.driverVersion โ€” version of the driver tied to the device ๐ŸŽ€
  • device.<num>.idType โ€” device identification type (e.g. pci) ๐Ÿฆ‹
  • device.<num>.pciVendor โ€” vendor ID for a PCI device (in decimal) ๐Ÿ’…
  • device.<num>.pciDevice โ€” device ID for a PCI device (in decimal) ๐Ÿ’…

โœจ guestvcpus โœจ

Syntax:

guestvcpus domain [[--enable] | [--disable]] [cpulist]

So this one talks to the guest agent (iykyk) to query or change the state of vCPUs from the guest's own point of view ๐Ÿ‘€. Call it with no cpulist and the guest gets asked what guest vCPUs it has available, what state they're in, and whether they're even allowed to be offlined.

If you do pass a cpulist, then you must also pass one of --enable or --disable โ€” no exceptions bestie ๐Ÿ˜ญ. Once you do, that operation runs on the domain.

Wanna know how cpulist works? Peek at vcpupin โ€” same energy, same syntax ๐Ÿซถ.


๐Ÿ’… iothreadadd ๐Ÿ’…

Syntax:

iothreadadd domain iothread_id [[--config] [--live] | [--current]]

Adds a brand-new IOThread to the domain using the iothread_id you gave it โœจ. If that iothread_id is already taken? The command straight up fails, no cap ๐Ÿ’€. And heads up: iothread_id has to be greater than zero.

  • --live โ€” affect a running guest. If the guest isn't running, you get an error, sorry ๐Ÿ˜ญ
  • --config โ€” affect the next start of a persistent guest ๐ŸŒธ
  • --current โ€” equivalent to either --live or --config, depending on what state the guest is in right now ๐Ÿฆ‹

๐ŸŽ€ iothreaddel ๐ŸŽ€

Syntax:

iothreaddel domain iothread_id [[--config] [--live] | [--current]]

Deletes an IOThread from the domain using the iothread_id you specify ๐Ÿ—‘๏ธ. But if that IOThread is currently assigned to a disk resource โ€” like via the attach-disk command โ€” then trying to remove it will fail ๐Ÿ’€. And if the iothread_id doesn't even exist? Error. Obviously. ๐Ÿ™ˆ

  • --live โ€” affect a running guest. Not running = error ๐Ÿ˜ญ
  • --config โ€” affect the next start of a persistent guest ๐ŸŒธ
  • --current โ€” equivalent to either --live or --config, depending on the current guest state ๐Ÿฆ‹

๐ŸŒˆ iothreadinfo ๐ŸŒˆ

Syntax:

iothreadinfo domain [[--live] [--config] | [--current]]

Shows you the basic domain IOThreads info โ€” that means the IOThread ID and the CPU Affinity for each one ๐Ÿ‘‘. It's giving "here's the whole roster".

  • --live โ€” grab the IOThreads data from the running guest. If the guest isn't running, error ๐Ÿซ 
  • --config โ€” grab the IOThreads data from the next start of a persistent guest ๐ŸŒธ
  • --current โ€” get the IOThread data based on the current guest state (live or offline). And if neither --live nor --config is given, this is what you get by default ๐Ÿฆ‹

โญ iothreadpin โญ

Syntax:

iothreadpin domain iothread cpulist [[--live] [--config] | [--current]]

Changes the pinning of a domain IOThread to host physical CPUs ๐Ÿ’…. Need the full list of IOThreads first? Use iothreadinfo. Then to pin one, hand over the cpulist you want for that IOThread ID as listed in the iothreadinfo output.

cpulist is a list of physical CPU numbers. Syntax is a comma-separated list, and there's special markup with - and ^ (ex. '0-4', '0-3,^2') that's allowed too โœจ. The - means a range, and ^ means exclusive. Oh and if you want to reset the iothreadpin setting โ€” i.e. pin an iothread to all physical CPUs โ€” just pass 'r' as your cpulist ๐ŸŽ€.

  • --live โ€” affect a running guest. If it's not running, error ๐Ÿ˜ญ
  • --config โ€” affect the next start of a persistent guest ๐ŸŒธ
  • --current โ€” equivalent to either --live or --config, depending on current guest state ๐Ÿฆ‹

Both --live and --config can be given if cpulist is present, but --current is exclusive ๐Ÿ”’. And if no flag is given at all, the behavior differs depending on the hypervisor ๐Ÿ‘€.

Note bestie, this one's important: the expression is sequentially evaluated, so "0-15,^8" is identical to "9-14,0-7,15" but not identical to "^8,0-15" ๐Ÿ’€. Order matters!

๐Ÿฆ„ iothreadset ๐Ÿฆ„

Syntax:

iothreadset domain iothread_id [[--poll-max-ns ns] [--poll-grow factor]
   [--poll-shrink divisor] [--poll-weight factor]
   [--thread-pool-min value] [--thread-pool-max value]]
   [[--config] [--live] | [--current]]

Modifies an existing iothread of the domain using the iothread_id you gave โœจ. Here's the full breakdown of every knob:

  • --poll-max-ns ns โ€” the maximum polling interval allowed for an IOThread, in ns. Pass a 0 (zero) and polling for that IOThread is disabled ๐Ÿ’€
  • --poll-grow factor โ€” the factor by which the current polling time gets adjusted to reach the max polling time. Pass 0 (zero) and the default factor is used ๐ŸŽ€
  • --poll-shrink divisor โ€” the quotient by which the current polling time is reduced to get below the maximum polling interval. Pass 0 (zero) and the default quotient is used ๐ŸŒธ
  • --poll-weight factor โ€” sets the weight shift value for adaptive polling. It decides how much the most recent event interval affects the next polling duration calculation. Larger values reduce the weight of recent events. Valid range is [0, 63] ๐Ÿ‘‘. If omitted, the value isn't changed ๐Ÿฆ‹
  • --thread-pool-min value โ€” the lower bound of the number of threads in the worker pool of the given iothread ๐Ÿ’œ
  • --thread-pool-max value โ€” the upper bound of the number of threads in that worker pool ๐Ÿ’œ

The polling values are purely dynamic for a running guest โ€” saving, destroying, stopping, etc. the guest means the polling values go right back to hypervisor defaults at the next start, restore, etc. ๐Ÿ™ˆ So don't expect them to stick.

For changes to an inactive configuration, you can pass -1 to remove the corresponding boundary from the domain configuration. For changes to a running guest, it's recommended to set the upper boundary first (--thread-pool-max) and only after that set the lower boundary (--thread-pool-min) โญ. It is allowed for the lower boundary to equal the upper boundary, but the upper boundary is not allowed to be a value of zero ๐Ÿ’€.

  • --live โ€” affect a running guest. If the guest isn't running, error ๐Ÿ˜ญ
  • --current โ€” if specified, or if --live isn't specified, then handle it as if --live had been specified ๐Ÿฆ‹ (Where "current" here means whatever the present guest state is: live or offline.)

๐ŸŒธ managedsave ๐ŸŒธ

Syntax:

managedsave domain [--bypass-cache] [{--running | --paused}] [--verbose]

Saves and destroys (stops) a running domain, so it can be restarted from that same state later ๐Ÿ‘‘. Next time you run the virsh start command for that domain, it'll automatically come up from this saved state โœจ. Pass --bypass-cache and the save avoids the file system cache โ€” although ngl, that may slow the whole thing down ๐Ÿข.

You can watch the progress with the domjobinfo virsh command, and cancel it with domjobabort (sent from another virsh instance) ๐ŸŽ€. Another option is sending SIGINT (usually Ctrl+C) to the virsh process running the managedsave command ๐Ÿ’…. And --verbose displays the progress of the save.

Normally, starting a managed save decides between running or paused based on the state the domain was in when the save happened. But passing either --running or --paused lets you override which state the start should use ๐Ÿ”ฅ.

Wanna know if a domain currently has a managed save image? The dominfo command can tell you ๐Ÿฆ‹.


๐ŸŽ€ managedsave-define ๐ŸŽ€

Syntax:

managedsave-define domain xml [{--running | --paused}]

Updates the domain XML that gets used when the domain is later started ๐ŸŒธ. The xml argument must be a file name containing the alternative XML โ€” with changes only in the host-specific portions of the domain XML, bestie. For example, it's great for changing disk file paths โœจ.

The managed save image records whether the domain should be started to a running or paused state. Normally this command doesn't alter that recorded state โ€” but passing either --running or --paused lets you override which state the start should use ๐Ÿ’….


๐Ÿฆ‹ managedsave-dumpxml ๐Ÿฆ‹

Syntax:

managedsave-dumpxml [--security-info] [--xpath EXPRESSION] [--wrap] domain

Extracts the domain XML that was in effect at the time the saved state file was created with the managedsave command ๐Ÿ‘‘. Throw in --security-info and you also get the security sensitive info included ๐Ÿ™ˆ.

  • --xpath EXPRESSION โ€” if given an XPath expression, it gets evaluated against the output XML and only those matching nodes get printed โœจ. Default behavior is to print each matching node as a standalone document. But for ease of additional processing, --wrap causes the matching node to be wrapped in a common root node ๐ŸŽ€

โญ managedsave-edit โญ

Syntax:

managedsave-edit domain [{--running | --paused}]

Edits the XML configuration associated with a saved state file of a domain that was created by the managedsave command ๐Ÿ’….

The managed save image records whether the domain should be started to a running or paused state. Normally this command doesn't alter that recorded state โ€” passing either --running or --paused lets you override which state the restore should use ๐ŸŒธ.

This is equivalent to:

virsh managedsave-dumpxml domain-name > state-file.xml
vi state-file.xml (or make changes with your other text editor)
virsh managedsave-define domain-name state-file-xml

...except that it does some error checking ๐Ÿฆ‹ (so like, it's the responsible version fr fr).

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi โœจ.


๐Ÿ“ managedsave-remove ๐Ÿ“

Syntax:

managedsave-remove domain

Removes the managedsave state file for a domain, if it exists ๐Ÿ’€. This guarantees the domain does a full boot the next time it's started ๐Ÿ”ฅ. Clean slate energy.


๐Ÿ’œ maxvcpus ๐Ÿ’œ

Syntax:

maxvcpus [type]

Tells you the maximum number of virtual CPUs supported for a guest VM on this connection ๐Ÿ‘‘. If you pass the type parameter, it must be a valid type attribute for the <domain> element of XML ๐ŸŽ€.


๐ŸŒˆ memtune ๐ŸŒˆ

Syntax:

memtune domain [--hard-limit size] [--soft-limit size] [--swap-hard-limit size]
   [--min-guarantee size] [[--config] [--live] | [--current]]

Without any flags, you're just taking a peek โ€” the current settings get displayed, no changes, no drama ๐Ÿ’…. Give it a flag though, and the matching limit gets adjusted if the hypervisor supports it. LXC and QEMU/KVM support --hard-limit, --soft-limit, and --swap-hard-limit. --min-guarantee is supported only by the ESX hypervisor. Each of these limits is a scaled integer (peep the NOTES above bestie), and if you don't slap a suffix on it, the default is kibibytes (blocks of 1024 bytes). Libvirt rounds up to the nearest kibibyte. Some hypervisors are picky and need a bigger granularity than KiB, so requests that aren't an even multiple get rounded up too โ€” for example, vSphere/ESX rounds the parameter up to mebibytes (1024 kibibytes). โœจ

If --live is specified, you're affecting a running guest. If --config is specified, you're affecting the next start of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive. If no flag is specified, behavior is different depending on hypervisor โ€” iykyk ๐Ÿ˜ญ

For QEMU/KVM, the parameters are applied to the QEMU process as a whole ๐Ÿซถ. So when you're counting them, you gotta add up guest RAM, guest video RAM, and some memory overhead of QEMU itself. That last piece is lowkey impossible to determine, so honestly you just guess and try ๐Ÿ’€.

For LXC, the displayed hard_limit value is the current memory setting from the XML or the results from a virsh setmem command.

  • --hard-limit โ€” the absolute maximum memory the guest can use ๐Ÿ”ฅ
  • --soft-limit โ€” the memory limit to enforce during memory contention
  • --swap-hard-limit โ€” the maximum memory plus swap the guest can use. This one has to be more than the hard-limit value you provided, no cap.
  • --min-guarantee โ€” the guaranteed minimum memory allocation for the guest ๐Ÿ‘‘

Specifying -1 as a value for these limits is interpreted as unlimited ๐ŸŒˆ


๐ŸŽ€ metadata ๐ŸŽ€

Syntax check bestie:

metadata domain [[--live] [--config] | [--current]]
   [--edit] [uri] [key] [set] [--remove]

Show or modify custom XML metadata of a domain. The metadata is a user defined XML that lets you stash arbitrary XML data in the domain definition ๐Ÿฆ‹. You can store multiple separate custom metadata pieces in the domain XML โ€” they're identified by a private XML namespace provided via the uri argument. (See also desc, which works with textual metadata of a domain.)

Flags --live or --config select whether this command works on live or persistent definitions of the domain. If both --live and --config are specified, the --config option takes precedence on getting the current description, and both live configuration and config are updated while setting the description. --current is exclusive and implied if none of these was specified ๐Ÿ‘‘.

Flag --remove specifies that the metadata element specified by the uri argument should be removed rather than updated.

Flag --edit specifies that an editor with the metadata identified by the uri argument should be opened and the contents saved back afterwards โœ๏ธ. Otherwise the new contents can be provided via the set argument.

When setting metadata via --edit or set, the key argument must be specified and is used to prefix the custom elements to bind them to the private namespace.

If neither of --edit and set are specified, the XML metadata corresponding to the uri namespace is displayed instead of being modified ๐ŸŒธ.


๐Ÿšš migrate ๐Ÿšš

Okay this one's a whole journey, strap in:

migrate [--live] [--offline] [--direct] [--p2p [--tunnelled]]
   [--persistent] [--undefinesource] [--suspend] [--copy-storage-all]
   [--copy-storage-inc] [--change-protection] [--unsafe] [--verbose]
   [--rdma-pin-all] [--abort-on-error] [--postcopy]
   [--postcopy-after-precopy] [--postcopy-resume] [--zerocopy]
   domain desturi [migrateuri] [graphicsuri] [listen-address] [dname]
   [--timeout seconds [--timeout-suspend | --timeout-postcopy]]
   [--xml file]
   [--migrate-disks disk-list] [--migrate-disks-detect-zeroes disk-list]
   [--migrate-disks-target-zero disk-list]
   [--disks-port port]
   [--compressed] [--comp-methods method-list]
   [--comp-mt-level] [--comp-mt-threads] [--comp-mt-dthreads]
   [--comp-xbzrle-cache] [--comp-zlib-level] [--comp-zstd-level]
   [--auto-converge] [auto-converge-initial]
   [auto-converge-increment] [--persistent-xml file] [--tls]
   [--postcopy-bandwidth bandwidth]
   [--parallel [--parallel-connections connections]]
   [--bandwidth bandwidth] [--tls-destination hostname]
   [--disks-uri URI] [--copy-storage-synchronous-writes]
   [--available-switchover-bandwidth bandwidth]

Migrate domain to another host, bestie โ€” glow-up but make it infrastructure โœจ. Add --live for live migration; --p2p for peer-2-peer migration; --direct for direct migration; or --tunnelled for tunnelled migration. --offline migrates the domain definition without starting the domain on destination and without stopping it on the source host. Offline migration may be used with inactive domains and it must be used with the --persistent option.

--persistent leaves the domain persistent on the destination host (see below for quirks when used together with --xml), --undefinesource undefines the domain on the source host, and --suspend leaves the domain paused on the destination host ๐Ÿ˜ด.

--copy-storage-all indicates migration with non-shared storage with full disk copy, and --copy-storage-inc indicates migration with non-shared storage with incremental copy (same base image shared between source and destination) ๐Ÿ’พ. In both cases the disk images have to exist on the destination host โ€” the --copy-storage-... options only tell libvirt to transfer data from the images on the source host to the images found at the same place on the destination host. By default only non-shared non-readonly images are transferred. Use --migrate-disks to explicitly specify a list of disk targets to transfer via the comma separated disk-list argument. The --migrate-disks-detect-zeroes option, which takes a comma separated list of disk target names, enables zeroed block detection for the listed migrated disks โ€” those blocks are not transferred or allocated (requires that 'discard' option on the given disk is set to 'unmap') on destination, effectively sparsifying the disk at the cost of CPU overhead ๐Ÿ”ฅ. The --migrate-disks-target-zero option, which takes a comma separated list of disk target names, specifies disk images where the target was zeroed out prior to the migration and thus the hypervisor will not attempt to zero them. With the --copy-storage-synchronous-writes flag used, the disk data migration will synchronously handle guest disk writes to both the original source and the destination to ensure that the disk migration converges โ€” at the price of possibly decreased burst performance ๐Ÿ˜ญ.

--change-protection enforces that no incompatible configuration changes will be made to the domain while the migration is underway; this flag is implicitly enabled when supported by the hypervisor, but can be explicitly used to reject the migration if the hypervisor lacks change protection support ๐Ÿ›ก๏ธ.

--verbose displays the progress of migration โ€” the little loading bar of your dreams.

--abort-on-error cancels the migration if a soft error (for example I/O error) happens during the migration ๐Ÿ’€.

--postcopy enables post-copy logic in migration, but does not actually start post-copy โ€” i.e., migration is started in pre-copy mode. Once migration is running, the user may switch to post-copy using the migrate-postcopy command sent from another virsh instance, or use --postcopy-after-precopy along with --postcopy to let libvirt automatically switch to post-copy after the first pass of pre-copy is finished ๐Ÿฆ‹. The maximum bandwidth consumed during the post-copy phase may be limited using --postcopy-bandwidth. The maximum bandwidth consumed during the pre-copy phase may be limited using --bandwidth. In case the connection between the hosts breaks while migration is in post-copy mode, the domain cannot be resumed on either source or destination host, and the migrate command will report an error leaving the domain active on both hosts ๐Ÿ˜ฑ. To recover from such a situation, repeat the original migrate command with an additional --postcopy-resume flag ๐Ÿซถ.

--auto-converge forces convergence during live migration. The initial guest CPU throttling rate can be set with auto-converge-initial. If the initial throttling rate is not enough to ensure convergence, the rate is periodically increased by auto-converge-increment ๐Ÿ“ˆ.

--rdma-pin-all can be used with RDMA migration (i.e., when migrateuri starts with rdma://) to tell the hypervisor to pin all the domain's memory at once before migration starts, rather than letting it pin memory pages as needed. For QEMU/KVM this requires the hard_limit memory tuning element (in the domain XML) to be used and set to the maximum memory configured for the domain plus any memory consumed by the QEMU process itself. > Beware of setting the memory limit too high (and thus allowing the domain to lock most of the host's memory). Doing so may be dangerous to both the domain and the host itself, since the host's kernel may run out of memory ๐Ÿ’€

--zerocopy requests the zero-copy mechanism to be used for migrating memory pages. For QEMU/KVM this means QEMU will be temporarily allowed to lock all guest pages in the host's memory, although only those that are queued for transfer will be locked at the same time โœจ.

Note: individual hypervisors usually do not support all possible types of migration. For example, QEMU does not support direct migration ๐Ÿ™ˆ

In some cases libvirt may refuse to migrate the domain because doing so may lead to potential problems such as data corruption, and thus the migration is considered unsafe. For a QEMU domain, this may happen if the domain uses disks without explicitly setting the cache mode to "none". Migrating such domains is unsafe unless the disk images are stored on a coherent clustered filesystem, such as GFS2 or GPFS. If you're sure the migration is safe or you just do not care, use --unsafe to force the migration ๐Ÿ˜ค.

dname is used for renaming the domain to a new name during migration, which also usually can be omitted.

--xml file, while usually not required, can be used to supply an alternative XML file for use on the destination, to supply a larger set of changes to any host-specific portions of the domain XML โ€” such as accounting for naming differences between source and destination in accessing underlying storage ๐ŸŽ€. If --xml is used together with --persistent, it's usually required to provide a persistent XML definition via --persistent-xml (see below), which is fixed the same way as the XML passed to --file was.

If --persistent is enabled, --persistent-xml file can be used to supply an alternative XML file which will be used as the persistent guest definition on the destination host ๐Ÿ‘‘.

  • --timeout seconds โ€” tells virsh to run a specified action when live migration exceeds that many seconds. It can only be used with --live. If --timeout-suspend is specified, the domain will be suspended after the timeout and the migration will complete offline; this is the default if no --timeout-* option is specified on the command line. When --timeout-postcopy is used, virsh will switch migration from pre-copy to post-copy upon timeout; migration has to be started with --postcopy option for this to work.
  • --compressed โ€” activates compression, and the compression method gets chosen by --comp-methods. The supported methods are "mt", "xbzrle", "zlib", and "zstd". The supported set of methods and their combinations depend on a hypervisor and migration options. QEMU only supports the "zlib" and "zstd" methods when --parallel is used, and they cannot be used at once. When no methods are specified, a hypervisor default method will be used. QEMU defaults to "xbzrle" as long as --parallel is not used. For --parallel migrations QEMU does not provide any default compression method and thus it has to be specified explicitly using --comp-method. Compression methods can be tuned further. --comp-mt-level sets the compression level for the "mt" method; values are in the range from 0 to 9, where 1 is maximum speed and 9 is maximum compression. --comp-mt-threads and --comp-mt-dthreads set the number of compress threads on source and the number of decompress threads on target respectively. --comp-xbzrle-cache sets the size of the page cache in bytes. --comp-zlib-level sets the compression level when using the "zlib" method; values are in the range from 0 to 9 and default to 1, where 0 is no compression, 1 is maximum speed and 9 is maximum compression. --comp-zstd-level sets the compression level when using the "zstd" method; values are in the range from 0 to 20 and default to 1, where 0 is no compression, 1 is maximum speed and 20 is maximum compression.
  • --tls โ€” makes the migration use the host configured TLS setup (see migrate_tls_x509_cert_dir in /etc/libvirt/qemu.conf) in order to perform the migration of the domain. Usage requires proper TLS setup for both source and target, bestie, both sides. Normally the TLS certificate from the destination host must match the host's name for TLS verification to succeed. When the certificate does not match the destination hostname and the expected certificate's hostname is known, --tls-destination can be used to pass the expected hostname when starting the migration. ๐ŸŽ€
  • --parallel โ€” will cause migration data to be sent over multiple parallel connections. The number of such connections can be set using --parallel-connections. Parallel connections may help with saturating the network link between the source and the target and thus speed up the migration.

Running migration can be canceled by interrupting virsh (usually using Ctrl+C) or by the domjobabort command sent from another virsh instance.

The desturi and migrateuri parameters can be used to control which destination the migration uses. desturi is important for managed migration, but unused for direct migration; migrateuri is required for direct migration, but can usually be automatically determined for managed migration. ๐Ÿ’…

Note: the desturi parameter for normal migration and peer2peer migration has different semantics:
  • normal migration: the desturi is an address of the target host as seen from the client machine.
  • peer2peer migration: the desturi is an address of the target host as seen from the source machine.

In a special circumstance where you require complete control of the connection and/or libvirt does not have network access to the remote side, you can use a UNIX transport in the URI and specify a socket path in the query. For example, with the qemu driver you could use this:

qemu+unix:///system?socket=/path/to/socket

When migrateuri is not specified, libvirt will automatically determine the hypervisor specific URI. Some hypervisors, including QEMU, have an optional "migration_host" configuration parameter (useful when the host has multiple network interfaces). If this is unspecified, libvirt determines a name by looking up the target host's configured hostname. ๐ŸŒธ

There are a few scenarios where specifying migrateuri may help:

  • The configured hostname is incorrect, or DNS is broken. If a host has a hostname which will not resolve to match one of its public IP addresses, then libvirt will generate an incorrect URI. In this case migrateuri should be explicitly specified, using an IP address, or a correct hostname.
  • The host has multiple network interfaces. If a host has multiple network interfaces, it might be desirable for the migration data stream to be sent over a specific interface for either security or performance reasons. In this case migrateuri should be explicitly specified, using an IP address associated with the network to be used.
  • The firewall restricts what ports are available. When libvirt generates a migration URI, it will pick a port number using hypervisor specific rules. Some hypervisors only require a single port to be open in the firewalls, while others require a whole range of port numbers. In the latter case migrateuri might be specified to choose a specific port number outside the default range in order to comply with local firewall policies.
  • The desturi uses UNIX transport method. In this advanced case libvirt should not guess a migrateuri and it should be specified using UNIX socket path URI:
unix:///path/to/socket

See https://libvirt.org/migration.html#uris for more details on migration URIs. ๐Ÿ‘‘

Optional graphicsuri overrides connection parameters used for automatically reconnecting graphical clients at the end of migration. If omitted, libvirt will compute the parameters based on target host IP address. In case the client does not have direct access to the network the virtualization hosts are connected to and needs to connect through a proxy, graphicsuri may be used to specify the address the client should connect to. The URI is formed as follows:

protocol://hostname[:port]/[?parameters]

where protocol is either "spice" or "vnc" and parameters is a list of protocol specific parameters separated by '&'. Currently recognized parameters are "tlsPort" and "tlsSubject". For example,

spice://target.host.com:1234/?tlsPort=4567

Optional listen-address sets the listen address that the hypervisor on the destination side should bind to for incoming migration. Both IPv4 and IPv6 addresses are accepted as well as hostnames (the resolving is done on destination). Some hypervisors do not support specifying the listen address and will return an error if this parameter is used. This parameter cannot be used if desturi uses UNIX transport method. ๐Ÿฆ‹

Optional disks-port sets the port that the hypervisor on the destination side should bind to for incoming disks traffic. Currently it is supported only by QEMU.

Optional disks-uri can also be specified (mutually exclusive with disks-port) to specify what the remote hypervisor should bind/connect to when migrating disks. This can be tcp://address:port to specify a listen address (which overrides --migrate-uri and --listen-address for the disk migration) and a port, or unix:///path/to/socket in case you need the disk migration to happen over a UNIX socket with that specified path. In this case you need to make sure the same socket path is accessible to both source and destination hypervisors and connecting to the socket on the source (after the hypervisor creates it on the destination) will actually connect to the destination. If you are using SELinux (at least on the source host) you need to make sure the socket on the source is accessible to libvirtd/QEMU for connection. Libvirt cannot change the context of the existing socket because it is different from the file representation of the socket and the context is chosen by its creator (usually by using setsockcreatecon{,_raw}() functions). ๐Ÿ˜ญ

Optional --available-switchover-bandwidth overrides the automatically computed bandwidth (in MiB/s) available for the final phase of (pre-copy) migration during which CPUs are stopped and all the remaining memory and device state is transferred. Knowing this bandwidth is important for accurate estimation of the domain downtime and deciding the right moment for switching over. Normally this would be estimated based on the bandwidth used by migration, but this could be lower than the actual available bandwidth. Using this option may help with migration convergence when the migration would keep iterating over and over thinking there's not enough bandwidth to comply with the configured maximum downtime. ๐Ÿ”ฅ


๐ŸŽ€ migrate-compcache ๐ŸŽ€

Syntax:

migrate-compcache domain [--size bytes]

Sets and/or gets the size of the cache (in bytes) used for compressing repeatedly transferred memory pages during live migration. When called without size, the command just prints the current size of the compression cache. When size is specified, the hypervisor is asked to change the compression cache to size bytes and then the current size is printed (the result may differ from the requested size due to rounding done by the hypervisor). The size option is supposed to be used while the domain is being live-migrated, as a reaction to migration progress and an increasing number of compression cache misses obtained from domjobinfo. โœจ


๐ŸŒˆ migrate-getmaxdowntime ๐ŸŒˆ

Syntax:

migrate-getmaxdowntime domain

Get the maximum tolerable downtime for a domain which is being live-migrated to another host. This is the number of milliseconds the guest is allowed to be down at the end of live migration. ๐Ÿ’–


๐Ÿฆ‹ migrate-getspeed ๐Ÿฆ‹

Syntax:

migrate-getspeed domain [--postcopy]

Get the maximum migration bandwidth (in MiB/s) for a domain. If the --postcopy option is specified, the command will get the maximum bandwidth allowed during a post-copy migration phase. โญ


๐Ÿ’… migrate-postcopy ๐Ÿ’…

Syntax:

migrate-postcopy domain

Switch the current migration from pre-copy to post-copy. This is only supported for a migration started with the --postcopy option. No cap, it has to have been started that way. ๐Ÿ‘‘


๐Ÿ“ migrate-setmaxdowntime ๐Ÿ“

Syntax:

migrate-setmaxdowntime domain downtime

Set the maximum tolerable downtime for a domain which is being live-migrated to another host. The downtime is a number of milliseconds the guest is allowed to be down at the end of live migration. ๐Ÿซถ


๐Ÿงš migrate-setspeed ๐Ÿงš

Syntax:

migrate-setspeed domain bandwidth [--postcopy]

okay so this next bit is still the bandwidth situation: set the maximum migration bandwidth (in MiB/s) for a domain that's being migrated to another host. bandwidth is interpreted as an unsigned long long value. Specifying a negative value results in an essentially unlimited value being provided to the hypervisor. The hypervisor can choose whether to reject the value or convert it to the maximum value allowed. If the --postcopy option is specified, the command will set the maximum bandwidth allowed during a post-copy migration phase. ๐Ÿ’…


๐ŸŒธ numatune

Syntax:

numatune domain [--mode mode] [--nodeset nodeset]
   [[--config] [--live] | [--current]]

Set or get a domain's numa parameters, corresponding to the <numatune> element of domain XML. Without flags, the current settings are displayed. โœจ

mode can be one of strict, interleave, preferred and restrictive or any valid number from the virDomainNumatuneMemMode enum in case the daemon supports it. For a running domain, the mode can't be changed, and the nodeset can be changed only if the domain was started with restrictive mode. ๐Ÿ˜ญ

nodeset is a list of numa nodes used by the host for running the domain. Its syntax is a comma separated list, with - for ranges and ^ for excluding a node.

  • --mode mode โ€” set the numa memory mode to one of strict, interleave, preferred, restrictive, or a valid number from virDomainNumatuneMemMode if the daemon supports it.
  • --nodeset nodeset โ€” set the numa node list, like 0-3,^1 (comma separated, - for ranges, ^ to exclude).
  • --live โ€” set scheduler information of a running guest.
  • --config โ€” affect the next start of a persistent guest.
  • --current โ€” equivalent to either --live or --config, depending on the current state of the guest.

For running guests on Linux hosts, the changes made in the domain's numa parameters do not imply that the guest memory will be moved to a different nodeset immediately. The memory migration depends on the guest activity, and the memory of an idle guest will remain in its previous nodeset for longer. The presence of VFIO devices will also lock parts of the guest memory in the same nodeset used to start the guest, regardless of nodeset changes. no cap, that's just how it is ๐Ÿซถ


๐Ÿ”ฅ perf

Syntax:

perf domain [--enable eventSpec] [--disable eventSpec]
   [[--config] [--live] | [--current]]

Get the current perf events setting or enable/disable specific perf events for a guest domain. ๐Ÿ‘‘

Perf is a performance analyzing tool in Linux, and it can instrument CPU performance counters, tracepoints, kprobes, and uprobes (dynamic tracing). Perf supports a list of measurable events, and can measure events coming from different sources. For instance, some events are pure kernel countersโ€”those are called software events, including context-switches, minor-faults, etc. Now dozens of events from different sources can be supported by perf. โœจ

Currently only QEMU/KVM supports this command. The --enable and --disable options combined with eventSpec can be used to enable or disable a specific performance event. eventSpec is a string list of one or more events separated by commas. Valid event names are as follows:

Valid perf event names

  • cmt โ€” A PQos (Platform Qos) feature to monitor the usage of cache by applications running on the platform.
  • mbmt โ€” Provides a way to monitor the total system memory bandwidth between one level of cache and another.
  • mbml โ€” Provides a way to limit the amount of data (bytes/s) send through the memory controller on the socket.
  • cache_misses โ€” Provides the count of cache misses by applications running on the platform.
  • cache_references โ€” Provides the count of cache hits by applications running on the platform.
  • instructions โ€” Provides the count of instructions executed by applications running on the platform.
  • cpu_cycles โ€” Provides the count of cpu cycles (total/elapsed). May be used with instructions in order to get a cycles per instruction.
  • branch_instructions โ€” Provides the count of branch instructions executed by applications running on the platform.
  • branch_misses โ€” Provides the count of branch misses executed by applications running on the platform.
  • bus_cycles โ€” Provides the count of bus cycles executed by applications running on the platform.
  • stalled_cycles_frontend โ€” Provides the count of stalled cpu cycles in the frontend of the instruction processor pipeline by applications running on the platform.
  • stalled_cycles_backend โ€” Provides the count of stalled cpu cycles in the backend of the instruction processor pipeline by applications running on the platform.
  • ref_cpu_cycles โ€” Provides the count of total cpu cycles not affected by CPU frequency scaling by applications running on the platform.
  • cpu_clock โ€” Provides the cpu clock time consumed by applications running on the platform.
  • task_clock โ€” Provides the task clock time consumed by applications running on the platform.
  • page_faults โ€” Provides the count of page faults by applications running on the platform.
  • context_switches โ€” Provides the count of context switches by applications running on the platform.
  • cpu_migrations โ€” Provides the count of cpu migrations by applications running on the platform.
  • page_faults_min โ€” Provides the count of minor page faults by applications running on the platform.
  • page_faults_maj โ€” Provides the count of major page faults by applications running on the platform.
  • alignment_faults โ€” Provides the count of alignment faults by applications running on the platform.
  • emulation_faults โ€” Provides the count of emulation faults by applications running on the platform.
Note: The statistics can be retrieved using the domstats command using the --perf flag.
  • --enable eventSpec โ€” enable the perf event(s) in the comma-separated list.
  • --disable eventSpec โ€” disable the perf event(s) in the comma-separated list.
  • --live โ€” affect a running guest.
  • --config โ€” affect the next start of a persistent guest.
  • --current โ€” equivalent to either --live or --config, depending on the current state of the guest.

Both --live and --config flags may be given, but --current is exclusive. If no flag is specified, behavior is different depending on hypervisor. ๐Ÿ˜ญ iykyk


๐ŸŽ€ reboot

Syntax:

reboot domain [--mode MODE-LIST]

Reboot a domain. This acts just as if the domain had the reboot command run from the console. The command returns as soon as it has executed the reboot action, which may be significantly before the domain actually reboots. โญ

The exact behavior of a domain when it reboots is set by the on_reboot parameter in the domain's XML definition.

By default the hypervisor will try to pick a suitable shutdown method. To specify an alternative method, the --mode parameter can specify a comma separated list which includes acpi, agent, initctl, signal and paravirt. The order in which drivers will try each mode is undefined, and not related to the order specified to virsh. For strict control over ordering, use a single mode at a time and repeat the command. ๐Ÿ’…

  • --mode MODE-LIST โ€” comma-separated list of reboot methods: acpi, agent, initctl, signal, paravirt.

๐Ÿ’€ reset

Syntax:

reset domain

Reset a domain immediately without any guest shutdown. reset emulates the power reset button on a machine, where all guest hardware sees the RST line set and reinitializes internal state. ๐Ÿ”ฅ

Note: Reset without any guest OS shutdown risks data loss. literally be careful, bestie ๐Ÿ˜ญ

๐Ÿฆ‹ restore

Syntax:

restore state-file [--bypass-cache] [--xml file]
   [{--running | --paused}] [--reset-nvram] [--parallel-channels]

Restores a domain from a virsh save state file. See save for more info. ๐Ÿ’–

  • --bypass-cache โ€” avoid the file system cache. Depending on the specific scenario this may slow down or speed up the operation.
  • --xml file โ€” usually omitted, but can supply an alternative XML file for use on the restored guest with changes only in the host-specific portions of the domain XML. For example, it can be used to account for file naming differences in underlying storage due to disk snapshots taken after the guest was saved.
  • --running โ€” override the recorded state and start the restored domain running.
  • --paused โ€” override the recorded state and start the restored domain paused.
  • --reset-nvram โ€” delete any existing NVRAM/varstore file and re-initialize it from its pristine template.
  • --parallel-channels โ€” specify the number of parallel IO channels to be used when loading memory from file. The page also says parallel save may significantly reduce the time required to save large memory domains.

Normally, restoring a saved image will use the state recorded in the save image to decide between running or paused; passing either the --running or --paused flag will allow overriding which state the domain should be started in. โœจ

Note: To avoid corrupting file system contents within the domain, you should not reuse the saved state file for a second restore unless you have also reverted all storage volumes back to the same contents as when the state file was created. fr fr do not skip this part ๐Ÿซถ

๐ŸŒˆ resume

Syntax:

resume domain

Moves a domain out of the suspended state. This will allow a previously suspended domain to now be eligible for scheduling by the underlying hypervisor. ๐Ÿ‘‘


๐Ÿ“ save

Syntax:

save domain state-file [--bypass-cache] [--xml file]
   [--image-format format]
   [--parallel-channels channels]
   [{--running | --paused}] [--verbose]

Saves a running domain (RAM, but not disk state) to a state file so that it can be restored later. Once saved, the domain will no longer be running on the system, thus the memory allocated for the domain will be free for other domains to use. virsh restore restores from this state file. ๐Ÿ’พ

  • --bypass-cache โ€” avoid the file system cache. Depending on the specific scenario this may slow down or speed up the operation.
  • --xml file โ€” usually omitted, but can supply an alternative XML file for use on the restored guest with changes only in the host-specific portions of the domain XML. For example, it can be used to account for file naming differences that are planned to be made via disk snapshots of underlying storage after the guest is saved.
  • --image-format format โ€” change the default image format used to save data into file. For more details consult the qemu.conf configuration file.
  • --parallel-channels channels โ€” number of parallel IO channels to use when saving/loading memory.
  • --running โ€” override the recorded state so the restore uses running.
  • --paused โ€” override the recorded state so the restore uses paused.
  • --verbose โ€” display the progress of save.

The progress may be monitored using the domjobinfo virsh command and canceled with the domjobabort command (sent by another virsh instance). Another option is to send SIGINT (usually with Ctrl+C) to the virsh process running the save command. --verbose displays the progress of save. ๐Ÿ˜ญ

This is roughly equivalent to doing a hibernate on a running computer, with all the same limitations. Open network connections may be severed upon restore, as TCP timeouts may have expired. ๐Ÿ’…

Normally, restoring a saved image will decide between running or paused based on the state the domain was in when the save was done; passing either the --running or --paused flag will allow overriding which state the restore should use. โœจ

Like, the --parallel-channels option lets you pick how many parallel IO channels get used when you're saving memory to a file ๐Ÿ’จ โ€” and heads up, using parallel IO channels requires the sparse image save format. The payoff is real though: parallel saving can significantly cut down the time it takes to save big memory domains. Slay for big guests.

Okay but here's the vibe check on domain saved state files: they assume your disk images will be unchanged between when you create the save and when you restore it ๐Ÿ‘€. So if you want a genuinely complete system restore point โ€” one where the disk state gets saved right alongside the memory state โ€” go look at the snapshot family of commands instead. That's the one you want, iykyk.

๐ŸŒธ save-image-define

Syntax:

save-image-define file xml [{--running | --paused}]

This one updates the domain XML that'll be used later when file gets fed into the restore command โœจ. The xml argument has to be a file name holding the alternative XML โ€” and the changes should only be in the host-specific portions of the domain XML. Like, for example, it's the tool for accounting for file naming differences that pop up when you make disk snapshots of the underlying storage after the guest was already saved. Very niche, very necessary.

The save image records whether the domain should be restored to a running or paused state. Normally this command doesn't touch that recorded state โ€” but if you pass either --running or --paused, you get to override which state the restore uses. Main character energy, honestly ๐Ÿ‘‘.

๐Ÿฆ‹ save-image-dumpxml

Syntax:

save-image-dumpxml [--security-info] [--xpath EXPRESSION] [--wrap] file

Extracts the domain XML that was in effect at the exact moment the saved state file file was created with the save command ๐Ÿ“ธ. If you pass --security-info, you'll also get the security sensitive information included โ€” spicy ๐Ÿ”ฅ.

Now, if --xpath hands over an XPath expression, it gets evaluated against the output XML, and only those matching nodes get printed. Default behaviour is printing each matching node as its own standalone document โ€” but for ease of additional processing, --wrap makes the matching node get wrapped in a common root node. So organized ๐Ÿ’….

๐ŸŽ€ save-image-edit

Syntax:

save-image-edit file [{--running | --paused}]

Edits the XML configuration tied to a saved state file file that was created by the save command โœ๏ธ.

Same deal as before: the save image records whether the domain should be restored to a running or paused state, and normally this command doesn't alter that recorded state. Passing either --running or --paused lets you override which state the restore should use.

This whole thing is equivalent to:

virsh save-image-dumpxml state-file > state-file.xml
vi state-file.xml (or make changes with your other text editor)
virsh save-image-define state-file state-file-xml

โ€ฆexcept that it does some error checking for you ๐Ÿซถ. The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and it defaults to vi.

๐Ÿ’œ schedinfo

Syntax:

schedinfo domain [[--config] [--live] | [--current]] [[--set] parameter=value]...
schedinfo [--weight number] [--cap number] domain

Lets you show (and set!) the domain scheduler parameters โš™๏ธ. The parameters available for each hypervisor are:

  • LXC (posix scheduler) : cpu_shares, vcpu_period, vcpu_quota
  • QEMU/KVM (posix scheduler): cpu_shares, vcpu_period, vcpu_quota, emulator_period, emulator_quota, global_period, global_quota, iothread_period, iothread_quota
  • Xen (credit scheduler): weight, cap
  • ESX (allocation scheduler): reservation, limit, shares

If --live is specified, you set scheduler info on a running guest. If --config is specified, you affect the next start of a persistent guest. And if --current is specified, that's equivalent to either --live or --config, depending on the current state of the guest ๐Ÿ‘.

Note: the cpu_shares parameter has a valid value range of 2-262144 with cgroups v1, and 1-10000 with cgroups v2.
Note: the weight and cap parameters are defined only for the XEN_CREDIT scheduler.
Note: the vcpu_period, emulator_period, and iothread_period parameters have a valid value range of 1000-1000000 or 0, and the vcpu_quota, emulator_quota, and iothread_quota parameters have a valid value range of 1000-17592186044415 or less than 0. A value of 0 for either parameter is the same as not specifying that parameter at all. No cap, literally ๐ŸŒˆ.

๐Ÿ“ธ screenshot

Syntax:

screenshot domain [imagefilepath] [--screen screenID]

Takes a screenshot of a current domain console and stores it into a file โ€” say cheese ๐Ÿงš. Optionally, if the hypervisor supports more displays for a domain, screenID lets you specify which screen gets captured. It's the sequential number of the screen. And in case of multiple graphics cards, heads are enumerated before devices โ€” so like, if you have two graphics cards both with four heads, screen ID 5 addresses the second head on the second card. The way that numbering works is genuinely wild ๐Ÿ˜ญ.

โŒจ๏ธ send-key

Syntax:

send-key domain [--codeset codeset] [--holdtime holdtime] keycode...

Parses the keycode sequence as keystrokes to send to domain ๐Ÿซฐ. Each keycode can either be a numeric value or a symbolic name from the corresponding codeset. If --holdtime is given, each keystroke gets held for that many milliseconds. Default codeset is linux, but the --codeset option lets you choose other codesets.

Lowkey important: if multiple keycodes are specified, they're all sent simultaneously to the guest, and they may be received in random order ๐Ÿ’€. If you need distinct keypresses, you have to use multiple send-key invocations. Periodt.
  • linux The numeric values are those defined by the Linux generic input event subsystem. The symbolic names match the corresponding Linux key constant macro names.

See virkeycode-linux(7) and virkeyname-linux(7)

  • xt The numeric values are those defined by the original XT keyboard controller. No symbolic names are provided.

See virkeycode-xt(7)

  • atset1 The numeric values are those defined by the AT keyboard controller, set 1 (aka XT compatible set). Extended keycodes from atset1 may differ from extended keycodes in the xt codeset. No symbolic names are provided.

See virkeycode-atset1(7)

  • atset2 The numeric values are those defined by the AT keyboard controller, set 2. No symbolic names are provided.

See virkeycode-atset2(7)

  • atset3 The numeric values are those defined by the AT keyboard controller, set 3 (aka PS/2 compatible set). No symbolic names are provided.

See virkeycode-atset3(7)

  • os_x The numeric values are those defined by the macOS keyboard input subsystem. The symbolic names match the corresponding macOS key constant macro names.

See virkeycode-osx(7) and virkeyname-osx(7)

  • xt_kbd The numeric values are those defined by the Linux KBD device. These are a variant on the original XT codeset, but often with different encoding for extended keycodes. No symbolic names are provided.

See virkeycode-xtkbd(7)

  • win32 The numeric values are those defined by the Win32 keyboard input subsystem. The symbolic names match the corresponding Win32 key constant macro names.

See virkeycode-win32(7) and virkeyname-win32(7)

  • usb The numeric values are those defined by the USB HID specification for keyboard input. No symbolic names are provided.

See virkeycode-usb(7)

  • qnum The numeric values are those defined by the QNUM extension for sending raw keycodes. These are a variant on the XT codeset, but extended keycodes have the low bit of the second byte set, instead of the high bit of the first byte. No symbolic names are provided.

See virkeycode-qnum(7)

Examples:

# send three strokes 'k', 'e', 'y', using xt codeset. these
# are all pressed simultaneously and may be received by the guest
# in random order
virsh send-key dom --codeset xt 37 18 21

# send one stroke 'right-ctrl+C'
virsh send-key dom KEY_RIGHTCTRL KEY_C

# send a tab, held for 1 second
virsh send-key --holdtime 1000 0xf

๐ŸŽฏ send-process-signal

Syntax:

send-process-signal domain-id pid signame

Sends a signal signame to the process identified by pid running in the virtual domain domain-id ๐Ÿซก. The pid is a process ID in the virtual domain namespace.

The signame argument may be either an integer signal constant number, or one of these symbolic names:

"nop", "hup", "int", "quit", "ill",
"trap", "abrt", "bus", "fpe", "kill",
"usr1", "segv", "usr2", "pipe", "alrm",
"term", "stkflt", "chld", "cont", "stop",
"tstp", "ttin", "ttou", "urg", "xcpu",
"xfsz", "vtalrm", "prof", "winch", "poll",
"pwr", "sys", "rt0", "rt1", "rt2", "rt3",
"rt4", "rt5", "rt6", "rt7", "rt8", "rt9",
"rt10", "rt11", "rt12", "rt13", "rt14", "rt15",
"rt16", "rt17", "rt18", "rt19", "rt20", "rt21",
"rt22", "rt23", "rt24", "rt25", "rt26", "rt27",
"rt28", "rt29", "rt30", "rt31", "rt32"

The symbol name may optionally be prefixed with sig or sig_, and may be in uppercase or lowercase ๐Ÿ’–. So flexible.

Examples:

virsh send-process-signal myguest 1 15
virsh send-process-signal myguest 1 term
virsh send-process-signal myguest 1 sigterm
virsh send-process-signal myguest 1 SIG_HUP

๐ŸŒ€ set-lifecycle-action

Syntax:

set-lifecycle-action domain type action
   [[--config] [--live] | [--current]]

Sets the lifecycle action for the specified lifecycle type โœจ. The valid types are "poweroff", "reboot" and "crash", and for each of them the valid action is one of "destroy", "restart", "rename-restart", "preserve". And for type "crash", there are additional actions supported: "coredump-destroy" and "coredump-restart". Choose your fighter ๐Ÿ’….

๐Ÿ” set-user-password

Syntax:

set-user-password domain user password [--encrypted]

Sets the password for the user account in the guest domain ๐Ÿ”‘.

If --encrypted is specified, the password is assumed to already be encrypted by the method the guest OS requires.

For QEMU/KVM, this requires the guest agent to be configured and running โ€” no agent, no dice ๐Ÿ™ˆ.

๐Ÿ—๏ธ set-user-sshkeys

Syntax:

set-user-sshkeys domain user [--file FILE] [{--reset | --remove}]

Appends keys read from FILE into the user's SSH authorized keys file in the guest domain ๐ŸŒธ. In the FILE, keys must be on separate lines, and each line must follow authorized keys format as defined by sshd(8).

If --reset is specified, then the guest authorized keys file content gets removed before appending the new keys. As a special case: if --reset is provided and no FILE was provided, then no new keys are added and the authorized keys file is just cleared out ๐Ÿงน.

If --remove is specified, then instead of adding new keys, the keys read from FILE get removed from the authorized keys file. And it's not considered an error if the key doesn't exist in the file โ€” very forgiving, we love that ๐Ÿซถ.

โš–๏ธ setmaxmem

Syntax:

setmaxmem domain size [[--config] [--live] | [--current]]

Change the maximum memory allocation limit for a guest domain. Slap --live on there and you're affecting a running guest. Add --config and you're affecting the next start of a persistent guest. --current is the chill one โ€” it's literally equivalent to either --live or --config, whichever matches the current state of the guest. You can give both --live and --config together, but --current is exclusive (it's not a group project, bestie). And if you pass no flag at all, the behavior changes depending on the hypervisor. ๐Ÿ™ƒ

Okay so real talk: some hypervisors, QEMU/KVM for example, don't support live changes of the maximum memory limit (especially increasing it). Even persistent configuration changes might not happen with some hypervisors/configs (like on NUMA enabled domains on QEMU). For complex configuration changes, use the edit command instead. ๐Ÿ’…

size is a scaled integer (peep the NOTES above); it defaults to kibibytes (blocks of 1024 bytes) unless you give it a suffix (and heads up, the older option name --kilobytes still exists as a deprecated synonym). Libvirt rounds up to the nearest kibibyte. Some hypervisors require a bigger granularity than KiB, and requests that aren't an even multiple get rounded up. Example: vSphere/ESX rounds the parameter up to mebibytes (1024 kibibytes).


๐Ÿง  setmem

Syntax:

setmem domain size [[--config] [--live] | [--current]]

Change the memory allocation for a guest domain. Give it --live and it performs a memory balloon on a running guest. Give it --config and it affects the next start of a persistent guest. Give it --current and it's equivalent to either --live or --config depending on the current state of the guest. Both --live and --config may be given, but --current is exclusive, no exceptions. No flag at all? Then behavior differs depending on hypervisor. โœจ

size is a scaled integer (see NOTES above); it defaults to kibibytes (blocks of 1024 bytes) unless you provide a suffix (and yep, the older option name --kilobytes is available as a deprecated synonym). Libvirt rounds up to the nearest kibibyte. Some hypervisors require a larger granularity than KiB, and requests that aren't an even multiple will be rounded up. For example, vSphere/ESX rounds the parameter up to mebibytes (1024 kibibytes).

For Xen, you can only adjust the memory of a running domain if the domain is paravirtualized or running the PV balloon driver.

For LXC, the value being set is the cgroups value for limit_in_bytes or the maximum amount of user memory (including file cache). When viewing memory inside the container, this is the /proc/meminfo "MemTotal" value. When viewing the value from the host, use the virsh memtune command. And in order to view the current memory in use and the maximum value allowed to set memory, use the virsh dominfo command.


๐ŸŽ›๏ธ setvcpus

Syntax:

setvcpus domain count [--maximum] [[--config] [--live] | [--current]] [--guest] [--hotpluggable] [--async]

Change the number of virtual CPUs active in a guest domain. By default this command works on active guest domains. Wanna change the settings for an inactive guest domain? Use the --config flag. ๐Ÿฆ‹

The count value may be limited by the host, the hypervisor, or a limit coming from the original description of the guest domain. For Xen, you can only adjust the virtual CPUs of a running domain if the domain is paravirtualized.

If you specify --config, the change is made to the stored XML configuration for the guest domain, and it only takes effect when the guest domain is next started.

If --live is specified, the guest domain must be active, and the change takes place immediately. Both --config and --live may be specified together if the hypervisor supports it. โš ๏ธ If you run this command before the guest has finished booting, the guest may fail to process the change.

If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest.

When no flags are given, --live is assumed and the guest domain must be active. In this situation it's up to the hypervisor whether --config is also assumed, and therefore whether the XML configuration is adjusted to make the change persistent.

If --async is specified, live vCPU unplug requests are fired without waiting for the guest to comply. Final completion is reported by the vcpu-removed domain event, while rejected unplug requests continue to be reported by device-removal-failed. This flag cannot be combined with --guest. ๐Ÿšซ

If --guest is specified, then the count of cpus is modified in the guest instead of the hypervisor. This flag is usable only for live domains and may require a guest agent to be configured in the guest.

To allow adding vcpus to persistent definitions that can be later hotunplugged after the domain is booted, you gotta specify the --hotpluggable flag. Vcpus added to live domains supporting vcpu unplug are automatically marked as hotpluggable. ๐Ÿ”ฅ

The --maximum flag controls the maximum number of virtual cpus that can be hot-plugged the next time the domain is booted. As such, it must only be used with the --config flag, and not with --live or --current. Note that it may not be possible to change the maximum vcpu count if the processor topology is specified for the guest.


๐Ÿ”Œ setvcpu

Syntax:

setvcpu domain vcpulist [--enable] | [--disable] [--async]
   [[--live] [--config] | [--current]]

Change the state of individual vCPUs using the hot(un)plug mechanism. ๐Ÿ’…

See vcpupin for info on the format of vcpulist. Hypervisor drivers may require that vcpulist contains exactly vCPUs belonging to one hotpluggable entity. Usually that's just a single vCPU, but certain architectures such as ppc64 require a full core to be specified at once.

Heads up: hypervisors may refuse to disable certain vcpus, such as vcpu 0 or others. ๐Ÿ™ˆ

If --live is specified, it affects a running domain. If --config is specified, it affects the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest โ€” and that's the default. Both --live and --config may be given, but --current is exclusive.

If --async is specified with --disable, live vCPU unplug requests are fired without waiting for the guest to comply. Final completion of this operation is reported by the vcpu-removed domain event, while rejected unplug requests continue to be reported by device-removal-failed.


๐ŸŒ™ shutdown

Syntax:

shutdown domain [--mode MODE-LIST]

Gracefully shuts down a domain. It coordinates with the domain OS to do a graceful shutdown, so likeโ€ฆ there's no guarantee it'll succeed ๐Ÿ˜ญ and it may take a variable amount of time depending on what services must be shut down in the domain.

The exact behavior of a domain when it shuts down is set by the on_poweroff parameter in the domain's XML definition.

If domain is transient, then the metadata of any snapshots and checkpoints will be lost once the guest stops running โ€” but the underlying contents still exist, and a new domain with the same name and UUID can restore the snapshot metadata with snapshot-create, and the checkpoint metadata with checkpoint-create. ๐Ÿซถ

By default the hypervisor tries to pick a suitable shutdown method. To specify an alternative, the --mode parameter can take a comma separated list including acpi, agent, initctl, signal and paravirt. The order in which drivers try each mode is undefined, and not related to the order you specified to virsh. For strict control over ordering, use a single mode at a time and repeat the command. ๐ŸŽ€


๐Ÿš€ start

Syntax:

start domain-name-or-uuid [--console] [--paused]
   [--autodestroy] [--bypass-cache] [--force-boot]
   [--pass-fds N,M,...] [--reset-nvram]

Start a (previously defined) inactive domain, either from the last managedsave state, or via a fresh boot if there's no managedsave state present. The domain will be paused if you use the --paused option and the driver supports it; otherwise it'll be running. If you ask for --console, it attaches to the console after creation. If you ask for --autodestroy, then the guest gets automatically destroyed when virsh closes its connection to libvirt, or otherwise exits. If --bypass-cache is specified and managedsave state exists, the restore avoids the file system cache โ€” although this may slow down the operation ๐ŸŒ. If --force-boot is specified, then any managedsave state is discarded and a fresh boot occurs.

If --pass-fds is specified, the argument is a comma separated list of open file descriptors that should be passed into the guest. The file descriptors will be re-numbered in the guest, starting from 3. This is only supported with container based virtualization. ๐Ÿ“

If --reset-nvram is specified, any existing NVRAM/varstore file will be deleted and re-initialized from its pristine template. โœจ


๐Ÿ˜ด suspend

Syntax:

suspend domain

Suspend a running domain. It's kept in memory but won't be scheduled anymore. Literally the "brb bestie" of commands. ๐Ÿ’ค


๐Ÿ–ฅ๏ธ ttyconsole

Syntax:

ttyconsole domain

Output the device used for the TTY console of the domain. If the info isn't available, the process will provide an exit code of 1. ๐Ÿ˜ญ


๐Ÿ—‘๏ธ undefine

Syntax:

undefine domain [--managed-save] [--snapshots-metadata]
   [--checkpoints-metadata] [--nvram] [--keep-nvram]
   [ {--storage volumes | --remove-all-storage
      [--delete-storage-volume-snapshots]} --wipe-storage]
   [--tpm] [--keep-tpm]

Undefine a domain. If the domain is running, this converts it to a transient domain โ€” without stopping it. If the domain is inactive, the domain configuration is removed. ๐Ÿ‘‹

The --managed-save flag guarantees that any managed save image (see the managedsave command) is also cleaned up. Without the flag, attempts to undefine a domain with a managed save image will fail.

The --snapshots-metadata flag guarantees that any snapshots (see the snapshot-list command) are also cleaned up when undefining an inactive domain. Without the flag, attempts to undefine an inactive domain with snapshot metadata will fail. If the domain is active, this flag is ignored.

The --checkpoints-metadata flag guarantees that any checkpoints (see the checkpoint-list command) are also cleaned up when undefining an inactive domain. Without the flag, attempts to undefine an inactive domain with checkpoint metadata will fail. If the domain is active, this flag is ignored.

The --nvram and --keep-nvram flags specify whether to delete or keep the NVRAM (/domain/os/nvram/) or varstore (/domain/os/varstore) file respectively. โš ๏ธ If the domain has an NVRAM/varstore file and the flags are omitted, the undefine operation will fail.

  • --storage โ€” okay so this one takes a parameter, volumes, which is a comma-separated list of volume target names or source paths of the storage volumes you want yeeted along with the undefined domain ๐Ÿ’… Heads up tho: volumes can only be undefined (and thus removed) on inactive domains, no cap. Volume deletion is only attempted after the domain is undefined, and if not all the requested volumes could be deleted, the error message tells you what's still lurking behind ๐Ÿ˜ญ If a volume path isn't found in the domain definition, it's treated as if the volume was successfully deleted (fake it till you make it, bestie โœจ). Only volumes managed by libvirt in storage pools can be removed this way. Also note it only removes the top level image of a backing chain โ€” any backing stores of the image are kept, since they might be shared ๐Ÿซถ (peep domblklist for the list of target names associated to a domain, iykyk). Example: --storage vda,/path/to/storage.img
  • --remove-all-storage โ€” this flag says: every single storage volume this domain has? delete it, as if you'd listed them all via --storage. All of them. Periodt ๐Ÿ”ฅ
  • --delete-storage-volume-snapshots (previously --delete-snapshots, iconic rebrand ๐Ÿ’…) โ€” says any snapshots associated with the storage volume should be deleted too. Requires the --remove-all-storage flag to be provided, so don't skip that step. Not all storage drivers support this option โ€” presently only rbd does. And if you use it while also removing volumes handled by a storage driver that doesn't support the flag, you get a failure ๐Ÿ’€
  • --wipe-storage โ€” says the storage volumes should be wiped before removal. Clean it up before you throw it out, we love a tidy queen ๐ŸŽ€
  • --tpm and --keep-tpm โ€” these bad boys specify accordingly whether to delete or keep a TPM's persistent state directory structure and files. If the flags are omitted, then the persistent_state attribute in the TPM emulator definition in the domain XML decides whether the TPM state is kept ๐Ÿ‘‘
NOTE: for an inactive domain, the domain name or UUID must be used as the domain. No shortcuts, bestie ๐Ÿ™ˆ

๐ŸŒธ vcpucount ๐ŸŒธ

Syntax:

vcpucount domain  [{--maximum | --active}
   {--config | --live | --current}] [--guest]

Prints info about the virtual cpu counts of the given domain, and honestly it's giving spreadsheet energy in the best way ๐Ÿ’– If you specify no flags at all, every possible count is listed in a table; otherwise, the output is limited to just the numeric value you asked for. And for historical reasons (don't ask ๐Ÿ˜ญ), the table lists the label "current" on the rows that can be queried in isolation via the --active flag โ€” rather than relating to the --current flag. Yes, confusing. No, we can't change it.

  • --maximum โ€” requests info on the max cap of vcpus that a domain can add via setvcpus, while --active shows the current usage. These two flags cannot both be specified, pick a lane ๐ŸŒˆ
  • --config โ€” requires a persistent guest and requests info regarding the next time the domain will be booted
  • --live โ€” requires a running domain and lists current values
  • --current โ€” queries according to the current state of the domain (corresponding to --live if running, or --config if inactive)

Those last three flags are mutually exclusive, so no, you can't have all three ๐Ÿ’€

If --guest is specified, then the count of cpus is reported from the perspective of the guest ๐Ÿ‘€ This flag is usable only for live domains and may require the guest agent to be configured in the guest, so set that up first bestie.


๐Ÿฆ‹ vcpuinfo ๐Ÿฆ‹

Syntax:

vcpuinfo domain [--pretty]

Returns basic info about the domain's virtual CPUs โ€” like the number of vCPUs, the running time, the affinity to physical processors. It's a whole vibe check for your CPUs ๐Ÿ’…

With --pretty, cpu affinities are shown as ranges, which is so much easier on the eyes ngl.

Example:

$ virsh vcpuinfo fedora
VCPU:           0
CPU:            0
State:          running
CPU time:       7,0s
CPU Affinity:   yyyy

VCPU:           1
CPU:            1
State:          running
CPU time:       0,7s
CPU Affinity:   yyyy

โšก STATES โšก

The State field displays the current operating state of a virtual CPU. Here's the roster:

  • offline โ€” the virtual CPU is offline and not usable by the domain. This state is not supported by all hypervisors ๐Ÿ™ˆ
  • running โ€” the virtual CPU is available to the domain and is operating. Main character energy ๐Ÿ‘‘
  • blocked โ€” the virtual CPU is available to the domain but is waiting for a resource. This state is not supported by all hypervisors, in which case running may be reported instead ๐Ÿ’€
  • no state โ€” the virtual CPU state could not be determined. This could happen if the hypervisor is newer than virsh (imagine being outdressed by your own hypervisor ๐Ÿ˜ญ)
  • N/A โ€” there's no information about the virtual CPU state available. This can be the case if the domain is not running, or the hypervisor doesn't report the virtual CPU state.

๐ŸŽ€ vcpupin ๐ŸŽ€

Syntax:

vcpupin domain [vcpu] [cpulist] [[--live] [--config] | [--current]]

Query or change the pinning of domain VCPUs to host physical CPUs ๐Ÿซถ To pin a single vcpu, specify cpulist; otherwise, you can query one vcpu or just omit vcpu to list all at once. Efficiency, slay.

cpulist is a list of physical CPU numbers โœจ Its syntax is a comma-separated list, and special markup using - and ^ (ex. 0-4, 0-3,^2) can also be allowed. The - denotes the range and the ^ denotes exclusive. To pin the vcpu to all physical cpus, specify r as a cpulist ๐Ÿ†

If --live is specified, affect a running guest. If --config is specified, affect the next start of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given if cpulist is present, but --current is exclusive ๐Ÿ’… If no flag is specified, behavior is different depending on hypervisor (mystery era, we don't love it).

Note: the expression is sequentially evaluated, so "0-15,^8" is identical to "9-14,0-7,15" but not identical to "^8,0-15". Order matters, bestie ๐Ÿ˜ญ

๐Ÿงš vncdisplay ๐Ÿงš

Syntax:

vncdisplay domain

Outputs the IP address and port number for the VNC display ๐Ÿ–ฅ๏ธ If the information is not available, the processes will provide an exit code of 1 โ€” so if you get a 1, that's why, don't spiral ๐Ÿ’€


๐Ÿ’… DEVICE COMMANDS ๐Ÿ’…

The following commands manipulate devices associated to domains ๐Ÿ”ง The domain can be specified as a short integer, a name, or a full UUID. To better understand the values allowed as options for the command, read the documentation at https://libvirt.org/formatdomain.html on the format of the device sections โ€” that's where you get the most accurate set of accepted values, fr fr ๐Ÿ“š


๐ŸŒˆ attach-device ๐ŸŒˆ

Syntax:

attach-device domain FILE [[[--live] [--config] | [--current]] | [--persistent]]

Attaches a device to the domain, using a device definition in an XML file โ€” and it uses a device definition element such as <disk> or <interface> as the top-level element, okay? See the docs at https://libvirt.org/formatdomain.html#elementsDevices to learn about the libvirt XML format for a device, it's all there ๐Ÿซถ

If --config is specified, the command alters the persistent guest configuration, with the device attach taking effect the next time libvirt starts the domain โœจ For cdrom and floppy devices, this command only replaces the media within an existing device โ€” consider using update-device for that usage instead. And for passthrough host devices, see also nodedev-detach, which you need if the PCI device doesn't use managed mode ๐Ÿ‘‘

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive ๐Ÿ’… When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver (again: mystery era ๐Ÿ˜ญ).

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain. Iconic dual citizenship behavior ๐Ÿ‘‘.

Note: using partial device definition XML files may lead to unexpected results, since some fields may be autogenerated and thus match devices other than expected ๐Ÿ˜ฑ Be careful out there.

๐Ÿ“ attach-disk ๐Ÿ“

Syntax:

attach-disk domain source target [[[--live] [--config] |
   [--current]] | [--persistent]] [--targetbus bus]
   [--driver driver] [--subdriver subdriver] [--iothread iothread]
   [--cache cache] [--io io] [--type type] [--alias alias]
   [--mode mode] [--sourcetype sourcetype]
   [--source-protocol protocol] [--source-host-name hostname:port]
   [--source-host-transport transport] [--source-host-socket socket]
   [--serial serial] [--wwn wwn] [--rawio] [--address address]
   [--multifunction] [--print-xml] [--throttle-groups groups]

Attaches a brand new disk device to the domain ๐Ÿ’พ Let's break it down because this one has range:

source is the path for the files and devices โ€” unless --source-protocol is specified, in which case source is the name of a network disk ๐ŸŒ

target controls the bus or device under which the disk is exposed to the guest OS. It indicates the "logical" device name; the optional targetbus attribute specifies the type of disk device to emulate; possible values are driver specific, with typical values being ide, scsi, virtio, xen, usb, sata, or sd. If it's omitted, the bus type is inferred from the style of the device name (e.g. a device named sda will typically be exported using a SCSI bus) โœจ

driver can be file, tap or phy for the Xen hypervisor depending on the kind of access; or qemu for the QEMU emulator. Further details to the driver can be passed using subdriver. For Xen, subdriver can be aio, while for QEMU, subdriver should match the format of the disk source, such as raw or qcow2. The hypervisor default will be used if subdriver is not specified โ€” however, the default may not be correct, esp. for QEMU, as for security reasons it is configured not to detect disk formats ๐Ÿ’€ so like, pay attention.

type can indicate lun, cdrom or floppy as an alternative to the disk default, although this use only replaces the media within the existing virtual cdrom or floppy device; consider using update-device for this usage instead ๐ŸŽ€

alias can set a user supplied alias. mode can specify the two specific modes readonly or shareable. sourcetype can indicate the type of source (block|file|network). cache can be one of "default", "none", "writethrough", "writeback", "directsync" or "unsafe" โšก io controls specific policies on I/O; QEMU guests support "threads", "native" and "io_uring". iothread is the number within the range of domain IOThreads to which this disk may be attached (QEMU only) ๐Ÿ”ฅ

serial is the serial of the disk device. wwn is the wwn of the disk device. rawio indicates the disk needs rawio capability. address is the address of the disk device in the form of pci:domain.bus.slot.function, scsi:controller.bus.unit, ide:controller.bus.unit, usb:bus.port, sata:controller.bus.unit or ccw:cssid.ssid.devno. Virtio-ccw devices must have their cssid set to 0xfe ๐Ÿ‘€ multifunction indicates the specified pci address is a multifunction pci device address. throttle-groups is a comma separated list of throttle groups to be applied ๐ŸŽฏ

Still riding the network-disk wave, bestie โ€” there's also support for using a network disk ๐Ÿซถ. As specified, you can hand over a --source-protocol, and then the source parameter gets interpreted as the source name. --source-protocol must be provided if you're gonna provide a network disk or host information. Host info comes in via the tags --source-host-name, --source-host-transport, and --source-host-socket, which respectively denote the name of the host, the host's transport method, and the socket that the host uses. Heads up: --source-host-socket and --source-host-name cannot both be provided, and you must provide a --source-host-transport if you want to provide a --source-host-socket. The --source-host-name parameter supports host:port syntax if you wanna pass a port along too, iykyk ๐Ÿ’….

If --print-xml is specified, then the XML of the disk that would be attached gets printed instead โ€” no attaching, just vibes and preview ๐Ÿ“„โœจ.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive โ€” she does not share the spotlight ๐Ÿ’…. When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver.

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain. Likewise, --shareable is an alias for --mode shareable ๐ŸŽ€.


๐ŸŒ‰ attach-interface ๐ŸŒ‰

Syntax:

   attach-interface domain type source [[[--live]
      [--config] | [--current]] | [--persistent]]
      [--target target] [--mac mac] [--script script] [--model model]
      [--inbound average,peak,burst,floor] [--outbound average,peak,burst]
      [--alias alias] [--managed] [--print-xml]
      [--source-mode mode]

Attach a brand-new network interface to the domain โ€” giving your guest a whole new way to talk to the world ๐Ÿฆ‹.

type can be one of the:

  • network โ€” to indicate connection via a libvirt virtual network
  • bridge โ€” to indicate connection via a bridge device on the host
  • direct โ€” to indicate connection directly to one of the host's network interfaces or bridges
  • hostdev โ€” to indicate connection using a passthrough of PCI device on the host
  • vhostuser โ€” to indicate connection using a virtio transport protocol

source indicates the source of the connection. The source depends on the type of the interface:

  • network โ€” name of the virtual network
  • bridge โ€” the name of the bridge device
  • direct โ€” the name of the host's interface or bridge
  • hostdev โ€” the PCI address of the host's interface formatted as domain:bus:slot.function
  • vhostuser โ€” the path to UNIX socket (control plane)

--target is used to specify the tap/macvtap device to be used to connect the domain to the source. Names starting with vnet are considered as auto-generated and are blanked out/regenerated each time the interface is attached ๐Ÿ”.

--mac specifies the MAC address of the network interface; if a MAC address isn't given, a new address will be automatically generated (and stored in the persistent configuration if --config is given on the command line) ๐ŸŽ€.

--script is used to specify a path to a custom script to be called while attaching to a bridge โ€” this will be called instead of the default script, not in addition to it. This is valid only for interfaces of bridge type and only for Xen domains. Very niche, very exclusive ๐Ÿ’….

--model specifies the network device model to be presented to the domain.

alias can set user supplied alias.

--inbound and --outbound control the bandwidth of the interface. At least one from the average, floor pair must be specified. The other two, peak and burst, are optional, so "average,peak", "average,,burst", "average,,,floor", "average" and ",,,floor" are also legal. Values for average, floor and peak are expressed in kiB per second, while burst is expressed in kiB in a single burst at peak speed, as described in the Network XML documentation at https://libvirt.org/formatnetwork.html#quality-of-service ๐Ÿ“ถ

--managed is usable only for hostdev type and tells libvirt that the interface should be managed, which means detached and reattached from/to the host by libvirt.

--source-mode is mandatory for vhostuser interface and accepts values server and client, that control whether the hypervisor waits for the other process to connect, or initiates connection, respectively.

If --print-xml is specified, then the XML of the interface that would be attached is printed instead ๐Ÿ“„.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, affect the current domain state, which can either be live or offline. Both --live and --config flags may be given, but --current is exclusive. When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver.

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain.

Note: the optional target value is the name of a device to be created as the back-end on the node. If not provided, a device named "vnetN" or "vifN" will be created automatically. โœจ

๐Ÿซฅ detach-device ๐Ÿซฅ

Syntax:

   detach-device domain FILE [[[--live] [--config] |
      [--current]] | [--persistent]]

Detach a device from the domain โ€” takes the same kind of XML descriptions as the command attach-device. For passthrough host devices, see also nodedev-reattach, needed if the device doesn't use managed mode ๐Ÿ‘€.

Note: The supplied XML description of the device should be as specific as its definition in the domain XML. The set of attributes used to match the device are internal to the drivers. Using a partial definition, or attempting to detach a device that isn't present in the domain XML, but shares some specific attributes with one that is present, may lead to unexpected results ๐Ÿ˜ญ โ€” fr fr, be precise.
Quirk: Device unplug is asynchronous in most cases and requires guest cooperation. This means that it's up to the discretion of the guest to disallow or delay the unplug arbitrarily. As the libvirt API used in this command was designed as synchronous, it returns success after some timeout even if the device was not unplugged yet, to allow further interactions with the domain, e.g. if the guest is unresponsive. Callers which need to make sure that the device was unplugged can use libvirt events (see virsh event) to be notified when the device is removed. Note that the event may arrive before the command returns ๐Ÿ˜ตโ€๐Ÿ’ซ.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive. When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver.

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain.

Note that older versions of virsh used --config as an alias for --persistent ๐Ÿซถ.


๐Ÿท๏ธ detach-device-alias ๐Ÿท๏ธ

Syntax:

   detach-device-alias domain alias [[[--live] [--config] | [--current]]]]

Detach a device with the given alias from the domain. This command returns successfully after the unplug request was sent to the hypervisor. The actual removal of the device is notified asynchronously via libvirt events (see virsh event) โ€” so like, request sent โ‰  device gone, bestie ๐Ÿฆ‹.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive.


๐Ÿ’ฟ detach-disk ๐Ÿ’ฟ

Syntax:

   detach-disk domain target [[[--live] [--config] |
      [--current]] | [--persistent]] [--print-xml]

Detach a disk device from a domain. The target is the device as seen from the domain โ€” like, from the guest's own point of view ๐Ÿ‘‘.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive. When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver.

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain.

Note that older versions of virsh used --config as an alias for --persistent.

If --print-xml is specified, then the XML which would be used to detach the disk is printed instead ๐Ÿ“„โœจ.

Please see documentation for detach-device for known quirks โ€” yeah, those async unplug shenanigans apply here too ๐Ÿ˜ญ.


๐Ÿ”Œ detach-interface ๐Ÿ”Œ

Syntax:

   detach-interface domain [type] [--mac mac]
      [[[--live] [--config] | [--current]] | [--persistent]] [--print-xml]

Detach a network interface from a domain. Bye-bye bandwidth ๐ŸŒธ.

In case when multiple interfaces are present in the type and/or --mac must be used to narrow down the selection to 1 interface.

type can be either network to indicate a physical network device, or bridge to indicate a bridge to a device.

--mac can select the interface based on the configured MAC address.

If --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive. When no flag is specified, the legacy API is used, whose behavior depends on the hypervisor driver.

For compatibility purposes, --persistent behaves like --config for an offline domain, and like --live --config for a running domain.

Note that older versions of virsh used --config as an alias for --persistent.

If --print-xml is specified, then the XML used to detach the interface is printed instead ๐Ÿ“„.

Please see documentation for detach-device for known quirks.


๐Ÿ”„ update-device ๐Ÿ”„

Syntax:

   update-device domain file [--force] [[[--live]
      [--config] | [--current]] | [--persistent]]

Update the characteristics of a device associated with domain, based on the device definition in an XML file. The --force option can be used to force device update โ€” e.g., to eject a CD-ROM even if it's locked/mounted in the domain ๐Ÿ’ฟ๐Ÿ’…. See the documentation at https://libvirt.org/formatdomain.html#elementsDevices to learn about the libvirt XML format for a device.

Okay so real quick, before we get into the new commands, here's the deal with those three little state flags โ€” they show up everywhere in the device commands and they all mean slightly different things:

  • --live โ€” poke the domain that's running right now ๐Ÿƒโ€โ™€๏ธ
  • --config โ€” change what a persistent guest gets on its next startup (so like, future-you's problem, but make it cute) ๐Ÿ“
  • --current โ€” "whichever one makes sense rn", i.e. it's equivalent to either --live or --config depending on the current state of the guest ๐Ÿ”ฎ

You can give both --live and --config at the same time, but --current is exclusive โ€” she does not share the spotlight ๐Ÿ’…. And if you specify no flag at all? That's literally the same as specifying --current. No cap.

Compatibility tea โ˜•: --persistent behaves like --config for an offline domain, and like --live --config for a running domain. Also, heads up โ€” older versions of virsh used --config as an alias for --persistent. So if you're reading ancient forum posts, that's why. ๐Ÿ˜ญ
โš ๏ธ Real warning, bestie: using partial device definition XML files may lead to unexpected results, because some fields may be autogenerated and thus match devices other than expected. Like, the XML you wrote is doing its own thing and matching the wrong device. Rude. ๐Ÿ™ˆ

๐Ÿง  update-memory-device

Syntax:

update-memory-device domain [--print-xml] [[--alias alias] | [--node node]]
  [[--live] [--config] | [--current]]
  [--requested-size size]

So what this does: it finds the <memory/> device inside the domain you gave it, changes the requested values, and hands the updated device XML to the daemon. โœจ

  • --print-xml โ€” the device is not changed, and instead the updated device XML gets printed to stdout. Peek, don't touch ๐Ÿ‘€
  • --alias / --node โ€” if there's more than one <memory/> device in the domain, use one of these to select the one you actually want ๐ŸŽฏ

And the usual state-flag manifesto: if --live is specified, affect a running domain. If --config is specified, affect the next startup of a persistent guest. If --current is specified, it's equivalent to either --live or --config depending on the current state of the guest. Both --live and --config flags may be given, but --current is exclusive. Not specifying any flag is the same as specifying --current. (Yes, it's the same paragraph as above. It's copy-pasted all over this manpage and honestly? Relatable. ๐Ÿ’€)

  • --requested-size โ€” if given, the <requested/> under the memory target gets changed to the requested size (as a scaled integer, see NOTES above, cutie ๐Ÿซถ). It defaults to kibibytes if no suffix is provided. This option is only valid for the virtio-mem memory device model โ€” so don't try it on other models, it's giving "wrong crowd" energy.

๐Ÿ’ฟ change-media

Syntax:

change-media domain path [--eject] [--insert]
  [--update] [source] [--force] [[--live] [--config] |
  [--current]] [--print-xml] [--block]

This is the "swap out the CD/floppy" command, icon behavior fr ๐Ÿ”ฅ. It changes the media of a CDROM or floppy drive.

  • path โ€” can be the fully-qualified path or the unique target name (like <target dev='hdc'>) of the disk device ๐ŸŽฏ
  • source โ€” the path of the media to be inserted or updated ๐Ÿ“€
  • --block โ€” lets you set the backing type in case a block device is used as media for the CDROM or floppy drive instead of a file. Block device moment ๐Ÿ’…

Now the actual flag lore, pay attention bestie:

  • --eject โ€” the media will be ejected ๐Ÿ‘‹
  • --insert โ€” the media will be inserted. source must be specified here, no source no insert ๐Ÿšซ
  • --update โ€” the smart one, and she adapts:
    • If the device has source (e.g. <source file='media'>), and source is not specified, --update is equal to --eject.
    • If the device has no source, and source is specified, --update is equal to --insert.
    • If the device has source, and source is specified, --update behaves like a combination of --eject and --insert. Both, at once. Main character combo move โœจ
  • If none of --eject, --insert, and --update is specified, --update is used by default. She's the default for a reason ๐ŸŒŸ
  • --force โ€” used to force media changing. For when the drive is being dramatic ๐Ÿ’€

State flags, but read carefully because this one's different:

  • --live โ€” alter live configuration of running guest ๐Ÿƒโ€โ™€๏ธ
  • --config โ€” alter persistent configuration, effect observed on next startup of the guest ๐Ÿ“
  • --current โ€” can be either or both of live and config, depends on the hypervisor's implementation ๐Ÿ‘€
  • Both --live and --config flags may be given, but --current is exclusive.
  • If no flag is specified, behavior is different depending on hypervisor. Not "same as --current" this time. Different command, different rules, keep up ๐Ÿซถ
  • --print-xml โ€” the XML that would be used to change media is printed instead of changing the media. Preview era ๐Ÿ™ˆ

๐Ÿ”Œ dom-fd-associate

Syntax:

dom-fd-associate domain --name FDGROUPNAME --pass-fds M,N,....
    [--seclabel-writable] [--seclabel-restore]

This one associates one or more fds described via the --pass-fds argument to the domain, as --name. That's the whole vibe: you bring fds, you name them, you hand them over ๐ŸŽ

The lifetime of the passed fd group is the same as the connection โ€” so exiting virsh un-registers them afterwards. Basically when you leave the group chat, the fds leave too ๐Ÿ˜ญ no lingering.

By default, security labels are applied if needed, but they are not restored after use, to avoid keeping them open unnecessarily. Sensible queen behavior ๐Ÿ‘‘. Best-effort security label restore may be requested by using the --seclabel-restore flag ๐ŸŽ€

(And yeah, --seclabel-writable is sitting right there in the syntax too, doing its thing. ๐Ÿ’…)

๐Ÿฆ‹ NODEDEV COMMANDS ๐Ÿฆ‹

Okay bestie, this is the part where we talk about host devices โ€” like, the actual physical hardware on your machine that you want to hand over to a guest domain so it can use it directly. You do that with <hostdev> elements inside the domain's <devices> section. Iconic.

A node device key is generally the bus name followed by its address, with underscores between every single component. So like pci_0000_00_02_1, or usb_1_5_3, or net_eth1_00_27_13_6a_fe_00. The nodedev-list command gives you the full list of host devices libvirt knows about โ€” but heads up, that list also includes devices that cannot be assigned to a guest. Example: if you try to detach the PCI device that controls the host's hard disk controller (the one where the guest's disk images live), you could make the host system lock up or reboot. So likeโ€ฆ don't do that. ๐Ÿ˜ญ

For more info on node device definition, see: https://libvirt.org/formatnode.html.

Passthrough devices cannot be used by the host and its guest domains at the same time โ€” and not by multiple active guests at once either. No sharing, it's not that kind of party. If the <hostdev> description of a PCI device includes the attribute managed='yes', and the hypervisor driver supports it, then the device is in managed mode โ€” and any attempt to use that passthrough device in an active guest will automatically behave as if nodedev-detach (on guest start, or device hot-plug) and nodedev-reattach (on guest stop, or device hot-unplug) were called at exactly the right moments. ๐ŸŽฏ

If a PCI device is not marked as managed, then you have to manually detach it before guests can use it, and manually reattach it to give it back to the host. Also, if a device is manually detached, then the host does not regain control of the device without a matching reattach โ€” even if the guests use the device in managed mode. No cap, that's just how it is.


โœจ nodedev-create โœจ

Syntax:

nodedev-create FILE [--validate]

Create a device on the host node that can then be assigned to virtual machines. Normally libvirt is able to automatically figure out which host nodes are available for use, but this command lets you register host hardware that libvirt did not automatically detect. file contains the xml for a top-level <device> description of a node device.

If --validate is specified, it validates the format of the XML document against an internal RNG schema. ๐Ÿ‘‘

โœจ nodedev-update โœจ

Syntax:

nodedev-update device FILE [[--live] [--config] | [--current]]

Update a device on the host. device can be either a device name or a wwn pair in "wwnn,wwpn" format (only works for vHBA currently). file contains the xml for a top-level <device> description of the node device. --current can be either or both of live and config, depends on the hypervisor's implementation. Both --live and --config flags may be given, but --current is exclusive. If no flag is specified, behavior is different depending on hypervisor. ๐Ÿฆ‹

โœจ nodedev-destroy โœจ

Syntax:

nodedev-destroy device

Destroy (stop) a device on the host. device can be either a device name or a wwn pair in "wwnn,wwpn" format (only works for vHBA currently).

โš ๏ธ Note that this makes libvirt quit managing a host device, and may even make that device unusable by the rest of the physical host until a reboot. So likeโ€ฆ be sure, bestie. ๐Ÿ’€

โœจ nodedev-define โœจ

Syntax:

nodedev-define FILE [--validate]

Define an inactive persistent device, or modify an existing persistent one, from the XML in FILE.

If --validate is specified, it validates the format of the XML document against an internal RNG schema. โœจ

โœจ nodedev-undefine โœจ

Syntax:

nodedev-undefine device

Undefine the configuration for a persistent device. If the device is active, make it transient. Poof, configuration gone. ๐ŸŽ€

โœจ nodedev-start โœจ

Syntax:

nodedev-start device

Start a (previously defined) inactive device. Wake up bestie, you're on. ๐ŸŒธ

โœจ nodedev-detach โœจ

Syntax:

nodedev-detach nodedev [--driver backend_driver]

Detach nodedev from the host driver and bind it to a special driver that provides the API the hypervisor needs for assigning the device to a virtual machine (using <hostdev> in the domain XML definition). This gets reversed with nodedev-reattach, and it's done automatically by the hypervisor driver for managed devices โ€” those are the devices with "managed='yes'" in their XML definition. ๐Ÿซถ

Different hypervisors expect the device being assigned to be bound to different drivers. For example, QEMU's "vfio" backend requires the device to be bound to the driver "vfio-pci" or to a "VFIO variant" driver (this is a driver that supports the full API provided by vfio-pci, plus some other APIs to support things like live migration). The --driver parameter can be used to specify a particular driver (e.g. a device-specific VFIO variant driver) the device should be bound to. When --driver is omitted, the default driver for the hypervisor is used ("vfio-pci" for QEMU, "pciback" for Xen). ๐Ÿ‘‘

โœจ nodedev-dumpxml โœจ

Syntax:

nodedev-dumpxml [--inactive] [--xpath EXPRESSION] [--wrap] device

Dump a <device> XML representation for the given node device, including such info as the device name, which bus owns the device, the vendor and product id, and any capabilities of the device usable by libvirt (such as whether device reset is supported). device can be either a device name or a wwn pair in "wwnn,wwpn" format (only works for HBA). An additional option affecting the XML dump may be used. --inactive tells virsh to dump the node device configuration that will be used on next start of the node device, as opposed to the current node device configuration. ๐Ÿฆ‹

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document โ€” however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. Cute and practical. ๐ŸŽ€

โœจ nodedev-info โœจ

Syntax:

nodedev-info device

Returns basic information about the device object. Just the lil essentials. ๐Ÿ’…

โœจ nodedev-list โœจ

Syntax:

nodedev-list [--cap capability] [--tree] [--inactive | --all] [--persistent | --transient]

List all of the devices available on the node that are known by libvirt. cap is used to filter the list by capability types, and the types must be separated by comma, e.g. --cap pci,scsi. Valid capability types include 'system', 'pci', 'usb_device', 'usb', 'net', 'scsi_host', 'scsi_target', 'scsi', 'storage', 'fc_host', 'vports', 'scsi_generic', 'drm', 'mdev', 'mdev_types', 'ccw', 'ccwgroup', 'ccwgroup_member', 'css', 'ap_card', 'ap_queue', 'ap_matrix'. Look at that list, it's giving catalog energy. ๐ŸŒˆ

By default, only active devices are listed. --inactive is used to list only inactive devices, and --all is used to list both active and inactive devices. --persistent is used to list only persistent devices, and --transient is used to list only transient devices. Not providing --persistent or --transient will list all devices unless filtered otherwise. --transient is mutually exclusive with --persistent and --inactive. If --tree is used, the output is formatted in a tree representing parents of each node. --tree is mutually exclusive with all other options but --all. ๐Ÿซถ

โœจ nodedev-reattach โœจ

Syntax:

nodedev-reattach nodedev

Declare that nodedev is no longer in use by any guests, and that the host can resume normal use of the device. This is done automatically for PCI devices in managed mode and USB devices, but must be done explicitly to match any explicit nodedev-detach. Give it back, it's the host's turn now. ๐ŸŒธ

โœจ nodedev-reset โœจ

Syntax:

nodedev-reset nodedev

Trigger a device reset for nodedev โ€” useful prior to transferring a node device between guest passthrough or the host. Libvirt will often do this action implicitly when required, but this command allows an explicit reset when needed. Sometimes you just gotta hit the reset button yourself. ๐Ÿ”ฅ

โœจ nodedev-event โœจ

Syntax:

nodedev-event {[nodedev] event [--loop] [--timeout seconds] [--timestamp] | --list}

Wait for a class of node device events to occur, and print appropriate details of events as they happen. The events can optionally be filtered by nodedev. Using --list as the only argument will provide a list of possible event values known by this client โ€” although the connection might not allow registering for all these events. ๐Ÿ‘‘

By default, this command is one-shot, and returns success once an event occurs; you can send SIGINT (usually via Ctrl+C) to quit immediately. If --timeout is specified, the command gives up waiting for events after seconds have elapsed. With --loop, the command prints all events until a timeout or interrupt key. ๐Ÿฆ‹

When --timestamp is used, a human-readable timestamp will be printed before the event. Periodt.

โœจ nodedev-autostart โœจ

Syntax:

nodedev-autostart [--disable] device

Configure a device to be automatically started when the host machine boots or the parent device becomes available. With --disable, the device will be set to manual mode and will no longer be automatically started by the host. This command is only supported for persistently-defined mediated devices. ๐Ÿ’œ

๐ŸŒ VIRTUAL NETWORK COMMANDS ๐ŸŒ

Okay bestie, this whole section is about networks โ€” and ngl, this is where things get kinda iconic. Libvirt can literally define virtual networks that your domains (aka your VMs) use, and it can link those bad boys to actual network devices. If you want the full lore, the docs live at https://libvirt.org/formatnetwork.html. ๐Ÿซถ

A lot of these commands are giving very "same energy as the domain commands," but here's the โœจtwistโœจ: you name a virtual network either by its name or by its UUID. That's it, that's the vibe check. ๐Ÿ’…


๐Ÿ’ซ net-autostart

net-autostart network [--disable]

Okay so this one configures a virtual network to start itself automatically at boot. Very "I'll handle it myself, don't worry about me" energy. ๐Ÿ’

  • --disable โ€” turns autostarting off. So instead of main character energy at boot, it justโ€ฆ does not. ๐Ÿ™ˆ

๐ŸŒฑ net-create

net-create file [--validate]

Create a transient (temporary โ€” like, not saving-to-the-groupchat temporary) virtual network from an XML file, and instantiate (start) it. โœจ

If you need the full breakdown of the XML network format libvirt uses, the documentation is at https://libvirt.org/formatnetwork.html.

  • --validate โ€” optionally checks the format of your input XML file against an internal RNG schema. Basically a vibe check for your XML. ๐Ÿ”

๐Ÿ“Œ net-define

net-define file [--validate]

Define an inactive persistent virtual network, or modify an existing persistent one, from the XML file. Like saving it to your profile so it sticks around. ๐Ÿ’พ

  • --validate โ€” same deal as above: optionally validate the input XML format against an internal RNG schema. ๐ŸŽ€

๐Ÿท๏ธ net-desc

net-desc network [[--live] [--config] |
   [--current]] [--title] [--edit] [--new-desc
   New description or title message]

Show or modify the description and title of a network. These are legit user fields โ€” you can stash whatever arbitrary textual data you want in them so you can easily identify your networks later. The title should be short, although obvi it's not enforced. ๐Ÿ˜Œ (Also see net-metadata, which works with XML-based network metadata โ€” different vibe, same family.)

  • --live / --config โ€” select whether this command works on the live definition or the persistent definition of the network.
  • if you specify both --live and --config โ€” the --config option takes precedence when getting the current description, and while setting the description, both the live configuration and the config get updated. โœจ
  • --current โ€” exclusive, and implied if none of the others were specified.
  • --edit โ€” opens an editor with the contents of the current description or title, and saves the contents back afterwards. So you can edit it in your comfy little text editor. ๐Ÿ“
  • --title โ€” selects the operation on the title field instead of the description.
  • if neither --edit nor --new-desc is specified โ€” the note or description is displayed instead of being modified. No changes, just looking respectfully. ๐Ÿ‘€

๐Ÿ’ฅ net-destroy

net-destroy network

Destroy (stop) a given transient or persistent virtual network, specified by its name or UUID. And it takes effect immediately. No waiting around, no "let me think about it," just ๐Ÿ’€ gone. (Fr fr, be sure you mean it.)


๐Ÿ—‚๏ธ net-dumpxml

net-dumpxml [--inactive] [--xpath EXPRESSION] [--wrap] network

Outputs the virtual network information as an XML dump to stdout. ๐Ÿ’–

  • --inactive โ€” physical functions are not expanded into their associated virtual functions.
  • --xpath EXPRESSION โ€” if the --xpath argument provides an XPath expression, it gets evaluated against the output XML and only the matching nodes get printed. By default each matching node is printed as a standalone document. ๐Ÿ“„
  • --wrap โ€” for ease of additional processing, this causes the matching node to be wrapped in a common root node. ๐ŸŽ

โœ๏ธ net-edit

net-edit network

Edit the XML configuration file for a network. It's basically equivalent to:

virsh net-dumpxml --inactive network > network.xml
vi network.xml (or make changes with your other text editor)
virsh net-define network.xml

โ€ฆexcept that it does some error checking. So it's the upgraded version, iykyk. ๐Ÿ”ฅ

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi.


๐Ÿ“ก net-event

net-event {[network] event [--loop] [--timeout seconds] [--timestamp] | --list}

Wait for a class of network events to happen, then print the appropriate details as they occur. The events can optionally be filtered by network. ๐Ÿฆ‹

  • --list โ€” when used as the only argument, gives you a list of possible event values known by this client โ€” although the connection might not allow registering for all of these events. (Rude, but okay.)
  • default behavior โ€” one-shot: returns success once an event occurs. You can send SIGINT (usually via Ctrl+C) to quit immediately. ๐Ÿ˜ญ
  • --timeout seconds โ€” gives up waiting for events after seconds have elapsed.
  • --loop โ€” prints all events until a timeout or interrupt key. The loyallest option, honestly. ๐Ÿ’œ
  • --timestamp โ€” a human-readable timestamp gets printed before the event. โฐ

โ„น๏ธ net-info

net-info network

Returns basic information about the network object. Short, sweet, slay. โœจ


๐Ÿ“‹ net-list

net-list [--inactive | --all]
   { [--table] | --name | --uuid }
   [--persistent] [<--transient>]
   [--autostart] [<--no-autostart>]
   [--title]

Returns the list of active networks. Here's the breakdown, bestie:

  • --all โ€” also includes defined but inactive networks.
  • --inactive โ€” lists only the inactive ones.
  • --persistent โ€” filter the returned networks to list the persistent ones.
  • --transient โ€” filter to list the transient ones.
  • --autostart โ€” filter to list the ones with autostart enabled.
  • --no-autostart โ€” filter to list the ones with autostart disabled.
  • --name โ€” network names are printed instead of the table-formatted one-per-line output.
  • --uuid โ€” the network's UUIDs are printed instead of names.
  • --table โ€” specifies that the legacy table-formatted output should be used. This is the default. All of --table, --name and --uuid are mutually exclusive. ๐Ÿ’…
  • --title โ€” the short network description (title) is printed in an extra column. This flag is usable only with the default --table output.
NOTE: When talking to older servers, this command is forced to use a series of API calls with an inherent race โ€” a pool might not be listed, or might appear more than once, if it changed state between calls while the list was being collected. Newer servers do not have this problem. ๐Ÿ™

๐Ÿงฌ net-metadata

net-metadata network [[--live] [--config] | [--current]]
   [--edit] [uri] [key] [set] [--remove]

Show or modify custom XML metadata of a network. The metadata is user-defined XML that lets you store arbitrary XML data in the network definition. Multiple separate custom metadata pieces can be stored in the network XML, and each piece is identified by a private XML namespace provided via the uri argument. ๐ŸŽ€ (See also net-desc, which works with the textual metadata of a network, like title and description.)

  • --live / --config โ€” select whether this command works on the live or persistent definitions of the network.
  • both --live and --config โ€” the --config option takes precedence when getting the current description, and both the live configuration and the config get updated while setting the description. โœจ
  • --current โ€” exclusive, and implied if none of the others was specified.
  • --remove โ€” specifies that the metadata element identified by the uri argument should be removed rather than updated. ๐Ÿ—‘๏ธ
  • --edit โ€” opens an editor with the metadata identified by the uri argument, and saves the contents back afterwards. Otherwise, the new contents can be provided via the set argument.
  • when setting metadata via --edit or set โ€” the key argument must be specified, and is used to prefix the custom elements to bind them to the private namespace. ๐Ÿ”‘
  • if neither --edit nor set is specified โ€” the XML metadata corresponding to the uri namespace is displayed instead of being modified. Just peeking. ๐Ÿ‘€

๐Ÿ” net-name

net-name network-UUID

Converts a network UUID to a network name. Glow-up in reverse. โœจ


๐Ÿš€ net-start

net-start network

Start a (previously defined) inactive network. Time to wake up, sleeping beauty. ๐ŸŒธ


๐Ÿชฆ net-undefine

net-undefine network

Undefine the configuration for a persistent network. And if the network is active, it gets made transient. So it's like "you're still here but you're not official anymore." ๐Ÿ’€


๐Ÿ†” net-uuid

net-uuid network-name

Converts a network name to a network UUID. The other direction, slay. ๐Ÿ’…


๐Ÿ”„ net-update

net-update network command section xml
   [--parent-index index] [[--live] [--config] | [--current]]

Update the given section of an existing network definition, with the changes optionally taking effect immediately โ€” no needing to destroy and re-start the network. Obsessed with the efficiency. ๐Ÿ”ฅ

command is one of "add-first", "add-last", "add" (a synonym for add-last), "delete", or "modify". ๐Ÿ› ๏ธ

section is one of "bridge", "domain", "ip", "ip-dhcp-host", "ip-dhcp-range", "forward", "forward-interface", "forward-pf", "portgroup", "dns-host", "dns-txt", or "dns-srv" โ€” each section being named by a concatenation of the XML element hierarchy leading to the element being changed. So for example, "ip-dhcp-host" will change a <host> element that is contained inside a <dhcp> element inside an <ip> element of the network. ๐Ÿงš

xml is either the text of a complete XML element of the type being changed (e.g. "<host mac="00:11:22:33:44:55' ip='1.2.3.4'/>"), or the name of a file that contains a complete XML element. The disambiguation is done by looking at the first character of the provided text: if the first character is "<", it's XML text; if the first character is not "<", it's the name of a file containing the XML text to be used. ๐ŸŽฏ

  • --parent-index index โ€” specifies which of several parent elements the requested element is in (0-based). For example, a dhcp <host> element could be in any one of multiple <ip> elements in the network. If a parent-index isn't provided, the "most appropriate" <ip> element will be selected (usually the only one that already has a <dhcp> element), but if --parent-index is given, that particular instance of <ip> gets the modification. ๐Ÿ‘‘
  • --live โ€” affect a running network.
  • --config โ€” affect the next startup of a persistent network.
  • --current โ€” equivalent to either --live or --config, depending on the current state of the guest. Both --live and --config may be given, but --current is exclusive. Not specifying any flag is the same as specifying --current. ๐Ÿ’ซ

๐Ÿ“ net-dhcp-leases

net-dhcp-leases network [mac]

Get a list of dhcp leases for all network interfaces connected to the given virtual network โ€” or limited output just for one interface if mac is specified. Receipts for days. ๐Ÿงพโœจ

โœจ NETWORK PORT COMMANDS โœจ

Okay so these commands are all about network ports โ€” and no, bestie, you probably won't ever need them directly. ๐Ÿ’… Libvirt virtual networks get ports automatically created when a VM has a virtual network interface added to it. The hypervisor drivers already run these commands at exactly the right point in a virtual machine's lifecycle. So likeโ€ฆ they exist for debugging problems and/or recovering from bugs and stale state. That's the vibe. ๐Ÿฉน

โœจ net-port-list โœจ

Syntax:

net-port-list { [--table] | --uuid } network

Lists every network port recorded against the network. ๐Ÿ“‹

  • --uuid โ€” prints the network ports' UUIDs instead of a table
  • --table โ€” asks for the legacy table-formatted output

And --table is the default, btw. All of these flags are mutually exclusive โ€” pick one, bestie, you can't have all three. ๐Ÿ™…โ€โ™€๏ธ

โœจ net-port-create โœจ

Syntax:

net-port-create network file [--validate]

Allocates a shiny new network port, reserving resources based on the port description. ๐ŸŽ€

  • --validate โ€” optionally checks the format of the input XML file against an internal RNG schema

โœจ net-port-dumpxml โœจ

Syntax:

net-port-dumpxml [--xpath EXPRESSION] [--wrap] network port

Dumps the network port info as XML straight to stdout. ๐Ÿ–จ๏ธ

If --xpath gives it an XPath expression, it gets evaluated against the output XML and only the matching nodes get printed. Default behaviour prints each matching node as its own standalone document โ€” but for ease of extra processing, --wrap wraps the matching node in a common root node. Wrapped like a little gift. ๐ŸŽ

โœจ net-port-delete โœจ

Syntax:

net-port-delete network port

Deletes the record of the network port and releases its resources. Bye bestie. ๐Ÿ‘‹


๐Ÿฆ‹ INTERFACE COMMANDS ๐Ÿฆ‹

These ones manipulate host interfaces. Often these host interfaces can then be used by name inside domain <interface> elements (think: a system-created bridge interface), but lowkey there's no requirement that host interfaces be tied to any particular guest configuration XML at all. Free spirits. ๐ŸŒธ

A lot of these commands are super similar to the ones used for domains, and you name an interface either by its name or its MAC address. But โ€” and this is the important bit โ€” using a MAC address for an iface argument only works when that address is unique. If an interface and a bridge share the same MAC address (which, ngl, is often the case), then using that MAC address throws an error because it's ambiguous, and you gotta resort to a name instead. ๐Ÿ˜ญ

โœจ iface-bridge โœจ

Syntax:

iface-bridge interface bridge [--no-stp] [delay] [--no-start]

Creates a bridge device named bridge and attaches the existing network device interface to the new bridge. ๐ŸŒ‰

The new bridge defaults to starting immediately, with STP enabled and a delay of 0. You can change those with --no-stp, --no-start, and an integer number of seconds for delay. All IP address configuration of interface gets moved over to the new bridge device. Moving day! ๐Ÿ“ฆ

See also iface-unbridge for undoing this operation, iykyk.

โœจ iface-define โœจ

Syntax:

iface-define file [--validate]

Defines an inactive persistent physical host interface, or modifies an existing persistent one, from the XML file. ๐ŸŽ€

  • --validate โ€” optionally validates the format of the input XML file against an internal RNG schema

โœจ iface-destroy โœจ

Syntax:

iface-destroy interface

Destroys (stops) a given host interface โ€” like by running "if-down" to disable it from active use. Takes effect immediately, no waiting around. ๐Ÿ’€

โœจ iface-dumpxml โœจ

Syntax:

iface-dumpxml [--inactive] [--xpath EXPRESSION] [--wrap] interface

Outputs the host interface info as an XML dump to stdout. ๐Ÿ–จ๏ธ

  • --inactive โ€” the output reflects the persistent state of the interface, the one that'll be used next time it starts

If --xpath provides an XPath expression, it's evaluated against the output XML and only matching nodes get printed. Default = each matching node as a standalone document; --wrap = wrap it in a common root node for easier processing. โœจ

โœจ iface-edit โœจ

Syntax:

iface-edit interface

Edits the XML configuration file for a host interface. ๐Ÿ“

It's equivalent to:

virsh iface-dumpxml iface > iface.xml
vi iface.xml (or make changes with your other text editor)
virsh iface-define iface.xml

โ€ฆexcept it does some error checking for you. ๐Ÿซถ

The editor comes from the $VISUAL or $EDITOR environment variables, and defaults to vi.

โœจ iface-list โœจ

Syntax:

iface-list [--inactive | --all]

Returns the list of active host interfaces. ๐Ÿ’…

  • --all โ€” also includes defined but inactive interfaces
  • --inactive โ€” lists only the inactive ones

โœจ iface-name โœจ

Syntax:

iface-name interface

Converts a host interface MAC address to an interface name โ€” but only if the MAC address is unique among the host's interfaces. ๐Ÿ”

interface here specifies the interface MAC address.

โœจ iface-mac โœจ

Syntax:

iface-mac interface

Converts a host interface name to a MAC address. The other direction, iconic. ๐Ÿ”„

interface here specifies the interface name.

โœจ iface-start โœจ

Syntax:

iface-start interface

Starts a (previously defined) host interface โ€” like by running "if-up". ๐Ÿš€

โœจ iface-unbridge โœจ

Syntax:

iface-unbridge bridge [--no-start]

Tears down a bridge device named bridge, releases its underlying interface back to normal usage, and moves all the IP address configuration from the bridge device to the underlying device. ๐Ÿงจ

  • --no-start โ€” the underlying interface is restarted unless this flag is present. It's there for symmetry, but generally not recommended. ๐Ÿ™ˆ

See also iface-bridge for creating a bridge.

โœจ iface-undefine โœจ

Syntax:

iface-undefine interface

Undefines the configuration for an inactive host interface. Poof, gone. ๐Ÿ’จ

โœจ iface-begin โœจ

Syntax:

iface-begin

Creates a snapshot of the current host interface settings, which you can later commit (iface-commit) or restore (iface-rollback). ๐Ÿ“ธ

If a snapshot already exists, this command fails until the previous snapshot has been committed or restored. And โ€” heads up โ€” undefined behavior results if any external changes are made to host interfaces outside of the libvirt API between the beginning of a snapshot and its eventual commit or rollback. ๐Ÿšจ

Fr fr, don't go poking at host interfaces behind libvirt's back mid-snapshot. That's undefined behavior territory and it will not be cute.

โœจ iface-commit โœจ

Syntax:

iface-commit

Declares all changes since the last iface-begin as working, and deletes the rollback point. โœ…

If no interface snapshot has already been started, this command will fail. ๐Ÿ˜ญ

โœจ iface-rollback โœจ

Syntax:

iface-rollback

Reverts all host interface settings back to the state recorded in the last iface-begin. โช

If no interface snapshot has already been started, this command fails. And plot twist: rebooting the host also serves as an implicit rollback point. ๐Ÿ”„


๐ŸŒˆ STORAGE POOL COMMANDS ๐ŸŒˆ

These commands manipulate storage pools. Libvirt can manage all sorts of storage solutions โ€” files, raw partitions, and domain-specific formats โ€” used to provide the storage volumes visible as devices within virtual machines. ๐Ÿ’พ For the full lore, see the docs at https://libvirt.org/formatstorage.html . Many of the pool commands are, once again, super similar to the ones used for domains. (Pattern recognition, bestie. ๐Ÿ‘‘)

โœจ find-storage-pool-sources โœจ

Syntax:

find-storage-pool-sources type [srcSpec]

Returns XML describing all possible available storage pool sources that could be used to create or define a storage pool of the given type. ๐Ÿ”Ž If srcSpec is provided, it's a file containing XML that further restricts the query for pools.

Not every storage pool supports discovery this way. And even for the ones that do, only specific XML elements are required to return valid data โ€” other elements, and even attributes of some elements, get ignored since they're not necessary to find the pool based on the search criteria. Here's the supported type options and the expected minimal XML elements for the search: ๐Ÿ‘‡

  • For a "netfs" or "gluster" pool, the minimal expected XML is the <host> element with a "name" attribute describing the IP address or hostname to use to find the pool. The "port" attribute will be ignored, as will any other provided XML elements in srcSpec.
  • For a "logical" pool, the contents of the srcSpec file are ignored โ€” although if provided, the file must at least exist.
  • For an "iscsi" or "iscsi-direct" pool, the minimal expected XML is the <host> element with a "name" attribute describing the IP address or hostname to use to find the pool (the iSCSI server address). Optionally, the "port" attribute may be provided, although it defaults to 3260. Optionally, an <initiator> XML element with a "name" attribute may be provided to further restrict the iSCSI target search to a specific initiator for multi-iqn iSCSI storage pools. ๐ŸŽฏ

โœจ find-pool-sources-as โœจ

Syntax:

find-storage-pool-sources-as type [host] [port] [initiator]

Instead of handing over a srcSpec XML file to find-storage-pool-sources, this command option has virsh generate the query XML file for you using the optional arguments. โœจ It returns the same output XML as find-storage-pool-sources.

  • host โ€” describes a specific host to use for networked storage, like netfs, gluster, and iscsi type pools ๐ŸŒ
  • port โ€” further restricts which networked port to use for the connection, if the specific storage backend requires it, like iscsi
  • initiator โ€” further restricts the iscsi type pool searches to specific target initiators

โœจ pool-autostart โœจ

Syntax:

pool-autostart pool-or-uuid [--disable]

Configures whether pool should automatically start at boot. ๐Ÿš€

โœจ pool-build โœจ

Syntax:

pool-build pool-or-uuid [--overwrite] [--no-overwrite]

Builds a given pool. ๐Ÿ—๏ธ

--overwrite and --no-overwrite can only be used for pool-build of a filesystem, disk, or logical pool.

For a file system pool, if neither flag is specified, then pool-build just makes the target path directory and makes no attempt to run mkfs on the target volume device. If --no-overwrite is specified, it probes to determine if a filesystem already exists on the target device, returning an error if one exists โ€” or using mkfs to format the target device if not. If --overwrite is specified, mkfs is always executed and any existing data on the target device is overwritten unconditionally. ๐Ÿ’€

Bestie, --overwrite means exactly what it sounds like. Existing data? Gone. No takebacks. ๐Ÿ”ฅ

okay so continuing the pool-build tea, bestie โ˜•โœจ โ€” this is the part where it gets specific about your disk pools and your logical pools, and honestly the vibes are "read this twice before you type it."

For a disk pool, if neither of them is specified or --no-overwrite is specified, pool-build will check the target volume device for existing filesystems or partitions before attempting to write a new label on the target volume device. If the target volume device already has a label, the command will fail ๐Ÿ’€. If --overwrite is specified, then no check will be made on the target volume device prior to writing a new label. Writing of the label uses the pool source format type or "dos" if not specified. periodt.

For a logical pool, if neither of them is specified or --no-overwrite is specified, pool-build will check the target volume devices for existing filesystems or partitions before attempting to initialize and format each device for usage by the logical pool. If any target volume device already has a label, the command will fail ๐Ÿ˜ญ. If --overwrite is specified, then no check will be made on the target volume devices prior to initializing and formatting each device. Once all the target volume devices are properly formatted via pvcreate, the volume group will be created using all the devices. slay, but carefully ๐Ÿซถ


๐Ÿงš pool-create

Syntax:

pool-create file [--build] [[--overwrite] | [--no-overwrite]]

Create and start a pool object from the XML file. main character behavior, honestly ๐Ÿ‘‘

[--build] [[--overwrite] | [--no-overwrite]] perform a pool-build after creation in order to remove the need for a follow-up command to build the pool. The --overwrite and --no-overwrite flags follow the same rules as pool-build. If just --build is provided, then pool-build is called with no flags. iykyk ๐ŸŒธ


๐Ÿฆ‹ pool-create-as

Syntax:

pool-create-as name type
   [--source-host hostname] [--source-path path] [--source-dev path]
   [--source-name name] [--target path] [--source-format format]
   [--source-initiator initiator-iqn]
   [--auth-type authtype --auth-username username
   [--secret-usage usage | --secret-uuid uuid]]
   [--source-protocol-ver ver]
   [[--adapter-name name] | [--adapter-wwnn wwnn --adapter-wwpn wwpn]
   [--adapter-parent parent |
   --adapter-parent-wwnn parent_wwnn adapter-parent-wwpn parent_wwpn |
   --adapter-parent-fabric-wwn parent_fabric_wwn]]
   [--build] [[--overwrite] | [--no-overwrite]] [--print-xml]

Create and start a pool object name from the raw parameters. If --print-xml is specified, then print the XML of the pool object without creating the pool. Otherwise, the pool has the specified type. When using pool-create-as for a pool of type "disk", the existing partitions found on the --source-dev path will be used to populate the disk pool. Therefore, it is suggested to use pool-define-as and pool-build with the --overwrite in order to properly initialize the disk pool. not me warning you in advance so you don't have to learn the hard way ๐Ÿ’…

Now the flag lore, one by one ๐Ÿ‘‡

  • --source-host hostname โ€” provides the source hostname for pools backed by storage from a remote server (pool types netfs, iscsi, rbd, sheepdog, gluster).
  • --source-path path โ€” provides the source directory path for pools backed by directories (pool type dir).
  • --source-dev path โ€” provides the source path for pools backed by physical devices (pool types fs, logical, disk, iscsi, zfs).
  • --source-name name โ€” provides the source name for pools backed by storage from a named element (pool types logical, rbd, sheepdog, gluster).
  • --target path โ€” is the path for the mapping of the storage pool into the host file system.
  • --source-format format โ€” provides information about the format of the pool (pool types fs, netfs, disk, logical).
  • --source-initiator initiator-iqn โ€” provides the initiator iqn for iscsi connection of the pool (pool type iscsi-direct).
  • --auth-type authtype --auth-username username [--secret-usage usage | --secret-uuid uuid] โ€” provides the elements required to generate authentication credentials for the storage pool. The authtype is either chap for iscsi type pools or ceph for rbd type pools. Either the secret usage or uuid value may be provided, but not both ๐Ÿ™ˆ.
  • --source-protocol-ver ver โ€” provides the NFS protocol version number used to contact the server's NFS service via nfs mount option 'nfsvers=n'. It is expect the ver value is an unsigned integer. (yes, the manpage says "expect", we're keeping it fr fr ๐Ÿ’œ)
  • --adapter-name name โ€” defines the scsi_hostN adapter name to be used for the scsi_host adapter type pool.
  • --adapter-wwnn wwnn --adapter-wwpn wwpn [--adapter-parent parent | --adapter-parent-wwnn parent_wwnn adapter-parent-wwpn parent_wwpn | --adapter-parent-fabric-wwn parent_fabric_wwn] โ€” defines the wwnn and wwpn to be used for the fc_host adapter type pool. Optionally provide the parent scsi_hostN node device to be used for the vHBA either by parent name, parent_wwnn and parent_wwpn, or parent_fabric_wwn. The parent name could change between reboots if the hardware environment changes, so providing the parent_wwnn and parent_wwpn ensure usage of the same physical HBA even if the scsi_hostN node device changes. Usage of the parent_fabric_wwn allows a bit more flexibility to choose an HBA on the same storage fabric in order to define the pool. iconic flexibility behavior ๐ŸŒ€
  • --build [[--overwrite] | [--no-overwrite]] โ€” perform a pool-build after creation in order to remove the need for a follow-up command to build the pool. The --overwrite and --no-overwrite flags follow the same rules as pool-build. If just --build is provided, then pool-build is called with no flags. (yes bestie it's the same paragraph, it's important okay ๐Ÿ˜ค)

For a "logical" pool only --name needs to be provided. The --source-name if provided must match the Volume Group name. If not provided, one will be generated using the --name. If provided the --target is ignored and a target source is generated using the --source-name (or as generated from the --name). lowkey elegant ngl ๐ŸŒธ


๐ŸŽ€ pool-define

Syntax:

pool-define file [--validate]

Define an inactive persistent storage pool or modify an existing persistent one from the XML file. Optionally, the format of the input XML file can be validated against an internal RNG schema with --validate. very "trust but verify" of it โœจ


๐Ÿ’œ pool-define-as

Syntax:

pool-define-as name type
   [--source-host hostname] [--source-path path] [--source-dev path]
   [*--source-name name*] [*--target path*] [*--source-format format*]
   [--source-initiator initiator-iqn]
   [*--auth-type authtype* *--auth-username username*
   [*--secret-usage usage* | *--secret-uuid uuid*]]
   [*--source-protocol-ver ver*]
   [[*--adapter-name name*] | [*--adapter-wwnn* *--adapter-wwpn*]
   [*--adapter-parent parent*]] [*--print-xml*]

Create, but do not start, a pool object name from the raw parameters. If --print-xml is specified, then print the XML of the pool object without defining the pool. Otherwise, the pool has the specified type. it's giving "define now, start later" ๐Ÿ’…

Use the same arguments as pool-create-as, except for the --build, --overwrite, and --no-overwrite options. that's the whole difference bestie, don't overthink it ๐Ÿฆ‹


๐Ÿ˜ญ pool-destroy

Syntax:

pool-destroy pool-or-uuid

Destroy (stop) a given pool object. Libvirt will no longer manage the storage described by the pool object, but the raw data contained in the pool is not changed, and can be later recovered with pool-create. so dramatic for no reason โ€” your data is fine ๐Ÿซถ


๐Ÿ”ฅ pool-delete

Syntax:

pool-delete pool-or-uuid

Destroy the resources used by a given pool object. This operation is non-recoverable ๐Ÿ’€. The pool object will still exist after this command, ready for the creation of new storage volumes. so like, the pool stays but everything in it is gone gone. read that twice, bestie ๐Ÿ˜ญ


โญ pool-dumpxml

Syntax:

pool-dumpxml [--inactive] [--xpath EXPRESSION] [--wrap] pool-or-uuid

Returns the XML information about the pool object. --inactive tells virsh to dump pool configuration that will be used on next start of the pool as opposed to the current pool configuration. sneak peek energy ๐Ÿ‘€

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. thoughtful queen behavior ๐ŸŽ€


๐Ÿงš pool-edit

Syntax:

pool-edit pool-or-uuid

Edit the XML configuration file for a storage pool.

This is equivalent to:

virsh pool-dumpxml pool > pool.xml
vi pool.xml (or make changes with your other text editor)
virsh pool-define pool.xml

except that it does some error checking. so it's the same vibe but with a seatbelt โœจ

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi. set your $EDITOR bestie, future you will thank you ๐Ÿ’œ


๐ŸŒˆ pool-info

Syntax:

pool-info [--bytes] pool-or-uuid

Returns basic information about the pool object. If --bytes is specified the sizes of basic info are not converted to human friendly units. for the people who want the raw numbers and no cutesy rounding ๐Ÿ”ข


๐Ÿ‘‘ pool-list

Syntax:

pool-list [--inactive] [--all]
   [--persistent] [--transient]
   [--autostart] [--no-autostart]
   [[--details] [--uuid]
   [--name] [<type>]

List pool objects known to libvirt. By default, only active pools are listed; --inactive lists just the inactive pools, and --all lists all pools. the classic "wait why is my pool not showing up" moment, solved ๐ŸŒธ

In addition, there are several sets of filtering flags. --persistent is to list the persistent pools, --transient is to list the transient pools. --autostart lists the autostarting pools, --no-autostart lists the pools with autostarting disabled. If --uuid is specified only pool's UUIDs are printed. If --name is specified only pool's names are printed. If both --name and --uuid are specified, pool's UUID and names are printed side by side without any header. Option --details is mutually exclusive with options --uuid and --name. pick a lane bestie ๐Ÿ’…

You may also want to list pools with specified types using type, the pool types must be separated by comma, e.g. --type dir,disk. The valid pool types include 'dir', 'fs', 'netfs', 'logical', 'disk', 'iscsi', 'scsi', 'mpath', 'rbd', 'sheepdog', 'gluster', 'zfs', 'vstorage' and 'iscsi-direct'. so many options and every single one of them matters ๐Ÿ˜ค

The --details option instructs virsh to additionally display pool persistence and capacity related information where available. the "give me the lore" switch ๐Ÿ“

NOTE: When talking to older servers, this command is forced to use a series of API calls with an inherent race, where a pool might not be listed or might appear more than once if it changed state between calls while the list was being collected. Newer servers do not have this problem. ๐Ÿ’€ not a bug in virsh, just old-server chaos. don't @ me.

๐Ÿ’– pool-name

Syntax:

pool-name uuid

Convert the uuid to a pool name. short, sweet, does exactly one thing and does it well ๐ŸŽ€


๐Ÿฆ‹ pool-refresh

Syntax:

pool-refresh pool-or-uuid

Refresh the list of volumes contained in pool. it's giving "rescan the vibes" โœจ


๐ŸŒธ pool-start

Syntax:

pool-start pool-or-uuid [--build] [[--overwrite] | [--no-overwrite]]

Start the storage pool, which is previously defined but inactive. go little pool, go ๐Ÿ‘‘๐Ÿ’œ


  • --build โ€” does a pool-build before pool-start, so the pool's environment is already in the expected state and you don't have to run build yourself beforehand. The --overwrite / --no-overwrite flags work exactly like they do in pool-build. If you just pass --build on its own, then pool-build gets called with no flags. cute and efficient ๐Ÿ’…
heads up bestie โš ๏ธ a storage pool that leans on remote stuff โ€” think an "iscsi" pool or a (v)HBA backed "scsi" pool โ€” might need to be refreshed multiple times before every volume shows up (peep pool-refresh). Why? because the matching volume devices might not be sitting in the host's filesystem during the first pool startup or the current refresh attempt. How many retries you need? fully depends on the network connection and how long the host takes to export those devices. not me refreshing like five times ๐Ÿ˜ญ

pool-undefine

Syntax:

pool-undefine pool-or-uuid

Undefines the config for an inactive pool. bye-bye config ๐Ÿ‘‹

pool-uuid

Syntax:

pool-uuid pool

Returns the UUID of the pool you named. that little string of hex is literally its government name โœจ

pool-event

Syntax:

pool-event {[pool] event [--loop] [--timeout seconds] [--timestamp] | --list}

Waits for a whole class of storage pool events to pop off, then prints the deets of each event as it happens. You can optionally filter by pool. And if you run --list as your only argument, it gives you a list of the possible event values this client knows about โ€” though ngl the connection might not let you register for all of them ๐Ÿ™ˆ

By default this command is one-shot: it returns success the moment an event occurs. You can send SIGINT (usually via Ctrl+C) to quit immediately. If you give --timeout, the command gives up waiting for events once seconds have elapsed. With --loop, it prints all the events until a timeout or you hit the interrupt key. main character energy: it just keeps going ๐ŸŒ€

When --timestamp is used, a human-readable timestamp gets printed before the event. so you know exactly when things went down ๐Ÿ•


๐ŸŒธ VOLUME COMMANDS ๐ŸŒธ

vol-create

Syntax:

vol-create pool-or-uuid FILE [--prealloc-metadata] [--validate]

Creates a volume from an XML <file>. yes, from a file, we're being fancy ๐Ÿ’–

pool-or-uuid is the name or UUID of the storage pool you're creating the volume in.

FILE is the XML <file> holding the volume definition. An easy way to make that XML <file> is to run vol-dumpxml on a volume that already exists and steal its definition. iykyk ๐Ÿ˜Œ

  • --prealloc-metadata โ€” preallocates metadata (for qcow2 images that don't support full allocation). This makes a sparse image file with metadata, which gives you higher performance compared to images with no preallocation, while only using slightly more initial disk space. slay ๐Ÿ’…

If --validate is specified, it validates the format of the XML document against an internal RNG schema. strict queen ๐Ÿ‘‘

Example:

virsh vol-dumpxml --pool storagepool1 appvolume1 > newvolume.xml
vi newvolume.xml (or make changes with your other text editor)
virsh vol-create differentstoragepool newvolume.xml

vol-create-from

Syntax:

vol-create-from pool-or-uuid FILE vol-name-or-key-or-path
   [--inputpool pool-or-uuid]  [--prealloc-metadata] [--reflink] [--validate]

Creates a volume using another volume as its input. remix culture fr fr ๐ŸŽ€

pool-or-uuid is the name or UUID of the storage pool to create the volume in.

FILE is the XML <file> with the volume definition.

vol-name-or-key-or-path is the name, key, or path of the source volume.

--inputpool pool-or-uuid is the name or uuid of the storage pool that the source volume lives in.

  • --prealloc-metadata โ€” preallocates metadata (for qcow2 images that don't support full allocation). Creates a sparse image file with metadata โ†’ higher performance than images with no preallocation, and only a tiny bit more initial disk space used. ๐Ÿ’–

When --reflink is specified, it does a COW lightweight copy, where the data blocks only get copied once they're modified. If that's not possible, the copy fails. no silent fallback, she's dramatic ๐Ÿ’€

If --validate is specified, it validates the format of the XML document against an internal RNG schema.

vol-create-as

Syntax:

vol-create-as pool-or-uuid name capacity [--allocation size] [--format string]
   [--backing-vol vol-name-or-key-or-path]
   [--backing-vol-format string] [--prealloc-metadata] [--print-xml]

Creates a volume from a set of arguments โ€” unless you pass --print-xml, in which case it just prints the XML of the volume object without actually creating anything. window shopping โœจ

pool-or-uuid is the name or UUID of the storage pool to create the volume in.

name is the name of the new volume. For a disk pool, this has to match the partition name as determined from the pool's source device path and the next available partition. Example: if the source device path is /dev/sdb and there are no partitions on the disk, then the name must be sdb1, then next one sdb2, and so on. no skipping numbers bestie ๐Ÿ”ข

capacity is the size of the volume to be created, as a scaled integer (check the NOTES above), defaulting to bytes if you don't give a suffix.

  • --allocation size โ€” the initial size to be allocated in the volume, also as a scaled integer defaulting to bytes.
  • --format string โ€” used in file based storage pools to pick the volume file format: raw, bochs, qcow, qcow2, vmdk, qed. Use extended for disk storage pools to create an extended partition (other values do get validity checked but are not preserved when libvirtd is restarted or the pool is refreshed โ€” so don't get too attached ๐Ÿซ ).
  • --backing-vol vol-name-or-key-or-path โ€” the source backing volume to use if you're taking a snapshot of an existing volume.
  • --backing-vol-format string โ€” the format of the snapshot backing volume: raw, bochs, qcow, qcow2, qed, vmdk, host_device. These are, however, meant for file based storage pools.
  • --prealloc-metadata โ€” preallocates metadata (for qcow2 images which don't support full allocation). Creates a sparse image file with metadata, so you get higher performance than images with no preallocation and only slightly higher initial disk space usage. obsessed ๐Ÿงš

vol-clone

Syntax:

vol-clone vol-name-or-key-or-path name
   [--pool pool-or-uuid] [--prealloc-metadata] [--reflink] [--print-xml]

Clones an existing volume inside its parent pool. It's less powerful than vol-create-from, but way easier to type. the low-effort icon ๐Ÿ‘‘

vol-name-or-key-or-path is the name, key, or path of the source volume.

name is the name of the new volume.

  • --pool pool-or-uuid โ€” the name or UUID of the storage pool that contains the source volume and will contain the new volume. If you gave the source volume's name instead of its key or path, then this pool is required to find the volume being cloned; otherwise the first volume found by the key or path gets used.
  • --prealloc-metadata โ€” preallocates metadata (for qcow2 images which don't support full allocation). Sparse image file with metadata = higher performance compared to no preallocation, just a touch more initial disk space. ๐Ÿ’–

When --reflink is specified, it does a COW lightweight copy, where data blocks are only copied when they're modified. If that's not possible, the copy fails. periodt.

If --print-xml is specified, then the XML used to clone the volume gets printed instead. peek before you commit ๐Ÿ™ˆ

vol-delete

Syntax:

vol-delete vol-name-or-key-or-path [--pool pool-or-uuid] [--delete-snapshots]

Deletes a given volume. gone, girl ๐Ÿ’€

vol-name-or-key-or-path is the volume name, key, or path of the volume to delete.

  • --pool pool-or-uuid โ€” the name or UUID of the storage pool the volume is in. If you gave the volume name instead of the key or path, then this pool is necessary to find the volume to delete; otherwise the first volume found by the key or path gets used.

The --delete-snapshots flag says any snapshots associated with the storage volume should be deleted too. Not all storage drivers support this option โ€” presently only rbd does. so don't come for me if your driver says no ๐Ÿ˜ญ

vol-upload

Syntax:

vol-upload vol-name-or-key-or-path local-file
   [--pool pool-or-uuid] [--offset bytes]
   [--length bytes] [--sparse]

Uploads the contents of local-file into a storage volume. sending it ๐Ÿš€

vol-name-or-key-or-path is the name, key, or path of the volume that local-file gets uploaded into.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If you gave the volume name instead of the key or path, then this pool is necessary to find the volume to upload into; otherwise the first volume found by the key or path gets used.

--offset is the position in the storage volume where writing the data starts. The value must be 0 or larger.

--length is an upper bound on how much data gets uploaded. A negative value is interpreted as an unsigned long long value, which essentially includes everything from the offset to the end of the volume.

If --sparse is specified, this command preserves volume sparseness. keep it airy โœจ

important an error occurs if local-file is greater than the specified length. no sneaky overflow ๐Ÿ’…

See the description for the libvirt virStorageVolUpload API for the deets on possible target volume and pool changes that can happen because of the pool refresh when the upload is attempted.

vol-download

Syntax:

vol-download vol-name-or-key-or-path local-file
   [--pool pool-or-uuid] [--offset bytes] [--length bytes]
   [--sparse]

Downloads the contents of a storage volume into local-file. bringing it home ๐ŸŽ€

vol-name-or-key-or-path is the name, key, or path of the volume to download into local-file.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If you gave the volume name instead of the key or path, then this pool is necessary to find the volume to be uploaded into; otherwise the first volume found by the key or path gets used.

--offset is the position in the storage volume where reading the data starts. The value must be 0 or larger.

--length is an upper bound on how much data gets downloaded. A negative value is interpreted as an unsigned long long value, so it essentially includes everything from the offset to the end of the volume.

If --sparse is specified, this command preserves volume sparseness. ๐ŸŒธ

vol-wipe

Syntax:

vol-wipe vol-name-or-key-or-path [--pool pool-or-uuid] [--algorithm algorithm]

Wipes a volume, making sure the data that was previously on it isn't accessible to future reads. bye, evidence ๐Ÿ”ฅ

vol-name-or-key-or-path is the name, key, or path of the volume to wipe. And yes, you can choose different wiping algorithms instead of just rewriting the volume with zeroes. options, bestie ๐Ÿ’…

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If you gave the volume name instead of the key or path, then this pool is necessary to find the volume to wipe; otherwise the first volume found by the key or path gets used.

Use the --algorithm switch, picking from this whole list of algorithms, and that's how you tell it which wipe method to use ๐Ÿ’…

Supported algorithms ๐Ÿ‘‘

  • zero โ€” 1-pass all zeroes
  • nnsa โ€” 4-pass NNSA Policy Letter NAP-14.1-C (XVI-8) for sanitizing removable and non-removable hard disks: random x2, 0x00, verify.
  • dod โ€” 4-pass DoD 5220.22-M section 8-306 procedure for sanitizing removable and non-removable rigid disks: random, 0x00, 0xff, verify.
  • bsi โ€” 9-pass method recommended by the German Center of Security in Information Technologies (https://www.bsi.bund.de): 0xff, 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f.
  • gutmann โ€” The canonical 35-pass sequence described in Gutmann's paper.
  • schneier โ€” 7-pass method described by Bruce Schneier in "Applied Cryptography" (1996): 0x00, 0xff, random x5.
  • pfitzner7 โ€” Roy Pfitzner's 7-random-pass method: random x7.
  • pfitzner33 โ€” Roy Pfitzner's 33-random-pass method: random x33.
  • random โ€” 1-pass pattern: random.
  • trim โ€” 1-pass trimming the volume using TRIM or DISCARD
Heads up bestie ๐Ÿซถ The scrub binary is what handles the 'nnsa', 'dod', 'bsi', 'gutmann', 'schneier', 'pfitzner7' and 'pfitzner33' algorithms. And which algorithms you can actually use may be limited by whatever version of the scrub binary is installed on the host. The 'zero' algorithm writes zeroes to the entire volume โ€” and for some volumes, like sparse or rbd volumes, that can straight up completely fill the volume with zeroes until it looks completely full ๐Ÿ˜ญ. As an alternative, the 'trim' algorithm does not overwrite all the data in a volume โ€” instead it expects the storage driver to be able to discard all bytes in a volume. It's up to the storage driver to handle how the discarding happens. Not all storage drivers or volume types can support 'trim'. Periodt.

โœจ vol-dumpxml

Syntax:

vol-dumpxml [--pool pool-or-uuid] [--xpath EXPRESSION] [--wrap]
            vol-name-or-key-or-path

Output the volume information as an XML dump to stdout.

vol-name-or-key-or-path is the name or key or path of the volume to output the XML.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If the volume name is provided instead of the key or path, then providing the pool is necessary to find the volume to be uploaded into; otherwise, the first volume found by the key or path will be used. iykyk.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. cute, right? ๐ŸŽ€


๐ŸŒธ vol-info

Syntax:

vol-info vol-name-or-key-or-path [--pool pool-or-uuid] [--bytes] [--physical]

Returns basic information about the given storage volume.

vol-name-or-key-or-path is the name or key or path of the volume to return information for.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If the volume name is provided instead of the key or path, then providing the pool is necessary to find the volume to be uploaded into; otherwise, the first volume found by the key or path will be used.

If --bytes is specified the sizes are not converted to human friendly units. (Raw numbers, no cutesy "3.2 GiB" for you ๐Ÿ˜ค)

If --physical is specified, then the host physical size is returned and displayed instead of the allocation value. The physical value for some file types, such as qcow2 may have a different (larger) physical value than is shown for allocation. Additionally sparse files will have different physical and allocation values. The more you know ๐Ÿ’ซ


๐Ÿฆ‹ vol-list

Syntax:

vol-list [--pool pool-or-uuid] [--details]

Return the list of volumes in the given storage pool.

--pool pool-or-uuid is the name or UUID of the storage pool.

The --details option instructs virsh to additionally display volume type and capacity related information where available. Obsessed with extra info tbh ๐Ÿ“‹


๐Ÿ’… vol-pool

Syntax:

vol-pool vol-key-or-path [--uuid]

Return the pool name or UUID for a given volume. By default, the pool name is returned.

vol-key-or-path is the key or path of the volume to return the pool information.

If the --uuid option is given, the pool UUID is returned instead. slay ๐Ÿ”‘


โญ vol-path

Syntax:

vol-path vol-name-or-key [--pool pool-or-uuid]

Return the path for a given volume.

vol-name-or-key is the name or key of the volume to return the path.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If the volume name is provided instead of the key, then providing the pool is necessary to find the volume to be uploaded into; otherwise, the first volume found by the key will be used.


๐ŸŒˆ vol-name

Syntax:

vol-name vol-key-or-path

Return the name for a given volume.

vol-key-or-path is the key or path of the volume to return the name. No pool needed, she's independent ๐Ÿ’–


๐ŸŽ€ vol-key

Syntax:

vol-key vol-name-or-path [--pool pool-or-uuid]

Return the volume key for a given volume.

vol-name-or-path is the name or path of the volume to return the volume key.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If the volume name is provided instead of the path, then providing the pool is necessary to find the volume to be uploaded into; otherwise, the first volume found by the path will be used.


๐Ÿ”ฅ vol-resize

Syntax:

vol-resize vol-name-or-path capacity [--pool pool-or-uuid] [--allocate] [--delta] [--shrink]

Resize the capacity of the given volume, in bytes.

vol-name-or-key-or-path is the name or key or path of the volume to resize.

capacity is a scaled integer (see NOTES above) for the volume, which defaults to bytes if there is no suffix.

--pool pool-or-uuid is the name or UUID of the storage pool the volume is in. If the volume name is provided instead of the key or path, then providing the pool is necessary to find the volume to be uploaded into; otherwise, the first volume found by the key or path will be used.

The new capacity might be sparse unless --allocate is specified.

Normally, capacity is the new size, but if --delta is present, then it is added to the existing size.

Attempts to shrink the volume will fail unless --shrink is present. The capacity cannot be negative unless --shrink is provided, but a negative sign is not necessary.

Careful bestie ๐Ÿ’€ This command is only safe for storage volumes not in use by an active guest; see also blockresize for live resizing.

๐Ÿ” SECRET COMMANDS ๐Ÿ”

The following commands manipulate "secrets" (e.g. passwords, passphrases and encryption keys). Libvirt can store secrets independently from their use, and other objects (e.g. volumes or domains) can refer to the secrets for encryption or possibly other uses. Secrets are identified using a UUID. See https://libvirt.org/formatsecret.html for documentation of the XML format used to represent properties of secrets. The vault energy is unmatched ngl ๐Ÿ—๏ธ


๐Ÿงš secret-define

Syntax:

secret-define file [--validate]

Create a secret with the properties specified in file, with no associated secret value. If file does not specify a UUID, choose one automatically. If file specifies a UUID of an existing secret, replace its properties by properties defined in file, without affecting the secret value. (So the properties get a glow-up, the value stays put ๐Ÿ’…)

Optionally, the format of the input XML file can be validated against an internal RNG schema with --validate.


๐ŸŒธ secret-dumpxml

Syntax:

secret-dumpxml [--xpath EXPRESSION] [--wrap] secret

Output properties of secret (specified by its UUID) as an XML dump to stdout.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. Same drill as always, bestie โœจ


๐Ÿ‘‘ secret-event

Syntax:

secret-event {[secret] event [--loop] [--timeout seconds] [--timestamp] | --list}

Wait for a class of secret events to occur, and print appropriate details of events as they happen. The events can optionally be filtered by secret. Using --list as the only argument will provide a list of possible event values known by this client, although the connection might not allow registering for all these events. (Rude, but ok ๐Ÿฅฒ)

By default, this command is one-shot, and returns success once an event occurs; you can send SIGINT (usually via Ctrl+C) to quit immediately. If --timeout is specified, the command gives up waiting for events after seconds have elapsed. With --loop, the command prints all events until a timeout or interrupt key.

When --timestamp is used, a human-readable timestamp will be printed before the event.


๐Ÿ”‘ secret-set-value

Syntax:

secret-set-value secret (--file filename [--plain] | --interactive | base64)

Set the value associated with secret (specified by its UUID) to the value Base64-encoded value base64 or Base-64-encoded contents of file named filename. Using the --plain flag is together with --file allows one to use the file contents directly as the secret value.

If --interactive flag is used the secret value is read as a password from the terminal.

Note that --file, --interactive and base64 options are mutually exclusive. Pick one, bestie, you can't have all three ๐Ÿ™ˆ

Ok so this matters: Passing secrets via the base64 option on command line is INSECURE and deprecated. Use the --file option instead. fr fr, don't do it ๐Ÿ’€

๐Ÿ’œ secret-get-value

Syntax:

secret-get-value [--plain] secret

Output the value associated with secret (specified by its UUID) to stdout, encoded using Base64.

If the --plain flag is used the value is not base64 encoded, but rather printed raw. Note that unless virsh is started in quiet mode (virsh -q) it prints a newline at the end of the command. This newline is not part of the secret. (Do not let the newline gaslight you ๐Ÿซถ)


๐Ÿ“ secret-undefine

Syntax:

secret-undefine secret

Delete a secret (specified by its UUID), including the associated value, if any. Gone, gone, gone ๐Ÿ’ซ


๐Ÿฆ‹ secret-list

Syntax:

secret-list [--ephemeral] [--no-ephemeral]
            [--private] [--no-private]

Returns the list of secrets. You may also want to filter the returned secrets by --ephemeral to list the ephemeral ones, --no-ephemeral to list the non-ephemeral ones, --private to list the private ones, and --no-private to list the non-private ones. Filter era, honestly ๐ŸŒˆ

๐Ÿ’ซ SNAPSHOT COMMANDS ๐Ÿ’ซ

Okay bestie, this is the good stuff โ€” these commands let you mess with domain snapshots, and snapshots are lowkey the moment where a domain gets its polaroid taken ๐Ÿ“ธ. A snapshot grabs the disk, memory, and device state of a domain at one specific point in time and saves it for later. The uses are honestly endless: saving a "clean" copy of an OS image, or saving a domain's state right before you do something potentially destructive (we love a safety net ๐Ÿซถ). Every snapshot gets a unique name, that's just the rules. And for the full tea on the XML format that represents snapshot properties, the docs live at https://libvirt.org/formatsnapshot.html โ€” go read, it's giving reference material โœจ.


๐ŸŽ€ snapshot-create

Syntax, bestie:

snapshot-create domain [xmlfile] {[--redefine [--current]] |
   [--no-metadata] [--halt] [--disk-only] [--reuse-external]
   [--quiesce] [--atomic] [--live]} [--validate]

So this creates a snapshot for domain domain with all the properties you dropped into xmlfile. If you want, you can pass --validate to check that your input XML file actually matches the internal RNG schema (literally the same thing as using the virt-xml-validate(1) tool, iykyk). Normally the only properties you can set for a domain snapshot are the <name> and <description> elements, plus <disks> if you gave --disk-only; everything else gets ignored and libvirt just fills it in for you automatically. If you completely omit xmlfile, libvirt picks a value for every single field. The new snapshot becomes the current one, which you can see listed by snapshot-current. Periodt.

If --halt is specified, the domain gets left in an inactive state once the snapshot is created. ๐Ÿ’ค

If --disk-only is specified, the snapshot only includes disk content instead of the usual full system snapshot with vm state. Disk snapshots are captured faster than full system snapshots, but heads up โ€” reverting to a disk snapshot might require fsck or journal replays, because it's basically the disk state at the exact moment the power cord gets abruptly pulled ๐Ÿ˜ญ. And mixing --halt with --disk-only loses any data that wasn't flushed to disk at the time. No cap, be careful.

If --redefine is specified, then literally all XML elements produced by snapshot-dumpxml are valid โ€” this is how you migrate a snapshot hierarchy from one machine to another, recreate a hierarchy when a transient domain goes away and later comes back with the same name and UUID, or make slight alterations in the snapshot metadata (like host-specific aspects of the domain XML embedded in the snapshot). When this flag is in play, the xmlfile argument is mandatory, and the domain's current snapshot won't be altered unless you also pass --current.

If --no-metadata is specified, the snapshot data does get created, but any metadata is immediately discarded โ€” meaning libvirt does not treat the snapshot as current, and you can't revert to it unless --redefine is used later to teach libvirt about the metadata again. It's giving "sworn to secrecy" ๐Ÿคซ.

If --reuse-external is specified, and the snapshot XML asks for an external snapshot with a destination pointing at an existing file, then that destination must exist and be pre-created with the correct format and metadata. The file gets reused; otherwise the snapshot is refused so you don't lose the contents of those existing files. ๐Ÿ›‘

If --quiesce is specified, libvirt tries to use the guest agent to freeze and unfreeze the domain's mounted file systems. But if the domain has no guest agent, snapshot creation fails. Currently this also requires --disk-only to be passed too.

If --atomic is specified, libvirt guarantees the snapshot either fully succeeds or fails with no changes โ€” though not all hypervisors support this. If you don't pass this flag, some hypervisors may fail after partially performing the action, and then you gotta use dumpxml to check whether any partial changes happened. Messy. ๐Ÿ™ˆ

If --live is specified, libvirt takes the snapshot while the guest is running. Both disk snapshot and domain memory snapshot are taken. This increases the size of the memory image of the external snapshot. Currently supported only for full system external snapshots.

Existence of snapshot metadata will prevent attempts to undefine a persistent guest. However, for transient domains, snapshot metadata is silently lost when the domain quits running (whether by a command like destroy or by internal guest action). Slay, but also ๐Ÿ˜ญ.

For now, it is not possible to create snapshots in a domain that has checkpoints, although this restriction will be lifted in a future release. (Future us is gonna eat, current us is just waiting ๐Ÿ’…)


๐Ÿฆ‹ snapshot-create-as

Syntax:

snapshot-create-as domain {[--print-xml] [--no-metadata]
   [--halt] [--reuse-external]} [name]
   [description] [--disk-only [--quiesce]] [--atomic] [--validate]
   [[--live] [--memspec memspec]] [--diskspec] diskspec]...

Creates a snapshot for domain domain with the <name> and <description> you give it; if either value is omitted, libvirt picks one for you. If --print-xml is specified, then the XML appropriate for snapshot-create is output instead of actually creating a snapshot โ€” like a preview, very main character energy โœจ. Otherwise, if --halt is specified, the domain is left in an inactive state after the snapshot is created, and if --disk-only is specified, the snapshot won't include vm state.

The --memspec option controls whether a full system snapshot is internal or external. The --memspec flag is mandatory, followed by a memspec of the form [file=]name[,snapshot=type], where type can be no, internal, or external. To include a literal comma in file=name, escape it with a second comma. And --memspec cannot be used together with --disk-only. Not now, not ever ๐Ÿ’€.

The --diskspec option controls how --disk-only and external full system snapshots create external files. This option can occur multiple times, according to the number of <disk> elements in the domain xml. Each <diskspec> is in the form disk[,snapshot=type][,driver=type][,stype=type][,file=name]. A diskspec must be provided for disks backed by block devices, because libvirt doesn't auto-generate file names for those. The optional stype parameter lets you control the type of the source file โ€” supported values are 'file' (default) and 'block'. To exclude a disk from an external snapshot, use --diskspec disk,snapshot=no.

To include a literal comma in disk or in file=name, escape it with a second comma. A literal --diskspec must precede each diskspec unless all three of domain, name, and description are also present. For example, a diskspec of "vda,snapshot=external,file=/path/to,,new" results in the following XML:

<disk name='vda' snapshot='external'>
  <source file='/path/to,new'/>
</disk>

If --reuse-external is specified, and the domain XML or diskspec option requests an external snapshot with a destination of an existing file, then the destination must exist and be pre-created with the correct format and metadata. The file is then reused; otherwise, a snapshot is refused to avoid losing contents of the existing files. ๐Ÿซถ safety first.

If --quiesce is specified, libvirt tries to use the guest agent to freeze and unfreeze the domain's mounted file systems. However, if the domain has no guest agent, snapshot creation will fail. Currently this requires --disk-only to be passed as well.

If --no-metadata is specified, the snapshot data is created, but any metadata is immediately discarded โ€” that is, libvirt does not treat the snapshot as current, and cannot revert to it unless snapshot-create is later used to teach libvirt about the metadata again.

If --atomic is specified, libvirt guarantees that the snapshot either succeeds or fails with no changes; not all hypervisors support this. If this flag is not specified, then some hypervisors may fail after partially performing the action, and dumpxml must be used to see whether any partial changes occurred.

If --live is specified, libvirt takes the snapshot while the guest is running. This increases the size of the memory image of the external snapshot. This is currently supported only for external full system snapshots.

For now, it is not possible to create snapshots in a domain that has checkpoints, although this restriction will be lifted in a future release.

Optionally, --validate can be passed to validate the XML document which is internally generated by this command against the internal RNG schema. Go off, validation queen ๐Ÿ‘‘.


๐ŸŒธ snapshot-current

Syntax:

snapshot-current domain {[--name] | [--security-info] | [snapshotname]}

Without snapshotname, this outputs the snapshot XML for the domain's current snapshot (if there is one). If --name is specified, you just get the current snapshot name instead of the full xml. Otherwise, using --security-info will also include security sensitive information in the XML. ๐Ÿ™ˆ careful who you share that with.

With snapshotname, this is a request to make the existing named snapshot become the current snapshot without reverting the domain. Just a little promotion, no time travel. ๐Ÿ’…


๐Ÿงš snapshot-edit

Syntax:

snapshot-edit domain [snapshotname] [--current] {[--rename] | [--clone]}

Edits the XML configuration file for snapshotname of a domain. If both snapshotname and --current are specified, it also forces the edited snapshot to become the current snapshot. If snapshotname is omitted, then --current must be supplied, to edit the current snapshot.

This is equivalent to:

virsh snapshot-dumpxml dom name > snapshot.xml
vi snapshot.xml (or make changes with your other text editor)
virsh snapshot-create dom snapshot.xml --redefine [--current]

โ€ฆexcept that it does some error checking. Which is honestly the whole vibe โ€” same energy, better guardrails โœจ.

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi.

If --rename is specified, then the edits can change the snapshot name. If --clone is specified, then changing the snapshot name will create a clone of the snapshot metadata. If neither is specified, then the edits must not change the snapshot name. Note that changing a snapshot name must be done with care, since the contents of some snapshots โ€” such as internal snapshots within a single qcow2 file โ€” are accessible only from the original name. So like, rename at your own risk bestie ๐Ÿ˜ฌ.


โญ snapshot-info

Syntax:

snapshot-info domain {snapshot | --current}

Outputs basic information about a named <snapshot>, or the current snapshot with --current. Short, sweet, informative. We stan a low-effort high-reward command ๐ŸŽ€.


๐ŸŒˆ snapshot-list

Syntax:

snapshot-list domain [--metadata] [--no-metadata]
   [{--parent | --roots | [{--tree | --name}]}] [--topological]
   [{[--from] snapshot | --current} [--descendants]]
   [--leaves] [--no-leaves] [--inactive] [--active]
   [--disk-only] [--internal] [--external]

Lists all of the available snapshots for the given domain, defaulting to showing columns for the snapshot name, creation time, and domain state. A little snapshot inventory, very organized of you ๐Ÿ—‚๏ธโœจ.

Normally, table form output is sorted by snapshot name; using --topological instead sorts so that no child is listed before its ancestors (although there may be more than one possible ordering with this property). Genealogy but make it a table ๐ŸŒณ.

  • --parent โ€” adds a whole extra column to the output table showing the name of each snapshot's parent ๐Ÿ’–
  • --roots โ€” filters the list down to just the snapshots that have no parents (little orphan icons fr fr) ๐ŸŽ€
  • --tree โ€” prints the output in tree format, listing just snapshot names ๐ŸŒธ
Heads up bestie: those three โ€” --parent, --roots, --tree โ€” are mutually exclusive. Pick one, not a combo ๐Ÿ’…

If --name is specified, only the snapshot name gets printed โ€” optionally followed by a tab-separated name of the parent snapshot, but only if --parent is used as well. This one is mutually exclusive with --tree, no cap.

If --from is provided, the list gets filtered to snapshots that are children of the given snapshot; or if --current is provided, it starts at the current snapshot. When used in isolation or with --parent, the list is limited to direct children unless --descendants is also present. When used with --tree, the use of --descendants is implied. This option is not compatible with --roots. Also note: the starting point of --from or --current is not included in the list unless the --tree option is also present ๐Ÿ‘‘

If --leaves is specified, the list gets filtered to just snapshots that have no children. Likewise, if --no-leaves is specified, the list gets filtered to just snapshots with children. (Note that omitting both options does no filtering, while providing both options will either produce the same list or error out depending on whether the server recognizes the flags ๐Ÿ˜ญ server-dependent vibe check). Filtering options are not compatible with --tree.

If --metadata is specified, the list gets filtered to just snapshots that involve libvirt metadata, and thus would prevent undefine of a persistent guest, or be lost on destroy of a transient domain. Likewise, if --no-metadata is specified, the list gets filtered to just snapshots that exist without the need for libvirt metadata ๐Ÿฆ‹

If --inactive is specified, the list gets filtered to snapshots that were taken when the domain was shut off. If --active is specified, the list gets filtered to snapshots that were taken when the domain was running, and where the snapshot includes the memory state to revert to that running state. If --disk-only is specified, the list gets filtered to snapshots that were taken when the domain was running, but where the snapshot includes only disk state โœจ

If --internal is specified, the list gets filtered to snapshots that use internal storage of existing disk images. If --external is specified, the list gets filtered to snapshots that use external files for disk images or memory state ๐Ÿ’พ


๐Ÿงš snapshot-dumpxml

Syntax, bestie:

snapshot-dumpxml [--security-info] [--xpath EXPRESSION] [--wrap]
                 domain snapshot

This outputs the snapshot XML for the domain's snapshot named snapshot. Using --security-info will also include security sensitive information ๐Ÿ” (yes, the spicy stuff). Use snapshot-current to easily access the XML of the current snapshot โ€” handy shortcut, iykyk.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node ๐ŸŽ


๐Ÿซถ snapshot-parent

Syntax:

snapshot-parent domain {snapshot | --current}

Outputs the name of the parent snapshot, if any, for the given snapshot โ€” or for the current snapshot with --current. Simple as that, periodt ๐Ÿ’…


๐Ÿ’€ snapshot-revert

Syntax:

snapshot-revert domain {snapshot | --current} [{--running | --paused}]
   [--force] [--reset-nvram]

Reverts the given domain to the snapshot specified by snapshot, or to the current snapshot with --current.

โš ๏ธ Beware bestie, this is a DESTRUCTIVE action. Any changes in the domain since the last snapshot was taken will be lost. Gone. Poof. ๐Ÿ˜ญ

Also note that the state of the domain after snapshot-revert is complete will be the state of the domain at the time the original snapshot was taken.

Normally, reverting to a snapshot leaves the domain in the state it was at the time the snapshot was created, except that a disk snapshot with no vm state leaves the domain in an inactive state. Passing either the --running or --paused flag will perform additional state changes (such as booting an inactive domain, or pausing a running domain). Since transient domains cannot be inactive, it is required to use one of these flags when reverting to a disk snapshot of a transient domain ๐Ÿ‘‘

Since libvirt 7.10.0 the VM process is always restarted so the following paragraph is no longer valid. If the snapshot metadata lacks the full VM XML it's no longer possible to revert to such snapshot.

There are a number of cases where a snapshot revert involves extra risk, which requires the use of --force to proceed ๐Ÿ’€:

  • One is the case of a snapshot that lacks full domain information for reverting configuration (such as snapshots created prior to libvirt 0.9.5); since libvirt cannot prove that the current configuration matches what was in use at the time of the snapshot, supplying --force assures libvirt that the snapshot is compatible with the current configuration (and if it is not, the domain will likely fail to run).
  • Another is the case of reverting from a running domain to an active state where a new hypervisor has to be created rather than reusing the existing hypervisor, because it implies drawbacks such as breaking any existing VNC or Spice connections; this condition happens with an active snapshot that uses a provably incompatible configuration, as well as with an inactive snapshot that is combined with the --start or --pause flag.
  • Also, libvirt will refuse to restore snapshots of inactive QEMU domains while there is managed saved state. This is because those snapshots do not contain memory state and will therefore not replace the existing memory state. This ends up switching a disk underneath a running system and will likely cause extensive filesystem corruption or crashes due to swap content mismatches when run ๐Ÿซ 

If --reset-nvram is specified, any existing NVRAM/varstore file will be deleted and re-initialized from its pristine template โœจ (fresh start energy).


๐ŸŽ€ snapshot-delete

Syntax:

snapshot-delete domain {snapshot | --current}
   [--metadata] [{--children | --children-only}]

Deletes the snapshot for the domain named snapshot, or the current snapshot with --current. If this snapshot has child snapshots, changes from this snapshot will be merged into the children ๐Ÿงฌ If --children is passed, then delete this snapshot and any children of this snapshot. If --children-only is passed, then delete any children of this snapshot, but leave this snapshot intact.

These two flags โ€” --children and --children-only โ€” are mutually exclusive ๐Ÿ’…

If --metadata is specified, then only delete the snapshot metadata maintained by libvirt, while leaving the snapshot contents intact for access by external tools; otherwise deleting a snapshot also removes the data contents from that point in time. So like, --metadata = aesthetic delete only, everything else = full send ๐Ÿ”ฅ

๐Ÿ’– CHECKPOINT COMMANDS ๐Ÿ’–

Okay bestie, so checkpoints are literally the glow-up of "remember when". The following commands manipulate domain checkpoints. Checkpoints serve as a point in time to identify which portions of a guest's disks have changed after that time, making it possible to perform incremental and differential backups. Checkpoints are identified with a unique name. See https://libvirt.org/formatcheckpoint.html for documentation of the XML format used to represent properties of checkpoints.


checkpoint-create

Syntax:

checkpoint-create domain [xmlfile] { --redefine [--redefine-validate] | [--quiesce]}

Create a checkpoint for domain domain with the properties specified in xmlfile describing a <domaincheckpoint> top-level element. The format of the input XML file will be validated against an internal RNG schema (identical to using the virt-xml-validate(1) tool). If xmlfile is completely omitted, then libvirt will create a checkpoint with a name based on the current time. โฐโœจ

  • --redefine โ€” if this is specified, then all XML elements produced by checkpoint-dumpxml are valid; this can be used to migrate checkpoint hierarchy from one machine to another, to recreate hierarchy for the case of a transient domain that goes away and is later recreated with the same name and UUID, or to make slight alterations in the checkpoint metadata (such as host-specific aspects of the domain XML embedded in the checkpoint). When this flag is supplied, the xmlfile argument is mandatory.
  • --redefine-validate โ€” if this is specified along with --redefine the hypervisor performs validation of metadata associated with the checkpoint stored in places besides the checkpoint XML. Note that some hypervisors may require that the domain is running to perform validation. ๐Ÿ‘€
  • --quiesce โ€” if specified, libvirt will try to use guest agent to freeze and unfreeze domain's mounted file systems. However, if domain has no guest agent, checkpoint creation will fail. No agent, no vibes, no checkpoint. ๐Ÿ˜ญ
Existence of checkpoint metadata will prevent attempts to undefine a persistent guest. However, for transient domains, checkpoint metadata is silently lost when the domain quits running (whether by command such as destroy or by internal guest action). ๐Ÿ’€

For now, it is not possible to create checkpoints in a domain that has snapshots, although this restriction will be lifted in a future release. (Soon-ish, bestie. Soon-ish. ๐Ÿฆ‹)


checkpoint-create-as

Syntax:

checkpoint-create-as domain [--print-xml] [name]
   [description] [--quiesce] [--diskspec] diskspec]...

Create a checkpoint for domain domain with the given name and description; if either value is omitted, libvirt will choose a value. If --print-xml is specified, then XML appropriate for checkpoint-create is output, rather than actually creating a checkpoint. Lowkey the "look but don't touch" of checkpoints. ๐Ÿ™ˆ

The --diskspec option can be used to control which guest disks participate in the checkpoint. This option can occur multiple times, according to the number of <disk> elements in the domain xml. Each <diskspec> is in the form disk[,checkpoint=type][,bitmap=name]. A literal --diskspec must precede each diskspec unless all three of domain, name, and description are also present. For example, a diskspec of "vda,checkpoint=bitmap,bitmap=map1" results in the following XML:

<disk name='vda' checkpoint='bitmap' bitmap='map1'/>

Iconic. Chef's kiss. ๐ŸคŒ

If --quiesce is specified, libvirt will try to use guest agent to freeze and unfreeze domain's mounted file systems. However, if domain has no guest agent, checkpoint creation will fail.

For now, it is not possible to create checkpoints in a domain that has snapshots, although this restriction will be lifted in a future release.


checkpoint-edit

Syntax:

checkpoint-edit domain checkpointname

Edit the XML configuration file for checkpointname of a domain.

This is equivalent to:

virsh checkpoint-dumpxml dom name > checkpoint.xml
vi checkpoint.xml (or make changes with your other text editor)
virsh checkpoint-create dom checkpoint.xml --redefine

โ€ฆexcept that it does some error checking, including that the edits should not attempt to change the checkpoint name. Don't be chaotic like that, bestie. ๐Ÿซถ

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi.


checkpoint-info

Syntax:

checkpoint-info domain checkpoint

Output basic information about a named <checkpoint>. The vibe check, but for checkpoints. โœจ


checkpoint-list

Syntax:

checkpoint-list domain [{--parent | --roots |
   [{--tree | --name}]}] [--topological]
   [[--from] checkpoint | [--descendants]]
   [--leaves] [--no-leaves]

List all of the available checkpoints for the given domain, defaulting to show columns for the checkpoint name and creation time. ๐ŸŽ€

Normally, table form output is sorted by checkpoint name; using --topological instead sorts so that no child is listed before its ancestors (although there may be more than one possible ordering with this property). Highly structured. Very main character. ๐Ÿ‘‘

  • --parent โ€” add a column to the output table giving the name of the parent of each checkpoint.
  • --roots โ€” the list will be filtered to just checkpoints that have no parents.
  • --tree โ€” the output will be in a tree format, listing just checkpoint names.

These three options are mutually exclusive โ€” pick one, diva. ๐Ÿ’…

  • --name โ€” only the checkpoint name is printed, optionally followed by a tab-separated name of the parent checkpoint if --parent is used as well. This option is mutually exclusive with --tree.
  • --from โ€” filter the list to checkpoints which are children of the given checkpoint. When used in isolation or with --parent, the list is limited to direct children unless --descendants is also present. When used with --tree, the use of --descendants is implied. This option is not compatible with --roots. Note that the starting point of --from is not included in the list unless the --tree option is also present. ๐Ÿ‘€
  • --leaves โ€” the list will be filtered to just checkpoints that have no children.
  • --no-leaves โ€” likewise, the list will be filtered to just checkpoints with children.
No cap: omitting both options does no filtering, while providing both options will either produce the same list or error out depending on whether the server recognizes the flags. Filtering options are not compatible with --tree. ๐Ÿ™ˆ

checkpoint-dumpxml

Syntax:

checkpoint-dumpxml [--security-info] [--no-domain] [--size]
                   [--xpath EXPRESSION] [--wrap] domain checkpoint

Output the checkpoint XML for the domain's checkpoint named checkpoint. Using --security-info will also include security sensitive information. ๐Ÿ”

Using --size will add XML indicating the current size in bytes of guest data that has changed since the checkpoint was created (although remember that guest activity between a size check and actually creating a backup can result in the backup needing slightly more space). Note that some hypervisors may require that domain is running when --size is used. Like, actually running. ๐Ÿƒโ€โ™€๏ธ

Using --no-domain will omit the <domain> element from the output for a more compact view.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. So considerate. ๐ŸŽ€


checkpoint-parent

Syntax:

checkpoint-parent domain checkpoint

Output the name of the parent checkpoint, if any, for the given checkpoint. Everybody's got a parent, bestie. ๐ŸŒธ


checkpoint-delete

Syntax:

checkpoint-delete domain checkpoint
   [--metadata] [{--children | --children-only}]

Delete the checkpoint for the domain named checkpoint. The record of which portions of the disk changed since the checkpoint are merged into the parent checkpoint (if any). If --children is passed, then delete this checkpoint and any children of this checkpoint. If --children-only is passed, then delete any children of this checkpoint, but leave this checkpoint intact. These two flags are mutually exclusive. One or the other. Periodt. ๐Ÿ’…

If --metadata is specified, then only delete the checkpoint metadata maintained by libvirt, while leaving the checkpoint contents intact for access by external tools; otherwise deleting a checkpoint also removes the ability to perform an incremental backup from that point in time. Choose wisely, queen. ๐Ÿ‘‘


๐Ÿฆ‹ NWFILTER COMMANDS ๐Ÿฆ‹

The following commands manipulate network filters. Network filters allow filtering of the network traffic coming from and going to virtual machines. Individual network traffic filters are written in XML and may contain references to other network filters, describe traffic filtering rules, or contain both. Network filters are referenced by virtual machines from within their interface description. A network filter may be referenced by multiple virtual machines' interfaces. Sharing is caring, honestly. ๐Ÿซถ


nwfilter-define

Syntax:

nwfilter-define xmlfile [--validate]

Make a new network filter known to libvirt. If a network filter with the same name already exists, it will be replaced with the new XML. Any running virtual machine referencing this network filter will have its network traffic rules adapted. If for any reason the network traffic filtering rules cannot be instantiated by any of the running virtual machines, then the new XML will be rejected. ๐Ÿšซ

Optionally, the format of the input XML file can be validated against an internal RNG schema with --validate. โœจ


nwfilter-undefine

Syntax:

nwfilter-undefine nwfilter-name

Delete a network filter. The deletion will fail if any running virtual machine is currently using this network filter. It's giving "you can't sit with us". ๐Ÿ’€


nwfilter-list

Syntax:

nwfilter-list

List all of the available network filters. Simple. Clean. Iconic. ๐ŸŒˆ


nwfilter-dumpxml

Syntax:

nwfilter-dumpxml [--xpath EXPRESSION] [--wrap] nwfilter-name

Output the network filter XML.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node. Same energy as the checkpoint version, and yes she ate. ๐Ÿ’…


nwfilter-edit

Syntax:

nwfilter-edit nwfilter-name

Edit the XML of a network filter.

This is equivalent to:

virsh nwfilter-dumpxml myfilter > myfilter.xml
vi myfilter.xml (or make changes with your other text editor)
virsh nwfilter-define myfilter.xml

โ€ฆexcept that it does some error checking. The new network filter may be rejected due to the same reason as mentioned in nwfilter-define. ๐Ÿคทโ€โ™€๏ธ

The editor used can be supplied by the $VISUAL or $EDITOR environment variables, and defaults to vi.

๐Ÿ’– NWFILTER BINDING COMMANDS ๐Ÿ’–

okay so these commands are all about network filter bindings, bestie. A network filter binding tracks the association between a network port and a network filter. Generally the bindings are managed automatically by the hypervisor drivers when adding/removing NICs on a guest.

If an admin is creating/deleting TAP devices for non-guest usage, however, the network filter binding commands provide a way to make use of the network filters directly. slay.

โœจ nwfilter-binding-create โœจ

Syntax:

nwfilter-binding-create xmlfile [--validate]

Associate a network port with a network filter. The network filter backend will immediately attempt to instantiate the filter rules on the port. This command may be used to associate a filter with a currently running guest that does not have a filter defined for a specific network port. Since the bindings are generally automatically managed by the hypervisor, using this command to define a filter for a network port and then starting the guest afterwards may prevent the guest from starting if it attempts to use the network port and finds a filter already defined.

Optionally, the format of the input XML file can be validated against an internal RNG schema with --validate.

โš ๏ธ that โ€œguest may not startโ€ bit is real, okay? not me being dramatic โ€” itโ€™s literally in the docs ๐Ÿ’€

๐ŸŽ€ nwfilter-binding-delete ๐ŸŽ€

Syntax:

nwfilter-binding-delete port-name

Disassociate a network port from a network filter. The network filter backend will immediately tear down the filter rules that exist on the port. This command may be used to remove the network port binding for a filter currently in use for the guest while the guest is running without needing to restart the guest. Restoring the network port binding filter for the running guest would be accomplished by using nwfilter-binding-create.

๐Ÿฆ‹ nwfilter-binding-list ๐Ÿฆ‹

Syntax:

nwfilter-binding-list

List all of the network ports which have filters associated with them. short, sweet, iconic.

๐ŸŒธ nwfilter-binding-dumpxml ๐ŸŒธ

Syntax:

nwfilter-binding-dumpxml [--xpath EXPRESSION] [--wrap] port-name

Output the network filter binding XML for the network device called port-name.

If the --xpath argument provides an XPath expression, it will be evaluated against the output XML and only those matching nodes will be printed. The default behaviour is to print each matching node as a standalone document, however, for ease of additional processing, the --wrap argument will cause the matching node to be wrapped in a common root node.


๐Ÿซถ HYPERVISOR-SPECIFIC COMMANDS ๐Ÿซถ

๐Ÿ’€ NOTE: Use of the following commands is strongly discouraged. They can cause libvirt to become confused and do the wrong thing on subsequent operations. Once you have used these commands, please do not report problems to the libvirt developers; the reports will be ignored. If you find that these commands are the only way to accomplish something, then it is better to request that the feature be added as a first-class citizen in the regular libvirt library.

likeโ€ฆ they said what they said, bestie. proceed with main-character caution.

๐Ÿ”ฅ qemu-attach ๐Ÿ”ฅ

Syntax:

qemu-attach pid

Attach an externally launched QEMU process to the libvirt QEMU driver. The QEMU process must have been created with a monitor connection using the UNIX driver. Ideally the process will also have had the -name argument specified.

$ qemu-kvm -cdrom ~/demo.iso \
    -monitor unix:/tmp/demo,server,nowait \
    -name foo \
    -uuid cece4f9f-dff0-575d-0e8e-01fe380f12ea  &
$ QEMUPID=$!
$ virsh qemu-attach $QEMUPID

Not all functions of libvirt are expected to work reliably after attaching to an externally launched QEMU process. There may be issues with the guest ABI changing upon migration and device hotplug or hotunplug may not work. The attached environment should be considered primarily read-only.

๐Ÿšจ primarily read-only is the vibe. donโ€™t expect full chaos-mode libvirt functionality after this.

โญ qemu-monitor-command โญ

Syntax:

qemu-monitor-command domain { [--hmp] | [--pretty] [--return-value] }
    [--pass-fds N,M,...] command...

Send an arbitrary monitor command command to domain domain through the QEMU monitor. The results of the command will be printed on stdout.

If more than one argument is provided for command, they are concatenated with a space in between before passing the single command to the monitor.

Note that libvirt uses the QMP to talk to qemu so command must be valid JSON in QMP format to work properly. If command is not a JSON object libvirt tries to wrap it as a JSON object to provide convenient interface such as the groups of commands with identical handling:

# simple command
$ virsh qemu-monitor-command VM commandname
$ virsh qemu-monitor-command VM '{"execute":"commandname"}'

# with arguments
$ virsh qemu-monitor-command VM commandname '"arg1":123' '"arg2":"test"'
$ virsh qemu-monitor-command VM commandname '{"arg1":123,"arg2":"test"}'
$ virsh qemu-monitor-command VM '{"execute":"commandname", "arguments":{"arg1":123,"arg2":"test"}}'
  • --pretty โ€” if given, the QMP reply is pretty-printed. cute formatting moment โœจ
  • --return-value โ€” if given, the 'return' key of the QMP response object is extracted rather than passing through the full reply from QEMU.
  • --hmp โ€” if passed, the command is considered to be a human monitor command and libvirt will automatically convert it into QMP and convert the result back.
  • --pass-fds โ€” if specified, the argument is a comma separated list of open file descriptors which should be passed on to qemu along with the command.

๐Ÿ’œ qemu-agent-command ๐Ÿ’œ

Syntax:

qemu-agent-command domain [--timeout seconds | --async | --block] command...

Send an arbitrary guest agent command command to domain domain through QEMU agent. --timeout, --async and --block options are exclusive. --timeout requires timeout seconds seconds and it must be positive. When --aysnc is given, the command waits for timeout whether success or failed. And when --block is given, the command waits forever with blocking timeout.

๐Ÿซถ yes, --aysnc is literally spelled like that in the page. do not come for me, iโ€™m preserving the exact text, periodt.

๐ŸŒˆ qemu-monitor-event ๐ŸŒˆ

Syntax:

qemu-monitor-event [domain] [--event event-name]
  [--loop] [--timeout seconds] [--pretty] [--regex] [--no-case]
  [--timestamp]

Wait for arbitrary QEMU monitor events to occur, and print out the details of events as they happen. The events can optionally be filtered by domain or event-name. The 'query-events' QMP command can be used via qemu-monitor-command to learn what events are supported. If --regex is used, event-name is a basic regular expression instead of a literal string. If --no-case is used, event-name will match case-insensitively.

By default, this command is one-shot, and returns success once an event occurs; you can send SIGINT (usually via Ctrl+C) to quit immediately. If --timeout is specified, the command gives up waiting for events after seconds have elapsed. With --loop, the command prints all events until a timeout or interrupt key. If --pretty is specified, any JSON event details are pretty-printed for better legibility.

When --timestamp is used, a human-readable timestamp will be printed before the event, and the timing information provided by QEMU will be omitted.

๐Ÿ’… lxc-enter-namespace ๐Ÿ’…

Syntax:

lxc-enter-namespace domain [--noseclabel] --
   /path/to/binary [arg1, [arg2, ...]]

Enter the namespace of domain and execute the command /path/to/binary passing the requested args. The binary path is relative to the container root filesystem, not the host root filesystem. The binary will inherit the environment variables / console visible to virsh. The command will be run with the same sVirt context and cgroups placement as processes within the container. This command only works when connected to the LXC hypervisor driver. This command succeeds only if /path/to/binary has 0 exit status.

By default the new process will run with the security label of the new parent container. Use the --noseclabel option to instead have the process keep the same security label as virsh.


๐ŸŒฑ ENVIRONMENT ๐ŸŒฑ

The following environment variables can be set to alter the behaviour of virsh

  • VIRSH_DEBUG=<0 to 4> โ€” Turn on verbose debugging of virsh commands. Valid levels are:
    • VIRSH_DEBUG=0 โ€” DEBUG - Messages at ALL levels get logged
    • VIRSH_DEBUG=1 โ€” INFO - Logs messages at levels INFO, NOTICE, WARNING and ERROR
    • VIRSH_DEBUG=2 โ€” NOTICE - Logs messages at levels NOTICE, WARNING and ERROR
    • VIRSH_DEBUG=3 โ€” WARNING - Logs messages at levels WARNING and ERROR
    • VIRSH_DEBUG=4 โ€” ERROR - Messages at only ERROR level gets logged.
  • VIRSH_LOG_FILE=LOGFILE โ€” The file to log virsh debug messages.
  • VIRSH_DEFAULT_CONNECT_URI โ€” The hypervisor to connect to by default. Set this to a URI, in the same format as accepted by the connect option. This environment variable is deprecated in favour of the global LIBVIRT_DEFAULT_URI variable which serves the same purpose.
  • LIBVIRT_DEFAULT_URI โ€” The hypervisor to connect to by default. Set this to a URI, in the same format as accepted by the connect option. This overrides the default URI set in any client config file and prevents libvirt from probing for drivers.
  • VISUAL โ€” The editor to use by the edit and related options.
  • EDITOR โ€” The editor to use by the edit and related options, if VISUAL is not set.
  • VIRSH_HISTSIZE โ€” The number of commands to remember in the command history. The default value is 500.
  • LIBVIRT_DEBUG=LEVEL โ€” Turn on verbose debugging of all libvirt API calls. Valid levels are:
    • LIBVIRT_DEBUG=1 โ€” Messages at level DEBUG or above
    • LIBVIRT_DEBUG=2 โ€” Messages at level INFO or above
    • LIBVIRT_DEBUG=3 โ€” Messages at level WARNING or above
    • LIBVIRT_DEBUG=4 โ€” Messages at level ERROR

For further information about debugging options consult https://libvirt.org/logging.html


๐Ÿ› BUGS ๐Ÿ›

Please report all bugs you discover. This should be done via either:

  1. the mailing list https://libvirt.org/contact.html
  2. the bug tracker https://libvirt.org/bugs.html

Alternatively, you may report bugs to your software distributor / vendor.


๐Ÿ‘‘ AUTHORS ๐Ÿ‘‘

Please refer to the AUTHORS file distributed with libvirt.


Copyright (C) 2005, 2007-2015 Red Hat, Inc., and the authors listed in the libvirt AUTHORS file.


๐ŸŒธ LICENSE ๐ŸŒธ

virsh is distributed under the terms of the GNU LGPL v2+. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE


๐Ÿฆ‹ SEE ALSO ๐Ÿฆ‹


and thatโ€™s a wrap on the whole virsh(1) page, bestie โ€” footer stamp: VIRSH(1) ๐Ÿ’–โœจ๐Ÿซถ

๐Ÿ“ฆ where this page comes from