vmruntime

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0 Imports: 14 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.

Documentation

Overview

Package vmruntime holds host-side state for the managed VM.

Index

Constants

View Source
const (
	EnvFirstBootTimeout = "APP_VM_FIRST_BOOT_TIMEOUT"
	EnvFirstBootMax     = "APP_VM_FIRST_BOOT_MAX"
	EnvFirstBootStall   = "APP_VM_FIRST_BOOT_STALL"
	EnvSetupAttempts    = "APP_VM_SETUP_ATTEMPTS"
)

Env names for the first boot window. They seed the settings file at init.

View Source
const (
	DefaultFirstBootTimeout = 20 * time.Minute
	DefaultFirstBootMax     = 45 * time.Minute
	DefaultFirstBootStall   = 5 * time.Minute
	// DefaultSetupAttempts is how many failed setup boots pass before recreating is advised.
	DefaultSetupAttempts = 3
)

A first boot downloads and installs packages, so it gets far longer than a normal start.

View Source
const (
	EnvExperimental    = "APP_VM_EXPERIMENTAL"
	EnvMemoryMiB       = "APP_VM_MEMORY_MIB"
	EnvCPUs            = "APP_VM_CPUS"
	EnvDiskGiB         = "APP_VM_DISK_GIB"
	EnvMemoryMaxPct    = "APP_VM_MEMORY_MAX_PERCENT"
	EnvMemoryMinMiB    = "APP_VM_MEMORY_MIN_MIB"
	EnvBootTimeout     = "APP_VM_BOOT_TIMEOUT"
	EnvDashboardPort   = "APP_VM_DASHBOARD_PORT"
	EnvIngressPort     = "APP_VM_INGRESS_PORT"
	EnvUpgradeHealth   = "APP_VM_UPGRADE_HEALTH_TIMEOUT"
	EnvSocketPathMax   = "APP_VM_SOCKET_PATH_MAX"
	EnvSharesMax       = "APP_VM_SHARES_MAX"
	EnvDockerSocket    = "APP_VM_DOCKER_SOCKET"
	EnvRecheckSec      = "APP_VM_ISOLATION_RECHECK_SEC"
	EnvWatchListErrors = "APP_VM_WATCH_LIST_ERRORS"
	DefaultBootTimeout = 180 * time.Second
	// DefaultUpgradeHealth is how long vm upgrade waits for the new control plane before rolling back.
	DefaultUpgradeHealth = 5 * time.Minute
	// DefaultSocketPathMax is the unix socket path limit on macOS (sun_path, with its NUL).
	DefaultSocketPathMax = 104
	// DefaultWatchListErrors is how many failed VM listings in a row the watcher tolerates.
	DefaultWatchListErrors = 3
)

Env names. Env only seeds the file at init; the stored value wins afterwards.

View Source
const (
	Instance  = "levelrail"
	TokenPath = "/var/lib/levelrail/data/desktop-token" //nolint:gosec // a guest file path, not a credential
	// ExchangePath and SessionCookie mirror internal/desktopmode.
	ExchangePath  = "/api/desktop/exchange"
	SessionCookie = "session_token"
)

Guest names the host side reaches over limactl.

View Source
const DashboardHost = "levelrail.localhost"

DashboardHost is the only host name desktop mode serves on, so cookies stay host-only and never leak across other localhost ports.

View Source
const SchemaVersion = 1

SchemaVersion is bumped when the file layout changes incompatibly.

View Source
const StageRepairFailed = "failed:repair"

StageRepairFailed is reported by the guest when its package database could not be repaired.

Variables

View Source
var ErrNotFound = errors.New("vm settings file not found")

ErrNotFound means no settings file exists yet.

Functions

func BeginOperation

func BeginOperation(path, name string) (func(), error)

BeginOperation takes the lifecycle lock for name, or returns a *BusyError without waiting for the holder. The returned func releases it; a dead process releases it by itself.

func BootTimeout

func BootTimeout(env Lookup) (time.Duration, error)

BootTimeout reads APP_VM_BOOT_TIMEOUT as a Go duration.

func DashboardURL

func DashboardURL(port int) string

DashboardURL is the URL users and the desktop shell open for a dashboard port.

func DefaultPath

func DefaultPath() (string, error)

DefaultPath is the settings file under the user config dir.

func Exchange

func Exchange(ctx context.Context, client *http.Client, port int, token string) (*http.Cookie, string, error)

Exchange trades the token for a dashboard session on the loopback port. The Host header is the desktop name, which is all the control plane serves.

func IntEnv

func IntEnv(env Lookup, name string, def int) (int, error)

IntEnv returns the integer in name, or def when unset or empty.

func LifecyclePath

func LifecyclePath(dataDir string) string

LifecyclePath is the lock file that lets one lifecycle command at a time touch the VM.

func Limits

func Limits(env Lookup, hostMemMiB, hostCPUs int, homeDir, dataDir string) (lima.Limits, error)

Limits derives lima limits from the host and APP_VM_MEMORY_* env.

func LockFile

func LockFile(f *os.File) error

LockFile waits for an exclusive advisory lock, which closing f releases.

func LockPath

func LockPath(path string) string

LockPath is the lock file that orders writers of the settings file at path.

func ParseOnOff

func ParseOnOff(v string) (bool, error)

ParseOnOff accepts exactly on or off.

func ReadToken

func ReadToken(ctx context.Context, r Runner) (string, error)

ReadToken returns the guest desktop token. It is held in memory only and never logged.

func Save

func Save(path string, s Settings) error

Save writes s atomically with mode 0600: temp file, fsync, rename.

func ShareIdentity

func ShareIdentity(path string) (string, error)

ShareIdentity names the folder object at path, so a different folder put there later is told apart.

func SocketPathMax

func SocketPathMax(env Lookup) (int, error)

SocketPathMax reads the unix socket path limit used to choose the Lima home.

func TokenExists

func TokenExists(ctx context.Context, r Runner) bool

TokenExists reports whether the guest token file is present.

func TryLockFile

func TryLockFile(f *os.File) bool

TryLockFile takes the lock only if nobody holds it.

func Update

func Update(path string, apply func(*Settings) error) error

Update changes the stored settings while holding the writer lock, so concurrent commands cannot undo each other. Nothing is saved when apply fails.

func Upsert

func Upsert(path string, fresh Settings, apply func(*Settings)) error

Upsert is Update for first writes: fresh is saved as it is when no file exists yet.

Types

type Applied

type Applied struct {
	MemoryMiB     int `json:"memory_mib"`
	CPUs          int `json:"cpus"`
	DiskGiB       int `json:"disk_gib"`
	DashboardPort int `json:"dashboard_port"`
	IngressPort   int `json:"ingress_port"`
	// Shares are the folders mounted at that start.
	Shares       []Share `json:"shares,omitempty"`
	DockerSocket bool    `json:"docker_socket,omitempty"`
	RecheckSec   int     `json:"isolation_recheck_seconds,omitempty"`
}

Applied is what the running instance was last started with, so status can show settings that wait for a restart.

type BootWindow

type BootWindow struct {
	// Base is the normal limit. Max is the hard ceiling, reachable only while progress is seen.
	Base, Max time.Duration
	// Stall is how recent progress must be to keep waiting past Base. Zero never extends.
	Stall time.Duration
}

BootWindow bounds how long a start may run before the guest has to have passed its isolation check.

type BusyError

type BusyError struct{ Op Operation }

BusyError means another lifecycle command is still running.

func (*BusyError) Error

func (e *BusyError) Error() string

type Lookup

type Lookup func(string) (string, bool)

Lookup reads one env value, like os.LookupEnv.

type Operation

type Operation struct {
	Name  string `json:"name"`
	PID   int    `json:"pid"`
	Since string `json:"since"`
}

Operation is the lifecycle command that holds the VM.

func CurrentOperation

func CurrentOperation(path string) (Operation, bool)

CurrentOperation reports the lifecycle command in progress, if a live process holds the lock.

type Recheck

type Recheck struct {
	At     string `json:"at"`
	Result string `json:"result"` // pass or fail
	Detail string `json:"detail,omitempty"`
}

Recheck is the last isolation check the host ran while the Docker socket was on.

type Runner

type Runner interface {
	Run(ctx context.Context, args ...string) ([]byte, error)
}

Runner is the part of limactl access ReadToken needs.

type Settings

type Settings struct {
	Version       int      `json:"version"`
	MemoryMiB     int      `json:"memory_mib"`
	CPUs          int      `json:"cpus"`
	DiskGiB       int      `json:"disk_gib"`
	DashboardPort int      `json:"dashboard_port"`
	IngressPort   int      `json:"ingress_port"`
	Applied       *Applied `json:"applied,omitempty"`
	// Shares is empty unless the user opts in with `vm share add`.
	Shares    []Share `json:"shares,omitempty"`
	SharesMax int     `json:"shares_max,omitempty"`
	// DockerSocket gives the Mac's docker CLI the guest engine. Off unless the user opts in.
	DockerSocket bool     `json:"docker_socket,omitempty"`
	RecheckSec   int      `json:"isolation_recheck_seconds,omitempty"`
	LastRecheck  *Recheck `json:"last_recheck,omitempty"`
	// WatchListErrors is seeded from env at init; the stored value wins.
	WatchListErrors int `json:"watch_list_errors,omitempty"`
	// StartingUntil marks a start in progress, when a recheck would see a half provisioned guest.
	StartingUntil string `json:"starting_until,omitempty"`
	// UpgradeHealth is a Go duration, seeded from env at init; the stored value wins.
	UpgradeHealth string `json:"upgrade_health_timeout,omitempty"`
	// First boot limits and the setup attempt count, seeded from env at init; the stored values win.
	FirstBootTimeout string `json:"first_boot_timeout,omitempty"`
	FirstBootMax     string `json:"first_boot_max,omitempty"`
	FirstBootStall   string `json:"first_boot_stall,omitempty"`
	SetupAttempts    int    `json:"setup_attempts,omitempty"`
	// Setup is set while setup is unfinished.
	Setup         *Setup         `json:"setup,omitempty"`
	UpgradeBackup *UpgradeBackup `json:"upgrade_backup,omitempty"`
}

Settings is the host settings file. Ports are host loopback ports.

func Load

func Load(path string) (Settings, error)

Load reads and checks the schema version of the file at path.

func SeedFromEnv

func SeedFromEnv(env Lookup) (Settings, error)

SeedFromEnv builds first-init settings from env over the ADR defaults. Ports stay 0 when unset: the caller picks free ones.

func (*Settings) AdoptShareIdentities

func (s *Settings) AdoptShareIdentities(l lima.Limits) error

AdoptShareIdentities records the identity of such shares once they pass every share check. From then on a different folder at the same path is refused.

func (Settings) ListErrorLimit

func (s Settings) ListErrorLimit(env Lookup) int

ListErrorLimit is the stored count, else env, else the default; never below one.

func (Settings) NeedsShareIdentity

func (s Settings) NeedsShareIdentity() bool

NeedsShareIdentity reports shares stored before identities were recorded.

func (Settings) Pending

func (s Settings) Pending() []string

Pending lists settings whose stored value differs from the running one.

func (Settings) PinShares

func (s Settings) PinShares() (Settings, error)

PinShares re-resolves every share right before use and returns settings that carry the resolved paths. It fails when a path no longer leads to the folder that was shared.

func (Settings) RecheckInterval

func (s Settings) RecheckInterval() int

RecheckInterval is the stored seconds between isolation rechecks, or the default.

func (Settings) RecreateAdvised

func (s Settings) RecreateAdvised(env Lookup) bool

RecreateAdvised reports that resuming has failed often enough, or the guest cannot be repaired.

func (Settings) SetupIncomplete

func (s Settings) SetupIncomplete() bool

SetupIncomplete reports a guest that never finished setup, so it holds no apps or data.

func (Settings) ToLima

func (s Settings) ToLima() lima.Settings

ToLima converts to template settings. Sidecar is supplied by the caller.

func (Settings) UpgradeTimeout

func (s Settings) UpgradeTimeout(env Lookup) (time.Duration, error)

UpgradeTimeout is the stored health gate, else env, else the default.

func (Settings) Validate

func (s Settings) Validate(l lima.Limits) error

Validate checks the settings through the template validator.

func (Settings) Window

func (s Settings) Window(env Lookup) (BootWindow, error)

Window is the boot window of the next start: the short fixed one once setup is complete.

type Setup

type Setup struct {
	// ControlPlaneBin and ControlPlaneSHA let a later `vm start` finish an interrupted init.
	ControlPlaneBin string `json:"control_plane_bin,omitempty"`
	ControlPlaneSHA string `json:"control_plane_sha256,omitempty"`
	Failures        int    `json:"failures,omitempty"`
	// Stage is the last provisioning step the guest reported.
	Stage     string `json:"stage,omitempty"`
	LastError string `json:"last_error,omitempty"`
}

Setup is present until a start has provisioned the guest and installed the control plane.

type Share

type Share struct {
	HostPath  string `json:"host_path"`
	GuestPath string `json:"guest_path"`
	// Identity pins the folder object chosen at `vm share add`.
	Identity string `json:"identity,omitempty"`
}

Share is one opted-in host folder, always mounted read-only.

type UpgradeBackup

type UpgradeBackup struct {
	Path   string `json:"path"`
	At     string `json:"at"`
	Result string `json:"result"`
}

UpgradeBackup records the last guest data backup taken by vm upgrade.

Directories

Path Synopsis
Package guest holds the files and helpers that run inside the managed VM: the egress firewall baseline, the isolation self-check and the provisioning script.
Package guest holds the files and helpers that run inside the managed VM: the egress firewall baseline, the isolation self-check and the provisioning script.
Package lima renders and validates the Lima template for the managed VM.
Package lima renders and validates the Lima template for the managed VM.
Package limadist downloads and installs the pinned Lima release the managed VM runs on.
Package limadist downloads and installs the pinned Lima release the managed VM runs on.

Jump to

Keyboard shortcuts

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