libvirt

package module
v0.0.0-...-84fa71e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package libvirt provisions and drives throw-away virtual machines on a libvirt/QEMU host.

Adapted from the virtdeploy package in github.com/microsoft/trident (MIT).

Ownership

A Client owns one run. Every libvirt object it creates (domains, the NAT network, the storage pool and its volumes) is named "<namespace>_<run ID>_<something>". The run ID is random unless the caller supplies one, so two clients never share objects, not even with the same namespace, and Client.Destroy only removes objects with its own prefix. The separator "_" is not allowed inside namespaces, run IDs and VM names, so a prefix can never match the objects of a different namespace or run.

The ownership information lives in the names, which libvirt persists, so a process that crashed leaves objects that a later process can find with Client.Runs and remove by connecting with Options.RunID set. Taking over an existing run is always explicit; a client with a fresh run ID refuses to reuse a network or pool that already exists.

Connection lifetime is separate from ownership: Client.Close only disconnects.

Networking

Each run gets its own NAT network with a DHCP range, created once on the first Client.Provision. The /24 subnet inside 192.168.0.0/16 is derived from a hash of namespace and run ID, skipping subnets already used by existing libvirt networks and host interfaces. 192.168.0.0/24, 192.168.1.0/24 and the libvirt default 192.168.122.0/24 are never used. Because processes can race, the new network is checked after it has started against all other libvirt networks; on a conflict it is removed and another subnet is tried.

Typical use

c, err := libvirt.Connect(ctx, "", libvirt.Options{Namespace: "mytest"})
if err != nil { ... }
defer c.Close()
defer func() {
	// Cleanup must outlive a cancelled run: keep the values of ctx but
	// not its cancellation, and give it its own budget.
	dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute)
	defer cancel()
	_ = c.Destroy(dctx)
}()
vm, err := c.Provision(ctx, libvirt.Spec{Name: "vm0", CPUs: 2, MemoryMiB: 2048,
	Disks: []libvirt.Disk{{SizeGiB: 20, BootOrder: 1}}})
...
err = vm.Start(ctx)

Contexts

Every blocking method takes a context and uses no deadline of its own. The libvirt RPC client used underneath is not context aware, so a single RPC is never interrupted; the context is checked between calls and while polling. Long uploads (Disk.ImagePath) are aborted at the next read once the context ends. Provision's cleanup after a failure is the one exception: it runs with a short context of its own so that it still happens after a cancellation.

Host assumptions

UEFI firmware files are looked up on the local filesystem, and local host interfaces are consulted when choosing a subnet, so the libvirt daemon is expected to run on the machine running this library; the default "qemu:///system" does. CDROM.Path is a path on the libvirt host.

Index

Constants

View Source
const (
	ArchAMD64 = "amd64"
	ArchARM64 = "arm64"
)

Architectures accepted in Spec.Arch.

Variables

View Source
var ErrNoAddress = errors.New("no DHCP lease for VM")

ErrNoAddress is returned (wrapped) by VM.Address while the VM has no DHCP lease yet. Callers are expected to poll.

Functions

This section is empty.

Types

type CDROM

type CDROM struct {
	Path      string
	BootOrder uint
}

CDROM describes one optical drive. Path is the absolute path, on the libvirt host, of the ISO to insert; it must be readable by the hypervisor and allowed by the host's confinement policy. It may be empty to create an empty bay that VM.SetCDROM can fill later. BootOrder is described on Spec.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to one libvirt daemon on behalf of one run. Connection lifetime and resource ownership are separate: Client.Close only disconnects, and Client.Destroy removes what the run created.

func Connect

func Connect(ctx context.Context, uri string, o Options) (*Client, error)

Connect opens a connection to libvirt. An empty uri means qemu:///system.

The connection attempt itself is not interruptible; if ctx ends first, Connect returns promptly and a helper goroutine closes the connection as soon as the attempt finishes.

func (*Client) Close

func (c *Client) Close() error

Close disconnects from libvirt. It never removes or stops anything; call Client.Destroy for that. Serial console captures are tied to the connection and end with it, so Close stops them and waits for their goroutines.

func (*Client) Destroy

func (c *Client) Destroy(ctx context.Context) error

Destroy removes everything the client's run owns: its domains (stopped if running, with their NVRAM and TPM state), the volumes of its storage pool, the pool itself, and its NAT network. Only objects named with the run's own prefix, "<namespace>_<run ID>_", are touched; objects of other runs in the same namespace, and anything else on the host, are left alone. Objects that are already gone are ignored, and a failed Destroy can simply be called again.

The order is domains, then volumes and pool, then network. If a domain could not be stopped, its disks and network are left in place and the failure is returned. Otherwise Destroy keeps going after an individual failure and returns all failures joined. A pool whose volumes could not all be deleted is kept so that a retry still finds them. The Spec.SerialLog files are left alone; serial captures are stopped.

Destroy honours ctx like every other method, and uses no deadline of its own. To clean up after a cancelled or timed-out run, pass a context that outlives it with its own budget:

ctx, cancel := context.WithTimeout(context.WithoutCancel(runCtx), 2*time.Minute)
defer cancel()
err := c.Destroy(ctx)

func (*Client) Namespace

func (c *Client) Namespace() string

Namespace returns the namespace of the client.

func (*Client) Provision

func (c *Client) Provision(ctx context.Context, s Spec) (vm *VM, err error)

Provision defines a VM from s, creating the run's shared NAT network and storage pool on the first call and reusing them afterwards. The VM is defined but not started; see VM.Start. VM names must be unique within the run.

Before anything is created, Provision checks that the libvirt host can provide the requested architecture, firmware and devices; an unsupported SecureBoot or TPM request is an error, never a silent downgrade.

If Provision fails, the objects created for this VM are removed with a fresh bounded context and any failure of that cleanup is returned together with the original error (errors.Join). The shared network and pool stay until Client.Destroy.

Provision calls and Destroy on one Client are serialised.

func (*Client) RunID

func (c *Client) RunID() string

RunID returns the ID of the run the client owns. Record it (for example in a log or artifact) to be able to clean up after a crash by connecting again with Options.RunID.

func (*Client) Runs

func (c *Client) Runs(ctx context.Context) ([]string, error)

Runs lists the IDs of all runs in the client's namespace that have objects (domains, networks or storage pools) on the host, including the client's own run. It is meant for recovering from crashes: connect again with each leftover ID in Options.RunID and call Client.Destroy.

type Disk

type Disk struct {
	SizeGiB   uint
	ImagePath string
	BootOrder uint
}

Disk describes one disk of a VM. At least one of SizeGiB and ImagePath must be set.

With only SizeGiB, a blank, thin-provisioned qcow2 volume of that capacity is created in the run's storage pool.

ImagePath names an image on the machine running this library. It is an immutable source: its contents are copied (uploaded) into a new volume owned by the run, and the source file is neither modified nor attached to the VM. The format is detected from the file header: a qcow2 image becomes a qcow2 volume, anything else is treated as a raw image and becomes a raw volume. The volume has the image's virtual size, so the copy of a large image takes as long as the upload.

With both, the image is copied and the volume is then enlarged to SizeGiB. SizeGiB must not be smaller than the image's virtual size (shrinking is refused). Enlarging only extends the virtual disk; growing the guest's partitions and filesystems is up to the guest.

BootOrder is described on Spec.

type Options

type Options struct {
	// Namespace groups runs and prefixes the names of everything a client
	// creates, which makes them recognisable on a shared host. Required:
	// lowercase letters, digits and single hyphens, at most 32 characters.
	// Namespaces do not isolate anything by themselves; see RunID.
	Namespace string

	// RunID identifies the run that owns the created objects: lowercase letters
	// and digits, at most 16 characters. Leave it empty to start a new run
	// with a random ID; every object then carries an ID no one else has, and a
	// client never touches objects of another run, even in the same namespace.
	//
	// Setting it is an explicit opt-in to take over the objects of an
	// existing run, for example to destroy what a crashed process left behind
	// (see [Client.Runs]). Only then may Provision reuse a network and storage
	// pool that already exist.
	RunID string

	// Logf receives diagnostic messages. Nil means silent.
	Logf func(format string, args ...any)
}

Options configures a Client.

type Spec

type Spec struct {
	// Name identifies the VM within the run: lowercase letters, digits and
	// single hyphens. The libvirt domain is named
	// "<namespace>_<run ID>_<Name>".
	Name string

	CPUs      uint
	MemoryMiB uint

	// Arch is ArchAMD64 (default when empty) or ArchARM64.
	Arch string

	Disks  []Disk
	CDROMs []CDROM

	// SecureBoot selects the secure boot capable firmware with the
	// Microsoft keys enrolled.
	SecureBoot bool

	// TPM attaches an emulated TPM 2.0 device (requires swtpm on the host).
	TPM bool

	// SerialLog is a path on the machine running this library. When set, the
	// guest's first serial port is captured into that file from [VM.Start]
	// on, over the libvirt connection, so it works with remote libvirt URIs.
	// The file is created (mode 0644, owned by the calling user) if missing and
	// appended to, across guest reboots and VM restarts; it is never truncated
	// or removed by this library. Capture ends when the VM is shut off, the
	// client is closed or [Client.Destroy] runs.
	SerialLog string
}

Spec describes a VM to provision.

Boot order: BootOrder on a Disk or CDROM is one global ranking across both kinds of device. 0 means the device is not a boot device; a positive value is its libvirt boot order, and the firmware tries devices in ascending order (1 first). Positive values must be unique across all Disks and CDROMs; they need not be contiguous. If no device has a BootOrder, the firmware default applies.

The machine uses UEFI firmware (OVMF for amd64, AAVMF for arm64). amd64 guests are KVM accelerated q35 machines with SATA disks; arm64 guests use the TCG emulated "virt" machine with virtio disks. Provision checks the libvirt host's capabilities and fails if SecureBoot or TPM, or the architecture itself, cannot be provided; it never falls back to a weaker configuration.

type State

type State string

State is the coarse run state of a VM.

const (
	StateRunning State = "running"
	StateShutoff State = "shutoff"
	// StateOther covers every other libvirt state (paused, shutting down,
	// crashed, ...).
	StateOther State = "other"
)

type VM

type VM struct {
	// contains filtered or unexported fields
}

VM is a handle to a provisioned domain. Methods are safe for concurrent use.

func (*VM) Address

func (v *VM) Address(ctx context.Context) (netip.Addr, error)

Address returns the VM's IPv4 address from the network's DHCP leases. It makes one lookup (plus a bounded number of retries when several leases exist for the VM, which happens briefly when a guest sends duplicate DHCP requests) and never waits for a lease to appear: while there is none it returns an error wrapping ErrNoAddress, and the caller is expected to poll.

func (*VM) ForceStop

func (v *VM) ForceStop(ctx context.Context) error

ForceStop powers the VM off immediately, like pulling the plug. The domain definition is kept. Stopping a VM that is not running is a no-op.

func (*VM) MAC

func (v *VM) MAC() string

MAC returns the MAC address of the VM's network interface.

func (*VM) Name

func (v *VM) Name() string

Name returns the libvirt domain name, "<namespace>_<Spec.Name>", as shown by virsh.

func (*VM) Reset

func (v *VM) Reset(ctx context.Context) error

Reset hard-resets a running guest, like pressing the reset button. The domain keeps running, and so does the serial capture.

func (*VM) SerialLogPath

func (v *VM) SerialLogPath() string

SerialLogPath returns the path of the serial console capture file, or "" when none was requested.

func (*VM) SetCDROM

func (v *VM) SetCDROM(ctx context.Context, slot int, path string) error

SetCDROM inserts the ISO at path (an absolute path on the libvirt host) into the CDROM slot, or ejects the medium when path is empty. Slots are indexed in the order of Spec.CDROMs.

The change is made to the persistent definition, so the new medium (or the empty bay) is also what the VM has on its next boot, including after a shutdown and VM.Start. When the VM is running, the same change is applied to the live guest at the same time. Ejecting a running guest's medium is forced so that a tray locked by the guest does not block it. The drive keeps its boot order.

func (*VM) Shutdown

func (v *VM) Shutdown(ctx context.Context) error

Shutdown asks the guest to power off through ACPI and waits until the domain is shut off, so that callers can safely use the VM's disks afterwards. It returns nil only once the VM is off. If ctx ends first it returns an error wrapping the context's error and leaves the VM as it is: Shutdown never forces the VM off. A guest that ignores ACPI never shuts down, so pass a context with a timeout and decide yourself whether to call VM.ForceStop.

func (*VM) Start

func (v *VM) Start(ctx context.Context) error

Start boots the VM and, when Spec.SerialLog is set, begins capturing the serial console. Starting a running VM only makes sure the capture runs.

func (*VM) State

func (v *VM) State(ctx context.Context) (State, error)

State reports the current run state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL