Setup
EnsureInstalled()
~/.microsandbox/, downloading them from the matching GitHub release if not. Call at startup to surface install errors up front; otherwise the first sandbox call handles it. The FFI library is embedded in the Go binary and loads automatically — EnsureInstalled does not govern it. Idempotent.
Parameters
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Cancels an in-flight msb + libkrunfw download |
| opts | ...SetupOption | See SetupOption for the available knobs |
IsInstalled()
SDKVersion()
RuntimeVersion()
ErrLibraryNotLoaded only if loading fails (e.g. unsupported platform or GLIBC mismatch).
SetupOption
ConfiguresEnsureInstalled. Pass any of the options below as variadic arguments. Options apply only to the first call; subsequent calls are no-ops.
| Option | Effect |
|---|---|
WithSkipDownload() | Refuse to download msb + libkrunfw — require them to be pre-installed |
WithSkipDownload()
EnsureInstalled from fetching the msb + libkrunfw bundle from GitHub. Use when the runtime is already on disk at the install path (e.g. air-gapped CI). The embedded FFI library is unaffected — it ships with the SDK.
Top-level functions
CreateSandbox()
*Sandbox owns the VM process — call Close (or Stop + Close) when done.
Parameters
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Cancels the boot operation. Cancelling after this function returns has no effect on the running sandbox |
| name | string | Sandbox name, up to 128 UTF-8 bytes |
| opts | ...SandboxOption | Functional options — see Options |
| Type | Description |
|---|---|
*Sandbox | Running sandbox |
error | Typed *Error — see Error Handling |
StartSandbox()
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Cancels the boot operation |
| name | string | Name of a stopped sandbox, up to 128 UTF-8 bytes |
| Type | Description |
|---|---|
*Sandbox | Running sandbox |
StartSandboxDetached()
GetSandbox()
ErrSandboxNotFound if no such sandbox exists. The returned *SandboxHandle exposes Connect, Start, Stop, Kill, Remove, Metrics, and Logs.
ListSandboxes()
RemoveSandbox()
ErrSandboxStillRunning if the sandbox is still running.
AllSandboxMetrics()
Instance methods
The*Sandbox returned by CreateSandbox and friends has the following methods. *Sandbox is safe for concurrent use from multiple goroutines.
Name()
FS()
Exec()
ExecStream.
A non-zero exit code is not a Go error — inspect ExecOutput.Success or ExecOutput.ExitCode instead. Transport, timeout, and spawn failures are returned as errors.
ExecOption details.
ExecStream()
Started, Stdout, Stderr, Exited, and Done events as they happen. The handle MUST be closed with Close when done.
See ExecHandle for the event loop.
Shell()
/bin/sh -c. Shell syntax like pipes, redirects, and && chains works.
ShellStream()
Attach()
| Type | Description |
|---|---|
int | Exit code of the process |
AttachShell()
WithShell, defaults to /bin/sh).
Stop()
WithStopTimeout(...) to control the graceful shutdown window before force-kill.
RequestStop()
Kill()
WithKillTimeout(...) to control the observation timeout.
RequestKill()
RequestDrain()
WaitUntilStopped()
Detach()
WithDetached once the caller is done with the handle but the sandbox should keep running. After Detach, the handle is invalid; a subsequent Close returns ErrInvalidHandle.
Close()
ErrInvalidHandle.
For a sandbox created with WithDetached, Close will stop the VM — use Detach instead if the intent is to leave it running.
OwnsLifecycle()
true, closing or stopping the handle terminates the sandbox; when false the sandbox is detached.
OwnsLifecycleOrFalse()
false on any failure. Suitable for log lines and best-effort branching.
RemoveSandbox()
Metrics()
Logs()
MetricsStream()
interval. Sub-millisecond precision is rounded up. Close the returned handle when done.
Patch
Helpers that construct rootfs patches forWithPatches. Access via the package-level Patch value. Each method returns a PatchConfig. Mkdir and Remove are idempotent; other operations error at boot when targeting a path already present in the image unless Replace: true is passed in PatchOptions.
See Patches for conceptual context.
Patch.Text()
path.
Patch.Append()
content to an existing file at path. If the file lives in a lower image layer, it is copied up first.
Patch.Mkdir()
opts.Mode is honoured; Replace is ignored (the operation is idempotent).
Patch.Remove()
Patch.Symlink()
link pointing to target. Only opts.Replace is honoured.
Patch.CopyFile()
src into the guest rootfs at dst.
Patch.CopyDir()
src into the guest rootfs at dst. Only opts.Replace is honoured.
Init
Helpers that constructInitConfig values for WithInit to hand off PID 1 inside the guest after agentd setup. Access via the package-level Init value. See Custom init system for image picks and shutdown semantics.
Init.Auto()
/sbin/init, /lib/systemd/systemd, …).
Init.Cmd()
cmd must be an absolute path inside the guest rootfs.
Options
Functional options forCreateSandbox. Most options merge across repeated calls; WithImage and similar single-value setters replace.
WithImage()
"python:3.12", "docker.io/library/alpine"). Use WithImageDisk when a disk-image root needs an explicit filesystem type. Required unless WithSnapshot is used.
WithOCIUpperSize()
WithImageDisk()
"ext4". The disk format is inferred from the path extension (.qcow2, .raw, or .vmdk).
WithSnapshot()
WithImage. See Snapshots.
WithMemory()
WithCPUs()
WithWorkdir()
WithShell()
Sandbox.Shell and Sandbox.AttachShell. Defaults to /bin/sh on most images.
WithSecurityProfile()
SecurityProfileRestricted for stronger hardening that sets no_new_privs, drops mount-admin capability from user commands, and forces nosuid,nodev on user mounts.
WithEnv()
WithHostname()
WithUser()
WithReplace()
WithReplaceWithTimeout()
WithReplace but with a caller-specified timeout between SIGTERM and SIGKILL. Implies WithReplace. A zero duration skips SIGTERM and SIGKILLs immediately.
WithDetached()
WithEntrypoint()
msb exec / msb run (CLI command resolution against this sandbox), not by Sandbox.Exec / Sandbox.Shell — those pass cmd literally to the guest agent. Use this when configuring sandboxes via the SDK for later CLI attachment. For PID 1 handoff, use WithInit instead.
WithInit()
cfg via Init.
WithLogLevel()
LogLevel.
WithQuietLogs()
WithScripts()
/.msb/scripts/<name>. Called repeatedly, entries merge.
WithPullPolicy()
PullPolicy.
WithMaxDuration()
WithIdleTimeout()
WithRegistryAuth()
RegistryAuth.
WithPorts()
127.0.0.1.
WithPortBindings()
0.0.0.0. See PortBinding for the type definition and UDP examples.
WithPortsUDP()
127.0.0.1.
WithNetwork()
WithSecrets()
WithPatches()
Patch.
WithMounts()
SandboxHandle
A lightweight metadata reference to a sandbox returned byGetSandbox and ListSandboxes. Holds last-known name, status, config JSON, and timestamps; offers lifecycle methods that operate on the sandbox without an active connection. Call Connect or Start to upgrade to a full *Sandbox.
| Method | Returns | Description |
|---|---|---|
Name() | string | Sandbox name, up to 128 UTF-8 bytes |
Status() | SandboxStatus | Last-known lifecycle status |
ConfigJSON() | string | Raw JSON configuration |
CreatedAt() | time.Time | Creation time, zero value if unknown |
UpdatedAt() | time.Time | Last-update time, zero value if unknown |
Metrics(ctx) | (*Metrics, error) | Point-in-time resource metrics |
Logs(ctx, opts) | ([]LogEntry, error) | Persisted sandbox logs |
Connect(ctx) | (*Sandbox, error) | Reattach to the running sandbox |
Start(ctx) | (*Sandbox, error) | Boot a stopped sandbox in attached mode |
StartDetached(ctx) | (*Sandbox, error) | Boot a stopped sandbox in detached mode |
Stop(ctx) | error | Graceful shutdown |
Kill(ctx) | error | Force terminate |
Remove(ctx) | error | Delete sandbox and persisted state |
Snapshot(ctx, name) | (*SnapshotArtifact, error) | Snapshot stopped/crashed sandbox under a bare name |
SnapshotTo(ctx, path) | (*SnapshotArtifact, error) | Snapshot stopped/crashed sandbox to an explicit path |
Types
SandboxConfig
The config struct populated bySandboxOption functions. Most callers build a sandbox via CreateSandbox(ctx, name, ...opts); SandboxConfig is exported for callers that prefer to construct a value directly and pass its fields explicitly.
| Field | Type | Description |
|---|---|---|
| Image | string | OCI image, local path, or disk image |
| ImageFstype | string | Optional inner filesystem type for disk-image roots |
| OCIUpperSizeMiB | uint32 | Writable overlay upper size for OCI image roots |
| Snapshot | string | Snapshot artifact path or bare name; mutually exclusive with Image |
| MemoryMiB | uint32 | Guest memory in MiB |
| CPUs | uint8 | Virtual CPUs |
| Workdir | string | Default working directory |
| Shell | string | Shell binary used by Shell calls |
| SecurityProfile | SecurityProfile | In-guest security profile |
| Hostname | string | Guest hostname |
| User | string | Default guest user |
| Replace | bool | Replace existing sandbox with same name |
| ReplaceWithTimeout | *time.Duration | Timeout between SIGTERM and SIGKILL (implies Replace) |
| Env | map[string]string | Environment variables |
| Detached | bool | If true, sandbox survives after process exits |
| Entrypoint | []string | Override image entrypoint |
| Init | *InitConfig | Hand PID 1 off to a guest init binary |
| LogLevel | LogLevel | Sandbox log verbosity override |
| QuietLogs | bool | Suppress sandbox-level log output |
| Scripts | map[string]string | Named scripts mounted at /.msb/scripts/ |
| PullPolicy | PullPolicy | Image pull behaviour |
| MaxDuration | time.Duration | Maximum sandbox lifetime |
| IdleTimeout | time.Duration | Idle timeout |
| RegistryAuth | *RegistryAuth | Private registry credentials |
| Ports | map[uint16]uint16 | Host→guest TCP port mappings |
| PortsUDP | map[uint16]uint16 | Host→guest UDP port mappings |
| PortBindings | []PortBinding | Host→guest port mappings with explicit bind addresses |
| Network | *NetworkConfig | Network policy and configuration |
| Secrets | []SecretEntry | Secret injection entries |
| Patches | []PatchConfig | Rootfs modifications applied before boot |
| Volumes | map[string]MountConfig | Volume mounts keyed by guest path |
SandboxOption
CreateSandbox. All WithX helpers listed above return a SandboxOption.
SecurityProfile
InitConfig
Custom init specification.| Field | Type | Description |
|---|---|---|
| Cmd | string | Absolute path or "auto" to the init binary inside the guest rootfs |
| Args | []string | Supplemental argv (argv[0] is implicitly Cmd) |
| Env | map[string]string | Extra env vars merged on top of the inherited env |
InitOptions
Tuning struct forInit.Cmd.
| Field | Type | Description |
|---|---|---|
| Args | []string | Supplemental argv |
| Env | map[string]string | Extra env vars |
RegistryAuth
Private registry credentials.| Field | Type | Description |
|---|---|---|
| Username | string | Registry username |
| Password | string | Registry password |
PatchConfig
A single rootfs patch produced byPatch.
| Field | Type | Description |
|---|---|---|
| Kind | PatchKind | Patch flavour |
| Path | string | Absolute guest path (text / file / mkdir / remove / append) |
| Content | string | Text content (text / append) |
| Mode | *uint32 | File or directory mode, e.g. 0o644 |
| Replace | bool | When true, overwrite an existing path at the destination |
| Src | string | Host source path (copy_file / copy_dir) |
| Dst | string | Guest destination path (copy_file / copy_dir) |
| Target | string | Symlink target |
| Link | string | Symlink path |
PatchOptions
Tuning struct passed toPatch methods.
| Field | Type | Description |
|---|---|---|
| Mode | *uint32 | File or directory mode |
| Replace | bool | Overwrite an existing path |
PatchKind
| Constant | Value |
|---|---|
PatchKindText | "text" |
PatchKindAppend | "append" |
PatchKindMkdir | "mkdir" |
PatchKindRemove | "remove" |
PatchKindSymlink | "symlink" |
PatchKindCopyFile | "copy_file" |
PatchKindCopyDir | "copy_dir" |
PullPolicy
| Constant | Value | Description |
|---|---|---|
PullPolicyDefault | "" | Runtime default (currently PullPolicyIfMissing) |
PullPolicyAlways | "always" | Pull every time, even if cached locally |
PullPolicyIfMissing | "if-missing" | Pull only if not already cached |
PullPolicyNever | "never" | Never pull; fail if missing |
LogOptions
Filters forLogs.
| Field | Type | Description |
|---|---|---|
| Tail | uint64 | Keep only the last N matching entries |
| Since | time.Time | Inclusive lower timestamp bound |
| Until | time.Time | Exclusive upper timestamp bound |
| Sources | []LogSource | Sources to include; empty uses the runtime default |
LogEntry
One persisted log entry.| Field | Type | Description |
|---|---|---|
| Source | LogSource | Origin of the captured data |
| SessionID | *uint64 | Relay session ID, nil for system entries |
| Timestamp | time.Time | Capture timestamp |
| Data | []byte | Captured bytes |
| Method | Returns | Description |
|---|---|---|
Text() | string | Captured bytes as a string |
LogSource
| Constant | Value |
|---|---|
LogSourceStdout | "stdout" |
LogSourceStderr | "stderr" |
LogSourceOutput | "output" |
LogSourceSystem | "system" |
LogLevel
| Constant | Value | Description |
|---|---|---|
LogLevelDefault | "" | Runtime default |
LogLevelTrace | "trace" | Most verbose — all diagnostic output |
LogLevelDebug | "debug" | Debug and higher |
LogLevelInfo | "info" | Info and higher |
LogLevelWarn | "warn" | Warnings and errors only |
LogLevelError | "error" | Errors only |
SandboxStatus
| Constant | Value | Description |
|---|---|---|
SandboxStatusRunning | "running" | Guest agent is ready |
SandboxStatusStopped | "stopped" | VM shut down; can be restarted |
SandboxStatusCrashed | "crashed" | VM exited unexpectedly |
SandboxStatusDraining | "draining" | Graceful shutdown in progress |
SandboxStatusPaused | "paused" | VM is paused |
Metrics
Point-in-time resource usage snapshot returned byMetrics.
| Field | Type | Description |
|---|---|---|
| CPUPercent | float64 | CPU usage as a percentage |
| MemoryBytes | uint64 | Current memory usage in bytes |
| MemoryLimitBytes | uint64 | Memory limit in bytes |
| DiskReadBytes | uint64 | Total bytes read from disk since boot |
| DiskWriteBytes | uint64 | Total bytes written to disk since boot |
| NetRxBytes | uint64 | Total bytes received over the network since boot |
| NetTxBytes | uint64 | Total bytes sent over the network since boot |
| Uptime | time.Duration | Time since the sandbox was created |
MetricsStreamHandle
Live metrics subscription returned byMetricsStream.
| Method | Returns | Description |
|---|---|---|
Recv(ctx) | (*Metrics, error) | Block until the next snapshot arrives. Returns (nil, nil) when the stream ends |
Close() | error | Stop the stream and release Rust-side resources |