Release 0.2.3 polish: VM disk reclaim overhead, uniform Pod logs, Mac menu & Linux speed (#776)

Fixes macOS VM disk reclaim accounting for ext4 static metadata overhead, shares the numbered log console component with Kubernetes Pod logs, strips native AppKit WKWebView menus on macOS, optimizes Linux container creation/startup hot paths, and adds the head-to-head Kiri vs Docker Linux benchmark workflow (Closes #776).
This commit is contained in:
Precious Okwu authored and Precious Okwu committed 2026-11-26 01:40:04 +01:00
1 parent f9e23e9b94
commit 1c083755ee
16 files changed
+1160 -195

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# Head-to-head Linux benchmark comparing Kiri Engine against Docker Engine
# (`dockerd`) on the same runner (#776): ephemeral alpine lifecycle, multi-layer
# PHP app cold start & warm restart, container exec, 1,000-file bind-mount I/O,
# published-port HTTP latency, teardown, and engine RSS.
name: Linux Benchmark
on:
release:
types: [published]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: linux-benchmark-${{ github.ref }}
cancel-in-progress: false
jobs:
linux-benchmark:
name: Kiri vs Docker (Linux)
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build static Linux engine
run: |
mkdir -p "$RUNNER_TEMP/bin"
docker run --rm -v "$PWD:/src" -v "$RUNNER_TEMP/bin:/out" \
-w /src -e CARGO_TARGET_DIR=/tmp/target rust:1-alpine sh -c \
'apk add -q musl-dev && cargo build --release --locked -p kiri -p kiri-init && cp /tmp/target/release/kiri /tmp/target/release/kiri-init /out/'
- name: Run head-to-head Kiri vs Docker benchmark
env:
VERSION: ${{ github.event.release.tag_name || github.sha }}
run: |
set -eu
WORK="$RUNNER_TEMP/vs-docker"
mkdir -p "$WORK/data" "$WORK/run"
sudo env KIRI_DATA_DIR="$WORK/data" \
KIRI_SOCKET="$WORK/run/docker.sock" KIRI_HTTP_PORT=18080 KIRI_HTTPS_PORT=18443 \
"$RUNNER_TEMP/bin/kiri" daemon >"$WORK/daemon.log" 2>&1 &
KIRI_PID=$!
trap 'sudo kill -TERM $KIRI_PID 2>/dev/null || true' EXIT
for _ in $(seq 1 100); do
[ -S "$WORK/run/docker.sock" ] && break
sleep 0.2
done
sudo python3 scripts/bench-linux-docker.py \
--docker-sock /var/run/docker.sock \
--kiri-sock "$WORK/run/docker.sock" \
--kiri-pid "$KIRI_PID" \
--version "${VERSION}" \
--out "$WORK/benchmark.json" \
--report "$WORK/report.md"
cat "$WORK/report.md" >> "$GITHUB_STEP_SUMMARY"
- name: Upload benchmark results
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: linux-benchmark-results
path: ${{ runner.temp }}/vs-docker/benchmark.json
+6
View File
@@ -55,12 +55,18 @@ type FileStamp = Option<(u64, u64, i64, i64)>;
#[derive(Default)]
struct HostDns {
stamp: Option<[FileStamp; 2]>,
checked_at: Option<std::time::Instant>,
servers: Vec<[u8; 4]>,
}
impl HostDns {
fn get(&mut self) -> &[[u8; 4]] {
use std::os::unix::fs::MetadataExt;
let now_inst = std::time::Instant::now();
if self.checked_at.is_some_and(|t| now_inst.saturating_duration_since(t) < std::time::Duration::from_millis(250)) {
return &self.servers;
}
self.checked_at = Some(now_inst);
let stat = |p: &str| std::fs::metadata(p).ok().map(|m| (m.ino(), m.len(), m.mtime(), m.mtime_nsec()));
let now = [stat("/etc/resolv.conf"), stat("/run/systemd/resolve/resolv.conf")];
if self.stamp != Some(now) {
+88 -35
View File
@@ -590,10 +590,10 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
if spec.flags & run_flags::NET_HOST == 0 && prepared.net_join.is_none() {
let had_ping = host.sysctls.iter().any(|s| s.path == "net/ipv4/ping_group_range");
super::hostopts::add_net_defaults(&mut host.sysctls);
static SELF_PING_MAX: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
if !had_ping
&& let Ok(map) = fs::read_to_string("/proc/self/gid_map")
&& let Some(max) = *SELF_PING_MAX.get_or_init(|| fs::read_to_string("/proc/self/gid_map").ok().map(|m| ping_group_max(&m)))
{
let max = ping_group_max(&map);
if max < DEFAULT_PING_MAX
&& let Some(s) = host.sysctls.iter_mut().find(|s| s.path == "net/ipv4/ping_group_range")
{
@@ -616,9 +616,16 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
let (root_ready, child_root_ready) = sys::pipe().map_err(cleanup)?;
prepared.root_ready = Some(child_root_ready);
// The child waits here until the agent has moved it into its cgroup, for
// a start that clone3 could not place there itself.
let (child_cgroup_ready, cgroup_go) = sys::pipe().map_err(cleanup)?;
prepared.cgroup_ready = Some(child_cgroup_ready);
// a start that clone3 could not place there itself. Once `clone3` with
// `CLONE_INTO_CGROUP` is confirmed working in this process, skip making
// the fallback pipe on every start.
let cgroup_go = if sys::clone3_works() {
None
} else {
let (child_cgroup_ready, go_fd) = sys::pipe().map_err(cleanup)?;
prepared.cgroup_ready = Some(child_cgroup_ready);
Some(go_fd)
};
let (parent_io, child_io) = stdio(&prepared).map_err(cleanup)?;
let rootfs_c = sys::cstr(&rootfs).map_err(cleanup)?;
@@ -674,9 +681,13 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// it (the child exiting early) read as EOF here.
drop(prepared.root_ready.take());
drop(prepared.cgroup_ready.take());
if flags & libc::CLONE_NEWNET as u64 != 0 {
netns = fs::File::open(format!("/proc/{pid}/ns/net")).map_or(0, |f| netns_inode(&f));
}
let child_netns = if flags & libc::CLONE_NEWNET as u64 != 0 {
let f = fs::File::open(format!("/proc/{pid}/ns/net")).ok();
netns = f.as_ref().map_or(0, netns_inode);
f
} else {
None
};
drop(cgroup_fd);
// The child makes its mounts before it waits for its network, and a
// mount that fails ends it with a message of its own. A step here then
@@ -724,9 +735,11 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// the pipe until this write is done.
fs::write(cgroup.join("cgroup.procs"), pid.to_string())
.map_err(|e| kill_child(io::Error::new(e.kind(), format!("cgroup: {e}"))))?;
// SAFETY: one byte to a pipe we own: "you are in your cgroup".
if unsafe { libc::write(cgroup_go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 {
return Err(kill_child(io::Error::last_os_error()));
if let Some(go_fd) = &cgroup_go {
// SAFETY: one byte to a pipe we own: "you are in your cgroup".
if unsafe { libc::write(go_fd.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 {
return Err(kill_child(io::Error::last_os_error()));
}
}
}
drop(cgroup_go);
@@ -765,7 +778,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// Not bridged, but with sysctls to write: no network to wait for.
if let Some(go) = go.take_if(|_| !bridged) {
drop(prepared.net_ready.take());
super::hostopts::apply_sysctls(pid, &host.sysctls).map_err(kill_child)?;
super::hostopts::apply_sysctls(pid, child_netns.as_ref(), &host.sysctls).map_err(kill_child)?;
// SAFETY: one byte to a pipe we own: "go on".
unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) };
}
@@ -780,7 +793,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
let mac = net_opts::values(spec.net.opts, net_opts::MAC).next().and_then(net::parse_mac);
let v6 = net::Ip6::from_opts(spec.net.opts);
let plug = net::Plug::from_opts(spec.net.opts);
net::attach_container(net.bridges, spec.net.bridge, &host_if, pid, spec.net.ip, spec.net.prefix, spec.net.gateway, mac, v6, plug)
net::attach_container(net.bridges, spec.net.bridge, &host_if, pid, child_netns.as_ref(), spec.net.ip, spec.net.prefix, spec.net.gateway, mac, v6, plug)
.map_err(|e| kill_child(io::Error::new(e.kind(), format!("network: {e}"))))?;
uplinks.extend(net::Uplink::of(&host_if, "eth0", spec.net.gateway, v6, plug));
veths.push(("eth0".to_owned(), host_if));
@@ -806,15 +819,21 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// waiting for its output to be read (see `admit`): it must
// not stand in for this container's own.
net.dns.drop_container(pid);
std::fs::File::open(format!("/proc/{pid}/ns/net")).and_then(|ns| {
net.dns.serve_in(&ns, pid, spec.net.bridge)?;
// User networks it joins once it runs: their names
// answer from its first lookup (#449).
for b in net_opts::values(spec.net.opts, net_opts::DNS_BRIDGE) {
net.dns.serve_in(&ns, pid, b)?;
let opened;
let ns = match child_netns.as_ref() {
Some(f) => f,
None => {
opened = std::fs::File::open(format!("/proc/{pid}/ns/net"))?;
&opened
}
Ok(())
})
};
net.dns.serve_in(ns, pid, spec.net.bridge)?;
// User networks it joins once it runs: their names
// answer from its first lookup (#449).
for b in net_opts::values(spec.net.opts, net_opts::DNS_BRIDGE) {
net.dns.serve_in(ns, pid, b)?;
}
Ok(())
});
if let Some(e) = in_err {
net.dns.drop_container(pid);
@@ -837,7 +856,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
names = Some(Names { v4: !plug.no_ipv4, v6: v6.map(|v| v.ip), servers });
}
// Its 127.0.0.11 listener goes with it.
super::hostopts::apply_sysctls(pid, &host.sysctls).map_err(|e| {
super::hostopts::apply_sysctls(pid, child_netns.as_ref(), &host.sysctls).map_err(|e| {
net.dns.drop_container(pid);
kill_child(e)
})?;
@@ -961,17 +980,25 @@ fn map_rofs_error(base: &Path, writable: bool, err: io::Error) -> io::Error {
pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writable: bool) -> io::Result<PathBuf> {
valid_id(id)?;
let base = paths.containers.join(id);
if writable
let fresh_base = !base.exists();
if !fresh_base
&& writable
&& let Some(kind) = sys::detect_readonly_fs(&base)
{
return Err(sys::readonly_storage_error(kind));
}
let (upper, work, rootfs) = (base.join("upper"), base.join("work"), base.join("rootfs"));
let _ = sys::umount_lazy(&rootfs);
for d in [&upper, &work, &rootfs] {
if !d.is_dir() {
if fresh_base {
for d in [&upper, &work, &rootfs] {
fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?;
}
} else {
let _ = sys::umount_lazy(&rootfs);
for d in [&upper, &work, &rootfs] {
if !d.is_dir() {
fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?;
}
}
}
// Lower dirs are relative to the agent's working directory (the layer
// store), which keeps the option string short enough for many layers.
@@ -1001,14 +1028,33 @@ pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writa
}
lower.push(empty.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "container folder is not UTF-8"))?.to_owned());
}
let plain = plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))?;
let plain = if fresh_base {
match fs::write(base.join(PLAIN_UPPER), b"") {
Ok(()) => true,
Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => true,
Err(e) => return Err(map_rofs_error(&base, writable, e)),
}
} else {
plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))?
};
let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain));
sys::mount_overlay(&rootfs, &lower, &rest, 0).map_err(|e| map_rofs_error(&base, writable, e))?;
if writable
&& let Err(e) = ensure_writable_rootfs(&base, &rootfs)
{
super::roots::unmount(&rootfs);
return Err(e);
if writable {
let ro_err = if fresh_base {
// `create_dir_all` already verified `base` is writable; one `statvfs`
// on `rootfs` catches overlayfs's silent read-only fallback (#768).
if sys::is_statvfs_readonly(&rootfs).unwrap_or(false) {
ensure_writable_rootfs(&base, &rootfs).err()
} else {
None
}
} else {
ensure_writable_rootfs(&base, &rootfs).err()
};
if let Some(e) = ro_err {
super::roots::unmount(&rootfs);
return Err(e);
}
}
Ok(rootfs)
}
@@ -1041,8 +1087,13 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
let (parent_io, child_io) = stdio(&prepared)?;
// The child waits here until the agent has moved it into its cgroup, for
// a start that clone3 could not place there itself.
let (child_cgroup_ready, cgroup_go) = sys::pipe()?;
prepared.cgroup_ready = Some(child_cgroup_ready);
let cgroup_go = if sys::clone3_works() {
None
} else {
let (child_cgroup_ready, go_fd) = sys::pipe()?;
prepared.cgroup_ready = Some(child_cgroup_ready);
Some(go_fd)
};
let args = CloneArgs {
flags: CLONE_INTO_CGROUP,
exit_signal: libc::SIGCHLD as u64,
@@ -1093,7 +1144,9 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
if !child.into_cgroup {
// clone(2) cannot put the exec in the container's cgroup: do it now,
// then let it join the container's namespaces.
if let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, &cgroup_go) {
if let Some(go_fd) = &cgroup_go
&& let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, go_fd)
{
// SAFETY: killing and reaping the child we just cloned.
unsafe {
libc::kill(pid, libc::SIGKILL);
+61 -20
View File
@@ -221,46 +221,85 @@ pub fn add_net_defaults(sysctls: &mut Vec<Sysctl>) {
sysctls.splice(0..0, mine);
}
thread_local! {
static OWN_NS: std::cell::RefCell<[Option<(fs::File, (u64, u64))>; 3]> = const { std::cell::RefCell::new([None, None, None]) };
}
fn own_ns_entry(ns: Ns) -> io::Result<(std::os::fd::RawFd, (u64, u64))> {
let (slot, name) = match ns {
Ns::Net => (0, "net"),
Ns::Ipc => (1, "ipc"),
Ns::Uts => (2, "uts"),
};
OWN_NS.with(|arr| {
let mut arr = arr.borrow_mut();
if let Some((f, id)) = &arr[slot] {
return Ok((f.as_raw_fd(), *id));
}
let f = fs::File::open(format!("/proc/self/ns/{name}"))?;
let m = f.metadata()?;
let id = (m.dev(), m.ino());
let raw = f.as_raw_fd();
arr[slot] = Some((f, id));
Ok((raw, id))
})
}
/// Writes the sysctls from the agent, inside the container's namespaces:
/// /proc/sys shows the calling task's network, IPC and UTS namespace, so
/// the agent joins the one each key belongs to, writes, and comes back.
/// Runs after the network is set up, so per-interface keys (eth0) exist.
pub fn apply_sysctls(pid: libc::pid_t, sysctls: &[Sysctl]) -> io::Result<()> {
for s in sysctls {
let (name, kind) = match s.ns {
pub fn apply_sysctls(pid: libc::pid_t, netns: Option<&fs::File>, sysctls: &[Sysctl]) -> io::Result<()> {
let mut i = 0;
while i < sysctls.len() {
let ns = sysctls[i].ns;
let mut end = i + 1;
while end < sysctls.len() && sysctls[end].ns == ns {
end += 1;
}
let (name, kind) = match ns {
Ns::Net => ("net", libc::CLONE_NEWNET),
Ns::Ipc => ("ipc", libc::CLONE_NEWIPC),
Ns::Uts => ("uts", libc::CLONE_NEWUTS),
};
let own = fs::File::open(format!("/proc/self/ns/{name}"))?;
let theirs = fs::File::open(format!("/proc/{pid}/ns/{name}"))?;
let (own_fd, own_id) = own_ns_entry(ns)?;
let opened;
let theirs = match (ns, netns) {
(Ns::Net, Some(f)) => f,
_ => {
opened = fs::File::open(format!("/proc/{pid}/ns/{name}"))?;
&opened
}
};
let tm = theirs.metadata()?;
// The container shares the agent's own namespace (host network,
// directly or through `--network container:`): the key would change
// the whole VM or Linux host. The daemon refuses this first.
if same_namespace(&own, &theirs)? {
if (tm.dev(), tm.ino()) == own_id {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("sysctl {:?} not allowed in host {name} namespace", s.path.replace('/', ".")),
format!("sysctl {:?} not allowed in host {name} namespace", sysctls[i].path.replace('/', ".")),
));
}
sys::setns(theirs.as_raw_fd(), kind)?;
let written = fs::write(format!("/proc/sys/{}", s.path), &s.value);
let mut result = Ok(());
for s in &sysctls[i..end] {
if let Err(e) = fs::write(format!("/proc/sys/{}", s.path), &s.value) {
result = Err(io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e))));
break;
}
}
// Coming back must work, or the agent itself is in the container.
if let Err(e) = sys::setns(own.as_raw_fd(), kind) {
if let Err(e) = sys::setns(own_fd, kind) {
eprintln!("kiri-init: cannot leave a container's {name} namespace: {e}");
std::process::abort();
}
written.map_err(|e| io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e))))?;
result?;
i = end;
}
Ok(())
}
/// Two /proc/*/ns files name the same namespace when their inodes match.
fn same_namespace(a: &fs::File, b: &fs::File) -> io::Result<bool> {
let (a, b) = (a.metadata()?, b.metadata()?);
Ok((a.dev(), a.ino()) == (b.dev(), b.ino()))
}
/// The limits the engine's agent sets on itself as it starts, before it
/// starts anything, so that every container and build step inherits them
/// (a run's own `--ulimit` still replaces them in the child). In the VM the
@@ -453,11 +492,13 @@ mod tests {
fn own_namespace_is_refused() {
// A "container" that is this very process shares every namespace.
let me = std::process::id() as libc::pid_t;
let own = fs::File::open("/proc/self/ns/net").unwrap();
assert!(same_namespace(&own, &fs::File::open(format!("/proc/{me}/ns/net")).unwrap()).unwrap());
assert!(!same_namespace(&own, &fs::File::open("/proc/self/ns/ipc").unwrap()).unwrap());
let (_, own_net) = own_ns_entry(Ns::Net).unwrap();
let me_net = fs::File::open(format!("/proc/{me}/ns/net")).unwrap().metadata().unwrap();
let me_ipc = fs::File::open("/proc/self/ns/ipc").unwrap().metadata().unwrap();
assert_eq!(own_net, (me_net.dev(), me_net.ino()));
assert_ne!(own_net, (me_ipc.dev(), me_ipc.ino()));
let s = Sysctl { ns: Ns::Net, path: "net/ipv4/ip_unprivileged_port_start".into(), value: "77".into() };
let e = apply_sysctls(me, &[s]).unwrap_err();
let e = apply_sysctls(me, None, &[s]).unwrap_err();
assert_eq!(e.to_string(), "sysctl \"net.ipv4.ip_unprivileged_port_start\" not allowed in host net namespace");
}
}
+80 -21
View File
@@ -1110,10 +1110,11 @@ fn mac_of(name: &str) -> io::Result<[u8; 6]> {
type Bridge6 = Option<([u8; 16], u8)>;
/// Bridges that exist so far: name → (index, gateway (none when
/// IPv6-only), prefix, IPv6).
/// IPv6-only), prefix, IPv6), plus a persistent host `NETLINK_ROUTE` socket.
#[derive(Default)]
pub struct Bridges {
made: HashMap<String, (i32, Option<[u8; 4]>, u8, Bridge6)>,
route: Option<Netlink>,
}
/// What `Bridges::ensure` needs to do for a bridge given its cached state.
@@ -1131,6 +1132,13 @@ enum BridgePlan {
}
impl Bridges {
fn route_nl(&mut self) -> io::Result<&mut Netlink> {
if self.route.is_none() {
self.route = Some(Netlink::open(libc::NETLINK_ROUTE)?);
}
Ok(self.route.as_mut().expect("opened above"))
}
/// Whether `name` currently exists with an IPv6 subnet configured.
pub fn has_ipv6(&self, name: &str) -> bool {
matches!(self.made.get(name), Some((.., Some(_))))
@@ -1359,6 +1367,7 @@ pub fn attach_container(
bridge: &str,
host_ifname: &str,
pid: libc::pid_t,
netns: Option<&std::fs::File>,
ip: [u8; 4],
prefix: u8,
gateway: [u8; 4],
@@ -1366,7 +1375,7 @@ pub fn attach_container(
v6: Option<Ip6>,
plug: Plug,
) -> io::Result<()> {
attach(bridges, bridge, host_ifname, pid, 0, ip, prefix, gateway, mac, v6, plug)
attach_with_ns(bridges, bridge, host_ifname, pid, netns, 0, ip, prefix, gateway, mac, v6, plug)
}
/// Plugs the container into `bridge` as `eth{n}`. The first non-internal
@@ -1381,31 +1390,73 @@ pub fn attach_container(
/// MAC is made from it): neither the interface nor the bridge gets it.
#[allow(clippy::too_many_arguments)]
pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc::pid_t, n: u32, ip: [u8; 4], prefix: u8, gateway: [u8; 4], mac: Option<[u8; 6]>, v6: Option<Ip6>, plug: Plug) -> io::Result<()> {
attach_with_ns(bridges, bridge, host_ifname, pid, None, n, ip, prefix, gateway, mac, v6, plug)
}
#[allow(clippy::too_many_arguments)]
fn attach_with_ns(
bridges: &mut Bridges,
bridge: &str,
host_ifname: &str,
pid: libc::pid_t,
netns_fd: Option<&std::fs::File>,
n: u32,
ip: [u8; 4],
prefix: u8,
gateway: [u8; 4],
mac: Option<[u8; 6]>,
v6: Option<Ip6>,
plug: Plug,
) -> io::Result<()> {
let Plug { internal, no_ipv4 } = plug;
let mac = Some(mac.unwrap_or_else(|| mac_for(ip)));
let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?;
let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?;
let mut host = Netlink::open(libc::NETLINK_ROUTE)?;
// A stopped container's veth may still hold this address and MAC.
delete_retired(&mut host);
let opened_ns;
let netns = match netns_fd {
Some(f) => f,
None => {
opened_ns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?;
&opened_ns
}
};
let ifname = format!("eth{n}");
netlink::create_veth(&mut host, host_ifname, bridge_index, &netns, CONTAINER_MTU, &ifname, mac)?;
// By name: a new namespace may have tunl0, gre0 … before it.
let index = netlink::index_in(&netns, &ifname)?;
if v6.is_none() {
// Before it is up, so it never gets a link-local address. A kernel
// without IPv6 has no such file, and nothing to turn off.
let _ = netlink::in_netns(&netns, || sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1"));
{
let host = bridges.route_nl()?;
// A stopped container's veth may still hold this address and MAC.
delete_retired(host);
netlink::create_veth(host, host_ifname, bridge_index, netns, CONTAINER_MTU, &ifname, mac)?;
}
let mut inner = Netlink::open_in(&netns)?;
netlink::set_up(&mut inner, 1)?; // lo
if !no_ipv4 {
netlink::add_address(&mut inner, index, ip, prefix)?;
// Enter the container's network namespace once to resolve the peer index,
// disable IPv6 link-local when IPv6 is off, and open the inner route socket.
let (index, mut inner) = netlink::in_netns(netns, || {
let idx = netlink::index_of(&ifname)?;
if v6.is_none() {
let _ = sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1");
}
let nl = Netlink::open(libc::NETLINK_ROUTE)?;
Ok((idx, nl))
})?;
if n == 0 {
let mut batch = Vec::with_capacity(4);
batch.push(netlink::set_up_msg(1)); // lo
if !no_ipv4 {
batch.push(netlink::add_address_msg(index, ip, prefix));
}
if let Some(v) = v6 {
batch.push(netlink::add_address6_msg(index, v.ip, v.prefix));
}
batch.push(netlink::set_up_msg(index));
inner.request(&mut batch)?;
} else {
netlink::set_up(&mut inner, 1)?; // lo
if !no_ipv4 {
netlink::add_address(&mut inner, index, ip, prefix)?;
}
if let Some(v) = v6 {
netlink::add_address6(&mut inner, index, v.ip, v.prefix)?;
}
netlink::set_up(&mut inner, index)?;
}
if let Some(v) = v6 {
netlink::add_address6(&mut inner, index, v.ip, v.prefix)?;
}
netlink::set_up(&mut inner, index)?;
if !internal && !no_ipv4 {
netlink::add_default_route(&mut inner, index, gateway)?;
}
@@ -1417,6 +1468,7 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc:
/// Host-side veths of stopped containers, deleted by the next `attach`.
static RETIRED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
static HAS_RETIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Notes a stopped container's host-side veths for the next `attach` to
/// delete. Deleting one waits out RCU, 15-40 ms that every request after
@@ -1427,12 +1479,19 @@ static RETIRED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()
/// to the old namespace, and that answered with resets (a download that
/// broke mid-TLS or stalled).
pub fn retire(veths: &[String]) {
if veths.is_empty() {
return;
}
RETIRED.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(veths);
HAS_RETIRED.store(true, std::sync::atomic::Ordering::Release);
}
/// Deletes the veths `retire` noted. Gone already (the kernel took them
/// with their namespace) is fine.
fn delete_retired(nl: &mut Netlink) {
if !HAS_RETIRED.swap(false, std::sync::atomic::Ordering::AcqRel) {
return;
}
for v in std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())) {
let _ = netlink::delete_link(nl, &v);
}
+42 -14
View File
@@ -126,11 +126,7 @@ impl Netlink {
/// A route socket inside another network namespace: entered just long
/// enough to create the socket, which stays bound to that namespace.
pub fn open_in(netns: &std::fs::File) -> io::Result<Netlink> {
let own = std::fs::File::open("/proc/self/ns/net")?;
sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?;
let nl = Netlink::open(libc::NETLINK_ROUTE);
sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?;
nl
in_netns(netns, || Netlink::open(libc::NETLINK_ROUTE))
}
/// Sends messages (one batch) and waits for every acknowledgement.
@@ -314,13 +310,17 @@ pub fn delete_link(nl: &mut Netlink, name: &str) -> io::Result<()> {
nl.request(&mut [m])
}
pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> {
pub fn set_up_msg(index: i32) -> Msg {
let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK);
m.raw(&ifinfo(index, libc::IFF_UP as u32, libc::IFF_UP as u32));
nl.request(&mut [m])
m
}
pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> {
pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> {
nl.request(&mut [set_up_msg(index)])
}
pub fn add_address_msg(index: i32, addr: [u8; 4], prefix: u8) -> Msg {
let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL);
// struct ifaddrmsg: family, prefixlen, flags, scope, index.
let mut ifa = [0u8; 8];
@@ -328,7 +328,11 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i
ifa[1] = prefix;
ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes());
m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr);
match nl.request(&mut [m]) {
m
}
pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> {
match nl.request(&mut [add_address_msg(index, addr, prefix)]) {
Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
r => r,
}
@@ -337,7 +341,7 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i
/// An IPv6 address, usable at once: no duplicate address detection, which
/// would leave it tentative (not usable as a source) for about a second.
/// Kiri hands out every address on its networks, so none can be taken.
pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> {
pub fn add_address6_msg(index: i32, addr: [u8; 16], prefix: u8) -> Msg {
const IFA_F_NODAD: u8 = 0x02;
let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL);
let mut ifa = [0u8; 8];
@@ -346,7 +350,11 @@ pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) ->
ifa[2] = IFA_F_NODAD;
ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes());
m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr);
match nl.request(&mut [m]) {
m
}
pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> {
match nl.request(&mut [add_address6_msg(index, addr, prefix)]) {
Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
r => r,
}
@@ -397,7 +405,7 @@ fn default_route(nl: &mut Netlink, family: i32, gateway: &[u8], index: i32, flag
/// containers) succeed route lookup and reach nftables `output` redirect rules
/// instead of failing immediately with `ENETUNREACH`.
pub fn add_device_default_route(nl: &mut Netlink, index: i32, prefsrc: Option<[u8; 4]>) -> io::Result<()> {
let mut m = device_default_route_msg(index, prefsrc);
let m = device_default_route_msg(index, prefsrc);
match nl.request(&mut [m]) {
Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
r => r,
@@ -445,12 +453,32 @@ pub fn index_in(netns: &std::fs::File, name: &str) -> io::Result<i32> {
in_netns(netns, || index_of(name))
}
thread_local! {
static OWN_NETNS: std::cell::RefCell<Option<std::fs::File>> = const { std::cell::RefCell::new(None) };
}
fn own_netns_fd() -> io::Result<i32> {
OWN_NETNS.with(|slot| {
let mut slot = slot.borrow_mut();
if let Some(f) = slot.as_ref() {
return Ok(f.as_raw_fd());
}
let f = std::fs::File::open("/proc/self/ns/net")?;
let raw = f.as_raw_fd();
*slot = Some(f);
Ok(raw)
})
}
/// Runs `f` with this thread in `netns`, then back in its own.
pub fn in_netns<T>(netns: &std::fs::File, f: impl FnOnce() -> io::Result<T>) -> io::Result<T> {
let own = std::fs::File::open("/proc/self/ns/net")?;
let own = own_netns_fd()?;
sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?;
let r = f();
sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?;
if let Err(e) = sys::setns(own, libc::CLONE_NEWNET) {
eprintln!("kiri-init: cannot return to own network namespace: {e}");
std::process::abort();
}
r
}
+2
View File
@@ -932,6 +932,7 @@ mod tests {
"kiri0",
"kv_eg1",
c1_pid,
None,
[172, 18, 0, 2],
16,
[172, 18, 0, 1],
@@ -945,6 +946,7 @@ mod tests {
"kiri0",
"kv_eg2",
c2_pid,
None,
[172, 18, 0, 3],
16,
[172, 18, 0, 1],
+12
View File
@@ -555,17 +555,29 @@ fn clone_flags(args: &CloneArgs) -> libc::c_ulong {
/// # Safety
/// The caller must be single-threaded, as with fork(): the child gets a copy
/// of this thread only, so no other thread may hold a lock it needs.
static CLONE3_STATE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// True once `clone3(..., CLONE_INTO_CGROUP)` has succeeded in this process,
/// allowing later spawns/execs to skip creating the fallback `cgroup_ready` pipe.
pub fn clone3_works() -> bool {
CLONE3_STATE.load(std::sync::atomic::Ordering::Relaxed) == 1
}
pub unsafe fn clone3(args: &CloneArgs) -> io::Result<Cloned> {
// SAFETY: `args` is a valid clone_args of the size passed; the caller
// upholds the single-thread requirement.
let ret = unsafe { libc::syscall(libc::SYS_clone3, args as *const CloneArgs, std::mem::size_of::<CloneArgs>()) };
if ret >= 0 {
if ret > 0 {
CLONE3_STATE.store(1, std::sync::atomic::Ordering::Relaxed);
}
return Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: true });
}
let e = io::Error::last_os_error();
if !clone3_unavailable(e.raw_os_error()) {
return Err(io::Error::new(e.kind(), format!("clone3: {e}")));
}
CLONE3_STATE.store(2, std::sync::atomic::Ordering::Relaxed);
// SAFETY: as above. clone(2) has no cgroup, pidfd, set_tid, stack or tls
// arguments here: the child runs on a copy of this thread's stack, like
// fork(). Passing 0 for the four arguments after `flags` is identical on
+6 -4
View File
@@ -84,8 +84,10 @@ pub(super) fn trim(mountpoint: &str) -> io::Result<u64> {
}
/// Reports `(in_use, capacity)` in bytes for the filesystem mounted at
/// `mountpoint`, using `statvfs` (`in_use = (blocks - bavail) * frsize`,
/// `capacity = blocks * frsize`).
/// `mountpoint`, using `statvfs` (`in_use = (blocks - bfree) * frsize`,
/// `capacity = blocks * frsize`). Uses `f_bfree` rather than `f_bavail`
/// because `FITRIM` discards free blocks (`f_bfree`), never root-reserved
/// non-free blocks.
pub(super) fn stat(mountpoint: &str) -> io::Result<(u64, u64)> {
let path = std::ffi::CString::new(mountpoint).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
// SAFETY: statvfs fills a zero-initialized struct for a valid NUL-terminated path.
@@ -95,8 +97,8 @@ pub(super) fn stat(mountpoint: &str) -> io::Result<(u64, u64)> {
}
let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 };
let blocks = s.f_blocks as u64;
let bavail = s.f_bavail as u64;
let in_use = blocks.saturating_sub(bavail).saturating_mul(frsize);
let bfree = s.f_bfree as u64;
let in_use = blocks.saturating_sub(bfree).saturating_mul(frsize);
let capacity = blocks.saturating_mul(frsize);
Ok((in_use, capacity))
}
+10
View File
@@ -915,6 +915,16 @@ impl PinnedPeer {
if r != 0 || len as usize != std::mem::size_of::<libc::ucred>() || cred.pid <= 0 {
return None;
}
// `uid == 0` is unconditionally admitted by `Gate::check_subject`
// without inspecting supplementary groups or container cgroups.
if cred.uid == 0 {
return Some(PinnedPeer {
uid: 0,
gid: cred.gid,
groups: Vec::new(),
cgroup: String::new(),
});
}
let proc_path = CString::new(format!("/proc/{}", cred.pid)).ok()?;
// SAFETY: valid NUL-terminated path; pins the `/proc/<pid>` directory inode.
let raw_dir = unsafe { libc::open(proc_path.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) };
+175 -9
View File
@@ -384,8 +384,18 @@ static USED_CACHE: Mutex<Option<(PathBuf, Instant, u64)>> = Mutex::new(None);
#[cfg(target_os = "macos")]
static LAST_IN_USE: Mutex<Option<u64>> = Mutex::new(None);
#[cfg(target_os = "macos")]
static LAST_CAPACITY: Mutex<Option<u64>> = Mutex::new(None);
#[cfg(target_os = "macos")]
static RECLAIMING: AtomicBool = AtomicBool::new(false);
/// Persisted non-trimmable VM disk allocation (`<root>/vm/disk-overhead`),
/// measured right after `FITRIM` so ext4's own journal, bitmaps, and
/// initialized inode tables (up to ~2.5% of disk size, excluded from
/// `statvfs.f_blocks`) are counted as in-use VM disk rather than promised as
/// reclaimable space that `FITRIM` can never free.
#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
const DISK_OVERHEAD_FILE: &str = "vm/disk-overhead";
/// Reclaimable bytes under this threshold (64 MiB) are reported as 0 so
/// filesystem metadata slack does not prompt pointless trims.
pub const RECLAIM_THRESHOLD: u64 = 64 << 20;
@@ -397,10 +407,94 @@ pub fn reclaimable_bytes(disk_host: Option<u64>, disk_in_use: Option<u64>) -> Op
Some(if diff > RECLAIM_THRESHOLD { diff } else { 0 })
}
/// Allocated bytes (`st_blocks * 512`) and logical byte length (`st_size`) of
/// `<root>/vm/data.img`, if present.
pub fn data_img_stats(root: &Path) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let m = std::fs::metadata(root.join("vm/data.img")).ok()?;
Some((m.blocks().saturating_mul(512), m.len()))
}
/// Allocated bytes of `<root>/vm/data.img` (`st_blocks * 512`), if present.
pub fn data_img_allocated(root: &Path) -> Option<u64> {
use std::os::unix::fs::MetadataExt;
std::fs::metadata(root.join("vm/data.img")).ok().map(|m| m.blocks().saturating_mul(512))
data_img_stats(root).map(|(alloc, _)| alloc)
}
/// Upper bound on ext4's static metadata overhead (`logical_len - capacity`:
/// superblocks, group descriptors, bitmaps, journal, and inode tables), capped
/// to 1/16th of `capacity` + 512 MiB so an online-grown `data.img` whose guest
/// filesystem has not resized yet never treats the unmounted tail as overhead.
#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
fn max_ext4_overhead(logical_len: u64, capacity: u64) -> u64 {
if capacity == 0 || logical_len <= capacity {
return 0;
}
let cap = (capacity >> 4).saturating_add(512 << 20);
logical_len.saturating_sub(capacity).min(cap)
}
#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
fn read_disk_overhead(root: &Path) -> Option<u64> {
std::fs::read_to_string(root.join(DISK_OVERHEAD_FILE))
.ok()?
.trim()
.parse::<u64>()
.ok()
}
#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
fn write_disk_overhead(root: &Path, bytes: u64) {
let path = root.join(DISK_OVERHEAD_FILE);
let tmp = root.join("vm/disk-overhead.tmp");
if std::fs::write(&tmp, format!("{bytes}\n")).is_ok() {
let _ = std::fs::rename(&tmp, &path);
}
}
/// Effective bytes in use inside `data.img`, combining occupied filesystem
/// data blocks (`raw_in_use`) with allocated non-trimmable ext4 metadata so
/// `reclaimable_bytes(disk_host, effective_in_use)` matches what `FITRIM` can
/// actually return to macOS.
#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
fn effective_vm_in_use(
disk_host: Option<u64>,
logical_len: Option<u64>,
raw_in_use: Option<u64>,
capacity: Option<u64>,
recorded_overhead: Option<u64>,
) -> (Option<u64>, Option<u64>) {
let Some(raw) = raw_in_use else {
return (None, None);
};
let ext4_meta = match (logical_len, capacity) {
(Some(len), Some(cap)) => max_ext4_overhead(len, cap),
_ => 0,
};
let overhead = match recorded_overhead {
Some(saved) => match disk_host {
// If host allocation minus used data shrank below the saved floor
// (e.g. newly written files reused previously-allocated blocks),
// clamp downward and update the saved floor.
Some(host) => saved.min(host.saturating_sub(raw)),
None => saved,
},
None => {
// Before the first explicit reclaim records an exact post-FITRIM
// floor: a fresh disk (< 1 GiB of files) has near-zero initialized
// inode tables, whereas a mature populated disk (>= 1 GiB of files)
// has already completed `ext4lazyinit` across its block groups.
if raw >= (1 << 30) {
match disk_host {
Some(host) => ext4_meta.min(host.saturating_sub(raw)),
None => ext4_meta,
}
} else {
0
}
}
};
let clamped_update = recorded_overhead.filter(|&saved| overhead < saved).map(|_| overhead);
(Some(raw.saturating_add(overhead)), clamped_update)
}
#[cfg(target_os = "linux")]
@@ -513,14 +607,24 @@ pub fn report(engine: &Engine) -> Value {
let root = engine.store.root();
#[cfg(target_os = "macos")]
let disk = {
let disk_host = data_img_allocated(root);
let disk_in_use = match engine.disk_usage_if_awake() {
Some((in_use, _)) => {
let stats = data_img_stats(root);
let (disk_host, logical_len) = (stats.map(|(a, _)| a), stats.map(|(_, l)| l));
let (raw_in_use, capacity) = match engine.disk_usage_if_awake() {
Some((in_use, cap)) => {
*LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(in_use);
Some(in_use)
*LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(cap);
(Some(in_use), Some(cap))
}
None => *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()),
None => (
*LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()),
*LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()),
),
};
let recorded = read_disk_overhead(root);
let (disk_in_use, clamped) = effective_vm_in_use(disk_host, logical_len, raw_in_use, capacity, recorded);
if let Some(updated) = clamped {
write_disk_overhead(root, updated);
}
let disk_limit = Some(super::engine::vm_disk_gb().saturating_mul(1 << 30));
let reclaimable = reclaimable_bytes(disk_host, disk_in_use);
DiskInfo { disk_host, disk_in_use, disk_limit, reclaimable }
@@ -557,9 +661,18 @@ pub fn reclaim(engine: &Engine) -> Result<Value, Error> {
let t0 = Instant::now();
let root = engine.store.root();
let before = data_img_allocated(root).unwrap_or(0);
let (trimmed, in_use, _capacity) = engine.trim_disk().map_err(Error::Io)?;
*LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(in_use);
let (trimmed, raw_in_use, capacity) = engine.trim_disk().map_err(Error::Io)?;
// Flush pending VirtioBlock DISCARD hole-punches through XNU/APFS before
// sampling `st_blocks` so `after` reflects every reclaimed block immediately.
if let Ok(f) = std::fs::File::open(root.join("vm/data.img")) {
let _ = f.sync_all();
}
*LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(raw_in_use);
*LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(capacity);
let after = data_img_allocated(root).unwrap_or(0);
let overhead = after.saturating_sub(raw_in_use);
write_disk_overhead(root, overhead);
let in_use = raw_in_use.saturating_add(overhead);
invalidate_used_cache();
let reclaimed = before.saturating_sub(after);
let elapsed_ms = t0.elapsed().as_millis() as u64;
@@ -570,6 +683,8 @@ pub fn reclaim(engine: &Engine) -> Result<Value, Error> {
reclaimed = reclaimed,
trimmed = trimmed,
in_use = in_use,
raw_in_use = raw_in_use,
overhead = overhead,
elapsed_ms = elapsed_ms
);
Ok(json!({
@@ -577,6 +692,7 @@ pub fn reclaim(engine: &Engine) -> Result<Value, Error> {
"after": after,
"reclaimed": reclaimed,
"in_use": in_use,
"reclaimable": 0,
"elapsed_ms": elapsed_ms,
}))
}
@@ -1235,4 +1351,54 @@ mod tests {
assert_eq!(s["reclaimable"], 12_100_000_000u64);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn ext4_metadata_overhead_is_excluded_from_reclaimable_space() {
// Mature 128 GiB disk (`137.44 GB` logical, `134.15 GB` statvfs capacity ->
// `3.29 GB` ext4 journal + inode table overhead): `104.0 GB` on macOS with
// `98.4 GB` of files promises only the `2.31 GB` that FITRIM can free, and
// reports 0 reclaimable once `101.69 GB` remains after FITRIM.
let logical = 128u64 << 30;
let capacity = logical - 3_290_000_000;
let raw_used = 98_400_000_000u64;
let (in_use_before, clamped) = effective_vm_in_use(
Some(104_000_000_000),
Some(logical),
Some(raw_used),
Some(capacity),
None,
);
assert_eq!(clamped, None);
assert_eq!(in_use_before, Some(101_690_000_000));
assert_eq!(reclaimable_bytes(Some(104_000_000_000), in_use_before), Some(2_310_000_000));
// After FITRIM leaves `101.69 GB` on host, recorded overhead is `3.29 GB` and reclaimable is 0.
let d = scratch("reclaim-overhead");
std::fs::create_dir_all(d.join("vm")).unwrap();
write_disk_overhead(&d, 3_290_000_000);
assert_eq!(read_disk_overhead(&d), Some(3_290_000_000));
let (in_use_after, _) = effective_vm_in_use(
Some(101_690_000_000),
Some(logical),
Some(raw_used),
Some(capacity),
read_disk_overhead(&d),
);
assert_eq!(reclaimable_bytes(Some(101_690_000_000), in_use_after), Some(0));
// Fresh sparse disk (< 1 GiB of files) before first trim does not over-subtract lazy overhead.
let (fresh_used, _) = effective_vm_in_use(
Some(2_020_000_000),
Some(logical),
Some(20_000_000),
Some(capacity),
None,
);
assert_eq!(fresh_used, Some(20_000_000));
assert_eq!(reclaimable_bytes(Some(2_020_000_000), fresh_used), Some(2_000_000_000));
// Online-grown un-resized disk (`logical >> capacity`) caps static overhead safely.
assert!(max_ext4_overhead(256 << 30, 64 << 30) <= (4 << 30) + (512 << 20));
let _ = std::fs::remove_dir_all(&d);
}
}
+20 -3
View File
@@ -79,6 +79,9 @@ pub struct VmLink {
/// The guest's latest `Usage` lines, for `usage`.
usage: Arc<UsageSlot>,
pending: Arc<Mutex<VecDeque<SyncSender<Reply>>>>,
/// Layer digests confirmed unpacked in this guest instance, avoiding
/// repeated `LayerQuery` round-trips across `create` and `start`.
layers: Mutex<std::collections::HashSet<String>>,
/// Kept so the VM lives as long as the link. Behind a mutex only so the
/// link can be shared between threads; nothing touches it after boot.
_vm: Mutex<Vm>,
@@ -345,6 +348,7 @@ impl VmLink {
agent_dir: vm.agent_dir().to_owned(),
writer: Mutex::new(Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024] }),
pending,
layers: Mutex::new(std::collections::HashSet::new()),
windows,
usage,
connector: vm.connector(),
@@ -401,8 +405,16 @@ impl VmLink {
}
pub fn has_layer(&self, digest: &str) -> io::Result<bool> {
if self.layers.lock().unwrap_or_else(|e| e.into_inner()).contains(digest) {
return Ok(true);
}
match self.call(|o| Msg::LayerQuery(digest).encode(o), None)? {
Reply::LayerStatus(have) => Ok(have),
Reply::LayerStatus(have) => {
if have {
self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned());
}
Ok(have)
}
other => Err(io::Error::other(format!("expected LayerStatus, got {other:?}"))),
}
}
@@ -412,8 +424,9 @@ impl VmLink {
// fails here rather than half-way through the request.
let file = File::open(blob)?;
let size = file.metadata()?.len();
self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))
.map(drop)
self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))?;
self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned());
Ok(())
}
#[allow(clippy::too_many_arguments)]
@@ -638,6 +651,10 @@ impl VmLink {
/// Tells the guest which unpacked layers are still used; it deletes the rest.
pub fn retain_layers(&self, digests: &[String]) -> io::Result<()> {
{
let keep: std::collections::HashSet<&str> = digests.iter().map(String::as_str).collect();
self.layers.lock().unwrap_or_else(|e| e.into_inner()).retain(|d| keep.contains(d.as_str()));
}
self.send(|o| kiri_proto::encode_retain_layers(o, digests))
}
+68 -85
View File
@@ -3506,8 +3506,12 @@ window.kiriWords = (p) => {
/* A container's page: Overview, Logs, Terminal, Files. The log console and
the terminal are kept as live elements, so a list refresh never wipes
them or what is being typed. */
const logEl = Object.assign(document.createElement("div"), { className: "console numbered", tabIndex: 0 });
logEl.setAttribute("role", "log");
function makeLogConsole() {
const el = Object.assign(document.createElement("div"), { className: "console numbered", tabIndex: 0 });
el.setAttribute("role", "log");
return el;
}
const logEl = makeLogConsole();
const termEl = document.createElement("div");
termEl.className = "term";
termEl.innerHTML = `<div class="console" id="term-out" tabindex="0"></div>
@@ -3661,21 +3665,29 @@ function levelOf(line) {
return "";
}
const shown = (div, f, lvl) => (!f || div.textContent.toLowerCase().includes(f)) && (!lvl || div.dataset.lvl === lvl);
function logCount() {
const el = $("log-count");
if (!el) return;
const all = logEl.childElementCount, d = ui.detail;
const showing = d.logFilter || d.logLevel ? [...logEl.children].filter((x) => !x.classList.contains("hide")).length : all;
el.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() });
const LOG_LEVEL_OPTS = () => [["", tr("All levels")], ["error", tr("Error")], ["warn", tr("Warn")], ["info", tr("Info")], ["debug", tr("Debug")]];
function logToolbarHtml({ prefix, filter, level, follow, left = "", right = "", reloadAttr = "", clearAttr }) {
return `<div class="logbar">${left}<input class="field" id="${prefix}-filter" placeholder="${tr("Find in logs")}" spellcheck="false" value="${esc(filter)}">
<select id="${prefix}-level" aria-label="${tr("Level")}">${LOG_LEVEL_OPTS().map(([v, l]) => `<option value="${v}"${level === v ? " selected" : ""}>${l}</option>`).join("")}</select>
<span class="logcount" id="${prefix}-count"></span>
<span class="spacer" style="flex:1"></span>
${right}<label class="toggle"><input type="checkbox" id="${prefix}-follow"${follow ? " checked" : ""}> ${tr("Follow")}</label>${reloadAttr ? btn(tr("Reload"), reloadAttr) : ""}${btn(tr("Clear"), clearAttr)}</div>`;
}
function addLogs(parts) {
const atEnd = logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight < 40;
const filter = ui.detail.logFilter.toLowerCase(), level = ui.detail.logLevel;
function updateLogCount(el, countId, d) {
const cnt = $(countId);
if (!cnt || !d) return;
const all = el.childElementCount;
const showing = d.logFilter || d.logLevel ? [...el.children].filter((x) => !x.classList.contains("hide")).length : all;
cnt.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() });
}
function appendLogParts(el, countId, d, partial, nextN, parts) {
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const filter = d.logFilter.toLowerCase(), level = d.logLevel;
const frag = document.createDocumentFragment();
for (const p of parts) {
const lines = (ui.partial[p.e] + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n");
ui.partial[p.e] = lines.pop();
const key = Boolean(p.e);
const lines = ((partial[key] || "") + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n");
partial[key] = lines.pop();
for (const line of lines) {
const div = document.createElement("div");
const lvl = levelOf(line);
@@ -3683,22 +3695,37 @@ function addLogs(parts) {
if (lvl && lvl !== "info") div.className = `lvl-${lvl}`;
else if (p.e) div.className = "err";
div.textContent = line || " ";
div.dataset.n = ++ui.logN;
div.dataset.n = nextN();
if (!shown(div, filter, level)) div.classList.add("hide");
frag.append(div);
}
}
logEl.append(frag);
while (logEl.childElementCount > LOG_MAX) logEl.firstElementChild.remove();
if (ui.detail.follow && atEnd || ui.detail.follow && parts.length > 50) logEl.scrollTop = logEl.scrollHeight;
logCount();
el.append(frag);
while (el.childElementCount > LOG_MAX) el.firstElementChild.remove();
if (d.follow && atEnd || d.follow && parts.length > 50) el.scrollTop = el.scrollHeight;
updateLogCount(el, countId, d);
}
function filterLogs() {
const d = ui.detail, f = d.logFilter.toLowerCase();
for (const div of logEl.children) div.classList.toggle("hide", !shown(div, f, d.logLevel));
logCount();
function applyLogFilter(el, countId, d) {
const f = d.logFilter.toLowerCase();
for (const div of el.children) div.classList.toggle("hide", !shown(div, f, d.logLevel));
updateLogCount(el, countId, d);
}
function appendLogEnd(el, text) {
const div = document.createElement("div");
div.className = "quiet";
div.textContent = text;
el.append(div);
}
function clearLogConsole(el, countId, d, partial, resetN) {
el.textContent = "";
partial.false = "";
partial.true = "";
resetN();
updateLogCount(el, countId, d);
}
function logCount() { updateLogCount(logEl, "log-count", ui.detail); }
function addLogs(parts) { appendLogParts(logEl, "log-count", ui.detail, ui.partial, () => ++ui.logN, parts); }
function filterLogs() { applyLogFilter(logEl, "log-count", ui.detail); }
/* The prompt, as a shell shows it: user@host:dir# (or $ for other users).
Until the container has answered, it comes from the inspect data. */
@@ -3848,12 +3875,7 @@ function renderDetail() {
else if (d.tab === "logs" && keepLogs) logCount();
else if (d.tab === "logs") {
body.dataset.logs = c.Id;
const levels = [["", tr("All levels")], ["error", tr("Error")], ["warn", tr("Warn")], ["info", tr("Info")], ["debug", tr("Debug")]];
body.innerHTML = `<div class="logbar"><input class="field" id="log-filter" placeholder="${tr("Find in logs")}" spellcheck="false" value="${esc(d.logFilter)}">
<select id="log-level" aria-label="${tr("Level")}">${levels.map(([v, l]) => `<option value="${v}"${d.logLevel === v ? " selected" : ""}>${l}</option>`).join("")}</select>
<span class="logcount" id="log-count"></span>
<span class="spacer" style="flex:1"></span>
<label class="toggle"><input type="checkbox" id="log-follow"${d.follow ? " checked" : ""}> ${tr("Follow")}</label>${btn(tr("Clear"), "data-logclear")}</div>`;
body.innerHTML = logToolbarHtml({ prefix: "log", filter: d.logFilter, level: d.logLevel, follow: d.follow, clearAttr: "data-logclear" });
body.append(logEl);
logCount();
$("log-filter").addEventListener("input", (ev) => { d.logFilter = ev.target.value; filterLogs(); });
@@ -8812,7 +8834,7 @@ window.kiri = {
} else {
ui.stReclaimed = e;
if (ui.storage && e.after != null) {
ui.storage = { ...ui.storage, disk_host: e.after, ...(e.in_use != null ? { disk_in_use: e.in_use } : {}), reclaimable: 0 };
ui.storage = { ...ui.storage, disk_host: e.after, ...(e.in_use != null ? { disk_in_use: e.in_use } : {}), reclaimable: e.reclaimable ?? 0 };
}
toast("ok", e.reclaimed > 0 ? tr("Reclaimed {size} on {os}", { size: size(e.reclaimed), os: OS }) : tr("Nothing to reclaim"));
}
@@ -8862,7 +8884,7 @@ window.kiri = {
case "stats": if (ui.detail?.id === e.id) { e.at = Date.now(); addSample(e); } break;
case "stats-end": if (ui.detail?.id === e.id) ui.detail.statsOn = false; break;
case "logs": if (ui.detail?.id === e.id) addLogs(e.parts); break;
case "logs-end": if (ui.detail?.id === e.id) { const d = document.createElement("div"); d.className = "quiet"; d.textContent = tr("— the log stream ended —"); logEl.append(d); ui.detail.logsOn = false; } break;
case "logs-end": if (ui.detail?.id === e.id) { appendLogEnd(logEl, tr("— the log stream ended —")); ui.detail.logsOn = false; } break;
case "exec": if (ui.detail?.id === e.id) finishExec(e); break;
case "files": if (ui.detail?.name === e.name) { Object.assign(ui.detail.files, { path: e.path, entries: e.entries, error: e.error, loading: false }); render(); } break;
case "preview": if (ui.detail?.name === e.name && ui.detail.files.selected === e.path) { ui.detail.files.preview = e; render(); } break;
@@ -9051,7 +9073,7 @@ $("content").addEventListener("click", (ev) => {
else if ((el = t("[data-file]"))) { ui.detail.files.selected = el.dataset.file; ui.detail.files.preview = null; send("preview", { name: ui.detail.name, path: el.dataset.file }); render(); }
else if ((el = t("[data-reveal]"))) send("reveal", { name: ui.detail.name, path: el.dataset.reveal });
else if ((el = t("[data-terminal]"))) send("terminal", { name: ui.detail.name });
else if ((el = t("[data-logclear]"))) { logEl.textContent = ""; logCount(); }
else if ((el = t("[data-logclear]"))) clearLogConsole(logEl, "log-count", ui.detail, ui.partial, () => { ui.logN = 0; });
else if ((el = t("[data-save]"))) send("download", { name: ui.detail.name, path: el.dataset.save });
});
$("impstrip").addEventListener("click", (ev) => {
@@ -9135,7 +9157,7 @@ document.addEventListener("dblclick", (ev) => {
the sidebar's counts, every 30 s, and only while the node runs (the VM is
awake for it then anyway). Nothing here starts the cluster but Start. */
const K8S_VIEWS = new Set(["pods", "services"]);
const k8s = { state: null, ready: false, pods: [], services: [], icon: null, asked: 0, sig: "", detail: null, svc: null, partial: "",
const k8s = { state: null, ready: false, pods: [], services: [], icon: null, asked: 0, sig: "", detail: null, svc: null, partial: { false: "", true: "" }, logN: 0,
op: "", opAt: 0, opLine: "", context: "", config: null, sanDraft: null, port: null, wantPort: 6443, portDraft: null, argsDraft: null, defaultVer: "", manifestsDir: "" };
empty.pods = { title: "No pods", body: "Pods you create with <code>kubectl</code> show up here, grouped by namespace.", art: "pods" };
empty.services = { title: "No services", body: "Services you create with <code>kubectl expose</code> show up here. LoadBalancer services answer on <code>localhost</code>.", art: "services" };
@@ -9246,10 +9268,7 @@ function k8sOn(e) {
case "k8slogs": if (d?.logKey === e.key) addKLogs(e.parts); break;
case "k8slogs-end":
if (d?.logKey === e.key) {
const div = document.createElement("div");
div.className = "quiet";
div.textContent = d.previous ? tr("— the end of the run before the last restart —") : tr("— the log stream ended —");
klogEl.append(div);
appendLogEnd(klogEl, d.previous ? tr("— the end of the run before the last restart —") : tr("— the log stream ended —"));
d.logsOn = false;
}
break;
@@ -9471,15 +9490,14 @@ function deletePod(key) {
scrim.querySelector("[data-go]")?.focus();
}
/* A pod's page: Info and Logs. The log console is kept as a live element,
as the container page's is. */
const klogEl = Object.assign(document.createElement("div"), { className: "console", tabIndex: 0 });
klogEl.setAttribute("role", "log");
/* A pod's page: Info and Logs. Shares the numbered log console component with
container logs (`makeLogConsole`, `appendLogParts`, `logToolbarHtml`). */
const klogEl = makeLogConsole();
function openPod(key, tab = "info") {
closePod();
const [ns, name] = key.split("/");
k8s.detail = { ns, name, tab: "info", container: "", previous: false, follow: true, logFilter: "", logLevel: "", logsOn: false, logKey: "" };
klogEl.textContent = "";
clearLogConsole(klogEl, "klog-count", k8s.detail, k8s.partial, () => { k8s.logN = 0; });
if (tab === "logs") podTab("logs"); else render();
$("content").scrollTop = 0;
}
@@ -9502,42 +9520,12 @@ function podLogs(again = false) {
const key = `${d.ns}/${d.name}/${d.container}${d.previous ? "/previous" : ""}`;
if (!again && d.logKey === key && (d.logsOn || d.previous)) return;
Object.assign(d, { logKey: key, logsOn: !d.previous });
klogEl.textContent = "";
k8s.partial = "";
clearLogConsole(klogEl, "klog-count", d, k8s.partial, () => { k8s.logN = 0; });
send("k8s", { action: "logs", value: { ns: d.ns, pod: d.name, container: d.container, previous: d.previous } });
}
function addKLogs(parts) {
const d = k8s.detail, atEnd = klogEl.scrollHeight - klogEl.scrollTop - klogEl.clientHeight < 40;
const filter = d.logFilter.toLowerCase(), frag = document.createDocumentFragment();
for (const p of parts) {
const lines = (k8s.partial + p.t.replace(ansi, "")).split("\n");
k8s.partial = lines.pop();
for (const line of lines) {
const div = document.createElement("div"), lvl = levelOf(line);
div.dataset.lvl = lvl || "none";
if (lvl && lvl !== "info") div.className = `lvl-${lvl}`;
div.textContent = line || " ";
if (!shown(div, filter, d.logLevel)) div.classList.add("hide");
frag.append(div);
}
}
klogEl.append(frag);
while (klogEl.childElementCount > LOG_MAX) klogEl.firstElementChild.remove();
if (d.follow && atEnd || d.follow && parts.length > 50) klogEl.scrollTop = klogEl.scrollHeight;
klogCount();
}
function klogCount() {
const el = $("klog-count"), d = k8s.detail;
if (!el || !d) return;
const all = klogEl.childElementCount;
const showing = d.logFilter || d.logLevel ? [...klogEl.children].filter((x) => !x.classList.contains("hide")).length : all;
el.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() });
}
function filterKLogs() {
const d = k8s.detail, f = d.logFilter.toLowerCase();
for (const div of klogEl.children) div.classList.toggle("hide", !shown(div, f, d.logLevel));
klogCount();
}
function addKLogs(parts) { appendLogParts(klogEl, "klog-count", k8s.detail, k8s.partial, () => ++k8s.logN, parts); }
function klogCount() { updateLogCount(klogEl, "klog-count", k8s.detail); }
function filterKLogs() { applyLogFilter(klogEl, "klog-count", k8s.detail); }
function renderPod() {
const d = k8s.detail, p = podOf(d);
@@ -9556,15 +9544,10 @@ function renderPod() {
<div id="dbody"></div>`;
const body = $("dbody");
if (d.tab === "info") { body.innerHTML = podInfo(p); return; }
const levels = [["", tr("All levels")], ["error", tr("Error")], ["warn", tr("Warn")], ["info", tr("Info")], ["debug", tr("Debug")]];
const picker = p.containers.length > 1 ? `<select id="klog-container" aria-label="${tr("Container")}">${p.containers.map((c) => `<option${c.name === d.container ? " selected" : ""}>${esc(c.name)}</option>`).join("")}</select>` : "";
const restarted = p.containers.find((c) => c.name === d.container)?.restarts > 0;
body.innerHTML = `<div class="logbar">${picker}<input class="field" id="klog-filter" placeholder="${tr("Find in logs")}" spellcheck="false" value="${esc(d.logFilter)}">
<select id="klog-level" aria-label="${tr("Level")}">${levels.map(([v, l]) => `<option value="${v}"${d.logLevel === v ? " selected" : ""}>${l}</option>`).join("")}</select>
<span class="logcount" id="klog-count"></span>
<span class="spacer" style="flex:1"></span>
${restarted || d.previous ? `<label class="toggle" title="${tr("The run before the container's last restart")}"><input type="checkbox" id="klog-previous"${d.previous ? " checked" : ""}> ${tr("Previous run")}</label>` : ""}
<label class="toggle"><input type="checkbox" id="klog-follow"${d.follow ? " checked" : ""}> ${tr("Follow")}</label>${btn(tr("Reload"), "data-klogreload")}${btn(tr("Clear"), "data-klogclear")}</div>`;
const prevToggle = restarted || d.previous ? `<label class="toggle" title="${tr("The run before the container's last restart")}"><input type="checkbox" id="klog-previous"${d.previous ? " checked" : ""}> ${tr("Previous run")}</label>` : "";
body.innerHTML = logToolbarHtml({ prefix: "klog", filter: d.logFilter, level: d.logLevel, follow: d.follow, left: picker, right: prevToggle, reloadAttr: "data-klogreload", clearAttr: "data-klogclear" });
body.append(klogEl);
klogCount();
$("klog-container")?.addEventListener("change", (ev) => { d.container = ev.target.value; podLogs(); });
@@ -9886,7 +9869,7 @@ $("content").addEventListener("click", (ev) => {
else if (t("[data-k8smanifests]")) send("k8s", { action: "manifests" });
else if (t("[data-k8sdelete]")) deleteCluster();
else if (t("[data-klogreload]")) podLogs(true);
else if (t("[data-klogclear]")) { klogEl.textContent = ""; klogCount(); }
else if (t("[data-klogclear]")) clearLogConsole(klogEl, "klog-count", k8s.detail, k8s.partial, () => { k8s.logN = 0; });
});
$("title").addEventListener("click", (ev) => { if (ev.target.closest("[data-kback]")) { closePod(); render(); } });
$("content").addEventListener("paste", envPaste);
+37 -4
View File
@@ -13,8 +13,8 @@ use objc2::runtime::{AnyObject, ProtocolObject};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2::sel;
use objc2_app_kit::{
NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType, NSMenu, NSMenuDelegate, NSMenuItem,
NSWindow, NSWindowStyleMask, NSWindowTitleVisibility,
NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType, NSEvent, NSMenu, NSMenuDelegate, NSMenuItem,
NSResponder, NSView, NSWindow, NSWindowStyleMask, NSWindowTitleVisibility,
};
use objc2_foundation::{NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString};
use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandler, WKUserContentController, WKWebView, WKWebViewConfiguration};
@@ -141,7 +141,8 @@ fn make_webview(mtm: MainThreadMarker, frame: NSRect, tx: Sender<Cmd>, autostart
config
.userContentController()
.addScriptMessageHandler_name(ProtocolObject::from_ref(&*handler), &NSString::from_str("kiri"));
let webview = WKWebView::initWithFrame_configuration(WKWebView::alloc(mtm), frame, &config);
let webview = WebView::new(mtm, frame, &config);
webview.setAllowsLinkPreview(false);
if cfg!(debug_assertions) {
webview.setInspectable(true);
}
@@ -149,7 +150,7 @@ fn make_webview(mtm: MainThreadMarker, frame: NSRect, tx: Sender<Cmd>, autostart
let no: Retained<AnyObject> = msg_send![objc2::class!(NSNumber), numberWithBool: false];
let _: () = msg_send![&webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")];
webview.loadHTMLString_baseURL(&NSString::from_str(&super::assemble::page(PAGE, prefs()["lang"].as_str())), None);
webview
Retained::into_super(webview)
}
}
@@ -637,6 +638,38 @@ struct HandlerIvars {
view: Option<String>,
}
define_class!(
// SAFETY: WKWebView is a main-thread AppKit view safe to subclass without Drop.
#[unsafe(super(WKWebView, NSView, NSResponder, NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "KiriWebView"]
struct WebView;
unsafe impl NSObjectProtocol for WebView {}
impl WebView {
/// Kiri renders its own app editing menu (`#app-ctx` in `index.html`).
/// Clearing any AppKit `NSMenu` items WebKit builds guarantees Safari /
/// browser items (`Search with Google`, `Look Up`, `Translate`,
/// `Copy Link with Highlight`, `Share…`, `Speech`, `Services`) never
/// appear on macOS right-click or Ctrl-click.
#[unsafe(method(willOpenMenu:withEvent:))]
fn will_open_menu(&self, menu: &NSMenu, event: &NSEvent) {
menu.removeAllItems();
// SAFETY: forwarding `willOpenMenu:withEvent:` to `WKWebView` with valid args.
let _: () = unsafe { msg_send![super(self), willOpenMenu: menu, withEvent: event] };
}
}
);
impl WebView {
fn new(mtm: MainThreadMarker, frame: NSRect, config: &WKWebViewConfiguration) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(());
// SAFETY: `WKWebView`'s designated initializer on a freshly allocated subclass instance.
unsafe { msg_send![super(this), initWithFrame: frame, configuration: config] }
}
}
define_class!(
// SAFETY: NSObject has no subclassing requirements and this type has no Drop.
#[unsafe(super(NSObject))]
+411
View File
@@ -0,0 +1,411 @@
#!/usr/bin/env python3
"""Head-to-head Linux benchmark: Kiri Engine vs Docker Engine (`dockerd`).
Measures real-world container lifecycle and developer-workflow workloads on the
same Linux machine (alternating iterations so scheduler noise affects both
equally), producing a transparent markdown summary and JSON artifact (#776):
1. Ephemeral lifecycle (`docker run --rm alpine:3.21 true`, median & p95)
2. Multi-layer PHP app cold start (`php:8.2-cli-alpine` + 1,000-file bind mount
+ published port + HTTP readiness, modeling Lando / Compose dev stacks)
3. Warm app restart (`POST /containers/{id}/restart` + HTTP readiness)
4. Container `exec` (`100x php -r "echo 'ok';"` over Engine API)
5. Bind-mount filesystem I/O (`1,000` PHP files `glob` + `file_get_contents`)
6. Published-port HTTP latency (`250` GET requests)
7. App teardown (`stop` + `DELETE`, `SIGINT` stop signal)
8. Idle & post-benchmark engine RSS memory
Usage:
python3 scripts/bench-linux-docker.py --docker-sock /var/run/docker.sock \\
--kiri-sock /tmp/kiri-bench/docker.sock --kiri-pid <PID> \\
[--out results.json] [--report report.md]
Standard library only.
"""
import argparse
import http.client
import json
import os
import re
import socket
import statistics
import subprocess
import tempfile
import time
import urllib.request
ALPINE_IMG, ALPINE_TAG = "alpine", "3.21"
PHP_IMG, PHP_TAG = "php", "8.2-cli-alpine"
class UnixHTTP(http.client.HTTPConnection):
def __init__(self, path):
super().__init__("localhost", timeout=120)
self.path = path
def connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(120)
self.sock.connect(self.path)
class Client:
def __init__(self, name, sock):
self.name = name
self.sock = sock
self.conn = UnixHTTP(sock)
def reset(self):
try:
self.conn.close()
except Exception:
pass
self.conn = UnixHTTP(self.sock)
def call(self, method, path, body=None, want=(200, 201, 204, 304)):
data = json.dumps(body).encode() if body is not None else None
headers = {"Content-Type": "application/json"} if data is not None else {}
for attempt in range(2):
try:
self.conn.request(method, path, body=data, headers=headers)
r = self.conn.getresponse()
out = r.read()
break
except (http.client.HTTPException, OSError):
self.reset()
if attempt:
raise
if r.status not in want:
raise RuntimeError(f"[{self.name}] {method} {path}: {r.status} {out[:300]!r}")
return out
def pull(self, image, tag):
self.call("POST", f"/images/create?fromImage={image}&tag={tag}")
def run_ephemeral(self):
cid = json.loads(
self.call("POST", "/containers/create", {"Image": f"{ALPINE_IMG}:{ALPINE_TAG}", "Cmd": ["true"]})
)["Id"]
self.call("POST", f"/containers/{cid}/start")
self.call("POST", f"/containers/{cid}/wait")
self.call("DELETE", f"/containers/{cid}?force=1")
def exec_run(self, cid, cmd):
eid = json.loads(
self.call(
"POST",
f"/containers/{cid}/exec",
{"AttachStdout": True, "AttachStderr": True, "Cmd": cmd},
)
)["Id"]
return self.call("POST", f"/exec/{eid}/start", {"Detach": False, "Tty": False})
def proc_tree_rss_kib(pids):
seen = set()
queue = [p for p in pids if p and p > 0]
while queue:
pid = queue.pop()
if pid in seen:
continue
seen.add(pid)
try:
with open(f"/proc/{pid}/task/{pid}/children") as f:
for tok in f.read().split():
queue.append(int(tok))
except OSError:
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
try:
with open(f"/proc/{entry}/stat") as sf:
st = sf.read()
ppid = int(st.rsplit(")", 1)[1].split()[1])
if ppid == pid:
queue.append(int(entry))
except OSError:
pass
total = 0
for pid in seen:
try:
with open(f"/proc/{pid}/status") as f:
m = re.search(r"VmRSS:\s+(\d+)", f.read())
if m:
total += int(m.group(1))
except OSError:
pass
return total
def pidof_names(names):
out = []
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
try:
with open(f"/proc/{entry}/comm") as f:
comm = f.read().strip()
if comm in names:
out.append(int(entry))
except OSError:
pass
return out
def wait_http_ok(port, timeout_s=15.0):
deadline = time.perf_counter() + timeout_s
url = f"http://127.0.0.1:{port}/"
while time.perf_counter() < deadline:
try:
with urllib.request.urlopen(url, timeout=1.0) as resp:
if resp.status == 200 and b"ok" in resp.read():
return
except Exception:
time.sleep(0.01)
raise RuntimeError(f"HTTP server on port {port} did not become ready within {timeout_s}s")
def create_php_app(client, app_dir):
body = {
"Image": f"{PHP_IMG}:{PHP_TAG}",
"Cmd": ["php", "-S", "0.0.0.0:80", "-t", "/app"],
"StopSignal": "SIGINT",
"ExposedPorts": {"80/tcp": {}},
"HostConfig": {
"Binds": [f"{app_dir}:/app"],
"PortBindings": {"80/tcp": [{"HostIp": "127.0.0.1", "HostPort": "0"}]},
},
}
cid = json.loads(client.call("POST", "/containers/create", body))["Id"]
client.call("POST", f"/containers/{cid}/start")
info = json.loads(client.call("GET", f"/containers/{cid}/json"))
port = int(info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"])
wait_http_ok(port)
return cid, port
def destroy_php_app(client, cid):
client.call("POST", f"/containers/{cid}/stop?t=5")
client.call("DELETE", f"/containers/{cid}?force=1")
def restart_php_app(client, cid):
client.call("POST", f"/containers/{cid}/restart?t=5")
info = json.loads(client.call("GET", f"/containers/{cid}/json"))
port = int(info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"])
wait_http_ok(port)
return port
def summary(xs):
xs = sorted(xs)
p95_idx = max(0, int(len(xs) * 0.95) - 1)
return {"median": statistics.median(xs), "mean": statistics.mean(xs), "p95": xs[p95_idx], "n": len(xs)}
def extract_digits(raw):
# Strip Docker multiplexed stream headers (8-byte frames) and extract trailing integer.
clean = re.sub(rb"[\x00-\x08]", b"", raw).decode("utf-8", errors="ignore").strip().splitlines()
for line in reversed(clean):
digits = "".join(ch for ch in line if ch.isdigit())
if digits:
return float(digits)
raise RuntimeError(f"could not parse numeric output from {raw!r}")
def http_burst_ms(port, count=250):
t0 = time.perf_counter()
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
try:
for _ in range(count):
conn.request("GET", "/")
r = conn.getresponse()
r.read()
finally:
conn.close()
return (time.perf_counter() - t0) * 1000.0
def run_benchmark(args):
docker = Client("docker", args.docker_sock)
kiri = Client("kiri", args.kiri_sock)
engines = [("docker", docker), ("kiri", kiri)]
d_ver = json.loads(docker.call("GET", "/version"))
if "kiri" in json.dumps(d_ver).lower():
raise RuntimeError(f"--docker-sock ({args.docker_sock}) answered as Kiri ({d_ver.get('Platform')}); start dockerd first")
for _, c in engines:
c.call("GET", "/_ping")
c.pull(ALPINE_IMG, ALPINE_TAG)
c.pull(PHP_IMG, PHP_TAG)
for _ in range(5):
c.run_ephemeral()
time.sleep(1.0)
docker_pids = pidof_names({"dockerd", "containerd"})
kiri_pids = [args.kiri_pid] if args.kiri_pid else pidof_names({"kiri", "kiri-init"})
res = {
"kiri_version": args.version or "HEAD",
"docker": {"rss_idle_kib": proc_tree_rss_kib(docker_pids)},
"kiri": {"rss_idle_kib": proc_tree_rss_kib(kiri_pids)},
}
# 1. Alternating `docker run --rm alpine true`
ephemeral = {"docker": [], "kiri": []}
for i in range(args.ephemeral_runs):
pair = engines if i % 2 == 0 else list(reversed(engines))
for name, c in pair:
t0 = time.perf_counter()
c.run_ephemeral()
ephemeral[name].append((time.perf_counter() - t0) * 1000.0)
for name in ("docker", "kiri"):
res[name]["ephemeral_run_ms"] = summary(ephemeral[name])
# Prepare 1,000-file PHP fixture app (matching Xilonz/lando-engine-kiri)
with tempfile.TemporaryDirectory(prefix="kiri-php-bench-") as app_dir:
with open(os.path.join(app_dir, "index.php"), "w") as f:
f.write("<?php echo 'ok';\n")
fixtures = os.path.join(app_dir, "fixtures")
os.makedirs(fixtures, exist_ok=True)
for i in range(1, 1001):
with open(os.path.join(fixtures, f"file_{i}.php"), "w") as f:
f.write(f"<?php return 'fixture_data_{i}';\n")
cold = {"docker": [], "kiri": []}
destroy = {"docker": [], "kiri": []}
active = {}
# 2. Cold start & teardown (alternating)
for i in range(args.app_runs):
pair = engines if i % 2 == 0 else list(reversed(engines))
for name, c in pair:
t0 = time.perf_counter()
cid, port = create_php_app(c, app_dir)
cold[name].append((time.perf_counter() - t0) * 1000.0)
if i < args.app_runs - 1:
t1 = time.perf_counter()
destroy_php_app(c, cid)
destroy[name].append((time.perf_counter() - t1) * 1000.0)
else:
active[name] = (cid, port)
# 3. Warm restart (alternating)
warm = {"docker": [], "kiri": []}
for i in range(args.app_runs):
pair = engines if i % 2 == 0 else list(reversed(engines))
for name, c in pair:
cid, _ = active[name]
t0 = time.perf_counter()
port = restart_php_app(c, cid)
warm[name].append((time.perf_counter() - t0) * 1000.0)
active[name] = (cid, port)
# 4. 100x exec (`php -r "echo 'ok';"`)
for name, c in engines:
cid, _ = active[name]
t0 = time.perf_counter()
for _ in range(args.exec_runs):
c.exec_run(cid, ["php", "-r", "echo 'ok';"])
res[name]["exec_total_ms"] = (time.perf_counter() - t0) * 1000.0
res[name]["exec_runs"] = args.exec_runs
# 5. Bind-mount I/O (1,000 files, 10 passes inside PHP)
php_io = (
"$total = 0; "
"for ($p = 0; $p < 10; $p++) { "
" $t = microtime(true); "
" $files = glob('/app/fixtures/*.php'); "
" $sum = 0; "
" foreach ($files as $f) { $sum += strlen(file_get_contents($f)); } "
" $total += (microtime(true) - $t); "
"} "
"echo round(($total / 10) * 1000000);"
)
for name, c in engines:
cid, _ = active[name]
raw = c.exec_run(cid, ["php", "-r", php_io])
res[name]["bind_io_ms"] = extract_digits(raw) / 1000.0
# 6. Published-port HTTP latency (250 GET requests)
for name, _ in engines:
_, port = active[name]
res[name]["http_250_ms"] = http_burst_ms(port, 250)
# Final teardown sample
for name, c in engines:
cid, _ = active[name]
t1 = time.perf_counter()
destroy_php_app(c, cid)
destroy[name].append((time.perf_counter() - t1) * 1000.0)
for name in ("docker", "kiri"):
res[name]["app_cold_start_ms"] = summary(cold[name])
res[name]["app_warm_restart_ms"] = summary(warm[name])
res[name]["app_teardown_ms"] = summary(destroy[name])
res["docker"]["rss_after_kib"] = proc_tree_rss_kib(pidof_names({"dockerd", "containerd"}))
res["kiri"]["rss_after_kib"] = proc_tree_rss_kib([args.kiri_pid] if args.kiri_pid else pidof_names({"kiri", "kiri-init"}))
return res
def format_diff(d_val, k_val, unit="ms", decimals=2):
if d_val <= 0:
return "—"
pct = (k_val - d_val) / d_val * 100.0
word = "faster ⚡" if pct < -1.0 else ("slower" if pct > 1.0 else "on par")
return f"{k_val - d_val:+.{decimals}f} {unit} ({abs(pct):.1f}% {word})"
def render_markdown(res):
d, k = res["docker"], res["kiri"]
lines = [
f"## Linux Benchmark: Kiri (`{res.get('kiri_version', 'HEAD')}`) vs Docker Engine",
"",
"Alternating head-to-head runs on the same Linux host (ephemeral `alpine:3.21` + `php:8.2-cli-alpine` app stack with 1,000 bind-mounted files and published HTTP port).",
"",
"| Workload | Docker Engine | Kiri Engine | Comparison |",
"| :--- | ---: | ---: | :--- |",
f"| `docker run --rm alpine true` (median) | {d['ephemeral_run_ms']['median']:.2f} ms | {k['ephemeral_run_ms']['median']:.2f} ms | {format_diff(d['ephemeral_run_ms']['median'], k['ephemeral_run_ms']['median'])} |",
f"| `docker run --rm alpine true` (p95) | {d['ephemeral_run_ms']['p95']:.2f} ms | {k['ephemeral_run_ms']['p95']:.2f} ms | {format_diff(d['ephemeral_run_ms']['p95'], k['ephemeral_run_ms']['p95'])} |",
f"| PHP app cold start + HTTP ready (avg) | {d['app_cold_start_ms']['mean']:.1f} ms | {k['app_cold_start_ms']['mean']:.1f} ms | {format_diff(d['app_cold_start_ms']['mean'], k['app_cold_start_ms']['mean'], 'ms', 1)} |",
f"| PHP app warm restart + HTTP ready (avg) | {d['app_warm_restart_ms']['mean']:.1f} ms | {k['app_warm_restart_ms']['mean']:.1f} ms | {format_diff(d['app_warm_restart_ms']['mean'], k['app_warm_restart_ms']['mean'], 'ms', 1)} |",
f"| `{k['exec_runs']}x` `exec php -r \"echo 'ok';\"` | {d['exec_total_ms']:.1f} ms | {k['exec_total_ms']:.1f} ms | {format_diff(d['exec_total_ms'], k['exec_total_ms'], 'ms', 1)} |",
f"| Bind-mount I/O (1,000 PHP files, avg) | {d['bind_io_ms']:.2f} ms | {k['bind_io_ms']:.2f} ms | {format_diff(d['bind_io_ms'], k['bind_io_ms'])} |",
f"| Published-port HTTP (250 GETs) | {d['http_250_ms']:.1f} ms | {k['http_250_ms']:.1f} ms | {format_diff(d['http_250_ms'], k['http_250_ms'], 'ms', 1)} |",
f"| App teardown (`SIGINT` stop + rm, avg) | {d['app_teardown_ms']['mean']:.1f} ms | {k['app_teardown_ms']['mean']:.1f} ms | {format_diff(d['app_teardown_ms']['mean'], k['app_teardown_ms']['mean'], 'ms', 1)} |",
f"| Engine RSS at rest | {d['rss_idle_kib'] / 1024:.1f} MiB | {k['rss_idle_kib'] / 1024:.1f} MiB | {format_diff(d['rss_idle_kib'] / 1024, k['rss_idle_kib'] / 1024, 'MiB', 1)} |",
f"| Engine RSS after benchmark | {d['rss_after_kib'] / 1024:.1f} MiB | {k['rss_after_kib'] / 1024:.1f} MiB | {format_diff(d['rss_after_kib'] / 1024, k['rss_after_kib'] / 1024, 'MiB', 1)} |",
"",
]
return "\n".join(lines)
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--docker-sock", default="/var/run/docker.sock")
p.add_argument("--kiri-sock", required=True)
p.add_argument("--kiri-pid", type=int, default=0)
p.add_argument("--version", default="")
p.add_argument("--ephemeral-runs", type=int, default=100)
p.add_argument("--app-runs", type=int, default=10)
p.add_argument("--exec-runs", type=int, default=100)
p.add_argument("--out", default="")
p.add_argument("--report", default="")
args = p.parse_args()
res = run_benchmark(args)
if args.out:
with open(args.out, "w") as f:
json.dump(res, f, indent=2)
md = render_markdown(res)
if args.report:
with open(args.report, "w") as f:
f.write(md)
print(md)
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
// parity: macos windows linux
// Pod logs share the numbered log console component with Container logs.
const R = [];
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); };
kiri.on({
type: "lists",
containers: [{ Id: "k8snode000001", Names: ["/kiri-k8s"], Image: "rancher/k3s:v1.31.4-k3s1", State: "running", Status: "Up 2m", Created: 1700000000, Ports: [], Labels: {} }],
images: [], volumes: [], networks: [],
});
kiri.on({
type: "k8s",
state: "running",
ready: true,
context: "kiri",
port: 6443,
pods: [{
ns: "default",
name: "api-7d4b9",
phase: "Running",
ready: "1/1",
restarts: 1,
node: "kiri-k8s",
created: "2026-11-25T10:00:00Z",
containers: [{ name: "api", image: "app:1", state: "running", ready: true, restarts: 1 }],
}],
services: [],
});
show("pods");
openPod("default/api-7d4b9", "logs");
const key = "default/api-7d4b9/api";
kiri.on({
type: "k8slogs",
key,
parts: [
{ t: "2026-11-25T10:00:01Z INFO boot ready\r\n2026-11-25T10:00:02Z WARN slow query\n", e: false },
{ t: "2026-11-25T10:00:03Z ERROR connection dropped\n", e: true },
],
});
t("pod logs render in .console.numbered with line numbers, level classes, and count", () => {
const klog = document.querySelector("#dbody .console.numbered");
if (!klog) throw new Error("missing .console.numbered on pod logs");
const rows = [...klog.children];
eq(rows.map((r) => r.dataset.n), ["1", "2", "3"], "line numbers");
eq([rows[1].className, rows[2].className], ["lvl-warn", "lvl-error"], "level classes");
eq(document.querySelector("#klog-count")?.textContent, tr("{all} lines", { all: "3" }), "line count");
});
t("selecting pod logs omits line numbers", () => {
const klog = document.querySelector("#dbody .console.numbered");
getSelection().selectAllChildren(klog);
eq(
getSelection().toString().trim().split("\n"),
["2026-11-25T10:00:01Z INFO boot ready", "2026-11-25T10:00:02Z WARN slow query", "2026-11-25T10:00:03Z ERROR connection dropped"],
"copied lines",
);
getSelection().removeAllRanges();
});
t("filtering and clearing pod logs share uniform behavior and reset numbering", () => {
const klog = document.querySelector("#dbody .console.numbered");
const filter = document.querySelector("#klog-filter");
filter.value = "warn";
filter.dispatchEvent(new Event("input", { bubbles: true }));
const visible = [...klog.children].filter((r) => !r.classList.contains("hide"));
eq(visible.map((r) => r.dataset.n), ["2"], "filtered visible line");
filter.value = "";
filter.dispatchEvent(new Event("input", { bubbles: true }));
document.querySelector("[data-klogclear]").click();
eq(klog.childElementCount, 0, "cleared");
kiri.on({ type: "k8slogs", key, parts: [{ t: "restarted line\n", e: false }] });
eq(klog.firstElementChild?.dataset.n, "1", "restarted line number");
});
report(R);