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,--connectURI โ Connect to the specified URI, as if by theconnectcommand, instead of the default connection.-d,--debugLEVEL โ Enable debug messages at integer LEVEL and above. LEVEL can range from 0 to 4 (default). See the documentation ofVIRSH_DEBUGenvironment variable below for the description of each LEVEL.-e,--escapestring โ Set alternative escape sequence forconsolecommand. 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 thehelpcommand were given instead.-k,--keepalive-intervalINTERVAL โ 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-countCOUNT โ 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,--logFILE โ Output logging details to FILE.-q,--quietโ Avoid extra informational messages.-r,--readonlyโ Make the initial connection read-only, as if by the--readonlyoption of theconnectcommand.-t,--timingโ Output elapsed time information for each command.--no-pkttyagentโ Do not register pkttyagent as authentication agent with the polkit system daemon, even ifvirshhas been started from a terminal.-v,--version[=short]โ Ignore all other arguments, and prints the version of the libvirt libraryvirshis coming from.-V,--version=longโ Ignore all other arguments, and prints the version of the libvirt libraryvirshis 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 hypervisorqemu:///systemโ connect locally as root to the daemon supervising QEMU and KVM domainsqemu:///sessionโ connect locally as a normal user to their own set of QEMU and KVM domainslxc:///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 sleepshm-sleep-millisecsโ set the number of millisecs the shared memory service should sleep before the next scanshm-merge-across-nodesโ specifies if pages from different numa nodes can be merged. When set to0, only pages which physically reside in the memory area of the same NUMA node can be merged. When set to1, pages from all nodes can be merged. Default to1.
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 thevirsh capabilitiesoutput.emulatorbinโ specifies the path to the emulator. The value to be used is either the<emulator>element in the domain XML or thevirsh capabilitiesoutput.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 thevirsh capabililitesoutput. (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 thevirsh capabilitiesoutput 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
--alloption, it displays the free memory in each cell and the total free memory on the machine. - Finally, with a numeric argument, or with
--cellnoplus 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 thecapabilitiescommand. - 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 thedomcapabilitiescommand).
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--liveis specified, affect a running guest. If--configis specified, affect the next start of a persistent guest. If--currentis specified, it's equivalent to either--liveor--config, depending on the current state of the guest. Both--liveand--configflags may be given, but--currentis 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--deleteflag will attempt to remove these invalidated files at the successful completion of the commit operation. And when--keep-relativeis 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 ๐:
- Phase one โ top is copied into base, and the job can only be canceled, with top still containing data not yet in base.
- Phase two โ top and base remain identical until a call to
blockjobwith the--abortflag (keeping top as the active image that tracks changes from that point in time) or the--pivotflag (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
blockjobwith the--abortand--pivotflags pivots over to the copy โ or a call without--pivotleaves 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:
- prepare a template from an existing domain (skip directly to 3a if writing one from scratch)
# virsh dumpxml <domain> > domain.xml
- 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
- 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 ifvirlogdis 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 withdomain.
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 operationsrd_bytesโ count of read byteswr_reqโ count of write operationswr_bytesโ count of written byteserrsโ error countflush_operationsโ count of flush operationsrd_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: thesnapshot-createcommand has a--quiesceoption to freeze and thaw the filesystems automatically to keep snapshots consistent.domfsfreezeis 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.
domif-getlink ๐
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.
domif-setlink ๐
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 requiredminor_faultโ The number of other page faultsunusedโ 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 domainhugetlb_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 statediskโ the equivalent of the S4 ACPI statehybridโ 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 thedisktarget 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--configflag. 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 thevirDomainStateenumstate.reasonโ reason for entering the given state, returned as an int from thevirDomain*Reasonenum matching that state
--cpu-total returns:
cpu.timeโ total cpu time spent for this domain, in nanosecondscpu.userโ user cpu time spent, in nanosecondscpu.systemโ system cpu time spent, in nanosecondscpu.haltpoll.success.timeโ cpu halt polling success time spent, in nanosecondscpu.haltpoll.fail.timeโ cpu halt polling fail time spent, in nanosecondscpu.cache.monitor.countโ the number of cache monitors for this domaincpu.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 usedballoon.maximumโ the maximum memory in KiB allowedballoon.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 requiredballoon.minor_faultโ the number of other page faultsballoon.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 balloonballoon.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 CPUsvcpu.maximumโ maximum number of online virtual CPUsvcpu.<num>.stateโ state of the virtual CPU<num>, as a number from thevirVcpuStateenumvcpu.<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); requiresCONFIG_SCHED_INFOon Linuxvcpu.<num>.haltedโ virtual CPU<num>is halted:yesorno(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 domainnet.<num>.nameโ name of the interface<num>net.<num>.rx.bytesโ number of bytes receivednet.<num>.rx.pktsโ number of packets receivednet.<num>.rx.errsโ number of receive errorsnet.<num>.rx.dropโ number of receive packets droppednet.<num>.tx.bytesโ number of bytes transmittednet.<num>.tx.pktsโ number of packets transmittednet.<num>.tx.errsโ number of transmission errorsnet.<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 usedperf.mbmtโ total system bandwidth from one level of cacheperf.mbmlโ bandwidth of memory traffic for a memory controllerperf.cpu_cyclesโ the count of cpu cycles (total/elapsed)perf.instructionsโ the count of instructionsperf.cache_referencesโ the count of cache hitsperf.cache_missesโ the count of caches missesperf.branch_instructionsโ the count of branch instructionsperf.branch_missesโ the count of branch missesperf.bus_cyclesโ the count of bus cyclesperf.stalled_cycles_frontendโ the count of stalled frontend cpu cyclesperf.stalled_cycles_backendโ the count of stalled backend cpu cyclesperf.ref_cpu_cyclesโ the count of ref cpu cyclesperf.cpu_clockโ the count of cpu clock timeperf.task_clockโ the count of task clock timeperf.page_faultsโ the count of page faultsperf.context_switchesโ the count of context switchesperf.cpu_migrationsโ the count of cpu migrationsperf.page_faults_minโ the count of minor page faultsperf.page_faults_majโ the count of major page faultsperf.alignment_faultsโ the count of alignment faultsperf.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 listedblock.<num>.nameโ name of the target of the block device<num>(the same name for multiple entries if--backingis present)block.<num>.backingIndexโ when--backingis present, matches up with the<backingStore>index listed in the domain XML for backing filesblock.<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 happenedblock.<num>.rd.bytesโ how many bytes got readblock.<num>.rd.timesโ total time in ns spent on readsblock.<num>.wr.reqsโ number of write requestsblock.<num>.wr.bytesโ number of bytes writtenblock.<num>.wr.timesโ total time (ns) spent on writesblock.<num>.fl.reqsโ total flush requestsblock.<num>.fl.timesโ total time (ns) spent flushing the cacheblock.<num>.errorsโ Xen only bestie: this one's the'oo_req'valueblock.<num>.allocationโ offset of the highest written sector, in bytesblock.<num>.capacityโ logical size of the source file, in bytesblock.<num>.physicalโ physical size of the source file, in bytesblock.<num>.thresholdโ the threshold in bytes for delivering theVIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLDevent. Peepdomblkthresholdfor the deets ๐block.<num>.limits.request_alignmentโ alignment requirement for requests, in bytesblock.<num>.limits.discard_maxโ max number of bytes you can discard at onceblock.<num>.limits.discard_alignmentโ optimal alignment for discard requests, in bytesblock.<num>.limits.write_zeroes_maxโ max number of bytes that can be zeroed out at onceblock.<num>.limits.write_zeroes_alignmentโ optimal alignment for write_zeroes requests, in bytesblock.<num>.limits.transfer_optimalโ optimal transfer length, in bytesblock.<num>.limits.transfer_maxโ maximal transfer length, in bytesblock.<num>.limits.transfer_hw_maxโ maximal hardware transfer length of requests that bypass the kernel IO scheduler, in bytesblock.<num>.limits.iov_maxโ maximum number of scatter/gather elementsblock.<num>.limits.iov_hw_maxโ maximal number of scatter/gather elements of requests bypassing the kernel IO schedulerblock.<num>.limits.memory_alignment_minimalโ memory alignment in bytes so no bounce buffer is neededblock.<num>.limits.memory_alignment_optimalโ memory alignment in bytes that gets used for bounce buffersblock.<num>.timed_group.countโ number of blocks of timed group statisticsblock.<num>.timed_group.<num>.interval_lengthโ the time interval in seconds that the stats in this group were collected overblock.<num>.timed_group.<num>.rd_latency_minโ minimum latency of read operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.rd_latency_maxโ maximum latency of read operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.rd_latency_avgโ average latency of read operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.wr_latency_minโ minimum latency of write operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.wr_latency_maxโ maximum latency of write operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.wr_latency_avgโ average latency of write operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.zone_append_latency_minโ minimum latency of zone append operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.zone_append_latency_maxโ maximum latency of zone append operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.zone_append_latency_avgโ average latency of zone append operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.flush_latency_minโ minimum latency of flush operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.flush_latency_maxโ maximum latency of flush operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.flush_latency_avgโ average latency of flush operations in the defined interval, in nanosecondsblock.<num>.timed_group.<num>.rd_queue_depth_avgโ average number of pending read operations in the defined intervalblock.<num>.timed_group.<num>.wr_queue_depth_avgโ average number of pending write operations in the defined intervalblock.<num>.timed_group.<num>.zone_append_queue_depth_avgโ average number of pending zone append operations in the defined intervalblock.<num>.latency_histogram.<type>.bin.countโ number of bins in the latency histogram.<type>is one ofread,write,zone_append, orflush๐block.<num>.latency_histogram.<type>.bin.<num>.startโ start boundary of a latency histogram bin, in nanoseconds, of the given operation durationblock.<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 owniothread_idvalue as the<id>. There may be fewer<id>entries than theiothread.countvalue 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 of0(zero) means polling is disabled.iothread.<id>.poll-growโ the polling time grow value. A value of0(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 of0(zero) means the hypervisor's default weight gets used.
--memory returns:
memory.bandwidth.monitor.countโ how many memory bandwidth monitors this domain hasmemory.bandwidth.monitor.<num>.nameโ the name of monitor nummemory.bandwidth.monitor.<num>.vcpusโ the vcpu list of monitor nummemory.bandwidth.monitor.<num>.node.countโ the number of memory controllers in monitor nummemory.bandwidth.monitor.<num>.node.<index>.idโ host allocated memory controller id for controller index of monitor nummemory.bandwidth.monitor.<num>.node.<index>.bytes.localโ the accumulative bytes consumed by@vcpuspassing through the memory controller in the same processor that the scheduled host CPU belongs tomemory.bandwidth.monitor.<num>.node.<index>.bytes.totalโ the total bytes consumed by@vcpuspassing 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 thevirDomainDirtyRateStatusenumdirtyrate.calc_start_timeโ the start time of the last memory dirty rate calculationdirtyrate.calc_periodโ the period of the last memory dirty rate calculationdirtyrate.megabytes_per_secondโ the calculated memory dirty rate in MiB/sdirtyrate.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 valuesumโ aggregate valuemaxโ 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, orxen-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
--liveis specified, the domain continues to run until the core dump is complete โ no pausing up front, she keeps going ๐ - If
--crashis specified, the domain gets halted with a crashed status, rather than merely being left in a paused state - If
--resetis specified, the domain is reset after a successful dump - If
--bypass-cacheis specified, the save will avoid the file system cache โ although ngl this may slow down the operation ๐ญ - If
--memory-onlyis specified, the file is anelffile, 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 stringis 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--resetare 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 version6.1.0. A--memory-onlyoption is required in order to produce a validELFfile 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:
--inactivetells 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-infowill also include security sensitive information in the XML dump ๐--update-cpuupdates domain CPU requirements according to the host CPU--migratablelets 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--liveor--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 inactiveguest-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--timeoutis omitted)-1โ reset timeout to the default value (currently defined as5seconds 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 domainuser.<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 systemos.nameโ the name of the operating systemos.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 systemos.version-idโ the version id of the operating systemos.kernel-releaseโ the release of the operating system kernelos.kernel-versionโ the version of the operating system kernelos.machineโ the machine hardware nameos.variantโ a specific variant or edition of the operating systemos.variant-idโ the id for a specific variant or edition of the operating system
--timezone returns:
timezone.nameโ the name of the timezonetimezone.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 domainfs.<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 domaindisk.<num>.nameโ device node (Linux) or device UNC (Windows)disk.<num>.partitionโ whether this is a partition or diskdisk.<num>.dependency.countโ the number of device dependenciesdisk.<num>.dependency.<num>.nameโ a dependency namedisk.<num>.serialโ optional disk serial numberdisk.<num>.aliasโ the device alias of the disk (e.g.sda)disk.<num>.guest_aliasโ optional alias assigned to the diskdisk.<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 (thinketh0) 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 (likeipv4) ๐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--liveor--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--liveor--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--livenor--configis 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--liveor--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-nsns โ the maximum polling interval allowed for an IOThread, in ns. Pass a0(zero) and polling for that IOThread is disabled ๐--poll-growfactor โ the factor by which the current polling time gets adjusted to reach the max polling time. Pass0(zero) and the default factor is used ๐--poll-shrinkdivisor โ the quotient by which the current polling time is reduced to get below the maximum polling interval. Pass0(zero) and the default quotient is used ๐ธ--poll-weightfactor โ 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-minvalue โ the lower bound of the number of threads in the worker pool of the given iothread ๐--thread-pool-maxvalue โ 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--liveisn't specified, then handle it as if--livehad 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 ๐.
--xpathEXPRESSION โ 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,--wrapcauses 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 thehard-limitvalue 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 ๐.
--timeoutseconds โ tells virsh to run a specified action when live migration exceeds that many seconds. It can only be used with--live. If--timeout-suspendis 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-postcopyis used, virsh will switch migration from pre-copy to post-copy upon timeout; migration has to be started with--postcopyoption 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--parallelis 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--parallelis not used. For--parallelmigrations 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-levelsets 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-threadsand--comp-mt-dthreadsset the number of compress threads on source and the number of decompress threads on target respectively.--comp-xbzrle-cachesets the size of the page cache in bytes.--comp-zlib-levelsets 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-levelsets 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 (seemigrate_tls_x509_cert_dirin/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-destinationcan 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 ofstrict,interleave,preferred,restrictive, or a valid number fromvirDomainNumatuneMemModeif the daemon supports it.--nodeset nodesetโ set the numa node list, like0-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--liveor--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 withinstructionsin 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 thedomstatscommand using the--perfflag.
--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--liveor--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 theqemu.confconfiguration 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: theweightandcapparameters are defined only for theXEN_CREDITscheduler.
Note: thevcpu_period,emulator_period, andiothread_periodparameters have a valid value range of 1000-1000000 or 0, and thevcpu_quota,emulator_quota, andiothread_quotaparameters 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.
linuxThe 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)
xtThe numeric values are those defined by the original XT keyboard controller. No symbolic names are provided.
See virkeycode-xt(7)
atset1The numeric values are those defined by the AT keyboard controller, set 1 (aka XT compatible set). Extended keycodes fromatset1may differ from extended keycodes in thextcodeset. No symbolic names are provided.
atset2The numeric values are those defined by the AT keyboard controller, set 2. No symbolic names are provided.
atset3The numeric values are those defined by the AT keyboard controller, set 3 (aka PS/2 compatible set). No symbolic names are provided.
os_xThe 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_kbdThe 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.
win32The 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)
usbThe numeric values are those defined by the USB HID specification for keyboard input. No symbolic names are provided.
qnumThe 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.
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 ๐ซถ (peepdomblklistfor 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-storageflag to be provided, so don't skip that step. Not all storage drivers support this option โ presently onlyrbddoes. 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 ๐--tpmand--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 thepersistent_stateattribute 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 viasetvcpus, while--activeshows 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--liveif running, or--configif 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 caserunningmay 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 networkbridgeโ to indicate connection via a bridge device on the hostdirectโ to indicate connection directly to one of the host's network interfaces or bridgeshostdevโ to indicate connection using a passthrough of PCI device on the hostvhostuserโ 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 networkbridgeโ the name of the bridge devicedirectโ the name of the host's interface or bridgehostdevโ the PCI address of the host's interface formatted asdomain:bus:slot.functionvhostuserโ 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--liveor--configdepending 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 โ:--persistentbehaves like--configfor an offline domain, and like--live --configfor a running domain. Also, heads up โ older versions ofvirshused--configas 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 thevirtio-memmemory 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,--updateis equal to--eject. - If the device has no source, and source is specified,
--updateis equal to--insert. - If the device has source, and source is specified,
--updatebehaves like a combination of--ejectand--insert. Both, at once. Main character combo move โจ
- If the device has source (e.g.
- If none of
--eject,--insert, and--updateis specified,--updateis 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
--liveand--configflags may be given, but--currentis 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
--liveand--configโ the--configoption 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
--editnor--new-descis 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--xpathargument 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,--nameand--uuidare mutually exclusive. ๐--titleโ the short network description (title) is printed in an extra column. This flag is usable only with the default--tableoutput.
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
--liveand--configโ the--configoption 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
--editor set โ the key argument must be specified, and is used to prefix the custom elements to bind them to the private namespace. ๐ - if neither
--editnor 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-indexis 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--liveor--config, depending on the current state of the guest. Both--liveand--configmay be given, but--currentis 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 to3260. 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, andiscsitype 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
iscsitype 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 typesnetfs,iscsi,rbd,sheepdog,gluster).--source-path pathโ provides the source directory path for pools backed by directories (pool typedir).--source-dev pathโ provides the source path for pools backed by physical devices (pool typesfs,logical,disk,iscsi,zfs).--source-name nameโ provides the source name for pools backed by storage from a named element (pool typeslogical,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 typesfs,netfs,disk,logical).--source-initiator initiator-iqnโ provides the initiator iqn for iscsi connection of the pool (pool typeiscsi-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 eitherchapfor iscsi type pools orcephfor 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 thescsi_hostNadapter name to be used for thescsi_hostadapter 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 thefc_hostadapter type pool. Optionally provide the parentscsi_hostNnode 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 thescsi_hostNnode 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 apool-buildafter creation in order to remove the need for a follow-up command to build the pool. The--overwriteand--no-overwriteflags follow the same rules aspool-build. If just--buildis provided, thenpool-buildis 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 apool-buildbeforepool-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-overwriteflags work exactly like they do inpool-build. If you just pass--buildon its own, thenpool-buildgets 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)HBAbacked"scsi"pool โ might need to be refreshed multiple times before every volume shows up (peeppool-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 (forqcow2images 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 (forqcow2images 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. Useextendedfor disk storage pools to create an extended partition (other values do get validity checked but are not preserved whenlibvirtdis 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 (forqcow2images 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 (forqcow2images 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 zeroesnnsaโ 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 ๐ซถ Thescrubbinary 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 thescrubbinary 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 thebase64option on command line is INSECURE and deprecated. Use the--fileoption 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--forceassures 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
--startor--pauseflag. - 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 โ--childrenand--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 bycheckpoint-dumpxmlare 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--redefinethe 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--parentis 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--descendantsis also present. When used with--tree, the use of--descendantsis implied. This option is not compatible with--roots. Note that the starting point of--fromis not included in the list unless the--treeoption 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 loggedVIRSH_DEBUG=1โ INFO - Logs messages at levels INFO, NOTICE, WARNING and ERRORVIRSH_DEBUG=2โ NOTICE - Logs messages at levels NOTICE, WARNING and ERRORVIRSH_DEBUG=3โ WARNING - Logs messages at levels WARNING and ERRORVIRSH_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 globalLIBVIRT_DEFAULT_URIvariable 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, ifVISUALis not set.VIRSH_HISTSIZEโ The number of commands to remember in the command history. The default value is500.LIBVIRT_DEBUG=LEVELโ Turn on verbose debugging of all libvirt API calls. Valid levels are:LIBVIRT_DEBUG=1โ Messages at level DEBUG or aboveLIBVIRT_DEBUG=2โ Messages at level INFO or aboveLIBVIRT_DEBUG=3โ Messages at level WARNING or aboveLIBVIRT_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:
- the mailing list https://libvirt.org/contact.html
- 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 ๐
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
- centos-stream 10: libvirt-client 12.8.0-1.el10 ยท GPL-2.0-or-later AND LGPL-2.1-only AND LGPL-2.1-or-later AND OFL-1.1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms