hypervisor

package
v0.2.9 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	APISocketName   = "api.sock"
	ConsoleSockName = "console.sock"

	// CowSerial is the well-known virtio serial for the COW disk attached to OCI VMs.
	CowSerial = "cocoon-cow"

	// CreatingStateGCGrace is how long a VM can stay in "creating" state
	// before GC treats it as a crash remnant and cleans it up.
	CreatingStateGCGrace = 24 * time.Hour
)

Shared constants for all hypervisor backends.

Variables

View Source
var (
	ErrNotFound   = errors.New("VM not found")
	ErrNotRunning = errors.New("VM not running")
)

Functions

func BlobHexFromPath added in v0.2.9

func BlobHexFromPath(path string) string

BlobHexFromPath extracts the digest hex from a blob file path. e.g., "/var/lib/cocoon/oci/blobs/abc123.erofs" → "abc123"

func BuildIPParams added in v0.2.9

func BuildIPParams(networkConfigs []*types.NetworkConfig, vmName string, dnsServers []string) string

BuildIPParams generates kernel ip= parameters for NICs with static IPs.

func CleanupRuntimeFiles added in v0.2.9

func CleanupRuntimeFiles(ctx context.Context, runDir string, files []string)

CleanupRuntimeFiles removes the given list of runtime files from runDir.

func ConsoleSockPath added in v0.2.9

func ConsoleSockPath(runDir string) string

ConsoleSockPath returns the console socket path under a VM's run directory.

func CopyFile added in v0.2.9

func CopyFile(dst, src string) (err error)

CopyFile copies a single file preserving permissions.

func EnterNetns added in v0.2.9

func EnterNetns(nsPath string) (restore func(), err error)

EnterNetns locks the OS thread, saves the current netns, and switches to the target netns. The forked child process inherits the new netns. Returns a restore function that must be deferred by the caller.

func ExtractBlobIDs added in v0.2.9

func ExtractBlobIDs(storageConfigs []*types.StorageConfig, boot *types.BootConfig) map[string]struct{}

ExtractBlobIDs extracts digest hexes from storage/boot paths for GC pinning.

func PrefixToNetmask added in v0.2.9

func PrefixToNetmask(prefix int) string

PrefixToNetmask converts a CIDR prefix length to a dotted-decimal netmask string.

func RemoveVMDirs added in v0.2.9

func RemoveVMDirs(runDir, logDir string) error

RemoveVMDirs removes the run and log directories for a VM.

func SocketPath added in v0.2.9

func SocketPath(runDir string) string

SocketPath returns the API socket path under a VM's run directory.

func VerifyBaseFiles added in v0.2.9

func VerifyBaseFiles(storageConfigs []*types.StorageConfig, boot *types.BootConfig) error

VerifyBaseFiles checks that all read-only layer files and boot files exist.

func WaitForSocket added in v0.2.9

func WaitForSocket(ctx context.Context, socketPath string, pid int, timeout time.Duration, processName string) error

WaitForSocket polls until socketPath is connectable, the process exits, or the timeout/context fires.

Types

type Backend added in v0.2.9

type Backend struct {
	Typ    string
	Conf   BackendConfig
	DB     storage.Store[VMIndex]
	Locker lock.Locker
}

Backend provides shared store operations for hypervisor backends. Embed this struct in backend implementations to avoid duplicating store access patterns (resolve, load, state updates, VM iteration).

func (*Backend) AbortLaunch added in v0.2.9

func (b *Backend) AbortLaunch(ctx context.Context, pid int, sockPath, runDir string, runtimeFiles []string)

AbortLaunch kills a hypervisor process and removes runtime files after a failed launch.

func (*Backend) BatchMarkStarted added in v0.2.9

func (b *Backend) BatchMarkStarted(ctx context.Context, ids []string) error

BatchMarkStarted updates a batch of VMs to Running state with FirstBooted=true.

func (*Backend) CleanStalePlaceholders added in v0.2.9

func (b *Backend) CleanStalePlaceholders(_ context.Context, ids []string) error

CleanStalePlaceholders removes DB records stuck in "creating" state past the GC grace period. Used by GC Collect phase.

func (*Backend) ForEachVM added in v0.2.9

func (b *Backend) ForEachVM(ctx context.Context, ids []string, op string, fn func(context.Context, string) error) ([]string, error)

ForEachVM runs fn for each ID concurrently (bounded by PoolSize).

func (*Backend) GCCollect added in v0.2.9

func (b *Backend) GCCollect(ctx context.Context, ids []string) error

GCCollect removes orphan VM directories and stale DB records. Runs under the GC orchestrator's flock — uses lock-free DB access (ReadRaw/WriteRaw) to avoid self-deadlock.

func (*Backend) Inspect added in v0.2.9

func (b *Backend) Inspect(ctx context.Context, ref string) (*types.VM, error)

Inspect returns VM info for a single VM by ref (ID, name, or prefix).

func (*Backend) List added in v0.2.9

func (b *Backend) List(ctx context.Context) ([]*types.VM, error)

List returns VM info for all known VMs.

func (*Backend) LoadRecord added in v0.2.9

func (b *Backend) LoadRecord(ctx context.Context, id string) (VMRecord, error)

LoadRecord loads a deep copy of a VM record by ID.

func (*Backend) MarkError added in v0.2.9

func (b *Backend) MarkError(ctx context.Context, id string)

MarkError marks a VM as error state. Logs but does not return errors.

func (*Backend) PIDFilePath added in v0.2.9

func (b *Backend) PIDFilePath(runDir string) string

PIDFilePath returns the PID file path for the backend's PID file name.

func (*Backend) ReserveVM added in v0.2.9

func (b *Backend) ReserveVM(ctx context.Context, id string, vmCfg *types.VMConfig, blobIDs map[string]struct{}, runDir, logDir string) error

ReserveVM writes a placeholder VMRecord (state=Creating) so GC won't treat the VM's directories as orphans.

func (*Backend) ResolveRef added in v0.2.9

func (b *Backend) ResolveRef(ctx context.Context, ref string) (string, error)

ResolveRef resolves a single ref (ID, name, or prefix) to an exact VM ID.

func (*Backend) ResolveRefs added in v0.2.9

func (b *Backend) ResolveRefs(ctx context.Context, refs []string) ([]string, error)

ResolveRefs batch-resolves refs to exact VM IDs under a single lock.

func (*Backend) RollbackCreate added in v0.2.9

func (b *Backend) RollbackCreate(ctx context.Context, id, name string)

RollbackCreate removes a placeholder VM record from the DB.

func (*Backend) ToVM added in v0.2.9

func (b *Backend) ToVM(rec *VMRecord) *types.VM

ToVM converts a VMRecord to a types.VM with runtime fields populated. Deep-copies SnapshotIDs to prevent shared mutable reference to DB record.

func (*Backend) Type added in v0.2.9

func (b *Backend) Type() string

Type returns the backend identifier (e.g., "cloud-hypervisor", "firecracker").

func (*Backend) UpdateStates added in v0.2.9

func (b *Backend) UpdateStates(ctx context.Context, ids []string, state types.VMState) error

UpdateStates updates the state and timestamp for a batch of VM IDs.

func (*Backend) WithRunningVM added in v0.2.9

func (b *Backend) WithRunningVM(ctx context.Context, rec *VMRecord, fn func(pid int) error) error

WithRunningVM verifies the VM process is alive, then calls fn with the PID. Returns ErrNotRunning if the process is not alive.

type BackendConfig added in v0.2.9

type BackendConfig interface {
	BinaryName() string
	PIDFileName() string
	TerminateGracePeriod() time.Duration
	EffectivePoolSize() int
	VMRunDir(id string) string
	VMLogDir(id string) string
}

BackendConfig provides backend-specific values needed by shared Backend methods.

type Direct

type Direct interface {
	DirectClone(ctx context.Context, vmID string, vmCfg *types.VMConfig, networkConfigs []*types.NetworkConfig, snapshotConfig *types.SnapshotConfig, srcDir string) (*types.VM, error)
	DirectRestore(ctx context.Context, vmRef string, vmCfg *types.VMConfig, srcDir string) (*types.VM, error)
}

Direct is an optional interface for hypervisors that support clone/restore from a local snapshot directory.

type Hypervisor

type Hypervisor interface {
	Type() string

	Create(ctx context.Context, vmID string, vmCfg *types.VMConfig, storage []*types.StorageConfig, network []*types.NetworkConfig, boot *types.BootConfig) (*types.VM, error)
	Start(ctx context.Context, refs []string) ([]string, error)
	Stop(ctx context.Context, refs []string) ([]string, error)
	Inspect(ctx context.Context, ref string) (*types.VM, error)
	List(context.Context) ([]*types.VM, error)
	Delete(ctx context.Context, refs []string, force bool) ([]string, error)
	Console(ctx context.Context, ref string) (io.ReadWriteCloser, error)
	Snapshot(ctx context.Context, ref string) (*types.SnapshotConfig, io.ReadCloser, error)
	Clone(ctx context.Context, vmID string, vmCfg *types.VMConfig, networkConfigs []*types.NetworkConfig, snapshotConfig *types.SnapshotConfig, snapshot io.Reader) (*types.VM, error)
	Restore(ctx context.Context, vmRef string, vmCfg *types.VMConfig, snapshot io.Reader) (*types.VM, error)

	RegisterGC(*gc.Orchestrator)
}

Hypervisor manages VM lifecycle. Implemented by each backend.

type VMIndex

type VMIndex struct {
	VMs   map[string]*VMRecord `json:"vms"`
	Names map[string]string    `json:"names"` // name → VM ID
}

VMIndex is the top-level DB structure for a hypervisor backend.

func (*VMIndex) Init

func (idx *VMIndex) Init()

Init implements storage.Initer.

func (*VMIndex) Resolve

func (idx *VMIndex) Resolve(ref string) (string, error)

Resolve resolves a ref (exact ID, name, or ID prefix ≥3 chars) to a full VM ID.

func (*VMIndex) ResolveMany

func (idx *VMIndex) ResolveMany(refs []string) ([]string, error)

ResolveMany batch-resolves refs to exact VM IDs, deduplicating results.

type VMRecord

type VMRecord struct {
	types.VM

	BootConfig   *types.BootConfig   `json:"boot_config,omitempty"`    // nil for UEFI boot (cloudimg)
	ImageBlobIDs map[string]struct{} `json:"image_blob_ids,omitempty"` // blob hex set for GC pinning

	// RunDir and LogDir store the absolute paths used when the VM was created.
	// Persisting them ensures cleanup succeeds even if --run-dir / --log-dir
	// differ from the values at creation time.
	RunDir string `json:"run_dir,omitempty"`
	LogDir string `json:"log_dir,omitempty"`
}

VMRecord is the persisted record for a single VM.

StorageConfigs and NetworkConfigs live on the embedded types.VM so that a value-copy (info := rec.VM) automatically includes them — no manual field copying needed. The JSON tags are on types.VM; do NOT duplicate them here or Go's encoding/json will silently shadow the promoted fields.

type Watchable added in v0.2.6

type Watchable interface {
	WatchPath() string
}

Watchable is optionally implemented by hypervisors that support file-based state watching.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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