Documentation
¶
Overview ¶
Package qemuctl provides a Go library for managing QEMU virtual machines.
The library supports:
- Launching QEMU instances with a simplified configuration
- Attaching to existing QEMU processes
- Controlling VMs via QMP (QEMU Monitor Protocol)
- VNC and SPICE client connection passthrough
- State tracking and event handling
Quick Start ¶
Start a new QEMU instance:
cfg := qemuctl.DefaultConfig()
cfg.Memory = 2048
cfg.CPUs = 4
cfg.Drives = []qemuctl.DriveConfig{
{File: "/path/to/disk.qcow2", Format: "qcow2"},
}
inst, err := qemuctl.Start(cfg)
if err != nil {
log.Fatal(err)
}
defer inst.Stop(30 * time.Second)
Attach to an existing QEMU instance by socket:
inst, err := qemuctl.Attach("/var/run/qemu/myvm.sock")
if err != nil {
log.Fatal(err)
}
Attach to an existing QEMU instance by PID:
inst, err := qemuctl.AttachByPID(12345)
if err != nil {
log.Fatal(err)
}
Control Socket Location ¶
When starting a new instance, the QMP control socket is created in:
- For root: /var/run/qemu/<name>.sock
- For users: <os.UserCacheDir()>/qemuctl/<name>.sock
You can override this by setting Config.SocketDir.
QEMU Binary Location ¶
The library searches for QEMU binaries in this order:
- Config.QemuPath if provided
- PATH environment variable
- /pkg/main/app-emulation.qemu.core/bin/
- Common system paths (/usr/bin, /usr/local/bin)
Architecture Support ¶
The library uses GOARCH-style architecture names (amd64, arm64, 386, etc.) and maps them to QEMU binary names (qemu-system-x86_64, qemu-system-aarch64, etc.).
VNC and SPICE ¶
The library supports passing client connections to QEMU for VNC and SPICE:
// Accept a client connection clientConn, _ := listener.Accept() // Pass it to QEMU for VNC err := inst.AddVNCClient(clientConn, true)
This uses QEMU's add_client command with SCM_RIGHTS to pass the file descriptor.
Index ¶
- Variables
- func LocateQemu(arch string, customPath string) (string, error)
- func QemuArchName(goarch string) (string, bool)
- func SupportedArches() []string
- type AudioConfig
- type BalloonConfig
- type BlockInfo
- type BootConfig
- type BridgeNetBackend
- type CDROMConfig
- type CPUConfig
- type ChardevConfig
- type Config
- type DiskBackend
- type DiskConfig
- type DisplayConfig
- type DriveConfig
- type EFIConfig
- type Event
- type FileDiskBackend
- type ISCSIDiskBackend
- type Instance
- func Attach(socketPath string) (*Instance, error)
- func AttachByPID(pid int) (*Instance, error)
- func AttachByPIDContext(ctx context.Context, pid int) (*Instance, error)
- func AttachContext(ctx context.Context, socketPath string) (*Instance, error)
- func Start(cfg *Config) (*Instance, error)
- func StartContext(ctx context.Context, cfg *Config) (*Instance, error)
- func StartVM(cfg *VMConfig) (*Instance, error)
- func StartVMContext(ctx context.Context, cfg *VMConfig) (*Instance, error)
- func (i *Instance) AddSpiceClient(conn net.Conn, skipAuth bool) error
- func (i *Instance) AddVNCClient(conn net.Conn, skipAuth bool) error
- func (i *Instance) Continue() error
- func (i *Instance) Events() <-chan *Event
- func (i *Instance) ExpireSpicePassword(expireTime string) error
- func (i *Instance) ExpireVNCPassword(expireTime string) error
- func (i *Instance) ForceStop() error
- func (i *Instance) HumanMonitorCommand(cmd string) (string, error)
- func (i *Instance) Name() string
- func (i *Instance) PID() int
- func (i *Instance) Pause() error
- func (i *Instance) QMP() *QMP
- func (i *Instance) QueryBlockDevices() ([]BlockInfo, error)
- func (i *Instance) QueryState() error
- func (i *Instance) Quit() error
- func (i *Instance) Reset() error
- func (i *Instance) Screendump(filename string) error
- func (i *Instance) SendKey(keys ...string) error
- func (i *Instance) SetEventCallback(cb func(*Event))
- func (i *Instance) SetIOThrottle(device string, bps, iops uint64) error
- func (i *Instance) SetSpicePassword(password string) error
- func (i *Instance) SetStateChangeCallback(cb func(State))
- func (i *Instance) SetVNCPassword(password string) error
- func (i *Instance) Shutdown() error
- func (i *Instance) SocketPath() string
- func (i *Instance) State() State
- func (i *Instance) Stop(timeout time.Duration) error
- func (i *Instance) StopContext(ctx context.Context, timeout time.Duration) error
- func (i *Instance) Wait() error
- func (i *Instance) WaitContext(ctx context.Context) error
- type MachineConfig
- type MemoryBackendConfig
- type MemoryConfig
- type NBDDiskBackend
- type NetDevConfig
- type NetworkBackend
- type NetworkConfig
- type QMP
- func (q *QMP) Close() error
- func (q *QMP) Events() <-chan *Event
- func (q *QMP) Execute(command string, args map[string]any) (json.RawMessage, error)
- func (q *QMP) ExecuteWithFd(command string, args map[string]any, fd int) (json.RawMessage, error)
- func (q *QMP) ExecuteWithTimeout(command string, args map[string]any, timeout time.Duration) (json.RawMessage, error)
- func (q *QMP) SetEventCallback(cb func(*Event))
- func (q *QMP) SetStateChangeCallback(cb func(State))
- type QMPError
- type RBDDiskBackend
- type RTCConfig
- type SecretConfig
- type SerialConfig
- type SocketNetBackend
- type SpiceConfig
- type SpiceDisplayConfig
- type State
- type StreamNetBackend
- type TapNetBackend
- type ThrottleConfig
- type USBControllerConfig
- type USBDeviceConfig
- type UnsupportedArchError
- type UserNetBackend
- type VDENetBackend
- type VMBuilder
- type VMConfig
- type VNCConfig
- type VideoConfig
- type VirtioSerialConfig
- type VirtioSerialPortConfig
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotConnected = errors.New("not connected to QEMU") ErrNotRunning = errors.New("QEMU process not running") )
Common errors.
var ErrQemuNotFound = errors.New("QEMU binary not found")
ErrQemuNotFound is returned when QEMU cannot be located.
Functions ¶
func LocateQemu ¶
LocateQemu finds the QEMU system emulator for the given architecture. It searches in the following order: 1. If customPath is provided and valid, use it 2. Search in PATH 3. Search in /pkg/main/app-emulation.qemu.core/bin/ 4. Search in common system paths
The arch parameter should be a GOARCH-style value (e.g., "amd64", "arm64"). If arch is empty, it defaults to runtime.GOARCH.
func QemuArchName ¶
QemuArchName converts a GOARCH value to the QEMU architecture name.
func SupportedArches ¶
func SupportedArches() []string
SupportedArches returns a list of supported GOARCH values.
Types ¶
type AudioConfig ¶
type AudioConfig struct {
// Backend is the audio backend ("spice", "pa", "alsa", "none").
Backend string
// Device is the sound device type ("intel-hda", "ich9-intel-hda", "ac97").
Device string
// Codec is the codec for HDA devices ("hda-micro", "hda-duplex", "hda-output").
Codec string
}
AudioConfig configures audio device.
type BalloonConfig ¶
type BalloonConfig struct {
// Enabled enables/disables balloon device.
Enabled bool
}
BalloonConfig configures memory balloon device.
type BlockInfo ¶
type BlockInfo struct {
Device string `json:"device"`
NodeName string `json:"node-name"`
QDev string `json:"qdev,omitempty"`
Type string `json:"type"`
Inserted *struct {
File string `json:"file"`
NodeName string `json:"node-name"`
Ro bool `json:"ro"`
Drv string `json:"drv"`
BackingFile string `json:"backing_file,omitempty"`
BackingFileDepth int `json:"backing_file_depth"`
Encrypted bool `json:"encrypted"`
DetectZeroes string `json:"detect_zeroes"`
Bps int64 `json:"bps"`
BpsRd int64 `json:"bps_rd"`
BpsWr int64 `json:"bps_wr"`
Iops int64 `json:"iops"`
IopsRd int64 `json:"iops_rd"`
IopsWr int64 `json:"iops_wr"`
} `json:"inserted,omitempty"`
}
BlockInfo represents information about a block device.
type BootConfig ¶
type BootConfig struct {
// Order is the boot order (e.g., "cdn" for cdrom, disk, network).
Order string
// Menu enables/disables boot menu.
Menu *bool
// Strict enforces boot order.
Strict bool
// Kernel is the path to a kernel image for direct boot.
Kernel string
// Initrd is the path to an initrd image.
Initrd string
// Append is the kernel command line.
Append string
}
BootConfig configures boot options.
type BridgeNetBackend ¶
type BridgeNetBackend struct {
// Bridge is the bridge name.
Bridge string
// Helper is the bridge helper path.
Helper string
}
BridgeNetBackend provides bridge helper networking.
func (*BridgeNetBackend) BuildNetdevArgs ¶
func (b *BridgeNetBackend) BuildNetdevArgs(id string) []string
func (*BridgeNetBackend) Type ¶
func (b *BridgeNetBackend) Type() string
type CDROMConfig ¶
type CDROMConfig struct {
// Path is the ISO file path.
Path string
// BootIndex sets the boot priority.
BootIndex int
}
CDROMConfig configures a CD-ROM drive.
type CPUConfig ¶
type CPUConfig struct {
// Model is the CPU model (e.g., "host", "qemu64", "max").
Model string
// Features are CPU feature flags (e.g., "+ssse3", "-svm").
Features []string
// Sockets is the number of CPU sockets.
Sockets int
// Cores is the number of cores per socket.
Cores int
// Threads is the number of threads per core.
Threads int
}
CPUConfig configures the virtual CPU.
type ChardevConfig ¶
type ChardevConfig struct {
// ID is the chardev ID.
ID string
// Backend is the chardev backend type.
Backend string
// Path is the socket/file path.
Path string
// Server makes socket a server.
Server bool
// Wait waits for connection.
Wait bool
// Host is the TCP host.
Host string
// Port is the TCP port.
Port int
// Reconnect is the reconnect interval in seconds.
Reconnect int
// Name is the spicevmc channel name.
Name string
}
ChardevConfig configures a character device.
type Config ¶
type Config struct {
// Name is a unique identifier for this instance.
// If empty, a random name will be generated.
Name string
// Arch is the target architecture (GOARCH-style, e.g., "amd64", "arm64").
// Defaults to runtime.GOARCH if empty.
Arch string
// QemuPath is the path to the QEMU binary.
// If empty, it will be located automatically.
QemuPath string
// SocketDir is the directory for control sockets.
// If empty, defaults to os.UserCacheDir()/qemuctl for users
// or /var/run/qemu for root.
SocketDir string
// Memory is the amount of memory in megabytes.
// Defaults to 512 if not set.
Memory int
// CPUs is the number of virtual CPUs.
// Defaults to 1 if not set.
CPUs int
// Machine is the machine type (e.g., "q35", "pc", "virt").
// If empty, QEMU's default for the architecture is used.
Machine string
// CPU is the CPU model (e.g., "host", "qemu64").
// Defaults to "host" if KVM is available.
CPU string
// KVM enables KVM acceleration if available.
// Defaults to true.
KVM *bool
// Drives is a list of drive configurations.
Drives []DriveConfig
// NetworkDevices is a list of network device configurations.
NetworkDevices []NetDevConfig
// VNC enables VNC display.
// Use "none" for no listening socket (clients via add_client).
VNC string
// Spice enables SPICE display.
Spice *SpiceConfig
// ExtraArgs are additional command-line arguments.
ExtraArgs []string
// NoDefaults disables QEMU's default devices.
// Defaults to true.
NoDefaults *bool
// Daemonize runs QEMU in the background.
// Note: This is handled by the library, not QEMU's -daemonize.
Daemonize bool
}
Config holds the configuration for launching a QEMU instance.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults.
type DiskBackend ¶
type DiskBackend interface {
// Type returns the backend type name.
Type() string
// BuildBlockdevArgs builds the blockdev arguments.
BuildBlockdevArgs(id string) []string
}
DiskBackend is the interface for disk backends.
type DiskConfig ¶
type DiskConfig struct {
// ID is the drive/device ID.
ID string
// Backend configures the storage backend.
Backend DiskBackend
// Interface is the disk interface ("virtio", "ide", "scsi", "nvme").
Interface string
// Cache is the caching mode ("none", "writeback", "writethrough").
Cache string
// Discard enables discard/TRIM ("unmap", "ignore").
Discard string
// ReadOnly makes the drive read-only.
ReadOnly bool
// BootIndex sets the boot priority (lower = higher priority).
BootIndex int
// Throttle configures I/O throttling.
Throttle *ThrottleConfig
// Serial is the drive's serial number.
Serial string
}
DiskConfig configures a disk drive.
type DisplayConfig ¶
type DisplayConfig struct {
// Type is the display type ("none", "vnc", "spice", "gtk", "sdl").
Type string
// VNC configures VNC display.
VNC *VNCConfig
// Spice configures SPICE display.
Spice *SpiceDisplayConfig
// Video configures video device.
Video *VideoConfig
}
DisplayConfig configures display output.
type DriveConfig ¶
type DriveConfig struct {
// File is the path to the disk image.
File string
// Format is the disk format (e.g., "qcow2", "raw").
Format string
// Interface is the disk interface (e.g., "virtio", "ide", "scsi").
// Defaults to "virtio".
Interface string
// ReadOnly makes the drive read-only.
ReadOnly bool
// Cache is the caching mode (e.g., "none", "writeback").
Cache string
// Serial is the drive's serial number.
Serial string
}
DriveConfig configures a disk drive.
type EFIConfig ¶
type EFIConfig struct {
// Code is the path to the EFI code (pflash0).
Code string
// Vars is the path to the EFI variables file (pflash1).
Vars string
// VarsTemplate is the template for creating new vars file.
VarsTemplate string
}
EFIConfig configures UEFI firmware.
type FileDiskBackend ¶
type FileDiskBackend struct {
// Path is the file path.
Path string
// Format is the disk format ("raw", "qcow2", "vmdk").
Format string
// AutoReadOnly enables auto read-only mode.
AutoReadOnly bool
}
FileDiskBackend represents a file-based disk.
func (*FileDiskBackend) BuildBlockdevArgs ¶
func (f *FileDiskBackend) BuildBlockdevArgs(id string) []string
func (*FileDiskBackend) Type ¶
func (f *FileDiskBackend) Type() string
type ISCSIDiskBackend ¶
type ISCSIDiskBackend struct {
// Portal is the iSCSI portal address (host:port).
Portal string
// Target is the iSCSI target name.
Target string
// Lun is the LUN number.
Lun int
// User is the CHAP user name.
User string
// PasswordSecret is the secret ID for CHAP password.
PasswordSecret string
// InitiatorName is the initiator IQN.
InitiatorName string
}
ISCSIDiskBackend represents an iSCSI disk.
func (*ISCSIDiskBackend) BuildBlockdevArgs ¶
func (i *ISCSIDiskBackend) BuildBlockdevArgs(id string) []string
func (*ISCSIDiskBackend) Type ¶
func (i *ISCSIDiskBackend) Type() string
type Instance ¶
type Instance struct {
// contains filtered or unexported fields
}
Instance represents a running or attached QEMU instance.
func AttachByPID ¶
AttachByPID connects to an existing QEMU instance by its process ID. It uses runutil.ArgsOf to find the control socket from the process arguments.
func AttachByPIDContext ¶
AttachByPIDContext connects to an existing QEMU instance by PID with context.
func AttachContext ¶
AttachContext connects to an existing QEMU instance with context support.
func StartContext ¶
StartContext launches a new QEMU instance with context support.
func StartVMContext ¶
StartVMContext launches a QEMU instance with context support.
func (*Instance) AddSpiceClient ¶
AddSpiceClient passes a client connection to QEMU for SPICE. The connection will be taken over by QEMU for SPICE protocol. The skipAuth parameter controls whether SPICE authentication is skipped.
func (*Instance) AddVNCClient ¶
AddVNCClient passes a client connection to QEMU for VNC. The connection will be taken over by QEMU for VNC protocol. The skipAuth parameter controls whether VNC authentication is skipped.
func (*Instance) ExpireSpicePassword ¶
ExpireSpicePassword expires the SPICE password at a given time.
func (*Instance) ExpireVNCPassword ¶
ExpireVNCPassword expires the VNC password at a given time. Use "now" to expire immediately, "never" for no expiration.
func (*Instance) HumanMonitorCommand ¶
HumanMonitorCommand executes a human monitor command. This is useful for commands not exposed via QMP.
func (*Instance) QueryBlockDevices ¶
QueryBlockDevices returns information about all block devices.
func (*Instance) QueryState ¶
QueryState queries and updates the current state from QEMU.
func (*Instance) Reset ¶
Reset performs a hard reset of the VM. This is equivalent to pressing the reset button - it's immediate and does not give the guest OS a chance to shut down gracefully.
func (*Instance) Screendump ¶
Screendump captures the screen to a file.
func (*Instance) SendKey ¶
SendKey sends a key event to the guest. Keys should be in QEMU key format (e.g., "ctrl-alt-delete").
func (*Instance) SetEventCallback ¶
SetEventCallback sets a callback for all events.
func (*Instance) SetIOThrottle ¶
SetIOThrottle sets I/O throttling for a block device.
func (*Instance) SetSpicePassword ¶
SetSpicePassword sets the SPICE password.
func (*Instance) SetStateChangeCallback ¶
SetStateChangeCallback sets a callback for state changes.
func (*Instance) SetVNCPassword ¶
SetVNCPassword sets the VNC password.
func (*Instance) Shutdown ¶
Shutdown sends a powerdown request to the guest (ACPI power button). Unlike Stop, this does not wait or force kill.
func (*Instance) SocketPath ¶
SocketPath returns the path to the QMP control socket.
func (*Instance) Stop ¶
Stop performs a graceful shutdown, waiting for the guest to respond. If the guest doesn't shut down within the timeout, it is forcefully killed. Returns nil on successful shutdown, or an error if force stop was required.
func (*Instance) StopContext ¶
StopContext performs a graceful shutdown with context support. It sends an ACPI power button event (system_powerdown) and waits for the guest to shut down. If the guest doesn't respond within the timeout, it forcefully terminates the QEMU process.
type MachineConfig ¶
type MachineConfig struct {
// Type is the machine type (e.g., "q35", "pc", "virt").
Type string
// Accel is the accelerator (e.g., "kvm", "tcg", "hvf").
Accel string
// USB enables/disables USB controller creation by machine.
USB *bool
// DumpGuestCore enables/disables guest core dumps.
DumpGuestCore *bool
// Pflash0 is the node name for pflash0 (EFI code).
Pflash0 string
// Pflash1 is the node name for pflash1 (EFI vars).
Pflash1 string
}
MachineConfig configures the virtual machine type.
type MemoryBackendConfig ¶
type MemoryBackendConfig struct {
// Type is the backend type ("file", "memfd", "ram").
Type string
// Path is the file path for file-backed memory.
Path string
Share bool
// Prealloc preallocates memory.
Prealloc bool
}
MemoryBackendConfig configures a memory backend.
type MemoryConfig ¶
type MemoryConfig struct {
// Size is the memory size in megabytes.
Size int
// Backend configures memory backend (optional).
Backend *MemoryBackendConfig
// MemLock controls memory locking ("on", "off").
MemLock string
}
MemoryConfig configures the virtual machine memory.
type NBDDiskBackend ¶
type NBDDiskBackend struct {
// SocketPath is the Unix socket path.
SocketPath string
// Host is the TCP host (alternative to socket).
Host string
// Port is the TCP port.
Port int
// Export is the NBD export name.
Export string
// TLS enables TLS.
TLS bool
// TLSCreds is the TLS credentials ID.
TLSCreds string
}
NBDDiskBackend represents an NBD-connected disk.
func (*NBDDiskBackend) BuildBlockdevArgs ¶
func (n *NBDDiskBackend) BuildBlockdevArgs(id string) []string
func (*NBDDiskBackend) Type ¶
func (n *NBDDiskBackend) Type() string
type NetDevConfig ¶
type NetDevConfig struct {
// Type is the network type (e.g., "user", "tap", "socket").
Type string
// ID is the unique identifier for this network device.
ID string
// Model is the NIC model (e.g., "virtio", "e1000", "rtl8139").
// Defaults to "virtio".
Model string
// MACAddr is the MAC address.
MACAddr string
// Bridge is the bridge to connect to (for tap devices).
Bridge string
// Script is the interface up script path (for tap devices).
// Use "no" to disable.
Script string
// DownScript is the interface down script path.
// Use "no" to disable.
DownScript string
// SocketPath is the Unix socket path (for socket devices).
SocketPath string
}
NetDevConfig configures a network device.
type NetworkBackend ¶
type NetworkBackend interface {
// Type returns the backend type name.
Type() string
// BuildNetdevArgs builds the netdev arguments.
BuildNetdevArgs(id string) []string
}
NetworkBackend is the interface for network backends.
type NetworkConfig ¶
type NetworkConfig struct {
// ID is the netdev/device ID.
ID string
// Backend configures the network backend.
Backend NetworkBackend
// Model is the NIC model ("virtio-net-pci", "e1000", "rtl8139").
Model string
// MACAddr is the MAC address.
MACAddr string
// BootIndex sets the boot priority for network boot.
BootIndex int
}
NetworkConfig configures a network device.
type QMP ¶
type QMP struct {
// contains filtered or unexported fields
}
QMP handles the QEMU Monitor Protocol connection.
func (*QMP) ExecuteWithFd ¶
ExecuteWithFd sends a QMP command with a file descriptor via SCM_RIGHTS.
func (*QMP) ExecuteWithTimeout ¶
func (q *QMP) ExecuteWithTimeout(command string, args map[string]any, timeout time.Duration) (json.RawMessage, error)
ExecuteWithTimeout sends a QMP command with a custom timeout.
func (*QMP) SetEventCallback ¶
SetEventCallback sets a callback for all events.
func (*QMP) SetStateChangeCallback ¶
SetStateChangeCallback sets a callback for state changes.
type RBDDiskBackend ¶
type RBDDiskBackend struct {
// Pool is the RBD pool name.
Pool string
// Image is the RBD image name.
Image string
// Snapshot is the snapshot name (optional).
Snapshot string
// Conf is the path to ceph.conf.
Conf string
// User is the Ceph user name.
User string
// KeySecret is the secret ID for the key.
KeySecret string
// AuthClientRequired is the auth method list.
AuthClientRequired []string
}
RBDDiskBackend represents a Ceph RBD disk.
func (*RBDDiskBackend) BuildBlockdevArgs ¶
func (r *RBDDiskBackend) BuildBlockdevArgs(id string) []string
func (*RBDDiskBackend) Type ¶
func (r *RBDDiskBackend) Type() string
type RTCConfig ¶
type RTCConfig struct {
// Base is the RTC base ("utc", "localtime", datetime).
Base string
// Clock is the clock source ("host", "rt", "vm").
Clock string
// DriftFix is the drift fix mode ("slew", "none").
DriftFix string
}
RTCConfig configures the real-time clock.
type SecretConfig ¶
type SecretConfig struct {
// ID is the secret ID.
ID string
// Data is the raw secret data.
Data string
// File is the path to secret file.
File string
// Format is the secret format ("raw", "base64").
Format string
}
SecretConfig configures a secret object.
type SerialConfig ¶
type SerialConfig struct {
// Type is the chardev type ("socket", "pty", "file", "pipe").
Type string
// Path is the socket/file/pipe path.
Path string
// Server makes the socket a server.
Server bool
// Wait waits for client connection.
Wait bool
// Device is the serial device type ("isa-serial", "usb-serial", "virtio-serial").
Device string
}
SerialConfig configures a serial port.
type SocketNetBackend ¶
type SocketNetBackend struct {
// Path is the Unix socket path.
Path string
// Server makes this end the server.
Server bool
// Reconnect interval in seconds (client mode).
Reconnect int
}
SocketNetBackend provides socket-based networking.
func (*SocketNetBackend) BuildNetdevArgs ¶
func (s *SocketNetBackend) BuildNetdevArgs(id string) []string
func (*SocketNetBackend) Type ¶
func (s *SocketNetBackend) Type() string
type SpiceConfig ¶
type SpiceConfig struct {
// UnixSocket uses a Unix socket instead of TCP.
UnixSocket bool
// Password is the SPICE password.
Password string
// DisableTicketing disables password authentication.
DisableTicketing bool
// ImageCompression sets the image compression mode.
ImageCompression string
// PlaybackCompression enables audio playback compression.
PlaybackCompression bool
}
SpiceConfig configures SPICE display.
type SpiceDisplayConfig ¶
type SpiceDisplayConfig struct {
// Unix uses Unix socket instead of TCP.
Unix bool
// Port is the TCP port (0 for none).
Port int
// Password is the SPICE password.
Password string
// PasswordSecret is the secret ID for password.
PasswordSecret string
// DisableTicketing disables password authentication.
DisableTicketing bool
// ImageCompression sets image compression mode.
ImageCompression string
// JpegWanCompression sets JPEG WAN compression.
JpegWanCompression string
// ZlibGlzWanCompression sets zlib-glz WAN compression.
ZlibGlzWanCompression string
// PlaybackCompression enables audio playback compression.
PlaybackCompression bool
// SeamlessMigration enables seamless migration.
SeamlessMigration bool
// DisableCopyPaste disables copy-paste.
DisableCopyPaste bool
}
SpiceDisplayConfig configures SPICE display.
type State ¶
type State int
State represents the current state of a QEMU instance.
type StreamNetBackend ¶
type StreamNetBackend struct {
// Path is the Unix socket path.
Path string
// Host is the TCP host.
Host string
// Port is the TCP port.
Port int
// Server makes this end the server.
Server bool
// Reconnect interval in seconds (client mode).
Reconnect int
}
StreamNetBackend provides stream socket networking (QEMU 7.2+).
func (*StreamNetBackend) BuildNetdevArgs ¶
func (s *StreamNetBackend) BuildNetdevArgs(id string) []string
func (*StreamNetBackend) Type ¶
func (s *StreamNetBackend) Type() string
type TapNetBackend ¶
type TapNetBackend struct {
// Ifname is the TAP interface name.
Ifname string
// Bridge is the bridge to attach to.
Bridge string
// Script is the interface up script ("no" to disable).
Script string
// DownScript is the interface down script ("no" to disable).
DownScript string
// VHost enables vhost-net acceleration.
VHost bool
// Queues is the number of queues (for multiqueue).
Queues int
// FD is a pre-opened TAP file descriptor.
FD int
}
TapNetBackend provides TAP device networking.
func (*TapNetBackend) BuildNetdevArgs ¶
func (t *TapNetBackend) BuildNetdevArgs(id string) []string
func (*TapNetBackend) Type ¶
func (t *TapNetBackend) Type() string
type ThrottleConfig ¶
type ThrottleConfig struct {
// Group is the throttle group name.
Group string
// BPS is the total bytes per second limit.
BPS uint64
// BPSRead is the read bytes per second limit.
BPSRead uint64
// BPSWrite is the write bytes per second limit.
BPSWrite uint64
// IOPS is the total I/O operations per second limit.
IOPS uint64
// IOPSRead is the read IOPS limit.
IOPSRead uint64
// IOPSWrite is the write IOPS limit.
IOPSWrite uint64
// BPSMax is the burst BPS limit.
BPSMax uint64
// IOPSMax is the burst IOPS limit.
IOPSMax uint64
// BurstLength is the burst duration in seconds.
BurstLength int
}
ThrottleConfig configures I/O throttling.
func (*ThrottleConfig) BuildThrottleBlockdevArgs ¶
func (t *ThrottleConfig) BuildThrottleBlockdevArgs(id, fileNode string) []string
BuildThrottleBlockdevArgs builds throttle filter blockdev arguments.
func (*ThrottleConfig) BuildThrottleGroupArgs ¶
func (t *ThrottleConfig) BuildThrottleGroupArgs() []string
BuildThrottleGroupArgs builds throttle-group object arguments.
type USBControllerConfig ¶
type USBControllerConfig struct {
// Type is the controller type ("qemu-xhci", "nec-usb-xhci", "ich9-usb-uhci1").
Type string
}
USBControllerConfig configures USB controller.
type USBDeviceConfig ¶
type USBDeviceConfig struct {
// Type is the device type ("usb-tablet", "usb-mouse", "usb-kbd", "usb-redir").
Type string
// Chardev is the chardev ID (for usb-redir, usb-serial).
Chardev string
}
USBDeviceConfig configures a USB device.
type UnsupportedArchError ¶
type UnsupportedArchError struct {
Arch string
}
UnsupportedArchError is returned when the architecture is not supported.
func (*UnsupportedArchError) Error ¶
func (e *UnsupportedArchError) Error() string
type UserNetBackend ¶
type UserNetBackend struct {
// Hostfwd configures port forwarding (e.g., "tcp::2222-:22").
Hostfwd []string
// Net is the guest network (e.g., "10.0.2.0/24").
Net string
// Host is the host address in guest network.
Host string
// DNS is the DNS server address.
DNS string
// DHCPStart is the first DHCP address.
DHCPStart string
// Restrict isolates guest from host.
Restrict bool
}
UserNetBackend provides user-mode networking (NAT).
func (*UserNetBackend) BuildNetdevArgs ¶
func (u *UserNetBackend) BuildNetdevArgs(id string) []string
func (*UserNetBackend) Type ¶
func (u *UserNetBackend) Type() string
type VDENetBackend ¶
type VDENetBackend struct {
// Sock is the VDE socket path.
Sock string
// Port is the VDE port number.
Port int
// Group is the VDE group.
Group string
// Mode is the VDE socket mode.
Mode string
}
VDENetBackend provides VDE networking.
func (*VDENetBackend) BuildNetdevArgs ¶
func (v *VDENetBackend) BuildNetdevArgs(id string) []string
func (*VDENetBackend) Type ¶
func (v *VDENetBackend) Type() string
type VMBuilder ¶
type VMBuilder struct {
// contains filtered or unexported fields
}
VMBuilder builds QEMU command-line arguments from VMConfig.
func NewVMBuilder ¶
NewVMBuilder creates a new VM builder.
type VMConfig ¶
type VMConfig struct {
// Name is the VM name.
Name string
// Arch is the target architecture (GOARCH-style).
Arch string
// QemuPath overrides the QEMU binary path.
QemuPath string
// SocketDir overrides the socket directory.
SocketDir string
// Machine configures the machine type.
Machine *MachineConfig
// CPU configures the virtual CPU.
CPU *CPUConfig
// Memory configures the memory.
Memory *MemoryConfig
// EFI configures UEFI firmware.
EFI *EFIConfig
// Boot configures boot options.
Boot *BootConfig
// Disks is the list of disk configurations.
Disks []*DiskConfig
// CDROMs is the list of CD-ROM drives.
CDROMs []*CDROMConfig
// Networks is the list of network configurations.
Networks []*NetworkConfig
// Display configures display output.
Display *DisplayConfig
// Audio configures audio device.
Audio *AudioConfig
// Serials is the list of serial port configurations.
Serials []*SerialConfig
// Chardevs is the list of character devices.
Chardevs []*ChardevConfig
// VirtioSerial configures virtio-serial.
VirtioSerial *VirtioSerialConfig
// USB configures USB controller.
USB *USBControllerConfig
// USBDevices is the list of USB devices.
USBDevices []*USBDeviceConfig
// Balloon configures memory balloon.
Balloon *BalloonConfig
// RTC configures real-time clock.
RTC *RTCConfig
// Secrets is the list of secret objects.
Secrets []*SecretConfig
// NoDefaults disables QEMU's default devices.
NoDefaults bool
// ExtraArgs are additional command-line arguments.
ExtraArgs []string
}
VMConfig is a comprehensive VM configuration.
func DefaultVMConfig ¶
func DefaultVMConfig() *VMConfig
DefaultVMConfig returns a VMConfig with sensible defaults.
func (*VMConfig) WithGuestAgent ¶
WithGuestAgent adds a guest agent chardev and virtio-serial port.
func (*VMConfig) WithSpiceAgent ¶
WithSpiceAgent adds a SPICE agent chardev and virtio-serial port.
func (*VMConfig) WithUSBTablet ¶
WithUSBTablet adds a USB tablet device for better mouse handling.
type VNCConfig ¶
type VNCConfig struct {
// Listen is the listen address (e.g., ":0", "127.0.0.1:5900", "none").
// Use "none" for add_client mode.
Listen string
// Password is the VNC password (use PasswordSecret for security).
Password string
// PasswordSecret is the secret ID for password.
PasswordSecret string
// Lossy enables lossy compression.
Lossy bool
// AudioDev is the audio device ID for VNC audio.
AudioDev string
// Websocket enables websocket support on given port.
Websocket int
}
VNCConfig configures VNC display.
type VideoConfig ¶
type VideoConfig struct {
// Type is the video device type ("qxl-vga", "virtio-vga", "vga", "cirrus").
Type string
// VgaMem is VGA memory size in MB.
VgaMem int
// Ram is video RAM size in bytes (for QXL).
Ram int
// Vram is video VRAM size in bytes (for QXL).
Vram int
// MaxOutputs is maximum number of outputs.
MaxOutputs int
}
VideoConfig configures video device.
type VirtioSerialConfig ¶
type VirtioSerialConfig struct {
// MaxPorts is maximum number of ports.
MaxPorts int
// Ports is the list of serial ports.
Ports []VirtioSerialPortConfig
}
VirtioSerialConfig configures virtio-serial device.
type VirtioSerialPortConfig ¶
type VirtioSerialPortConfig struct {
// Chardev is the chardev ID.
Chardev string
// Name is the port name (e.g., "org.qemu.guest_agent.0").
Name string
// Type is the port type ("virtserialport", "virtconsole").
Type string
}
VirtioSerialPortConfig configures a virtio-serial port.