m "github.com/superradcompany/microsandbox/sdk/go".
For local runtime installation and verification, see Runtime setup.
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.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
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()
Returns
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. 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.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.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. For a sandbox created with WithDetached, Close stops the VM. Use Detach instead to leave it running.
sb.OwnsLifecycle()
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
true if attached.sb.OwnsLifecycleOrFalse()
OwnsLifecycle that swallows the error and returns false on any failure. Suitable for log lines and best-effort branching.
Returns
true if attached, false on detach or error.Options
Functional options forCreateSandbox. Map and slice options merge across repeated calls; single-value setters like WithImage replace.
WithImage()
"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. See Snapshots.
Parameters
pathOrNamestringWithMemory()
512 MiB.
Parameters
mebibytesuint32WithMaxMemory()
Parameters
mebibytesuint32WithCPUs()
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 stops a detached sandbox; use Detach to leave it running.
WithEphemeral()
Parameters
ephemeralbooltrue to delete all state on termination.WithEntrypoint()
WithInit instead.
Parameters
cmd…stringWithInit()
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
authRegistryAuthWithPorts()
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.DurationWithKillTimeout()
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.
Patch
Factory that constructs 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.
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
Factory that constructsInitConfig 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()
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
cmdstringoptsInitOptionsTypes
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 cannotExec 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 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.
Metrics
Returned by Metrics() · MetricsStream() · AllSandboxMetrics()
Point-in-time resource usage snapshot.MetricsStreamHandle
Returned by MetricsStream()
Live metrics subscription. CallClose to release Rust-side resources.
SandboxStopResult
Returned by WaitUntilStopped()
Describes a terminal sandbox state observed byWaitUntilStopped.
SandboxStatus
Used by SandboxHandle.Status() · SandboxStopResult.Status
LogEntry
Returned by Logs() · LogStream()
A single captured log entry.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.
LogStreamHandle
Returned by LogStream()
Live log subscription. CallClose to release Rust-side resources.
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.
Init
Produces InitConfig for WithInit()
Package-level factory namespace forInitConfig values. See the Init section for its methods.
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.
Patch
Produces PatchConfig for WithPatches()
Package-level factory namespace forPatchConfig values. See the Patch section for its methods.
SetupOption type is documented under Runtime setup.