libvirt — Main API¶
- class libvirt.virConnect(_obj: object | None = None)[source]¶
Bases:
object- allocPages(pages: str, startCell: int | None = 0, cellCount: int | None = 0, flags: int | None = 0) int[source]¶
Allocate or free some pages in the huge pages pool
- baselineCPU(xmlCPUs: list[str], flags: int | None = 0) str[source]¶
Computes the most feature-rich CPU which is compatible with all given host CPUs.
- baselineHypervisorCPU(emulator: str, arch: str, machine: str, virttype: str, xmlCPUs: list[str], flags: int | None = 0) str[source]¶
Computes the most feature-rich CPU which is compatible with all given CPUs and can be provided by the specified hypervisor.
- changeBegin(flags: int | None = 0) int[source]¶
This function creates a restore point to which one can return later by calling virInterfaceChangeRollback(). This function should be called before any transaction with interface configuration. Once it is known that a new configuration works, it can be committed via virInterfaceChangeCommit(), which frees the restore point.
If virInterfaceChangeBegin() is called when a transaction is already opened, this function will fail, and a VIR_ERR_INVALID_OPERATION will be logged.
- changeCommit(flags: int | None = 0) int[source]¶
This commits the changes made to interfaces and frees the restore point created by virInterfaceChangeBegin().
If virInterfaceChangeCommit() is called when a transaction is not opened, this function will fail, and a VIR_ERR_INVALID_OPERATION will be logged.
- changeRollback(flags: int | None = 0) int[source]¶
This cancels changes made to interfaces settings by restoring previous state created by virInterfaceChangeBegin().
If virInterfaceChangeRollback() is called when a transaction is not opened, this function will fail, and a VIR_ERR_INVALID_OPERATION will be logged.
- close() int[source]¶
This function closes the connection to the Hypervisor. This should not be called if further interaction with the Hypervisor are needed especially if there is running domain which need further monitoring by the application.
Connections are reference counted; the count is explicitly increased by the initial open (virConnectOpen, virConnectOpenAuth, and the like) as well as virConnectRef; it is also temporarily increased by other API that depend on the connection remaining alive. The open and every virConnectRef call should have a matching virConnectClose, and all other references will be released after the corresponding operation completes.
- compareCPU(xmlDesc: str, flags: int | None = 0) int[source]¶
Compares the given CPU description with the host CPU.
See virConnectCompareHypervisorCPU() if you want to consider hypervisor abilities and compare the CPU to the CPU which a hypervisor is able to provide on the host.
- compareHypervisorCPU(emulator: str, arch: str, machine: str, virttype: str, xmlCPU: str, flags: int | None = 0) int[source]¶
Compares the given CPU description with the CPU the specified hypervisor is able to provide on the host. Any of @emulator, @arch, @machine, and @virttype parameters may be None; libvirt will choose sensible defaults tailored to the host and its current configuration.
This is different from virConnectCompareCPU() which compares the CPU definition with the host CPU without considering any specific hypervisor and its abilities.
- createLinux(xmlDesc: str, flags: int | None = 0) virDomain[source]¶
Deprecated after 0.4.6. Renamed to virDomainCreateXML() providing identical functionality. This existing name will be left indefinitely for API compatibility.
- createXML(xmlDesc: str, flags: int | None = 0) virDomain[source]¶
Launch a new guest domain, based on an XML description similar to the one returned by virDomainGetXMLDesc() This function may require privileged access to the hypervisor. The domain is not persistent, so its definition will disappear when it is destroyed, or if the host is restarted (see virDomainDefineXML() to define persistent domains).
If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume.
If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration. Hypervisors may also block save-to-file, or snapshots.
If @flags includes VIR_DOMAIN_START_RESET_NVRAM, then libvirt will discard any existing NVRAM file and re-initialize NVRAM from the pristine template.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- createXMLWithFiles(xmlDesc: str, files: list[int], flags: int | None = 0) virDomain[source]¶
Launch a new guest domain, based on an XML description similar to the one returned by virDomainGetXMLDesc() This function may require privileged access to the hypervisor. The domain is not persistent, so its definition will disappear when it is destroyed, or if the host is restarted (see virDomainDefineXML() to define persistent domains).
@files provides an array of file descriptors which will be made available to the ‘init’ process of the guest. The file handles exposed to the guest will be renumbered to start from 3 (ie immediately following stderr). This is only supported for guests which use container based virtualization technology.
If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume.
If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration, save-to-file, or snapshots.
- defineXML(xml: str) virDomain[source]¶
Define a domain, but does not start it. This definition is persistent, until explicitly undefined with virDomainUndefine(). A previous definition for this domain with the same UUID and name would be overridden if it already exists.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- defineXMLFlags(xml: str, flags: int | None = 0) virDomain[source]¶
Defines a domain, but does not start it. This definition is persistent, until explicitly undefined with virDomainUndefine(). A previous definition for this domain with the same UUID and name would be overridden if it already exists.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- domainEventDeregister(cb: Callable[[virConnect, virDomain, int, int, _T], int | None]) None[source]¶
Removes a Domain Event Callback. De-registering for a domain callback will disable delivery of this event type
- domainEventDeregisterAny(callbackID: int) None[source]¶
Removes a Domain Event Callback. De-registering for a domain callback will disable delivery of this event type
- domainEventRegister(cb: Callable[[virConnect, virDomain, int, int, _T], int | None], opaque: _T) None[source]¶
Adds a Domain Event Callback. Registering for a domain callback will enable delivery of the events
- domainEventRegisterAny(dom: virDomain | None, eventID: int, cb: Callable, opaque: _T) int[source]¶
Adds a Domain Event Callback. Registering for a domain callback will enable delivery of the events
- domainListGetStats(doms: list[virDomain], stats: int | None = 0, flags: int | None = 0) list[tuple[virDomain, dict[str, Any]]][source]¶
Query statistics for given domains. Report statistics of various parameters for a running VM according to @stats field. The statistics are returned as an array of structures for each queried domain. The structure contains an array of typed parameters containing the individual statistics. The typed parameter name for each statistic field consists of a dot-separated string containing name of the requested group followed by a group specific description of the statistic value. The statistic groups are enabled using the @stats parameter which is a binary-OR of enum virDomainStatsTypes. The following groups are available (although not necessarily implemented for each hypervisor): VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that state. The typed parameter keys are in this format: "state.state" - state of the VM, returned as int from virDomainState enum "state.reason" - reason for entering given state, returned as int from virDomain*Reason enum corresponding to given state. Using 0 for @stats returns all stats groups supported by the given hypervisor. Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes the function return error in case some of the stat types in @stats were not recognized by the daemon. Get statistics about domains provided as a list in @doms. @stats is a bit field selecting requested statistics types.
- domainXMLFromNative(nativeFormat: str, nativeConfig: str, flags: int | None = 0) str[source]¶
Reads native configuration data describing a domain, and generates libvirt domain XML. The format of the native data is hypervisor dependent.
- domainXMLToNative(nativeFormat: str, domainXml: str, flags: int | None = 0) str[source]¶
Reads a domain XML configuration document, and generates a native configuration file describing the domain. The format of the native data is hypervisor dependent.
Note that certain hypervisor drivers such as the QEMU driver configure many aspects of the domain dynamically via hypervisor APIs and that may not be part of the returned native configuration format. Similarly certain resources are passed to the hypervisor via file descriptors, which are not part of the native configuration returned by this API. Such configuration is thus not trivially usable outside of libvirt.
- findStoragePoolSources(type: str, srcSpec: str, flags: int | None = 0) str[source]¶
Talks to a storage backend and attempts to auto-discover the set of available storage pool sources. e.g. For iSCSI this would be a set of iSCSI targets. For NFS this would be a list of exported paths. The srcSpec (optional for some storage pool types, e.g. local ones) is an instance of the storage pool’s source element specifying where to look for the pools.
srcSpec is not required for some types (e.g., those querying local storage resources only)
- getAllDomainStats(stats: int | None = 0, flags: int | None = 0) list[tuple[virDomain, dict[str, Any]]][source]¶
Query statistics for all domains on a given connection. Report statistics of various parameters for a running VM according to @stats field. The statistics are returned as an array of structures for each queried domain. The structure contains an array of typed parameters containing the individual statistics. The typed parameter name for each statistic field consists of a dot-separated string containing name of the requested group followed by a group specific description of the statistic value. The statistic groups are enabled using the @stats parameter which is a binary-OR of enum virDomainStatsTypes. The following groups are available (although not necessarily implemented for each hypervisor): VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that state. The typed parameter keys are in this format: "state.state" - state of the VM, returned as int from virDomainState enum "state.reason" - reason for entering given state, returned as int from virDomain*Reason enum corresponding to given state. Using 0 for @stats returns all stats groups supported by the given hypervisor. Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes the function return error in case some of the stat types in @stats were not recognized by the daemon. Similarly to virConnectListAllDomains, @flags can contain various flags to filter the list of domains to provide stats for. VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE selects online domains while VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE selects offline ones. VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT and VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT allow to filter the list according to their persistence. To filter the list of VMs by domain state @flags can contain VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING, VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED, VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF and/or VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER for all other states.
- getCPUModelNames(arch: str, flags: int | None = 0) str[source]¶
Get the list of supported CPU models.
- getCellsFreeMemory(startCell: int, maxCells: int) str[source]¶
Returns the available memory for a list of cells
- getDomainCapabilities(emulatorbin: str | None = None, arch: str | None = None, machine: str | None = None, virttype: str | None = None, flags: int | None = 0) str[source]¶
Query domain capabilities
- getFreeMemory() int[source]¶
provides the free memory available on the Node Note: most libvirt APIs provide memory sizes in kibibytes, but in this function the returned value is in bytes. Divide by 1024 as necessary.
- getFreePages(pages: str, startCell: int, maxCells: int, flags: int | None = 0) str[source]¶
Returns the number of available pages for a list of cells and page sizes
- getHostname() str[source]¶
This returns a system hostname on which the hypervisor is running (based on the result of the gethostname system call, but possibly expanded to a fully-qualified domain name via getaddrinfo). If we are connected to a remote system, then this returns the hostname of the remote system.
- getInfo() str[source]¶
Extract hardware information about the Node. Note that the memory size is reported in MiB instead of KiB.
- getMaxVcpus(type: str) int[source]¶
Provides the maximum number of virtual CPUs supported for a guest VM of a specific type. The ‘type’ parameter here corresponds to the ‘type’ attribute in the <domain> element of the XML. This API doesn’t take emulator limits into consideration, hence the returned value is not guaranteed to be usable. It is recommended to use virConnectGetDomainCapabilities() and look for “<vcpu max=’…’>” in its output instead.
- getSEVInfo(flags: int | None = 0) str[source]¶
Get platform specific information from the SEV firmware
- getStoragePoolCapabilities(flags: int | None = 0) str[source]¶
Prior creating a storage pool (for instance via virStoragePoolCreateXML or virStoragePoolDefineXML) it may be suitable to know what pool types are supported along with the file/disk formats for each pool.
- getSysinfo(flags: int | None = 0) str[source]¶
This returns the XML description of the sysinfo details for the host on which the hypervisor is running, in the same format as the <sysinfo> element of a domain XML. This information is generally available only for hypervisors running with root privileges.
- getType() str[source]¶
Get the name of the Hypervisor driver used. This is merely the driver name; for example, both KVM and QEMU guests are serviced by the driver for the qemu:// URI, so a return of “QEMU” does not indicate whether KVM acceleration is present. For more details about the hypervisor, use virConnectGetCapabilities().
- getURI() str[source]¶
This returns the URI (name) of the hypervisor connection. Normally this is the same as or similar to the string passed to the virConnectOpen/virConnectOpenReadOnly call, but the driver may make the URI canonical. If name == None was passed to virConnectOpen, then the driver will return a non-None URI which can be used to connect to the same hypervisor later.
- interfaceDefineXML(xml: str, flags: int | None = 0) virInterface[source]¶
Define an inactive persistent physical host interface or modify an existing persistent one from the XML description.
Normally this change in the interface configuration is immediately permanent/persistent, but if virInterfaceChangeBegin() has been previously called (i.e. if an interface config transaction is open), the new interface definition will only become permanent if virInterfaceChangeCommit() is called prior to the next reboot of the system running libvirtd. Prior to that time, it can be explicitly removed using virInterfaceChangeRollback(), or will be automatically removed during the next reboot of the system running libvirtd.
virInterfaceFree should be used to free the resources after the interface object is no longer needed.
- interfaceLookupByMACString(macstr: str) virInterface[source]¶
Try to lookup an interface on the given hypervisor based on its MAC.
virInterfaceFree should be used to free the resources after the interface object is no longer needed.
- interfaceLookupByName(name: str) virInterface[source]¶
Try to lookup an interface on the given hypervisor based on its name.
virInterfaceFree should be used to free the resources after the interface object is no longer needed.
- isAlive() int[source]¶
Determine if the connection to the hypervisor is still alive
A connection will be classed as alive if it is either local, or running over a channel (TCP or UNIX socket) which is not closed.
- isSecure() int[source]¶
Determine if the connection to the hypervisor is secure
A connection will be classed as secure if it is either encrypted, or running over a channel which is not exposed to eavesdropping (eg a UNIX domain socket, or pipe)
- listAllDevices(flags: int | None = 0) list[virNodeDevice][source]¶
Returns a list of host node device objects
- listAllDomains(flags: int | None = 0) list[virDomain][source]¶
List all domains and returns a list of domain objects
- listAllInterfaces(flags: int | None = 0) list[virInterface][source]¶
Returns a list of interface objects
- listAllNWFilterBindings(flags: int | None = 0) list[virNWFilterBinding][source]¶
Returns a list of network filter binding objects
- listAllNWFilters(flags: int | None = 0) list[virNWFilter][source]¶
Returns a list of network filter objects
- listAllNetworks(flags: int | None = 0) list[virNetwork][source]¶
Returns a list of network objects
- listAllStoragePools(flags: int | None = 0) list[virStoragePool][source]¶
Returns a list of storage pool objects
- listDefinedDomains() str[source]¶
list the defined domains, stores the pointers to the names in @names
- listDefinedInterfaces() str[source]¶
list the defined interfaces, stores the pointers to the names in @names
- listDefinedNetworks() str[source]¶
list the defined networks, stores the pointers to the names in @names
- listDefinedStoragePools() str[source]¶
list the defined storage pool, stores the pointers to the names in @names
- listInterfaces() str[source]¶
list the running interfaces, stores the pointers to the names in @names
- lookupByID(id: int) virDomain[source]¶
Try to find a domain based on the hypervisor ID number Note that this won’t work for inactive domains which have an ID of -1, in that case a lookup based on the Name or UUID need to be done instead.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- lookupByName(name: str) virDomain[source]¶
Try to lookup a domain on the given hypervisor based on its name.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- lookupByUUID(uuid: bytes) virDomain[source]¶
Try to lookup a domain on the given hypervisor based on its UUID.
- lookupByUUIDString(uuidstr: str) virDomain[source]¶
Try to lookup a domain on the given hypervisor based on its UUID.
virDomainFree should be used to free the resources after the domain object is no longer needed.
- networkCreateXML(xmlDesc: str) virNetwork[source]¶
Create and start a new virtual network, based on an XML description similar to the one returned by virNetworkGetXMLDesc()
virNetworkFree should be used to free the resources after the network object is no longer needed.
- networkCreateXMLFlags(xmlDesc: str, flags: int | None = 0) virNetwork[source]¶
Create and start a new virtual network, based on an XML description similar to the one returned by virNetworkGetXMLDesc()
virNetworkFree should be used to free the resources after the network object is no longer needed.
- networkDefineXML(xml: str) virNetwork[source]¶
Define an inactive persistent virtual network or modify an existing persistent one from the XML description.
virNetworkFree should be used to free the resources after the network object is no longer needed.
- networkDefineXMLFlags(xml: str, flags: int | None = 0) virNetwork[source]¶
Define an inactive persistent virtual network or modify an existing persistent one from the XML description.
virNetworkFree should be used to free the resources after the network object is no longer needed.
- networkEventDeregisterAny(callbackID: int) None[source]¶
Removes a Network Event Callback. De-registering for a network callback will disable delivery of this event type
- networkEventRegisterAny(net: virNetwork | None, eventID: int, cb: Callable, opaque: _T) int[source]¶
Adds a Network Event Callback. Registering for a network callback will enable delivery of the events
- networkLookupByName(name: str) virNetwork[source]¶
Try to lookup a network on the given hypervisor based on its name.
virNetworkFree should be used to free the resources after the network object is no longer needed.
- networkLookupByUUID(uuid: bytes) virNetwork[source]¶
Try to lookup a network on the given hypervisor based on its UUID.
- networkLookupByUUIDString(uuidstr: str) virNetwork[source]¶
Try to lookup a network on the given hypervisor based on its UUID.
- newStream(flags: int | None = 0) virStream[source]¶
Creates a new stream object which can be used to perform streamed I/O with other public API function.
When no longer needed, a stream object must be released with virStreamFree. If a data stream has been used, then the application must call virStreamFinish or virStreamAbort before free’ing to, in order to notify the driver of termination.
If a non-blocking data stream is required passed VIR_STREAM_NONBLOCK for flags, otherwise pass 0.
- nodeDeviceCreateXML(xmlDesc: str, flags: int | None = 0) virNodeDevice[source]¶
Create a new device on the VM host machine, for example, virtual HBAs created using vport_create.
virNodeDeviceFree should be used to free the resources after the node device object is no longer needed.
- nodeDeviceDefineXML(xmlDesc: str, flags: int | None = 0) virNodeDevice[source]¶
Define a new inactive persistent device or modify an existing persistent one from the XML description on the VM host machine, for example, a mediated device.
virNodeDeviceFree should be used to free the resources after the node device object is no longer needed.
- nodeDeviceEventDeregisterAny(callbackID: int) None[source]¶
Removes a Node Device Event Callback. De-registering for a node device callback will disable delivery of this event type
- nodeDeviceEventRegisterAny(dev: virNodeDevice | None, eventID: int, cb: Callable, opaque: _T) int[source]¶
Adds a Node Device Event Callback. Registering for a node device callback will enable delivery of the events
- nodeDeviceLookupByName(name: str) virNodeDevice[source]¶
Lookup a node device by its name.
virNodeDeviceFree should be used to free the resources after the node device object is no longer needed.
- nodeDeviceLookupSCSIHostByWWN(wwnn: str, wwpn: str, flags: int | None = 0) virNodeDevice[source]¶
Lookup SCSI Host which is capable with ‘fc_host’ by its WWNN and WWPN.
virNodeDeviceFree should be used to free the resources after the node device object is no longer needed.
- numOfDefinedInterfaces() int[source]¶
Provides the number of defined (inactive) interfaces on the physical host.
- numOfDevices(cap: str, flags: int | None = 0) int[source]¶
Provides the number of node devices.
If the optional ‘cap’ argument is non-None, then the count will be restricted to devices with the specified capability
- nwfilterBindingCreateXML(xml: str, flags: int | None = 0) virNWFilterBinding[source]¶
Define a new network filter, based on an XML description similar to the one returned by virNWFilterGetXMLDesc(). This API 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.
virNWFilterFree should be used to free the resources after the binding object is no longer needed.
- nwfilterBindingLookupByPortDev(portdev: str) virNWFilterBinding[source]¶
Try to lookup a network filter binding on the given hypervisor based on network port device name.
virNWFilterBindingFree should be used to free the resources after the binding object is no longer needed.
- nwfilterDefineXML(xmlDesc: str) virNWFilter[source]¶
Define a new network filter, based on an XML description similar to the one returned by virNWFilterGetXMLDesc()
virNWFilterFree should be used to free the resources after the nwfilter object is no longer needed.
- nwfilterDefineXMLFlags(xmlDesc: str, flags: int | None = 0) virNWFilter[source]¶
Define a new network filter, based on an XML description similar to the one returned by virNWFilterGetXMLDesc()
virNWFilterFree should be used to free the resources after the nwfilter object is no longer needed.
- nwfilterLookupByName(name: str) virNWFilter[source]¶
Try to lookup a network filter on the given hypervisor based on its name.
virNWFilterFree should be used to free the resources after the nwfilter object is no longer needed.
- nwfilterLookupByUUID(uuid: bytes) virNWFilter[source]¶
Try to lookup a network filter on the given hypervisor based on its UUID.
- nwfilterLookupByUUIDString(uuidstr: str) virNWFilter[source]¶
Try to lookup an nwfilter on the given hypervisor based on its UUID.
virNWFilterFree should be used to free the resources after the nwfilter object is no longer needed.
- registerCloseCallback(cb: Callable[[virConnect, int, _T], None], opaque: _T) int[source]¶
Adds a close event callback, providing a notification when a connection fails / closes
- restore(frm: str) int[source]¶
This method will restore a domain saved to disk by virDomainSave().
See virDomainRestoreFlags() for more control.
- restoreFlags(frm: str, dxml: str | None = None, flags: int | None = 0) int[source]¶
This method will restore a domain saved to disk by virDomainSave().
If the hypervisor supports it, @dxml can be used to alter host-specific portions of the domain XML that will be used when restoring an image. For example, it is possible to alter the backing filename that is associated with a disk device, in order to prepare for file renaming done as part of backing up the disk device while the domain is stopped.
If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will attempt to bypass the file system cache while restoring the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing restores from NFS.
Normally, the saved state file will remember whether the domain was running or paused, and restore defaults to the same state. Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in @flags will override the default read from the file. These two flags are mutually exclusive.
If @flags includes VIR_DOMAIN_SAVE_RESET_NVRAM, then libvirt will discard any existing NVRAM file and re-initialize NVRAM from the pristine template.
- restoreParams(params: dict[str, Any], flags: int | None = 0) int[source]¶
This method will restore a domain saved to disk.
- saveImageDefineXML(file: str, dxml: str, flags: int | None = 0) int[source]¶
This updates the definition of a domain stored in a saved state file. @file must be a file created previously by virDomainSave() or virDomainSaveFlags().
@dxml can be used to alter host-specific portions of the domain XML that will be used when restoring an image. For example, it is possible to alter the backing filename that is associated with a disk device, to match renaming done as part of backing up the disk device while the domain is stopped.
Normally, the saved state file will remember whether the domain was running or paused, and restore defaults to the same state. Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in @flags will override the default saved into the file; omitting both leaves the file’s default unchanged. These two flags are mutually exclusive.
- saveImageGetXMLDesc(file: str, flags: int | None = 0) str[source]¶
This method will extract the XML describing the domain at the time a saved state file was created. @file must be a file created previously by virDomainSave() or virDomainSaveFlags().
No security-sensitive data will be included unless @flags contains VIR_DOMAIN_SAVE_IMAGE_XML_SECURE.
- secretDefineXML(xml: str, flags: int | None = 0) virSecret[source]¶
If XML specifies a UUID, locates the specified secret and replaces all attributes of the secret specified by UUID by attributes specified in xml (any attributes not specified in xml are discarded).
Otherwise, creates a new secret with an automatically chosen UUID, and initializes its attributes from xml.
virSecretFree should be used to free the resources after the secret object is no longer needed.
- secretEventDeregisterAny(callbackID: int) None[source]¶
Removes a Secret Event Callback. De-registering for a secret callback will disable delivery of this event type
- secretEventRegisterAny(secret: virSecret | None, eventID: int, cb: Callable, opaque: _T) int[source]¶
Adds a Secret Event Callback. Registering for a secret callback will enable delivery of the events
- secretLookupByUUID(uuid: bytes) virSecret[source]¶
Try to lookup a secret on the given hypervisor based on its UUID.
- secretLookupByUUIDString(uuidstr: str) virSecret[source]¶
Try to lookup a secret on the given hypervisor based on its UUID. Uses the printable string value to describe the UUID
virSecretFree should be used to free the resources after the secret object is no longer needed.
- secretLookupByUsage(usageType: int, usageID: str) virSecret[source]¶
Try to lookup a secret on the given hypervisor based on its usage The usageID is unique within the set of secrets sharing the same usageType value.
virSecretFree should be used to free the resources after the secret object is no longer needed.
- setIdentity(params: dict[str, Any], flags: int | None = 0) int[source]¶
Override the default identity information associated with the connection.
- setKeepAlive(interval: int, count: int) int[source]¶
Start sending keepalive messages after @interval seconds of inactivity and consider the connection to be broken when no response is received after @count keepalive messages sent in a row. In other words, sending count + 1 keepalive message results in closing the connection. When @interval is <= 0, no keepalive messages will be sent. When @count is 0, the connection will be automatically closed after @interval seconds of inactivity without sending any keepalive messages.
Note: The client has to implement and run an event loop with virEventRegisterImpl() or virEventRegisterDefaultImpl() to be able to use keepalive messages. Failure to do so may result in connections being closed unexpectedly.
Note: This API function controls only keepalive messages sent by the client. If the server is configured to use keepalive you still need to run the event loop to respond to them, even if you disable keepalives by this function.
- setMemoryParameters(params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the node memory tunables
- storagePoolCreateXML(xmlDesc: str, flags: int | None = 0) virStoragePool[source]¶
Create a new storage based on its XML description. The pool is not persistent, so its definition will disappear when it is destroyed, or if the host is restarted
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storagePoolDefineXML(xml: str, flags: int | None = 0) virStoragePool[source]¶
Define an inactive persistent storage pool or modify an existing persistent one from the XML description.
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storagePoolEventDeregisterAny(callbackID: int) None[source]¶
Removes a Storage Pool Event Callback. De-registering for a storage pool callback will disable delivery of this event type
- storagePoolEventRegisterAny(pool: virStoragePool | None, eventID: int, cb: Callable, opaque: _T) int[source]¶
Adds a Storage Pool Event Callback. Registering for a storage pool callback will enable delivery of the events
- storagePoolLookupByName(name: str) virStoragePool[source]¶
Fetch a storage pool based on its unique name
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storagePoolLookupByTargetPath(path: str) virStoragePool[source]¶
Fetch a storage pool which maps to a particular target directory. If more than one pool maps to the path, it is undefined which will be returned first.
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storagePoolLookupByUUID(uuid: bytes) virStoragePool[source]¶
Fetch a storage pool based on its globally unique id
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storagePoolLookupByUUIDString(uuidstr: str) virStoragePool[source]¶
Fetch a storage pool based on its globally unique id
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- storageVolLookupByKey(key: str) virStorageVol[source]¶
Fetch a pointer to a storage volume based on its globally unique key
virStorageVolFree should be used to free the resources after the storage volume object is no longer needed.
- storageVolLookupByPath(path: str) virStorageVol[source]¶
Fetch a pointer to a storage volume based on its locally (host) unique path
virStorageVolFree should be used to free the resources after the storage volume object is no longer needed.
- suspendForDuration(target: int, duration: int, flags: int | None = 0) int[source]¶
Attempt to suspend the node (host machine) for the given duration of time in the specified state (Suspend-to-RAM, Suspend-to-Disk or Hybrid-Suspend). Schedule the node’s Real-Time-Clock interrupt to resume the node after the duration is complete.
- virConnGetLastError() tuple[int, int, str, int, str, str | None, str | None, int, int][source]¶
Provide a pointer to the last error caught on that connection
This method is not protected against access from multiple threads. In a multi-threaded application, always use the global virGetLastError() API which is backed by thread local storage.
If the connection object was discovered to be invalid by an API call, then the error will be reported against the global error object.
Since 0.6.0, all errors reported in the per-connection object are also duplicated in the global error object. As such an application can always use virGetLastError(). This method remains for backwards compatibility.
- class libvirt.virDomain(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- FDAssociate(name: str, files: list[int], flags: int | None = 0) int[source]¶
Associate the array of FDs passed as @fds with the domain object under @name. The FDs are associated as long as the connection used to associated exists and are disposed of afterwards. FD may still be kept open by the hypervisor for as long as it’s needed.
Security labelling (e.g. via the selinux) may be applied on the passed FDs when requiredg for usage by the VM. By default libvirt does not restore the seclabels on the FDs afterwards to avoid keeping it open unnecessarily.
Restoring of the security label can be requested by passing either VIR_DOMAIN_FD_ASSOCIATE_SECLABEL_RESTORE for a best-effort attempt to restore the security label after use. Requesting the restore of security label will require that the file descriptors are kept open for the whole time they are used by the hypervisor, or other additional overhead.
In certain cases usage of the fd group would imply read-only access. Passing VIR_DOMAIN_FD_ASSOCIATE_SECLABEL_WRITABLE in @flags ensures that a writable security label is picked in case when the file represented by the fds may be used in write mode.
- XMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the domain. The description may be reused later to relaunch the domain with virDomainCreateXML().
No security-sensitive data will be included unless @flags contains VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only connections. If @flags includes VIR_DOMAIN_XML_INACTIVE, then the XML represents the configuration that will be used on the next boot of a persistent domain; otherwise, the configuration represents the currently running domain. If @flags contains VIR_DOMAIN_XML_UPDATE_CPU, then the portion of the domain XML describing CPU capabilities is modified to match actual capabilities of the host.
If @flags contains VIR_DOMAIN_XML_MIGRATABLE, the XML is altered to assist in migrations, since the source and destination may be running different libvirt versions. This may include trimming redundant or default information that might confuse an older recipient, or exposing internal details that aid a newer recipient; this flag is rejected on read-only connections, and the resulting XML might not validate against the schema, so it is mainly for internal use.
- abortJob() int[source]¶
Requests that the current background job be aborted at the soonest opportunity. In case the job is a migration in a post-copy mode, virDomainAbortJob will report an error (see virDomainMigrateStartPostCopy for more details).
- abortJobFlags(flags: int | None = 0) int[source]¶
Requests that the current background job be aborted at the soonest opportunity. In case the job is a migration in a post-copy mode, this function will report an error unless VIR_DOMAIN_ABORT_JOB_POSTCOPY flag is used (see virDomainMigrateStartPostCopy for more details).
- addIOThread(iothread_id: int, flags: int | None = 0) int[source]¶
Dynamically add an IOThread to the domain. It is left up to the underlying virtual hypervisor to determine the valid range for an @iothread_id and determining whether the @iothread_id already exists.
Note that this call can fail if the underlying virtualization hypervisor does not support it or if growing the number is arbitrarily limited. This function requires privileged access to the hypervisor.
@flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain and may fail if domain is not alive. If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, and will fail for transient domains. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed.
- agentSetResponseTimeout(timeout: int, flags: int | None = 0) int[source]¶
Set how long to wait for a response from guest agent commands. By default, agent commands block forever waiting for a response. @timeout must be a value from virDomainAgentResponseTimeoutValues or positive: VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_BLOCK(-2): meaning to block forever waiting for a result. VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_DEFAULT(-1): use default timeout value. VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_NOWAIT(0): does not wait. positive value: wait for @timeout seconds In all guest-agent based APIs when a timeout happens if an actual command was send to the guest agent the returned error code will be VIR_ERR_AGENT_COMMAND_TIMEOUT.
- attachDevice(xml: str) int[source]¶
Create a virtual device attachment to backend. This function, having hotplug semantics, is only allowed on an active domain.
For compatibility, this method can also be used to change the media in an existing CDROM/Floppy device, however, applications are recommended to use the virDomainUpdateDeviceFlags method instead.
Be aware that hotplug changes might not persist across a domain going into S4 state (also known as hibernation) unless you also modify the persistent domain definition.
- attachDeviceFlags(xml: str, flags: int | None = 0) int[source]¶
Attach a virtual device to a domain, using the flags parameter to control how the device is attached. VIR_DOMAIN_AFFECT_CURRENT specifies that the device allocation is made based on current domain state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be allocated to the active domain instance only and is not added to the persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG specifies that the device shall be allocated to the persisted domain configuration only. Note that the target hypervisor must return an error if unable to satisfy flags. E.g. the hypervisor driver will return failure if LIVE is specified but it only supports modifying the persisted device allocation.
For compatibility, this method can also be used to change the media in an existing CDROM/Floppy device, however, applications are recommended to use the virDomainUpdateDeviceFlag method instead.
Be aware that hotplug changes might not persist across a domain going into S4 state (also known as hibernation) unless you also modify the persistent domain definition.
- authorizedSSHKeysGet(user: str, flags: int | None = 0) str[source]¶
Fetch list of public SSH authorized keys for given user in domain.
- authorizedSSHKeysSet(user: str, keys: str | None = None, flags: int | None = 0) int[source]¶
Manipulate set of public SSH authorized keys for given user in domain.
- autostartOnce() int[source]¶
Provides a boolean value indicating whether the domain is configured to be automatically started the next time the host machine boots only.
- backupBegin(backupXML: str, checkpointXML: str, flags: int | None = 0) int[source]¶
Start a point-in-time backup job for the specified disks of a running domain.
A backup job is a domain job and thus mutually exclusive with any other domain job such as migration.
For now, backup jobs are also mutually exclusive with any other block job on the same device, although this restriction may be lifted in a future release. Progress of the backup job can be tracked via virDomainGetJobStats(). Completion of the job is also announced asynchronously via VIR_DOMAIN_EVENT_ID_JOB_COMPLETED event.
There are two fundamental backup approaches. The first, called a push model, instructs the hypervisor to copy the state of the guest disk to the designated storage destination (which may be on the local file system or a network device). In this mode, the hypervisor writes the content of the guest disk to the destination, then emits VIR_DOMAIN_EVENT_ID_JOB_COMPLETED when the backup is either complete or failed (the backup image is invalid if the job fails or virDomainAbortJob() is used prior to the event being emitted). This kind of the job finishes automatically. Users can determine success by using virDomainGetJobStats() with VIR_DOMAIN_JOB_STATS_COMPLETED flag.
The second, called a pull model, instructs the hypervisor to expose the state of the guest disk over an NBD export. A third-party client can then connect to this export and read whichever portions of the disk it desires. In this mode libvirt has to be informed via virDomainAbortJob() when the third-party NBD client is done and the backup resources can be released.
The @backupXML parameter contains details about the backup in the top-level element <domainbackup>, including which backup mode to use, whether the backup is incremental from a previous checkpoint, which disks participate in the backup, the destination for a push model backup, and the temporary storage and NBD server details for a pull model backup.
virDomainBackupGetXMLDesc() can be called to learn actual values selected. For more information, see https://libvirt.org/formatbackup.html#backup-xml
The @checkpointXML parameter is optional; if non-None, then libvirt behaves as if virDomainCheckpointCreateXML() were called to create a checkpoint atomically covering the same point in time as the backup.
The VIR_DOMAIN_BACKUP_BEGIN_REUSE_EXTERNAL specifies that the output or temporary files described by the @backupXML document were created by the caller with correct format and size to hold the backup or temporary data.
When the VIR_DOMAIN_BACKUP_BEGIN_PRESERVE_SHUTDOWN_DOMAIN flag is used libvirt will not terminate the VM if the guest OS shuts down while the backup is running. The VM will be kept in the VIR_DOMAIN_PAUSED state until the backup job finishes or until it’s resumed via virDomainResume.
The creation of a new checkpoint allows for future incremental backups. Note that some hypervisors may require a particular disk format, such as qcow2, in order to take advantage of checkpoints, while allowing arbitrary formats if checkpoints are not involved.
- backupGetXMLDesc(flags: int | None = 0) str[source]¶
Queries the configuration of the active backup job.
In some cases, a user can start a backup job without supplying all details and rely on libvirt to fill in the rest (for example, selecting the port used for an NBD export). This API can then be used to learn what default values were chosen.
- blockCommit(disk: str, base: str, top: str, bandwidth: int | None = 0, flags: int | None = 0) int[source]¶
Commit changes that were made to temporary top-level files within a disk image backing file chain into a lower-level base file. In other words, take all the difference between @base and @top, and update @base to contain that difference; after the commit, any portion of the chain that previously depended on @top will now depend on @base, and all files after @base up to and including @top will now be invalidated. A typical use of this command is to reduce the length of a backing file chain after taking an external disk snapshot. To move data in the opposite direction, see virDomainBlockPull().
This command starts a long-running commit block job, whose status may be tracked by virDomainBlockJobInfo() with a job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT, and the operation can be aborted with virDomainBlockJobAbort(). When finished, an asynchronous event is raised to indicate the final status, and the job no longer exists. If the job is aborted, it is up to the hypervisor whether starting a new job will resume from the same point, or start over.
As a special case, if @top is the active image (or None), and @flags includes VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, the block job will have a type of VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, and operates in two phases. In the first phase, the contents are being committed into @base, and the job can only be canceled. The job transitions to the second phase when the block job event with state VIR_DOMAIN_BLOCK_JOB_READY is emitted for the given device. This information is also visible in the live XML as ‘ready=”yes”’ attribute of the corresponding <mirror> element. Once in the second phase, the user must choose whether to cancel the job (keeping @top as the active image, but now containing only the changes since the time the job ended) or to pivot the job (adjusting to @base as the active image, and invalidating @top).
Be aware that this command may invalidate files even if it is aborted; the user is cautioned against relying on the contents of invalidated intermediate files such as @top (when @top is not the active image) without manually rebasing those files to use a backing file of a read-only copy of @base prior to the point where the commit operation was started (and such a rebase cannot be safely done until the commit has successfully completed). However, the domain itself will not have any issues; the active layer remains valid throughout the entire commit operation.
Some hypervisors may support a shortcut where if @flags contains VIR_DOMAIN_BLOCK_COMMIT_DELETE, then this command will unlink all files that were invalidated, after the commit successfully completes.
If @flags contains VIR_DOMAIN_BLOCK_COMMIT_RELATIVE, the name recorded into the overlay of the @top image (if there is such image) as the path to the new backing file will be kept relative to other images. The operation will fail if libvirt can’t infer the name.
By default, if @base is None, the commit target will be the bottom of the backing chain; if @flags contains VIR_DOMAIN_BLOCK_COMMIT_SHALLOW, then the immediate backing file of @top will be used instead. If @top is None, the active image at the top of the chain will be used. Some hypervisors place restrictions on how much can be committed, and might fail if @base is not the immediate backing file of @top, or if @top is the active layer in use by a running domain but @flags did not include VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, or if @top is not the top-most file; restrictions may differ for online vs. offline domains.
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
The @base and @top parameters can be either paths to files within the backing chain, or the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”) followed by an index to the backing chain enclosed in square brackets. Backing chain indexes can be found by inspecting //disk//backingStore/@index in the domain XML. Thus, for example, “vda[3]” refers to the backing store with index equal to “3” in the chain of disk “vda”.
The maximum bandwidth that will be used to do the commit can be specified with the @bandwidth parameter. If set to 0, there is no limit. If @flags includes VIR_DOMAIN_BLOCK_COMMIT_BANDWIDTH_BYTES, @bandwidth is in bytes/second; otherwise, it is in MiB/second. Values larger than 2^52 bytes/sec may be rejected due to overflow considerations based on the word size of both client and server, and values larger than 2^31 bytes/sec may cause overflow problems if later queried by virDomainGetBlockJobInfo() without scaling. Hypervisors may further restrict the range of valid bandwidth values. Some hypervisors do not support this feature and will return an error if bandwidth is not 0; in this case, it might still be possible for a later call to virDomainBlockJobSetSpeed() to succeed. The actual speed can be determined with virDomainGetBlockJobInfo().
- blockCopy(disk: str, destxml: str, params: dict[str, Any] | None = None, flags: int | None = 0) int[source]¶
Copy the guest-visible contents of a disk image to a new file described by destxml
- blockInfo(path: str, flags: int | None = 0) str[source]¶
Extract information about a domain block device size
- blockJobAbort(disk: str, flags: int | None = 0) int[source]¶
Cancel the active block job on the given disk.
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or (since 0.9.5) the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, then by default, this function performs a synchronous operation and the caller may assume that the operation has completed when 0 is returned. However, BlockJob operations may take a long time to cancel, and during this time further domain interactions may be unresponsive. To avoid this problem, pass VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC in the @flags argument to enable asynchronous behavior, returning as soon as possible. When the job has been canceled, a BlockJob event will be emitted, with status VIR_DOMAIN_BLOCK_JOB_CANCELED (even if the ABORT_ASYNC flag was not used); it is also possible to poll virDomainBlockJobInfo() to see if the job cancellation is still pending. This type of job can be restarted to pick up from where it left off.
If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_COPY, then the default is to abort the mirroring and revert to the source disk; likewise, if the current job is VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, the default is to abort without changing the active layer of @disk. Adding @flags of VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT causes this call to fail with VIR_ERR_BLOCK_COPY_ACTIVE if the copy or commit is not yet ready; otherwise it will swap the disk over to the new active image to end the mirroring or active commit. An event will be issued when the job is ended, and it is possible to use VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC to control whether this command waits for the completion of the job. Restarting a copy or active commit job requires starting over from the beginning of the first phase.
- blockJobInfo(path: str, flags: int | None = 0) str[source]¶
Get progress information for a block job
- blockJobSetSpeed(disk: str, bandwidth: int, flags: int | None = 0) int[source]¶
Set the maximum allowable bandwidth that a block job may consume. If bandwidth is 0, the limit will revert to the hypervisor default of unlimited.
If @flags contains VIR_DOMAIN_BLOCK_JOB_SPEED_BANDWIDTH_BYTES, @bandwidth is in bytes/second; otherwise, it is in MiB/second. Values larger than 2^52 bytes/sec may be rejected due to overflow considerations based on the word size of both client and server, and values larger than 2^31 bytes/sec may cause overflow problems if later queried by virDomainGetBlockJobInfo() without scaling. Hypervisors may further restrict the range of valid bandwidth values.
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or (since 0.9.5) the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
- blockPeek(disk: str, offset: int, size: int, flags: int | None = 0) str[source]¶
Read the contents of domain’s disk device
- blockPull(disk: str, bandwidth: int | None = 0, flags: int | None = 0) int[source]¶
Populate a disk image with data from its backing image. Once all data from its backing image has been pulled, the disk no longer depends on a backing image. This function pulls data for the entire device in the background. Progress of the operation can be checked with virDomainGetBlockJobInfo() and the operation can be aborted with virDomainBlockJobAbort(). When finished, an asynchronous event is raised to indicate the final status. To move data in the opposite direction, see virDomainBlockCommit().
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or (since 0.9.5) the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
The maximum bandwidth that will be used to do the copy can be specified with the @bandwidth parameter. If set to 0, there is no limit. If @flags includes VIR_DOMAIN_BLOCK_PULL_BANDWIDTH_BYTES, @bandwidth is in bytes/second; otherwise, it is in MiB/second. Values larger than 2^52 bytes/sec may be rejected due to overflow considerations based on the word size of both client and server, and values larger than 2^31 bytes/sec may cause overflow problems if later queried by virDomainGetBlockJobInfo() without scaling. Hypervisors may further restrict the range of valid bandwidth values. Some hypervisors do not support this feature and will return an error if bandwidth is not 0; in this case, it might still be possible for a later call to virDomainBlockJobSetSpeed() to succeed. The actual speed can be determined with virDomainGetBlockJobInfo().
This is shorthand for virDomainBlockRebase() with a None base.
- blockRebase(disk: str, base: str, bandwidth: int | None = 0, flags: int | None = 0) int[source]¶
Populate a disk image with data from its backing image chain, and setting the backing image to @base, or alternatively copy an entire backing chain to a new file @base.
When @flags is 0, this starts a pull, where @base must be the absolute path of one of the backing images further up the chain, or None to convert the disk image so that it has no backing image. Once all data from its backing image chain has been pulled, the disk no longer depends on those intermediate backing images. This function pulls data for the entire device in the background. Progress of the operation can be checked with virDomainGetBlockJobInfo() with a job type of VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, and the operation can be aborted with virDomainBlockJobAbort(). When finished, an asynchronous event is raised to indicate the final status, and the job no longer exists. If the job is aborted, a new one can be started later to resume from the same point.
If @flags contains VIR_DOMAIN_BLOCK_REBASE_RELATIVE, the name recorded into the active disk as the location for @base will be kept relative. The operation will fail if libvirt can’t infer the name.
When @flags includes VIR_DOMAIN_BLOCK_REBASE_COPY, this starts a copy, where @base must be the name of a new file to copy the chain to. By default, the copy will pull the entire source chain into the destination file, but if @flags also contains VIR_DOMAIN_BLOCK_REBASE_SHALLOW, then only the top of the source chain will be copied (the source and destination have a common backing file). By default, @base will be created with the same file format as the source, but this can be altered by adding VIR_DOMAIN_BLOCK_REBASE_COPY_RAW to force the copy to be raw (does not make sense with the shallow flag unless the source is also raw), or by using VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT to reuse an existing file which was pre-created with the correct format and metadata and sufficient size to hold the copy. In case the VIR_DOMAIN_BLOCK_REBASE_SHALLOW flag is used the pre-created file has to exhibit the same guest visible contents as the backing file of the original image. This allows a management app to pre-create files with relative backing file names, rather than the default of absolute backing file names; as a security precaution, you should generally only use reuse_ext with the shallow flag and a non-raw destination file. By default, the copy destination will be treated as type=’file’, but using VIR_DOMAIN_BLOCK_REBASE_COPY_DEV treats the destination as type=’block’ (affecting how virDomainGetBlockInfo() will report allocation after pivoting).
A copy job has two parts; in the first phase, the @bandwidth parameter affects how fast the source is pulled into the destination, and the job can only be canceled by reverting to the source file; progress in this phase can be tracked via the virDomainBlockJobInfo() command, with a job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COPY. The job transitions to the second phase when the job info states cur == end, and remains alive to mirror all further changes to both source and destination. The user must call virDomainBlockJobAbort() to end the mirroring while choosing whether to revert to source or pivot to the destination. An event is issued when the job ends, and depending on the hypervisor, an event may also be issued when the job transitions from pulling to mirroring. If the job is aborted, a new job will have to start over from the beginning of the first phase.
Some hypervisors will restrict certain actions, such as virDomainSave() or virDomainDetachDevice(), while a copy job is active; they may also restrict a copy job to transient domains.
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
The @base parameter can be either a path to a file within the backing chain, or the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”) followed by an index to the backing chain enclosed in square brackets. Backing chain indexes can be found by inspecting //disk//backingStore/@index in the domain XML. Thus, for example, “vda[3]” refers to the backing store with index equal to “3” in the chain of disk “vda”.
The maximum bandwidth that will be used to do the copy can be specified with the @bandwidth parameter. If set to 0, there is no limit. If @flags includes VIR_DOMAIN_BLOCK_REBASE_BANDWIDTH_BYTES, @bandwidth is in bytes/second; otherwise, it is in MiB/second. Values larger than 2^52 bytes/sec may be rejected due to overflow considerations based on the word size of both client and server, and values larger than 2^31 bytes/sec may cause overflow problems if later queried by virDomainGetBlockJobInfo() without scaling. Hypervisors may further restrict the range of valid bandwidth values. Some hypervisors do not support this feature and will return an error if bandwidth is not 0; in this case, it might still be possible for a later call to virDomainBlockJobSetSpeed() to succeed. The actual speed can be determined with virDomainGetBlockJobInfo().
When @base is None and @flags is 0, this is identical to virDomainBlockPull(). When @flags contains VIR_DOMAIN_BLOCK_REBASE_COPY, this command is shorthand for virDomainBlockCopy() where the destination XML encodes @base as a <disk type=’file’>, @bandwidth is properly scaled and passed as a typed parameter, the shallow and reuse external flags are preserved, and remaining flags control whether the XML encodes a destination format of raw instead of leaving the destination identical to the source format or probed from the reused file.
- blockResize(disk: str, size: int, flags: int | None = 0) int[source]¶
Resize a block device of domain while the domain is running. If @flags is 0, then @size is in kibibytes (blocks of 1024 bytes); since 0.9.11, if @flags includes VIR_DOMAIN_BLOCK_RESIZE_BYTES, @size is in bytes instead. @size is taken directly as the new size. Depending on the file format, the hypervisor may round up to the next alignment boundary.
If @flag contains VIR_DOMAIN_BLOCK_RESIZE_CAPACITY (since 10.0.0) the hypervisor will resize the guest block device to fully fill the source. @size must be either set to zero, or to the exact size of the block device source. This is possible only for image formats with no metadata (‘raw’) and for source devices with limited capacity such as block devices.
The @disk parameter is either an unambiguous source name of the block device (the <source file=’…’/> sub-element, such as “/path/to/image”), or (since 0.9.5) the device target shorthand (the <target dev=’…’/> sub-element, such as “vda”). Valid names can be found by calling virDomainGetXMLDesc() and inspecting elements within //domain/devices/disk.
Note that this call may fail if the underlying virtualization hypervisor does not support it; this call requires privileged access to the hypervisor.
- blockStatsFlags(path: str, flags: int | None = 0) str[source]¶
Extracts block device statistics parameters of a running domain
- checkpointCreateXML(xmlDesc: str, flags: int | None = 0) virDomainCheckpoint[source]¶
Create a new checkpoint using @xmlDesc, with a top-level <domaincheckpoint> element, on a running @domain. Note that @xmlDesc must validate against the <domaincheckpoint> XML schema. Typically, it is more common to create a new checkpoint as part of kicking off a backup job with virDomainBackupBegin(); however, it is also possible to start a checkpoint without a backup.
See https://libvirt.org/formatcheckpoint.html#checkpoint-xml for more details on @xmlDesc. In particular, some hypervisors may require particular disk formats, such as qcow2, in order to support this command; where @xmlDesc can be used to limit the checkpoint to a working subset of the domain’s disks.
If @flags includes VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE, then this is a request to reinstate checkpoint metadata that was previously captured from virDomainCheckpointGetXMLDesc() before removing that metadata, rather than creating a new checkpoint. Note that while original creation can omit a number of elements from @xmlDesc (and libvirt will supply sane defaults based on the domain state at that point in time), a redefinition must supply more elements (as the domain may have changed in the meantime, so that libvirt no longer has a way to resupply correct defaults). Not all hypervisors support this flag.
If @flags includes VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE_VALIDATE along with VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE the state of the metadata related to the disk state of the redefined checkpoint is validated. Note that hypervisors may require that the @domain is running to perform validation.
If @flags includes VIR_DOMAIN_CHECKPOINT_CREATE_QUIESCE, then the libvirt will attempt to use guest agent to freeze and thaw all file systems in use within domain OS. However, if the guest agent is not present, an error is thrown. This flag is incompatible with VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE.
Note: A checkpoint represents point in time after which blocks changed by the hypervisor are tracked. The tracking of changed blocks notes only whether a block was modified, but does not preserve the old contents. The main purpose of checkpoints is to enable incremental backups. But for a checkpoint to be useful for this purpose, a backup must be performed at the same time as the checkpoint is created. This is done via the virDomainBackupBegin API, which also allows to create a checkpoint at the same time. Creating checkpoints with virDomainCheckpointCreateXML is generally only useful for re-creating the libvirt metadata.
- checkpointLookupByName(name: str, flags: int | None = 0) virDomainCheckpoint[source]¶
Try to lookup a domain checkpoint based on its name.
- controlInfo(flags: int | None = 0) str[source]¶
Extract details about current state of control interface to a domain.
- coreDump(to: str, flags: int | None = 0) int[source]¶
This method will dump the core of a domain on a given file for analysis. Note that for remote Xen Daemon the file path will be interpreted in the remote host. Hypervisors may require the user to manually ensure proper permissions on the file named by @to.
If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with a crashed state after the dump completes. If @flags includes VIR_DUMP_LIVE, then make the core dump while continuing to allow the guest to run; otherwise, the guest is suspended during the dump. VIR_DUMP_RESET flag forces reset of the guest after dump. The above three flags are mutually exclusive.
Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt will attempt to bypass the file system cache while creating the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing saves to NFS.
For more control over the output format, see virDomainCoreDumpWithFormat().
- coreDumpWithFormat(to: str, dumpformat: int, flags: int | None = 0) int[source]¶
This method will dump the core of a domain on a given file for analysis. Note that for remote Xen Daemon the file path will be interpreted in the remote host. Hypervisors may require the user to manually ensure proper permissions on the file named by @to.
@dumpformat controls which format the dump will have; use of VIR_DOMAIN_CORE_DUMP_FORMAT_RAW mirrors what virDomainCoreDump() will perform. Not all hypervisors are able to support all formats.
If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with a crashed state after the dump completes. If @flags includes VIR_DUMP_LIVE, then make the core dump while continuing to allow the guest to run; otherwise, the guest is suspended during the dump. VIR_DUMP_RESET flag forces reset of the guest after dump. The above three flags are mutually exclusive.
Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt will attempt to bypass the file system cache while creating the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing saves to NFS.
- create() int[source]¶
Launch a defined domain. If the call succeeds the domain moves from the defined to the running domains pools. The domain will be paused only if restoring from managed state created from a paused domain. For more control, see virDomainCreateWithFlags().
- createWithFiles(files: list[int], flags: int | None = 0) virDomain[source]¶
Launch a defined domain. If the call succeeds the domain moves from the defined to the running domains pools.
@files provides an array of file descriptors which will be made available to the ‘init’ process of the guest. The file handles exposed to the guest will be renumbered to start from 3 (ie immediately following stderr). This is only supported for guests which use container based virtualization technology.
If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain has a managed save image that requested paused state (see virDomainManagedSave()) the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume(). In all other cases, the guest domain will be running.
If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration, save-to-file, or snapshots.
If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a managed save file for this domain (created by virDomainManagedSave()), then libvirt will attempt to bypass the file system cache while restoring the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing loads from NFS.
If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save file for this domain is discarded, and the domain boots from scratch.
- createWithFlags(flags: int | None = 0) int[source]¶
Launch a defined domain. If the call succeeds the domain moves from the defined to the running domains pools.
If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain has a managed save image that requested paused state (see virDomainManagedSave()) the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume(). In all other cases, the guest domain will be running.
If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration. Hypervisors may also block save-to-file, or snapshots.
If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a managed save file for this domain (created by virDomainManagedSave()), then libvirt will attempt to bypass the file system cache while restoring the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing loads from NFS.
If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save file for this domain is discarded, and the domain boots from scratch.
If @flags includes VIR_DOMAIN_START_RESET_NVRAM, then libvirt will discard any existing NVRAM file and re-initialize NVRAM from the pristine template.
- delIOThread(iothread_id: int, flags: int | None = 0) int[source]¶
Dynamically delete an IOThread from the domain. The @iothread_id to be deleted must not have a resource associated with it and can be any of the currently valid IOThread ID’s.
Note that this call can fail if the underlying virtualization hypervisor does not support it or if reducing the number is arbitrarily limited. This function requires privileged access to the hypervisor.
@flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain and may fail if domain is not alive. If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, and will fail for transient domains. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed.
- delThrottleGroup(group: str, flags: int | None = 0) int[source]¶
Delete an throttlegroup from the domain. @group cannot be None, and the @group to be deleted must not have a throttlefilter associated with it and can be any of the current valid group.
@flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain and may fail if domain is not alive. If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, and will fail for transient domains. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed.
- destroy() int[source]¶
Destroy the domain object. The running instance is shutdown if not down already and all resources used by it are given back to the hypervisor. This does not free the associated virDomainPtr object. This function may require privileged access.
virDomainDestroy first requests that a guest terminate (e.g. SIGTERM), then waits for it to comply. After a reasonable timeout, if the guest still exists, virDomainDestroy will forcefully terminate the guest (e.g. SIGKILL) if necessary (which may produce undesirable results, for example unflushed disk cache in the guest). To avoid this possibility, it’s recommended to instead call virDomainDestroyFlags, sending the VIR_DOMAIN_DESTROY_GRACEFUL flag.
If the domain is transient and has any snapshot metadata (see virDomainSnapshotNum()), then that metadata will automatically be deleted when the domain quits.
- destroyFlags(flags: int | None = 0) int[source]¶
Destroy the domain object. The running instance is shutdown if not down already and all resources used by it are given back to the hypervisor. This does not free the associated virDomainPtr object. This function may require privileged access.
Calling this function with no @flags set (equal to zero) is equivalent to calling virDomainDestroy, and after a reasonable timeout will forcefully terminate the guest (e.g. SIGKILL) if necessary (which may produce undesirable results, for example unflushed disk cache in the guest). Including VIR_DOMAIN_DESTROY_GRACEFUL in the flags will prevent the forceful termination of the guest, and virDomainDestroyFlags will instead return an error if the guest doesn’t terminate by the end of the timeout; at that time, the management application can decide if calling again without VIR_DOMAIN_DESTROY_GRACEFUL is appropriate.
If VIR_DOMAIN_DESTROY_REMOVE_LOGS flag is set then domain specific logs will be deleted as well if there are any. Note that not all deployments are be supported. For example in case of QEMU driver this flags is noop if virtlogd is not used for handling QEMU process output.
Another alternative which may produce cleaner results for the guest’s disks is to use virDomainShutdown() instead, but that depends on guest support (some hypervisor/guest combinations may ignore the shutdown request).
- detachDevice(xml: str) int[source]¶
This is an equivalent of virDomainDetachDeviceFlags() when called with @flags parameter set to VIR_DOMAIN_AFFECT_LIVE.
See virDomainDetachDeviceFlags() for more details.
- detachDeviceAlias(alias: str, flags: int | None = 0) int[source]¶
Detach a virtual device from a domain, using the alias to specify the device. The value of @flags should be either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values from VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CURRENT, although hypervisors vary in which flags are supported.
In contrast to virDomainDetachDeviceFlags() this API is asynchronous - it returns immediately after sending the detach request to the hypervisor. It’s caller’s responsibility to wait for VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED event to signal actual device removal or for VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED to signal rejected device removal.
- detachDeviceFlags(xml: str, flags: int | None = 0) int[source]¶
Detach a virtual device from a domain, using the flags parameter to control how the device is detached. VIR_DOMAIN_AFFECT_CURRENT specifies that the device allocation is removed based on current domain state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be deallocated from the active domain instance only and is not from the persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG specifies that the device shall be deallocated from the persisted domain configuration only. Note that the target hypervisor must return an error if unable to satisfy flags. E.g. the hypervisor driver will return failure if LIVE is specified but it only supports removing the persisted device allocation.
Some hypervisors may prevent this operation if there is a current block job running operation on the device being detached; in that case, use virDomainBlockJobAbort() to stop the block job first.
Beware that depending on the hypervisor and device type, detaching a device from a running domain may be asynchronous. That is, calling virDomainDetachDeviceFlags may just request device removal while the device is actually removed later (in cooperation with a guest OS). Previously, this fact was ignored and the device could have been removed from domain configuration before it was actually removed by the hypervisor causing various failures on subsequent operations. To check whether the device was successfully removed, either recheck domain configuration using virDomainGetXMLDesc() or add a handler for the VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED event. In case the device is already gone when virDomainDetachDeviceFlags returns, the event is delivered before this API call ends. To help existing clients work better in most cases, this API will try to transform an asynchronous device removal that finishes shortly after the request into a synchronous removal. In other words, this API may wait a bit for the removal to complete in case it was not synchronous.
Be aware that hotplug changes might not persist across a domain going into S4 state (also known as hibernation) unless you also modify the persistent domain definition.
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 is not present in the domain XML, but shares some specific attributes with one that is present, may lead to unexpected results.
- emulatorPinInfo(flags: int | None = 0) str[source]¶
Query the CPU affinity setting of the emulator process of domain
- fSTrim(mountPoint: str, minimum: int, flags: int | None = 0) int[source]¶
Calls FITRIM within the guest (hence guest agent may be required depending on hypervisor used). Either call it on each mounted filesystem (@mountPoint is None) or just on specified @mountPoint. @minimum hints that free ranges smaller than this may be ignored (this is a hint and the guest may not respect it). 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. If @minimum is not zero, the command may fail.
- fsFreeze(mountpoints: list[str] | None = None, flags: int | None = 0) int[source]¶
Freeze specified filesystems within the guest
- fsInfo(flags: int | None = 0) str[source]¶
Get a list of mapping information for each mounted file systems within the specified guest and the disks.
- fsThaw(mountpoints: list[str] | None = None, flags: int | None = 0) int[source]¶
Thaw specified filesystems within the guest
- getCPUStats(total: bool, flags: int | None = 0) str[source]¶
Extracts CPU statistics for a running domain. On success it will return a list of data of dictionary type. If boolean total is False or 0, the first element of the list refers to CPU0 on the host, second element is CPU1, and so on. The format of data struct is as follows: [{cpu_time:xxx}, {cpu_time:xxx}, …] If it is True or 1, it returns total domain CPU statistics in the format of [{cpu_time:xxx, user_time:xxx, system_time:xxx}]
- graphicsReload(type: int, flags: int | None = 0) int[source]¶
Reload domain’s graphics. This can be used to reload TLS certificates without restarting the domain.
- guestInfo(types: int | None = 0, flags: int | None = 0) str[source]¶
Get aggregated info from guest agent
- guestVcpus(flags: int | None = 0) int[source]¶
returns a dictionary containing information regarding guest vcpus
- hasCurrentSnapshot(flags: int | None = 0) int[source]¶
Determine if the domain has a current snapshot.
- hasManagedSaveImage(flags: int | None = 0) int[source]¶
Check if a domain has a managed save image as created by virDomainManagedSave(). Note that any running domain should not have such an image, as it should have been removed on restart.
- hostname(flags: int | None = 0) str[source]¶
Get the hostname for that domain. If no hostname is found, then an error is raised with VIR_ERR_NO_HOSTNAME code.
Dependent on hypervisor and @flags used, this may require a guest agent to be available.
- info() str[source]¶
Extract information about a domain. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.
- interfaceAddresses(source: int, flags: int | None = 0) str[source]¶
returns a dictionary of domain interfaces along with their MAC and IP addresses
- interfaceParameters(device: str, flags: int | None = 0) str[source]¶
Get the bandwidth tunables for a interface device
- ioThreadInfo(flags: int | None = 0) str[source]¶
Query the CPU affinity setting of the IOThreads of the domain
- isPersistent() int[source]¶
Determine if the domain has a persistent configuration which means it will still exist after shutting down
- jobStats(flags: int | None = 0) str[source]¶
Extract information about an active job being processed for a domain.
- listAllCheckpoints(flags: int | None = 0) list[virDomainCheckpoint][source]¶
List all checkpoints and returns a list of checkpoint objects
- listAllSnapshots(flags: int | None = 0) list[virDomainSnapshot][source]¶
List all snapshots and returns a list of snapshot objects
- managedSave(flags: int | None = 0) int[source]¶
This method will suspend a domain and save its memory contents to a file on disk. After the call, if successful, the domain is not listed as running anymore. The difference from virDomainSave() is that libvirt is keeping track of the saved state itself, and will reuse it once the domain is being restarted (automatically or via an explicit libvirt call). As a result any running domain is sure to not have a managed saved image. This also implies that managed save only works on persistent domains, since the domain must still exist in order to use virDomainCreate() to restart it.
If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will attempt to bypass the file system cache while creating the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing saves to NFS.
Normally, the managed saved state will remember whether the domain was running or paused, and start will resume to the same state. Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in @flags will override the default saved into the file. These two flags are mutually exclusive.
- managedSaveDefineXML(dxml: str, flags: int | None = 0) int[source]¶
This updates the definition of a domain stored in a saved state file.
@dxml can be used to alter host-specific portions of the domain XML that will be used on the next start of the domain. For example, it is possible to alter the backing filename that is associated with a disk device.
Normally, the saved state file will remember whether the domain was running or paused, and restore defaults to the same state. Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in @flags will override the default saved into the file; omitting both leaves the file’s default unchanged. These two flags are mutually exclusive.
- managedSaveGetXMLDesc(flags: int | None = 0) str[source]¶
This method will extract the XML description of the managed save state file of a domain.
No security-sensitive data will be included unless @flags contains VIR_DOMAIN_SAVE_IMAGE_XML_SECURE; this flag is rejected on read-only connections.
- managedSaveRemove(flags: int | None = 0) int[source]¶
Remove any managed save image for this domain.
- maxMemory() int[source]¶
Retrieve the maximum amount of physical memory allocated to a domain. If domain is None, then this get the amount of memory reserved to Domain0 i.e. the domain where the application runs.
- maxVcpus() int[source]¶
Provides the maximum number of virtual CPUs supported for the guest VM. If the guest is inactive, this is basically the same as virConnectGetMaxVcpus(). If the guest is running this will reflect the maximum number of virtual CPUs the guest was booted with. For more details, see virDomainGetVcpusFlags().
- memoryPeek(start: int, size: int, flags: int | None = 0) str[source]¶
Read the contents of domain’s memory
- metadata(type: int, uri: str, flags: int | None = 0) str[source]¶
Retrieves the appropriate domain element given by @type. If VIR_DOMAIN_METADATA_ELEMENT is requested parameter @uri must be set to the name of the namespace the requested elements belong to, otherwise must be None.
If an element of the domain XML is not present, the resulting error will be VIR_ERR_NO_DOMAIN_METADATA. This method forms a shortcut for seeing information from virDomainSetMetadata() without having to go through virDomainGetXMLDesc().
@flags controls whether the live domain or persistent configuration will be queried.
- migrate(dconn: virConnect, flags: int | None = 0, dname: str | None = None, uri: str | None = None, bandwidth: int | None = 0) virDomain[source]¶
Migrate the domain object from its current host to the destination host given by dconn (a connection to the destination host).
This function is similar to virDomainMigrate3, but it only supports a fixed set of parameters: @dname corresponds to VIR_MIGRATE_PARAM_DEST_NAME, @uri is VIR_MIGRATE_PARAM_URI, and @bandwidth is VIR_MIGRATE_PARAM_BANDWIDTH.
virDomainFree should be used to free the resources after the returned domain object is no longer needed.
- migrate2(dconn: virConnect, dxml: str | None = None, flags: int | None = 0, dname: str | None = None, uri: str | None = None, bandwidth: int | None = 0) virDomain[source]¶
Migrate the domain object from its current host to the destination host given by dconn (a connection to the destination host).
This function is similar to virDomainMigrate3, but it only supports a fixed set of parameters: @dxml corresponds to VIR_MIGRATE_PARAM_DEST_XML, @dname is VIR_MIGRATE_PARAM_DEST_NAME, @uri is VIR_MIGRATE_PARAM_URI, and @bandwidth is VIR_MIGRATE_PARAM_BANDWIDTH.
virDomainFree should be used to free the resources after the returned domain object is no longer needed.
- migrate3(dconn: virConnect, params: str, flags: int | None = 0) virDomain[source]¶
Migrate the domain object from its current host to the destination host given by dconn (a connection to the destination host).
- migrateGetCompressionCache(flags: int | None = 0) int[source]¶
Get current size of the cache (in bytes) used for compressing repeatedly transferred memory pages during live migration.
- migrateGetMaxDowntime(flags: int | None = 0) int[source]¶
Get the current value of the maximum downtime (in milliseconds) allowed during a migration of a guest.
- migrateGetMaxSpeed(flags: int | None = 0) int[source]¶
Get currently configured maximum migration speed for a domain
- migrateSetCompressionCache(cacheSize: int, flags: int | None = 0) int[source]¶
Sets size of the cache (in bytes) used for compressing repeatedly transferred memory pages during live migration. It’s supposed to be called while the domain is being live-migrated as a reaction to migration progress and increasing number of compression cache misses obtained from virDomainGetJobStats.
- migrateSetMaxDowntime(downtime: int, flags: int | None = 0) int[source]¶
Sets maximum tolerable time for which the domain is allowed to be paused at the end of live migration. It’s supposed to be called while the domain is being live-migrated as a reaction to migration progress.
- migrateSetMaxSpeed(bandwidth: int, flags: int | None = 0) int[source]¶
The maximum bandwidth (in MiB/s) that will be used to do migration can be specified with the bandwidth parameter. Not all hypervisors will support a bandwidth cap. When VIR_DOMAIN_MIGRATE_MAX_SPEED_POSTCOPY is set in @flags, this API sets the maximum bandwidth for the post-copy phase of the migration.
- migrateStartPostCopy(flags: int | None = 0) int[source]¶
Starts post-copy migration. This function has to be called while migration (initiated with VIR_MIGRATE_POSTCOPY flag) is in progress. Traditional pre-copy migration iteratively walks through guest memory pages and migrates those that changed since the previous iteration. The iterative phase stops when the number of dirty pages is low enough so that the virtual CPUs can be paused, all dirty pages transferred to the destination, where the virtual CPUs are unpaused, and all this can happen within a predefined downtime period. It's clear that this process may never converge if downtime is too short and/or the guest keeps changing a lot of memory pages. When migration is switched to post-copy mode, the virtual CPUs are paused immediately, only a minimum set of pages is transferred, and the CPUs are unpaused on destination. The source keeps sending all remaining memory pages to the destination while the guest is already running there. Whenever the guest tries to read a memory page which has not been migrated yet, the hypervisor has to tell the source to transfer that page in a priority channel. To minimize such page faults, it is a good idea to run at least one iteration of pre-copy migration before switching to post-copy. Post-copy migration is guaranteed to converge since each page is transferred at most once no matter how fast it changes. On the other hand once the guest is running on the destination host, the migration can no longer be rolled back because none of the hosts has complete state. If this happens, libvirt will leave the domain paused on the source host with VIR_DOMAIN_PAUSED_POSTCOPY_FAILED reason. The domain on the destination host will remain running with VIR_DOMAIN_RUNNING_POSTCOPY_FAILED reason. It's up to the upper layer to decide what to do in such case. Because of this, libvirt will refuse to cancel post-copy migration via virDomainAbortJobFlags unless it is called with VIR_DOMAIN_ABORT_JOB_POSTCOPY, in which case the post-copy migration will be paused. Failed post-copy migration can be recovered once the cause for the failure (e.g., a network issue) is resolved by repeating the migration with an additional VIR_MIGRATE_POSTCOPY_RESUME flag. This will recreate the connection and resume migration from the point where it failed. This step can be repeated in case the migration breaks again. The following domain life cycle events are emitted during post-copy migration: VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY (on the source) -- migration entered post-copy mode. VIR_DOMAIN_EVENT_RESUMED_POSTCOPY (on the destination) -- the guest is running on the destination host while some of its memory pages still remain on the source host; neither the source nor the destination host contain a complete guest state from this point until migration finishes. VIR_DOMAIN_EVENT_RESUMED_MIGRATED (on the destination), VIR_DOMAIN_EVENT_STOPPED_MIGRATED (on the source) -- migration finished successfully and the destination host holds a complete guest state. VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED (on the source), VIR_DOMAIN_EVENT_RESUMED_POSTCOPY_FAILED (on the destination) -- emitted when migration fails in post-copy mode and it's unclear whether any of the hosts has a complete guest state. Virtual CPUs on the destination are still running. The progress of a post-copy migration can be monitored normally using virDomainGetJobStats on the source host. Fetching statistics of a completed post-copy migration can also be done on the source host (by calling virDomainGetJobStats or listening to VIR_DOMAIN_EVENT_ID_JOB_COMPLETED event, but (in contrast to pre-copy migration) the statistics are not available on the destination host. Thus, VIR_DOMAIN_EVENT_ID_JOB_COMPLETED event is the only way of getting statistics of a completed post-copy migration of a transient domain (because the domain is removed after migration and there's no domain to run virDomainGetJobStats on).
- migrateToURI(duri: str, flags: int | None = 0, dname: str | None = None, bandwidth: int | None = 0) int[source]¶
Migrate the domain object from its current host to the destination host given by duri.
This function is similar to virDomainMigrateToURI3, but it only supports a fixed set of parameters: @dname corresponds to VIR_MIGRATE_PARAM_DEST_NAME, and @bandwidth corresponds to VIR_MIGRATE_PARAM_BANDWIDTH.
The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
If the VIR_MIGRATE_PEER2PEER flag IS set, the @duri parameter must be a valid libvirt connection URI, by which the source libvirt driver can connect to the destination libvirt. In other words, @duri corresponds to @dconnuri of virDomainMigrateToURI3.
If the VIR_MIGRATE_PEER2PEER flag is NOT set, the @duri parameter takes a hypervisor specific URI used to initiate the migration. In this case @duri corresponds to VIR_MIGRATE_PARAM_URI of virDomainMigrateToURI3.
- migrateToURI2(dconnuri: str | None = None, miguri: str | None = None, dxml: str | None = None, flags: int | None = 0, dname: str | None = None, bandwidth: int | None = 0) int[source]¶
Migrate the domain object from its current host to the destination host given by @dconnuri.
This function is similar to virDomainMigrateToURI3, but it only supports a fixed set of parameters: @miguri corresponds to VIR_MIGRATE_PARAM_URI, @dxml is VIR_MIGRATE_PARAM_DEST_XML, @dname is VIR_MIGRATE_PARAM_DEST_NAME, and @bandwidth corresponds to VIR_MIGRATE_PARAM_BANDWIDTH.
The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
If the VIR_MIGRATE_PEER2PEER flag IS set, the @dconnuri parameter must be a valid libvirt connection URI, by which the source libvirt driver can connect to the destination libvirt. In other words, @dconnuri has the same semantics as in virDomainMigrateToURI3.
If the VIR_MIGRATE_PEER2PEER flag is NOT set, the @dconnuri must be None and the @miguri parameter takes a hypervisor specific URI used to initiate the migration. In this case @miguri corresponds to VIR_MIGRATE_PARAM_URI of virDomainMigrateToURI3.
- migrateToURI3(dconnuri: str, params: str, flags: int | None = 0) int[source]¶
Migrate the domain object from its current host to the destination host given by URI.
- openChannel(name: str, st: virStream, flags: int | None = 0) int[source]¶
This opens the host interface associated with a channel device on a guest, if the host interface is supported. If @name is given, it can match either the device alias (e.g. “channel0”), or the virtio target name (e.g. “org.qemu.guest_agent.0”). If @name is omitted, then the first channel is opened. The channel is associated with the passed in @st stream, which should have been opened in non-blocking mode for bi-directional I/O.
By default, when @flags is 0, the open will fail if libvirt detects that the channel is already in use by another client; passing VIR_DOMAIN_CHANNEL_FORCE will cause libvirt to forcefully remove the other client prior to opening this channel.
- openConsole(dev_name: str, st: virStream, flags: int | None = 0) int[source]¶
This opens the backend associated with a console, serial or parallel port device on a guest, if the backend is supported. If the @dev_name is omitted, then the first console or serial device is opened. The console is associated with the passed in @st stream, which should have been opened in non-blocking mode for bi-directional I/O.
By default, when @flags is 0, the open will fail if libvirt detects that the console is already in use by another client; passing VIR_DOMAIN_CONSOLE_FORCE will cause libvirt to forcefully remove the other client prior to opening this console.
If flag VIR_DOMAIN_CONSOLE_SAFE the console is opened only in the case where the hypervisor driver supports safe (mutually exclusive) console handling.
Older servers did not support either flag, and also did not forbid simultaneous clients on a console, with potentially confusing results. When passing @flags of 0 in order to support a wider range of server versions, it is up to the client to ensure mutual exclusion.
- openGraphics(idx: int, fd: int, flags: int | None = 0) int[source]¶
This will attempt to connect the file descriptor @fd, to the graphics backend of @dom. If @dom has multiple graphics backends configured, then @idx will determine which one is opened, starting from @idx 0.
To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH constant for @flags.
The caller should use an anonymous socketpair to open @fd before invocation.
This method can only be used when connected to a local libvirt hypervisor, over a UNIX domain socket. Attempts to use this method over a TCP connection will always fail
- openGraphicsFD(idx: int, flags: int | None = 0) int[source]¶
This will create a socket pair connected to the graphics backend of @dom. One end of the socket will be returned on success, and the other end is handed to the hypervisor. If @dom has multiple graphics backends configured, then @idx will determine which one is opened, starting from @idx 0.
To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH constant for @flags.
This method can only be used when connected to a local libvirt hypervisor, over a UNIX domain socket. Attempts to use this method over a TCP connection will always fail.
- pMSuspendForDuration(target: int, duration: int, flags: int | None = 0) int[source]¶
Attempt to have the guest enter the given @target power management suspension level. If @duration is non-zero, also schedule the guest to resume normal operation after that many seconds, if nothing else has resumed it earlier. Some hypervisors require that @duration be 0, for an indefinite suspension.
Dependent on hypervisor used, this may require a guest agent to be available, e.g. QEMU.
Beware that at least for QEMU, the domain’s process will be terminated when VIR_NODE_SUSPEND_TARGET_DISK is used and a new process will be launched when libvirt is asked to wake up the domain. As a result of this, any runtime changes, such as device hotplug or memory settings, are lost unless such changes were made with VIR_DOMAIN_AFFECT_CONFIG flag.
- pMWakeup(flags: int | None = 0) int[source]¶
Inject a wakeup into the guest that previously used virDomainPMSuspendForDuration, rather than waiting for the previously requested duration (if any) to elapse.
- pinEmulator(cpumap: bytes, flags: int | None = 0) int[source]¶
Dynamically change the real CPUs which can be allocated to the emulator process of a domain. This function requires privileged access to the hypervisor.
- pinIOThread(iothread_val: int, cpumap: bytes, flags: int | None = 0) int[source]¶
Dynamically change the real CPUs which can be allocated to an IOThread. This function requires privileged access to the hypervisor.
- pinVcpu(vcpu: int, cpumap: bytes) int[source]¶
Dynamically change the real CPUs which can be allocated to a virtual CPU. This function requires privileged access to the hypervisor.
- pinVcpuFlags(vcpu: int, cpumap: bytes, flags: int | None = 0) int[source]¶
Dynamically change the real CPUs which can be allocated to a virtual CPU. This function requires privileged access to the hypervisor.
- reboot(flags: int | None = 0) int[source]¶
Reboot a domain, the domain object is still usable thereafter, but the domain OS is being stopped for a restart. Note that the guest OS may ignore the request. Additionally, the hypervisor may check and support the domain ‘on_reboot’ XML setting resulting in a domain that shuts down instead of rebooting.
If @flags is set to zero, then the hypervisor will choose the method of shutdown it considers best. To have greater control pass one or more of the virDomainRebootFlagValues. The order in which the hypervisor tries each shutdown method is undefined, and a hypervisor is not required to support all methods.
To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML must have <channel> configured.
Due to implementation limitations in some drivers (the qemu driver, for instance) it is not advised to migrate or save a guest that is rebooting as a result of this API. Migrating such a guest can lead to a plain shutdown on the destination.
- rename(new_name: str, flags: int | None = 0) int[source]¶
Rename a domain. New domain name is specified in the second argument. Depending on each driver implementation it may be required that domain is in a specific state.
There might be some attributes and/or elements in domain XML that if no value provided at XML defining time, libvirt will derive their value from the domain name. These are not updated by this API. Users are strongly advised to change these after the rename was successful.
- reset(flags: int | None = 0) int[source]¶
Reset a domain immediately without any guest OS shutdown. Reset emulates the power reset button on a machine, where all hardware sees the RST line set and reinitializes internal state.
Note that there is a risk of data loss caused by reset without any guest OS shutdown.
- resume() int[source]¶
Resume a suspended domain, the process is restarted from the state where it was frozen by calling virDomainSuspend(). This function may require privileged access Moreover, resume may not be supported if domain is in some special state like VIR_DOMAIN_PMSUSPENDED.
- revertToSnapshot(snap: virDomainSnapshot, flags: int | None = 0) int[source]¶
revert the domain to the given snapshot
- save(to: str) int[source]¶
This method will suspend a domain and save its memory contents to a file or direcotry (based on the vmm) on disk. After the call, if successful,the domain is not listed as running anymore (this ends the life of a transient domain). Use virDomainRestore() to restore a domain after saving.
See virDomainSaveFlags() and virDomainSaveParams() for more control. Also, a save file can be inspected or modified slightly with virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML().
- saveFlags(to: str, dxml: str | None = None, flags: int | None = 0) int[source]¶
This method will suspend a domain and save its memory contents to a file on disk. After the call, if successful, the domain is not listed as running anymore (this ends the life of a transient domain). Use virDomainRestore() to restore a domain after saving.
If the hypervisor supports it, @dxml can be used to alter host-specific portions of the domain XML that will be used when restoring an image. For example, it is possible to alter the backing filename that is associated with a disk device, in order to prepare for file renaming done as part of backing up the disk device while the domain is stopped.
If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will attempt to bypass the file system cache while creating the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing saves to NFS.
Normally, the saved state file will remember whether the domain was running or paused, and restore defaults to the same state. Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in @flags will override what state gets saved into the file. These two flags are mutually exclusive.
A save file can be inspected or modified slightly with virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML().
Some hypervisors may prevent this operation if there is a current block job running; in that case, use virDomainBlockJobAbort() to stop the block job first.
- saveParams(params: dict[str, Any], flags: int | None = 0) int[source]¶
This method will suspend a domain and save its memory contents to a file on disk.
- schedulerParameters() str[source]¶
Get the scheduler parameters, the @params array will be filled with the values.
- screenshot(stream: virStream, screen: int, flags: int | None = 0) str[source]¶
Take a screenshot of current domain console as a stream. The image format is hypervisor specific. Moreover, some hypervisors supports multiple displays per domain. These can be distinguished by @screen argument.
This call sets up a stream; subsequent use of stream API is necessary to transfer actual data, determine how much data is successfully transferred, and detect any errors.
The screen ID is the sequential number of screen. In case of multiple graphics cards, heads are enumerated before devices, e.g. having two graphics cards, both with four heads, screen ID 5 addresses the second head on the second card.
- securityLabel() str[source]¶
Extract information about the domain security label. Only the first label will be returned.
- securityLabelList() str[source]¶
Extract information about the domain security label. A list of all labels will be returned.
- sendKey(codeset: int, holdtime: int, keycodes: list[int], nkeycodes: int, flags: int | None = 0) int[source]¶
Send key(s) to the guest.
- sendProcessSignal(pid_value: int, signum: int, flags: int | None = 0) int[source]¶
Send a signal to the designated process in the guest
The signal numbers must be taken from the virDomainProcessSignal enum. These will be translated to the corresponding signal number for the guest OS, by the guest agent delivering the signal. If there is no mapping from virDomainProcessSignal to the native OS signals, this API will report an error.
If @pid_value is an integer greater than zero, it is treated as a process ID. If @pid_value is an integer less than zero, it is treated as a process group ID. All the @pid_value numbers are from the container/guest namespace. The value zero is not valid.
Not all hypervisors will support sending signals to arbitrary processes or process groups. If this API is implemented the minimum requirement is to be able to use @pid_value == 1 (i.e. kill init). No other value is required to be supported.
If the @signum is VIR_DOMAIN_PROCESS_SIGNAL_NOP then this API will simply report whether the process is running in the container/guest.
- setAutostart(autostart: int) int[source]¶
Configure the domain to be automatically started each time when the host machine boots.
- setAutostartOnce(autostart: int) int[source]¶
Configure the domain to be automatically started the next when the host machine boots.
Note that autostart configured via the virDomain[Set|Get]AutostartOnce APIs is independent from the autostart configured via virDomain[Set|Get]Autostart. Enabling either of them will cause the VM to be started on the next boot.
- setBlkioParameters(params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the blkio tunables
- setBlockIoTune(disk: str, params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the I/O tunables for a block device
- setBlockThreshold(dev: str, threshold: int, flags: int | None = 0) int[source]¶
Set the threshold level for delivering the VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD if the device or backing chain element described by @dev is written beyond the set threshold level. The threshold level is unset once the event fires. The event might not be delivered at all if libvirtd was not running at the moment when the threshold was reached. Note that if the threshold level is reached for a top level image, the event is emitted for @dev corresponding to the disk target, and may also be reported with @dev corresponding to the disk target with an index corresponding to the ‘index’ attribute of ‘source’ in the live VM XML if the attribute is present.
@dev can either be a disk target name (vda, sda) or disk target with index ( vda[4]). Without the index the top image in the backing chain will have the threshold set. The index corresponds to the ‘index’ attribute reported in the live VM XML for ‘backingStore’ or ‘source’ elements of a disk. If index is given the threshold is set for the corresponding image.
In case when @dev does not contain index the VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD event may be emitted twice, once for the disk device target without index and once containing the index.
Note that the threshold event can be registered also for destinations of a ‘virDomainBlockCopy’ destination by using the ‘index’ of the ‘mirror’ source.
Hypervisors report the last written sector of an image in the bulk stats API (virConnectGetAllDomainStats/virDomainListGetStats) as “block.<num>.allocation” in the VIR_DOMAIN_STATS_BLOCK group. The current threshold value is reported as “block.<num>.threshold”.
This event allows to use thin-provisioned storage which needs management tools to grow it without the need for polling of the data.
- setGuestVcpus(cpumap: str, state: int, flags: int | None = 0) int[source]¶
Sets state of individual vcpus described by @cpumap via guest agent. Other vcpus are not modified.
This API requires the VM to run. Various hypervisors or guest agent implementation may limit to operate on just 1 vCPU per call.
@cpumap is a list of vCPU numbers. Its syntax is a comma separated list and a special markup using ‘-’ and ‘^’ (ex. ‘0-4’, ‘0-3,^2’). The ‘-’ denotes the range and the ‘^’ denotes exclusive. The expression is sequentially evaluated, so “0-15,^8” is identical to “9-14,0-7,15” but not identical to “^8,0-15”.
Note that OSes (notably Linux) may require vCPU 0 to stay online to support low-level features a S3 sleep.
- setIOThreadParams(iothread_val: int, params: dict[str, Any], flags: int | None = 0) int[source]¶
Dynamically allow changing the IOThread polling related parameters. This function requires privileged access to the hypervisor.
- setInterfaceParameters(device: str, params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the bandwidth tunables for a interface device
- setLaunchSecurityState(params: dict[str, Any], flags: int | None = 0) int[source]¶
Set a launch security secret in the guest’s memory.
- setLifecycleAction(type: int, action: int, flags: int | None = 0) int[source]¶
Changes the actions of lifecycle events for domain represented as <on_$type>$action</on_$type> in the domain XML.
QEMU driver has a limitation that if all lifecycle events are set to destroy when the domain is started, it’s not possible to change any action for running domain.
- setMaxMemory(memory: int) int[source]¶
Dynamically change the maximum amount of physical memory allocated to a domain. If domain is None, then this change the amount of memory reserved to Domain0 i.e. the domain where the application runs. This function may require privileged access to the hypervisor.
This command is hypervisor-specific for whether active, persistent, or both configurations are changed; for more control, use virDomainSetMemoryFlags().
- setMemory(memory: int) int[source]¶
Dynamically change the target amount of physical memory allocated to a domain. If domain is None, then this change the amount of memory reserved to Domain0 i.e. the domain where the application runs. This function may require privileged access to the hypervisor.
This command is hypervisor-specific for whether active, persistent, or both configurations are changed; for more control, use virDomainSetMemoryFlags().
- setMemoryFlags(memory: int, flags: int | None = 0) int[source]¶
Dynamically change the target amount of physical memory allocated to a domain. If domain is None, then this change the amount of memory reserved to Domain0 i.e. the domain where the application runs. This function may require privileged access to the hypervisor.
@flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain and will fail if domain is not active. If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, and will fail for transient domains. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed. If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain’s maximum memory size rather than current memory size. Not all hypervisors can support all flag combinations.
- setMemoryParameters(params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the memory tunables
- setMemoryStatsPeriod(period: int, flags: int | None = 0) int[source]¶
Dynamically change the domain memory balloon driver statistics collection period. Use 0 to disable and a positive value to enable.
@flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain and will fail if domain is not active. If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, and will fail for transient domains. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed.
Not all hypervisors can support all flag combinations.
- setMetadata(type: int, metadata: str, key: str, uri: str, flags: int | None = 0) int[source]¶
Sets the appropriate domain element given by @type to the value of @metadata. A @type of VIR_DOMAIN_METADATA_DESCRIPTION is free-form text; VIR_DOMAIN_METADATA_TITLE is free-form, but no newlines are permitted, and should be short (although the length is not enforced). For these two options @key and @uri are irrelevant and must be set to None.
For type VIR_DOMAIN_METADATA_ELEMENT @metadata must be well-formed XML belonging to namespace defined by @uri with local name @key.
Passing None for @metadata says to remove that element from the domain XML (passing the empty string leaves the element present).
The resulting metadata will be present in virDomainGetXMLDesc(), as well as quick access through virDomainGetMetadata().
@flags controls whether the live domain, persistent configuration, or both will be modified.
- setNumaParameters(params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the NUMA tunables
- setPerfEvents(params: dict[str, Any], flags: int | None = 0) int[source]¶
Enable or disable the particular list of perf events
- setSchedulerParametersFlags(params: dict[str, Any], flags: int | None = 0) int[source]¶
Change the scheduler parameters
- setThrottleGroup(group: str, params: dict[str, Any], flags: int | None = 0) int[source]¶
Add throttlegroup or change all of the throttlegroup options within specific domain.
- setTime(time: int | None = None, flags: int | None = 0) int[source]¶
Set guest time to the given value. @time is a dict containing ‘seconds’ field for seconds and ‘nseconds’ field for nanoseconds
- setUserPassword(user: str, password: str, flags: int | None = 0) int[source]¶
Sets the @user password to the value specified by @password. If @flags contain VIR_DOMAIN_PASSWORD_ENCRYPTED, the password is assumed to be encrypted by the method required by the guest OS.
Please note that some hypervisors may require guest agent to be configured and running in order to be able to run this API.
- setVcpu(vcpumap: str, state: int, flags: int | None = 0) int[source]¶
Enables/disables individual vcpus described by @vcpumap in the hypervisor.
Various hypervisor implementations may limit to operate on just 1 hotpluggable entity (which may contain multiple vCPUs on certain platforms).
Note that OSes and hypervisors may require vCPU 0 to stay online.
- setVcpus(nvcpus: int) int[source]¶
Dynamically change the number of virtual CPUs used by the domain. Note that this call may fail if the underlying virtualization hypervisor does not support it or if growing the number is arbitrarily limited. This function may require privileged access to the hypervisor.
Note that if this call is executed before the guest has finished booting, the guest may fail to process the change.
This command only changes the runtime configuration of the domain, so can only be called on an active domain. It is hypervisor-dependent whether it also affects persistent configuration; for more control, use virDomainSetVcpusFlags().
- setVcpusFlags(nvcpus: int, flags: int | None = 0) int[source]¶
Dynamically change the number of virtual CPUs used by the domain. Note that this call may fail if the underlying virtualization hypervisor does not support it or if growing the number is arbitrarily limited. This function may require privileged access to the hypervisor.
@flags may include VIR_DOMAIN_AFFECT_LIVE to affect a running domain (which may fail if domain is not active), or VIR_DOMAIN_AFFECT_CONFIG to affect the next boot via the XML description of the domain. Both flags may be set. If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies persistent setup, while an active domain is hypervisor-dependent on whether just live or both live and persistent state is changed.
Note that if this call is executed before the guest has finished booting, the guest may fail to process the change.
If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then VIR_DOMAIN_AFFECT_LIVE must be clear, and only the maximum virtual CPU limit is altered; generally, this value must be less than or equal to virConnectGetMaxVcpus(). Otherwise, this call affects the current virtual CPU limit, which must be less than or equal to the maximum limit. Note that hypervisors may not allow changing the maximum vcpu count if processor topology is specified.
If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of processors is modified inside the guest instead of the hypervisor. This flag can only be used with live guests and is incompatible with VIR_DOMAIN_VCPU_MAXIMUM. The usage of this flag may require a guest agent configured.
Not all hypervisors can support all flag combinations.
- shutdown() int[source]¶
Shutdown a domain, the domain object is still usable thereafter, but the domain OS is being stopped. Note that the guest OS may ignore the request. Additionally, the hypervisor may check and support the domain ‘on_poweroff’ XML setting resulting in a domain that reboots instead of shutting down. For guests that react to a shutdown request, the differences from virDomainDestroy() are that the guests disk storage will be in a stable state rather than having the (virtual) power cord pulled, and this command returns as soon as the shutdown request is issued rather than blocking until the guest is no longer running.
If the domain is transient and has any snapshot metadata (see virDomainSnapshotNum()), then that metadata will automatically be deleted when the domain quits.
- shutdownFlags(flags: int | None = 0) int[source]¶
Shutdown a domain, the domain object is still usable thereafter but the domain OS is being stopped. Note that the guest OS may ignore the request. Additionally, the hypervisor may check and support the domain ‘on_poweroff’ XML setting resulting in a domain that reboots instead of shutting down. For guests that react to a shutdown request, the differences from virDomainDestroy() are that the guest’s disk storage will be in a stable state rather than having the (virtual) power cord pulled, and this command returns as soon as the shutdown request is issued rather than blocking until the guest is no longer running.
If the domain is transient and has any snapshot metadata (see virDomainSnapshotNum()), then that metadata will automatically be deleted when the domain quits.
If @flags is set to zero, then the hypervisor will choose the method of shutdown it considers best. To have greater control pass one or more of the virDomainShutdownFlagValues. The order in which the hypervisor tries each shutdown method is undefined, and a hypervisor is not required to support all methods.
To use guest agent (VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) the domain XML must have <channel> configured.
- snapshotCreateXML(xmlDesc: str, flags: int | None = 0) virDomainSnapshot[source]¶
Creates a new snapshot of a domain based on the snapshot xml contained in xmlDesc, with a top-level element <domainsnapshot>.
If @flags is 0, the domain can be active, in which case the snapshot will be a full system snapshot (capturing both disk state, and runtime VM state such as RAM contents), where reverting to the snapshot is the same as resuming from hibernation (TCP connections may have timed out, but everything else picks up where it left off); or the domain can be inactive, in which case the snapshot includes just the disk state prior to booting. The newly created snapshot becomes current (see virDomainSnapshotCurrent()), and is a child of any previous current snapshot.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_VALIDATE, then @xmlDesc is validated against the <domainsnapshot> XML schema.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE, then this is a request to reinstate snapshot metadata that was previously captured from virDomainSnapshotGetXMLDesc() before removing that metadata, rather than creating a new snapshot. This can be used to recreate a snapshot hierarchy on a destination, then remove it on the source, in order to allow migration (since migration normally fails if snapshot metadata still remains on the source machine). Note that while original creation can omit a number of elements from @xmlDesc (and libvirt will supply sane defaults based on the domain state at that point in time), a redefinition must supply more elements (as the domain may have changed in the meantime, so that libvirt no longer has a way to resupply correct defaults). When redefining snapshot metadata, the domain’s current snapshot will not be altered unless the VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT flag is also present. It is an error to request the VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT flag without VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE. On some hypervisors, redefining an existing snapshot can be used to alter host-specific portions of the domain XML to be used during revert (such as backing filenames associated with disk devices), but must not alter guest-visible layout. When redefining a snapshot name that does not exist, the hypervisor may validate that reverting to the snapshot appears to be possible (for example, disk images have snapshot contents by the requested name). Not all hypervisors support these flags.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, then the domain’s disk images are modified according to @xmlDesc, but libvirt does not track any metadata (similar to immediately calling virDomainSnapshotDelete() with VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY). This flag is incompatible with VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_HALT, then the domain will be inactive after the snapshot completes, regardless of whether it was active before; otherwise, a running domain will still be running after the snapshot. This flag is invalid on transient domains, and is incompatible with VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_LIVE, then the domain is not paused while creating the snapshot. This increases the size of the memory dump file, but reduces downtime of the guest while taking the snapshot. Some hypervisors only support this flag during external snapshots.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, then the snapshot will be limited to the disks described in @xmlDesc, and no VM state will be saved. For an active guest, the disk image may be inconsistent (as if power had been pulled), and specifying this with the VIR_DOMAIN_SNAPSHOT_CREATE_HALT flag risks data loss.
If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE, then the libvirt will attempt to use guest agent to freeze and thaw all file systems in use within domain OS. However, if the guest agent is not present, an error is thrown. Moreover, this flag requires VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY to be passed as well. For better control and error recovery users should invoke virDomainFSFreeze manually before taking the snapshot and then virDomainFSThaw to restore the VM rather than using VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE.
By default, if the snapshot involves external files, and any of the destination files already exist as a non-empty regular file, the snapshot is rejected to avoid losing contents of those files. However, if @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT, then the destination files must be pre-created manually with the correct image format and metadata including backing store path (this allows a management app to pre-create files with relative backing file names, rather than the default of creating with absolute backing file names). Note that only the file specified in the snapshot XML is inserted as a snapshot thus setting incorrect metadata in the pre-created image may lead to the VM being unable to start or other block jobs may fail.
Be aware that although libvirt prefers to report errors up front with no other effect, some hypervisors have certain types of failures where the overall command can easily fail even though the guest configuration was partially altered (for example, if a disk snapshot request for two disks fails on the second disk, but the first disk alteration cannot be rolled back). If this API call fails, it is therefore normally necessary to follow up with virDomainGetXMLDesc() and check each disk to determine if any partial changes occurred. However, if @flags contains VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC, then libvirt guarantees that this command will not alter any disks unless the entire set of changes can be done atomically, making failure recovery simpler (note that it is still possible to fail after disks have changed, but only in the much rarer cases of running out of memory or disk space).
Some hypervisors may prevent this operation if there is a current block copy operation; in that case, use virDomainBlockJobAbort() to stop the block copy first.
virDomainSnapshotFree should be used to free the resources after the snapshot object is no longer needed.
- snapshotCurrent(flags: int | None = 0) virDomainSnapshot[source]¶
Get the current snapshot for a domain, if any.
virDomainSnapshotFree should be used to free the resources after the snapshot object is no longer needed.
- snapshotListNames(flags: int | None = 0) str[source]¶
collect the list of snapshot names for the given domain
- snapshotLookupByName(name: str, flags: int | None = 0) virDomainSnapshot[source]¶
Try to lookup a domain snapshot based on its name.
- snapshotNum(flags: int | None = 0) int[source]¶
Provides the number of domain snapshots for this domain.
This function will accept VIR_DOMAIN_SNAPSHOT_LIST_TOPOLOGICAL in @flags only if virDomainSnapshotListNames() can honor it, although the flag has no other effect here.
By default, this command covers all snapshots. It is also possible to limit things to just snapshots with no parents, when @flags includes VIR_DOMAIN_SNAPSHOT_LIST_ROOTS. Additional filters are provided via the same @flags values as documented in virDomainListAllSnapshots().
- startDirtyRateCalc(seconds: int, flags: int | None = 0) int[source]¶
Calculate the current domain’s memory dirty rate in next @seconds. The calculated dirty rate information is available by calling virConnectGetAllDomainStats.
- suspend() int[source]¶
Suspends an active domain, the process is frozen without further access to CPU resources and I/O but the memory used by the domain at the hypervisor level will stay allocated. Use virDomainResume() to reactivate the domain. This function may require privileged access. Moreover, suspend may not be supported if domain is in some special state like VIR_DOMAIN_PMSUSPENDED.
- undefine() int[source]¶
Undefine a domain. If the domain is running, it’s converted to transient domain, without stopping it. If the domain is inactive, the domain configuration is removed.
If the domain has a managed save image (see virDomainHasManagedSaveImage()), or if it is inactive and has any snapshot metadata (see virDomainSnapshotNum()) or checkpoint metadata (see virDomainListAllCheckpoints()), then the undefine will fail. See virDomainUndefineFlags() for more control.
- undefineFlags(flags: int | None = 0) int[source]¶
Undefine a domain. If the domain is running, it’s converted to transient domain, without stopping it. If the domain is inactive, the domain configuration is removed.
If the domain has a managed save image (see virDomainHasManagedSaveImage()), then including VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in @flags will also remove that file, and omitting the flag will cause the undefine process to fail.
If the domain is inactive and has any snapshot metadata (see virDomainSnapshotNum()), then including VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA in @flags will also remove that metadata. Omitting the flag will cause the undefine of an inactive domain with snapshots to fail. Active domains will retain snapshot metadata until the (now-transient) domain halts, regardless of whether this flag is present. On hypervisors that support snapshots, but where snapshots do not use libvirt metadata, this flag has no effect.
If the domain is inactive and has any checkpoint metadata (see virDomainListAllCheckpoints()), then including VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA in @flags will also remove that metadata. Omitting the flag will cause the undefine of an inactive domain with checkpoints to fail. Active domains will retain checkpoint metadata until the (now-transient) domain halts, regardless of whether this flag is present. On hypervisors that support checkpoints, but where checkpoints do not use libvirt metadata, this flag has no effect.
If the domain has any nvram specified, the undefine process will fail unless VIR_DOMAIN_UNDEFINE_KEEP_NVRAM is specified, or if VIR_DOMAIN_UNDEFINE_NVRAM is specified to remove the nvram file.
- updateDeviceFlags(xml: str, flags: int | None = 0) int[source]¶
Change a virtual device on a domain, using the flags parameter to control how the device is changed. VIR_DOMAIN_AFFECT_CURRENT specifies that the device change is made based on current domain state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be changed on the active domain instance only and is not added to the persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG specifies that the device shall be changed on the persisted domain configuration only. Note that the target hypervisor must return an error if unable to satisfy flags. E.g. the hypervisor driver will return failure if LIVE is specified but it only supports modifying the persisted device allocation.
This method is used for actions such changing CDROM/Floppy device media, altering the graphics configuration such as password, reconfiguring the NIC device backend connectivity, etc.
The supplied XML description of the device should contain all the information that is found in the corresponding domain XML. Leaving out any piece of information may be treated as a request for its removal, which may be denied. For instance, when users want to change CDROM media only for live XML, they must provide live disk XML as found in the corresponding live domain XML with only the disk path changed.
- vcpuPinInfo(flags: int | None = 0) str[source]¶
Query the CPU affinity setting of all virtual CPUs of domain
- vcpus() str[source]¶
Extract information about virtual CPUs of domain, store it in info array and also in cpumaps.
- vcpusFlags(flags: int | None = 0) int[source]¶
Query the number of virtual CPUs used by the domain. Note that this call may fail if the underlying virtualization hypervisor does not support it. This function may require privileged access to the hypervisor.
If @flags includes VIR_DOMAIN_AFFECT_LIVE, this will query a running domain (which will fail if domain is not active); if it includes VIR_DOMAIN_AFFECT_CONFIG, this will query the XML description of the domain. It is an error to set both flags. If neither flag is set (that is, VIR_DOMAIN_AFFECT_CURRENT), then the configuration queried depends on whether the domain is currently running.
If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then the maximum virtual CPU limit is queried. Otherwise, this call queries the current virtual CPU count.
If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of the processors is queried in the guest instead of the hypervisor. This flag is only usable on live domains. Guest agent may be needed for this flag to be available.
- class libvirt.virDomainCheckpoint(dom: virDomain, _obj: object | None = None)[source]¶
Bases:
object- delete(flags: int | None = 0) int[source]¶
Removes a checkpoint from the domain.
When removing a checkpoint, the record of which portions of the disk were dirtied after the checkpoint will be merged into the record tracked by the parent checkpoint, if any.
If @flags includes VIR_DOMAIN_CHECKPOINT_DELETE_CHILDREN, then any descendant checkpoints are also deleted. If @flags includes VIR_DOMAIN_CHECKPOINT_DELETE_CHILDREN_ONLY, then any descendant checkepoints are deleted, but this checkpoint remains. These two flags are mutually exclusive.
If @flags includes VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY, then any checkpoint metadata tracked by libvirt is removed while keeping the checkpoint contents intact; if a hypervisor does not require any libvirt metadata to track checkpoints, then this flag is silently ignored.
- getConnect() virConnect[source]¶
Get the connection that owns the domain that a checkpoint was created for
- getParent(flags: int | None = 0) virDomainCheckpoint[source]¶
Get the parent checkpoint for @checkpoint, if any.
virDomainCheckpointFree should be used to free the resources after the checkpoint object is no longer needed.
- getXMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the domain checkpoint.
No security-sensitive data will be included unless @flags contains VIR_DOMAIN_CHECKPOINT_XML_SECURE; this flag is rejected on read-only connections.
Normally, the XML description includes an element giving a full description of the domain at the time the checkpoint was created; to reduce parsing time, it will be suppressed when @flags contains VIR_DOMAIN_CHECKPOINT_XML_NO_DOMAIN.
By default, the XML description contains only static information that does not change over time. However, when @flags contains VIR_DOMAIN_CHECKPOINT_XML_SIZE, each <disk> listing adds an additional attribute that shows an estimate of the current size in bytes that have been dirtied between the time the checkpoint was created and the current point in time. Note that updating the size may be expensive and data will be inaccurate once guest OS writes to the disk. Also note that hypervisors may require that the domain associated with @checkpoint is running when VIR_DOMAIN_CHECKPOINT_XML_SIZE is used.
- listAllChildren(flags: int | None = 0) list[virDomainCheckpoint][source]¶
List all child checkpoints and returns a list of checkpoint objects
- class libvirt.virDomainSnapshot(dom: virDomain, _obj: object | None = None)[source]¶
Bases:
object- delete(flags: int | None = 0) int[source]¶
Delete the snapshot.
If @flags is 0, then just this snapshot is deleted, and changes from this snapshot are automatically merged into children snapshots. If @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, then this snapshot and any descendant snapshots are deleted. If @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, then any descendant snapshots are deleted, but this snapshot remains. These two flags are mutually exclusive.
If @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, then any snapshot metadata tracked by libvirt is removed while keeping the snapshot contents intact; if a hypervisor does not require any libvirt metadata to track snapshots, then this flag is silently ignored.
Since libvirt 9.0.0 deletion of external snapshots is supported for QEMU driver. Using @flags VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN and VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY is not supported with external snapshots. In case that daemon process is terminated while the snapshot delete is in process the operation will be aborted when the daemon starts again.
- getConnect() virConnect[source]¶
Get the connection that owns the domain that a snapshot was created for
- getParent(flags: int | None = 0) virDomainSnapshot[source]¶
Get the parent snapshot for @snapshot, if any.
virDomainSnapshotFree should be used to free the resources after the snapshot object is no longer needed.
- getXMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the domain snapshot, with a top-level element of <domainsnapshot>.
No security-sensitive data will be included unless @flags contains VIR_DOMAIN_SNAPSHOT_XML_SECURE; this flag is rejected on read-only connections.
- hasMetadata(flags: int | None = 0) int[source]¶
Determine if the given snapshot is associated with libvirt metadata that would prevent the deletion of the domain.
- isCurrent(flags: int | None = 0) int[source]¶
Determine if the given snapshot is the domain’s current snapshot. See also virDomainHasCurrentSnapshot().
- listAllChildren(flags: int | None = 0) list[virDomainSnapshot][source]¶
List all child snapshots and returns a list of snapshot objects
- listChildrenNames(flags: int | None = 0) str[source]¶
collect the list of child snapshot names for the given snapshot
- numChildren(flags: int | None = 0) int[source]¶
Provides the number of child snapshots for this domain snapshot.
This function will accept VIR_DOMAIN_SNAPSHOT_LIST_TOPOLOGICAL in @flags only if virDomainSnapshotListChildrenNames() can honor it, although the flag has no other effect here.
By default, this command covers only direct children. It is also possible to expand things to cover all descendants, when @flags includes VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS. Additional filters are provided via the same @flags values as documented in virDomainSnapshotListAllChildren().
- class libvirt.virInterface(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- MACString() str[source]¶
Get the MAC for an interface as string. For more information about MAC see RFC4122.
- XMLDesc(flags: int | None = 0) str[source]¶
VIR_INTERFACE_XML_INACTIVE - return the static configuration, suitable for use redefining the interface via virInterfaceDefineXML() Provide an XML description of the interface. If VIR_INTERFACE_XML_INACTIVE is set, the description may be reused later to redefine the interface with virInterfaceDefineXML(). If it is not set, the ip address and netmask will be the current live setting of the interface, not the settings from the config files.
- create(flags: int | None = 0) int[source]¶
Activate an interface (i.e. call “ifup”).
If there was an open network config transaction at the time this interface was defined (that is, if virInterfaceChangeBegin() had been called), the interface will be brought back down (and then undefined) if virInterfaceChangeRollback() is called.
- destroy(flags: int | None = 0) int[source]¶
deactivate an interface (ie call “ifdown”) This does not remove the interface from the config, and does not free the associated virInterfacePtr object.
If there is an open network config transaction at the time this interface is destroyed (that is, if virInterfaceChangeBegin() had been called), and if the interface is later undefined and then virInterfaceChangeRollback() is called, the restoral of the interface definition will also bring the interface back up.
- undefine() int[source]¶
Undefine an interface, ie remove it from the config. This does not free the associated virInterfacePtr object.
Normally this change in the interface configuration is permanent/persistent, but if virInterfaceChangeBegin() has been previously called (i.e. if an interface config transaction is open), the removal of the interface definition will only become permanent if virInterfaceChangeCommit() is called prior to the next reboot of the system running libvirtd. Prior to that time, the definition can be explicitly restored using virInterfaceChangeRollback(), or will be automatically restored during the next reboot of the system running libvirtd.
- class libvirt.virNWFilter(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object
- class libvirt.virNWFilterBinding(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the network filter. The description may be reused later to redefine the network filter with virNWFilterCreateXML().
- delete() int[source]¶
Delete the binding object. This does not free the associated virNWFilterBindingPtr object. This API may be used to remove the network port binding 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 virNWFilterBindingCreateXML.
- class libvirt.virNetwork(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- DHCPLeases(mac: str | None = None, flags: int | None = 0) str[source]¶
Returns a list of dhcp leases for interfaces connected to the given virtual network
- XMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the network. The description may be reused later to relaunch the network with virNetworkCreateXML().
Normally, if a network included a physical function, the output includes all virtual functions tied to that physical interface. If @flags includes VIR_NETWORK_XML_INACTIVE, then the expansion of virtual interfaces is not performed.
- bridgeName() str[source]¶
Provides a bridge interface name to which a domain may connect a network interface in order to join the network.
- create() int[source]¶
Create and start a defined network. If the call succeed the network moves from the defined to the running networks pools.
- destroy() int[source]¶
Destroy the network object. The running instance is shutdown if not down already and all resources used by it are given back to the hypervisor. This does not free the associated virNetworkPtr object. This function may require privileged access
- isPersistent() int[source]¶
Determine if the network has a persistent configuration which means it will still exist after shutting down
- listAllPorts(flags: int | None = 0) list[virNetworkPort][source]¶
List all ports on the network and returns a list of network port objects
- metadata(type: int, uri: str, flags: int | None = 0) str[source]¶
Retrieves the appropriate network element given by @type. If VIR_NETWORK_METADATA_ELEMENT is requested parameter @uri must be set to the name of the namespace the requested elements belong to, otherwise must be None.
If an element of the network XML is not present, the resulting error will be VIR_ERR_NO_NETWORK_METADATA. This method forms a shortcut for seeing information from virNetworkSetMetadata() without having to go through virNetworkGetXMLDesc().
@flags controls whether the live network state or persistent configuration will be queried.
- portCreateXML(xmldesc: str, flags: int | None = 0) virNetworkPort[source]¶
Create a new network port, based on an XML description similar to the one returned by virNetworkPortGetXMLDesc()
virNetworkPortFree should be used to free the resources after the network port object is no longer needed.
- portLookupByUUID(uuid: bytes) virNetworkPort[source]¶
Try to lookup a port on the given network based on its UUID.
- portLookupByUUIDString(uuidstr: str) virNetworkPort[source]¶
Try to lookup a port on the given network based on its UUID.
- setAutostart(autostart: int) int[source]¶
Configure the network to be automatically started when the host machine boots.
- setMetadata(type: int, metadata: str, key: str, uri: str, flags: int | None = 0) int[source]¶
Sets the appropriate network element given by @type to the value of @metadata. A @type of VIR_NETWORK_METADATA_DESCRIPTION is free-form text; VIR_NETWORK_METADATA_TITLE is free-form, but no newlines are permitted, and should be short (although the length is not enforced). For these two options @key and @uri are irrelevant and must be set to None.
For type VIR_NETWORK_METADATA_ELEMENT @metadata must be well-formed XML belonging to namespace defined by @uri with local name @key.
Passing None for @metadata says to remove that element from the network XML (passing the empty string leaves the element present).
The resulting metadata will be present in virNetworkGetXMLDesc(), as well as quick access through virNetworkGetMetadata().
@flags controls whether the live network state, persistent configuration, or both will be modified.
- class libvirt.virNetworkPort(net: virNetwork, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Provide an XML description of the network port. The description may be reused later to recreate the port with virNetworkPortCreateXML().
- class libvirt.virNodeDevice(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Fetch an XML document describing all aspects of the device.
- destroy() int[source]¶
Destroy the device object. The virtual device (only works for vHBA currently) is removed from the host operating system. This function may require privileged access.
- detachFlags(driverName: str, flags: int | None = 0) int[source]¶
Detach the node device from the node itself so that it may be assigned to a guest domain.
Depending on the hypervisor, this may involve operations such as unbinding any device drivers from the device, binding the device to a dummy device driver and resetting the device. Different backend drivers expect the device to be bound to different dummy devices. For example, QEMU’s “kvm” backend driver (the default) expects the device to be bound to “pci-stub”, but its “vfio” backend driver expects the device to be bound to “vfio-pci”.
If the device is currently in use by the node, this method may fail.
Once the device is not assigned to any guest, it may be re-attached to the node using the virNodeDeviceReAttach() method.
- dettach() int[source]¶
Detach the node device from the node itself so that it may be assigned to a guest domain.
Depending on the hypervisor, this may involve operations such as unbinding any device drivers from the device, binding the device to a dummy device driver and resetting the device.
If the device is currently in use by the node, this method may fail.
Once the device is not assigned to any guest, it may be re-attached to the node using the virNodeDeviceReattach() method.
If the caller needs control over which backend driver will be used during PCI device assignment (to use something other than the default, for example VFIO), the newer virNodeDeviceDetachFlags() API should be used instead.
- isPersistent() int[source]¶
Determine if the node device has a persistent configuration which means it will still exist after shutting down
- reAttach() int[source]¶
Re-attach a previously detached node device to the node so that it may be used by the node again.
Depending on the hypervisor, this may involve operations such as resetting the device, unbinding it from a dummy device driver and binding it to its appropriate driver.
If the device is currently in use by a guest, this method may fail.
- reset() int[source]¶
Reset a previously detached node device to the node before or after assigning it to a guest.
The exact reset semantics depends on the hypervisor and device type but, for example, KVM will attempt to reset PCI devices with a Function Level Reset, Secondary Bus Reset or a Power Management D-State reset.
If the reset will affect other devices which are currently in use, this function may fail.
- setAutostart(autostart: int) int[source]¶
Configure the node device to be automatically started when the host machine boots or the parent device becomes available.
- class libvirt.virSecret(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Fetches an XML document describing attributes of the secret.
- undefine() int[source]¶
Deletes the specified secret. This does not free the associated virSecretPtr object.
- usageID() str[source]¶
Get the unique identifier of the object with which this secret is to be used. The format of the identifier is dependent on the usage type of the secret. For a secret with a usage type of VIR_SECRET_USAGE_TYPE_VOLUME the identifier will be a fully qualified path name. The identifiers are intended to be unique within the set of all secrets sharing the same usage type. ie, there shall only ever be one secret for each volume path.
- usageType() int[source]¶
Get the type of object which uses this secret. The returned value is one of the constants defined in the virSecretUsageType enumeration. More values may be added to this enumeration in the future, so callers should expect to see usage types they do not explicitly know about.
- class libvirt.virStoragePool(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Fetch an XML document describing all aspects of the storage pool. This is suitable for later feeding back into the virStoragePoolCreateXML method.
- build(flags: int | None = 0) int[source]¶
Currently only filesystem pool accepts flags VIR_STORAGE_POOL_BUILD_OVERWRITE and VIR_STORAGE_POOL_BUILD_NO_OVERWRITE.
Build the underlying storage pool
- createXML(xmlDesc: str, flags: int | None = 0) virStorageVol[source]¶
Create a storage volume within a pool based on an XML description. Not all pools support creation of volumes.
Since 1.0.1 VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA in flags can be used to get higher performance with qcow2 image files which don’t support full preallocation, by creating a sparse image file with metadata.
virStorageVolFree should be used to free the resources after the storage volume object is no longer needed.
- createXMLFrom(xmlDesc: str, clonevol: virStorageVol, flags: int | None = 0) virStorageVol[source]¶
Create a storage volume in the parent pool, using the ‘clonevol’ volume as input. Information for the new volume (name, perms) are passed via a typical volume XML description.
Since 1.0.1 VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA in flags can be used to get higher performance with qcow2 image files which don’t support full preallocation, by creating a sparse image file with metadata.
virStorageVolFree should be used to free the resources after the storage volume object is no longer needed.
- delete(flags: int | None = 0) int[source]¶
Delete the underlying pool resources. This is a non-recoverable operation. The virStoragePoolPtr object itself is not free’d.
- destroy() int[source]¶
Destroy an active storage pool. This will deactivate the pool on the host, but keep any persistent config associated with it. If it has a persistent config it can later be restarted with virStoragePoolCreate(). This does not free the associated virStoragePoolPtr object.
- info() str[source]¶
Extract information about a storage pool. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.
- isPersistent() int[source]¶
Determine if the storage pool has a persistent configuration which means it will still exist after shutting down
- listAllVolumes(flags: int | None = 0) list[virStorageVol][source]¶
List all storage volumes and returns a list of storage volume objects
- refresh(flags: int | None = 0) int[source]¶
Request that the pool refresh its list of volumes. This may involve communicating with a remote server, and/or initializing new devices at the OS layer
- setAutostart(autostart: int) int[source]¶
Configure the storage pool to be automatically started when the host machine boots.
- storageVolLookupByName(name: str) virStorageVol[source]¶
Fetch a pointer to a storage volume based on its name within a pool
virStorageVolFree should be used to free the resources after the storage volume object is no longer needed.
- class libvirt.virStorageVol(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- XMLDesc(flags: int | None = 0) str[source]¶
Fetch an XML document describing all aspects of the storage volume
- download(stream: virStream, offset: int, length: int, flags: int | None = 0) int[source]¶
Download the content of the volume as a stream. If @length is zero, then the remaining contents of the volume after @offset will be downloaded. Please note that the stream transports the volume itself as is, so the downloaded data may not correspond to guest OS visible state in cases when a complex storage format such as qcow2 or vmdk is used.
If VIR_STORAGE_VOL_DOWNLOAD_SPARSE_STREAM is set in @flags effective transmission of holes is enabled. This assumes using the @stream with combination of virStreamSparseRecvAll() or virStreamRecvFlags(stream, …, flags = VIR_STREAM_RECV_STOP_AT_HOLE) for honouring holes sent by server.
This call sets up an asynchronous stream; subsequent use of stream APIs is necessary to transfer the actual data, determine how much data is successfully transferred, and detect any errors. The results will be unpredictable if another active stream is writing to the storage volume.
- info() str[source]¶
Extract information about a storage volume. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.
- infoFlags(flags: int | None = 0) str[source]¶
Extract information about a storage volume. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.
- key() str[source]¶
Fetch the storage volume key. This is globally unique, so the same volume will have the same key no matter what host it is accessed from
- path() str[source]¶
Fetch the storage volume path. Depending on the pool configuration this is either persistent across hosts, or dynamically assigned at pool startup. Consult pool documentation for information on getting the persistent naming
- resize(capacity: int, flags: int | None = 0) int[source]¶
Changes the capacity of the storage volume @vol to @capacity. The operation will fail if the new capacity requires allocation that would exceed the remaining free space in the parent pool. The contents of the new capacity will appear as all zero bytes. The capacity value will be rounded to the granularity supported by the hypervisor.
Normally, the operation will attempt to affect capacity with a minimum impact on allocation (that is, the default operation favors a sparse resize). If @flags contains VIR_STORAGE_VOL_RESIZE_ALLOCATE, then the operation will ensure that allocation is sufficient for the new capacity; this may make the operation take noticeably longer.
Normally, the operation treats @capacity as the new size in bytes; but if @flags contains VIR_STORAGE_VOL_RESIZE_DELTA, then @capacity represents the size difference to add to the current size. It is up to the storage pool implementation whether unaligned requests are rounded up to the next valid boundary, or rejected.
Normally, this operation should only be used to enlarge capacity; but if @flags contains VIR_STORAGE_VOL_RESIZE_SHRINK, it is possible to attempt a reduction in capacity even though it might cause data loss. If VIR_STORAGE_VOL_RESIZE_DELTA is also present, then @capacity is subtracted from the current size; without it, @capacity represents the absolute new size regardless of whether it is larger or smaller than the current size.
- storagePoolLookupByVolume() virStoragePool[source]¶
Fetch a storage pool which contains a particular volume
virStoragePoolFree should be used to free the resources after the storage pool object is no longer needed.
- upload(stream: virStream, offset: int, length: int, flags: int | None = 0) int[source]¶
Upload new content to the volume from a stream. This call will fail if @offset + @length exceeds the size of the volume. Otherwise, if @length is non-zero, an error will be raised if an attempt is made to upload greater than @length bytes of data. Please note that the stream transports the volume itself as is, so the downloaded data may not correspond to guest OS visible state in cases when a complex storage format such as qcow2 or vmdk is used.
If VIR_STORAGE_VOL_UPLOAD_SPARSE_STREAM is set in @flags effective transmission of holes is enabled. This assumes using the @stream with combination of virStreamSparseSendAll() or virStreamSendHole() to preserve source file sparseness.
This call sets up an asynchronous stream; subsequent use of stream APIs is necessary to transfer the actual data, determine how much data is successfully transferred, and detect any errors. The results will be unpredictable if another active stream is writing to the storage volume.
When the data stream is closed whether the upload is successful or not an attempt will be made to refresh the target storage pool if an asynchronous build is not running in order to reflect pool and volume changes as a result of the upload. Depending on the target volume storage backend and the source stream type for a successful upload, the target volume may take on the characteristics from the source stream such as format type, capacity, and allocation.
- wipe(flags: int | None = 0) int[source]¶
Ensure data previously on a volume is not accessible to future reads.
The data to be wiped may include the format and possibly size information, so non-raw images might become raw with a different size. It is storage backend dependent whether the format and size information is regenerated once the initial volume wipe is completed.
Depending on the actual volume representation, this call may not overwrite the physical location of the volume. For instance, files stored journaled, log structured, copy-on-write, versioned, and network file systems are known to be problematic.
- wipePattern(algorithm: int, flags: int | None = 0) int[source]¶
Similar to virStorageVolWipe, but one can choose between different wiping algorithms. Also note, that depending on the actual volume representation, this call may not really overwrite the physical location of the volume. For instance, files stored journaled, log structured, copy-on-write, versioned, and network file systems are known to be problematic.
- streamBufSize = 262120¶
- class libvirt.virStream(conn: virConnect, _obj: object | None = None)[source]¶
Bases:
object- abort() int[source]¶
Request that the in progress data transfer be cancelled abnormally before the end of the stream has been reached. For output streams this can be used to inform the driver that the stream is being terminated early. For input streams this can be used to inform the driver that it should stop sending data.
If the stream is non-blocking, any callback must be removed beforehand.
- eventUpdateCallback(events: int) int[source]¶
Changes the set of events to monitor for a stream. This allows for event notification to be changed without having to unregister & register the callback completely. This method is guaranteed to succeed if a callback is already registered
- finish() int[source]¶
Indicate that there is no further data to be transmitted on the stream. For output streams this should be called once all data has been written. For input streams this should be called once virStreamRecv returns end-of-file.
This method is a synchronization point for all asynchronous errors, so if this returns a success code the application can be sure that all data has been successfully processed.
If the stream is non-blocking, any callback must be removed beforehand.
- recv(nbytes: int) bytes[source]¶
Reads a series of bytes from the stream. This method may block the calling application for an arbitrary amount of time.
Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call.
On success, the received data is returned. On failure, an exception is raised. If the stream is a NONBLOCK stream and the request would block, integer -2 is returned.
- recvAll(handler: Callable[[virStream, bytes, _T], int], opaque: _T) None[source]¶
Receive the entire data stream, sending the data to the requested data sink. This is simply a convenient alternative to virStreamRecv, for apps that do blocking-I/O. A hypothetical handler function looks like: def handler(stream, # virStream instance buf, # string containing received data opaque): # extra data passed to recvAll as opaque fd = opaque return os.write(fd, buf)
- recvFlags(nbytes: int, flags: int | None = 0) bytes | int[source]¶
Reads a series of bytes from the stream. This method may block the calling application for an arbitrary amount of time. This is just like recv except it has flags argument.
Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call.
On success, the received data is returned. On failure, an exception is raised. If the stream is a NONBLOCK stream and the request would block, integer -2 is returned.
- recvHole(flags: int | None = 0) int[source]¶
This method is used to determine the length in bytes of the empty space to be created in a stream’s target file when uploading or downloading sparsely populated files. This is the counterpart to sendHole.
- send(data: bytes) int[source]¶
Write a series of bytes to the stream. This method may block the calling application for an arbitrary amount of time. Once an application has finished sending data it should call virStreamFinish to wait for successful confirmation from the driver, or detect any error
This method may not be used if a stream source has been registered
Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call.
- sendAll(handler: Callable[[virStream, int, _T], bytes], opaque: _T) None[source]¶
Send the entire data stream, reading the data from the requested data source. This is simply a convenient alternative to virStreamSend, for apps that do blocking-I/O. A hypothetical handler function looks like: def handler(stream, # virStream instance nbytes, # int amt of data to read opaque): # extra data passed to recvAll as opaque fd = opaque return os.read(fd, nbytes)
- sendHole(length: int, flags: int | None = 0) int[source]¶
Rather than transmitting empty file space, this method directs the stream target to create length bytes of empty space. This method would be used when uploading or downloading sparsely populated files to avoid the needless copy of empty file space.
- sparseRecvAll(handler: Callable[[virStream, bytes, _T], bytes | int], holeHandler: Callable[[virStream, int, _T], int | None], opaque: _T) None[source]¶
Receive the entire data stream, sending the data to the requested data sink handler and calling the skip holeHandler to generate holes for sparse stream targets. This is simply a convenient alternative to recvFlags, for apps that do blocking-I/O and want to preserve sparseness. Hypothetical callbacks can look like this: def handler(stream, # virStream instance buf, # string containing received data opaque): # extra data passed to sparseRecvAll as opaque fd = opaque return os.write(fd, buf) def holeHandler(stream, # virStream instance length, # number of bytes to skip opaque): # extra data passed to sparseRecvAll as opaque fd = opaque cur = os.lseek(fd, length, os.SEEK_CUR) return os.ftruncate(fd, cur) # take this extra step to # actually allocate the hole
- sparseSendAll(handler: Callable[[virStream, int, _T], bytes | int], holeHandler: Callable[[virStream, _T], tuple[bool, int]], skipHandler: Callable[[virStream, int, _T], int], opaque: _T) None[source]¶
Send the entire data stream, reading the data from the requested data source. This is simply a convenient alternative to virStreamSend, for apps that do blocking-I/O and want to preserve sparseness. Hypothetical callbacks can look like this: def handler(stream, # virStream instance nbytes, # int amt of data to read opaque): # extra data passed to sparseSendAll as opaque fd = opaque return os.read(fd, nbytes) def holeHandler(stream, # virStream instance opaque): # extra data passed to sparseSendAll as opaque fd = opaque cur = os.lseek(fd, 0, os.SEEK_CUR) # ... find out current section and its boundaries # and set inData = True/False and sectionLen correspondingly os.lseek(fd, cur, os.SEEK_SET) return [inData, sectionLen] def skipHandler(stream, # virStream instance length, # number of bytes to skip opaque): # extra data passed to sparseSendAll as opaque fd = opaque return os.lseek(fd, length, os.SEEK_CUR)
- libvirt.getVersion(name: str | None = None) int[source]¶
If no name parameter is passed (or name is None) then the version of the libvirt library is returned as an integer.
If a name is passed and it refers to a driver linked to the libvirt library, then this returns a tuple of (library version, driver version).
If the name passed refers to a non-existent driver, then you will get the exception ‘no support for hypervisor’.
Versions numbers are integers: 1000000*major + 1000*minor + release.
- libvirt.open(name: str | None = None) virConnect[source]¶
This function should be called first to get a connection to the Hypervisor and xen store
If @name is None, if the LIBVIRT_DEFAULT_URI environment variable is set, then it will be used. Otherwise if the client configuration file has the “uri_default” parameter set, then it will be used. Finally probing will be done to determine a suitable default driver to activate. This involves trying each hypervisor in turn until one successfully opens.
If connecting to an unprivileged hypervisor driver which requires the libvirtd daemon to be active, it will automatically be launched if not already running. This can be prevented by setting the environment variable LIBVIRT_AUTOSTART=0
URIs are documented at https://libvirt.org/uri.html
virConnectClose should be used to release the resources after the connection is no longer needed.
- libvirt.openAuth(uri: str, auth: list, flags: int | None = 0) virConnect[source]¶
This function should be called first to get a connection to the Hypervisor. If necessary, authentication will be performed fetching credentials via the callback. See :py:func:`open` for notes about environment variables which can have an effect on opening drivers and freeing the connection resources. :param str uri: (Optional) connection URI, see https://libvirt.org/uri.html :param auth: a list that contains 3 items: - a list of supported credential types - a callable that takes 2 arguments (credentials, user-data) and returns 0 on succcess and -1 on errors. The credentials argument is a list of credentials that libvirt (actually the ESX driver) would like to request. An element of this list is itself a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. :py:const:`libvirt.VIR_CRED_AUTHNAME` - a prompt to be displayed to the user - a challenge, the ESX driver sets this to the hostname to allow automatic distinction between requests for ESX and vCenter credentials - a default result for the request - a place to store the actual result for the request - user data that will be passed to the callable as second argument :param int flags: bitwise-OR of virConnectFlags :returns: a :py:class:`virConnect` instance on success. :raises libvirtError: on errors.
- libvirt.openReadOnly(name: str | None = None) virConnect[source]¶
This function should be called first to get a restricted connection to the library functionalities. The set of APIs usable are then restricted on the available methods to control the domains.
See virConnectOpen for notes about environment variables which can have an effect on opening drivers and freeing the connection resources
URIs are documented at https://libvirt.org/uri.html
- libvirt.registerErrorHandler(f: Callable[[_T, tuple[int, int, str, int, str, str | None, str | None, int, int]], None], ctx: _T) int[source]¶
Register a Python function for error reporting. The function is called back as f(ctx, error), with error being a list of information about the error being raised. Returns 1 in case of success.
- libvirt.virEventAddHandle(fd: int, events: int, cb: Callable[[int, int, int, _T], None], opaque: _T) int[source]¶
register a callback for monitoring file handle events @fd: file handle to monitor for events @events: bitset of events to watch from virEventHandleType constants @cb: callback to invoke when an event occurs @opaque: user data to pass to callback Example callback prototype is: def cb(watch, # int id of the handle fd, # int file descriptor the event occurred on events, # int bitmap of events that have occurred opaque): # opaque data passed to eventAddHandle
- libvirt.virEventAddTimeout(timeout: int, cb: Callable[[int, _T], None], opaque: _T) int[source]¶
register a callback for a timer event @timeout: time between events in milliseconds @cb: callback to invoke when an event occurs @opaque: user data to pass to callback Setting timeout to -1 will disable the timer. Setting the timeout to zero will cause it to fire on every event loop iteration. Example callback prototype is: def cb(timer, # int id of the timer opaque): # opaque data passed to eventAddTimeout
- libvirt.virEventInvokeFreeCallback(opaque: Any) None[source]¶
Execute callback which frees the opaque buffer
@opaque: the opaque object passed to addHandle or addTimeout
WARNING: This function should not be called from any call by libvirt’s core. It will most probably cause deadlock in C-level libvirt code. Instead it should be scheduled and called from implementation’s stack.
See https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddHandleFunc for more information.
This function is not dependent on any event loop implementation.
- libvirt.virEventRegisterDefaultImpl() int[source]¶
Registers a default event implementation based on the poll() system call. This is a generic implementation that can be used by any client application which does not have a need to integrate with an external event loop impl.
For proper event handling, it is important that the event implementation is registered before a connection to the Hypervisor is opened.
Once registered, the application has to invoke virEventRunDefaultImpl() in a loop to process events. Failure to do so may result in connections being closed unexpectedly as a result of keepalive timeout. The default event loop fully supports handle and timeout events, but only wakes up on events registered by libvirt API calls such as virEventAddHandle() or virConnectDomainEventRegisterAny().
- libvirt.virEventRegisterImpl(addHandle: Callable[[int, int, Callable[[int, int, int, _T], None], _T], int], updateHandle: Callable[[int, int], None], removeHandle: Callable[[int], int], addTimeout: Callable[[int, Callable[[int, _T], None], _T], int], updateTimeout: Callable[[int, int], None], removeTimeout: Callable[[int], int]) None[source]¶
Registers an event implementation, to allow integration with an external event loop. Applications would use this to integrate with the libglib2 event loop, or libevent or the QT event loop.
For proper event handling, it is important that the event implementation is registered before a connection to the Hypervisor is opened.
Use of the virEventAddHandle() and similar APIs require that the corresponding handler is registered. Use of the virConnectDomainEventRegisterAny() and similar APIs requires that the three timeout handlers are registered. Likewise, the three timeout handlers must be registered if the remote server has been configured to send keepalive messages, or if the client intends to call virConnectSetKeepAlive(), to avoid either side from unexpectedly closing the connection due to inactivity.
If an application does not need to integrate with an existing event loop implementation, then the virEventRegisterDefaultImpl() method can be used to setup the generic libvirt implementation.
Once registered, the event loop implementation cannot be changed, and must be run continuously. Note that callbacks may remain registered for a short time even after calling virConnectClose on all open connections, so it is not safe to stop running the event loop immediately after closing the connection.
- libvirt.virEventRemoveHandle(watch: int) int[source]¶
Unregister a callback from a file handle. This function requires that an event loop has previously been registered with virEventRegisterImpl() or virEventRegisterDefaultImpl().
- libvirt.virEventRemoveTimeout(timer: int) int[source]¶
Unregister a callback for a timer. This function requires that an event loop has previously been registered with virEventRegisterImpl() or virEventRegisterDefaultImpl().
- libvirt.virEventRunDefaultImpl() int[source]¶
Run one iteration of the event loop. Applications will generally want to have a thread which invokes this method in an infinite loop. Furthermore, it is wise to set up a pipe-to-self handler (via virEventAddHandle()) or a timeout (via virEventAddTimeout()) before calling this function, as it will block forever if there are no registered events. static bool quit; while (!quit) { if (virEventRunDefaultImpl() < 0) ...print error... }
- libvirt.virEventUpdateHandle(watch: int, events: int) None[source]¶
Change event set for a monitored file handle. This function requires that an event loop has previously been registered with virEventRegisterImpl() or virEventRegisterDefaultImpl().
Will not fail if fd exists.
- libvirt.virEventUpdateTimeout(timer: int, timeout: int) None[source]¶
Change frequency for a timer. This function requires that an event loop has previously been registered with virEventRegisterImpl() or virEventRegisterDefaultImpl().
Setting frequency to -1 will disable the timer. Setting the frequency to zero will cause it to fire on every event loop iteration.
Will not fail if timer exists.
- libvirt.virGetLastError() tuple[int, int, str, int, str, str | None, str | None, int, int][source]¶
Provide a pointer to the last error caught at the library level
The error object is kept in thread local storage, so separate threads can safely access this concurrently.
- libvirt.virGetLastErrorDomain() int[source]¶
Get the most recent error domain (enum virErrorDomain).
- libvirt.virInitialize() int[source]¶
Initialize the library.
This method is invoked automatically by any of the virConnectOpen() API calls, and by virGetVersion(). Since release 1.0.0, there is no need to call this method even in a multithreaded application, since initialization is performed in a thread safe manner; but applications using an older version of the library should manually call this before setting up competing threads that attempt virConnectOpen in parallel.
The only other time it would be necessary to call virInitialize is if the application did not invoke virConnectOpen as its first API call, such as when calling virEventRegisterImpl() before setting up connections, or when using virSetErrorFunc() to alter error reporting of the first connection attempt.