Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions README-zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,51 @@ N=100 实测 CoW 开销是 **每个 child 0.12 MiB**(详见 [bench/](./bench/)),

要求:x86_64 Linux,带 KVM,Ubuntu 22.04 或更新。

### 一. 确认主机环境就绪

```bash
pip install forkd
sudo bash scripts/setup-host.sh # KVM + tap 设备,一次性
sudo bash scripts/netns-setup.sh 3 # 每子 VM 的网络 namespace
forkd doctor # 一键检查上面这些是否到位
```

`forkd doctor` 跑 10 项检查(KVM、tap、netns、firecracker 二进制、
内核镜像、daemon...),不通过的项目附带修复提示。任何东西觉得不对
就先跑它。

### 二. 从 Docker 镜像起步(一条命令)

`forkd from-image` 把 Docker pull → ext4 → 启动 + 暖启动 → pause →
注册 tag 串成一条命令,输出是一个你可以立刻 fork 的 tag:

```bash
sudo -E forkd from-image python:3.12-slim \
--tag py-numpy \
--extra python3-numpy
# 第一次 2-3 分钟(Docker pull + ext4 + warmup),之后走缓存。

sudo -E forkd fork --tag py-numpy -n 5 --per-child-netns
```

### 三. 探测你装的 forkd 实际有多快

```bash
forkd bench --tag py-numpy --n 5
# forkd bench against snapshot py-numpy
# spawn (n=1) 61 ms
# exec round-trip 22 ms
# branch (diff=true) 287 ms pause_ms=234 ...
# fanout (n=5) 65 ms 13ms/child
# cleanup 136 ms
# -----
# total 571 ms
```

screenshot 友好,跑一遍能知道 v0.3 在你机器上是不是真有那个速度。

### 四. 从源码构建你自己的暖启动父 VM

```bash
# 1. 主机准备:KVM、Firecracker、Rust、KSM、大页、tap 设备。
sudo bash scripts/setup-host.sh
Expand Down
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,13 +319,22 @@ Measured CoW overhead at N=100 is **0.12 MiB / child** on top of the parent ([be

Requires: x86_64 Linux with KVM, Ubuntu 22.04 or newer.

### Fastest path — pull a pre-built snapshot from the Hub
### Confirm your host is ready

```bash
pip install forkd
sudo bash scripts/setup-host.sh # KVM + tap device, one-time
sudo bash scripts/netns-setup.sh 3 # per-child network namespaces
forkd doctor # green-lights everything above
```

`forkd doctor` runs 10 checks (KVM, tap, netns, firecracker binary,
kernel image, daemon, ...) and emits fix hints for each failure.
Run this first whenever something feels off.

### Fastest path — pull a pre-built snapshot from the Hub

```bash
# 14.5 MiB pack (a Python 3.12 + LangGraph-ready snapshot) → 15s download.
forkd pull deeplethe/langgraph-react

Expand All @@ -336,6 +345,38 @@ sudo -E forkd fork --tag langgraph -n 3 --per-child-netns
See [`docs/HUB.md`](./docs/HUB.md) for the registry model + how to
publish your own snapshot pack.

### From a Docker image (one command)

`forkd from-image` wraps Docker pull → ext4 → boot + warmup → pause →
register tag into a single verb. The output is a tag you can
immediately fork from:

```bash
sudo -E forkd from-image python:3.12-slim \
--tag py-numpy \
--extra python3-numpy
# 2-3 min the first time (Docker pull + ext4 + warmup); cached after that.

sudo -E forkd fork --tag py-numpy -n 5 --per-child-netns
```

### Probe your install's latency

```bash
forkd bench --tag py-numpy --n 5
# forkd bench against snapshot py-numpy
# spawn (n=1) 61 ms sb-...-0027
# exec round-trip 22 ms exit=0
# branch (diff=true) 287 ms pause_ms=234 diff_physical_bytes=393216
# fanout (n=5) 65 ms 13ms/child
# cleanup 136 ms
# -----
# total 571 ms
```

Run this against any snapshot to see how forkd actually performs on
your hardware. Screenshot-friendly output.

### From-source path — build your own warmed parent

```bash
Expand Down
44 changes: 44 additions & 0 deletions crates/forkd-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
mod bench;
mod doctor;
mod hub;
mod sandbox;

use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
Expand Down Expand Up @@ -242,6 +243,38 @@ enum Cmd {
#[arg(long)]
mem_size_mib: Option<u32>,
},
/// List live sandboxes (GET /v1/sandboxes). Table output.
Ls {
/// Controller daemon base URL.
#[arg(long, env = "FORKD_URL", default_value = "http://127.0.0.1:8889")]
daemon_url: String,
/// Bearer token (matches the daemon's --token-file).
#[arg(long, env = "FORKD_TOKEN")]
daemon_token: Option<String>,
},
/// Kill one or more sandboxes (DELETE /v1/sandboxes/:id).
///
/// Examples:
/// forkd kill sb-abc-0000
/// forkd kill sb-abc-0000 sb-abc-0001
/// forkd kill --all
/// forkd kill --tag pyagent
Kill {
/// Sandbox IDs to kill. Repeatable; ignored if --all or --tag is set.
ids: Vec<String>,
/// Kill every live sandbox the daemon knows about.
#[arg(long, conflicts_with = "tag")]
all: bool,
/// Kill every sandbox forked from this snapshot tag.
#[arg(long, conflicts_with = "all")]
tag: Option<String>,
/// Controller daemon base URL.
#[arg(long, env = "FORKD_URL", default_value = "http://127.0.0.1:8889")]
daemon_url: String,
/// Bearer token (matches the daemon's --token-file).
#[arg(long, env = "FORKD_TOKEN")]
daemon_token: Option<String>,
},
/// Show where snapshots are stored.
Where,
/// Pack a local snapshot into a portable `.forkd-snapshot.tar.zst` file.
Expand Down Expand Up @@ -610,6 +643,17 @@ fn main() -> Result<()> {
boot_wait_secs,
mem_size_mib,
),
Cmd::Ls {
daemon_url,
daemon_token,
} => sandbox::ls(&daemon_url, daemon_token),
Cmd::Kill {
ids,
all,
tag,
daemon_url,
daemon_token,
} => sandbox::kill(&daemon_url, daemon_token, ids, all, tag),
Cmd::Where => {
println!("{}", data_dir().display());
Ok(())
Expand Down
164 changes: 164 additions & 0 deletions crates/forkd-cli/src/sandbox.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
//! `forkd ls` + `forkd kill` — direct sandbox lifecycle without curl.
//!
//! Wraps the two endpoints (GET /v1/sandboxes, DELETE /v1/sandboxes/:id)
//! that previously required hand-written curl invocations. Output is
//! a formatted table for `ls` and a per-id status line for `kill`.

use anyhow::{Context, Result};
use std::time::Duration;

/// `forkd ls` — list live sandboxes the daemon knows about.
pub fn ls(daemon_url: &str, token: Option<String>) -> Result<()> {
let sandboxes = list_sandboxes(daemon_url, token.as_deref())?;
if sandboxes.is_empty() {
eprintln!("no live sandboxes");
return Ok(());
}
// Column widths.
let id_w = sandboxes
.iter()
.filter_map(|s| s.get("id").and_then(|v| v.as_str()))
.map(str::len)
.max()
.unwrap_or(8)
.max(8);
let tag_w = sandboxes
.iter()
.filter_map(|s| s.get("snapshot_tag").and_then(|v| v.as_str()))
.map(str::len)
.max()
.unwrap_or(8)
.max(8);
println!(
" {:<id_w$} {:<tag_w$} {:<8} {:<14} GUEST_ADDR",
"ID",
"SNAPSHOT",
"PID",
"NETNS",
id_w = id_w,
tag_w = tag_w,
);
for s in &sandboxes {
let id = s.get("id").and_then(|v| v.as_str()).unwrap_or("?");
let tag = s
.get("snapshot_tag")
.and_then(|v| v.as_str())
.unwrap_or("?");
let pid = s
.get("pid")
.and_then(|v| v.as_u64())
.map(|p| p.to_string())
.unwrap_or_else(|| "—".to_string());
let netns = s.get("netns").and_then(|v| v.as_str()).unwrap_or("—");
let guest = s.get("guest_addr").and_then(|v| v.as_str()).unwrap_or("—");
println!(
" {:<id_w$} {:<tag_w$} {:<8} {:<14} {}",
id,
tag,
pid,
netns,
guest,
id_w = id_w,
tag_w = tag_w,
);
}
println!(
"\n {} sandbox{}",
sandboxes.len(),
if sandboxes.len() == 1 { "" } else { "es" }
);
Ok(())
}

/// `forkd kill` — terminate one or more sandboxes via DELETE.
pub fn kill(
daemon_url: &str,
token: Option<String>,
ids: Vec<String>,
all: bool,
tag: Option<String>,
) -> Result<()> {
let targets: Vec<String> = if all || tag.is_some() {
let sandboxes = list_sandboxes(daemon_url, token.as_deref())?;
sandboxes
.iter()
.filter(|s| match &tag {
Some(t) => s
.get("snapshot_tag")
.and_then(|v| v.as_str())
.map(|x| x == t)
.unwrap_or(false),
None => true,
})
.filter_map(|s| s.get("id").and_then(|v| v.as_str()).map(String::from))
.collect()
} else {
if ids.is_empty() {
anyhow::bail!("no sandbox specified; pass <ID>... or --all or --tag <TAG>");
}
ids
};

if targets.is_empty() {
eprintln!("no matching sandboxes");
return Ok(());
}

let mut errs = 0;
for id in &targets {
match delete_sandbox(daemon_url, token.as_deref(), id) {
Ok(()) => println!(" ✓ {id}"),
Err(e) => {
println!(" ✗ {id} ({e})");
errs += 1;
}
}
}
if errs > 0 {
anyhow::bail!("{errs} of {} kills failed", targets.len());
}
Ok(())
}

// ----------------------------------------------------------------------
// HTTP helpers
// ----------------------------------------------------------------------

fn list_sandboxes(daemon_url: &str, token: Option<&str>) -> Result<Vec<serde_json::Value>> {
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(10))
.build();
let url = format!("{}/v1/sandboxes", daemon_url.trim_end_matches('/'));
let mut req = agent.get(&url);
if let Some(t) = token {
req = req.set("Authorization", &format!("Bearer {t}"));
}
let resp = req.call().map_err(map_err)?;
let body = resp.into_string().context("read body")?;
let v: serde_json::Value =
serde_json::from_str(&body).with_context(|| format!("parse JSON: {body}"))?;
Ok(v.as_array().cloned().unwrap_or_default())
}

fn delete_sandbox(daemon_url: &str, token: Option<&str>, id: &str) -> Result<()> {
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(30))
.build();
let url = format!("{}/v1/sandboxes/{}", daemon_url.trim_end_matches('/'), id);
let mut req = agent.delete(&url);
if let Some(t) = token {
req = req.set("Authorization", &format!("Bearer {t}"));
}
req.call().map_err(map_err)?;
Ok(())
}

fn map_err(e: ureq::Error) -> anyhow::Error {
match e {
ureq::Error::Status(code, r) => {
let body = r.into_string().unwrap_or_default();
anyhow::anyhow!("HTTP {code}: {body}")
}
e => anyhow::anyhow!("transport: {e}"),
}
}
Loading