hypervisor

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

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

	// VsockGuestCID is constant — per-VM isolation comes from distinct UDS paths.
	VsockGuestCID = 3
	// VsockAgentPort is the cocoon-agent listen port.
	VsockAgentPort = 1024

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

	// CreatingStateGCGrace bounds how long GC tolerates a "creating" VM.
	CreatingStateGCGrace = 24 * time.Hour

	// VMMemTransferTimeout is the single-shot timeout for snapshot/restore API calls.
	VMMemTransferTimeout = 10 * time.Minute

	// MinBalloonMemory: balloon overhead is not worthwhile below 256 MiB guest memory.
	MinBalloonMemory = 256 << 20

	// DefaultBalloonDiv sizes the initial balloon as memory/DefaultBalloonDiv (25%).
	DefaultBalloonDiv = 4

	// GracefulStopPollInterval polls between graceful shutdown signal and timeout escalation.
	GracefulStopPollInterval = 500 * time.Millisecond
)
View Source
const (
	// SnapshotFileMemory is a read-only memory/state file (hard link or symlink).
	SnapshotFileMemory SnapshotFileKind = iota
	// SnapshotFileCOW is a writable disk that must be copied (reflink/sparse).
	SnapshotFileCOW
	// SnapshotFileMeta is small metadata that is plain-copied.
	SnapshotFileMeta
	// SnapshotFileSkip means the file should not be cloned.
	SnapshotFileSkip

	// MinDataDiskSize is the minimum user data disk size; mkfs.ext4 is unstable below this on small sparse files.
	MinDataDiskSize int64 = 16 << 20
)
View Source
const SnapshotMetaFile = "cocoon.json"

SnapshotMetaFile is the cocoon-owned sidecar carrying fields the hypervisor's native config can't hold (Role/MountPoint/FSType/DirectIO; FC CPU/Memory).

Variables

View Source
var (
	ErrNotFound   = errors.New("vm not found")
	ErrNotRunning = errors.New("vm not running")
	ErrAmbiguous  = errors.New("vm ref resolves to multiple backends")
)

Functions

func BalloonSize added in v0.3.9

func BalloonSize(memoryBytes int64, windows bool) (int64, bool)

BalloonSize returns (bytes, enabled); disabled on Windows (virtio-win driver loops on deflation) and below MinBalloonMemory.

func BlobHexFromPath added in v0.2.9

func BlobHexFromPath(path string) string

BlobHexFromPath returns the digest hex of a blob path (e.g. .../abc123.erofs → abc123).

func BuildBaseCmdline added in v0.4.1

func BuildBaseCmdline(prefix, layers, cow string, networkConfigs []*types.NetworkConfig, vmName string, dnsServers []string) string

BuildBaseCmdline composes the cocoon-shared cmdline: prefix (backend-specific console+quirks) + boot/layers/cow + per-NIC ip= params.

func BuildIPParams added in v0.2.9

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

func CleanSnapshotFiles added in v0.3.6

func CleanSnapshotFiles(runDir string, match func(name string) bool) error

CleanSnapshotFiles removes snapshot-specific files from runDir.

func CleanupRuntimeFiles added in v0.2.9

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

func CloneSnapshotFiles added in v0.3.6

func CloneSnapshotFiles(dstDir, srcDir string, classify func(name string) SnapshotFileKind) error

CloneSnapshotFiles copies snapshot files using per-file strategies to minimize I/O.

func CloneStorageConfigs added in v0.3.9

func CloneStorageConfigs(storageConfigs []*types.StorageConfig) []*types.StorageConfig

func ConsoleSockPath added in v0.2.9

func ConsoleSockPath(runDir string) string

func CopyFile added in v0.2.9

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

func DataDiskBaseName added in v0.3.8

func DataDiskBaseName(serial string) string

DataDiskBaseName is the canonical file name (centralized so matchers, reflink loops, and clone path rewrites stay in sync).

func EnterNetns added in v0.2.9

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

func ExpandRawImage added in v0.3.6

func ExpandRawImage(path string, targetSize int64) error

ExpandRawImage truncates path up to targetSize; no-op if path already meets it.

func ExtractBlobIDs added in v0.2.9

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

func InitCOWFilesystem added in v0.3.6

func InitCOWFilesystem(ctx context.Context, path string) error

func IsDataDiskFile added in v0.3.8

func IsDataDiskFile(name string) bool

IsDataDiskFile reports whether name matches the data disk file pattern.

func IsUnderDir added in v0.3.9

func IsUnderDir(path, dir string) bool

IsUnderDir reports whether path is strictly under dir. An empty dir returns false (disables the check) rather than matching every path.

func MergeDirInto added in v0.3.1

func MergeDirInto(src, dst string) error

MergeDirInto renames entries from src to dst, overwriting existing files.

func PopulateFromSrc added in v0.3.9

func PopulateFromSrc(runDir, srcDir string, clean func(string) error, clone func(string, string) error) error

PopulateFromSrc cleans runDir of old snapshot files then copies fresh ones from srcDir (used by DirectRestore).

func PrefixToNetmask added in v0.2.9

func PrefixToNetmask(prefix int) string

func PreflightRestore added in v0.3.9

func PreflightRestore(srcDir, rootDir, runDir string, rec *VMRecord, integrity func(srcDir string, sidecar []*types.StorageConfig) error) error

PreflightRestore: load+validate sidecar, run backend-specific integrity, assert snapshot role sequence is a prefix of rec.

func PrepareDataDisks added in v0.3.8

func PrepareDataDisks(ctx context.Context, baseDir string, specs []types.DataDiskSpec) ([]*types.StorageConfig, error)

PrepareDataDisks creates sparse files for each spec under baseDir, optionally formats (ext4 default), returns StorageConfigs; names must be unique and ValidDataDiskName-passing.

func PrepareOCICOW added in v0.3.6

func PrepareOCICOW(ctx context.Context, cowPath string, storage int64, storageConfigs []*types.StorageConfig) ([]*types.StorageConfig, error)

PrepareOCICOW creates an ext4-formatted sparse COW at cowPath and returns storageConfigs with the new CowSerial entry appended (use the returned slice; append may reallocate).

func PrepareStagingDir added in v0.3.6

func PrepareStagingDir(runDir string, snapshot io.Reader) (stagingDir string, cleanup func(), err error)

func ReflinkDataDisks added in v0.3.8

func ReflinkDataDisks(dstDir string, configs []*types.StorageConfig) error

ReflinkDataDisks reflinks every Role==Data disk into dstDir under data-<serial>.raw (CH+FC use it inside the snapshot pause window).

func RemoveVMDirs added in v0.2.9

func RemoveVMDirs(runDir, logDir string) error

func ReverseLayers added in v0.3.9

func ReverseLayers[T any](storageConfigs []*types.StorageConfig, project func(idx int, sc *types.StorageConfig) T) []T

ReverseLayers projects Role==Layer entries through fn in reverse order (topmost layer first, matching overlayfs lowerdir semantics).

func SaveSnapshotMeta added in v0.3.9

func SaveSnapshotMeta(dir string, meta *SnapshotMeta) error

func SocketPath added in v0.2.9

func SocketPath(runDir string) string

func ValidateHostCPU added in v0.3.1

func ValidateHostCPU(cpu int) error

func ValidateMetaPaths added in v0.3.9

func ValidateMetaPaths(meta *SnapshotMeta, rootDir, runDir string) error

ValidateMetaPaths rejects sidecar paths escaping cocoon-managed roots; an imported snapshot's cocoon.json is otherwise untrusted.

func ValidateRoleSequence added in v0.3.8

func ValidateRoleSequence(sidecar, rec []*types.StorageConfig) error

ValidateRoleSequence checks sidecar is a role-by-role prefix of rec; rec may carry trailing cidata (cloudimg post-first-boot) — the only allowed extension.

func ValidateSnapshotIntegrity added in v0.3.8

func ValidateSnapshotIntegrity(srcDir string, sidecar []*types.StorageConfig) error

ValidateSnapshotIntegrity is the backend-agnostic preflight: sidecar is structurally valid and every snapshot-resident disk (COW/Cidata/Data) is on disk. Layers are shared blobs; backends add their own (state.json, vmstate) checks.

func VerifyBaseFiles added in v0.2.9

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

func VsockSockPath added in v0.3.9

func VsockSockPath(runDir string) string

func WaitForSocket added in v0.2.9

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

Types

type AfterExtractFn added in v0.4.1

type AfterExtractFn func(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, runDir, logDir string, now time.Time, sourceSnapshotID string) (*types.VM, error)

AfterExtractFn finalizes a cloned VM after snapshot files are in place; sourceSnapshotID flows through for metering lineage.

type Backend added in v0.2.9

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

Backend provides shared store operations for hypervisor backends.

func NewBackend added in v0.4.1

func NewBackend(typ string, conf BackendConfig, rec metering.Recorder) (*Backend, error)

NewBackend wires shared init: EnsureDirs, flock, JSON store, nil-recorder fallback.

func (*Backend) AbortLaunch added in v0.2.9

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

AbortLaunch terminates a failed launch and clears runtime files.

func (*Backend) BatchMarkStarted added in v0.2.9

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

BatchMarkStarted flips ids to VMStateRunning; entrants with an open compute interval are stale-running (close stop-crash, then open fresh).

func (*Backend) BuildGCModule added in v0.3.6

func (b *Backend) BuildGCModule() gc.Module[VMGCSnapshot]

BuildGCModule builds GC module that scans DB and dirs for orphan VMs.

func (*Backend) BuildSnapshotConfig added in v0.3.6

func (b *Backend) BuildSnapshotConfig(snapID string, rec *VMRecord) *types.SnapshotConfig

func (*Backend) CleanStalePlaceholders added in v0.2.9

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

CleanStalePlaceholders removes "creating" records past GC grace period.

func (*Backend) CloneFromStream added in v0.3.6

func (b *Backend) CloneFromStream(
	ctx context.Context, vmID string, vmCfg *types.VMConfig,
	net types.NetSetup, snapshotConfig *types.SnapshotConfig, snapshot io.Reader,
	afterExtract AfterExtractFn,
) (_ *types.VM, err error)

CloneFromStream clones from a tar stream into a fresh runDir. Used when the snapshot arrives over the network (cross-node clone).

func (*Backend) CloneSetup added in v0.3.1

func (b *Backend) CloneSetup(ctx context.Context, vmID string, vmCfg *types.VMConfig, snapshotConfig *types.SnapshotConfig) (runDir, logDir string, now time.Time, cleanup func(), err error)

CloneSetup is the shared pre-clone sequence: validate CPU, reserve a placeholder, ensure dirs, return a cleanup that rolls back both.

func (*Backend) CreateSequence added in v0.3.9

func (b *Backend) CreateSequence(ctx context.Context, id string, spec CreateSpec) (_ *types.VM, err error)

CreateSequence is the shared placeholder→finalize create skeleton.

func (*Backend) DeleteAll added in v0.3.9

func (b *Backend) DeleteAll(ctx context.Context, refs []string, force bool, stopOne func(context.Context, string) error) ([]string, error)

DeleteAll removes VMs by ref; dir cleanup before DB delete keeps a failed cleanup retry-able.

func (*Backend) DirectCloneBase added in v0.3.6

func (b *Backend) DirectCloneBase(
	ctx context.Context, vmID string, vmCfg *types.VMConfig,
	net types.NetSetup, snapshotConfig *types.SnapshotConfig, srcDir string,
	cloneFiles func(dstDir, srcDir string) error,
	afterExtract AfterExtractFn,
) (_ *types.VM, err error)

DirectCloneBase clones from a local snapshot directory. Used when the snapshot lives on the same host (no tar streaming needed).

func (*Backend) DirectRestoreSequence added in v0.3.9

func (b *Backend) DirectRestoreSequence(ctx context.Context, vmRef string, spec DirectRestoreSpec) (*types.VM, error)

DirectRestoreSequence restores from a local snapshot directory.

func (*Backend) FinalizeClone added in v0.3.6

func (b *Backend) FinalizeClone(ctx context.Context, vmID string, info *types.VM, bootCfg *types.BootConfig, blobIDs map[string]struct{}, sourceSnapshotID string) error

FinalizeClone persists the record and emits the clone open-interval pair.

func (*Backend) FinalizeCreate added in v0.3.6

func (b *Backend) FinalizeCreate(ctx context.Context, id string, info *types.VM, bootCfg *types.BootConfig, blobIDs map[string]struct{}) error

FinalizeCreate persists the populated VM record (replacing the placeholder) and emits metering vm.storage.start.

func (*Backend) FinalizeRestore added in v0.3.6

func (b *Backend) FinalizeRestore(ctx context.Context, vmID string, vmCfg *types.VMConfig, rec *VMRecord, pid int) (*types.VM, error)

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 over ids in parallel up to EffectivePoolSize, logging per-id failures.

func (*Backend) GracefulStop added in v0.3.6

func (b *Backend) GracefulStop(ctx context.Context, vmID string, pid int, timeout time.Duration, signal, escalate func() error) error

GracefulStop signals shutdown, polls until exit, escalates on timeout.

func (*Backend) HandleStopResult added in v0.3.6

func (b *Backend) HandleStopResult(ctx context.Context, id, runDir string, runtimeFiles []string, shutdownErr error) error

func (*Backend) Inspect added in v0.2.9

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

func (*Backend) IsAPISocketLive added in v0.4.1

func (b *Backend) IsAPISocketLive(ctx context.Context, rec *VMRecord) (bool, error)

IsAPISocketLive: (true,nil)=confirmed live; (false,nil)=ENOENT/ECONNREFUSED; (true,err)=fail-closed for unknown dial errors.

func (*Backend) KillForRestore added in v0.3.6

func (b *Backend) KillForRestore(ctx context.Context, vmID string, rec *VMRecord, terminate func(pid int) error, runtimeFiles []string) error

func (*Backend) LaunchVMProcess added in v0.3.9

func (b *Backend) LaunchVMProcess(ctx context.Context, spec LaunchSpec) (pid int, err error)

LaunchVMProcess starts spec.Cmd and waits for the API socket; any post-Start error kills the process + removes the PID file.

func (*Backend) List added in v0.2.9

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

List snapshots all records under the DB lock then runs ToVM (which does file IO) outside the lock so concurrent writers don't queue behind status polls. Mutable map fields are cloned inside the lock to avoid a concurrent-read race with RecordSnapshot etc.

func (*Backend) LoadRecord added in v0.2.9

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

LoadRecord returns a shallow value-copy; pointer/slice/map fields still alias the live record. Treat as read-only outside DB transactions.

func (*Backend) LogFilePath added in v0.4.0

func (b *Backend) LogFilePath(logDir string) string

LogFilePath returns the per-VM hypervisor log file under logDir (named after the backend so write/read can't drift).

func (*Backend) LogPath added in v0.4.0

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

LogPath resolves ref → log path via the persisted LogDir (survives --log-dir change); falls back to current Conf for legacy records.

func (*Backend) MarkError added in v0.2.9

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

MarkError flips a single VM's state to VMStateError, logging on persist failure.

func (*Backend) PIDFilePath added in v0.2.9

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

func (*Backend) PrepareStart added in v0.3.6

func (b *Backend) PrepareStart(ctx context.Context, id string, runtimeFiles []string) (*VMRecord, error)

PrepareStart loads the record, verifies not-running, ensures dirs exist.

func (*Backend) RecordSnapshot added in v0.3.6

func (b *Backend) RecordSnapshot(ctx context.Context, vmID string) (string, error)

RecordSnapshot generates a snapshot ID and records it on the VM's record.

func (*Backend) RegisterGC added in v0.3.6

func (b *Backend) RegisterGC(orch *gc.Orchestrator)

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 inserts a "creating" placeholder under id, failing on id/name collision.

func (*Backend) ResolveAndLoad added in v0.4.1

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

ResolveAndLoad combines ResolveRef + LoadRecord under a single DB lock.

func (*Backend) ResolveForRestore added in v0.3.6

func (b *Backend) ResolveForRestore(ctx context.Context, vmRef string) (string, *VMRecord, error)

func (*Backend) ResolveRef added in v0.2.9

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

func (*Backend) ResolveRefs added in v0.2.9

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

ResolveRefs batch-resolves under a single lock.

func (*Backend) RestoreSequence added in v0.3.9

func (b *Backend) RestoreSequence(ctx context.Context, vmRef string, spec RestoreSpec) (*types.VM, error)

RestoreSequence is the shared restore skeleton (preflight before kill).

func (*Backend) RollbackCreate added in v0.2.9

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

func (*Backend) SnapshotSequence added in v0.3.9

func (b *Backend) SnapshotSequence(ctx context.Context, ref string, spec SnapshotSpec) (_ *types.SnapshotConfig, _ io.ReadCloser, err error)

SnapshotSequence is the shared capture skeleton; only capture runs in the pause window — AfterCapture (e.g. cidata copy) runs outside.

func (*Backend) StartAll added in v0.3.9

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

StartAll runs startOne per ref; only launched=true ids reach BatchMarkStarted.

func (*Backend) StartSequence added in v0.4.1

func (b *Backend) StartSequence(ctx context.Context, id string, spec StartSpec) (bool, error)

StartSequence runs the shared start skeleton; returns whether a fresh process was launched.

func (*Backend) StopAll added in v0.3.9

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

StopAll mirrors StartAll: stopOne per ref, batch-flip succeeded to Stopped.

func (*Backend) StopOneSequence added in v0.4.1

func (b *Backend) StopOneSequence(ctx context.Context, id string, spec StopSpec) error

StopOneSequence runs the shared per-id stop skeleton (LoadRecord → WithRunningVM(Shutdown) → HandleStopResult) so backends only express their force-vs-graceful choice.

func (*Backend) ToVM added in v0.2.9

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

func (*Backend) Type added in v0.2.9

func (b *Backend) Type() string

func (*Backend) UpdateStates added in v0.2.9

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

UpdateStates flips ids to Stopped or Error and emits compute.stop on Running→Stopped (Error paths can't prove the process is dead so the interval stays open until a confirmed-dead helper closes it). To open a fresh interval, use BatchMarkStarted — UpdateStates intentionally rejects Running to avoid silent ledger drift.

func (*Backend) WatchPath added in v0.3.6

func (b *Backend) WatchPath() string

WatchPath returns VM index file path for filesystem-based watching.

func (*Backend) WithPausedVM added in v0.3.9

func (b *Backend) WithPausedVM(ctx context.Context, rec *VMRecord, pause, resume, fn func() error) error

WithPausedVM pauses, runs fn, resumes; eager resume on success promotes its error, deferred resume on fn-error only logs.

func (*Backend) WithRunningVM added in v0.2.9

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

WithRunningVM calls fn if rec still points to a live VM process.

type BackendConfig added in v0.2.9

type BackendConfig interface {
	BinaryName() string
	PIDFileName() string
	TerminateGracePeriod() time.Duration
	SocketWaitTimeout() time.Duration
	EffectivePoolSize() int
	IndexFile() string
	IndexLock() string
	EnsureDirs() error
	RunDir() string
	LogDir() string
	VMRunDir(id string) string
	VMLogDir(id string) string
}

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

type BaseConfig added in v0.3.1

type BaseConfig struct {
	*config.Config
	// contains filtered or unexported fields
}

BaseConfig holds the directory layout + timeout defaults shared by all hypervisor backends; backends embed it and add binary-specific methods.

func NewBaseConfig added in v0.3.1

func NewBaseConfig(conf *config.Config, name string) BaseConfig

NewBaseConfig creates a BaseConfig for the named backend.

func (*BaseConfig) DataDiskPath added in v0.3.8

func (c *BaseConfig) DataDiskPath(vmID, name string) string

DataDiskPath returns the canonical raw path; filename embeds the disk name so cleanSnapshotFiles prefix-match works.

func (*BaseConfig) EnsureDirs added in v0.3.1

func (c *BaseConfig) EnsureDirs() error

EnsureDirs creates all static directories required by the backend.

func (*BaseConfig) IndexFile added in v0.3.1

func (c *BaseConfig) IndexFile() string

func (*BaseConfig) IndexLock added in v0.3.1

func (c *BaseConfig) IndexLock() string

func (*BaseConfig) LogDir added in v0.3.1

func (c *BaseConfig) LogDir() string

func (*BaseConfig) RunDir added in v0.3.1

func (c *BaseConfig) RunDir() string

func (*BaseConfig) SocketWaitTimeout added in v0.3.1

func (c *BaseConfig) SocketWaitTimeout() time.Duration

SocketWaitTimeout returns configured timeout or default (5s).

func (*BaseConfig) TerminateGracePeriod added in v0.3.1

func (c *BaseConfig) TerminateGracePeriod() time.Duration

TerminateGracePeriod returns configured grace period or default (5s).

func (*BaseConfig) VMLogDir added in v0.3.1

func (c *BaseConfig) VMLogDir(vmID string) string

func (*BaseConfig) VMRunDir added in v0.3.1

func (c *BaseConfig) VMRunDir(vmID string) string

type CreateSpec added in v0.3.9

type CreateSpec struct {
	VMCfg          *types.VMConfig
	StorageConfigs []*types.StorageConfig
	Net            types.NetSetup
	BootConfig     *types.BootConfig
	Prepare        func(ctx context.Context, vmID string, vmCfg *types.VMConfig, storageConfigs []*types.StorageConfig, net types.NetSetup, boot *types.BootConfig) ([]*types.StorageConfig, error)
}

CreateSpec carries CreateSequence inputs.

type Direct

type Direct interface {
	DirectClone(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, snapshotConfig *types.SnapshotConfig, srcDir string) (*types.VM, error)
	DirectRestore(ctx context.Context, vmRef string, vmCfg *types.VMConfig, srcDir, sourceSnapshotID string) (*types.VM, error)
}

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

type DirectRestoreSpec added in v0.3.9

type DirectRestoreSpec struct {
	VMCfg            *types.VMConfig
	SrcDir           string
	SourceSnapshotID string
	Preflight        func(srcDir string, rec *VMRecord) error
	Kill             func(ctx context.Context, vmID string, rec *VMRecord) error
	Wrap             func(rec *VMRecord, fn func() error) error
	Populate         func(rec *VMRecord, srcDir string) error
	AfterExtract     func(ctx context.Context, vmID string, vmCfg *types.VMConfig, rec *VMRecord) (*types.VM, error)
}

DirectRestoreSpec is RestoreSpec for a local srcDir; Populate replaces staging+merge.

type Hypervisor

type Hypervisor interface {
	Type() string

	Create(ctx context.Context, vmID string, vmCfg *types.VMConfig, storage []*types.StorageConfig, net types.NetSetup, 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)
	LogPath(ctx context.Context, ref string) (string, error)
	Snapshot(ctx context.Context, ref string) (*types.SnapshotConfig, io.ReadCloser, error)
	Clone(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, snapshotConfig *types.SnapshotConfig, snapshot io.Reader) (*types.VM, error)
	Restore(ctx context.Context, vmRef string, vmCfg *types.VMConfig, snapshot io.Reader, sourceSnapshotID string) (*types.VM, error)

	RegisterGC(*gc.Orchestrator)
}

Hypervisor manages VM lifecycle. Implemented by each backend.

type LaunchSpec added in v0.3.9

type LaunchSpec struct {
	Cmd       *exec.Cmd
	PIDPath   string
	SockPath  string
	NetnsPath string
	OnFail    func()
}

LaunchSpec is the per-call input to Backend.LaunchVMProcess.

type RestoreSpec added in v0.3.9

type RestoreSpec struct {
	VMCfg            *types.VMConfig
	Snapshot         io.Reader
	SourceSnapshotID string
	Preflight        func(stagingDir string, rec *VMRecord) error
	Kill             func(ctx context.Context, vmID string, rec *VMRecord) error
	Wrap             func(rec *VMRecord, fn func() error) error
	BeforeMerge      func(rec *VMRecord) error
	AfterExtract     func(ctx context.Context, vmID string, vmCfg *types.VMConfig, rec *VMRecord) (*types.VM, error)
}

RestoreSpec carries backend hooks for Backend.RestoreSequence.

type SnapshotFileKind added in v0.3.6

type SnapshotFileKind int

SnapshotFileKind classifies a snapshot file for CloneSnapshotFiles.

type SnapshotMeta added in v0.3.9

type SnapshotMeta struct {
	StorageConfigs []*types.StorageConfig `json:"storage_configs"`
	BootConfig     *types.BootConfig      `json:"boot_config,omitempty"`
	// CPU/Memory populated by FC only; CH reads them from config.json on restore.
	CPU    int   `json:"cpu,omitempty"`
	Memory int64 `json:"memory,omitempty"`
}

func LoadAndValidateMeta added in v0.3.9

func LoadAndValidateMeta(dir, rootDir, runDir string) (*SnapshotMeta, error)

func LoadSnapshotMeta added in v0.3.9

func LoadSnapshotMeta(dir string) (*SnapshotMeta, error)

type SnapshotSpec added in v0.3.9

type SnapshotSpec struct {
	Pause        func(rec *VMRecord, hc *http.Client) error
	Resume       func(rec *VMRecord, hc *http.Client) error
	Capture      func(rec *VMRecord, hc *http.Client, tmpDir string) error
	Wrap         func(rec *VMRecord, fn func() error) error
	AfterCapture func(rec *VMRecord, tmpDir string) error
	BuildMeta    func(rec *VMRecord, tmpDir string) (*SnapshotMeta, error)
}

SnapshotSpec carries backend hooks for SnapshotSequence; the shared hc keeps HTTP keep-alive across pause/capture/resume.

type StartSpec added in v0.4.1

type StartSpec struct {
	RuntimeFiles []string
	Launch       func(ctx context.Context, rec *VMRecord, sockPath string) (int, error)
	PostLaunch   func(ctx context.Context, rec *VMRecord, sockPath string, pid int) error
}

StartSpec carries StartSequence inputs.

type StopSpec added in v0.4.1

type StopSpec struct {
	RuntimeFiles []string
	Shutdown     func(ctx context.Context, rec *VMRecord, sockPath string, pid int) error
}

StopSpec carries StopOneSequence inputs.

type VMGCSnapshot added in v0.3.6

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

VMGCSnapshot is the ReadDB-phase data for any hypervisor GC module (CH + FC share the shape).

func (VMGCSnapshot) ActiveVMIDs added in v0.3.6

func (s VMGCSnapshot) ActiveVMIDs() map[string]struct{}

func (VMGCSnapshot) UsedBlobIDs added in v0.3.6

func (s VMGCSnapshot) UsedBlobIDs() map[string]struct{}

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) GetRecord added in v0.3.9

func (idx *VMIndex) GetRecord(vmID string) (*VMRecord, error)

func (*VMIndex) Init

func (idx *VMIndex) Init()

func (*VMIndex) Resolve

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

func (*VMIndex) ResolveMany

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

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/LogDir are persisted absolute paths so cleanup still finds them if --run-dir / --log-dir change later.
	RunDir string `json:"run_dir,omitempty"`
	LogDir string `json:"log_dir,omitempty"`
}

VMRecord is the persisted record for a single VM. JSON tags live on the embedded types.VM — duplicating them here would 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