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".

Typical flow

import m "github.com/superradcompany/microsandbox/sdk/go"

sb, err := m.CreateSandbox(ctx, "api",              // 1. configure + boot
    m.WithImage("python"),
    m.WithMemory(1024),
)
if err != nil {
    return err
}
defer sb.Close()                                    // 4. shut down

out, err := sb.Exec(ctx, "python", []string{"-V"})  // 2. run
if err != nil {
    return err
}
fmt.Println(out.Stdout())                           // 3. read output

Functions

m.CreateSandbox()

func CreateSandbox(ctx context.Context, name string, opts ...SandboxOption) (*Sandbox, error)
sb, err := m.CreateSandbox(ctx, "api",
    m.WithImage("python:3.12"),
    m.WithMemory(512),
    m.WithCPUs(2),
    m.WithEnv(map[string]string{"PYTHONDONTWRITEBYTECODE": "1"}),
)
if err != nil {
    return err
}
defer func() {
    _ = sb.Stop(context.Background())
    _ = sb.Close()
}()
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()

func GetSandbox(ctx context.Context, name string) (*SandboxHandle, error)
h, err := m.GetSandbox(ctx, "api")
if err != nil {
    return err
}
fmt.Println(h.Status())
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, 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()

func ListSandboxes(ctx context.Context) ([]*SandboxHandle, error)
handles, err := m.ListSandboxes(ctx)
if err != nil {
    return err
}
for _, h := range handles {
    fmt.Printf("%s%s\n", h.Name(), h.Status())
}
Return metadata for every known sandbox (running, stopped, draining, crashed), ordered by creation time, newest first.

Returns

All sandbox handles.

m.ListSandboxesWith()

func ListSandboxesWith(ctx context.Context, filter SandboxFilter) ([]*SandboxHandle, error)
filter := m.NewSandboxFilter().WithLabels(map[string]string{"user.id": "alice"})
handles, err := m.ListSandboxesWith(ctx, filter)
Return sandbox metadata narrowed by a SandboxFilter. Label selectors are AND-matched: a sandbox matches only if it carries every label in the filter.

Parameters

Label selector. The zero value matches every sandbox.

Returns

Matching sandbox handles.

m.NewSandboxFilter()

func NewSandboxFilter() SandboxFilter
Return an empty SandboxFilter that matches every sandbox. Chain WithLabels to narrow the results passed to ListSandboxesWith.

Returns

Empty filter.

m.StartSandbox()

func StartSandbox(ctx context.Context, name string) (*Sandbox, error)
sb, err := m.StartSandbox(ctx, "api")
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()

func StartSandboxDetached(ctx context.Context, name string) (*Sandbox, error)
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()

func RemoveSandbox(ctx context.Context, name string) error
err := m.RemoveSandbox(ctx, "api")
Delete a stopped sandbox and all its persisted state from disk. Fails if the sandbox is still running, stop it first.

Parameters

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

m.AllSandboxMetrics()

func AllSandboxMetrics(ctx context.Context) (map[string]*Metrics, error)
all, err := m.AllSandboxMetrics(ctx)
for name, metrics := range all {
    fmt.Printf("%s: %.1f%% CPU\n", name, metrics.CPUPercent)
}
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.

m.EnsureInstalled()

func EnsureInstalled(ctx context.Context, opts ...SetupOption) error
if err := m.EnsureInstalled(ctx); err != nil {
    log.Fatal(err)
}
Optional. Ensure msb + libkrunfw are present under ~/.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; options apply only to the first call.

Parameters

ctxcontext.Context
Cancels an in-flight msb + libkrunfw download.
Install knobs, e.g. WithSkipDownload().

m.IsInstalled()

func IsInstalled() bool
Report whether msb + libkrunfw are present on disk at the SDK’s pinned version. Does not dlopen the FFI library (which ships embedded).

Returns

bool
true if the runtime is present at the expected version.

m.SDKVersion()

func SDKVersion() string
Return the microsandbox release version this SDK was compiled against.

Returns

string
Pinned release version, e.g. “0.5.8”.

m.RuntimeVersion()

func RuntimeVersion() (string, error)
Return the version reported by the loaded FFI library. Auto-loads the library on first use; returns an error with Kind == ErrLibraryNotLoaded only if loading fails (e.g. unsupported platform or GLIBC mismatch).

Returns

string
FFI library version.

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()

func (s *Sandbox) Name() string
Return the sandbox name.

Returns

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

sb.FS()

func (s *Sandbox) FS() *SandboxFSOps
err := sb.FS().Write(ctx, "/tmp/hello.txt", []byte("hi"))
Return a filesystem accessor for reading and writing files inside the running sandbox. See Filesystem for the API.

Returns

Filesystem accessor.

sb.SSH()

func (s *Sandbox) SSH() *SandboxSSHOps
client, err := sb.SSH().OpenClient(ctx)
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()

func (s *Sandbox) Logs(ctx context.Context, opts LogOptions) ([]LogEntry, error)
entries, err := sb.Logs(ctx, m.LogOptions{
    Sources: []m.LogSource{m.LogSourceStdout, m.LogSourceStderr},
})
for _, e := range entries {
    fmt.Printf("[%s] %s", e.Source, e.Text())
}
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()

func (s *Sandbox) LogStream(ctx context.Context, opts LogStreamOptions) (*LogStreamHandle, error)
stream, err := sb.LogStream(ctx, m.LogStreamOptions{Follow: true})
if err != nil {
    return err
}
defer stream.Close()
for {
    entry, err := stream.Recv(ctx)
    if err != nil || entry == nil {
        break
    }
    fmt.Print(entry.Text())
}
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.Metrics()

func (s *Sandbox) Metrics(ctx context.Context) (*Metrics, error)
metrics, err := sb.Metrics(ctx)
fmt.Printf("cpu %.1f%% · mem %d MiB\n",
    metrics.CPUPercent, metrics.MemoryBytes/(1<<20))
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()

func (s *Sandbox) MetricsStream(ctx context.Context, interval time.Duration) (*MetricsStreamHandle, error)
stream, err := sb.MetricsStream(ctx, 500*time.Millisecond)
if err != nil {
    return err
}
defer stream.Close()
for {
    metrics, err := stream.Recv(ctx)
    if err != nil || metrics == nil {
        break
    }
    fmt.Printf("CPU: %.1f%%\n", metrics.CPUPercent)
}
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()

func (s *Sandbox) Attach(ctx context.Context, cmd string, args ...string) (int, error)
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()

func (s *Sandbox) AttachShell(ctx context.Context) (int, error)
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()

func (s *Sandbox) Stop(ctx context.Context, opts ...StopOption) error
err := sb.Stop(ctx, m.WithStopTimeout(30*time.Second))
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()

func (s *Sandbox) RequestStop(ctx context.Context) error
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()

func (s *Sandbox) Kill(ctx context.Context, opts ...KillOption) error
err := sb.Kill(ctx)
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()

func (s *Sandbox) RequestKill(ctx context.Context) error
Request force termination and return once the request is sent, without waiting for the sandbox to reach stopped state.

sb.RequestDrain()

func (s *Sandbox) RequestDrain(ctx context.Context) error
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()

func (s *Sandbox) WaitUntilStopped(ctx context.Context) (*SandboxStopResult, error)
result, err := sb.WaitUntilStopped(ctx)
fmt.Printf("ended as %s\n", result.Status)
Block until the sandbox is observed in a terminal state, then return how it ended.

Returns

Terminal status, exit code, and signal.

sb.Detach()

func (s *Sandbox) Detach(ctx context.Context) error
err := sb.Detach(ctx) // keeps running in the background
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()

func (s *Sandbox) Close() error
defer 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()

func (s *Sandbox) OwnsLifecycle() (bool, error)
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()

func (s *Sandbox) OwnsLifecycleOrFalse() bool
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. Simple setters are demonstrated by the Typical flow above.

WithImage()

func WithImage(image string) SandboxOption
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 WithSnapshot is used. Use WithImageDisk when a disk-image root needs an explicit filesystem type.

Parameters

imagestring
OCI image, local path, or disk image.

WithOCIUpperSize()

func WithOCIUpperSize(mebibytes uint32) SandboxOption
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()

func WithImageDisk(path string, fstype string) SandboxOption
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.

WithSnapshot()

func WithSnapshot(pathOrName string) SandboxOption
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()

func WithMemory(mebibytes uint32) SandboxOption
Set the guest memory limit in MiB. This is a limit, not an upfront reservation. Default: 512 MiB.

Parameters

mebibytesuint32
Memory in MiB.

WithCPUs()

func WithCPUs(cpus uint8) SandboxOption
Set the number of virtual CPUs. This is a limit, not a reservation. Default: 1.

Parameters

cpusuint8
Number of vCPUs.

WithWorkdir()

func WithWorkdir(path string) SandboxOption
Set the default working directory for all commands.

Parameters

pathstring
Absolute path inside the guest.

WithShell()

func WithShell(shell string) SandboxOption
Set the shell used by Shell and AttachShell. Defaults to /bin/sh on most images.

Parameters

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

WithSecurityProfile()

func WithSecurityProfile(profile SecurityProfile) SandboxOption
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()

func WithEnv(env map[string]string) SandboxOption
Set environment variables visible to all commands. Called repeatedly, the maps merge; later keys overwrite earlier ones.

Parameters

envmap[string]string
Environment variables.

WithLabels()

func WithLabels(labels map[string]string) SandboxOption
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()

func WithLabel(key, value string) SandboxOption
Attach a single label. Shorthand for WithLabels with one entry.

Parameters

keystring
Label key.
valuestring
Label value.

WithHostname()

func WithHostname(hostname string) SandboxOption
Set the guest hostname.

Parameters

hostnamestring
Hostname.

WithUser()

func WithUser(user string) SandboxOption
Set the default guest user (UID or name) for all commands.

Parameters

userstring
User name or UID.

WithReplace()

func WithReplace() SandboxOption
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()

func WithReplaceWithTimeout(timeout time.Duration) SandboxOption
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()

func WithDetached() SandboxOption
Create the sandbox in detached mode. The VM continues running after the Go process exits; reattach via GetSandbox. Note that Close stops a detached sandbox, use Detach to leave it running.

WithEphemeral()

func WithEphemeral(ephemeral bool) SandboxOption
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()

func WithEntrypoint(cmd ...string) SandboxOption
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, for that, use WithInit instead.

Parameters

cmd…string
Entrypoint command and arguments.

WithInit()

func WithInit(cfg InitConfig) SandboxOption
sb, err := m.CreateSandbox(ctx, "worker",
    m.WithImage("jrei/systemd-debian:12"),
    m.WithInit(m.Init.Auto()),
)
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()

func WithLogLevel(level LogLevel) SandboxOption
Override the sandbox process’s log verbosity. See LogLevel.

Parameters

Log level.

WithQuietLogs()

func WithQuietLogs() SandboxOption
Suppress sandbox-level log output entirely.

WithScripts()

func WithScripts(scripts map[string]string) SandboxOption
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()

func WithPullPolicy(p PullPolicy) SandboxOption
Control when the OCI image is pulled from the registry. See PullPolicy.

Parameters

Pull behavior.

WithMaxDuration()

func WithMaxDuration(d time.Duration) SandboxOption
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()

func WithIdleTimeout(d time.Duration) SandboxOption
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()

func WithRegistryAuth(auth RegistryAuth) SandboxOption
Set credentials for pulling from a private OCI registry. See RegistryAuth.

Parameters

Registry credentials.

WithPorts()

func WithPorts(ports map[uint16]uint16) SandboxOption
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()

func WithPortsUDP(ports map[uint16]uint16) SandboxOption
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()

func WithPortBindings(bindings ...PortBinding) SandboxOption
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()

func WithNetwork(net *NetworkConfig) SandboxOption
sb, err := m.CreateSandbox(ctx, "api",
    m.WithImage("python"),
    m.WithNetwork(m.NetworkPolicy.PublicOnly()),
)
Configure the network stack: preset, custom rules, DNS, and TLS interception. Build via the NetworkPolicy factory or a *NetworkConfig literal. See Networking.

Parameters

Network configuration.

WithSecrets()

func WithSecrets(secrets ...SecretEntry) SandboxOption
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()

func WithPatches(patches ...PatchConfig) SandboxOption
sb, err := m.CreateSandbox(ctx, "api",
    m.WithImage("python"),
    m.WithPatches(
        m.Patch.Mkdir("/app", m.PatchOptions{}),
        m.Patch.Text("/app/config.txt", "ready\n", m.PatchOptions{}),
    ),
)
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()

func WithMounts(mounts map[string]MountConfig) SandboxOption
sb, err := m.CreateSandbox(ctx, "api",
    m.WithImage("python"),
    m.WithMounts(map[string]m.MountConfig{
        "/data": m.Mount.Named("my-vol", m.MountOptions{}),
        "/tmp":  m.Mount.Tmpfs(m.TmpfsOptions{SizeMiB: 256}),
    }),
)
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()

func WithStopTimeout(timeout time.Duration) StopOption
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()

func WithKillTimeout(timeout time.Duration) KillOption
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.

WithSkipDownload()

func WithSkipDownload() SetupOption
Prevent 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. This is a SetupOption, pass it to EnsureInstalled.

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()

func (patchFactory) Text(path, content string, opts PatchOptions) PatchConfig
Write UTF-8 text content at path.

Parameters

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

Patch.Append()

func (patchFactory) Append(path, content string) PatchConfig
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()

func (patchFactory) Mkdir(path string, opts PatchOptions) PatchConfig
Create a directory. Idempotent. Only opts.Mode is honored; Replace is ignored.

Parameters

pathstring
Absolute path inside the guest.
Only Mode applies.

Patch.Remove()

func (patchFactory) Remove(path string) PatchConfig
Delete a file or directory at path. Idempotent.

Parameters

pathstring
Absolute path inside the guest.
func (patchFactory) Symlink(target, link string, opts PatchOptions) PatchConfig
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()

func (patchFactory) CopyFile(src, dst string, opts PatchOptions) PatchConfig
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()

func (patchFactory) CopyDir(src, dst string, opts PatchOptions) PatchConfig
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()

func (initFactory) Auto() InitConfig
m.WithInit(m.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()

func (initFactory) Cmd(cmd string, opts InitOptions) InitConfig
m.WithInit(m.Init.Cmd(
    "/lib/systemd/systemd",
    m.InitOptions{
        Args: []string{"--unit=multi-user.target"},
        Env:  map[string]string{"container": "microsandbox"},
    },
))
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.
MethodReturnsDescription
Name()stringSandbox name, up to 128 UTF-8 bytes
Status()SandboxStatusLast-known lifecycle status
ConfigJSON()stringRaw JSON configuration
Config()(*SandboxConfig, error)Parsed configuration
CreatedAt()time.TimeCreation time, zero value if unknown
UpdatedAt()time.TimeLast-update time, zero value if unknown
Refresh(ctx)(*SandboxHandle, error)Fresh handle for the same name
Metrics(ctx)(*Metrics, error)Point-in-time resource metrics
Logs(ctx, opts)([]LogEntry, error)Read captured exec.log (works without starting)
LogStream(ctx, opts)(*LogStreamHandle, error)Stream captured output
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, opts...)errorGraceful shutdown; accepts StopOption
RequestStop(ctx)errorAsync stop request
Kill(ctx, opts...)errorForce terminate; accepts KillOption
RequestKill(ctx)errorAsync kill request
RequestDrain(ctx)errorAsync drain request
WaitUntilStopped(ctx)(*SandboxStopResult, error)Block until terminal state
Remove(ctx)errorDelete sandbox and persisted state
Snapshot(ctx, name)(*SnapshotArtifact, error)Snapshot a stopped sandbox under a bare name
SnapshotTo(ctx, path)(*SnapshotArtifact, error)Snapshot a stopped sandbox to an explicit path

SandboxFilter

Built by NewSandboxFilter() · used by ListSandboxesWith()

Narrows the results of ListSandboxesWith. The zero value matches every sandbox. Built fluently; WithLabels returns a new value so calls chain.
MethodReturnsDescription
WithLabels(labels)SandboxFilterRequire all of these labels (AND-matched). Repeated calls merge; later keys overwrite earlier ones

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.
FieldTypeDescription
NamestringSandbox name, up to 128 UTF-8 bytes
ImagestringOCI image, local path, or disk image
ImageFstypestringOptional inner filesystem type for disk-image roots
OCIUpperSizeMiBuint32Writable overlay upper size for OCI image roots
SnapshotstringSnapshot artifact path or bare name; mutually exclusive with Image
MemoryMiBuint32Guest memory in MiB
CPUsuint8Virtual CPUs
WorkdirstringDefault working directory
ShellstringShell binary used by Shell calls
SecurityProfileSecurityProfileIn-guest security profile
HostnamestringGuest hostname
UserstringDefault guest user
ReplaceboolReplace existing sandbox with same name
ReplaceWithTimeout*time.DurationTimeout between SIGTERM and SIGKILL (implies Replace)
Envmap[string]stringEnvironment variables
Labelsmap[string]stringLabels for metrics attribution and filtering
DetachedboolIf true, sandbox survives after the process exits
EphemeralboolIf true, all state is removed on termination
Entrypoint[]stringOverride image entrypoint
Init*InitConfigHand PID 1 off to a guest init binary
LogLevelLogLevelSandbox log verbosity override
QuietLogsboolSuppress sandbox-level log output
Scriptsmap[string]stringNamed scripts mounted at /.msb/scripts/
PullPolicyPullPolicyImage pull behavior
MaxDurationtime.DurationMaximum sandbox lifetime
IdleTimeouttime.DurationIdle timeout
RegistryAuth*RegistryAuthPrivate registry credentials
Portsmap[uint16]uint16Host to guest TCP port mappings
PortsUDPmap[uint16]uint16Host to guest UDP port mappings
PortBindings[]PortBindingPort mappings with explicit bind addresses
Network*NetworkConfigNetwork policy and configuration
Secrets[]SecretEntrySecret injection entries
Patches[]PatchConfigRootfs modifications applied before boot
Volumesmap[string]MountConfigVolume mounts keyed by guest path

SandboxOption

Consumed by CreateSandbox()

type SandboxOption func(*SandboxConfig)
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.
FieldTypeDescription
CPUPercentfloat64CPU usage as a percentage
VCPUTimeNsuint64Cumulative vCPU time in nanoseconds
MemoryBytesuint64Current memory usage in bytes
MemoryAvailableBytes*uint64Guest-reported available memory when known
MemoryHostResidentBytes*uint64Host RSS backing the guest when known
MemoryLimitBytesuint64Memory limit in bytes
DiskReadBytesuint64Total bytes read from disk since boot
DiskWriteBytesuint64Total bytes written to disk since boot
NetRxBytesuint64Total bytes received over the network since boot
NetTxBytesuint64Total bytes sent over the network since boot
UpperUsedBytes*uint64Guest-visible OCI upper filesystem used bytes when the protected reporter is available and fresh
UpperFreeBytes*uint64Guest-visible OCI upper filesystem free bytes when the protected reporter is available and fresh
UpperHostAllocatedBytes*uint64Host-allocated bytes for the writable OCI upper image when available
Uptimetime.DurationTime since the sandbox was created

MetricsStreamHandle

Returned by MetricsStream()

Live metrics subscription. Call Close to release Rust-side resources.
MethodReturnsDescription
Recv(ctx)(*Metrics, error)Block until the next snapshot arrives. Returns (nil, nil) when the stream ends (sandbox exited)
Close()errorStop the stream and release Rust-side resources

SandboxStopResult

Returned by WaitUntilStopped()

Describes a terminal sandbox state observed by WaitUntilStopped.
FieldTypeDescription
NamestringSandbox name
StatusSandboxStatusTerminal status (stopped or crashed)
ExitCode*intProcess exit code when known
Signal*intTerminating signal when known
ObservedAttime.TimeWhen the terminal state was observed
Source*stringOrigin of the stop observation when known

SandboxStatus

Used by SandboxHandle.Status() · SandboxStopResult.Status

type SandboxStatus string
ConstantValueDescription
SandboxStatusRunning"running"Guest agent is ready; Exec, Shell, FS work
SandboxStatusStopped"stopped"VM shut down; configuration persisted; can be restarted
SandboxStatusCrashed"crashed"VM exited unexpectedly (kernel panic, OOM, etc.)
SandboxStatusDraining"draining"Graceful shutdown in progress; existing commands finish, new ones rejected
SandboxStatusPaused"paused"VM is paused

LogEntry

Returned by Logs() · LogStream()

A single captured log entry.
FieldTypeDescription
SourceLogSourceOrigin of the captured data
SessionID*uint64Relay-monotonic session id; nil for system entries
Timestamptime.TimeWall-clock capture time on the host
Data[]byteThe captured bytes
CursorstringOpaque resume token; pass to LogStreamOptions.FromCursor
MethodReturnsDescription
Text()stringCaptured bytes as a string

LogOptions

Used by Logs()

Filters passed to Logs. The zero value returns everything for the default sources (stdout + stderr).
FieldTypeDescription
Tailuint64Keep only the last N matching entries
Sincetime.TimeInclusive lower timestamp bound
Untiltime.TimeExclusive upper timestamp bound
Sources[]LogSourceSources to include; empty = stdout + stderr. Add LogSourceOutput or LogSourceSystem for PTY-merged output or runtime/kernel diagnostics

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.
FieldTypeDescription
Sources[]LogSourceSources to include; empty = stdout + stderr + output
Sincetime.TimeStart at the first entry with timestamp >= this; mutually exclusive with FromCursor
FromCursorstringResume strictly after the entry whose Cursor matches; mutually exclusive with Since
Untiltime.TimeStop at the first entry with timestamp >= this
FollowboolKeep the stream open past EOF and yield new entries as written

LogStreamHandle

Returned by LogStream()

Live log subscription. Call Close to release Rust-side resources.
MethodReturnsDescription
Recv(ctx)(*LogEntry, error)Block until the next entry arrives. Returns (nil, nil) when the stream ends
Close()errorStop the stream and release Rust-side resources

LogSource

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

type LogSource string
ConstantValueDescription
LogSourceStdout"stdout"Captured stdout (pipe mode, streams stayed separated)
LogSourceStderr"stderr"Captured stderr (pipe mode)
LogSourceOutput"output"PTY-merged stdout and stderr from a session running in pty mode
LogSourceSystem"system"Synthetic lifecycle markers plus runtime/kernel diagnostic lines

LogLevel

Used by WithLogLevel()

type LogLevel string
Sandbox process log verbosity.
ConstantValueDescription
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

PullPolicy

Used by WithPullPolicy()

type PullPolicy string
Controls when the SDK fetches an OCI image from the registry.
ConstantValueDescription
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

SecurityProfile

Used by WithSecurityProfile()

type SecurityProfile string
Sandbox-wide in-guest security profile.
ConstantValueDescription
SecurityProfileDefault"default"Normal guest-root semantics
SecurityProfileRestricted"restricted"Stronger hardening: no_new_privs, dropped mount-admin capability, forced nosuid,nodev on user mounts

RegistryAuth

Used by WithRegistryAuth()

Credentials for a private OCI registry.
FieldTypeDescription
UsernamestringRegistry username
PasswordstringRegistry password

InitConfig

Built by Init · used by WithInit()

Custom guest PID-1 init specification. Construct via the Init factory rather than building the struct directly.
FieldTypeDescription
CmdstringAbsolute path inside the guest, or "auto"
Args[]stringSupplemental argv (argv[0] is implicitly Cmd)
Envmap[string]stringExtra env vars merged on top of the inherited env

InitOptions

Used by Init.Cmd()

Tuning struct for Init.Cmd beyond the required cmd.
FieldTypeDescription
Args[]stringSupplemental argv
Envmap[string]stringExtra env vars

Init

Produces InitConfig for WithInit()

Package-level factory namespace for InitConfig values. See the Init section for its methods.
MethodReturnsDescription
Auto()InitConfigAuto-detect a guest init
Cmd(cmd, opts)InitConfigExplicit init binary with argv and env

PatchConfig

Built by Patch · used by WithPatches()

A single rootfs patch. Construct via the Patch factory; the fields populated depend on the PatchKind.
FieldTypeDescription
KindPatchKindPatch flavour
PathstringAbsolute guest path (text / append / mkdir / remove)
ContentstringText content (text / append)
Mode*uint32File or directory mode, e.g. 0o644
ReplaceboolWhen true, overwrite an existing path at the destination
SrcstringHost source path (copy_file / copy_dir)
DststringGuest destination path (copy_file / copy_dir)
TargetstringSymlink target
LinkstringSymlink path

PatchOptions

Used by Patch methods

Tuning struct passed to Patch methods that accept a mode and replace flag.
FieldTypeDescription
Mode*uint32File or directory mode
ReplaceboolOverwrite an existing path

PatchKind

Used by PatchConfig.Kind

type PatchKind string
Discriminator for PatchConfig. Prefer the Patch factory.
ConstantValue
PatchKindText"text"
PatchKindAppend"append"
PatchKindMkdir"mkdir"
PatchKindRemove"remove"
PatchKindSymlink"symlink"
PatchKindCopyFile"copy_file"
PatchKindCopyDir"copy_dir"

Patch

Produces PatchConfig for WithPatches()

Package-level factory namespace for PatchConfig values. See the Patch section for its methods.
MethodReturnsDescription
Text(path, content, opts)PatchConfigWrite UTF-8 text
Append(path, content)PatchConfigAppend to an existing file
Mkdir(path, opts)PatchConfigCreate a directory (idempotent)
Remove(path)PatchConfigDelete a file or directory (idempotent)
Symlink(target, link, opts)PatchConfigCreate a symlink
CopyFile(src, dst, opts)PatchConfigCopy a host file into the rootfs
CopyDir(src, dst, opts)PatchConfigCopy a host directory into the rootfs

SetupOption

Consumed by EnsureInstalled()

type SetupOption func(*setupConfig)
A functional option for EnsureInstalled. The only helper is WithSkipDownload.