Lifecycle convergence
ConnectOrCreateSandbox converges on the current persisted sandbox by name and uses options only when it creates. Receiver lifecycle operations are bound to the stable opaque ID; a stale receiver returns ErrSandboxReplaced instead of acting on a replacement that reused the name. Sandbox also exposes WaitForStatus, Restart, and Destroy. See Lifecycle convergence and identity safety for state behavior and examples.
Functions
m.CreateSandbox()
Example
Example
*Sandbox owns the VM process. Call Close (or Stop + Close) when done. See Options for all configuration knobs.
Parameters
ctxcontext.Contextnamestringopts…SandboxOptionReturns
*Error, see Error Handling.m.ConnectOrCreateSandbox()
SandboxStatusStarting, starts it when it is created, stopped, or crashed, and creates it only when the name is absent. Options apply only to creation; an existing sandbox keeps its persisted configuration. Concurrent callers converge on the winning identity. WithReplace and WithReplaceWithTimeout are invalid with this function.
Parameters
ctx: controls this convergence operation; cancellation does not stop a sandbox already returned.name: reusable sandbox name, up to 128 UTF-8 bytes.opts: the same creation options accepted byCreateSandbox, used only when creation is necessary.
Returns
(*Sandbox, error)
m.GetSandbox()
Example
Example
Kind == ErrSandboxNotFound if no such sandbox exists. The returned *SandboxHandle exposes Connect, Start, Stop, Kill, Remove, Ping, Touch, Metrics, Logs, and snapshot methods.
Parameters
namestringReturns
m.ListSandboxes()
Example
Example
Returns
m.ListSandboxesWith()
Example
Example
Parameters
options…SandboxListOptionWithListLimit, WithListCursor, and/or WithListLabels options.Returns
m.StartSandbox()
Example
Example
*Sandbox.
Parameters
namestringReturns
m.StartSandboxDetached()
Parameters
namestringReturns
m.RemoveSandbox()
Example
Example
Parameters
namestringm.AllSandboxMetrics()
Example
Example
Metrics snapshot for every running sandbox, keyed by sandbox name. Only running and draining sandboxes appear.
Returns
Sandbox
A live sandbox connection that is safe for concurrent use.sb.Name()
Returns
sb.ID()
sb.FS()
Example
Example
Returns
sb.SSH()
Example
Example
Returns
sb.Logs()
Example
Example
exec.log. Backed by an on-disk file, so it works for running and stopped sandboxes alike without guest-agent protocol traffic. The default sources are stdout and stderr; add LogSourceOutput for PTY-merged output or LogSourceSystem for runtime and kernel diagnostics. The same method exists on SandboxHandle for callers that don’t want to start the sandbox first.
Parameters
optsLogOptionsTail, Since, Until, Sources. The zero value returns everything for the default stdout and stderr sources.Returns
sb.LogStream()
Example
Example
LogStreamOptions{Follow: true} to keep the stream open past current EOF and pick up new entries as they are written. Close the returned *LogStreamHandle when done. Also available on SandboxHandle.
Parameters
optsLogStreamOptionsSince or FromCursor start point.Returns
Recv in a loop.sb.Ping()
Example
Example
core.ping and waits for core.pong; it does not start stopped sandboxes and returns an error if the sandbox is not running or agentd cannot respond. After upgrading from a runtime that predates protocol generation 6, restart already-running sandboxes so the guest agent understands the message.
Returns
sb.Touch()
Example
Example
core.touch, receives core.touched, and advances the guest activity sequence used by the runtime idle-timeout monitor. It does not start stopped sandboxes and it does not bypass MaxDuration.
Returns
sb.Modify()
Example
Example
"live", "next start", "requires restart", or "unsupported", and apply is all-or-nothing.
CPUs and MemoryMiB resize live within the WithMaxCPUs / WithMaxMemory ceilings; raising a ceiling requires a restart. RootDiskSizeMiB changes are offline: managed and flat OCI root disks grow only, tmpfs root disks can change in either direction on the next boot, and user-supplied disk images are rejected. Env and workdir changes affect future execs only. On a stopped sandbox, changes are saved for the next boot.
Secret specs are keyed by stable secret name. Each SecretModifySpec selects at most one source—Env, Value, or Store—and may also set Placeholder and AllowedHosts; omitting a source updates only the other supplied fields. Plans expose only safe references and metadata; raw secret values never appear in a plan. Removal is explicit through SecretsRemove.
A live CPU or memory resize can take a moment to settle. The new limits are enforced immediately, and the returned plan’s ResizeStatus reports when the sandbox has finished adjusting. See SandboxModificationPlan.
Parameters
optsModifyOptionsPolicy and DryRun. Zero-valued fields are left unchanged.Returns
DryRun is set.sb.Metrics()
Example
Example
Returns
sb.MetricsStream()
Example
Example
Metrics snapshot every interval. Sub-millisecond precision is rounded up; a zero or negative value uses the runtime minimum (~1 ms). Close the returned *MetricsStreamHandle when done.
Parameters
intervaltime.DurationReturns
Recv in a loop.sb.Attach()
Parameters
cmdstringargs…stringReturns
sb.AttachWith()
Example
Example
Attach, but takes AttachOption values so the session can run as a different guest user, in a different working directory, with extra environment variables, or with custom detach keys.
Parameters
Returns
sb.AttachShell()
WithShell, defaults to /bin/sh). Blocks until the shell exits and returns its exit code.
Returns
sb.Stop()
Example
Example
WithStopTimeout to change it.
Parameters
opts…StopOptionWithStopTimeout(30 * time.Second).sb.RequestStop()
WaitUntilStopped to await termination.
sb.Kill()
Example
Example
fsync’d may be lost. Prefer Stop for graceful shutdown. Defaults to a five-second observation window; pass WithKillTimeout to change it.
Parameters
opts…KillOptionsb.RequestKill()
sb.RequestDrain()
sb.WaitUntilStopped()
Example
Example
Returns
sb.WaitForStatus()
status, returning a refreshed metadata handle. The context supplies cancellation or a deadline. Returns ErrSandboxReplaced rather than following a reused name.
sb.Restart()
WithRestartForce, WithRestartTimeout, and WithRestartDetached for explicit controls.
sb.Destroy()
WithDestroyForce or WithDestroyTimeout for explicit controls. Returns ErrSandboxReplaced instead of deleting a same-name replacement.
sb.Detach()
Example
Example
WithDetached once the caller is done with the handle but the sandbox should keep running in the background. After Detach, the handle is invalid; a subsequent Close returns an error with Kind == ErrInvalidHandle. Reconnect later with GetSandbox.
sb.Close()
Example
Example
Kind == ErrInvalidHandle. A local attached handle stops its VM on Close; local detached and cloud handles release client resources only. Stop or remove a cloud sandbox explicitly.
sb.OwnsLifecycle()
true; local detached handles and all cloud handles return false, because the cloud worker owns the sandbox process. The error return covers stale handles and FFI failures; use OwnsLifecycleOrFalse when you don’t care.
Returns
true for a local attached handle.sb.OwnsLifecycleOrFalse()
OwnsLifecycle that swallows the error and returns false for cloud, detached, or invalid handles. Suitable for log lines and best-effort branching.
Returns
true if attached, false on detach or error.Options
Functional options for creating and listing sandboxes. Map and slice options merge across repeated calls; single-value setters likeWithImage replace.
WithListLimit()
Parameters
limituint32WithListCursor()
NextCursor. Keep the same label filters when requesting the next page.
Parameters
cursorstringWithListLabels()
Parameters
labelsmap[string]stringWithImage()
"python:3.12", "docker.io/library/alpine"). Required unless WithFromSnapshot is used. Use WithImageDisk when a disk-image root needs an explicit filesystem type.
Parameters
imagestringWithOCIUpperSize()
Parameters
mebibytesuint32WithImageDisk()
"ext4". The disk format is inferred from the path extension (.qcow2, .raw, or .vmdk).
Parameters
pathstringfstypestringWithFromSnapshot()
WithImage. Pass a SnapshotArtifact or SnapshotHandle
directly to preserve its typed identifier-or-path reference without inspecting
the selected backend.
Parameters
snapshotstring | *SnapshotArtifact | *SnapshotHandleWithMemory()
512 MiB.
Parameters
mebibytesuint32WithMaxMemory()
Parameters
mebibytesuint32WithTHP()
THPMadvise.
Parameters
policyTHPPolicyTHPAlways, THPMadvise, or THPNever.WithCPUs()
1.
Parameters
cpusuint8WithMaxCPUs()
Parameters
cpusuint8WithWorkdir()
Parameters
pathstringWithShell()
Shell and AttachShell. Defaults to /bin/sh on most images.
Parameters
shellstring“/bin/bash”.WithSecurityProfile()
SecurityProfileRestricted applies stronger hardening: sets no_new_privs, drops mount-admin capability from user commands, and forces nosuid,nodev on user mounts.
Parameters
profileSecurityProfileWithEnv()
Parameters
envmap[string]stringWithLabels()
ListSandboxesWith filtering. Called repeatedly, the maps merge; later keys overwrite earlier ones. Keys must not use the reserved prefixes sandbox., microsandbox., or service..
Parameters
labelsmap[string]stringWithLabel()
WithLabels with one entry.
Parameters
keystringvaluestringWithHostname()
Parameters
hostnamestringWithUser()
Parameters
userstringWithReplace()
WithReplaceWithTimeout to set a different window.
WithReplaceWithTimeout()
WithReplace but with a caller-specified timeout between SIGTERM and SIGKILL. Implies WithReplace; calling this alone is enough. A zero duration skips SIGTERM and SIGKILLs immediately.
Parameters
timeouttime.DurationWithDetached()
GetSandbox. Close releases this non-owning handle without stopping the VM.
WithEphemeral()
Parameters
ephemeralbooltrue to delete all state on termination.WithEntrypoint()
Exec, Attach, and Shell calls ignore it. This is the user workload, not the guest PID 1; for that, use WithInit instead.
Parameters
cmd…stringWithCmd()
WithCmd() with no arguments explicitly clears the image CMD. This describes durable configuration and does not execute anything during CreateSandbox.
WithInit()
Example
Example
cfg via the Init factory. See Custom init system for image picks and shutdown semantics.
Parameters
cfgInitConfigWithLogLevel()
LogLevel.
Parameters
levelLogLevelWithQuietLogs()
WithScripts()
/.msb/scripts/<name> inside the guest. Scripts are added to PATH and can be called by name. Called repeatedly, entries merge; later names overwrite earlier ones.
Parameters
scriptsmap[string]stringWithPullPolicy()
PullPolicy.
Parameters
WithMaxDuration()
Parameters
dtime.DurationWithIdleTimeout()
Parameters
dtime.DurationWithRegistryAuth()
RegistryAuth.
Parameters
authRegistryAuthWithRegistryInsecure()
localhost:5050/my-app:latest.
WithRegistryCACerts()
Parameters
pem[]byteWithRegistryCACertsPath()
WithRegistryCACerts but reads the PEM bundle from a file. The file is read when CreateSandbox runs, which fails if it is unreadable. Called repeatedly, the bundles accumulate.
Parameters
pathstringWithPorts()
127.0.0.1. Called repeatedly, the maps merge.
Parameters
portsmap[uint16]uint16WithPortsUDP()
127.0.0.1.
Parameters
portsmap[uint16]uint16WithPortBindings()
0.0.0.0. See PortBinding for the type definition and UDP examples.
Parameters
bindings…PortBindingWithNetwork()
Example
Example
NetworkPolicy factory or a *NetworkConfig literal. See Networking.
Parameters
WithSecrets()
Secret factory. See Secrets.
Parameters
secrets…SecretEntryWithPatches()
Example
Example
Patch factory.
Parameters
patches…PatchConfigWithMounts()
Example
Example
Mount factory. Called repeatedly, the maps merge; later entries overwrite earlier ones for the same guest path. See Volumes.
Parameters
mountsmap[string]MountConfigWithStopTimeout()
Stop waits for graceful shutdown before force-killing. Default: 10 seconds. This is a StopOption, not a SandboxOption. Pass it to Stop.
Parameters
timeouttime.DurationWithConnectOrStartDetached()
ConnectOrStart must start a local sandbox, start it in detached/background mode. This option does not change ownership when the sandbox is already running.
WithRestartForce()
Restart.
WithRestartTimeout()
Restart. The default is ten seconds.
WithRestartDetached()
WithDestroyForce()
Destroy.
WithDestroyTimeout()
Destroy. The default is ten seconds.
WithKillTimeout()
Kill waits for stopped-state observation. Default: 5 seconds. This is a KillOption, pass it to Kill.
Parameters
timeouttime.DurationWithSkipDownload() option is documented under Runtime setup.
Attach options
WithAttachCwd()
Parameters
pathstringWithAttachUser()
WithUser).
Parameters
userstringuser:group.WithAttachEnv()
Parameters
envmap[string]stringWithAttachDetachKeys()
ctrl-] (the default), ctrl-p,ctrl-q, or a single character like q.
Parameters
keysstringPatch
Produces PatchConfig for WithPatches()
Factory forPatchConfig values.
Patch.Text()
path.
Parameters
pathstringcontentstringoptsPatchOptionsMode and Replace.Patch.Append()
content to an existing file at path. If the file lives in a lower image layer, it is copied up first.
Parameters
pathstringcontentstringPatch.Mkdir()
opts.Mode is honored; Replace is ignored.
Parameters
pathstringoptsPatchOptionsMode applies.Patch.Remove()
path. Idempotent.
Parameters
pathstringPatch.Symlink()
link pointing to target. Only opts.Replace is honored.
Parameters
targetstringlinkstringoptsPatchOptionsReplace applies.Patch.CopyFile()
src into the guest rootfs at dst.
Parameters
srcstringdststringoptsPatchOptionsMode and Replace.Patch.CopyDir()
src into the guest rootfs at dst. Only opts.Replace is honored.
Parameters
srcstringdststringoptsPatchOptionsReplace applies.Init
Produces InitConfig for WithInit()
Factory forInitConfig values.
Init.Auto()
Example
Example
/sbin/init, /lib/systemd/systemd, …) inside the guest.
Returns
Init.Cmd()
Example
Example
cmd must be an absolute path inside the guest rootfs.
Parameters
cmdstringoptsInitOptionsSandboxHandle
Returned by GetSandbox() · ListSandboxes() · ListSandboxesWith()
A sandbox metadata and lifecycle handle that does not require an active guest-agent connection.h.Name()
Returns
string
h.ID()
ErrSandboxReplaced when the reusable name now points to another sandbox.
h.Status()
Returns
SandboxStatus
h.ConfigJSON()
Returns
string
h.Config()
Returns
(*SandboxConfig, error)
h.CreatedAt()
Returns
time.Time
h.UpdatedAt()
Returns
time.Time
h.Refresh()
Returns
(*SandboxHandle, error)
h.Ping()
Returns
(*SandboxPingResult, error)
h.Touch()
Returns
(*SandboxTouchResult, error)
h.Modify()
ModifyOptions as Modify(). Does not start stopped sandboxes; changes persist for the next boot
Returns
(*SandboxModificationPlan, error)
h.Metrics()
Returns
(*Metrics, error)
h.Logs()
exec.log (works without starting)
Returns
([]LogEntry, error)
h.LogStream()
Returns
(*LogStreamHandle, error)
h.Connect()
Returns
(*Sandbox, error)
h.ConnectOrStart()
SandboxStatusStarting, or start it when it is created, stopped, or crashed. Draining and paused states are rejected. WithConnectOrStartDetached affects only a required local start; connecting to an already-running sandbox does not change ownership.
h.Start()
Returns
(*Sandbox, error)
h.StartDetached()
Returns
(*Sandbox, error)
h.WaitForStatus()
status, returning a refreshed handle. The context supplies cancellation or a deadline. Returns ErrSandboxReplaced rather than rebinding to a replacement.
h.Restart()
Sandbox.Restart.
h.Destroy()
ErrSandboxReplaced instead of destroying a same-name replacement.
h.Stop()
StopOption
Returns
error
h.RequestStop()
Returns
error
h.Kill()
KillOption
Returns
error
h.RequestKill()
Returns
error
h.RequestDrain()
Returns
error
h.WaitUntilStopped()
Returns
(*SandboxStopResult, error)
h.Remove()
Returns
error
h.Snapshot()
Returns
(*SnapshotArtifact, error)
MetricsStreamHandle
Returned by MetricsStream()
Live metrics subscription. CallClose to release Rust-side resources.
metricsStream.Recv()
(nil, nil) when the stream ends (sandbox exited)
Returns
(*Metrics, error)
metricsStream.Close()
Returns
error
LogEntry
Returned by Logs() · LogStream()
A single captured log entry.entry.Source
LogSource
Origin of the captured data
entry.SessionID
*uint64
Relay-monotonic session id; nil for system entries
entry.Timestamp
time.Time
Wall-clock capture time on the host
entry.Data
[]byte
The captured bytes
entry.Cursor
string
Opaque resume token; pass to LogStreamOptions.FromCursor
entry.Text()
Returns
string
LogStreamHandle
Returned by LogStream()
Live log subscription. CallClose to release Rust-side resources.
logStream.Recv()
(nil, nil) when the stream ends
Returns
(*LogEntry, error)
logStream.Close()
Returns
error
Types
SandboxPingResult
Returned by Ping()
Agent reachability result.SandboxTouchResult
Returned by Touch()
Explicit idle-refresh result.ModifyOptions
Used by Modify()
A requested sandbox modification. Zero-valued fields are left unchanged (0 is not a valid CPU, memory, or disk size).
SecretModifySpec
Used by Modify()
Desired state for one secret.Env, Value, and Store are mutually exclusive sources. Leave all three empty to update only the placeholder or allowed hosts.
SandboxModificationPlan
Returned by Modify()
Dry-run or apply plan for a sandbox modification. Values never appear in a plan: secret entries carry only guest-visible references.PlannedChange is one planned entry. Kind is "config" or "secret"; config entries carry Before / After while secret entries carry Name, BeforeRef / AfterRef (guest-visible references, values are omitted by construction), and AllowHosts:
ResourceResizeStatus reports runtime convergence for a live resize; enforcement applies immediately, the guest converges asynchronously:
SandboxPage
One stable, newest-first page returned byListSandboxes or ListSandboxesWith. Pass NextCursor back through WithListCursor with the same filters to continue.
SandboxListOption
Functional options accepted byListSandboxesWith.
SandboxConfig
Populated by SandboxOption · parsed by SandboxHandle.Config()
The full configuration of a sandbox. Most callers build a sandbox viaCreateSandbox(ctx, name, ...opts); SandboxConfig is exported for callers that prefer to construct a value directly.
SandboxOption
Consumed by CreateSandbox()
CreateSandbox. Every WithX helper in the Options section returns one. The lifecycle setters WithStopTimeout and WithKillTimeout return distinct StopOption / KillOption types passed to Stop and Kill instead.
AttachConfig
Populated by AttachOption
Configures a singleAttachWith call. Most callers set fields through the WithAttach* functional options; AttachConfig is exported for parity with the other SDKs’ config types.
AttachOption
Accepted by sb.AttachWith()
AttachConfig. Construct them with the WithAttach* functions below.
Metrics
Returned by Metrics() · MetricsStream() · AllSandboxMetrics()
Point-in-time resource usage snapshot.SandboxStopResult
Returned by WaitUntilStopped()
Describes a terminal sandbox state observed byWaitUntilStopped.
SandboxStatus
Used by SandboxHandle.Status() · SandboxStopResult.Status
LogOptions
Used by Logs()
Filters passed toLogs. The zero value returns everything for the default sources (stdout + stderr).
LogStreamOptions
Used by LogStream()
Configures a live log stream. The zero value reads the default sources from the beginning with follow off.Since and FromCursor are mutually exclusive.
LogSource
Used by LogEntry.Source · LogOptions.Sources · LogStreamOptions.Sources
LogLevel
Used by WithLogLevel()
PullPolicy
Used by WithPullPolicy()
SecurityProfile
Used by WithSecurityProfile()
RegistryAuth
Used by WithRegistryAuth()
Credentials for a private OCI registry.InitConfig
Built by Init · used by WithInit()
Custom guest PID-1 init specification. Construct via theInit factory rather than building the struct directly.
InitOptions
Used by Init.Cmd()
Tuning struct forInit.Cmd beyond the required cmd.
PatchConfig
Built by Patch · used by WithPatches()
A single rootfs patch. Construct via thePatch factory; the fields populated depend on the PatchKind.
PatchOptions
Used by Patch methods
Tuning struct passed toPatch methods that accept a mode and replace flag.
PatchKind
Used by PatchConfig.Kind
PatchConfig. Prefer the Patch factory.
SetupOption
The setup-onlySetupOption type is documented under Runtime setup.