feat: support a better ps command

This commit is contained in:
2026-10-21 18:10:56 +02:00
parent bc7512a373
commit 230927d8db
6 changed files with 203 additions and 31 deletions
Generated
+1 -1
View File
@@ -854,7 +854,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]] [[package]]
name = "wsbx" name = "wsbx"
version = "0.1.2" version = "0.1.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "wsbx" name = "wsbx"
version = "0.1.2" version = "0.1.3"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
+2 -1
View File
@@ -16,7 +16,8 @@ wsbx run -p 8000 alpine # host's localhost:8000 reachable as localh
wsbx exec NAME # shell in a running sandbox (alias: sh), as the image's user wsbx exec NAME # shell in a running sandbox (alias: sh), as the image's user
wsbx exec -u root NAME -- apk add git # command, exit code propagated wsbx exec -u root NAME -- apk add git # command, exit code propagated
wsbx forward NAME 3000 8080:80 # sandbox's localhost:3000 on the Mac's localhost:3000 (until Ctrl-C; alias fwd) wsbx forward NAME 3000 8080:80 # sandbox's localhost:3000 on the Mac's localhost:3000 (until Ctrl-C; alias fwd)
wsbx ps # sandboxes: running/stopped, image, disk use, workspace (alias: ls) wsbx ps # sandboxes: status, CPU, memory, net/block I/O, PIDs, disk, image (alias: ls)
wsbx ps -f # same, refreshed every second like `docker stats`
wsbx rm NAME... # delete stopped sandboxes; --disk deletes only the disk (fresh on next start) wsbx rm NAME... # delete stopped sandboxes; --disk deletes only the disk (fresh on next start)
wsbx pull IMAGE wsbx pull IMAGE
wsbx gc # delete cached images no sandbox uses wsbx gc # delete cached images no sandbox uses
+24 -6
View File
@@ -76,7 +76,7 @@ pub fn exec(h: &Path, name: &str, user: Option<String>, argv: Vec<String>) -> Re
} }
}); });
} }
let code = output(s); let code = output(s, &mut io::stdout().lock(), &mut io::stderr().lock());
if let Some(s) = saved { if let Some(s) = saved {
stty(&[s.trim()]); stty(&[s.trim()]);
} }
@@ -90,10 +90,28 @@ fn send(w: &Mutex<UnixStream>, kind: u8, p: &[u8]) -> io::Result<()> {
w.lock().unwrap().write_all(&frame(kind, p)) w.lock().unwrap().write_all(&frame(kind, p))
} }
/// Copy guest output frames to stdout/stderr until the exit status arrives (None: connection closed first). /// Run a command as root in a running sandbox (no tty, empty stdin) and return its stdout, at most 64 KiB.
fn output(s: UnixStream) -> io::Result<Option<i32>> { pub fn capture(sock: &Path, argv: &[&str]) -> Result<String> {
let mut s = UnixStream::connect(sock)?;
s.set_read_timeout(Some(Duration::from_secs(2)))?;
// uid 0, not "root": works even if the image has no /etc/passwd
s.write_all(format!("{}\n", json!({"argv": argv, "user": "0", "tty": false})).as_bytes())?;
s.write_all(&frame(b'e', &[]))?;
const CAP: usize = 64 << 10;
let mut buf = vec![0u8; CAP];
let mut w = &mut buf[..]; // a slice writer errors once full: the guest can't make us buffer more
match output(s, &mut w, &mut io::sink())? {
Some(0) => {
let n = CAP - w.len();
Ok(String::from_utf8_lossy(&buf[..n]).into_owned())
}
c => bail!("guest command failed ({c:?})"),
}
}
/// Copy guest output frames to out/err until the exit status arrives (None: connection closed first).
fn output(s: UnixStream, out: &mut impl Write, err: &mut impl Write) -> io::Result<Option<i32>> {
let mut r = io::BufReader::new(s); let mut r = io::BufReader::new(s);
let (mut out, mut err) = (io::stdout().lock(), io::stderr().lock());
loop { loop {
let mut h = [0u8; 5]; let mut h = [0u8; 5];
if r.read_exact(&mut h).is_err() { if r.read_exact(&mut h).is_err() {
@@ -102,11 +120,11 @@ fn output(s: UnixStream) -> io::Result<Option<i32>> {
let mut p = (&mut r).take(u32::from_be_bytes([h[1], h[2], h[3], h[4]]).into()); let mut p = (&mut r).take(u32::from_be_bytes([h[1], h[2], h[3], h[4]]).into());
match h[0] { match h[0] {
b'o' => { b'o' => {
io::copy(&mut p, &mut out)?; io::copy(&mut p, out)?;
out.flush()?; out.flush()?;
} }
b'r' => { b'r' => {
io::copy(&mut p, &mut err)?; io::copy(&mut p, err)?;
} }
b'x' => { b'x' => {
let mut c = [0u8; 4]; let mut c = [0u8; 4];
+7 -3
View File
@@ -81,9 +81,13 @@ enum Cmd {
#[arg(required = true)] #[arg(required = true)]
ports: Vec<String>, ports: Vec<String>,
}, },
/// List sandboxes and whether they're running /// List sandboxes with live stats (CPU, memory, network, block I/O, processes)
#[command(visible_alias = "ps")] #[command(visible_alias = "ps")]
Ls, Ls {
/// Keep refreshing every second, like `docker stats` (Ctrl-C to stop)
#[arg(short, long)]
follow: bool,
},
/// Remove stopped sandboxes /// Remove stopped sandboxes
Rm { Rm {
#[arg(required = true)] #[arg(required = true)]
@@ -168,7 +172,7 @@ fn main() -> Result<()> {
Cmd::Pi { a, pi_auth } => agents::pi(&h, a, pi_auth), Cmd::Pi { a, pi_auth } => agents::pi(&h, a, pi_auth),
Cmd::Exec { name, user, cmd } => exec::exec(&h, &name, user, cmd), Cmd::Exec { name, user, cmd } => exec::exec(&h, &name, user, cmd),
Cmd::Forward { name, ports } => forward::forward(&h, &name, ports), Cmd::Forward { name, ports } => forward::forward(&h, &name, ports),
Cmd::Ls => sandbox::ls(&h), Cmd::Ls { follow } => sandbox::ls(&h, follow),
Cmd::Gc => sandbox::gc(&h), Cmd::Gc => sandbox::gc(&h),
Cmd::Rm { names, disk } => sandbox::rm(&h, names, disk), Cmd::Rm { names, disk } => sandbox::rm(&h, names, disk),
Cmd::Version => Ok(println!("wsbx {}", env!("CARGO_PKG_VERSION"))), Cmd::Version => Ok(println!("wsbx {}", env!("CARGO_PKG_VERSION"))),
+168 -19
View File
@@ -1,11 +1,15 @@
//! Sandbox bookkeeping: listing, removal, image gc. //! Sandbox bookkeeping: listing, removal, image gc.
use crate::exec;
use crate::oci; use crate::oci;
use crate::util::sanitize; use crate::util::sanitize;
use anyhow::{Context, Result, anyhow, bail}; use anyhow::{Context, Result, anyhow, bail};
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap;
use std::fs; use std::fs;
use std::io::Write;
use std::os::unix::fs::MetadataExt; use std::os::unix::fs::MetadataExt;
use std::path::Path; use std::path::{Path, PathBuf};
use std::time::Duration;
/// The lock `run` holds for the VM's lifetime; Err if the sandbox is running. /// The lock `run` holds for the VM's lifetime; Err if the sandbox is running.
pub fn lock_stopped(dir: &Path) -> Result<fs::File> { pub fn lock_stopped(dir: &Path) -> Result<fs::File> {
@@ -14,26 +18,156 @@ pub fn lock_stopped(dir: &Path) -> Result<fs::File> {
Ok(f) Ok(f)
} }
pub fn ls(h: &Path) -> Result<()> { /// Guest counters, read from /proc through the exec channel.
println!("{:<28} {:<8} {:<40} {:>8} WORKSPACE", "NAME", "STATUS", "IMAGE", "DISK"); #[derive(Default, Debug, PartialEq)]
let Ok(rd) = fs::read_dir(h.join("sandboxes")) else { return Ok(()) }; struct Stats {
let mut rows: Vec<_> = rd.flatten().collect(); busy: u64,
rows.sort_by_key(|e| e.file_name()); total: u64,
for e in rows { ncpu: u64,
mem_used: u64,
mem_total: u64,
rx: u64,
tx: u64,
rd: u64,
wr: u64,
pids: u64,
}
const STATS_SH: &str = "cd /proc; B=/.wsbx/busybox; $B grep ^cpu stat; $B grep -E '^Mem(Total|Available):' meminfo; \
$B tail -n +3 net/dev; $B grep ' vda ' diskstats; set -- [0-9]*; echo pids $#";
fn parse(out: &str) -> Stats {
let (mut s, mut avail) = (Stats::default(), 0);
for l in out.lines() {
let f: Vec<&str> = l.split_whitespace().collect();
let num = |i: usize| f.get(i).and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
match f.first().copied() {
Some("cpu") => {
let v: Vec<u64> = (1..=8).map(num).collect(); // user nice system idle iowait irq softirq steal
s.total = v.iter().sum();
s.busy = s.total.saturating_sub(v[3] + v[4]);
}
Some(c) if c.starts_with("cpu") => s.ncpu += 1,
Some("MemTotal:") => s.mem_total = num(1) * 1024,
Some("MemAvailable:") => avail = num(1) * 1024,
Some("pids") => s.pids = num(1),
_ if f.get(2) == Some(&"vda") => (s.rd, s.wr) = (num(5) * 512, num(9) * 512),
_ => {
// net/dev: " eth0:123 ..." (no space once rx bytes outgrow the column)
if let Some((ifc, rest)) = l.split_once(':')
&& ifc.trim() != "lo"
{
let n: Vec<u64> = rest.split_whitespace().filter_map(|v| v.parse().ok()).collect();
s.rx += n.first().copied().unwrap_or(0);
s.tx += n.get(8).copied().unwrap_or(0);
}
}
}
}
s.mem_used = s.mem_total.saturating_sub(avail);
s
}
fn human(b: u64) -> String {
let (mut v, mut u) = (b as f64, 0);
while v >= 1024.0 && u < 4 {
v /= 1024.0;
u += 1;
}
if u == 0 { format!("{b}B") } else { format!("{v:.1}{}", ["", "KiB", "MiB", "GiB", "TiB"][u]) }
}
struct Row {
name: String,
dir: PathBuf,
meta: Value,
running: bool,
}
fn rows(h: &Path) -> Result<Vec<Row>> {
let Ok(rd) = fs::read_dir(h.join("sandboxes")) else { return Ok(vec![]) };
let mut rows = vec![];
for e in rd.flatten() {
let Ok(m) = fs::read(e.path().join("meta.json")) else { continue }; let Ok(m) = fs::read(e.path().join("meta.json")) else { continue };
let m: Value = serde_json::from_slice(&m)?; let running = lock_stopped(&e.path()).is_err();
let used = fs::metadata(e.path().join("disk.img")).map(|m| m.blocks() * 512).unwrap_or(0); rows.push(Row { name: e.file_name().to_string_lossy().into(), dir: e.path(), meta: serde_json::from_slice(&m)?, running });
let status = if lock_stopped(&e.path()).is_err() { "running" } else { "stopped" }; }
println!( rows.sort_by(|a, b| a.name.cmp(&b.name));
"{:<28} {:<8} {:<40} {:>6}MB {}", Ok(rows)
e.file_name().to_string_lossy(), }
status,
m["image"].as_str().unwrap_or("?"), /// Stats of all running sandboxes, sampled in parallel; sandboxes that don't answer are left out.
used / 1_000_000, fn sample(rows: &[Row]) -> HashMap<String, Stats> {
m["workspace"].as_str().unwrap_or("-") std::thread::scope(|sc| {
); let hs: Vec<_> = rows
.iter()
.filter(|r| r.running)
.map(|r| (r.name.clone(), sc.spawn(|| exec::capture(&r.dir.join("exec.sock"), &["/.wsbx/busybox", "sh", "-c", STATS_SH]))))
.collect();
hs.into_iter().filter_map(|(n, j)| Some((n, parse(&j.join().ok()?.ok()?)))).collect()
})
}
fn table(rows: &[Row], prev: &HashMap<String, Stats>, cur: &HashMap<String, Stats>) -> Vec<[String; 11]> {
let head = ["NAME", "STATUS", "CPU %", "MEM USAGE / LIMIT", "MEM %", "NET I/O", "BLOCK I/O", "PIDS", "DISK", "IMAGE", "WORKSPACE"];
let mut t = vec![head.map(String::from)];
for r in rows {
let pct = |a: u64, b: u64| format!("{:.1}%", a as f64 * 100.0 / b.max(1) as f64);
let st = cur.get(&r.name).map(|c| {
// like docker: 100% = one vCPU busy
let cpu = prev.get(&r.name).filter(|p| c.total > p.total).map(|p| pct(c.busy.saturating_sub(p.busy) * c.ncpu.max(1), c.total - p.total));
[
cpu.unwrap_or("-".into()),
format!("{} / {}", human(c.mem_used), human(c.mem_total)),
pct(c.mem_used, c.mem_total),
format!("{} / {}", human(c.rx), human(c.tx)),
format!("{} / {}", human(c.rd), human(c.wr)),
c.pids.to_string(),
]
});
let [cpu, mem, memp, net, blk, pids] = st.unwrap_or_else(|| std::array::from_fn(|_| "-".into()));
let disk = fs::metadata(r.dir.join("disk.img")).map(|m| m.blocks() * 512).unwrap_or(0);
let s = |k: &str| r.meta[k].as_str().unwrap_or("-").to_string();
let status = if r.running { "running" } else { "stopped" };
t.push([r.name.clone(), status.into(), cpu, mem, memp, net, blk, pids, human(disk), s("image"), s("workspace")]);
}
t
}
/// `wsbx ps`; with `follow`, redraws every second like `docker stats` until Ctrl-C.
pub fn ls(h: &Path, follow: bool) -> Result<()> {
let mut prev = HashMap::new();
let mut first = true;
loop {
let rows = rows(h)?;
let cur = sample(&rows);
if first && !cur.is_empty() {
// CPU % needs two samples
(prev, first) = (cur, false);
std::thread::sleep(Duration::from_millis(500));
continue;
}
let t = table(&rows, &prev, &cur);
let w: Vec<usize> = (0..11).map(|i| t.iter().map(|r| r[i].chars().count()).max().unwrap_or(0)).collect();
let mut out = String::new();
for r in &t {
let line: String = r
.iter()
.enumerate()
.map(|(i, c)| if (2..9).contains(&i) { format!("{c:>w$} ", w = w[i]) } else { format!("{c:<w$} ", w = w[i]) })
.collect();
out += line.trim_end();
out += if follow { "\x1b[K\n" } else { "\n" };
}
if !follow {
print!("{out}");
return Ok(());
}
print!("\x1b[H{out}\x1b[J"); // home, overwrite, clear the rest: no flicker
std::io::stdout().flush()?;
(prev, first) = (cur, false);
std::thread::sleep(Duration::from_secs(1));
} }
Ok(())
} }
pub fn rm(h: &Path, names: Vec<String>, disk: bool) -> Result<()> { pub fn rm(h: &Path, names: Vec<String>, disk: bool) -> Result<()> {
@@ -60,6 +194,21 @@ pub fn rm(h: &Path, names: Vec<String>, disk: bool) -> Result<()> {
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
#[test]
fn parse_proc() {
let out = "cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3\ncpu1 1 2 3\nMemTotal: 2000 kB\nMemAvailable: 500 kB\n\
\x20 lo: 999 0 0 0 0 0 0 0 999 0\n eth0:123456789 1 0 0 0 0 0 0 42 1 0 0 0 0 0 0\n\
\x20254 0 vda 10 0 4 0 7 0 8 0 0 0 0\npids 17\n";
let s = super::parse(out);
assert_eq!((s.total, s.busy, s.ncpu), (1000, 150, 2));
assert_eq!((s.mem_total, s.mem_used), (2000 * 1024, 1500 * 1024));
assert_eq!((s.rx, s.tx, s.rd, s.wr, s.pids), (123456789, 42, 2048, 4096, 17));
assert_eq!(super::human(1536), "1.5KiB");
}
}
/// Delete cached images no sandbox was created from. /// Delete cached images no sandbox was created from.
pub fn gc(h: &Path) -> Result<()> { pub fn gc(h: &Path) -> Result<()> {
let used: Vec<String> = fs::read_dir(h.join("sandboxes")) let used: Vec<String> = fs::read_dir(h.join("sandboxes"))