qemuctl

package module
v0.0.0-...-e15a332 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 19 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.

README

qemuctl

A Go library for managing QEMU virtual machines via QMP (QEMU Monitor Protocol).

Features

  • Launch QEMU instances with comprehensive configuration
  • Attach to existing QEMU processes by socket path or PID
  • Full QMP support for VM control (start, stop, pause, reset, etc.)
  • VNC/SPICE client passthrough via SCM_RIGHTS file descriptor passing
  • Event handling with callbacks for state changes
  • Automatic QEMU discovery in PATH or standard locations
  • Architecture support using GOARCH-style names (amd64, arm64, etc.)
  • Multiple disk backends (file, NBD, RBD/Ceph, iSCSI)
  • Multiple network backends (user NAT, TAP, socket, stream, VDE, bridge)
  • I/O throttling with configurable BPS/IOPS limits
  • EFI/UEFI support with OVMF firmware
  • Guest agent support via virtio-serial
  • Automatic PCI slot allocation for Q35 and i440FX machines

Installation

go get github.com/KarpelesLab/qemuctl

Quick Start

Simple VM (Basic Config)
package main

import (
    "log"
    "time"

    "github.com/KarpelesLab/qemuctl"
)

func main() {
    cfg := qemuctl.DefaultConfig()
    cfg.Name = "my-vm"
    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)

    log.Printf("VM started with PID %d", inst.PID())
    log.Printf("State: %s", inst.State())

    // Wait for VM to exit
    inst.Wait()
}
Advanced VM (VMConfig)

For full control over VM configuration, use VMConfig and StartVM:

package main

import (
    "log"
    "time"

    "github.com/KarpelesLab/qemuctl"
)

func main() {
    cfg := &qemuctl.VMConfig{
        Name: "production-vm",
        Machine: &qemuctl.MachineConfig{
            Type:  "q35",
            Accel: "kvm",
        },
        CPU: &qemuctl.CPUConfig{
            Model:   "host",
            Sockets: 1,
            Cores:   4,
            Threads: 2,
        },
        Memory: &qemuctl.MemoryConfig{
            Size: 8192, // 8GB
        },
        EFI: &qemuctl.EFIConfig{
            Code: "/usr/share/OVMF/OVMF_CODE.fd",
            Vars: "/var/lib/qemu/my-vm_VARS.fd",
        },
        Disks: []*qemuctl.DiskConfig{
            {
                ID: "system",
                Backend: &qemuctl.FileDiskBackend{
                    Path:   "/var/lib/qemu/system.qcow2",
                    Format: "qcow2",
                },
                Interface: "virtio",
                BootIndex: 1,
            },
        },
        Networks: []*qemuctl.NetworkConfig{
            {
                ID: "net0",
                Backend: &qemuctl.UserNetBackend{
                    Hostfwd: []string{"tcp::2222-:22"},
                },
                Model:   "virtio-net-pci",
                MACAddr: "52:54:00:12:34:56",
            },
        },
        Display: &qemuctl.DisplayConfig{
            Type: "vnc",
            VNC: &qemuctl.VNCConfig{
                Listen: "none", // Use add_client mode
            },
        },
        NoDefaults: true,
    }

    // Add guest agent support
    cfg.WithGuestAgent("/var/run/qemu/my-vm-qga.sock")

    // Add USB tablet for better mouse handling
    cfg.WithUSBTablet()

    inst, err := qemuctl.StartVM(cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer inst.Stop(30 * time.Second)

    log.Printf("VM started with PID %d", inst.PID())
}
Attach to Existing VM
// By socket path
inst, err := qemuctl.Attach("/var/run/qemu/my-vm.sock")

// By PID (automatically finds the QMP socket from process arguments)
inst, err := qemuctl.AttachByPID(12345)
VM Control
// Pause and resume
inst.Pause()
inst.Continue()

// Reset (hard reboot)
inst.Reset()

// Graceful shutdown (sends ACPI power button)
inst.Shutdown()

// Graceful shutdown with timeout, then force kill
inst.Stop(30 * time.Second)

// Force kill immediately
inst.ForceStop()

// Send quit command to QEMU
inst.Quit()
VNC/SPICE Client Passthrough

Pass incoming client connections directly to QEMU:

// Accept a client connection from your proxy/server
clientConn, _ := listener.Accept()

// Pass it to QEMU for VNC (skipAuth=true to skip VNC auth)
err := inst.AddVNCClient(clientConn, true)

// Or for SPICE
err := inst.AddSpiceClient(clientConn, false)

Set display passwords:

inst.SetVNCPassword("secret123")
inst.SetSpicePassword("secret123")
Event Handling
// Set callback for state changes
inst.SetStateChangeCallback(func(state qemuctl.State) {
    log.Printf("State changed to: %s", state)
})

// Set callback for all events
inst.SetEventCallback(func(event *qemuctl.Event) {
    log.Printf("Event: %s, Data: %v", event.Name, event.Data)
})

// Or read from event channel
go func() {
    for event := range inst.Events() {
        log.Printf("Event: %s", event.Name)
    }
}()
Direct QMP Commands
// Execute any QMP command
result, err := inst.QMP().Execute("query-version", nil)

// Human monitor command (for commands not in QMP)
output, err := inst.HumanMonitorCommand("info registers")
Utility Functions
// Query block devices
blocks, err := inst.QueryBlockDevices()

// Set I/O throttling
err := inst.SetIOThrottle("drive0", 100*1024*1024, 1000) // 100MB/s, 1000 IOPS

// Capture screenshot
err := inst.Screendump("/tmp/screen.ppm")

// Send key combination
err := inst.SendKey("ctrl", "alt", "delete")

Disk Backends

File Backend
backend := &qemuctl.FileDiskBackend{
    Path:         "/var/lib/qemu/disk.qcow2",
    Format:       "qcow2", // or "raw", "vmdk"
    AutoReadOnly: true,
}
NBD Backend
// Unix socket
backend := &qemuctl.NBDDiskBackend{
    SocketPath: "/tmp/nbd.sock",
    Export:     "disk0",
}

// TCP
backend := &qemuctl.NBDDiskBackend{
    Host:   "192.168.1.100",
    Port:   10809,
    Export: "disk0",
    TLS:    true,
}
Ceph RBD Backend
backend := &qemuctl.RBDDiskBackend{
    Pool:      "rbd",
    Image:     "vm-disk-0",
    User:      "admin",
    KeySecret: "ceph-key", // Reference to a secret object
    Conf:      "/etc/ceph/ceph.conf",
}
iSCSI Backend
backend := &qemuctl.ISCSIDiskBackend{
    Portal:         "192.168.1.100:3260",
    Target:         "iqn.2023-01.com.example:storage",
    Lun:            0,
    User:           "admin",
    PasswordSecret: "iscsi-password",
    InitiatorName:  "iqn.2023-01.com.example:client",
}
I/O Throttling
disk := &qemuctl.DiskConfig{
    ID:      "drive0",
    Backend: backend,
    Throttle: &qemuctl.ThrottleConfig{
        Group:    "tg0",
        BPS:      100 * 1024 * 1024, // 100 MB/s
        IOPS:     1000,
        BPSMax:   200 * 1024 * 1024, // Burst: 200 MB/s
        IOPSMax:  2000,
    },
}

Network Backends

User Mode (NAT)
backend := &qemuctl.UserNetBackend{
    Hostfwd: []string{
        "tcp::2222-:22",  // SSH
        "tcp::8080-:80",  // HTTP
    },
    Net:      "10.0.2.0/24",
    DNS:      "10.0.2.3",
    Restrict: false,
}
TAP Device
backend := &qemuctl.TapNetBackend{
    Ifname:     "tap0",
    Bridge:     "br0",
    Script:     "no",     // Or path to up script
    DownScript: "no",
    VHost:      true,     // Enable vhost-net
    Queues:     4,        // Multiqueue
}
Socket Backend
backend := &qemuctl.SocketNetBackend{
    Path:   "/tmp/vm-network.sock",
    Server: true,
}
Stream Backend (QEMU 7.2+)
// Unix socket
backend := &qemuctl.StreamNetBackend{
    Path:   "/tmp/stream.sock",
    Server: true,
}

// TCP with reconnect
backend := &qemuctl.StreamNetBackend{
    Host:      "192.168.1.1",
    Port:      5000,
    Server:    false,
    Reconnect: 10, // Reconnect every 10 seconds
}
Bridge Helper
backend := &qemuctl.BridgeNetBackend{
    Bridge: "br0",
    Helper: "/usr/lib/qemu/qemu-bridge-helper",
}

Display Configuration

VNC
display := &qemuctl.DisplayConfig{
    Type: "vnc",
    VNC: &qemuctl.VNCConfig{
        Listen:         "none",  // Use add_client mode
        PasswordSecret: "vnc-pw",
        Lossy:          true,
        Websocket:      5901,
    },
    Video: &qemuctl.VideoConfig{
        Type:   "virtio-vga",
        VgaMem: 64,
    },
}
SPICE
display := &qemuctl.DisplayConfig{
    Type: "spice",
    Spice: &qemuctl.SpiceDisplayConfig{
        Unix:                true,
        DisableTicketing:    false,
        PasswordSecret:      "spice-pw",
        ImageCompression:    "auto_glz",
        PlaybackCompression: true,
        SeamlessMigration:   true,
    },
    Video: &qemuctl.VideoConfig{
        Type:   "qxl-vga",
        VgaMem: 64,
        Ram:    128 * 1024 * 1024,
        Vram:   128 * 1024 * 1024,
    },
}

// Add SPICE agent for copy/paste
cfg.WithSpiceAgent()

Configuration Reference

Basic Config Options
Field Type Description
Name string Instance name (auto-generated if empty)
Arch string Target architecture (GOARCH-style)
QemuPath string Path to QEMU binary (auto-detected if empty)
SocketDir string Directory for control sockets
Memory int Memory in MB (default: 512)
CPUs int Number of vCPUs (default: 1)
Machine string Machine type (e.g., "q35", "pc", "virt")
CPU string CPU model (default: "host" with KVM)
KVM *bool Enable KVM acceleration (default: true)
NoDefaults *bool Disable QEMU default devices (default: true)
VMConfig Options
Field Type Description
Machine *MachineConfig Machine type, accelerator, pflash
CPU *CPUConfig CPU model, features, topology
Memory *MemoryConfig Size, backend, memory locking
EFI *EFIConfig UEFI firmware (OVMF) configuration
Boot *BootConfig Boot order, kernel, initrd
Disks []*DiskConfig Disk configurations with backends
CDROMs []*CDROMConfig CD-ROM drives
Networks []*NetworkConfig Network configurations
Display *DisplayConfig VNC, SPICE, video device
Audio *AudioConfig Sound device and backend
Serials []*SerialConfig Serial ports
Chardevs []*ChardevConfig Character devices
VirtioSerial *VirtioSerialConfig Virtio-serial controller
USB *USBControllerConfig USB controller
USBDevices []*USBDeviceConfig USB devices
Balloon *BalloonConfig Memory balloon
RTC *RTCConfig Real-time clock
Secrets []*SecretConfig Secret objects
Socket Locations

Control sockets are created in:

  • Root: /var/run/qemu/<name>.sock
  • User: <os.UserCacheDir()>/qemuctl/<name>.sock

Override with Config.SocketDir or VMConfig.SocketDir.

QEMU Binary Discovery

The library searches for QEMU in this order:

  1. Config.QemuPath if provided
  2. PATH environment variable
  3. /pkg/main/app-emulation.qemu.core/bin/
  4. /usr/bin, /usr/local/bin

States

State Description
StateUnknown Unknown state
StateRunning VM is running
StatePaused VM is paused
StateShutdown VM has shut down
StateCrashed VM has crashed
StateSuspended VM is suspended
StatePrelaunch VM is initializing

Architecture Mapping

GOARCH QEMU Binary
amd64 qemu-system-x86_64
386 qemu-system-i386
arm64 qemu-system-aarch64
arm qemu-system-arm
riscv64 qemu-system-riscv64
ppc64/ppc64le qemu-system-ppc64
mips qemu-system-mips
mips64 qemu-system-mips64
s390x qemu-system-s390x

License

See LICENSE file.

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:

  1. Config.QemuPath if provided
  2. PATH environment variable
  3. /pkg/main/app-emulation.qemu.core/bin/
  4. 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

Constants

This section is empty.

Variables

View Source
var (
	ErrNotConnected = errors.New("not connected to QEMU")
	ErrNotRunning   = errors.New("QEMU process not running")
)

Common errors.

View Source
var ErrQemuNotFound = errors.New("QEMU binary not found")

ErrQemuNotFound is returned when QEMU cannot be located.

Functions

func LocateQemu

func LocateQemu(arch string, customPath string) (string, error)

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

func QemuArchName(goarch string) (string, bool)

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration and returns an error if invalid.

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 Event

type Event struct {
	Name      string
	Data      map[string]any
	Timestamp time.Time
}

Event represents a QMP event from QEMU.

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 Attach

func Attach(socketPath string) (*Instance, error)

Attach connects to an existing QEMU instance by its control socket.

func AttachByPID

func AttachByPID(pid int) (*Instance, error)

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

func AttachByPIDContext(ctx context.Context, pid int) (*Instance, error)

AttachByPIDContext connects to an existing QEMU instance by PID with context.

func AttachContext

func AttachContext(ctx context.Context, socketPath string) (*Instance, error)

AttachContext connects to an existing QEMU instance with context support.

func Start

func Start(cfg *Config) (*Instance, error)

Start launches a new QEMU instance with the given configuration.

func StartContext

func StartContext(ctx context.Context, cfg *Config) (*Instance, error)

StartContext launches a new QEMU instance with context support.

func StartVM

func StartVM(cfg *VMConfig) (*Instance, error)

StartVM launches a QEMU instance using VMConfig.

func StartVMContext

func StartVMContext(ctx context.Context, cfg *VMConfig) (*Instance, error)

StartVMContext launches a QEMU instance with context support.

func (*Instance) AddSpiceClient

func (i *Instance) AddSpiceClient(conn net.Conn, skipAuth bool) error

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

func (i *Instance) AddVNCClient(conn net.Conn, skipAuth bool) error

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) Continue

func (i *Instance) Continue() error

Continue resumes a paused VM.

func (*Instance) Events

func (i *Instance) Events() <-chan *Event

Events returns the event channel.

func (*Instance) ExpireSpicePassword

func (i *Instance) ExpireSpicePassword(expireTime string) error

ExpireSpicePassword expires the SPICE password at a given time.

func (*Instance) ExpireVNCPassword

func (i *Instance) ExpireVNCPassword(expireTime string) error

ExpireVNCPassword expires the VNC password at a given time. Use "now" to expire immediately, "never" for no expiration.

func (*Instance) ForceStop

func (i *Instance) ForceStop() error

ForceStop immediately terminates the QEMU process.

func (*Instance) HumanMonitorCommand

func (i *Instance) HumanMonitorCommand(cmd string) (string, error)

HumanMonitorCommand executes a human monitor command. This is useful for commands not exposed via QMP.

func (*Instance) Name

func (i *Instance) Name() string

Name returns the instance name.

func (*Instance) PID

func (i *Instance) PID() int

PID returns the process ID of the QEMU process.

func (*Instance) Pause

func (i *Instance) Pause() error

Pause pauses a running VM.

func (*Instance) QMP

func (i *Instance) QMP() *QMP

QMP returns the QMP connection for direct command execution.

func (*Instance) QueryBlockDevices

func (i *Instance) QueryBlockDevices() ([]BlockInfo, error)

QueryBlockDevices returns information about all block devices.

func (*Instance) QueryState

func (i *Instance) QueryState() error

QueryState queries and updates the current state from QEMU.

func (*Instance) Quit

func (i *Instance) Quit() error

Quit sends the quit command to QEMU (immediate exit).

func (*Instance) Reset

func (i *Instance) Reset() error

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

func (i *Instance) Screendump(filename string) error

Screendump captures the screen to a file.

func (*Instance) SendKey

func (i *Instance) SendKey(keys ...string) error

SendKey sends a key event to the guest. Keys should be in QEMU key format (e.g., "ctrl-alt-delete").

func (*Instance) SetEventCallback

func (i *Instance) SetEventCallback(cb func(*Event))

SetEventCallback sets a callback for all events.

func (*Instance) SetIOThrottle

func (i *Instance) SetIOThrottle(device string, bps, iops uint64) error

SetIOThrottle sets I/O throttling for a block device.

func (*Instance) SetSpicePassword

func (i *Instance) SetSpicePassword(password string) error

SetSpicePassword sets the SPICE password.

func (*Instance) SetStateChangeCallback

func (i *Instance) SetStateChangeCallback(cb func(State))

SetStateChangeCallback sets a callback for state changes.

func (*Instance) SetVNCPassword

func (i *Instance) SetVNCPassword(password string) error

SetVNCPassword sets the VNC password.

func (*Instance) Shutdown

func (i *Instance) Shutdown() error

Shutdown sends a powerdown request to the guest (ACPI power button). Unlike Stop, this does not wait or force kill.

func (*Instance) SocketPath

func (i *Instance) SocketPath() string

SocketPath returns the path to the QMP control socket.

func (*Instance) State

func (i *Instance) State() State

State returns the current state of the instance.

func (*Instance) Stop

func (i *Instance) Stop(timeout time.Duration) error

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

func (i *Instance) StopContext(ctx context.Context, timeout time.Duration) error

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.

func (*Instance) Wait

func (i *Instance) Wait() error

Wait waits for the QEMU process to exit.

func (*Instance) WaitContext

func (i *Instance) WaitContext(ctx context.Context) error

WaitContext waits for the QEMU process with context support.

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 enables memory sharing with other processes.
	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) Close

func (q *QMP) Close() error

Close closes the QMP connection.

func (*QMP) Events

func (q *QMP) Events() <-chan *Event

Events returns the event channel.

func (*QMP) Execute

func (q *QMP) Execute(command string, args map[string]any) (json.RawMessage, error)

Execute sends a QMP command and waits for the response.

func (*QMP) ExecuteWithFd

func (q *QMP) ExecuteWithFd(command string, args map[string]any, fd int) (json.RawMessage, error)

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

func (q *QMP) SetEventCallback(cb func(*Event))

SetEventCallback sets a callback for all events.

func (*QMP) SetStateChangeCallback

func (q *QMP) SetStateChangeCallback(cb func(State))

SetStateChangeCallback sets a callback for state changes.

type QMPError

type QMPError struct {
	Class       string
	Description string
}

QMPError is returned when QEMU reports an error.

func (*QMPError) Error

func (e *QMPError) Error() string

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.

const (
	StateUnknown State = iota
	StateRunning
	StatePaused
	StateShutdown
	StateCrashed
	StateSuspended
	StatePrelaunch // VM is being initialized but not yet running
)

func (State) IsAlive

func (s State) IsAlive() bool

IsAlive returns true if the state indicates the VM is alive (running or paused).

func (State) String

func (s State) String() string

String returns the string representation of the state.

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

func NewVMBuilder(cfg *VMConfig) *VMBuilder

NewVMBuilder creates a new VM builder.

func (*VMBuilder) Build

func (b *VMBuilder) Build(name, socketPath string) []string

Build builds the complete QEMU command-line arguments.

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) ToConfig

func (cfg *VMConfig) ToConfig() *Config

ToConfig converts VMConfig to the simpler Config for Start().

func (*VMConfig) WithGuestAgent

func (cfg *VMConfig) WithGuestAgent(socketPath string) *VMConfig

WithGuestAgent adds a guest agent chardev and virtio-serial port.

func (*VMConfig) WithSpiceAgent

func (cfg *VMConfig) WithSpiceAgent() *VMConfig

WithSpiceAgent adds a SPICE agent chardev and virtio-serial port.

func (*VMConfig) WithUSBTablet

func (cfg *VMConfig) WithUSBTablet() *VMConfig

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.

Jump to

Keyboard shortcuts

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