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.

Typical flow

use microsandbox::Sandbox;

let sb = Sandbox::builder("api")             // 1. configure
    .image("python")
    .memory(1024)
    .create()                                // 2. boot the microVM
    .await?;

let out = sb.exec("python", ["-V"]).await?;  // 3. run
println!("{}", out.stdout()?);

sb.stop().await?;                            // 4. shut down

Static methods

Sandbox::builder()

fn builder(name: impl Into<String>) -> SandboxBuilder
let sb = Sandbox::builder("api")
    .image("python")
    .create()
    .await?;
Create a builder for configuring a new sandbox. The builder lets you set the image, resources, volumes, networking, secrets, and other options before booting the VM. Sandbox names must be non-empty and no longer than 128 UTF-8 bytes. See SandboxBuilder for all available options.

Parameters

nameimpl Into<String>
Sandbox name - must be unique and no longer than 128 UTF-8 bytes.

Returns

Builder for configuring the sandbox.

Sandbox::get()

async fn get(name: &str) -> MicrosandboxResult<SandboxHandle>
let handle = Sandbox::get("api").await?;
println!("{:?}", handle.status());
Get a handle to an existing sandbox (running or stopped). The handle provides status, configuration, and lifecycle control without requiring a full connection to the guest agent.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Returns

Handle with status and lifecycle control.

Sandbox::list()

async fn list() -> MicrosandboxResult<Vec<SandboxHandle>>
for h in Sandbox::list().await? {
    println!("{} - {:?}", h.name(), h.status());
}
List all sandboxes (running, stopped, and crashed).

Returns

All sandbox handles.

Sandbox::remove()

async fn remove(name: &str) -> MicrosandboxResult<()>
Sandbox::remove("api").await?;
Delete a stopped sandbox and all its state from disk (configuration, logs, runtime directory). Fails if the sandbox is still running - stop it first.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Sandbox::start()

async fn start(name: &str) -> MicrosandboxResult<Sandbox>
let sb = Sandbox::start("api").await?;
Restart a previously stopped sandbox. The VM reboots using the persisted configuration. The sandbox enters attached mode - it stops when your process exits.

Parameters

name&str
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox.

Sandbox::start_detached()

async fn start_detached(name: &str) -> MicrosandboxResult<Sandbox>
Restart a stopped sandbox in detached mode. The sandbox survives after your process exits.

Parameters

name&str
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox.

Instance methods

sb.config()

fn config(&self) -> &SandboxConfig
println!("{} MiB", sb.config().memory_mib);
Access the sandbox’s full configuration.

Returns

Sandbox configuration.

sb.detach()

async fn detach(self)
sb.detach().await; // keeps running in the background
Release the handle without stopping the sandbox. The sandbox continues running as a background process. Reconnect later with Sandbox::get().

sb.drain()

async fn drain(&self) -> MicrosandboxResult<()>
sb.drain().await?;
Start a graceful drain. Existing commands run to completion, but 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.request_drain()

async fn request_drain(&self) -> MicrosandboxResult<()>
Request graceful drain and return once the request is sent. Pair with wait_until_stopped() when the caller needs stopped-state observation.

sb.fs()

fn fs(&self) -> SandboxFsOps<'_>
sb.fs().write("/tmp/hello.txt", "hi").await?;
Get a filesystem handle for reading and writing files inside the running sandbox. See Filesystem for API details.

Returns

Filesystem handle.

sb.kill()

async fn kill(&self) -> MicrosandboxResult<()>
sb.kill().await?; // SIGKILL, no graceful shutdown
Force-terminate the sandbox immediately with SIGKILL. No graceful shutdown - use when the sandbox is unresponsive. Waits up to five seconds for stopped-state observation after the kill request. Pending writes that the workload hasn’t fsync’d may be lost, same durability semantics as a sudden power loss on a physical machine. Prefer stop() for graceful shutdown that gives the workload a chance to flush.

sb.kill_with_timeout()

async fn kill_with_timeout(&self, timeout: Duration) -> MicrosandboxResult<()>
Force-terminate the sandbox and wait up to timeout for stopped-state observation.

sb.request_kill()

async fn request_kill(&self) -> MicrosandboxResult<()>
Request force termination and return once the request is sent, without waiting for stopped-state observation.

sb.metrics()

async fn metrics(&self) -> MicrosandboxResult<SandboxMetrics>
let m = sb.metrics().await?;
println!("cpu {:.1}% · mem {} MiB", m.cpu_percent, m.memory_bytes / 1_048_576);
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 metrics.

sb.metrics_stream()

fn metrics_stream(&self, interval: Duration) -> impl Stream<Item = MicrosandboxResult<SandboxMetrics>>
use futures::StreamExt;

let mut stream = sb.metrics_stream(Duration::from_secs(1));
while let Some(snapshot) = stream.next().await {
    println!("{:.1}%", snapshot?.cpu_percent);
}
Stream resource metrics at a regular interval. Returns an async stream that yields a new snapshot every interval duration.

Parameters

intervalDuration
Time between metric snapshots.

Returns

Async stream yielding a snapshot each interval.

sb.logs()

fn logs(&self, opts: &LogOptions) -> MicrosandboxResult<Vec<LogEntry>>
use microsandbox::sandbox::{LogOptions, LogSource, Sandbox};

let handle = Sandbox::get("web").await?;

// Default: all user-program output, regardless of pipe/pty mode
let entries = handle.logs(&LogOptions::default())?;

for e in entries {
    let source = match e.source {
        LogSource::Stdout => "OUT",
        LogSource::Stderr => "ERR",
        LogSource::Output => "PTY",
        LogSource::System => "SYS",
    };
    println!(
        "[{}] {} {:?}: {}",
        e.timestamp.to_rfc3339(),
        source,
        e.session_id,
        String::from_utf8_lossy(&e.data).trim_end()
    );
}

// Filtered: last 50 entries from the past hour, including system lines
let recent = handle.logs(&LogOptions {
    tail: Some(50),
    since: Some(chrono::Utc::now() - chrono::Duration::hours(1)),
    sources: vec![
        LogSource::Stdout,
        LogSource::Stderr,
        LogSource::Output,
        LogSource::System,
    ],
    ..Default::default()
})?;
Read captured output from the sandbox’s exec.log. Backed by an on-disk JSON Lines file the runtime writes via the relay tap. Works on running and stopped sandboxes alike; there is no protocol traffic. The same method is available on SandboxHandle for callers that don’t want to start the sandbox first. The default sources are Stdout, Stderr, and Output (PTY-merged). Pass LogSource::System to also include synthetic lifecycle markers and runtime/kernel diagnostic lines. logs() is synchronous because it’s a pure file read.

Parameters

Filters: tail, since, until, sources. LogOptions::default() returns everything for the default sources.

Returns

Matching entries in chronological order.

sb.ping()

async fn ping(&self) -> MicrosandboxResult<SandboxPingResult>
let result = sb.ping().await?;
println!("{} reachable in {:?}", result.name, result.latency);
Check whether the running sandbox’s guest agent is reachable. This sends core.ping, returns the SDK-measured round-trip latency, and does not refresh the sandbox idle timer.

Returns

Sandbox name and ping latency.

sb.touch()

async fn touch(&self) -> MicrosandboxResult<SandboxTouchResult>
let result = sb.touch().await?;
println!("{} activity seq {}", result.name, result.activity_seq);
Explicitly refresh the running sandbox’s idle timer. This sends core.touch; use it when keeping an idle sandbox alive is intentional.

Returns

Sandbox name and agent activity sequence after the touch.

sb.modify()

fn modify(&self) -> SandboxModificationBuilder
let plan = sb.modify()
    .cpus(4)             // live when 4 <= max_cpus
    .memory(4096)        // live when 4096 MiB <= max_memory
    .env("MODE", "prod") // future execs only; the plan warns about this
    .apply()
    .await?;

for r in &plan.resize_status {
    println!("{:?}: requested {} · actual {} · {:?}", r.resource, r.requested, r.actual, r.state);
}
Plan or apply a configuration change. Set what to change (CPUs, memory, env vars, labels, workdir, secrets), then call dry_run() to preview or apply() to commit; both return a SandboxModificationPlan labeling each change live, next start, requires restart, or unsupported. Apply is all-or-nothing. CPU and memory resize live within the max_cpus / max_memory 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. See SandboxModificationBuilder for all setters and msb modify for the CLI.

Returns

Fluent builder; terminate with dry_run() or apply().

sb.name()

fn name(&self) -> &str
Get the sandbox name.

Returns

&str
Sandbox name, up to 128 UTF-8 bytes.

sb.owns_lifecycle()

fn owns_lifecycle(&self) -> bool
Whether this handle owns the sandbox lifecycle. true in attached mode (sandbox stops when your process exits), false in detached mode.

Returns

bool
true if attached.

sb.remove_persisted()

async fn remove_persisted(&self) -> MicrosandboxResult<()>
sb.remove_persisted().await?;
Remove the sandbox and all its persisted state from disk.

sb.request_stop()

async fn request_stop(&self) -> MicrosandboxResult<()>
Request graceful shutdown and return once the request is sent, without waiting for stopped-state observation. Pair with wait_until_stopped() when the caller needs the terminal state.

sb.stop()

async fn stop(&self) -> MicrosandboxResult<()>
sb.stop().await?;
Gracefully shut down the sandbox. Lets the sandbox finish writing any pending data to disk before it exits, so files written inside the sandbox aren’t lost across a later restart. Waits up to ten seconds for a clean exit; if the sandbox is still running after that, it is force-killed.

sb.stop_with_timeout()

async fn stop_with_timeout(&self, timeout: Duration) -> MicrosandboxResult<()>
Gracefully shut down the sandbox with an explicit timeout before escalation. Duration::ZERO skips graceful shutdown and force-kills immediately.

sb.stop_and_wait()

async fn stop_and_wait(&self) -> MicrosandboxResult<ExitStatus>
let status = sb.stop_and_wait().await?;
println!("exited: {}", status.success());
Stop the sandbox and wait for the exit status. This is a local-backend compatibility helper; prefer stop() or stop_with_timeout() when the caller only needs stopped-state observation.

Returns

Exit code and success flag.

sb.wait()

async fn wait(&self) -> MicrosandboxResult<ExitStatus>
let status = sb.wait().await?;
Block until the sandbox exits on its own (without triggering a stop). Returns the exit status.

Returns

Exit code and success flag.

sb.wait_until_stopped()

async fn wait_until_stopped(&self) -> MicrosandboxResult<SandboxStopResult>
Block until the sandbox is observed in a terminal non-running state. Owned local sandboxes can include process exit details; detached, name-addressed, and cloud-backed sandboxes report the observed backend state. Returns
TypeDescription
SandboxStopResultObserved terminal sandbox state

SandboxBuilder

Builder for configuring a sandbox before creation. Obtained via Sandbox::builder(name). Every setter returns Self, so calls chain. Examples are shown on the methods where usage is non-obvious; simple setters are demonstrated by the Typical flow above.

.build()

async fn build(self) -> MicrosandboxResult<SandboxConfig>
Materialize the SandboxConfig without booting the sandbox. Validates the configuration and, if from_snapshot was called, opens the snapshot manifest to pin its image reference and upper-layer source. For booting, use create instead; call detached(true) first for background mode. create() calls build internally.

Returns

Validated, ready-to-boot configuration.

.cpus()

fn cpus(self, count: u8) -> Self
Set the number of virtual CPUs. This is a limit, not a reservation. Default: 1.

Parameters

countu8
Number of vCPUs.

.max_cpus()

fn max_cpus(self, count: u8) -> Self
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

countu8
Maximum possible vCPUs.

.create()

async fn create(self) -> MicrosandboxResult<Sandbox>
Boot the sandbox in attached mode. The sandbox stops when your process exits.

Returns

Running sandbox.

.detached()

fn detached(self, detached: bool) -> Self
let sb = Sandbox::builder("worker")
    .image("python")
    .detached(true)
    .create()
    .await?;
sb.detach().await;
Choose whether the sandbox is created in detached/background mode. Detached sandboxes survive the creating process. Defaults to false.

Parameters

detachedbool
When true, create the sandbox in detached mode.

.create_detached()

async fn create_detached(self) -> MicrosandboxResult<Sandbox>
let sb = Sandbox::builder("worker")
    .image("python")
    .create_detached()
    .await?;
sb.detach().await;
Boot the sandbox in detached mode. This is a compatibility helper for .detached(true).create(). Prefer detached(true) with create() for new code so attached and detached creation use the same flow.

Returns

Running sandbox.

.disable_network()

fn disable_network(self) -> Self
Fully disable networking. No network interface is created.

.entrypoint()

fn entrypoint(self, cmd: impl IntoIterator<Item = impl Into<String>>) -> Self
Override the OCI image’s stored ENTRYPOINT. The value is consulted by command-resolution paths that follow OCI semantics, specifically msb exec / msb run against this sandbox from the terminal. Sandbox::exec and Sandbox::shell do not consult it; they pass cmd literally to the guest agent. Use this when configuring a sandbox via the SDK for later CLI attachment.

Parameters

cmdimpl IntoIterator
Entrypoint command and arguments.

.env()

fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self
Set an environment variable visible to all commands. Can be called multiple times. Per-command env vars (via exec_with) are merged on top.

Parameters

keyimpl Into<String>
Variable name.
valueimpl Into<String>
Variable value.

.hostname()

fn hostname(self, hostname: impl Into<String>) -> Self
Set the guest hostname.

Parameters

hostnameimpl Into<String>
Hostname.

.idle_timeout()

fn idle_timeout(self, secs: u64) -> Self
Auto-drain the sandbox after this many seconds of inactivity (no active exec sessions). Enforced on the host side.

Parameters

secsu64
Idle timeout in seconds.

.init()

fn init(self, cmd: impl Into<PathBuf>) -> Self
let sb = Sandbox::builder("worker")
    .image("jrei/systemd-debian:12")
    .init("auto")
    .create()
    .await?;
Hand off PID 1 inside the guest to cmd after agentd finishes its boot-time setup. The agent forks; the parent execs the init and becomes PID 1, the agent continues as a child process. See Custom init system for image picks, shutdown semantics, and tradeoffs. cmd is either an absolute path inside the guest rootfs or the literal "auto". Auto first honors a known init at the start of the image ENTRYPOINT, such as /init in s6-overlay images, then falls back to probing /sbin/init, /lib/systemd/systemd, and /usr/lib/systemd/systemd inside the guest. When attached msb run uses an image-declared init entrypoint, the remaining ENTRYPOINT plus CMD or trailing command is passed to that init instead of direct-executed through agentd. For init binaries that take argv or extra env (rare), use init_with.

Parameters

cmdimpl Into<PathBuf>
Absolute path inside the guest, or “auto”.

.init_with()

fn init_with(
    self,
    cmd: impl Into<PathBuf>,
    f: impl FnOnce(InitOptionsBuilder) -> InitOptionsBuilder,
) -> Self
let sb = Sandbox::builder("worker")
    .image("jrei/systemd-debian:12")
    .init_with("/lib/systemd/systemd", |i| i
        .args(["--unit=multi-user.target"])
        .env("container", "microsandbox"))
    .create()
    .await?;
Like init, but with a closure-builder for argv and env vars. Mirrors exec_with in shape. The builder exposes arg, args, env, and envs. Calling init or init_with more than once overwrites, unlike env, which appends. The init is one-shot pre-boot.

Parameters

cmdimpl Into<PathBuf>
Absolute path to the init binary inside the guest.
fFnOnce(InitOptionsBuilder)
Closure populating argv and env.

.image()

fn image(self, image: impl IntoImage) -> Self
Set the root filesystem source. Accepts OCI image names, local directory paths, or disk image paths. The format is auto-detected.

Parameters

imageimpl IntoImage
OCI image name, local directory path, or disk image path.

.image_with()

fn image_with(self, f: impl FnOnce(ImageBuilder) -> ImageBuilder) -> Self
use microsandbox::size::SizeExt;

let sb = Sandbox::builder("worker")
    .image_with(|i| i.oci("python:3.12").upper_size(8.gib()))
    .create()
    .await?;
Configure an explicit rootfs source. Use this for OCI-only settings such as the writable overlay upper size, or for disk images when the filesystem type can’t be auto-detected.

Parameters

fFnOnce(ImageBuilder)
Configure the rootfs source.

.log_level()

fn log_level(self, level: LogLevel) -> Self
Override the sandbox process’s log verbosity.

Parameters

Log level.

.max_duration()

fn max_duration(self, secs: u64) -> Self
Set the maximum sandbox lifetime in seconds. When exceeded, the sandbox is drained and stopped. Enforced on the host side - the guest cannot override it.

Parameters

secsu64
Maximum lifetime in seconds.

.memory()

fn memory(self, size: impl Into<Mebibytes>) -> Self
Set the guest memory size. Physical pages are only allocated as the guest touches them, so this is a limit, not an upfront reservation. Default: 512 MiB.

Parameters

sizeimpl Into<Mebibytes>
Memory in MiB.

.max_memory()

fn max_memory(self, size: impl Into<Mebibytes>) -> Self
Set the boot-time maximum hotpluggable guest memory. 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

sizeimpl Into<Mebibytes>
Maximum memory in MiB.

.network()

fn network(self, f: impl FnOnce(NetworkBuilder) -> NetworkBuilder) -> Self
Configure networking. See Networking for the full builder API.

Parameters

Configure the network.

.patch()

fn patch(self, f: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self
Modify the rootfs before the VM boots. Patches go into the writable layer - the base image is untouched. See PatchBuilder for the operations.

Parameters

Configure rootfs patches.

.port()

fn port(self, host_port: u16, guest_port: u16) -> Self
Publish a TCP port from the sandbox to the host. The default host bind address is 127.0.0.1.

Parameters

host_portu16
Port on the host.
guest_portu16
Port inside the sandbox.

.port_bind()

fn port_bind(self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self
Publish a TCP port on a specific host bind address, such as 0.0.0.0.

Parameters

host_bindIpAddr
Host bind address.
host_portu16
Port on the host.
guest_portu16
Port inside the sandbox.

.port_udp()

fn port_udp(self, host_port: u16, guest_port: u16) -> Self
Publish a UDP port. The default host bind address is 127.0.0.1.

Parameters

host_portu16
Port on the host.
guest_portu16
Port inside the sandbox.

.port_udp_bind()

fn port_udp_bind(self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self
Publish a UDP port on a specific host bind address.

Parameters

host_bindIpAddr
Host bind address.
host_portu16
Port on the host.
guest_portu16
Port inside the sandbox.

.pull_policy()

fn pull_policy(self, policy: PullPolicy) -> Self
Control when the OCI image is pulled from the registry.

Parameters

Pull behavior.

.registry()

fn registry(self, f: impl FnOnce(RegistryConfigBuilder) -> RegistryConfigBuilder) -> Self
use microsandbox::{RegistryAuth, Sandbox};

let sb = Sandbox::builder("worker")
    .image("registry.example.com/team/app:latest")
    .registry(|r| r.auth(RegistryAuth::Basic {
        username: "user".into(),
        password: "token".into(),
    }))
    .create()
    .await?;
Configure registry connection settings for the sandbox image pull, including explicit auth, insecure HTTP, and custom CA certificates.

Parameters

Closure that configures registry auth and TLS options.

.replace()

fn replace(self) -> Self
If a sandbox with the same name already exists, stop it, remove it, and create a fresh one. Without this, creation fails on name conflict.

.script()

fn script(self, name: impl Into<String>, content: impl Into<String>) -> Self
Add a named script at /.msb/scripts/ inside the guest. Scripts are added to PATH and can be called by name via exec() or shell().

Parameters

nameimpl Into<String>
Script name (becomes the filename).
contentimpl Into<String>
Script content.

.secret()

fn secret(self, f: impl FnOnce(SecretBuilder) -> SecretBuilder) -> Self
Add a secret with full configuration. See Secrets for the builder API. Automatically enables TLS interception.

Parameters

Configure the secret.

.secret_env()

fn secret_env(self, env_var: impl Into<String>, value: impl Into<String>, allowed_host: impl Into<String>) -> Self
Shorthand for adding a header-injected secret. Equivalent to .secret(|s| s.env(env_var).value(value).allow_host(allowed_host)).
Plaintext at rest. The value is persisted verbatim in the durable sandbox config until a later modify rotate migrates the entry to a source reference. Prefer .secret(|s| s.source(..)) when the value can be referenced; use this path when you hold only a value. A future host-side secret store will switch this method to import-then-reference with no signature change.

Parameters

env_varimpl Into<String>
Environment variable name (non-empty, no = or NUL).
valueimpl Into<String>
Secret value.
allowed_hostimpl Into<String>
Allowed destination host.

.shell()

fn shell(self, shell: impl Into<String>) -> Self
Set the shell used by Sandbox::shell(). Default: /bin/sh.

Parameters

shellimpl Into<String>
Shell path (e.g. “/bin/bash”).

.user()

fn user(self, user: impl Into<String>) -> Self
Set the default guest user for all commands.

Parameters

userimpl Into<String>
User name or UID.

.volume()

fn volume(self, guest_path: impl Into<String>, f: impl FnOnce(MountBuilder) -> MountBuilder) -> Self
Add a volume mount. See Volumes for mount types.

Parameters

guest_pathimpl Into<String>
Mount point inside the sandbox.
Configure the mount.

.workdir()

fn workdir(self, path: impl Into<String>) -> Self
Set the default working directory for all commands.

Parameters

pathimpl Into<String>
Absolute path inside the guest.

PatchBuilder

Fluent builder for the ordered list of pre-boot rootfs patches. Used in SandboxBuilder::patch(|p| p...). Each method appends one operation; calls are chainable. By default a method that targets a path already present in the image errors at boot; pass replace = true on the operation to allow overwriting. mkdir and remove are idempotent. See Patches for conceptual context.

.append()

fn append(self, path: impl Into<String>, content: impl Into<String>) -> Self
Append content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.

Parameters

pathimpl Into<String>
Absolute path inside the guest.
contentimpl Into<String>
Text to append.

.copy_dir()

fn copy_dir(self, src: impl Into<PathBuf>, dst: impl Into<String>, replace: bool) -> Self
Recursively copy a host directory at src into the guest rootfs at dst.

Parameters

srcimpl Into<PathBuf>
Host source directory.
dstimpl Into<String>
Absolute destination path inside the guest.
replacebool
When true, overwrite an existing path at dst.

.copy_file()

fn copy_file(
    self,
    src: impl Into<PathBuf>,
    dst: impl Into<String>,
    mode: Option<u32>,
    replace: bool,
) -> Self
Copy a single host file at src into the guest rootfs at dst.

Parameters

srcimpl Into<PathBuf>
Host source file.
dstimpl Into<String>
Absolute destination path inside the guest.
modeOption<u32>
File mode, e.g. Some(0o644). None keeps the source mode.
replacebool
When true, overwrite an existing path at dst.

.file()

fn file(
    self,
    path: impl Into<String>,
    content: impl Into<Vec<u8>>,
    mode: Option<u32>,
    replace: bool,
) -> Self
Write raw bytes at path.

Parameters

pathimpl Into<String>
Absolute path inside the guest.
contentimpl Into<Vec<u8>>
Raw byte content.
modeOption<u32>
File mode, e.g. Some(0o644).
replacebool
When true, overwrite an existing path.

.mkdir()

fn mkdir(self, path: impl Into<String>, mode: Option<u32>) -> Self
Create a directory at path. Idempotent: a no-op if the directory already exists.

Parameters

pathimpl Into<String>
Absolute path inside the guest.
modeOption<u32>
Directory mode, e.g. Some(0o755).

.remove()

fn remove(self, path: impl Into<String>) -> Self
Delete a file or directory at path. Idempotent: a no-op if the path doesn’t exist.

Parameters

pathimpl Into<String>
Absolute path inside the guest.
fn symlink(self, target: impl Into<String>, link: impl Into<String>, replace: bool) -> Self
Create a symlink at link pointing to target.

Parameters

targetimpl Into<String>
What the symlink points to (literal symlink target text).
linkimpl Into<String>
Absolute path of the symlink itself.
replacebool
When true, overwrite an existing path at link.

.text()

fn text(
    self,
    path: impl Into<String>,
    content: impl Into<String>,
    mode: Option<u32>,
    replace: bool,
) -> Self
Write UTF-8 text content at path.

Parameters

pathimpl Into<String>
Absolute path inside the guest.
contentimpl Into<String>
Text content.
modeOption<u32>
File mode, e.g. Some(0o644).
replacebool
When true, overwrite an existing path.

SandboxModificationBuilder

Fluent builder for changing an existing sandbox’s configuration. Obtained via sb.modify() or SandboxHandle::modify(). Nothing happens until you finish with dry_run() or apply(); both return a SandboxModificationPlan that labels each change live, next start, requires restart, or unsupported. Apply is all-or-nothing: if any change conflicts, is unsupported, or needs a restart you did not allow, the call fails and nothing changes. CPU and memory changes take effect immediately on a running sandbox as long as the new values stay within max_cpus / max_memory; raising those limits requires a restart, so reserve headroom at create time. Env and workdir changes affect future execs only; running processes keep their current environment (the plan notes this as a warning). The CLI equivalent is msb modify.

.apply()

async fn apply(self) -> MicrosandboxResult<SandboxModificationPlan>
Apply the changes. Live changes are made to the running sandbox first, and the new config is saved only after they succeed, so a failed apply leaves the old config in place. Changes for a stopped sandbox, or requested with next_start(), are saved and take effect on the next start. With restart(), the sandbox is stopped and started so that restart-required changes take effect. A live CPU or memory resize can take a moment to settle. The returned plan’s resize_status reports progress per resource; see ResourceResizeStatus.

Returns

The applied plan, with applied: true and live resize outcomes in resize_status.

.cpus()

fn cpus(self, cpus: u8) -> Self
Set the desired effective vCPU count. Applies live to a running sandbox when the target fits inside the booted max_cpus; otherwise it requires a restart.

Parameters

cpusu8
Number of vCPUs.

.max_cpus()

fn max_cpus(self, max_cpus: u8) -> Self
Set the desired boot-time maximum possible vCPU count. Capacity is fixed at boot, so this is always restart-backed on a running sandbox.

Parameters

max_cpusu8
Maximum possible vCPUs.

.dry_run()

async fn dry_run(self) -> MicrosandboxResult<SandboxModificationPlan>
let plan = sb.modify().cpus(8).dry_run().await?;

for change in &plan.changes {
    if let PlannedChange::Config(c) = change {
        println!("{}: {:?} -> {:?} ({:?})", c.field, c.before, c.after, c.disposition);
    }
}
Compute the modification plan without applying anything. Use it to preview how each change classifies and whether conflicts block the patch.

Returns

The plan, with applied: false.

.env()

fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self
Set an environment variable for future execs. Can be called multiple times. On a running sandbox this applies to future execs only; running processes keep their current environment.

Parameters

keyimpl Into<String>
Variable name.
valueimpl Into<String>
Variable value.

.remove_env()

fn remove_env(self, key: impl Into<String>) -> Self
Remove an environment variable. Same future-execs-only semantics as env().

Parameters

keyimpl Into<String>
Variable name to remove.

.label()

fn label(self, key: impl Into<String>, value: impl Into<String>) -> Self
Set a sandbox label. Can be called multiple times.

Parameters

keyimpl Into<String>
Label key.
valueimpl Into<String>
Label value.

.remove_label()

fn remove_label(self, key: impl Into<String>) -> Self
Remove a sandbox label.

Parameters

keyimpl Into<String>
Label key to remove.

.memory()

fn memory(self, size: impl Into<Mebibytes>) -> Self
Set the desired effective guest memory. Applies live to a running sandbox when the target fits inside the booted max_memory; otherwise it requires a restart.

Parameters

sizeimpl Into<Mebibytes>
Memory in MiB.

.memory_mib()

fn memory_mib(self, memory_mib: u32) -> Self
Set the desired effective guest memory in MiB. Same as memory() with an explicit unit.

Parameters

memory_mibu32
Memory in MiB.

.max_memory()

fn max_memory(self, size: impl Into<Mebibytes>) -> Self
Set the desired boot-time maximum hotpluggable memory. Capacity is fixed at boot, so this is always restart-backed on a running sandbox.

Parameters

sizeimpl Into<Mebibytes>
Maximum memory in MiB.

.max_memory_mib()

fn max_memory_mib(self, max_memory_mib: u32) -> Self
Set the desired boot-time maximum hotpluggable memory in MiB. Same as max_memory() with an explicit unit.

Parameters

max_memory_mibu32
Maximum memory in MiB.

.next_start()

fn next_start(self) -> Self
Persist the requested changes for the next start, leaving any running VM unchanged. Every change classifies as next start.

.restart()

fn restart(self) -> Self
Plan under restart-backed apply semantics. When the patch contains restart-required changes, apply() stops the sandbox, persists the config, and starts it again so the changes become active now.

.secret()

fn secret(self, f: impl FnOnce(SecretPatchBuilder) -> SecretPatchBuilder) -> Self
use microsandbox::sandbox::SecretSource;

let plan = sb.modify()
    .secret(|s| s
        .env("API_KEY")
        .source(SecretSource::Env { var: "API_KEY".into() })
        .allow_host("api.example.com"))
    .apply()
    .await?;
Declare the desired state of one secret via a SecretPatchBuilder closure. The spec mirrors the create-time SecretBuilder vocabulary, and the planner diffs it against the existing config to infer the change: a secret that does not exist yet is added, material on an existing secret rotated, and host or placeholder differences update those aspects. Declaring the same secret again replaces the earlier spec; removal is always explicit through remove_secret().

Parameters

fFnOnce(SecretPatchBuilder)
Closure declaring the secret’s desired state.

.remove_secret()

fn remove_secret(self, name: impl Into<String>) -> Self
Remove a secret. Removal is always explicit; omitting a secret from the patch never removes it.

Parameters

nameimpl Into<String>
Secret name (its environment variable name).

.workdir()

fn workdir(self, path: impl Into<String>) -> Self
Set the working directory for future execs. On a running sandbox this applies to future execs only.

Parameters

pathimpl Into<String>
Absolute path inside the guest.

Types

LogEntry

Returned by logs()

A single captured log entry returned by logs().
FieldTypeDescription
timestampDateTime<Utc>Wall-clock capture time on the host
sourceLogSourceWhere the chunk came from
session_idOption<u64>Relay-monotonic session id; None for System entries
dataBytesThe chunk’s bytes (UTF-8 lossy decoded by default; raw bytes if --raw mode was used)

LogLevel

Used by log_level()

Sandbox process log verbosity.
ValueDescription
ErrorErrors only
WarnWarnings and errors only
InfoInfo and higher
DebugDebug and higher
TraceMost verbose - all diagnostic output

LogOptions

Used by logs()

Filters passed to logs(). All fields optional. LogOptions::default() returns everything for the default sources (Stdout + Stderr + Output).
FieldTypeDescription
tailOption<usize>Show only the last N entries after other filters apply
sinceOption<DateTime<Utc>>Inclusive lower bound on entry timestamp
untilOption<DateTime<Utc>>Exclusive upper bound on entry timestamp
sourcesVec<LogSource>Sources to include. Empty = [Stdout, Stderr, Output] (the default user-program sources). Add System to merge runtime/kernel diagnostics.

LogSource

Used by LogEntry.source · LogOptions.sources

Tag indicating where a captured log entry came from.
ValueDescription
StdoutCaptured from a session’s stdout (pipe mode; streams stayed separated)
StderrCaptured from a session’s stderr (pipe mode)
OutputCaptured from a session running in pty mode. PTY allocation merges stdout and stderr at the kernel level inside the guest, so they arrive as a single stream, tagged Output rather than mislabeled as Stdout.
SystemSynthetic entry: lifecycle markers in exec.log plus runtime/kernel diagnostic lines merged in at read time when System is requested.

SandboxPingResult

Returned by ping() · SandboxHandle.ping()

Result of a successful agent reachability check.
FieldTypeDescription
nameStringSandbox name that was pinged
latencyDurationSDK-measured round-trip latency

SandboxTouchResult

Returned by touch() · SandboxHandle.touch()

Result of an explicit idle-timer refresh.
FieldTypeDescription
nameStringSandbox name that was touched
activity_sequ64Agent activity sequence after the touch was recorded

PullPolicy

Used by pull_policy()

Controls when the SDK fetches an OCI image from the registry.
ValueDescription
AlwaysPull the image every time, even if cached locally
IfMissingPull only if the image is not already cached. This is the default.
NeverNever pull; fail if the image is not cached locally

RegistryAuth

Used by registry()

Credentials for authenticating to a private container registry.
VariantFieldsDescription
Basic- username: String
- password: String
Username and password authentication

RegistryConfigBuilder

Used by registry()

Builder passed to registry() for per-sandbox registry connection settings.
MethodDescription
auth(auth: RegistryAuth)Set explicit credentials for the image registry
insecure()Use plain HTTP for the registry
ca_certs(pem_data: Vec<u8>)Trust additional PEM-encoded CA certificates

SandboxConfig

Returned by config() · build()

The full configuration of a sandbox. Obtained via config() or built via SandboxBuilder. Contains all settings used to create the sandbox.
FieldTypeDescription
cpusu8Number of virtual CPUs
envVec<(String, String)>Environment variables
idle_timeout_secsOption<u64>Idle timeout
imageRootfsSourceRoot filesystem source (OCI, bind, or disk image)
max_duration_secsOption<u64>Maximum lifetime
max_cpusu8Boot-time maximum possible virtual CPUs
max_memory_mibu32Boot-time maximum hotpluggable memory in MiB
memory_mibu32Guest memory in MiB
nameStringSandbox name, up to 128 UTF-8 bytes
patchesVec<Patch>Rootfs patches
scriptsVec<(String, String)>Named scripts
shellOption<String>Shell for shell() calls
volumesVec<VolumeMount>Volume mounts
workdirOption<String>Default working directory

SandboxHandle

Returned by Sandbox::get() · Sandbox::list()

A lightweight handle to an existing sandbox (running or stopped). Obtained via Sandbox::get() or Sandbox::list(). Provides status, configuration, and lifecycle control without an active connection to the guest agent. You cannot exec or fs on a handle - call .start() or .connect() to upgrade to a full Sandbox.
Property / MethodTypeDescription
config()Result<SandboxConfig>Parsed configuration
config_json()&strRaw JSON configuration
connect()Result<Sandbox>Connect to a running sandbox; returns an error if it doesn’t respond within ten seconds
connect_with_timeout(timeout)Result<Sandbox>Same as connect() with an explicit timeout
created_at()Option<DateTime<Utc>>Creation timestamp
kill()Result<()>Force terminate and wait until stopped state is observed
kill_with_timeout(timeout)Result<()>Same as kill() with an explicit observation timeout
logs()Result<Vec<LogEntry>>Read captured exec.log (works without starting)
metrics()Result<SandboxMetrics>Point-in-time resource metrics
modify()SandboxModificationBuilderStart planning a configuration change (works without starting; changes on a stopped sandbox persist for the next boot)
name()&strSandbox name, up to 128 UTF-8 bytes
ping()Result<SandboxPingResult>Check agent reachability without refreshing idle activity
remove()Result<()>Delete sandbox and state
request_drain()Result<()>Request graceful drain without waiting
request_kill()Result<()>Request force termination without waiting
request_stop()Result<()>Request graceful shutdown without waiting
start()Result<Sandbox>Start in attached mode
start_detached()Result<Sandbox>Start in detached mode
status()SandboxStatusCurrent status
stop()Result<()>Gracefully shut down. Waits up to ten seconds for pending writes to flush, then force-kills
stop_with_timeout(timeout)Result<()>Same as stop() with an explicit timeout; Duration::ZERO force-kills immediately
touch()Result<SandboxTouchResult>Explicitly refresh the sandbox idle timer
updated_at()Option<DateTime<Utc>>Last update timestamp
wait_until_stopped()Result<SandboxStopResult>Block until terminal state is observed

SandboxModificationPlan

Returned by dry_run() · apply()

Dry-run or apply plan for a sandbox modification. Values never appear in a plan: secret entries carry only guest-visible references.
FieldTypeDescription
sandboxStringSandbox being modified
statusStringSandbox status used for classification ("running", "stopped", …)
appliedboolWhether the changes were applied; false for dry runs
policyModificationPolicyPolicy used to produce the plan: NoRestart (default), NextStart, or Restart
changesVec<PlannedChange>Planned changes, one entry per field or secret
conflictsVec<ModificationConflict>Conflicts (field + message) that must be resolved before the patch can apply
warningsVec<ModificationWarning>Non-fatal warnings (field + message) about the patch or current runtime capabilities, e.g. the future-execs-only env caveat
resize_statusVec<ResourceResizeStatus>Live resource resize outcomes, populated by apply() when a live change ran

SecretPatchBuilder

Used by secret()

Fluent builder for one declarative secret patch inside SandboxModificationBuilder::secret(). It shares the create-time SecretBuilder vocabulary: name the secret, provide material by source reference or raw value, set the placeholder when needed, and declare the allowed hosts. Import path: microsandbox::sandbox::SecretPatchBuilder. Prefer source(...) over value(...) when the value can be referenced; see the at-rest note on secret_env() and Secrets for the full model.

.env()

fn env(self, name: impl Into<String>) -> Self
Name the secret. This is the environment variable that exposes the placeholder inside the guest. Required.

Parameters

nameimpl Into<String>
Secret name, usually the environment variable name.

.source()

fn source(self, source: SecretSource) -> Self
Provide the secret material as a host-side SecretSource reference. The durable config records only the reference, and the value is resolved host-side when the change applies. Mutually exclusive with value(...).

Parameters

Host-side reference for the secret material.

.value()

fn value(self, value: impl Into<String>) -> Self
Provide the secret material as a raw value, for embedders that hold only a value. The value is zeroized on drop, redacted from Debug, and never enters the plan. Applying a value persists it into the durable config until a later source-based rotate migrates it to a reference, the same at-rest property as secret_env(). Mutually exclusive with source(...).

Parameters

valueimpl Into<String>
Raw secret value held by the embedding process.

.placeholder()

fn placeholder(self, placeholder: impl Into<String>) -> Self
Set the guest-visible placeholder. Placeholder changes cannot reach already-running processes, so they classify as requires restart on a running sandbox.

Parameters

placeholderimpl Into<String>
Guest-visible placeholder string.

.allow_host()

fn allow_host(self, host: impl Into<String>) -> Self
Add an allowed host pattern, such as api.example.com, *.example.org, or *. A non-empty list replaces the secret’s current allow-list; an empty list leaves it unchanged. A new secret needs at least one.

Parameters

hostimpl Into<String>
Allowed exact host, wildcard host pattern, or *.

SecretSource

Used by SecretPatchBuilder.source()

Host-side source for secret material. The source is resolved when the modification applies, and plans only show guest-visible references. Import path: microsandbox::sandbox::SecretSource.
VariantFieldDescription
Envvar: StringRead the value from a host environment variable at apply time
Storereference: StringReserved for a host-side secret store reference; current modifiers report it as unsupported

PlannedChange

Used by SandboxModificationPlan.changes

One planned modification entry. This enum has a Config variant for ordinary configuration fields and a Secret variant for secret changes.
VariantTypeDescription
ConfigConfigPlannedChangeOrdinary config change
SecretSecretPlannedChangeSecret change. Values are omitted by construction; references are guest-visible only

ConfigPlannedChange

Variant of PlannedChange::Config

Ordinary configuration change in a modification plan.
FieldTypeDescription
fieldStringConfig field being changed
changeChangeKindAdded, Updated, or Removed
beforeOption<String>Previous safe visible state
afterOption<String>New safe visible state
dispositionModificationDispositionWhen or whether the change can take effect
reasonOption<String>Human-readable reason for the classification, when useful

SecretPlannedChange

Variant of PlannedChange::Secret

Secret change in a modification plan. Values are omitted by construction; before_ref and after_ref are guest-visible references.
FieldTypeDescription
fieldStringAlways "secret"
nameStringStable secret identity, usually the environment variable name
changeSecretChangeKindAdded, Rotated, Removed, Renamed, HostsUpdated, or PlaceholderUpdated
before_refOption<String>Previous guest-visible reference or placeholder
after_refOption<String>New guest-visible reference or placeholder
dispositionModificationDispositionWhen or whether the change can take effect
allow_hostsVec<String>Allowed hosts after the requested change
reasonOption<String>Human-readable reason for the classification, when useful

ModificationDisposition

Used by ConfigPlannedChange.disposition · SecretPlannedChange.disposition

When or whether a planned change can take effect. Serializes as the quoted strings below.
ValueDescription
Live ("live")Applies to the running VM now
NextStart ("next start")Persists to the desired config and applies the next time the sandbox starts
RequiresRestart ("requires restart")Needs a restart before it can take effect; apply() refuses it unless the restart() policy is selected
Unsupported ("unsupported")Cannot be changed by modify

ResourceResizeStatus

Used by SandboxModificationPlan.resize_status

Runtime convergence status for a live resource resize. Enforcement applies immediately; the guest converges asynchronously (onlining CPUs, plugging memory blocks).
FieldTypeDescription
resourceResourceKindCpus or Memory
requestedStringRequested value
actualStringActual value observed in the guest/runtime
enforcedStringHost/VMM-enforced value
stateResourceConvergenceStateConvergence state, see below
StateDescription
AcceptedThe runtime accepted the request
ConvergingThe guest and VMM are still converging on the requested state
AppliedDesired, actual, and enforced state match
GuestRefusedThe guest would not cooperate; the host enforces the new limit anyway
FailedThe resize failed

SandboxStopResult

Observed terminal sandbox state returned by wait_until_stopped().
FieldTypeDescription
nameStringSandbox name
statusSandboxStatusTerminal status that was observed
exit_codeOption<i32>Process exit code when available from an owned child process
signalOption<i32>Terminating signal when available from an owned child process
observed_atDateTime<Utc>When the terminal state was observed
sourceOption<String>Description of the observation source

SandboxMetrics

Returned by metrics() · metrics_stream()

Point-in-time resource usage snapshot.
FieldTypeDescription
cpu_percentf32CPU usage as a percentage
disk_read_bytesu64Total bytes read from disk since boot
disk_write_bytesu64Total bytes written to disk since boot
memory_bytesu64Current memory usage in bytes
memory_limit_bytesu64Memory limit in bytes
net_rx_bytesu64Total bytes received over the network since boot
net_tx_bytesu64Total bytes sent over the network since boot
upper_used_bytesOption<u64>Guest-visible OCI upper filesystem used bytes when the protected reporter is available and fresh
upper_free_bytesOption<u64>Guest-visible OCI upper filesystem free bytes when the protected reporter is available and fresh
upper_host_allocated_bytesOption<u64>Host-allocated bytes for the writable OCI upper image when available
timestampDateTime<Utc>When this measurement was taken
uptimeDurationTime since the sandbox was created

SandboxStatus

Used by SandboxHandle.status()

ValueDescription
CrashedVM exited unexpectedly (kernel panic, OOM, etc.)
DrainingGraceful shutdown in progress; existing commands finish, new ones rejected
RunningGuest agent is ready; exec, shell, fs work
StoppedVM shut down; configuration persisted; can be restarted