Skip to main content
Create and control a microVM sandbox: boot it from an image, run commands, stream logs and metrics, then shut it down. See Overview for configuration examples and Lifecycle for state management. Examples assume the package is imported as m "github.com/superradcompany/microsandbox/sdk/go". For local runtime installation and verification, see Runtime setup.

Functions

m.CreateSandbox()

Create and boot a new sandbox. Pulls the image if needed, boots the VM, starts the guest agent, and waits until it is ready to accept commands. Sandbox names must be non-empty and no longer than 128 UTF-8 bytes. The returned *Sandbox owns the VM process. Call Close (or Stop + Close) when done. See Options for all configuration knobs.

Parameters

ctxcontext.Context
Cancels the boot operation only. Cancelling after this function returns has no effect on the running sandbox.
namestring
Sandbox name, up to 128 UTF-8 bytes.
Functional options applied in order.

Returns

Running sandbox. Safe for concurrent use from multiple goroutines.
error
Typed *Error, see Error Handling.

m.GetSandbox()

Look up a sandbox by name and return a metadata handle without connecting to it. Returns an error with Kind == ErrSandboxNotFound if no such sandbox exists. The returned *SandboxHandle exposes Connect, Start, Stop, Kill, Remove, Ping, Touch, Metrics, Logs, and snapshot methods.

Parameters

namestring
Sandbox name, up to 128 UTF-8 bytes.

Returns

Metadata handle with status and lifecycle control.

m.ListSandboxes()

Return the first page of known sandboxes (running, stopped, draining, crashed), ordered newest first. The default page size is 20.

Returns

*SandboxPage
Handles in this page and an optional cursor for the next page.

m.ListSandboxesWith()

Return a configured page of sandbox metadata. Label selectors are applied before pagination and AND-matched.

Parameters

options…SandboxListOption
WithListLimit, WithListCursor, and/or WithListLabels options.

Returns

*SandboxPage
Matching handles and an optional cursor for the next page.

m.StartSandbox()

Restart a previously stopped sandbox. The VM reboots using the persisted configuration and returns a live *Sandbox.

Parameters

namestring
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox.

m.StartSandboxDetached()

Boot a stopped sandbox in detached mode. The VM keeps running after the returned handle is released.

Parameters

namestring
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox in detached mode.

m.RemoveSandbox()

Delete a stopped sandbox by name. See Remove for the exact local deletion scope and the external resources that are preserved. Fails if the sandbox is still running; stop it first.

Parameters

namestring
Sandbox name, up to 128 UTF-8 bytes.

m.AllSandboxMetrics()

Return a point-in-time Metrics snapshot for every running sandbox, keyed by sandbox name. Only running and draining sandboxes appear.

Returns

Per-sandbox metrics keyed by name.
Runtime installation and verification helpers are documented under Runtime setup. The Go-only version helpers are under Inspect Go versions.

Methods

The *Sandbox returned by CreateSandbox, StartSandbox, and SandboxHandle.Connect carries the methods below. *Sandbox is safe for concurrent use from multiple goroutines. The command-execution methods, Exec, ExecStream, Shell, and ShellStream, live on the same value and are documented under Execution.

sb.Name()

Return the sandbox name.

Returns

string
Sandbox name, up to 128 UTF-8 bytes.

sb.FS()

Return a filesystem accessor for reading and writing files inside the running sandbox. See Filesystem for the API.

Returns

Filesystem accessor.

sb.SSH()

Return an SSH accessor for opening a native in-process SSH client or preparing a reusable SSH server endpoint against the running sandbox. See SSH for the API.

Returns

SSH accessor.

sb.Logs()

Read persisted output from the sandbox’s 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

Filters: Tail, Since, Until, Sources. The zero value returns everything for the default stdout and stderr sources.

Returns

Matching entries in chronological order.

sb.LogStream()

Start a streaming log subscription against a live sandbox. Pass 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

Sources, follow mode, and a Since or FromCursor start point.

Returns

Live subscription; call Recv in a loop.

sb.Ping()

Check that the running sandbox’s guest agent is reachable without refreshing idle activity. This sends 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

Sandbox name and agent round-trip latency.

sb.Touch()

Explicitly refresh the running sandbox’s idle activity. This sends 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

Sandbox name and updated activity sequence.

sb.Modify()

Plan or apply a configuration change. The returned plan labels each change "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. 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

Requested changes plus Policy and DryRun. Zero-valued fields are left unchanged.

Returns

The modification plan, applied unless DryRun is set.

sb.Metrics()

Get a point-in-time snapshot of the sandbox’s resource usage: CPU, memory, disk I/O, network I/O, optional upper-disk usage, and uptime.

Returns

Resource snapshot.

sb.MetricsStream()

Start a streaming metrics subscription that delivers a 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.Duration
Time between snapshots.

Returns

Live subscription; call Recv in a loop.

sb.Attach()

Bridge the caller’s terminal to a process inside the sandbox for a fully interactive PTY session. Blocks until the process exits and returns its exit code. The caller’s terminal must be a real TTY, so this is primarily useful for CLI tools, not library code.

Parameters

cmdstring
Command to run.
args…string
Command arguments.

Returns

int
Exit code of the process.

sb.AttachShell()

Attach to the sandbox’s default shell (configured via WithShell, defaults to /bin/sh). Blocks until the shell exits and returns its exit code.

Returns

int
Exit code of the shell.

sb.Stop()

Gracefully shut down the sandbox and wait until stopped state is observed. Lets the workload finish writing any pending data to disk before it exits. Defaults to a ten-second graceful window before force-kill; pass WithStopTimeout to change it.

Parameters

Graceful shutdown window, e.g. WithStopTimeout(30 * time.Second).

sb.RequestStop()

Request graceful shutdown and return once the request is sent, without waiting for the sandbox to reach stopped state. Pair with WaitUntilStopped to await termination.

sb.Kill()

Force-terminate the sandbox with SIGKILL and wait until stopped state is observed. No graceful shutdown, so pending writes the workload hasn’t fsync’d may be lost. Prefer Stop for graceful shutdown. Defaults to a five-second observation window; pass WithKillTimeout to change it.

Parameters

Stopped-state observation window.

sb.RequestKill()

Request force termination and return once the request is sent, without waiting for the sandbox to reach stopped state.

sb.RequestDrain()

Request a graceful drain and return once the request is sent. Existing commands run to completion while new exec calls are rejected; the sandbox transitions to stopped when all in-flight commands finish. Useful for zero-downtime rotation of worker sandboxes.

sb.WaitUntilStopped()

Block until the sandbox is observed in a terminal state, then return how it ended.

Returns

Terminal status, exit code, and signal.

sb.Detach()

Release the Rust-side handle without stopping the VM. Use on sandboxes created with 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()

Release the Rust-side handle. Safe to call multiple times; the second call returns an error with Kind == ErrInvalidHandle. For a sandbox created with WithDetached, Close stops the VM. Use Detach instead to leave it running.

sb.OwnsLifecycle()

Report whether this handle owns the VM process. When true, closing or stopping the handle terminates the sandbox (attached mode); false means it is detached. The error return covers stale handles and FFI failures; use OwnsLifecycleOrFalse when you don’t care.

Returns

bool
true if attached.

sb.OwnsLifecycleOrFalse()

Convenience wrapper around OwnsLifecycle that swallows the error and returns false on any failure. Suitable for log lines and best-effort branching.

Returns

bool
true if attached, false on detach or error.

Options

Functional options for CreateSandbox. Map and slice options merge across repeated calls; single-value setters like WithImage replace.

WithImage()

Set the root filesystem source: an OCI image name, local directory path, or disk image path (e.g. "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

imagestring
OCI image, local path, or disk image.

WithOCIUpperSize()

Set the writable overlay upper size for an OCI image, in MiB. Valid only with an OCI image rootfs, not disk images or snapshots.

Parameters

mebibytesuint32
Upper layer size in MiB.

WithImageDisk()

Use a disk image as the root filesystem and optionally provide the inner filesystem type, e.g. "ext4". The disk format is inferred from the path extension (.qcow2, .raw, or .vmdk).

Parameters

pathstring
Host path to the disk image.
fstypestring
Inner filesystem hint, empty to auto-detect.

WithFromSnapshot()

option
Boot from a snapshot artifact by bare name or filesystem path. Mutually exclusive with WithImage. See Snapshots.

Parameters

pathOrNamestring
Snapshot artifact path or bare name.

WithMemory()

Set the guest memory limit in MiB. This is a limit, not an upfront reservation. Default: 512 MiB.

Parameters

mebibytesuint32
Memory in MiB.

WithMaxMemory()

Set the boot-time maximum hotpluggable guest memory in MiB. This reserves the envelope a sandbox can use after restart-backed changes and future live memory activation; it does not increase the effective memory by itself.

Parameters

mebibytesuint32
Maximum memory in MiB.

WithCPUs()

Set the number of virtual CPUs. This is a limit, not a reservation. Default: 1.

Parameters

cpusuint8
Number of vCPUs.

WithMaxCPUs()

Set the boot-time maximum possible virtual CPU capacity. This reserves the envelope a sandbox can use after restart-backed changes and future live CPU activation; it does not increase the effective vCPU count by itself.

Parameters

cpusuint8
Maximum possible vCPUs.

WithWorkdir()

Set the default working directory for all commands.

Parameters

pathstring
Absolute path inside the guest.

WithShell()

Set the shell used by Shell and AttachShell. Defaults to /bin/sh on most images.

Parameters

shellstring
Shell path, e.g. “/bin/bash”.

WithSecurityProfile()

Set the in-guest security profile. SecurityProfileRestricted applies stronger hardening: sets no_new_privs, drops mount-admin capability from user commands, and forces nosuid,nodev on user mounts.

Parameters

Security profile.

WithEnv()

Set environment variables visible to all commands. Called repeatedly, the maps merge; later keys overwrite earlier ones.

Parameters

envmap[string]string
Environment variables.

WithLabels()

Attach labels to the sandbox for metrics attribution and 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]string
Label key-value pairs.

WithLabel()

Attach a single label. Shorthand for WithLabels with one entry.

Parameters

keystring
Label key.
valuestring
Label value.

WithHostname()

Set the guest hostname.

Parameters

hostnamestring
Hostname.

WithUser()

Set the default guest user (UID or name) for all commands.

Parameters

userstring
User name or UID.

WithReplace()

Replace any existing sandbox with the same name. Sends SIGTERM, waits up to 10s for graceful exit, then escalates to SIGKILL. Without this, creation fails on name conflict. Use WithReplaceWithTimeout to set a different window.

WithReplaceWithTimeout()

Like 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.Duration
Grace period before SIGKILL.

WithDetached()

Create the sandbox in detached mode. The VM continues running after the Go process exits; reattach via GetSandbox. Close stops a detached sandbox; use Detach to leave it running.

WithEphemeral()

Mark whether the runtime should remove the sandbox’s DB row, on-disk state, logs, and captured output after it reaches a terminal status.

Parameters

ephemeralbool
true to delete all state on termination.

WithEntrypoint()

Override the user-workload entrypoint baked into the image: the command the agent execs per request. This is the user workload, not the guest PID 1. To override the guest PID 1, use WithInit instead.

Parameters

cmd…string
Entrypoint command and arguments.

WithInit()

Hand off PID 1 inside the guest to a custom init binary after agentd finishes boot-time setup. Construct cfg via the Init factory. See Custom init system for image picks and shutdown semantics.

Parameters

Init specification.

WithLogLevel()

Override the sandbox process’s log verbosity. See LogLevel.

Parameters

Log level.

WithQuietLogs()

Suppress sandbox-level log output entirely.

WithScripts()

Add named scripts mounted at /.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]string
Script name to script content.

WithPullPolicy()

Control when the OCI image is pulled from the registry. See PullPolicy.

Parameters

Pull behavior.

WithMaxDuration()

Cap the sandbox’s total runtime. When exceeded, the sandbox is drained and stopped. Zero means unlimited. Sub-second precision is rounded up to whole seconds. Enforced on the host side.

Parameters

dtime.Duration
Maximum lifetime.

WithIdleTimeout()

Stop the sandbox after this much wall-clock time without exec activity. Zero means unlimited. Sub-second precision is rounded up to whole seconds.

Parameters

dtime.Duration
Idle timeout.

WithRegistryAuth()

Set credentials for pulling from a private OCI registry. See RegistryAuth.

Parameters

Registry credentials.

WithPorts()

Publish guest TCP ports onto host ports (map key = host port, value = guest port). The default host bind address is 127.0.0.1. Called repeatedly, the maps merge.

Parameters

portsmap[uint16]uint16
Host port to guest port.

WithPortsUDP()

Publish guest UDP ports onto host ports. The default host bind address is 127.0.0.1.

Parameters

portsmap[uint16]uint16
Host port to guest port.

WithPortBindings()

Publish ports on explicit host bind addresses, such as 0.0.0.0. See PortBinding for the type definition and UDP examples.

Parameters

Explicit bind-address port mappings.

WithNetwork()

Configure the network stack: profiles, custom rules, DNS, and TLS interception. Build via the NetworkPolicy factory or a *NetworkConfig literal. See Networking.

Parameters

Network configuration.

WithSecrets()

Append credential secrets to the sandbox. Secrets never enter the VM; the network proxy substitutes them at the transport layer. Build entries via the Secret factory. See Secrets.

Parameters

Secret injection entries.

WithPatches()

Append rootfs patches applied before the VM boots. Patches go into the writable layer; the base image is untouched. Only compatible with OverlayFS rootfs (not disk images). Build entries via the Patch factory.

Parameters

Ordered rootfs patches.

WithMounts()

Add volume mount configurations keyed by guest path. Build values via the Mount factory. Called repeatedly, the maps merge; later entries overwrite earlier ones for the same guest path. See Volumes.

Parameters

mountsmap[string]MountConfig
Guest path to mount config.

WithStopTimeout()

Set how long Stop waits for graceful shutdown before force-killing. Default: 10 seconds. This is a StopOption, not a SandboxOption. Pass it to Stop.

Parameters

timeouttime.Duration
Graceful shutdown window.

WithKillTimeout()

Set how long Kill waits for stopped-state observation. Default: 5 seconds. This is a KillOption, pass it to Kill.

Parameters

timeouttime.Duration
Observation window.
The setup-only WithSkipDownload() option is documented under Runtime setup.

Patch

Factory that constructs rootfs patches for WithPatches. 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()

Write UTF-8 text content at path.

Parameters

pathstring
Absolute path inside the guest.
contentstring
Text content.
Mode and Replace.

Patch.Append()

Append content to an existing file at path. If the file lives in a lower image layer, it is copied up first.

Parameters

pathstring
Absolute path inside the guest.
contentstring
Text to append.

Patch.Mkdir()

Create a directory. Idempotent. Only opts.Mode is honored; Replace is ignored.

Parameters

pathstring
Absolute path inside the guest.
Only Mode applies.

Patch.Remove()

Delete a file or directory at path. Idempotent.

Parameters

pathstring
Absolute path inside the guest.
Create a symlink at link pointing to target. Only opts.Replace is honored.

Parameters

targetstring
What the symlink points to.
linkstring
Absolute path of the symlink itself.
Only Replace applies.

Patch.CopyFile()

Copy a single host file at src into the guest rootfs at dst.

Parameters

srcstring
Host source file.
dststring
Absolute destination path inside the guest.
Mode and Replace.

Patch.CopyDir()

Recursively copy a host directory at src into the guest rootfs at dst. Only opts.Replace is honored.

Parameters

srcstring
Host source directory.
dststring
Absolute destination path inside the guest.
Only Replace applies.

Init

Factory that constructs InitConfig values for WithInit, handing 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()

Use a known init at the start of the image ENTRYPOINT when present, preserving attached init-entrypoint commands; otherwise delegate to agentd to probe common init paths (/sbin/init, /lib/systemd/systemd, …) inside the guest.

Returns

Auto-detect init config.

Init.Cmd()

Specify the init binary explicitly with optional argv and env. cmd must be an absolute path inside the guest rootfs.

Parameters

cmdstring
Absolute path to the init binary inside the guest.
Argv and env.

Types

SandboxHandle

Returned by GetSandbox() · ListSandboxes() · ListSandboxesWith()

A lightweight reference to a sandbox’s persisted state. Carries metadata (name, status, config JSON, timestamps) and offers lifecycle methods that operate on the sandbox without an active guest-agent connection. You cannot Exec or FS on a handle. Call Connect or Start to upgrade to a full *Sandbox.

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 or memory 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 by ListSandboxes or ListSandboxesWith. Pass NextCursor back through WithListCursor with the same filters to continue.

SandboxListOption

Functional options accepted by ListSandboxesWith.

SandboxConfig

Populated by SandboxOption · parsed by SandboxHandle.Config()

The full configuration of a sandbox. Most callers build a sandbox via CreateSandbox(ctx, name, ...opts); SandboxConfig is exported for callers that prefer to construct a value directly.

SandboxOption

Consumed by CreateSandbox()

A functional option for 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.

Metrics

Returned by Metrics() · MetricsStream() · AllSandboxMetrics()

Point-in-time resource usage snapshot.

MetricsStreamHandle

Returned by MetricsStream()

Live metrics subscription. Call Close to release Rust-side resources.

SandboxStopResult

Returned by WaitUntilStopped()

Describes a terminal sandbox state observed by WaitUntilStopped.

SandboxStatus

Used by SandboxHandle.Status() · SandboxStopResult.Status

LogEntry

Returned by Logs() · LogStream()

A single captured log entry.

LogOptions

Used by Logs()

Filters passed to Logs. 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.

LogStreamHandle

Returned by LogStream()

Live log subscription. Call Close to release Rust-side resources.

LogSource

Used by LogEntry.Source · LogOptions.Sources · LogStreamOptions.Sources

LogLevel

Used by WithLogLevel()

Sandbox process log verbosity.

PullPolicy

Used by WithPullPolicy()

Controls when the SDK fetches an OCI image from the registry.

SecurityProfile

Used by WithSecurityProfile()

Sandbox-wide in-guest security profile.

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 the Init factory rather than building the struct directly.

InitOptions

Used by Init.Cmd()

Tuning struct for Init.Cmd beyond the required cmd.

Init

Produces InitConfig for WithInit()

Package-level factory namespace for InitConfig values. See the Init section for its methods.

PatchConfig

Built by Patch · used by WithPatches()

A single rootfs patch. Construct via the Patch factory; the fields populated depend on the PatchKind.

PatchOptions

Used by Patch methods

Tuning struct passed to Patch methods that accept a mode and replace flag.

PatchKind

Used by PatchConfig.Kind

Discriminator for PatchConfig. Prefer the Patch factory.

Patch

Produces PatchConfig for WithPatches()

Package-level factory namespace for PatchConfig values. See the Patch section for its methods. The setup-only SetupOption type is documented under Runtime setup.