use clap::{Args, Parser, Subcommand};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::io::{self, BufRead, Read, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use unkernel_rs::cache::{DEFAULT_UNKERNEL_VERSION, default_cache_dir, prepare_artifacts};
use unkernel_rs::{
ApprovalDecision, AuditEvent, ExecOptions, MonitorConfig, MountSpec, NetConfig,
SwitchAttachment, VirtualSwitch, Vm, VmConfig, VmSnapshot, open_audit_file, peak_rss_mib,
terminal_approval_callback,
};
use wasmtime::{Config, Engine, Result, bail};
#[derive(Parser, Debug)]
#[command(
name = "unkernel-rs",
version,
about = "Native Rust + Wasmtime Linux sandbox powered by unkernel (zero Node, zero JSPI, zero KVM)"
)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Args, Debug, Clone)]
struct CommonVmArgs {
#[arg(long, default_value_t = 128)]
mem: u32,
#[arg(long, default_value = "alpine")]
distro: String,
#[arg(long)]
distro_file: Option<PathBuf>,
#[arg(long)]
bundle: Option<PathBuf>,
#[arg(long)]
cache_dir: Option<PathBuf>,
#[arg(long, default_value = DEFAULT_UNKERNEL_VERSION)]
unkernel_version: String,
#[arg(long)]
offline: bool,
#[arg(long)]
rebuild_cache: bool,
#[arg(long)]
no_jit: bool,
#[arg(short = 'm', long = "mount")]
mounts: Vec<String>,
#[arg(long = "disk", alias = "data")]
data_disk: Option<PathBuf>,
#[arg(long)]
disk_ro: bool,
#[arg(long)]
disk_snapshot: bool,
#[arg(long)]
net: bool,
#[arg(long = "allow-host")]
allow_hosts: Vec<String>,
#[arg(long)]
allow_lan: bool,
#[arg(short = 'p', long = "publish")]
publish: Vec<String>,
#[arg(long)]
vmi_tls: bool,
#[arg(long)]
tls_keylog: Option<PathBuf>,
#[arg(long)]
mitm_tls: bool,
#[arg(long)]
mitm_insecure_upstream: bool,
#[arg(long)]
vm_timeout_ms: Option<u64>,
#[arg(long)]
sandbox: bool,
#[arg(long)]
require_sandbox: bool,
#[arg(long)]
console: bool,
#[arg(long)]
audit: bool,
#[arg(long)]
audit_file: Option<PathBuf>,
#[arg(long)]
ask_net: bool,
#[arg(long)]
ask_fs_write: bool,
#[arg(long)]
ask_sensitive: bool,
#[arg(long)]
freeze_on_ask: bool,
}
impl CommonVmArgs {
fn to_vm_config(&self) -> Result<VmConfig> {
self.to_vm_config_with_serve_out(None, None)
}
fn to_vm_config_with_serve_out(
&self,
serve_out: Option<Arc<Mutex<io::Stdout>>>,
ready_gate: Option<Arc<AtomicBool>>,
) -> Result<VmConfig> {
let mut mounts = Vec::with_capacity(self.mounts.len());
for spec in &self.mounts {
mounts.push(MountSpec::parse(spec)?);
}
let audit_file = match &self.audit_file {
Some(path) => Some(open_audit_file(path)?),
None => None,
};
let tls_keylog_file = match &self.tls_keylog {
Some(path) => Some(open_audit_file(path)?),
None => None,
};
let vmi_tls = self.vmi_tls || tls_keylog_file.is_some();
let any_ask = self.ask_net || self.ask_fs_write || self.ask_sensitive;
let (audit_callback, approval_callback) = if let Some(out) = serve_out {
let emit_all = self.audit;
let cb = if emit_all || any_ask {
Some(Arc::new(move |ev: AuditEvent| {
if let Some(gate) = &ready_gate
&& !gate.load(Ordering::Acquire)
{
return;
}
let should_emit = emit_all
|| matches!(
ev,
AuditEvent::ApprovalRequired { .. }
| AuditEvent::ApprovalResolved { .. }
| AuditEvent::VmPaused { .. }
| AuditEvent::VmResumed { .. }
);
if should_emit && let Ok(line) = serde_json::to_string(&ev) {
let mut guard = out.lock().unwrap();
let _ = writeln!(guard, "{line}");
let _ = guard.flush();
}
}) as unkernel_rs::AuditCallback)
} else {
None
};
(cb, None)
} else {
let audit_cb = if self.audit {
Some(Arc::new(|ev: AuditEvent| {
if let Ok(line) = serde_json::to_string(&ev) {
let mut err = io::stderr().lock();
let _ = writeln!(err, "{line}");
let _ = err.flush();
}
}) as unkernel_rs::AuditCallback)
} else {
None
};
let approval_cb = if any_ask {
Some(terminal_approval_callback())
} else {
None
};
(audit_cb, approval_cb)
};
let mut port_forwards = Vec::new();
for spec in &self.publish {
port_forwards.push(
unkernel_rs::PortForward::parse(spec)
.map_err(|e| wasmtime::format_err!("{e}"))?,
);
}
Ok(VmConfig {
memory_mib: self.mem,
distro: if self.distro == "none" {
None
} else {
Some(self.distro.clone())
},
distro_file: self.distro_file.clone(),
bundle_file: self.bundle.clone(),
cache_dir: self.cache_dir.clone(),
unkernel_version: self.unkernel_version.clone(),
offline: self.offline,
rebuild_cache: self.rebuild_cache,
jit: !self.no_jit,
mounts,
data_disk: self.data_disk.clone(),
data_disk_ro: self.disk_ro,
data_disk_snapshot: self.disk_snapshot,
data_disk_snapshot_state: None,
workspace_snapshots: Vec::new(),
net: NetConfig {
enabled: self.net
|| !self.allow_hosts.is_empty()
|| !port_forwards.is_empty()
|| vmi_tls
|| self.mitm_tls
|| self.ask_net,
allow_lan: self.allow_lan,
allow_hosts: self.allow_hosts.clone(),
port_forwards,
vmi_tls,
tls_keylog_file,
mitm_tls: self.mitm_tls,
mitm_insecure_upstream: self.mitm_insecure_upstream,
},
switch: None,
monitor: MonitorConfig {
audit_callback,
audit_file,
audit_enabled: self.audit,
ask_net: self.ask_net,
ask_fs_write: self.ask_fs_write,
ask_sensitive_read: self.ask_sensitive,
freeze_on_ask: self.freeze_on_ask,
approval_callback,
},
vm_timeout: self.vm_timeout_ms.map(Duration::from_millis),
sandbox: self.sandbox,
require_sandbox: self.require_sandbox,
forward_console: self.console,
})
}
}
#[derive(Subcommand, Debug)]
enum Commands {
Fetch {
#[command(flatten)]
vm: CommonVmArgs,
},
Exec {
#[command(flatten)]
vm: CommonVmArgs,
#[arg(short = 'u', long)]
user: Option<String>,
#[arg(short = 'w', long)]
cwd: Option<String>,
#[arg(short = 'e', long = "env")]
env: Vec<String>,
#[arg(long, default_value_t = 30_000)]
timeout_ms: u64,
#[arg(long)]
stdin: bool,
#[arg(long)]
json: bool,
#[arg(long)]
show_diff: bool,
#[arg(long)]
commit_cow: bool,
#[arg(required = true, trailing_var_arg = true)]
cmd: Vec<String>,
},
Shell {
#[command(flatten)]
vm: CommonVmArgs,
#[arg(short = 'u', long)]
user: Option<String>,
#[arg(short = 'w', long)]
cwd: Option<String>,
},
Serve {
#[command(flatten)]
vm: CommonVmArgs,
},
Bench {
#[command(flatten)]
vm: CommonVmArgs,
#[arg(long)]
json: bool,
},
Lab {
#[command(flatten)]
vm: CommonVmArgs,
#[arg(long, default_value_t = 2)]
nodes: usize,
#[arg(long = "node")]
node_names: Vec<String>,
#[arg(long)]
pcap: Option<PathBuf>,
#[arg(long = "run")]
run_steps: Vec<String>,
#[arg(long)]
json: bool,
},
}
#[derive(Deserialize)]
struct ServeRequest {
#[serde(default)]
id: Option<serde_json::Value>,
#[serde(default)]
shutdown: bool,
#[serde(default)]
pause: bool,
#[serde(default)]
resume: bool,
#[serde(default)]
pending: bool,
#[serde(default)]
procs: bool,
#[serde(default)]
diff: Option<String>,
#[serde(default)]
discard: Option<String>,
#[serde(default)]
commit: Option<String>,
#[serde(default)]
snapshot: Option<String>,
#[serde(default)]
restore: Option<String>,
#[serde(default)]
approve: Option<u64>,
#[serde(default)]
decision: Option<ApprovalDecision>,
#[serde(default)]
cmd: Option<String>,
#[serde(default)]
program: Option<String>,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
cwd: Option<String>,
#[serde(default)]
user: Option<String>,
#[serde(default)]
env: BTreeMap<String, String>,
#[serde(default)]
input: Option<String>,
#[serde(default)]
timeout_ms: Option<u64>,
}
#[derive(Serialize)]
struct ServeResponse {
id: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
stdout: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stderr: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
exit_code: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
signal: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code.clamp(0, 255) as u8),
Err(e) => {
eprintln!("unkernel-rs error: {e:#}");
ExitCode::from(1)
}
}
}
fn run() -> Result<i32> {
let cli = Cli::parse();
match cli.command {
Commands::Fetch { vm } => cmd_fetch(vm),
Commands::Exec {
vm,
user,
cwd,
env,
timeout_ms,
stdin,
json,
show_diff,
commit_cow,
cmd,
} => cmd_exec(
vm, user, cwd, env, timeout_ms, stdin, json, show_diff, commit_cow, cmd,
),
Commands::Shell { vm, user, cwd } => cmd_shell(vm, user, cwd),
Commands::Serve { vm } => cmd_serve(vm),
Commands::Bench { vm, json } => cmd_bench(vm, json),
Commands::Lab {
vm,
nodes,
node_names,
pcap,
run_steps,
json,
} => cmd_lab(vm, nodes, node_names, pcap, run_steps, json),
}
}
fn cmd_fetch(args: CommonVmArgs) -> Result<i32> {
let mut wt_cfg = Config::new();
wt_cfg.wasm_threads(true);
wt_cfg.shared_memory(true);
wt_cfg.wasm_simd(true);
wt_cfg.epoch_interruption(true);
let engine = Engine::new(&wt_cfg)?;
let cache_root = args.cache_dir.clone().unwrap_or_else(default_cache_dir);
let distro = if args.distro == "none" {
None
} else {
Some(args.distro.as_str())
};
let art = prepare_artifacts(
&engine,
args.bundle.as_deref(),
distro,
args.distro_file.as_deref(),
&cache_root,
&args.unkernel_version,
args.offline,
true,
args.rebuild_cache,
)?;
println!(
"Ready ({}) in {} ms\n cache_dir: {}\n cwasm: {}\n distro: {}\n initrd: {} KiB",
if art.from_cwasm_cache {
"cached .cwasm"
} else {
"compiled & cached .cwasm"
},
art.load_ms,
art.cache_dir.display(),
art.cwasm_path.display(),
art.distro_path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "none".into()),
art.initrd.len() / 1024
);
Ok(0)
}
#[allow(clippy::too_many_arguments)]
fn cmd_exec(
vm_args: CommonVmArgs,
user: Option<String>,
cwd: Option<String>,
env_pairs: Vec<String>,
timeout_ms: u64,
read_stdin: bool,
json: bool,
show_diff: bool,
commit_cow: bool,
cmd: Vec<String>,
) -> Result<i32> {
let mut env = BTreeMap::new();
for pair in env_pairs {
let Some((k, v)) = pair.split_once('=') else {
bail!("invalid --env {pair:?} (expected KEY=VAL)");
};
env.insert(k.to_string(), v.to_string());
}
let stdin_bytes = if read_stdin {
let mut buf = Vec::new();
io::stdin().read_to_end(&mut buf)?;
Some(buf)
} else {
None
};
let cfg = vm_args.to_vm_config()?;
let vm = Vm::boot(cfg)?;
let mut exec_opts = ExecOptions::new(&cmd[0], &cmd[1..]);
exec_opts.user = user;
exec_opts.cwd = cwd;
exec_opts.env = env;
exec_opts.stdin = stdin_bytes;
exec_opts.timeout_ms = Some(timeout_ms);
let res = vm.exec(&exec_opts)?;
let timings = vm.timings();
let jit = vm.jit_stats();
let sb = vm.sandbox_status().clone();
let cow_diffs = vm.diff_all_workspaces();
let code = res
.exit_code
.unwrap_or_else(|| res.signal.map(|s| 128 + s).unwrap_or(1));
let mut committed = false;
if commit_cow && code == 0 && !cow_diffs.is_empty() {
for d in &cow_diffs {
vm.commit_workspace(&d.guest_path)?;
}
committed = true;
}
vm.shutdown();
if json {
let payload = serde_json::json!({
"stdout": res.stdout_lossy(),
"stderr": res.stderr_lossy(),
"exit_code": res.exit_code,
"signal": res.signal,
"pid": res.pid,
"timings": timings,
"jit": jit,
"workspace_diffs": cow_diffs,
"committed": committed,
"sandbox": {
"enabled": sb.enabled,
"landlock_abi": sb.landlock_abi,
"net_blocked": sb.net_blocked,
"reason": sb.reason,
}
});
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
let mut out = io::stdout().lock();
out.write_all(&res.stdout)?;
out.flush()?;
let mut err = io::stderr().lock();
err.write_all(&res.stderr)?;
if show_diff {
for d in &cow_diffs {
let status = if committed { "committed" } else { "staged" };
let _ = writeln!(
err,
"[unkernel-rs :cow {} ({})]: +{} ~{} -{}",
d.guest_path,
status,
d.created.len(),
d.modified.len(),
d.deleted.len()
);
for p in &d.created {
let _ = writeln!(err, " + {p}");
}
for p in &d.modified {
let _ = writeln!(err, " ~ {p}");
}
for p in &d.deleted {
let _ = writeln!(err, " - {p}");
}
}
}
err.flush()?;
}
Ok(code)
}
#[cfg(unix)]
struct RawModeGuard {
fd: i32,
orig: libc::termios,
active: bool,
}
#[cfg(unix)]
impl RawModeGuard {
fn enter() -> Self {
let fd = libc::STDIN_FILENO;
unsafe {
let mut orig: libc::termios = std::mem::zeroed();
if libc::isatty(fd) == 1 && libc::tcgetattr(fd, &mut orig) == 0 {
let mut raw = orig;
libc::cfmakeraw(&mut raw);
let active = libc::tcsetattr(fd, libc::TCSANOW, &raw) == 0;
return Self { fd, orig, active };
}
Self {
fd,
orig,
active: false,
}
}
}
}
#[cfg(unix)]
impl Drop for RawModeGuard {
fn drop(&mut self) {
if self.active {
unsafe {
let _ = libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig);
}
}
}
}
#[cfg(unix)]
fn terminal_size() -> (u16, u16) {
unsafe {
let mut ws: libc::winsize = std::mem::zeroed();
if libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) == 0
&& ws.ws_col > 0
&& ws.ws_row > 0
{
return (ws.ws_col, ws.ws_row);
}
}
(80, 24)
}
#[cfg(not(unix))]
fn terminal_size() -> (u16, u16) {
(80, 24)
}
fn cmd_shell(vm_args: CommonVmArgs, user: Option<String>, cwd: Option<String>) -> Result<i32> {
let cfg = vm_args.to_vm_config()?;
let vm = Vm::boot(cfg)?;
let (cols, rows) = terminal_size();
#[cfg(unix)]
let _raw = RawModeGuard::enter();
let code = vm.interactive_pty(cols, rows, user.as_deref(), cwd.as_deref(), None, &[])?;
vm.shutdown();
Ok(code)
}
fn write_json_line(out: &Arc<Mutex<io::Stdout>>, value: &impl Serialize) -> Result<()> {
let line = serde_json::to_string(value)?;
let mut guard = out.lock().unwrap();
writeln!(guard, "{line}")?;
guard.flush()?;
Ok(())
}
fn cmd_serve(vm_args: CommonVmArgs) -> Result<i32> {
let out = Arc::new(Mutex::new(io::stdout()));
let ready_gate = Arc::new(AtomicBool::new(false));
let cfg = vm_args.to_vm_config_with_serve_out(Some(out.clone()), Some(ready_gate.clone()))?;
let mut vm = Arc::new(Vm::boot(cfg)?);
let mut snapshots: HashMap<String, VmSnapshot> = HashMap::new();
let timings = vm.timings();
let sb = vm.sandbox_status().clone();
let ready = serde_json::json!({
"ready": true,
"timings": timings,
"vmi_calibrated": vm.vmi_offsets().is_some(),
"sandbox": {
"enabled": sb.enabled,
"landlock_abi": sb.landlock_abi,
"net_blocked": sb.net_blocked,
},
"monitor": {
"audit": vm_args.audit,
"ask_net": vm_args.ask_net,
"ask_fs_write": vm_args.ask_fs_write,
"ask_sensitive": vm_args.ask_sensitive,
"freeze_on_ask": vm_args.freeze_on_ask,
}
});
write_json_line(&out, &ready)?;
ready_gate.store(true, Ordering::Release);
let mut workers: Vec<std::thread::JoinHandle<()>> = Vec::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line?;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
workers.retain(|h| !h.is_finished());
let req: ServeRequest = match serde_json::from_str(trimmed) {
Ok(r) => r,
Err(e) => {
let resp = ServeResponse {
id: None,
stdout: None,
stderr: None,
exit_code: None,
signal: None,
error: Some(format!("invalid JSON: {e}")),
};
write_json_line(&out, &resp)?;
continue;
}
};
if req.shutdown {
break;
}
if req.pause {
let changed = vm.pause();
let resp = serde_json::json!({
"id": req.id,
"ok": true,
"paused": vm.is_paused(),
"changed": changed,
});
write_json_line(&out, &resp)?;
continue;
}
if req.resume {
let paused_ms = vm.resume();
let resp = serde_json::json!({
"id": req.id,
"ok": true,
"paused": vm.is_paused(),
"paused_ms": paused_ms,
});
write_json_line(&out, &resp)?;
continue;
}
if req.pending {
let pending = vm.pending_approvals();
let resp = serde_json::json!({
"id": req.id,
"ok": true,
"pending": pending,
});
write_json_line(&out, &resp)?;
continue;
}
if req.procs {
let procs = vm.active_processes();
let resp = serde_json::json!({
"id": req.id,
"ok": true,
"paused": vm.is_paused(),
"vmi_calibrated": vm.vmi_offsets().is_some(),
"procs": procs,
});
write_json_line(&out, &resp)?;
continue;
}
if let Some(guest_path) = req.diff {
let resp = if guest_path == "*" || guest_path.is_empty() {
serde_json::json!({
"id": req.id,
"ok": true,
"diffs": vm.diff_all_workspaces(),
})
} else {
match vm.workspace_diff(&guest_path) {
Ok(diff) => serde_json::json!({
"id": req.id,
"ok": true,
"diff": diff,
}),
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("{e:#}"),
}),
}
};
write_json_line(&out, &resp)?;
continue;
}
if let Some(guest_path) = req.discard {
let resp = match vm.discard_workspace(&guest_path) {
Ok(()) => serde_json::json!({
"id": req.id,
"ok": true,
"guest_path": guest_path,
}),
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("{e:#}"),
}),
};
write_json_line(&out, &resp)?;
continue;
}
if let Some(guest_path) = req.commit {
let resp = match vm.commit_workspace(&guest_path) {
Ok(diff) => serde_json::json!({
"id": req.id,
"ok": true,
"diff": diff,
}),
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("{e:#}"),
}),
};
write_json_line(&out, &resp)?;
continue;
}
if let Some(name) = req.snapshot {
let resp = match vm.snapshot() {
Ok(snap) => {
let dirty_bytes = snap.disk.as_ref().map(|d| d.dirty_bytes()).unwrap_or(0);
let workspaces = snap.workspaces.len();
snapshots.insert(name.clone(), snap);
serde_json::json!({
"id": req.id,
"ok": true,
"snapshot": name,
"dirty_disk_bytes": dirty_bytes,
"cow_workspaces": workspaces,
})
}
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("{e:#}"),
}),
};
write_json_line(&out, &resp)?;
continue;
}
if let Some(name) = req.restore {
let resp = match snapshots.get(&name).cloned() {
Some(snap) => match vm_args
.to_vm_config_with_serve_out(Some(out.clone()), Some(ready_gate.clone()))
{
Ok(mon_base) => match snap.boot_branch(None, Some(mon_base.monitor)) {
Ok(branch_vm) => {
let timings = branch_vm.timings();
let vmi_calibrated = branch_vm.vmi_offsets().is_some();
let old_vm = std::mem::replace(&mut vm, Arc::new(branch_vm));
if old_vm.is_paused() || !old_vm.pending_approvals().is_empty() {
old_vm.monitor().shutdown();
}
old_vm.shutdown();
serde_json::json!({
"id": req.id,
"ok": true,
"restored": name,
"vmi_calibrated": vmi_calibrated,
"timings": timings,
})
}
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("branch boot failed: {e:#}"),
}),
},
Err(e) => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("{e:#}"),
}),
},
None => serde_json::json!({
"id": req.id,
"ok": false,
"error": format!("unknown snapshot {name:?}"),
}),
};
write_json_line(&out, &resp)?;
continue;
}
if let Some(approval_id) = req.approve {
let Some(decision) = req.decision else {
let resp = serde_json::json!({
"id": req.id,
"ok": false,
"error": "missing 'decision' (allow_once|allow_always|deny_once|deny_always)",
});
write_json_line(&out, &resp)?;
continue;
};
let ok = vm.resolve_approval(approval_id, decision);
let resp = serde_json::json!({
"id": req.id,
"ok": ok,
"approval_id": approval_id,
"decision": decision,
"error": if ok { None } else { Some(format!("no pending approval #{approval_id}")) },
});
write_json_line(&out, &resp)?;
continue;
}
let mut opts = if let Some(prog) = req.program {
ExecOptions::new(prog, req.args)
} else if let Some(cmd) = req.cmd {
ExecOptions::shell(cmd)
} else {
let resp = ServeResponse {
id: req.id,
stdout: None,
stderr: None,
exit_code: None,
signal: None,
error: Some(
"request must include 'cmd', 'program', 'procs', 'diff', 'discard', 'commit', 'snapshot', 'restore', 'approve', 'pause', 'resume', 'pending', or 'shutdown'"
.into(),
),
};
write_json_line(&out, &resp)?;
continue;
};
opts.cwd = req.cwd;
opts.user = req.user;
opts.env = req.env;
opts.stdin = req.input.map(|s| s.into_bytes());
opts.timeout_ms = req.timeout_ms.or(Some(30_000));
let vm_w = vm.clone();
let out_w = out.clone();
let req_id = req.id;
let handle = std::thread::Builder::new()
.name("serve-exec".into())
.spawn(move || {
let resp = match vm_w.exec(&opts) {
Ok(r) => ServeResponse {
id: req_id,
stdout: Some(r.stdout_lossy()),
stderr: Some(r.stderr_lossy()),
exit_code: r.exit_code,
signal: r.signal,
error: None,
},
Err(e) => ServeResponse {
id: req_id,
stdout: None,
stderr: None,
exit_code: None,
signal: None,
error: Some(format!("{e:#}")),
},
};
let _ = write_json_line(&out_w, &resp);
})?;
workers.push(handle);
}
if vm.is_paused() || !vm.pending_approvals().is_empty() {
vm.monitor().shutdown();
}
for h in workers {
let _ = h.join();
}
vm.shutdown();
Ok(0)
}
fn cmd_bench(vm_args: CommonVmArgs, json: bool) -> Result<i32> {
let mut cfg_jit = vm_args.to_vm_config()?;
cfg_jit.jit = true;
let vm_jit = Vm::boot(cfg_jit)?;
let timings_jit = vm_jit.timings();
let mut exec_latencies_ms = Vec::new();
for _ in 0..5 {
let t = Instant::now();
let r = vm_jit.exec(&ExecOptions::new("true", Vec::<String>::new()))?;
if r.exit_code != Some(0) {
bail!("exec('true') failed");
}
exec_latencies_ms.push(t.elapsed().as_secs_f64() * 1000.0);
}
let avg_exec_ms = exec_latencies_ms.iter().sum::<f64>() / exec_latencies_ms.len() as f64;
let t_cpu_jit = Instant::now();
let r_cpu_jit = vm_jit.exec(&ExecOptions::shell("seq 50000 | sort -r | head -n 1"))?;
let cpu_jit_ms = t_cpu_jit.elapsed().as_millis() as u64;
if r_cpu_jit.exit_code != Some(0) || r_cpu_jit.stdout_lossy().trim() != "9999" {
bail!("JIT benchmark command returned unexpected output");
}
let jit_stats = vm_jit.jit_stats();
let peak_rss = peak_rss_mib();
vm_jit.shutdown();
let mut cfg_nojit = vm_args.to_vm_config()?;
cfg_nojit.jit = false;
cfg_nojit.rebuild_cache = false;
let vm_nojit = Vm::boot(cfg_nojit)?;
let t_cpu_nojit = Instant::now();
let r_cpu_nojit = vm_nojit.exec(&ExecOptions::shell("seq 50000 | sort -r | head -n 1"))?;
let cpu_nojit_ms = t_cpu_nojit.elapsed().as_millis() as u64;
if r_cpu_nojit.exit_code != Some(0) {
bail!("interpreter benchmark failed");
}
vm_nojit.shutdown();
let native_ms = if !vm_args.sandbox && !vm_args.require_sandbox {
let t_nat = Instant::now();
let ok = std::process::Command::new("sh")
.args(["-c", "seq 50000 | sort -r | head -n 1 >/dev/null"])
.status()
.map(|s| s.success())
.unwrap_or(false);
if ok {
Some(t_nat.elapsed().as_millis() as u64)
} else {
None
}
} else {
None
};
if json {
let report = serde_json::json!({
"timings": timings_jit,
"exec_true_avg_ms": avg_exec_ms,
"cpu_sort_50k_jit_ms": cpu_jit_ms,
"cpu_sort_50k_interpreter_ms": cpu_nojit_ms,
"cpu_sort_50k_native_ms": native_ms,
"jit_speedup": (cpu_nojit_ms as f64) / (cpu_jit_ms.max(1) as f64),
"jit_stats": jit_stats,
"peak_rss_mib": peak_rss,
});
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
println!(
"=== unkernel-rs Benchmark (Alpine / Linux 7.3.4+ aarch64, {} MiB) ===",
vm_args.mem
);
println!(
"Module load ({}): {} ms",
if timings_jit.from_cwasm_cache {
"cached .cwasm"
} else {
"Cranelift AOT"
},
timings_jit.module_load_ms
);
println!(
"Boot -> first exec('true'): {} ms (total {} ms)",
timings_jit.ready_ms, timings_jit.total_boot_ms
);
println!("exec('true') avg latency: {avg_exec_ms:.2} ms (5 runs)");
println!(
"seq 50000 | sort -r (JIT ON): {} ms ({} blocks, {:.1} ms compile, {} KiB wasm)",
cpu_jit_ms,
jit_stats.compiled,
jit_stats.compile_ms,
jit_stats.bytes / 1024
);
println!("seq 50000 | sort -r (JIT OFF): {} ms", cpu_nojit_ms);
println!(
"Cranelift JIT speedup: {:.2}x",
(cpu_nojit_ms as f64) / (cpu_jit_ms.max(1) as f64)
);
if let Some(n) = native_ms {
println!("Native host baseline: {n} ms");
}
println!("Peak host RSS (VmHWM): {peak_rss:.1} MiB");
}
Ok(0)
}
#[derive(Deserialize)]
struct LabJsonCmd {
op: String,
#[serde(default)]
node: Option<String>,
#[serde(default)]
cmd: Option<String>,
#[serde(default)]
pct: Option<u8>,
#[serde(default)]
ms: Option<u64>,
#[serde(default)]
user: Option<String>,
#[serde(default)]
timeout_ms: Option<u64>,
}
fn cmd_lab(
vm_args: CommonVmArgs,
nodes_count: usize,
node_names: Vec<String>,
pcap_path: Option<PathBuf>,
run_steps: Vec<String>,
json_mode: bool,
) -> Result<i32> {
let names: Vec<String> = if !node_names.is_empty() {
node_names
} else {
let n = nodes_count.clamp(1, 32);
(1..=n).map(|i| format!("node{i}")).collect()
};
if names.len() > 32 {
bail!(
"lab supports at most 32 nodes per switch (requested {})",
names.len()
);
}
let mut seen = std::collections::HashSet::new();
for name in &names {
if name.trim().is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
bail!("invalid lab node name {name:?} (allowed: a-z, A-Z, 0-9, -, _)");
}
if !seen.insert(name.clone()) {
bail!("duplicate lab node name {name:?}");
}
}
let switch = VirtualSwitch::new("switch0");
if let Some(p) = &pcap_path {
if let Some(parent) = p.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)?;
}
let file = std::fs::File::create(p)?;
switch.attach_pcap(file)?;
}
let base_cfg = vm_args.to_vm_config()?;
{
let mut wt_cfg = Config::new();
wt_cfg.wasm_threads(true);
wt_cfg.shared_memory(true);
wt_cfg.wasm_simd(true);
wt_cfg.epoch_interruption(true);
let engine = Engine::new(&wt_cfg)?;
let cache_root = base_cfg.cache_dir.clone().unwrap_or_else(default_cache_dir);
let _ = prepare_artifacts(
&engine,
base_cfg.bundle_file.as_deref(),
base_cfg.distro.as_deref(),
base_cfg.distro_file.as_deref(),
&cache_root,
&base_cfg.unkernel_version,
base_cfg.offline,
base_cfg.rebuild_cache,
json_mode,
)?;
}
let mut identities: Vec<(String, [u8; 6], [u8; 4])> = Vec::with_capacity(names.len());
let mut hosts_entries = String::from("127.0.0.1 localhost\n10.0.2.2 gateway\n");
for (idx, name) in names.iter().enumerate() {
let (mac, ip) = VirtualSwitch::allocate_identity(idx);
identities.push((name.clone(), mac, ip));
hosts_entries.push_str(&format!(
"{}.{}.{}.{} {}\n",
ip[0], ip[1], ip[2], ip[3], name
));
}
let t_lab = Instant::now();
let mut handles = Vec::with_capacity(identities.len());
for (name, mac, ip) in &identities {
let mut cfg = base_cfg.clone();
cfg.rebuild_cache = false;
cfg.offline = true; cfg.switch = Some(SwitchAttachment {
switch: switch.clone(),
node_name: name.clone(),
mac: *mac,
ip: *ip,
});
let node_name = name.clone();
let node_ip = *ip;
let hosts = hosts_entries.clone();
let has_uplink = cfg.net.enabled;
handles.push(std::thread::spawn(move || -> Result<(String, Vm)> {
let vm = Vm::boot(cfg)?;
let ip_str = format!(
"{}.{}.{}.{}",
node_ip[0], node_ip[1], node_ip[2], node_ip[3]
);
let route_cmd = if has_uplink {
"ip route replace default via 10.0.2.2 dev eth0 2>/dev/null || true; printf 'nameserver 10.0.2.3\\n' > /etc/resolv.conf"
} else {
"true"
};
let setup_script = format!(
"hostname {node_name} 2>/dev/null || true; \
ip link set lo up 2>/dev/null || true; \
ip link set eth0 up 2>/dev/null || true; \
ip addr flush dev eth0 2>/dev/null || true; \
ip addr add {ip_str}/24 dev eth0 2>/dev/null || true; \
{route_cmd}; \
cat > /etc/hosts"
);
let mut opts = ExecOptions::shell(setup_script);
opts.user = Some("root".to_string());
opts.stdin = Some(hosts.into_bytes());
opts.timeout_ms = Some(10_000);
let _ = vm.exec(&opts)?;
Ok((node_name, vm))
}));
}
let mut vms: BTreeMap<String, Vm> = BTreeMap::new();
for h in handles {
let (name, vm) = h
.join()
.map_err(|_| wasmtime::format_err!("lab boot thread panicked"))??;
vms.insert(name, vm);
}
let boot_ms = t_lab.elapsed().as_millis() as u64;
if json_mode {
println!(
"{}",
serde_json::to_string(&serde_json::json!({
"event": "lab_ready",
"switch": switch.name(),
"boot_ms": boot_ms,
"pcap": pcap_path.as_ref().map(|p| p.display().to_string()),
"ports": switch.port_stats(),
}))?
);
} else {
eprintln!(
"[unkernel-rs lab] switch0 ready ({} nodes booted in {} ms{})",
vms.len(),
boot_ms,
pcap_path
.as_ref()
.map(|p| format!(", pcap={}", p.display()))
.unwrap_or_default()
);
for st in switch.port_stats() {
eprintln!(
" port {}: {:<12} {:<12} mac={} link={} uplink={}",
st.port_id,
st.node,
st.ip,
st.mac,
if st.link_up { "up" } else { "cut" },
if st.has_uplink { "nat" } else { "airgap" }
);
}
}
let mut final_exit = 0i32;
if !run_steps.is_empty() {
for step in &run_steps {
let code = execute_lab_step(&vms, &switch, step, json_mode)?;
if code != 0 {
final_exit = code;
}
}
} else {
if !json_mode {
eprintln!(
"[unkernel-rs lab] commands: exec <node> <cmd> | cut <node> | reconnect <node> | drop <node> <pct> | delay <node> <ms> | stats | macs | quit (or JSON lines)"
);
}
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line?;
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if trimmed == "quit" || trimmed == "exit" {
break;
}
if trimmed.starts_with('{') {
let req: LabJsonCmd = match serde_json::from_str(trimmed) {
Ok(r) => r,
Err(e) => {
println!(
"{}",
serde_json::to_string(&serde_json::json!({"error": e.to_string()}))?
);
continue;
}
};
if req.op == "quit" || req.op == "shutdown" {
println!(
"{}",
serde_json::to_string(&serde_json::json!({"ok": true, "op": "shutdown"}))?
);
break;
}
handle_lab_json_cmd(&vms, &switch, req)?;
} else {
let _ = execute_lab_repl_line(&vms, &switch, trimmed, json_mode)?;
}
}
}
switch.flush_pcap();
for (_, vm) in vms {
vm.shutdown();
}
Ok(final_exit)
}
fn execute_lab_step(
vms: &BTreeMap<String, Vm>,
switch: &Arc<VirtualSwitch>,
step: &str,
json_mode: bool,
) -> Result<i32> {
if step == "stats" || step == "topology" {
print_lab_stats(switch, json_mode)?;
return Ok(0);
}
if step == "macs" {
print_lab_macs(switch, json_mode)?;
return Ok(0);
}
if let Some(node) = step.strip_prefix("cut:") {
let ok = switch.cut_link(node.trim());
print_lab_action("cut", node.trim(), ok, json_mode)?;
return Ok(if ok { 0 } else { 1 });
}
if let Some(node) = step.strip_prefix("reconnect:") {
let ok = switch.reconnect_link(node.trim());
print_lab_action("reconnect", node.trim(), ok, json_mode)?;
return Ok(if ok { 0 } else { 1 });
}
if let Some(rest) = step.strip_prefix("drop:")
&& let Some((node, pct_s)) = rest.split_once(':')
{
let pct: u8 = pct_s.trim().parse().unwrap_or(0);
let ok = switch.set_drop_rate(node.trim(), pct);
print_lab_action("drop", node.trim(), ok, json_mode)?;
return Ok(if ok { 0 } else { 1 });
}
if let Some(rest) = step.strip_prefix("delay:")
&& let Some((node, ms_s)) = rest.split_once(':')
{
let ms: u64 = ms_s.trim().parse().unwrap_or(0);
let ok = switch.set_delay_ms(node.trim(), ms);
print_lab_action("delay", node.trim(), ok, json_mode)?;
return Ok(if ok { 0 } else { 1 });
}
let Some((node, cmd)) = step.split_once(':') else {
bail!(
"invalid --run step {step:?} (expected `node:cmd`, `cut:node`, `reconnect:node`, `drop:node:pct`, `delay:node:ms`, `stats`, or `macs`)"
);
};
run_lab_exec(vms, node.trim(), cmd.trim(), None, None, json_mode)
}
fn execute_lab_repl_line(
vms: &BTreeMap<String, Vm>,
switch: &Arc<VirtualSwitch>,
line: &str,
json_mode: bool,
) -> Result<i32> {
let mut parts = line.splitn(3, char::is_whitespace);
let op = parts.next().unwrap_or("");
let arg1 = parts.next().unwrap_or("").trim();
let arg2 = parts.next().unwrap_or("").trim();
match op {
"exec" => {
if arg1.is_empty() || arg2.is_empty() {
eprintln!("usage: exec <node> <shell command>");
return Ok(1);
}
run_lab_exec(vms, arg1, arg2, None, None, json_mode)
}
"cut" => {
let ok = switch.cut_link(arg1);
print_lab_action("cut", arg1, ok, json_mode)?;
Ok(if ok { 0 } else { 1 })
}
"reconnect" => {
let ok = switch.reconnect_link(arg1);
print_lab_action("reconnect", arg1, ok, json_mode)?;
Ok(if ok { 0 } else { 1 })
}
"drop" => {
let pct: u8 = arg2.parse().unwrap_or(0);
let ok = switch.set_drop_rate(arg1, pct);
print_lab_action("drop", arg1, ok, json_mode)?;
Ok(if ok { 0 } else { 1 })
}
"delay" => {
let ms: u64 = arg2.parse().unwrap_or(0);
let ok = switch.set_delay_ms(arg1, ms);
print_lab_action("delay", arg1, ok, json_mode)?;
Ok(if ok { 0 } else { 1 })
}
"stats" | "topology" | "ls" => {
print_lab_stats(switch, json_mode)?;
Ok(0)
}
"macs" => {
print_lab_macs(switch, json_mode)?;
Ok(0)
}
_ => {
eprintln!(
"unknown lab command {op:?} (try: exec, cut, reconnect, drop, delay, stats, macs, quit)"
);
Ok(1)
}
}
}
fn handle_lab_json_cmd(
vms: &BTreeMap<String, Vm>,
switch: &Arc<VirtualSwitch>,
req: LabJsonCmd,
) -> Result<()> {
match req.op.as_str() {
"exec" => {
let node = req.node.as_deref().unwrap_or("");
let cmd = req.cmd.as_deref().unwrap_or("");
let _ = run_lab_exec(vms, node, cmd, req.user, req.timeout_ms, true)?;
}
"cut" => {
let node = req.node.as_deref().unwrap_or("");
let ok = switch.cut_link(node);
print_lab_action("cut", node, ok, true)?;
}
"reconnect" => {
let node = req.node.as_deref().unwrap_or("");
let ok = switch.reconnect_link(node);
print_lab_action("reconnect", node, ok, true)?;
}
"drop" => {
let node = req.node.as_deref().unwrap_or("");
let ok = switch.set_drop_rate(node, req.pct.unwrap_or(0));
print_lab_action("drop", node, ok, true)?;
}
"delay" => {
let node = req.node.as_deref().unwrap_or("");
let ok = switch.set_delay_ms(node, req.ms.unwrap_or(0));
print_lab_action("delay", node, ok, true)?;
}
"stats" | "topology" => print_lab_stats(switch, true)?,
"macs" => print_lab_macs(switch, true)?,
other => {
println!(
"{}",
serde_json::to_string(
&serde_json::json!({"error": format!("unknown op {other:?}")})
)?
);
}
}
Ok(())
}
fn run_lab_exec(
vms: &BTreeMap<String, Vm>,
node: &str,
cmd: &str,
user: Option<String>,
timeout_ms: Option<u64>,
json_mode: bool,
) -> Result<i32> {
let Some(vm) = vms.get(node) else {
if json_mode {
println!(
"{}",
serde_json::to_string(
&serde_json::json!({"error": format!("unknown node {node:?}")})
)?
);
} else {
eprintln!("unknown node {node:?}");
}
return Ok(1);
};
let mut opts = ExecOptions::shell(cmd);
opts.user = user.or_else(|| Some("root".to_string()));
opts.timeout_ms = timeout_ms.or(Some(30_000));
let res = vm.exec(&opts)?;
let stdout = String::from_utf8_lossy(&res.stdout).to_string();
let stderr = String::from_utf8_lossy(&res.stderr).to_string();
if json_mode {
println!(
"{}",
serde_json::to_string(&serde_json::json!({
"op": "exec",
"node": node,
"exit_code": res.exit_code,
"stdout": stdout,
"stderr": stderr,
}))?
);
} else {
if !stdout.is_empty() {
print!("[{node}] {stdout}");
if !stdout.ends_with('\n') {
println!();
}
}
if !stderr.is_empty() {
eprint!("[{node} stderr] {stderr}");
if !stderr.ends_with('\n') {
eprintln!();
}
}
}
Ok(res.exit_code.unwrap_or(1))
}
fn print_lab_action(op: &str, node: &str, ok: bool, json_mode: bool) -> Result<()> {
if json_mode {
println!(
"{}",
serde_json::to_string(&serde_json::json!({"op": op, "node": node, "ok": ok}))?
);
} else if ok {
println!("[switch0] {op} {node}: ok");
} else {
eprintln!("[switch0] {op} {node}: unknown node");
}
Ok(())
}
fn print_lab_stats(switch: &Arc<VirtualSwitch>, json_mode: bool) -> Result<()> {
let stats = switch.port_stats();
if json_mode {
println!(
"{}",
serde_json::to_string(&serde_json::json!({
"op": "stats",
"switch": switch.name(),
"total_frames": switch.total_frames(),
"ports": stats,
}))?
);
} else {
println!(
"=== {} ({} frames switched) ===",
switch.name(),
switch.total_frames()
);
for s in stats {
println!(
" port {}: {:<10} {:<11} mac={} link={} drop={}% delay={}ms tx={} rx={} dropped={}",
s.port_id,
s.node,
s.ip,
s.mac,
if s.link_up { "up" } else { "cut" },
s.drop_pct,
s.delay_ms,
s.tx_frames,
s.rx_frames,
s.dropped_frames
);
}
}
Ok(())
}
fn print_lab_macs(switch: &Arc<VirtualSwitch>, json_mode: bool) -> Result<()> {
let macs = switch.mac_table();
if json_mode {
println!(
"{}",
serde_json::to_string(&serde_json::json!({
"op": "macs",
"switch": switch.name(),
"entries": macs,
}))?
);
} else {
println!(
"=== {} MAC table ({} entries) ===",
switch.name(),
macs.len()
);
for m in macs {
println!(" {} -> port {} ({})", m.mac, m.port_id, m.node);
}
}
Ok(())
}