hypervisor

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 6 Imported by: 0

README

Hypervisor Abstraction

Provides a common interface for VM management across different hypervisors.

Purpose

Hypeman originally supported only Cloud Hypervisor. This abstraction layer allows supporting multiple hypervisors through a unified interface, enabling:

  • Hypervisor choice per instance - Different instances can use different hypervisors
  • Platform support - Linux uses Cloud Hypervisor/QEMU, macOS uses Virtualization.framework
  • Feature parity where possible - Common operations work the same way
  • Graceful degradation - Features unsupported by a hypervisor can be detected and handled

Implementations

Hypervisor Platform Process Model Control Interface
Cloud Hypervisor Linux External process HTTP API over Unix socket
Firecracker Linux External process HTTP API over Unix socket
QEMU Linux External process QMP over Unix socket
vz macOS Subprocess (vz-shim) HTTP API over Unix socket

How It Works

The abstraction defines two key interfaces:

  1. Hypervisor - VM lifecycle operations (create, boot, pause, resume, snapshot, restore, shutdown)
  2. VMStarter - VM startup and configuration (start binary, get binary path)

Each implementation translates generic configuration to its native format. Cloud Hypervisor and QEMU run as external processes with socket-based control. The vz implementation runs VMs as separate vz-shim subprocesses using Apple's Virtualization.framework.

Before using optional features, callers check capabilities:

if hv.Capabilities().SupportsSnapshot {
    hv.Snapshot(ctx, path)
}

Platform Differences

Linux (Cloud Hypervisor, QEMU)
  • VMs run as separate processes with PIDs
  • State persists across hypeman restarts (reconnect via socket)
  • TAP devices and Linux bridges for networking
macOS (vz)
  • VMs run as separate vz-shim subprocesses (detached process group)
  • State persists across hypeman restarts (reconnect via socket)
  • NAT networking via Virtualization.framework
  • Requires code signing with virtualization entitlement

Hypervisor Switching

Instances store their hypervisor type in metadata. An instance can switch hypervisors only when stopped (no running VM, no snapshot), since:

  • Disk images are hypervisor-agnostic
  • Snapshots are hypervisor-specific and cannot be restored by a different hypervisor

Documentation

Overview

Package hypervisor provides an abstraction layer for virtual machine managers. This allows the instances package to work with different hypervisors (e.g., Cloud Hypervisor, QEMU) through a common interface.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrHypervisorNotRunning is returned when trying to connect to a hypervisor
	// that is not currently running or cannot be reconnected to.
	ErrHypervisorNotRunning = errors.New("hypervisor is not running")

	// ErrNotSupported is returned when an operation is not supported by the hypervisor.
	ErrNotSupported = errors.New("operation not supported by this hypervisor")
)

Common errors

Functions

func RegisterClientFactory added in v0.0.6

func RegisterClientFactory(t Type, factory ClientFactory)

RegisterClientFactory registers a Hypervisor client factory.

func RegisterSocketName

func RegisterSocketName(t Type, name string)

RegisterSocketName registers the socket filename for a hypervisor type. Called by each hypervisor implementation's init() function.

func RegisterVsockDialerFactory

func RegisterVsockDialerFactory(t Type, factory VsockDialerFactory)

RegisterVsockDialerFactory registers a VsockDialer factory for a hypervisor type. Called by each hypervisor implementation's init() function.

func RegisterVsockSocketName added in v0.0.7

func RegisterVsockSocketName(t Type, name string)

RegisterVsockSocketName registers the vsock socket filename for a hypervisor type.

func SocketNameForType

func SocketNameForType(t Type) string

SocketNameForType returns the socket filename for a hypervisor type. Falls back to type + ".sock" if not registered.

func VsockSocketNameForType added in v0.0.7

func VsockSocketNameForType(t Type) string

VsockSocketNameForType returns the vsock socket filename for a hypervisor type. Falls back to "vsock.sock" when a hypervisor doesn't require a custom name.

Types

type CPUTopology

type CPUTopology struct {
	ThreadsPerCore int
	CoresPerDie    int
	DiesPerPackage int
	Packages       int
}

CPUTopology defines the virtual CPU topology

type Capabilities

type Capabilities struct {
	// SupportsSnapshot indicates if Snapshot/Restore are available
	SupportsSnapshot bool

	// SupportsHotplugMemory indicates if ResizeMemory is available
	SupportsHotplugMemory bool

	// SupportsPause indicates if Pause/Resume are available
	SupportsPause bool

	// SupportsVsock indicates if vsock communication is available
	SupportsVsock bool

	// SupportsGPUPassthrough indicates if PCI device passthrough is available
	SupportsGPUPassthrough bool

	// SupportsDiskIOLimit indicates if disk I/O rate limiting is available
	SupportsDiskIOLimit bool
}

Capabilities indicates which optional features a hypervisor supports. Callers should check these before calling optional methods.

type ClientFactory added in v0.0.6

type ClientFactory func(socketPath string) (Hypervisor, error)

ClientFactory creates Hypervisor client instances for a hypervisor type.

type DiskConfig

type DiskConfig struct {
	Path       string
	Readonly   bool
	IOBps      int64 // Sustained I/O rate limit in bytes/sec (0 = unlimited)
	IOBurstBps int64 // Burst I/O rate in bytes/sec (0 = same as IOBps)
}

DiskConfig represents a disk attached to the VM

type ForkNetworkConfig added in v0.0.7

type ForkNetworkConfig struct {
	TAPDevice string
	IP        string
	MAC       string
	Netmask   string
}

ForkNetworkConfig contains network identity fields for fork preparation.

type ForkPrepareRequest added in v0.0.7

type ForkPrepareRequest struct {
	// SnapshotConfigPath is optional. When empty, implementations should only
	// validate fork support and return without snapshot rewrites.
	SnapshotConfigPath string

	SourceDataDir string
	TargetDataDir string

	VsockCID    int64
	VsockSocket string

	SerialLogPath string
	Network       *ForkNetworkConfig
}

ForkPrepareRequest contains hypervisor-specific fork preparation inputs.

type ForkPrepareResult added in v0.0.7

type ForkPrepareResult struct {
	// VsockCIDUpdated indicates whether snapshot state was updated to use
	// ForkPrepareRequest.VsockCID.
	VsockCIDUpdated bool
}

ForkPrepareResult describes which optional fork rewrites were actually applied.

type Hypervisor

type Hypervisor interface {
	// DeleteVM sends a graceful shutdown signal to the guest.
	DeleteVM(ctx context.Context) error

	// Shutdown stops the VMM process gracefully.
	Shutdown(ctx context.Context) error

	// GetVMInfo returns current VM state information.
	GetVMInfo(ctx context.Context) (*VMInfo, error)

	// Pause suspends VM execution.
	// Check Capabilities().SupportsPause before calling.
	Pause(ctx context.Context) error

	// Resume continues VM execution after pause.
	// Check Capabilities().SupportsPause before calling.
	Resume(ctx context.Context) error

	// Snapshot creates a VM snapshot at the given path.
	// Check Capabilities().SupportsSnapshot before calling.
	Snapshot(ctx context.Context, destPath string) error

	// ResizeMemory changes the VM's memory allocation.
	// Check Capabilities().SupportsHotplugMemory before calling.
	ResizeMemory(ctx context.Context, bytes int64) error

	// ResizeMemoryAndWait changes the VM's memory allocation and waits for it to stabilize.
	// This polls until the actual memory size matches the target or stabilizes.
	// Check Capabilities().SupportsHotplugMemory before calling.
	ResizeMemoryAndWait(ctx context.Context, bytes int64, timeout time.Duration) error

	// Capabilities returns what features this hypervisor supports.
	Capabilities() Capabilities
}

Hypervisor defines the interface for VM control operations. A Hypervisor client is returned by VMStarter.StartVM after the VM is running.

func NewClient added in v0.0.6

func NewClient(hvType Type, socketPath string) (Hypervisor, error)

NewClient creates a Hypervisor client for the given type and socket.

type NetworkConfig

type NetworkConfig struct {
	TAPDevice string
	IP        string
	MAC       string
	Netmask   string
	// DownloadBps limits host->guest bandwidth in bytes/sec (0 = unlimited).
	// Hypeman enforces this host-side via TAP shaping for all hypervisors.
	// Firecracker also maps it to per-interface API rate limiters.
	DownloadBps int64
	// UploadBps limits guest->host bandwidth in bytes/sec (0 = unlimited).
	// Hypeman enforces this host-side via TAP shaping for all hypervisors.
	// Firecracker also maps it to per-interface API rate limiters.
	UploadBps int64
}

NetworkConfig represents a network interface attached to the VM

type Type

type Type string

Type identifies the hypervisor implementation

const (
	// TypeCloudHypervisor is the Cloud Hypervisor VMM
	TypeCloudHypervisor Type = "cloud-hypervisor"
	// TypeFirecracker is the Firecracker VMM
	TypeFirecracker Type = "firecracker"
	// TypeQEMU is the QEMU VMM
	TypeQEMU Type = "qemu"
	// TypeVZ is the Virtualization.framework VMM (macOS only)
	TypeVZ Type = "vz"
)

type VMConfig

type VMConfig struct {
	// Compute resources
	VCPUs        int
	MemoryBytes  int64
	HotplugBytes int64
	Topology     *CPUTopology

	// Storage
	Disks []DiskConfig

	// Network
	Networks []NetworkConfig

	// Console
	SerialLogPath string

	// Vsock
	VsockCID    int64
	VsockSocket string

	// PCI device passthrough (GPU, etc.)
	PCIDevices []string

	// Boot configuration
	KernelPath string
	InitrdPath string
	KernelArgs string
}

VMConfig is the hypervisor-agnostic VM configuration. Each hypervisor implementation translates this to its native format.

type VMInfo

type VMInfo struct {
	State            VMState
	MemoryActualSize *int64 // Current actual memory size in bytes (if available)
}

VMInfo contains current VM state information

type VMStarter

type VMStarter interface {
	// SocketName returns the socket filename for this hypervisor.
	// Uses short names to stay within Unix socket path length limits (SUN_LEN ~108 bytes).
	SocketName() string

	// GetBinaryPath returns the path to the hypervisor binary, extracting if needed.
	GetBinaryPath(p *paths.Paths, version string) (string, error)

	// GetVersion returns the version of the hypervisor binary.
	// For embedded binaries (Cloud Hypervisor), returns the latest supported version.
	// For system binaries (QEMU), queries the installed binary for its version.
	GetVersion(p *paths.Paths) (string, error)

	// StartVM launches the hypervisor process and boots the VM.
	// Returns the process ID and a Hypervisor client for subsequent operations.
	StartVM(ctx context.Context, p *paths.Paths, version string, socketPath string, config VMConfig) (pid int, hv Hypervisor, err error)

	// RestoreVM starts the hypervisor and restores VM state from a snapshot.
	// Each hypervisor implements its own restore flow:
	// - Cloud Hypervisor: starts process, calls Restore API
	// - QEMU: would start with -incoming or -loadvm flags (not yet implemented)
	// Returns the process ID and a Hypervisor client. The VM is in paused state after restore.
	RestoreVM(ctx context.Context, p *paths.Paths, version string, socketPath string, snapshotPath string) (pid int, hv Hypervisor, err error)

	// PrepareFork allows hypervisors to prepare forked instance state.
	// For snapshot-based forks, implementations can rewrite snapshot config with
	// fork identity (paths, vsock, network). Hypervisors that don't support fork
	// should return ErrNotSupported.
	PrepareFork(ctx context.Context, req ForkPrepareRequest) (ForkPrepareResult, error)
}

VMStarter handles the full VM startup sequence. Each hypervisor implements its own startup flow: - Cloud Hypervisor: starts process, configures via HTTP API, boots via HTTP API - QEMU: converts config to command-line args, starts process (VM runs immediately)

type VMState

type VMState string

VMState represents the VM execution state

const (
	// StateCreated means the VM is configured but not running
	StateCreated VMState = "created"
	// StateRunning means the VM is actively executing
	StateRunning VMState = "running"
	// StatePaused means the VM execution is suspended
	StatePaused VMState = "paused"
	// StateShutdown means the VM has stopped but VMM exists
	StateShutdown VMState = "shutdown"
)

type VsockDialer

type VsockDialer interface {
	// DialVsock connects to the guest on the specified port.
	// Returns a net.Conn that can be used for bidirectional communication.
	DialVsock(ctx context.Context, port int) (net.Conn, error)

	// Key returns a unique identifier for this dialer, used for connection pooling.
	Key() string
}

VsockDialer provides vsock connectivity to a guest VM. Each hypervisor implements its own connection method: - Cloud Hypervisor: Unix socket file + text handshake protocol - QEMU: Kernel AF_VSOCK with CID-based addressing

func NewVsockDialer

func NewVsockDialer(hvType Type, vsockSocket string, vsockCID int64) (VsockDialer, error)

NewVsockDialer creates a VsockDialer for the given hypervisor type. Returns an error if the hypervisor type doesn't have a registered factory.

type VsockDialerFactory

type VsockDialerFactory func(vsockSocket string, vsockCID int64) VsockDialer

VsockDialerFactory creates VsockDialer instances for a hypervisor type.

Directories

Path Synopsis
Package cloudhypervisor implements the hypervisor.Hypervisor interface for Cloud Hypervisor VMM.
Package cloudhypervisor implements the hypervisor.Hypervisor interface for Cloud Hypervisor VMM.
Package qemu implements the hypervisor.Hypervisor interface for QEMU.
Package qemu implements the hypervisor.Hypervisor interface for QEMU.
vz
Package vz implements the hypervisor.Hypervisor interface for Apple's Virtualization.framework on macOS via the vz-shim subprocess.
Package vz implements the hypervisor.Hypervisor interface for Apple's Virtualization.framework on macOS via the vz-shim subprocess.
shimconfig
Package shimconfig defines the configuration types shared between the hypeman API server and the vz-shim subprocess.
Package shimconfig defines the configuration types shared between the hypeman API server and the vz-shim subprocess.

Jump to

Keyboard shortcuts

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