Documentation
¶
Index ¶
- Constants
- Variables
- func BalloonSize(memoryBytes int64, windows bool) (int64, bool)
- func BlobHexFromPath(path string) string
- func BuildIPParams(networkConfigs []*types.NetworkConfig, vmName string, dnsServers []string) string
- func CleanSnapshotFiles(runDir string, match func(name string) bool) error
- func CleanupRuntimeFiles(ctx context.Context, runDir string, files []string)
- func CloneSnapshotFiles(dstDir, srcDir string, classify func(name string) SnapshotFileKind) error
- func CloneStorageConfigs(storageConfigs []*types.StorageConfig) []*types.StorageConfig
- func ConsoleSockPath(runDir string) string
- func CopyFile(dst, src string) (err error)
- func DataDiskBaseName(serial string) string
- func EnterNetns(nsPath string) (restore func(), err error)
- func ExpandRawImage(path string, targetSize int64) error
- func ExtractBlobIDs(storageConfigs []*types.StorageConfig, boot *types.BootConfig) map[string]struct{}
- func InitCOWFilesystem(ctx context.Context, path string) error
- func IsDataDiskFile(name string) bool
- func IsUnderDir(path, dir string) bool
- func MergeDirInto(src, dst string) error
- func PopulateFromSrc(runDir, srcDir string, clean func(string) error, ...) error
- func PrefixToNetmask(prefix int) string
- func PreflightRestore(srcDir, rootDir, runDir string, rec *VMRecord, ...) error
- func PrepareDataDisks(ctx context.Context, baseDir string, specs []types.DataDiskSpec) ([]*types.StorageConfig, error)
- func PrepareOCICOW(ctx context.Context, cowPath string, storage int64, ...) ([]*types.StorageConfig, error)
- func PrepareStagingDir(runDir string, snapshot io.Reader) (stagingDir string, cleanup func(), err error)
- func ReflinkDataDisks(dstDir string, configs []*types.StorageConfig) error
- func RemoveVMDirs(runDir, logDir string) error
- func ReverseLayers[T any](storageConfigs []*types.StorageConfig, ...) []T
- func SaveSnapshotMeta(dir string, meta *SnapshotMeta) error
- func SocketPath(runDir string) string
- func ValidateHostCPU(cpu int) error
- func ValidateMetaPaths(meta *SnapshotMeta, rootDir, runDir string) error
- func ValidateRoleSequence(sidecar, rec []*types.StorageConfig) error
- func ValidateSnapshotIntegrity(srcDir string, sidecar []*types.StorageConfig) error
- func VerifyBaseFiles(storageConfigs []*types.StorageConfig, boot *types.BootConfig) error
- func VsockSockPath(runDir string) string
- func WaitForSocket(ctx context.Context, socketPath string, pid int, timeout time.Duration, ...) error
- type Backend
- func (b *Backend) AbortLaunch(ctx context.Context, pid int, sockPath, runDir string, runtimeFiles []string)
- func (b *Backend) BatchMarkStarted(ctx context.Context, ids []string) error
- func (b *Backend) BuildGCModule() gc.Module[VMGCSnapshot]
- func (b *Backend) BuildSnapshotConfig(snapID string, rec *VMRecord) *types.SnapshotConfig
- func (b *Backend) CleanStalePlaceholders(_ context.Context, ids []string) error
- func (b *Backend) CloneFromStream(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, ...) (_ *types.VM, err error)
- func (b *Backend) CloneSetup(ctx context.Context, vmID string, vmCfg *types.VMConfig, ...) (runDir, logDir string, now time.Time, cleanup func(), err error)
- func (b *Backend) CreateSequence(ctx context.Context, id string, spec CreateSpec) (_ *types.VM, err error)
- func (b *Backend) DeleteAll(ctx context.Context, refs []string, force bool, ...) ([]string, error)
- func (b *Backend) DirectCloneBase(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, ...) (_ *types.VM, err error)
- func (b *Backend) DirectRestoreSequence(ctx context.Context, vmRef string, spec DirectRestoreSpec) (*types.VM, error)
- func (b *Backend) FinalizeClone(ctx context.Context, vmID string, info *types.VM, bootCfg *types.BootConfig, ...) error
- func (b *Backend) FinalizeCreate(ctx context.Context, id string, info *types.VM, bootCfg *types.BootConfig, ...) error
- func (b *Backend) FinalizeRestore(ctx context.Context, vmID string, vmCfg *types.VMConfig, rec *VMRecord, ...) (*types.VM, error)
- func (b *Backend) ForEachVM(ctx context.Context, ids []string, op string, ...) ([]string, error)
- func (b *Backend) GCCollect(ctx context.Context, ids []string) error
- func (b *Backend) GracefulStop(ctx context.Context, vmID string, pid int, timeout time.Duration, ...) error
- func (b *Backend) HandleStopResult(ctx context.Context, id, runDir string, runtimeFiles []string, ...) error
- func (b *Backend) Inspect(ctx context.Context, ref string) (*types.VM, error)
- func (b *Backend) KillForRestore(ctx context.Context, vmID string, rec *VMRecord, terminate func(pid int) error, ...) error
- func (b *Backend) LaunchVMProcess(ctx context.Context, spec LaunchSpec) (pid int, err error)
- func (b *Backend) List(ctx context.Context) ([]*types.VM, error)
- func (b *Backend) LoadRecord(ctx context.Context, id string) (VMRecord, error)
- func (b *Backend) LogFilePath(logDir string) string
- func (b *Backend) LogPath(ctx context.Context, ref string) (string, error)
- func (b *Backend) MarkError(ctx context.Context, id string)
- func (b *Backend) PIDFilePath(runDir string) string
- func (b *Backend) PrepareStart(ctx context.Context, id string, runtimeFiles []string) (*VMRecord, error)
- func (b *Backend) RecordSnapshot(ctx context.Context, vmID string) (string, error)
- func (b *Backend) RegisterGC(orch *gc.Orchestrator)
- func (b *Backend) ReserveVM(ctx context.Context, id string, vmCfg *types.VMConfig, ...) error
- func (b *Backend) ResolveForRestore(ctx context.Context, vmRef string) (string, *VMRecord, error)
- func (b *Backend) ResolveRef(ctx context.Context, ref string) (string, error)
- func (b *Backend) ResolveRefs(ctx context.Context, refs []string) ([]string, error)
- func (b *Backend) RestoreSequence(ctx context.Context, vmRef string, spec RestoreSpec) (*types.VM, error)
- func (b *Backend) RollbackCreate(ctx context.Context, id, name string)
- func (b *Backend) SnapshotSequence(ctx context.Context, ref string, spec SnapshotSpec) (_ *types.SnapshotConfig, _ io.ReadCloser, err error)
- func (b *Backend) StartAll(ctx context.Context, refs []string, ...) ([]string, error)
- func (b *Backend) StopAll(ctx context.Context, refs []string, ...) ([]string, error)
- func (b *Backend) ToVM(rec *VMRecord) *types.VM
- func (b *Backend) Type() string
- func (b *Backend) UpdateStates(ctx context.Context, ids []string, state types.VMState) error
- func (b *Backend) WatchPath() string
- func (b *Backend) WithPausedVM(ctx context.Context, rec *VMRecord, pause, resume, fn func() error) error
- func (b *Backend) WithRunningVM(ctx context.Context, rec *VMRecord, fn func(pid int) error) error
- type BackendConfig
- type BaseConfig
- func (c *BaseConfig) DataDiskPath(vmID, name string) string
- func (c *BaseConfig) EnsureDirs() error
- func (c *BaseConfig) IndexFile() string
- func (c *BaseConfig) IndexLock() string
- func (c *BaseConfig) LogDir() string
- func (c *BaseConfig) RunDir() string
- func (c *BaseConfig) SocketWaitTimeout() time.Duration
- func (c *BaseConfig) TerminateGracePeriod() time.Duration
- func (c *BaseConfig) VMLogDir(vmID string) string
- func (c *BaseConfig) VMRunDir(vmID string) string
- type CreateSpec
- type Direct
- type DirectRestoreSpec
- type Hypervisor
- type LaunchSpec
- type RestoreSpec
- type SnapshotFileKind
- type SnapshotMeta
- type SnapshotSpec
- type VMGCSnapshot
- type VMIndex
- type VMRecord
- type Watchable
Constants ¶
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 )
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 )
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 ¶
Functions ¶
func BalloonSize ¶ added in v0.3.9
BalloonSize returns the balloon size in bytes and whether the balloon should be enabled. Disabled on Windows (virtio-win driver retries deflation indefinitely, blocking shutdown) and below MinBalloonMemory.
func BlobHexFromPath ¶ added in v0.2.9
BlobHexFromPath returns the digest hex of a blob path (e.g. .../abc123.erofs → abc123).
func BuildIPParams ¶ added in v0.2.9
func BuildIPParams(networkConfigs []*types.NetworkConfig, vmName string, dnsServers []string) string
func CleanSnapshotFiles ¶ added in v0.3.6
CleanSnapshotFiles removes snapshot-specific files from runDir.
func CleanupRuntimeFiles ¶ added in v0.2.9
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 DataDiskBaseName ¶ added in v0.3.8
DataDiskBaseName is the canonical file name for a user data disk. Centralized so cleanSnapshotFiles matchers, snapshot reflink loops, and clone path rewrites all agree.
func EnterNetns ¶ added in v0.2.9
func ExpandRawImage ¶ added in v0.3.6
ExpandRawImage truncates path up to targetSize. No-op if path is already at least targetSize. Used by both backends for raw COW expansion.
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 IsDataDiskFile ¶ added in v0.3.8
IsDataDiskFile reports whether name matches the data disk file pattern.
func IsUnderDir ¶ added in v0.3.9
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
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 in fresh ones from srcDir. Used by DirectRestore to swap a running VM's runtime state to a local snapshot directory.
func PrefixToNetmask ¶ added in v0.2.9
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 is the shared restore preflight: load+validate sidecar, run backend-specific integrity, then assert the snapshot's role sequence is a valid 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 raw sparse files for each spec under baseDir, optionally formats them, and returns StorageConfigs ready to append to a VM's storage list. Names must be unique and pass types.ValidDataDiskName; fstype is "ext4" (default) or "none". Returns an empty slice when specs is empty.
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 file at cowPath and returns storageConfigs with the new COW entry (CowSerial) appended. The returned slice must be used by the caller; append may reallocate.
func PrepareStagingDir ¶ added in v0.3.6
func PrepareStagingDir(runDir string, snapshot io.Reader) (stagingDir string, cleanup func(), err error)
PrepareStagingDir extracts the snapshot tar into a sibling staging dir.
func ReflinkDataDisks ¶ added in v0.3.8
func ReflinkDataDisks(dstDir string, configs []*types.StorageConfig) error
ReflinkDataDisks reflinks every Role==Data disk in configs into dstDir using the canonical data-<serial>.raw filename. Used by both CH and FC snapshot paths inside the pause window.
func RemoveVMDirs ¶ added in v0.2.9
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 ValidateHostCPU ¶ added in v0.3.1
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 that the snapshot's disk shape (sidecar) is a valid prefix of the VM's current record. Rec may have trailing cidata that the snapshot lacks (cloudimg post-first-boot snapshots) — that is 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: every disk in the sidecar passes structural validation, and every snapshot-resident disk (Role in {COW, Cidata, Data}) has its file present under srcDir. Layers are shared blobs and not part of the snapshot tar, so they're skipped here. Backends layer their own checks (e.g. CH state.json + memory-range, FC vmstate + mem) on top.
func VerifyBaseFiles ¶ added in v0.2.9
func VerifyBaseFiles(storageConfigs []*types.StorageConfig, boot *types.BootConfig) error
func VsockSockPath ¶ added in v0.3.9
Types ¶
type Backend ¶ added in v0.2.9
Backend provides shared store operations for hypervisor backends.
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
BatchMarkStarted flips ids to VMStateRunning and stamps FirstBooted=true in one DB write.
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
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 func(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, runDir, logDir string, now time.Time) (*types.VM, error), ) (_ *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 create skeleton. The placeholder-then-finalize shape lets a crash mid-create leave a rolled-back DB and rundir, so GC has nothing stale to reconcile.
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 precedes DB delete so a failed cleanup leaves the record intact for retry — otherwise an orphan rundir would survive without an index entry to GC it.
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 func(ctx context.Context, vmID string, vmCfg *types.VMConfig, net types.NetSetup, runDir, logDir string, now time.Time) (*types.VM, error), ) (_ *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; Populate replaces the tar staging+merge step used by RestoreSequence.
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{}) error
FinalizeClone updates the cloned VM's record in place after restore-and-resume.
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 writes a populated VM record to DB, replacing the placeholder.
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)
FinalizeRestore updates DB and assembles the returned VM after restore.
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) GCCollect ¶ added in v0.2.9
GCCollect kills leftover hypervisor processes and removes orphan dirs/records. Runs under the GC orchestrator's flock — uses lock-free DB access.
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 (*Backend) Inspect ¶ added in v0.2.9
Inspect returns VM info for a single VM by ref (ID, name, or prefix).
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
KillForRestore stops the running VM via the backend-specific terminate hook and clears runtime files.
func (*Backend) LaunchVMProcess ¶ added in v0.3.9
LaunchVMProcess starts spec.Cmd and waits for the API socket. On any error after Start, the process is killed and the PID file is removed. Caller reaps cmd via cmd.Wait() in a goroutine on success.
func (*Backend) LoadRecord ¶ added in v0.2.9
LoadRecord returns a value-copy of the VMRecord for an exact VM ID.
func (*Backend) LogFilePath ¶ added in v0.4.0
LogFilePath returns the per-VM hypervisor log file under logDir, named after the backend type. Used at launch time (write) and by LogPath (read) so the two ends can't drift.
func (*Backend) LogPath ¶ added in v0.4.0
LogPath resolves ref to a VM ID and returns its hypervisor log path. Reads LogDir from the persisted record so it stays correct after a --log-dir config change; falls back to the current Conf for legacy records that predate LogDir persistence.
func (*Backend) MarkError ¶ added in v0.2.9
MarkError flips a single VM's state to VMStateError, logging on persist failure.
func (*Backend) PIDFilePath ¶ added in v0.2.9
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
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) ResolveForRestore ¶ added in v0.3.6
ResolveForRestore resolves vmRef and validates the VM is running.
func (*Backend) ResolveRef ¶ added in v0.2.9
ResolveRef resolves a single ref (ID, name, or prefix) to an exact VM ID.
func (*Backend) ResolveRefs ¶ added in v0.2.9
ResolveRefs batch-resolves refs to exact VM IDs 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. Staging happens before the kill so a preflight failure leaves the original VM running.
func (*Backend) RollbackCreate ¶ added in v0.2.9
RollbackCreate removes a placeholder VM record from the DB.
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. The pause window is the VM-availability hit, so all hot work (capture only) runs inside it and 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) error) ([]string, error)
StartAll runs startOne for each ref and batch-flips the succeeded set to Running so a partial batch doesn't leave half-Running state.
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) ToVM ¶ added in v0.2.9
ToVM converts a stored VMRecord into the runtime types.VM exposed to callers.
func (*Backend) UpdateStates ¶ added in v0.2.9
UpdateStates batch-updates the State field for ids; sets StartedAt/StoppedAt as appropriate.
func (*Backend) WatchPath ¶ added in v0.3.6
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. Resume on the success path is eager so its error promotes to the return; on fn-error the deferred resume only logs (the inner error wins).
type BackendConfig ¶ added in v0.2.9
type BackendConfig interface {
BinaryName() string
PIDFileName() string
TerminateGracePeriod() time.Duration
SocketWaitTimeout() time.Duration
EffectivePoolSize() int
IndexFile() string
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
BaseConfig holds the directory layout and timeout defaults shared by all hypervisor backends. Each backend embeds BaseConfig and adds backend-specific methods (BinaryName, PIDFileName, etc.).
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 file path for a user data disk. Filename includes the disk name so cleanSnapshotFiles matchers can identify them via prefix.
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, networkConfigs []*types.NetworkConfig, boot *types.BootConfig) ([]*types.StorageConfig, error)
}
CreateSpec carries the inputs to CreateSequence. Prepare returns the final storage configs (e.g. with COW + data disks attached); the rest of the sequence is uniform across backends.
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 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
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 rather than a tar; 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) (*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 // empty = host netns
OnFail func() // optional cleanup on any error path
}
LaunchSpec is the per-call input to Backend.LaunchVMProcess. Shared BinaryName / SocketWaitTimeout come from BackendConfig.
type RestoreSpec ¶ added in v0.3.9
type RestoreSpec struct {
VMCfg *types.VMConfig
Snapshot io.Reader
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 // optional disk lock around merge+afterExtract
BeforeMerge func(rec *VMRecord) error // e.g. FC removes stale COW
AfterExtract func(ctx context.Context, vmID string, vmCfg *types.VMConfig, rec *VMRecord) (*types.VM, error)
}
RestoreSpec carries the backend-specific 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 the backend-specific hooks for SnapshotSequence. hc is the shared http.Client built by SnapshotSequence so HTTP keep-alive reuses one CH/FC API socket connection across pause/capture/resume.
type VMGCSnapshot ¶ added in v0.3.6
type VMGCSnapshot struct {
// contains filtered or unexported fields
}
VMGCSnapshot holds the data collected during the ReadDB phase of a hypervisor GC module. Both Cloud Hypervisor and Firecracker produce identical snapshots; the type lives here to avoid duplication.
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.
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.