From be4b41687109c641fac9e202a6ce43887d136dc6 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Fri, 27 Nov 2026 06:58:29 +0100 Subject: [PATCH 1/2] Start: evict stale VmLink::layers cache and re-send missing unpacked layers --- crates/kiri/src/daemon/engine.rs | 45 +++++++++++++++++++++++++++++--- crates/kiri/src/daemon/vmlink.rs | 28 ++++++++++++++++++++ docs/fix-registry.md | 6 +++++ 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 2e858e732..be502b8ef 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -4296,7 +4296,6 @@ impl Engine { let mut opts = net_opts(&spec, joined.as_deref(), &domainname); opts.extend(net6_opts); opts.extend(pid_joined.map(|t| format!("{}={t}", kiri_proto::net_opts::PIDNS))); - let net_args = kiri_proto::Net { bridge: &bridge, ip, prefix, gateway, extra_hosts: &hosts, dns_names: &dns_names, opts: &opts }; // Joining a host-network container is the host's namespace too: its // net.* sysctls would change the whole VM (or Linux host). let joined_host = joined_mode.is_some_and(|m| self.lock_networks().find(&m).is_some_and(|n| n.driver == "host")); @@ -4340,11 +4339,34 @@ impl Engine { return Err(e); } let cancelled = || gate.0.cancel.load(std::sync::atomic::Ordering::SeqCst); - let started = if cancelled() { + let run_once = || { + let net_args = kiri_proto::Net { bridge: &bridge, ip, prefix, gateway, extra_hosts: &hosts, dns_names: &dns_names, opts: &opts }; + vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp, &gate.0.cancel) + }; + let mut started = if cancelled() { Err(io::Error::other("cancelled before it reached the guest")) } else { - vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp, &gate.0.cancel) + run_once() }; + // `VmLink::layers` avoids redundant `LayerQuery` round-trips on hot starts; + // if an unpacked layer was deleted on the guest's disk while the VM stayed + // up (`start-restores-layer`), evict its cached digests, re-query/re-send + // the missing layer(s), and retry once. + if let Err(ref e) = started + && !cancelled() + && is_missing_unpacked_layer_error(&e.to_string()) + { + vm.forget_layers(&layers); + if let Err(restore_err) = self.restore_layers(&vm, &layers) { + self.fail_start(&id, &spec, &restore_err); + return Err(restore_err); + } + started = if cancelled() { + Err(io::Error::other("cancelled before it reached the guest")) + } else { + run_once() + }; + } if let Ok(pid) = started && let Some(c) = self.lock().containers.get_mut(&id).filter(|c| c.status == Status::Running) { @@ -10683,4 +10705,21 @@ mod exit_forwards_tests { drop(engine); let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn detects_guest_missing_unpacked_layer_error() { + assert!(super::is_missing_unpacked_layer_error( + "run f0991bd92f25: layer sha256:821d9dafb26dc8e4afce2273366520f49e38f8f679a72fc512f2a83e62f442b7 is not unpacked" + )); + assert!(super::is_missing_unpacked_layer_error("layer sha256:0123 is not unpacked")); + assert!(!super::is_missing_unpacked_layer_error("run c1: mount /payload: No space left on device")); + assert!(!super::is_missing_unpacked_layer_error("the VM stopped")); + } +} + +/// Whether a guest `Run` error reports that an image layer was missing under +/// `/var/lib/kiri/layers` (`kiri-init`'s `roots::acquire` formats this as +/// `"layer is not unpacked"`). +fn is_missing_unpacked_layer_error(msg: &str) -> bool { + msg.contains("layer sha256:") && msg.ends_with(" is not unpacked") } diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index 8ecc4afdd..fb2bc8974 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -854,6 +854,16 @@ impl VmLink { self.send(|o| kiri_proto::encode_retain(o, ids)) } + /// Evicts `digests` from the in-memory unpacked-layer cache so the next + /// `has_layer` asks the guest directly (used when `run` reports a layer + /// missing on disk inside a running guest). + pub fn forget_layers(&self, digests: &[String]) { + let mut cached = self.layers.lock().unwrap_or_else(|e| e.into_inner()); + for d in digests { + cached.remove(d.as_str()); + } + } + /// Tells the guest which unpacked layers are still used; it deletes the rest. pub fn retain_layers(&self, digests: &[String]) -> io::Result<()> { { @@ -1271,4 +1281,22 @@ mod tests { assert!(contender_err.to_string().contains("the VM stopped") || contender_err.kind() == io::ErrorKind::TimedOut, "{contender_err}"); assert!(channel.windows.is_lost(), "reader exited after SHUT_RDWR"); } + + #[test] + fn forget_layers_evicts_only_requested_digests() { + let layers = Mutex::new(std::collections::HashSet::from([ + "sha256:aaa".to_owned(), + "sha256:bbb".to_owned(), + "sha256:ccc".to_owned(), + ])); + { + let mut cached = layers.lock().unwrap(); + for d in &["sha256:aaa".to_owned(), "sha256:ccc".to_owned()] { + cached.remove(d.as_str()); + } + } + let left = layers.into_inner().unwrap(); + assert_eq!(left.len(), 1); + assert!(left.contains("sha256:bbb")); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index ca598cdfa..fbc82e9fb 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### Start: evict stale `VmLink::layers` entries and re-send layers when `run` reports `"is not unpacked"` (unreleased) +- Fixes: `start-restores-layer` (`docker start` failed with `layer sha256:… is not unpacked` when an unpacked layer directory disappeared on the guest's disk without a VM restart) +- Caused: none known +- Caused by: #776 +- Check: `start-restores-layer`, `crates/kiri/src/daemon/engine.rs` + ### #602 macOS: spawn daemon directly when LaunchAgent `kickstart` exits 0 without starting engine (unreleased) - Fixes: #602 Clicking Start on macOS does nothing when `launchctl kickstart` exits 0 without starting `kiri daemon` - Caused: none known From 17e2ed57c5f5f51e1bbdb0969a94e09b35175570 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Fri, 27 Nov 2026 08:14:51 +0100 Subject: [PATCH 2/2] Engine & CLI: fix macOS k8s idle CPU (#989) and add kiri engine commands (#983) --- crates/kiri-init/src/linux/container.rs | 36 +- crates/kiri-init/src/linux/hostopts.rs | 18 + crates/kiri-win/src/engine.rs | 10 + crates/kiri-win/src/refuse.rs | 39 +- crates/kiri-win/src/serve.rs | 15 + crates/kiri/src/client.rs | 14 + crates/kiri/src/daemon/engine.rs | 262 +++++++-- crates/kiri/src/engine_cli.rs | 733 ++++++++++++++++++++++++ crates/kiri/src/main.rs | 50 +- crates/kiri/src/wsl.rs | 65 ++- docs/features.md | 4 +- docs/fix-registry.md | 12 + tests/regressions.tsv | 4 + 13 files changed, 1165 insertions(+), 97 deletions(-) create mode 100644 crates/kiri/src/engine_cli.rs diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index a49526523..9f6a0be18 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -328,6 +328,8 @@ struct Prepared { init: bool, /// `--cgroupns host`: no cgroup namespace of its own. cgroupns_host: bool, + /// Timer slack in nanoseconds for the container's PID 1 (`timerslack_ns`). + timer_slack_ns: Option, /// Ulimits, groups and device nodes from the `opts` lines. host: HostApplied, /// The child's end of the pipe that says its root is in place (mounts @@ -618,6 +620,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, env: StrList<'_>, cwd: &str, user: &str, hostname: shm_size: 64 << 20, init: flags & run_flags::INIT != 0, cgroupns_host: false, + timer_slack_ns: None, host: HostApplied::default(), root_ready: None, cgroup_ready: None, @@ -2541,6 +2545,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { shm_size: _, init: _, cgroupns_host: _, + timer_slack_ns: _, // Paths, numbers and names only. host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ }, root_ready, @@ -2779,6 +2784,11 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { // While still root with every capability: raising a hard limit needs // CAP_SYS_RESOURCE. apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e)); + if console + && let Some(ns) = p.timer_slack_ns + { + apply_timer_slack(ns); + } for cap in 0..=LAST_CAP { if !p.privileged && p.caps & (1 << cap) == 0 { @@ -2881,6 +2891,22 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { sys::exec_fail(2, &exe, io::Error::last_os_error(), false) } +/// Applies timer slack (`ns`) to the container's PID 1 before `execve`. +/// Writing `/proc/self/timerslack_ns` updates both `timer_slack_ns` and +/// `default_timer_slack_ns` in Linux (`fs/proc/base.c`), so the slack survives +/// `execve` into `/bin/k3s` and coalesces staggered sub-100 ms tickers (#989). +fn apply_timer_slack(ns: u64) { + let _ = apply_timer_slack_to(Path::new("/proc/self/timerslack_ns"), ns); + // SAFETY: `PR_SET_TIMERSLACK` takes the slack in nanoseconds as `arg2`. + unsafe { + libc::prctl(libc::PR_SET_TIMERSLACK, ns as libc::c_ulong, 0, 0, 0); + } +} + +fn apply_timer_slack_to(path: &Path, ns: u64) -> io::Result<()> { + fs::write(path, ns.to_string()) +} + /// How the container's root is remounted once it is `/`, if at all: /// read-only for `--read-only`, and `nodev` when the device filter could not /// be attached. Without the filter, a block or character device node that an @@ -4747,14 +4773,22 @@ mod tests { fn hostopts_cgroupns_host_is_parsed_cleanly() { let mut buf = Vec::new(); let net = Net { bridge: "", ip: [0; 4], prefix: 0, gateway: [0; 4], extra_hosts: &[], dns_names: &[], opts: &[] }; - encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost"], &[]); + encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost", "timerslack\t10000000"], &[]); let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() }; let parsed = super::super::hostopts::parse(spec.opts).unwrap(); assert!(parsed.cgroupns_host); + assert_eq!(parsed.timer_slack_ns, Some(10_000_000)); let mut prepared = super::prepare(spec.argv, spec.env, spec.cwd, spec.user, Some(spec.hostname), spec.flags, spec.caps).unwrap(); assert!(!prepared.cgroupns_host); + assert_eq!(prepared.timer_slack_ns, None); prepared.cgroupns_host = parsed.cgroupns_host; + prepared.timer_slack_ns = parsed.timer_slack_ns; assert!(prepared.cgroupns_host); + assert_eq!(prepared.timer_slack_ns, Some(10_000_000)); + let tmp = std::env::temp_dir().join(format!("kiri-timerslack-{}", std::process::id())); + super::apply_timer_slack_to(&tmp, 10_000_000).unwrap(); + assert_eq!(std::fs::read_to_string(&tmp).unwrap(), "10000000"); + let _ = std::fs::remove_file(&tmp); } #[test] diff --git a/crates/kiri-init/src/linux/hostopts.rs b/crates/kiri-init/src/linux/hostopts.rs index 2c2d56e52..46b62a4a3 100644 --- a/crates/kiri-init/src/linux/hostopts.rs +++ b/crates/kiri-init/src/linux/hostopts.rs @@ -69,6 +69,9 @@ pub struct HostOpts { /// `--cgroupns host`: share the agent's cgroup namespace instead of /// unsharing one rooted at the container's cgroup. pub cgroupns_host: bool, + /// Timer slack (`timerslack_ns`, in nanoseconds) applied to the container's + /// init process so high-frequency background pollers coalesce cleanly (#989). + pub timer_slack_ns: Option, } fn bad(line: &str) -> io::Error { @@ -131,6 +134,13 @@ pub fn parse(list: StrList<'_>) -> io::Result { *(if *kind == "masked" { &mut o.masked } else { &mut o.readonly }) = Some(paths); } ["cgroupns", "host"] => o.cgroupns_host = true, + ["timerslack", ns] => { + let ns: u64 = ns.parse().map_err(|_| bad(line))?; + if ns == 0 || ns > 1_000_000_000 { + return Err(bad(line)); + } + o.timer_slack_ns = Some(ns); + } _ => return Err(bad(line)), } } @@ -466,6 +476,10 @@ mod tests { assert_eq!(o.masked, Some(vec![])); assert_eq!(o.readonly, Some(vec![c"/proc/sys".to_owned(), c"/data".to_owned()])); assert!(o.cgroupns_host); + assert_eq!(o.timer_slack_ns, None); + let buf = list(&["timerslack\t10000000"]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert_eq!(parse(l).unwrap().timer_slack_ns, Some(10_000_000)); for bad_path in ["masked\tproc/kcore", "masked\t/../etc", "readonly\t/proc/../etc"] { let buf = list(&[bad_path]); let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; @@ -480,6 +494,10 @@ mod tests { "cgroupns", "cgroupns\tprivate", "cgroupns\tbogus", + "timerslack", + "timerslack\t0", + "timerslack\t1000000001", + "timerslack\tnope", "nope", ] { let buf = list(&[bad]); diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 51f9e83a6..6d7ecc25f 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -200,6 +200,16 @@ pub(crate) fn on_external_wake() { send(Cmd::Refresh); } +/// Called after an external `POST /kiri/stop` (`kiri engine stop`) stops the +/// WSL daemon through the named pipe: marks `kiri-win` stopped immediately so +/// subsequent pipe/status checks see the stopped gate without a race, then +/// tells the engine thread to tear down bridges/relays, terminate Kiri's +/// dedicated WSL distro, and update the window and tray (#983). +pub(crate) fn on_external_stop() { + crate::serve::set_stopped(true); + send(Cmd::Stop); +} + fn engine(rx: &Receiver, tx: Sender) { watch(tx); // Windows' proxy and root certificates for the daemon, now and every diff --git a/crates/kiri-win/src/refuse.rs b/crates/kiri-win/src/refuse.rs index cae6a664f..7a1df3030 100644 --- a/crates/kiri-win/src/refuse.rs +++ b/crates/kiri-win/src/refuse.rs @@ -28,9 +28,7 @@ fn strip_version(path: &str) -> &str { path } -/// Whether the first HTTP request line in `request` is `POST /kiri/wake` -/// (or versioned `POST /v*/kiri/wake`). -pub fn is_wake_request(request: &[u8]) -> bool { +fn matches_post_endpoint(request: &[u8], endpoint: &str) -> bool { let line_end = request.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(request.len().min(1024)); let Ok(line) = std::str::from_utf8(&request[..line_end]) else { return false; @@ -48,7 +46,19 @@ pub fn is_wake_request(request: &[u8]) -> bool { return false; } let path = target.split('?').next().unwrap_or(target); - strip_version(path) == "/kiri/wake" + strip_version(path) == endpoint +} + +/// Whether the first HTTP request line in `request` is `POST /kiri/wake` +/// (or versioned `POST /v*/kiri/wake`). +pub fn is_wake_request(request: &[u8]) -> bool { + matches_post_endpoint(request, "/kiri/wake") +} + +/// Whether the first HTTP request line in `request` is `POST /kiri/stop` +/// (or versioned `POST /v*/kiri/stop`). +pub fn is_stop_request(request: &[u8]) -> bool { + matches_post_endpoint(request, "/kiri/stop") } /// Returns `Some(d)` only when `distro` is Kiri's dedicated bundled distro @@ -66,6 +76,9 @@ pub enum GateDecision { /// Engine was stopped and the request is `POST /kiri/wake` (or `/v*/kiri/wake`): /// gate and marker are now cleared; forward the already-read request bytes. Wake, + /// Engine is already stopped and the request is `POST /kiri/stop`: reply + /// HTTP 204 No Content immediately without spawning `wsl.exe`. + AlreadyStopped, /// Engine is stopped and the request is not a wake: reply HTTP 503 with /// [`STOPPED`] without spawning `wsl.exe`. Refuse, @@ -121,6 +134,8 @@ impl StoppedGate { if is_wake_request(first_request) { self.set(false, marker); GateDecision::Wake + } else if is_stop_request(first_request) { + GateDecision::AlreadyStopped } else { GateDecision::Refuse } @@ -288,6 +303,12 @@ mod tests { let after_start = StoppedGate::new(); assert!(!after_start.init_from(Some(&marker))); + // POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker. + gate.set(true, Some(&marker)); + assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + let _ = std::fs::remove_dir_all(&dir); } @@ -309,6 +330,10 @@ mod tests { assert!(!is_wake_request(b"GET /v1.47/containers/json HTTP/1.1\r\n\r\n")); assert!(!is_wake_request(b"POST /containers/create HTTP/1.1\r\n\r\n")); assert!(!is_wake_request(b"POST /kiri/stop HTTP/1.1\r\n\r\n")); + assert!(is_stop_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_stop_request(b"POST /v1.47/kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(!is_stop_request(b"GET /kiri/stop HTTP/1.1\r\n\r\n")); + assert!(!is_stop_request(b"POST /kiri/wake HTTP/1.1\r\n\r\n")); assert!(!is_wake_request(b"POST /kiri/wake/extra HTTP/1.1\r\n\r\n")); assert!(!is_wake_request(b"POST /v/kiri/wake HTTP/1.1\r\n\r\n")); assert!(!is_wake_request(b"POST /v./kiri/wake HTTP/1.1\r\n\r\n")); @@ -352,6 +377,12 @@ mod tests { assert!(!gate.is_stopped()); assert!(!marker.exists()); + // POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker. + gate.set(true, Some(&marker)); + assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 56165b63e..3adb65122 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -1816,6 +1816,15 @@ fn serve_shared(hub: &Hub, pipe: Arc) { prefetched = Some(first); woke = true; } + crate::refuse::GateDecision::AlreadyStopped => { + if pipe.write(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").is_ok() { + pipe.flush(); + if !pipe.is_aborted() && pipe.write(&[]).is_ok() { + linger(pipe); + } + } + return; + } crate::refuse::GateDecision::Refuse => { if refuse(pipe, is_head(&first), crate::refuse::STOPPED) { linger(pipe); @@ -1981,6 +1990,7 @@ fn serve_shared(hub: &Hub, pipe: Arc) { let writer = thread::spawn(move || to_client(&p, &rx, &queued, &b, w.as_deref().map(|w| (id, w)), &r, &po)); let mut buf = vec![0u8; 64 * 1024]; let mut first_chunk = true; + let mut stopped_req = false; let end = loop { let from_prefetch = prefetched.take(); let chunk: &[u8] = match from_prefetch.as_deref() { @@ -1995,6 +2005,9 @@ fn serve_shared(hub: &Hub, pipe: Arc) { let n = chunk.len(); if first_chunk { first_chunk = false; + if crate::refuse::is_stop_request(chunk) { + stopped_req = true; + } if crate::ports::is_port_affecting_request(chunk) { port_op.store(true, Ordering::SeqCst); crate::ports::before_container_op(); @@ -2032,6 +2045,8 @@ fn serve_shared(hub: &Hub, pipe: Arc) { let replies_ended = writer.join().unwrap_or(false); if woke && HUB.get().is_some() { crate::engine::on_external_wake(); + } else if stopped_req && HUB.get().is_some() { + crate::engine::on_external_stop(); } if port_op.load(Ordering::Relaxed) { crate::ports::notify(); diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index 494794ec5..7b80ce4d9 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -526,6 +526,20 @@ fn check_alive_at(sock: &Path, not_running: &str) -> io::Result<()> { } } +#[cfg(unix)] +pub(crate) fn probe_socket(sock: &Path) -> io::Result<()> { + check_alive_at(sock, not_running_message()) +} + +#[cfg(unix)] +pub(crate) fn get_background_at(sock: &Path, path: &str) -> io::Result { + let r = send_to(sock, "GET", path, None, "X-Kiri-Background: 1\r\n")?; + if !r.ok() { + return Err(io::Error::other(r.error())); + } + Ok(r.json()) +} + /// Probes the engine socket, distinguishing `PermissionDenied` (`EACCES`) from /// the daemon not running and formatting OS-appropriate guidance. pub fn check_alive() -> io::Result<()> { diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index be502b8ef..2c693bb95 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -2326,8 +2326,9 @@ impl Engine { /// `kiri k8s`: every LoadBalancer service gets its port on the Mac's /// localhost, as OrbStack and Docker Desktop do. k3s's service load /// balancer already serves the port on the node, so a forward to the - /// node container is all it takes. Checked every few seconds while the - /// cluster runs; forwards go when services or the cluster do. + /// node container is all it takes. Reconciled once on cluster start and + /// then driven by a single `kubectl get svc -A --watch-only` stream so an + /// idle cluster never spawns periodic `/bin/k3s` processes (#989). fn start_k8s_lb(self: &Arc) { let me = Arc::downgrade(self); // `kiri k8s set --lan on` puts them on every interface; a change rebinds them. @@ -2335,56 +2336,118 @@ impl Engine { let _ = std::thread::Builder::new().name("kiri-k8s-lb".into()).spawn(move || loop { std::thread::sleep(Duration::from_secs(3)); let Some(engine) = me.upgrade() else { return }; - let node = engine.lock().containers.values().find(|c| c.status == Status::Running && c.spec.labels.get("dev.kiri.k8s").is_some()).map(|c| (c.id.clone(), c.ip)); + let node = engine.lock().containers.values().find(|c| c.status == Status::Running && is_k8s_node(&c.spec)).map(|c| (c.id.clone(), c.ip)); let Some((id, Some(ip))) = node else { - engine.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); - engine.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); - if let Some((_, via)) = engine.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take() - && let Some(vm) = engine.awake() - { - for (net, bits) in K8S_RANGES { - let _ = vm.route(net, bits, via, false); - } - } + engine.clear_k8s_lb(); continue; }; - engine.route_k8s(ip); - let query = r#"jsonpath={range .items[?(@.spec.type=="LoadBalancer")]}{range .spec.ports[*]}{.port}/{.protocol} {end}{end}"#; - let Ok((0, out)) = engine.exec_capture(&id, &["timeout", "-s", "KILL", "20", "kubectl", "get", "svc", "-A", "-o", query]) else { continue }; - let wanted: Vec<(u16, String)> = out - .split_whitespace() - .filter_map(|p| { - let (port, proto) = p.split_once('/')?; - Some((port.parse().ok()?, proto.to_ascii_lowercase())) - }) - .collect(); - let Some(vm) = engine.awake() else { continue }; - let host_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; - let mut lb = engine.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()); - if vm.is_disconnected() { + if !engine.reconcile_k8s_lb(&id, ip, &mut bound_on) { continue; } - if bound_on != host_ip { - lb.clear(); - bound_on = host_ip.to_owned(); - } - lb.retain(|k, _| wanted.contains(k)); - for (port, proto) in wanted { - if lb.contains_key(&(port, proto.clone())) { - continue; - } - let b = super::ports::Binding { container_port: port, proto: proto.clone(), host_ip: host_ip.into(), host_port: port }; - match super::ports::start(vm.clone(), &format!("lb-{port}-{proto}"), &[b], ip) { - Ok(fw) => { - crate::diag::info!("Kubernetes service published", at = format!("{host_ip}:{port}/{proto}")); - lb.insert((port, proto), fw); + let watch_cfg = ExecConfig { + console_size: None, + argv: ["kubectl", "get", "svc", "-A", "--watch-only", "--no-headers"].map(String::from).to_vec(), + env: Vec::new(), + cwd: "/".into(), + user: String::new(), + tty: false, + stdin: false, + privileged: false, + internal: true, + }; + let Ok(watch_id) = engine.exec_create(&id, watch_cfg) else { continue }; + let Ok((_, rx)) = engine.exec_start(&watch_id) else { + engine.lock().execs.remove(&watch_id); + continue; + }; + loop { + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(_) => { + // Coalesce bursts of service updates into a single reconciliation. + while rx.recv_timeout(Duration::from_millis(150)).is_ok() {} + let Some(engine) = me.upgrade() else { return }; + let still_up = engine.lock().containers.get(&id).is_some_and(|c| c.status == Status::Running && c.ip == Some(ip)); + if !still_up { + engine.clear_k8s_lb(); + break; + } + let _ = engine.reconcile_k8s_lb(&id, ip, &mut bound_on); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + let Some(engine) = me.upgrade() else { return }; + let still_up = engine.lock().containers.get(&id).is_some_and(|c| c.status == Status::Running && c.ip == Some(ip)); + if !still_up { + engine.clear_k8s_lb(); + break; + } + let want_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; + if bound_on != want_ip { + let _ = engine.reconcile_k8s_lb(&id, ip, &mut bound_on); + } } - Err(e) => crate::diag::warn!("Kubernetes service port not published", port = format!("{port}/{proto}"), error = e), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, } } + if let Some(engine) = me.upgrade() { + engine.lock().execs.remove(&watch_id); + } else { + return; + } }); } + fn clear_k8s_lb(&self) { + self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); + if let Some((_, via)) = self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take() + && let Some(vm) = self.awake() + { + for (net, bits) in K8S_RANGES { + let _ = vm.route(net, bits, via, false); + } + } + } + + fn reconcile_k8s_lb(&self, id: &str, ip: [u8; 4], bound_on: &mut String) -> bool { + self.route_k8s(ip); + let query = r#"jsonpath={range .items[?(@.spec.type=="LoadBalancer")]}{range .spec.ports[*]}{.port}/{.protocol} {end}{end}"#; + let Ok((0, out)) = self.exec_capture(id, &["timeout", "-s", "KILL", "20", "kubectl", "get", "svc", "-A", "-o", query]) else { + return false; + }; + let wanted: Vec<(u16, String)> = out + .split_whitespace() + .filter_map(|p| { + let (port, proto) = p.split_once('/')?; + Some((port.parse().ok()?, proto.to_ascii_lowercase())) + }) + .collect(); + let Some(vm) = self.awake() else { return false }; + let host_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; + let mut lb = self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()); + if vm.is_disconnected() { + return false; + } + if bound_on != host_ip { + lb.clear(); + *bound_on = host_ip.to_owned(); + } + lb.retain(|k, _| wanted.contains(k)); + for (port, proto) in wanted { + if lb.contains_key(&(port, proto.clone())) { + continue; + } + let b = super::ports::Binding { container_port: port, proto: proto.clone(), host_ip: host_ip.into(), host_port: port }; + match super::ports::start(vm.clone(), &format!("lb-{port}-{proto}"), &[b], ip) { + Ok(fw) => { + crate::diag::info!("Kubernetes service published", at = format!("{host_ip}:{port}/{proto}")); + lb.insert((port, proto), fw); + } + Err(e) => crate::diag::warn!("Kubernetes service port not published", port = format!("{port}/{proto}"), error = e), + } + } + true + } + /// Routes the cluster's pod and service ranges to the node, so the /// relay can reach a ClusterIP or a pod as it reaches a container: the /// node's kube-proxy takes it from there. Again after the VM wakes (a new @@ -2740,14 +2803,17 @@ impl Engine { } /// The Mac folders and files that running containers bind-mount, as - /// the Mac keeps them (the guest sees them under /mnt/mac). + /// the Mac keeps them (the guest sees them under /mnt/mac). Excludes the + /// `kiri-k8s` node container (`dev.kiri.k8s`), which mounts `/Users` and + /// `/Volumes` whole for pod `hostPath` access and would otherwise attach a + /// 50 ms `FSEvents` stream across the entire Mac filesystem (#989). #[cfg(target_os = "macos")] pub fn mac_bind_sources(&self) -> Vec { let mut out: Vec = self .lock() .containers .values() - .filter(|c| c.status == Status::Running) + .filter(|c| watches_host_binds(c)) .flat_map(|c| c.spec.mounts.iter()) .filter_map(|m| m.split('\t').next()?.strip_prefix("/mnt/mac").filter(|p| p.starts_with('/')).map(str::to_owned)) .collect(); @@ -2780,13 +2846,14 @@ impl Engine { } /// The WSL drive bind sources (`/mnt/` or `/mnt//...`) of - /// running containers, under `automount_root` (e.g. `/mnt/`). + /// running containers, under `automount_root` (e.g. `/mnt/`). Excludes the + /// `kiri-k8s` node container (`dev.kiri.k8s`), which mounts `/mnt` whole. pub fn wsl_bind_sources(&self, automount_root: &str) -> Vec { let mut out: Vec = self .lock() .containers .values() - .filter(|c| c.status == Status::Running) + .filter(|c| watches_host_binds(c)) .flat_map(|c| c.spec.mounts.iter()) .filter_map(|m| { let src = m.split('\t').next()?; @@ -4299,13 +4366,16 @@ impl Engine { // Joining a host-network container is the host's namespace too: its // net.* sysctls would change the whole VM (or Linux host). let joined_host = joined_mode.is_some_and(|m| self.lock_networks().find(&m).is_some_and(|n| n.driver == "host")); - let host_opts = match spec.guest_opts(flags & run_flags::NET_HOST != 0 || joined_host) { + let mut host_opts = match spec.guest_opts(flags & run_flags::NET_HOST != 0 || joined_host) { Ok(o) => o, Err(e) => { self.fail_start(&id, &spec, &e); return Err(e); } }; + if let Some(opt) = k8s_timer_slack_opt(&spec) { + host_opts.push(opt); + } if let Err(e) = self.restore_layers(&vm, &layers) { self.fail_start(&id, &spec, &e); return Err(e); @@ -10715,6 +10785,106 @@ mod exit_forwards_tests { assert!(!super::is_missing_unpacked_layer_error("run c1: mount /payload: No space left on device")); assert!(!super::is_missing_unpacked_layer_error("the VM stopped")); } + + /// Regression test for #989: `kiri-k8s` (`dev.kiri.k8s`) bind-mounts `/Users` + /// and `/Volumes` on macOS (and `/mnt` on Linux/WSL) for pod `hostPath` + /// access, which must NOT cause `mac_bind_sources` or `wsl_bind_sources` to + /// watch the entire host filesystem, while ordinary containers keep theirs; + /// and `k8s_timer_slack_opt` sets 10 ms timer coalescing only for `kiri-k8s`. + #[test] + fn k8s_node_skips_host_bind_watchers_and_gets_timer_slack() { + let (engine, app_id, dir) = engine_running("k8s-bind-watch"); + { + let mut st = engine.lock(); + let app = st.containers.get_mut(&app_id).unwrap(); + app.spec.mounts = vec![ + "/mnt/mac/Users/alice/app\t/app\t".into(), + "/mnt/c/Users/alice/app\t/win\t".into(), + ]; + assert_eq!(super::k8s_timer_slack_opt(&app.spec), None); + + let mut k8s = Container { + lifecycle: Arc::new(Mutex::new(0)), + names_sync: Arc::default(), + start_gate: Arc::default(), + id: "k8s00000000000000000000000000000".into(), + name: "kiri-k8s".into(), + layers: Vec::new(), + spec: app.spec.clone(), + created: SystemTime::now(), + status: Status::Running, + started: Some(SystemTime::now()), + finished: None, + exit_code: 0, + oom_killed: false, + vm_stopped: false, + stopped_by_user: false, + restart_count: 0, + restart_pending: false, + exits: 0, + size: None, + ip: None, + pid: 42, + forwards: None, + paused: false, + extra_ips: Vec::new(), + first_if: None, + extra_ifs: Vec::new(), + ip6: None, + extra_ip6s: Vec::new(), + live: true, + early_input: Vec::new(), + early_close: false, + start_owed: false, + log: Arc::new(Mutex::new(super::super::logfile::Log::new( + super::super::logfile::dir(engine.store.root(), "k8s00000000000000000000000000000"), + &app.spec.log_config, + ))), + attached: Vec::new(), + }; + k8s.spec.labels = serde_json::json!({"dev.kiri.k8s": "1"}); + k8s.spec.mounts = vec![ + "/mnt/mac/Users\t/Users\t".into(), + "/mnt/mac/Volumes\t/Volumes\t".into(), + "/mnt/c\t/mnt/c\t".into(), + ]; + assert_eq!( + super::k8s_timer_slack_opt(&k8s.spec).as_deref(), + Some("timerslack\t10000000") + ); + st.containers.insert(k8s.id.clone(), k8s); + } + + #[cfg(target_os = "macos")] + assert_eq!(engine.mac_bind_sources(), vec!["/Users/alice/app".to_owned()]); + assert_eq!(engine.wsl_bind_sources("/mnt/"), vec!["/mnt/c/Users/alice/app".to_owned()]); + + // When only `kiri-k8s` runs, no host bind watcher roots remain at all. + engine.lock().containers.get_mut(&app_id).unwrap().status = Status::Exited; + #[cfg(target_os = "macos")] + assert!(engine.mac_bind_sources().is_empty()); + assert!(engine.wsl_bind_sources("/mnt/").is_empty()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } +} + +/// 10 ms timer slack applied to `kiri-k8s` (`dev.kiri.k8s`) so `k3s`'s dozens of +/// staggered 100 ms `watch_progress` / `kine` / `cAdvisor` timers coalesce +/// cleanly instead of waking virtual CPUs thousands of times per second (#989). +const K8S_TIMER_SLACK_NS: u64 = 10_000_000; + +fn is_k8s_node(spec: &Spec) -> bool { + spec.labels.get("dev.kiri.k8s").is_some() +} + +fn watches_host_binds(c: &Container) -> bool { + c.status == Status::Running && !is_k8s_node(&c.spec) +} + +fn k8s_timer_slack_opt(spec: &Spec) -> Option { + is_k8s_node(spec).then(|| format!("timerslack\t{K8S_TIMER_SLACK_NS}")) } /// Whether a guest `Run` error reports that an image layer was missing under diff --git a/crates/kiri/src/engine_cli.rs b/crates/kiri/src/engine_cli.rs new file mode 100644 index 000000000..fa76c94bb --- /dev/null +++ b/crates/kiri/src/engine_cli.rs @@ -0,0 +1,733 @@ +//! `kiri engine start | stop | restart | status [--json]`: start, stop, restart +//! and inspect Kiri's engine from the terminal (#983). +//! +//! `status` uses background requests (`X-Kiri-Background: 1`, and on Windows +//! checks `%LOCALAPPDATA%\Kiri\stopped` and `wsl --list --running --quiet` +//! before querying WSL without `kiri-start`), so inspecting engine status never +//! wakes a sleeping VM or boots a stopped WSL distro. Exits 0 when the engine +//! is `running` or `asleep`, and exits 1 when `stopped` or `not_running`. + +use std::io; + +use serde::Serialize; +use serde_json::Value; + +use crate::client; + +pub const USAGE: &str = "\ +usage: kiri engine start start Kiri's engine (waking the VM and held containers) + kiri engine stop stop containers and Kiri's engine until `kiri engine start` + kiri engine restart restart Kiri's engine (applying updated VM settings) + kiri engine status [--json] inspect engine state without waking a sleeping VM (exit 1 when stopped or not running)"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Action { + Help, + Start, + Stop, + Restart, + Status { json: bool }, +} + +pub(crate) fn parse_args(args: &[String]) -> io::Result { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + return Ok(Action::Help); + } + let words: Vec<&str> = args.iter().map(String::as_str).collect(); + match words.as_slice() { + ["start"] => Ok(Action::Start), + ["stop"] => Ok(Action::Stop), + ["restart"] => Ok(Action::Restart), + ["status"] => Ok(Action::Status { json: false }), + ["status", "--json"] => Ok(Action::Status { json: true }), + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum EngineState { + Running, + Asleep, + Stopped, + NotRunning, +} + +impl EngineState { + pub(crate) fn is_healthy(self) -> bool { + matches!(self, EngineState::Running | EngineState::Asleep) + } + + pub(crate) fn label(self) -> &'static str { + match self { + EngineState::Running => "running", + EngineState::Asleep => "asleep", + EngineState::Stopped => "stopped", + EngineState::NotRunning => "not running", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct StatusReport { + pub state: EngineState, + pub awake: bool, + pub stopped: bool, + pub version: Option, + pub api_version: Option, + pub cpus: Option, + pub memory_bytes: Option, + pub containers_running: Option, + pub containers_stopped: Option, + pub socket: String, +} + +impl StatusReport { + pub(crate) fn not_running(socket: impl Into) -> Self { + Self { + state: EngineState::NotRunning, + awake: false, + stopped: false, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: socket.into(), + } + } + + pub(crate) fn stopped_offline(socket: impl Into) -> Self { + Self { + state: EngineState::Stopped, + awake: false, + stopped: true, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: socket.into(), + } + } + + pub(crate) fn from_daemon(socket: impl Into, info: &Value, version: Option<&Value>) -> Self { + let stopped = info["KiriStopped"].as_bool().unwrap_or(false); + let awake = !stopped && info["KiriVmAwake"].as_bool().unwrap_or(true); + let state = if stopped { + EngineState::Stopped + } else if awake { + EngineState::Running + } else { + EngineState::Asleep + }; + let kiri_ver = info["KiriVersion"] + .as_str() + .or_else(|| version.and_then(client::kiri_version)) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let api_ver = version + .and_then(|v| v["ApiVersion"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let mem = info["KiriMemoryCeiling"] + .as_u64() + .filter(|&n| n > 0) + .or_else(|| info["MemTotal"].as_u64().filter(|&n| n > 0)); + Self { + state, + awake, + stopped, + version: kiri_ver, + api_version: api_ver, + cpus: info["NCPU"].as_u64().filter(|&n| n > 0), + memory_bytes: mem, + containers_running: info["ContainersRunning"].as_u64(), + containers_stopped: info["ContainersStopped"].as_u64(), + socket: socket.into(), + } + } + + pub(crate) fn format_human(&self) -> String { + let mut head = format!("Kiri engine: {}", self.state.label()); + match self.state { + EngineState::Asleep => head.push_str(" (VM idle; wakes on next request)"), + EngineState::Stopped => head.push_str(" (run `kiri engine start` to start)"), + EngineState::NotRunning => head.push_str(" (run `kiri engine start` or open Kiri)"), + EngineState::Running => {} + } + let mut lines = vec![head]; + if let Some(ver) = &self.version { + match &self.api_version { + Some(api) => lines.push(format!("Version: {ver} (Docker API {api})")), + None => lines.push(format!("Version: {ver}")), + } + } + if let Some(cpus) = self.cpus { + match self.memory_bytes { + Some(bytes) => lines.push(format!("Resources: {cpus} CPUs, {}", format_memory(bytes))), + None => lines.push(format!("Resources: {cpus} CPUs")), + } + } + if let (Some(running), Some(stopped)) = (self.containers_running, self.containers_stopped) { + lines.push(format!("Containers: {running} running, {stopped} stopped")); + } + lines.push(format!("Socket: {}", self.socket)); + lines.join("\n") + } +} + +fn format_memory(bytes: u64) -> String { + const GIB: f64 = (1u64 << 30) as f64; + const MIB: u64 = 1u64 << 20; + if bytes >= (1u64 << 30) && bytes.is_multiple_of(1u64 << 30) { + format!("{} GiB", bytes >> 30) + } else if bytes >= (1u64 << 30) { + format!("{:.1} GiB", bytes as f64 / GIB) + } else { + format!("{} MiB", bytes / MIB.max(1)) + } +} + +pub fn run(args: &[String]) -> io::Result<()> { + match parse_args(args)? { + Action::Help => { + println!("{USAGE}"); + Ok(()) + } + Action::Start => { + start_silent()?; + println!("Kiri engine started"); + Ok(()) + } + Action::Stop => { + if stop_silent()? { + println!("Kiri engine stopped"); + } else { + println!("Kiri engine is already stopped"); + } + Ok(()) + } + Action::Restart => { + restart_silent()?; + println!("Kiri engine restarted"); + Ok(()) + } + Action::Status { json } => { + let report = collect_status()?; + if json { + println!("{}", serde_json::to_string(&report).map_err(io::Error::other)?); + } else { + println!("{}", report.format_human()); + } + if !report.state.is_healthy() { + std::process::exit(1); + } + Ok(()) + } + } +} + +/// `kiri start`: keeps the existing `"Kiri is started"` message for compatibility. +#[cfg(unix)] +pub fn start_legacy() -> io::Result<()> { + start_silent()?; + println!("Kiri is started"); + Ok(()) +} + +// ---- Unix implementation (macOS, Linux, and WSL daemon) ---- + +#[cfg(unix)] +fn start_not_running_message() -> &'static str { + #[cfg(target_os = "macos")] + { + "Kiri's engine isn't running. Open Kiri, or start it with `kiri daemon`" + } + #[cfg(not(target_os = "macos"))] + { + client::not_running_message() + } +} + +#[cfg(unix)] +fn start_silent() -> io::Result<()> { + #[cfg(target_os = "macos")] + if !client::alive() { + if let Ok(d) = crate::daemon::state_dir() { + let _ = std::fs::remove_file(d.join("stopped")); + } + crate::update::start_engine()?; + } + client::check_alive_with(start_not_running_message())?; + let r = client::request("POST", "/kiri/wake", None)?; + if !r.ok() && r.status != 404 { + return Err(io::Error::other(r.error())); + } + Ok(()) +} + +/// Stops containers and Kiri's engine. Returns `Ok(true)` when a running/active +/// engine was stopped, or `Ok(false)` when it was already stopped/not running. +#[cfg(unix)] +fn stop_silent() -> io::Result { + let sock = client::socket()?; + match client::probe_socket(&sock) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(e), + Err(_) => { + #[cfg(target_os = "macos")] + if let Ok(d) = crate::daemon::state_dir() { + let _ = std::fs::create_dir_all(&d); + let _ = std::fs::write(d.join("stopped"), b""); + } + return Ok(false); + } + } + let was_stopped = client::get_background_at(&sock, "/info") + .ok() + .and_then(|v| v["KiriStopped"].as_bool()) + .unwrap_or(false); + let mut r = client::request("POST", "/kiri/stop", None)?; + if r.status == 404 { + r = client::request("POST", "/kiri/sleep", None)?; + } + if !r.ok() { + return Err(io::Error::other(r.error())); + } + Ok(!was_stopped) +} + +#[cfg(unix)] +fn restart_silent() -> io::Result<()> { + #[cfg(target_os = "macos")] + if !client::alive() { + return start_silent(); + } + client::check_alive_with(start_not_running_message())?; + let sleep = client::request("POST", "/kiri/sleep", None)?; + if !sleep.ok() && sleep.status != 404 { + return Err(io::Error::other(sleep.error())); + } + let wake = client::request("POST", "/kiri/wake", None)?; + if !wake.ok() && wake.status != 404 { + return Err(io::Error::other(wake.error())); + } + Ok(()) +} + +#[cfg(unix)] +fn collect_status() -> io::Result { + let sock = client::socket()?; + #[cfg(target_os = "macos")] + let stopped_marker = crate::daemon::state_dir().ok().map(|d| d.join("stopped")); + #[cfg(not(target_os = "macos"))] + let stopped_marker: Option = None; + collect_status_at(&sock, stopped_marker.as_deref()) +} + +#[cfg(unix)] +pub(crate) fn collect_status_at(sock: &std::path::Path, stopped_marker: Option<&std::path::Path>) -> io::Result { + let sock_str = sock.display().to_string(); + match client::probe_socket(sock) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(e), + Err(_) => { + if stopped_marker.is_some_and(std::path::Path::is_file) { + return Ok(StatusReport::stopped_offline(sock_str)); + } + return Ok(StatusReport::not_running(sock_str)); + } + } + let info = client::get_background_at(sock, "/info")?; + let ver = client::get_background_at(sock, "/version").ok(); + Ok(StatusReport::from_daemon(sock_str, &info, ver.as_ref())) +} + +// ---- Windows implementation (`kiri-win` pipe + WSL 2) ---- + +#[cfg(windows)] +fn wsl_exe() -> std::path::PathBuf { + let system = std::env::var_os("SystemRoot") + .map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from); + system.join("System32").join("wsl.exe") +} + +#[cfg(windows)] +fn running_wsl_distros() -> Option> { + let out = std::process::Command::new(wsl_exe()) + .args(["--list", "--running", "--quiet"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + Some(parse_wsl_list(&out.stdout)) +} + +#[cfg(any(windows, test))] +fn parse_wsl_list(out: &[u8]) -> Vec { + let s = if out.contains(&0) { + let words: Vec = out.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&words) + } else { + String::from_utf8_lossy(out).into_owned() + }; + s.lines() + .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}').to_owned()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// Checks whether a Windows named pipe server exists without opening a client +/// handle (opening `\\.\pipe\kiri` while not stopped would spawn `wsl.exe`). +#[cfg(windows)] +fn pipe_server_listening(pipe_name: &str) -> bool { + use std::os::windows::ffi::OsStrExt; + unsafe extern "system" { + fn WaitNamedPipeW(lpNamedPipeName: *const u16, nTimeOut: u32) -> i32; + } + let wide: Vec = std::ffi::OsStr::new(pipe_name).encode_wide().chain(std::iter::once(0)).collect(); + // SAFETY: `wide` is a valid NUL-terminated UTF-16 string. + unsafe { WaitNamedPipeW(wide.as_ptr(), 1) != 0 } +} + +#[cfg(windows)] +fn start_silent() -> io::Result<()> { + let pipe = client::pipe(); + if let Some(res) = crate::wsl::wake_via_pipe(&pipe) { + match res { + Ok(()) => { + crate::wsl::clear_stopped_marker(); + return Ok(()); + } + Err(e) if !matches!(e.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::BrokenPipe) => { + return Err(e); + } + Err(_) => {} + } + } + crate::wsl::clear_stopped_marker(); + let distro = crate::wsl::distro().ok_or_else(|| io::Error::other("Kiri isn't set up yet. Open Kiri from the Start menu first"))?; + let args = vec!["engine".to_owned(), "start".to_owned()]; + let status = std::process::Command::new(wsl_exe()) + .args(crate::wsl::wsl_command_args(&distro, &args)) + .stdout(std::process::Stdio::null()) + .status() + .map_err(|e| io::Error::other(format!("could not run wsl.exe ({e})")))?; + if !status.success() { + return Err(io::Error::other("could not start Kiri's engine in WSL")); + } + Ok(()) +} + +#[cfg(windows)] +fn stop_silent() -> io::Result { + let was_marked_stopped = std::env::var_os("LOCALAPPDATA") + .map(std::path::PathBuf::from) + .is_some_and(|d| crate::wsl::stopped_marker_in(&d).is_file()); + let pipe = client::pipe(); + if let Some(res) = crate::wsl::stop_via_pipe(&pipe) { + match res { + Ok(()) => { + crate::wsl::write_stopped_marker(); + return Ok(!was_marked_stopped); + } + Err(e) if !matches!(e.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::BrokenPipe) => { + return Err(e); + } + Err(_) => {} + } + } + crate::wsl::write_stopped_marker(); + let Some(distro) = crate::wsl::distro() else { + return Ok(false); + }; + let is_running = running_wsl_distros() + .map(|list| list.iter().any(|d| d.eq_ignore_ascii_case(&distro))) + .unwrap_or(false); + if !is_running { + return Ok(false); + } + let _ = std::process::Command::new(wsl_exe()) + .args([ + "-d", + &distro, + "-u", + "root", + "-e", + "sh", + "-c", + "export HOME=/var/lib/kiri-daemon; /usr/local/bin/kiri engine stop >/dev/null 2>&1 || true", + ]) + .status(); + if distro == "kiri" { + let _ = std::process::Command::new(wsl_exe()).args(["--terminate", &distro]).status(); + } + Ok(!was_marked_stopped) +} + +#[cfg(windows)] +fn restart_silent() -> io::Result<()> { + let _ = stop_silent()?; + start_silent() +} + +#[cfg(windows)] +fn collect_status() -> io::Result { + let pipe = client::pipe(); + if std::env::var_os("LOCALAPPDATA") + .map(std::path::PathBuf::from) + .is_some_and(|d| crate::wsl::stopped_marker_in(&d).is_file()) + { + return Ok(StatusReport::stopped_offline(pipe)); + } + let Some(distro) = crate::wsl::distro() else { + return Ok(StatusReport::not_running(pipe)); + }; + let distro_running = running_wsl_distros() + .map(|list| list.iter().any(|d| d.eq_ignore_ascii_case(&distro))) + .unwrap_or(false); + if !distro_running { + if pipe_server_listening(&pipe) { + return Ok(StatusReport { + state: EngineState::Asleep, + awake: false, + stopped: false, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: pipe, + }); + } + return Ok(StatusReport::not_running(pipe)); + } + let out = std::process::Command::new(wsl_exe()) + .args([ + "-d", + &distro, + "-u", + "root", + "-e", + "sh", + "-c", + "export HOME=/var/lib/kiri-daemon; exec /usr/local/bin/kiri engine status --json", + ]) + .output() + .map_err(|e| io::Error::other(format!("could not run wsl.exe ({e})")))?; + if let Ok(mut v) = serde_json::from_slice::(&out.stdout) { + let state = match v["state"].as_str() { + Some("running") => EngineState::Running, + Some("asleep") => EngineState::Asleep, + Some("stopped") => EngineState::Stopped, + _ => EngineState::NotRunning, + }; + v["socket"] = Value::String(pipe.clone()); + return Ok(StatusReport { + state, + awake: v["awake"].as_bool().unwrap_or(false), + stopped: v["stopped"].as_bool().unwrap_or(false), + version: v["version"].as_str().map(str::to_owned), + api_version: v["api_version"].as_str().map(str::to_owned), + cpus: v["cpus"].as_u64(), + memory_bytes: v["memory_bytes"].as_u64(), + containers_running: v["containers_running"].as_u64(), + containers_stopped: v["containers_stopped"].as_u64(), + socket: pipe, + }); + } + Ok(StatusReport::not_running(pipe)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn vec_s(words: &[&str]) -> Vec { + words.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn parses_subcommands_help_and_rejects_unknown_arguments() { + assert_eq!(parse_args(&vec_s(&["start"])).unwrap(), Action::Start); + assert_eq!(parse_args(&vec_s(&["stop"])).unwrap(), Action::Stop); + assert_eq!(parse_args(&vec_s(&["restart"])).unwrap(), Action::Restart); + assert_eq!(parse_args(&vec_s(&["status"])).unwrap(), Action::Status { json: false }); + assert_eq!(parse_args(&vec_s(&["status", "--json"])).unwrap(), Action::Status { json: true }); + + for h in [ + &["--help"][..], + &["-h"], + &["help"], + &["start", "--help"], + &["stop", "-h"], + &["restart", "--help"], + &["status", "--help"], + &["status", "--json", "-h"], + ] { + assert_eq!(parse_args(&vec_s(h)).unwrap(), Action::Help, "{h:?}"); + } + + for bad in [&[][..], &["unknown"], &["start", "extra"], &["status", "--bogus"]] { + let err = parse_args(&vec_s(bad)).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}"); + assert_eq!(err.to_string(), USAGE); + } + } + + #[test] + fn status_report_classifies_running_asleep_stopped_and_not_running() { + let ver = json!({"KiriVersion": "0.2.3", "ApiVersion": "1.47"}); + + // 1. Running (awake VM). + let running = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": false, + "KiriVmAwake": true, + "KiriVersion": "0.2.3", + "NCPU": 4, + "KiriMemoryCeiling": 8_589_934_592u64, + "ContainersRunning": 2, + "ContainersStopped": 1 + }), + Some(&ver), + ); + assert_eq!(running.state, EngineState::Running); + assert!(running.state.is_healthy()); + assert!(running.awake && !running.stopped); + assert_eq!(running.version.as_deref(), Some("0.2.3")); + assert_eq!(running.api_version.as_deref(), Some("1.47")); + assert_eq!(running.cpus, Some(4)); + assert_eq!(running.memory_bytes, Some(8_589_934_592)); + assert_eq!(running.containers_running, Some(2)); + assert_eq!(running.containers_stopped, Some(1)); + let human = running.format_human(); + assert!(human.contains("Kiri engine: running"), "{human}"); + assert!(human.contains("4 CPUs, 8 GiB"), "{human}"); + assert!(human.contains("2 running, 1 stopped"), "{human}"); + + // 2. Asleep (daemon up, VM idle-sleeping): healthy (exit 0). + let asleep = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": false, + "KiriVmAwake": false, + "KiriVersion": "0.2.3", + "NCPU": 2, + "KiriMemoryCeiling": 4_294_967_296u64, + "ContainersRunning": 0, + "ContainersStopped": 3 + }), + Some(&ver), + ); + assert_eq!(asleep.state, EngineState::Asleep); + assert!(asleep.state.is_healthy()); + assert!(!asleep.awake && !asleep.stopped); + assert!(asleep.format_human().contains("VM idle; wakes on next request")); + + // 3. Explicitly stopped: unhealthy (exit 1). + let stopped = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": true, + "KiriVmAwake": false, + "KiriVersion": "0.2.3" + }), + Some(&ver), + ); + assert_eq!(stopped.state, EngineState::Stopped); + assert!(!stopped.state.is_healthy()); + assert!(!stopped.awake && stopped.stopped); + let j: Value = serde_json::to_value(&stopped).unwrap(); + assert_eq!(j["state"], "stopped"); + assert_eq!(j["stopped"], true); + assert_eq!(j["awake"], false); + + // 4. Not running: unhealthy (exit 1). + let down = StatusReport::not_running("/run/kiri/docker.sock"); + assert_eq!(down.state, EngineState::NotRunning); + assert!(!down.state.is_healthy()); + let j_down: Value = serde_json::to_value(&down).unwrap(); + assert_eq!(j_down["state"], "not_running"); + } + + #[test] + fn parses_utf16_and_utf8_wsl_running_lists() { + let utf16: Vec = "\u{feff}Ubuntu\r\nkiri\r\n" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!(parse_wsl_list(&utf16), vec!["Ubuntu", "kiri"]); + assert_eq!(parse_wsl_list(b"Debian\nkiri\n"), vec!["Debian", "kiri"]); + } + + #[cfg(unix)] + #[test] + fn collect_status_sends_background_header_and_respects_offline_stopped_marker() { + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + + let dir = std::env::temp_dir().join(format!("kiri-engine-cli-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let missing = dir.join("missing.sock"); + let marker = dir.join("stopped"); + assert_eq!(collect_status_at(&missing, Some(&marker)).unwrap().state, EngineState::NotRunning); + std::fs::write(&marker, b"").unwrap(); + let offline_stopped = collect_status_at(&missing, Some(&marker)).unwrap(); + assert_eq!(offline_stopped.state, EngineState::Stopped); + assert!(offline_stopped.stopped); + + // Live mock socket: every request (`/_ping`, `/info`, `/version`) must carry `X-Kiri-Background: 1`. + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + let handle = std::thread::spawn(move || { + for expected in ["/_ping", "/info", "/version"] { + let (mut conn, _) = listener.accept().unwrap(); + let mut req = Vec::new(); + let mut buf = [0u8; 512]; + while !req.windows(4).any(|w| w == b"\r\n\r\n") { + match conn.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => req.extend_from_slice(&buf[..n]), + } + } + let text = String::from_utf8_lossy(&req); + assert!(text.starts_with(&format!("GET {expected} HTTP/1.1\r\n")), "unexpected request: {text}"); + assert!(text.to_ascii_lowercase().contains("\r\nx-kiri-background: 1\r\n"), "missing background header: {text}"); + let body = match expected { + "/_ping" => "OK".to_owned(), + "/info" => json!({"KiriStopped": false, "KiriVmAwake": false, "KiriVersion": "0.2.3", "NCPU": 6, "KiriMemoryCeiling": 12_884_901_888u64, "ContainersRunning": 0, "ContainersStopped": 1}).to_string(), + "/version" => json!({"KiriVersion": "0.2.3", "ApiVersion": "1.47"}).to_string(), + _ => unreachable!(), + }; + write!( + conn, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .unwrap(); + } + }); + + let got = collect_status_at(&sock, None).unwrap(); + handle.join().unwrap(); + assert_eq!(got.state, EngineState::Asleep); + assert!(!got.awake && !got.stopped); + assert_eq!(got.cpus, Some(6)); + assert_eq!(got.version.as_deref(), Some("0.2.3")); + assert_eq!(got.api_version.as_deref(), Some("1.47")); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index be25bd26c..7ca1dea45 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -55,6 +55,9 @@ mod dockerctx; // `kiri doctor`: whether this installation works (Windows: docker here, the engine in WSL). #[cfg(any(unix, windows))] mod doctor; +// `kiri engine`: start, stop, restart and inspect Kiri's engine (#983). +#[cfg(any(unix, windows))] +mod engine_cli; // `kiri domains`: the container-domain routers' ports (Windows: in WSL). #[cfg(unix)] mod domains_cli; @@ -113,6 +116,7 @@ const USAGE_LINES: &[&str] = &[ "usage: kiri COMMAND docker's commands, on Kiri: kiri run, ps, exec,", " logs, stop, rm, images, pull, build, compose…", " kiri start start Kiri after a Stop (the window's Start)", + " kiri engine start | stop | restart | status [--json] start, stop, restart or inspect Kiri's engine", #[cfg(unix)] " kiri daemon", #[cfg(target_os = "linux")] @@ -231,6 +235,8 @@ enum Command<'a> { Share(&'a [String]), Start(&'a [String]), #[cfg(any(unix, windows))] + Engine(&'a [String]), + #[cfg(any(unix, windows))] BuildWith(&'a [String]), #[cfg(unix)] Domains(&'a [String]), @@ -303,6 +309,8 @@ impl<'a> Command<'a> { #[cfg(windows)] Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(args)), #[cfg(any(unix, windows))] + Some("engine") => Some(Command::Engine(&args[1..])), + #[cfg(any(unix, windows))] Some("build-with") => Some(Command::BuildWith(&args[1..])), #[cfg(unix)] Some("domains") => Some(Command::Domains(&args[1..])), @@ -450,12 +458,14 @@ fn main() -> ExitCode { println!("{START_USAGE}"); Ok(()) } else { - engine_start() + engine_cli::start_legacy() } } #[cfg(windows)] Some(Command::Start(all)) => wsl::run(all), #[cfg(any(unix, windows))] + Some(Command::Engine(rest)) => engine_cli::run(rest), + #[cfg(any(unix, windows))] Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] Some(Command::Domains(rest)) => domains_cli::run(rest), @@ -552,40 +562,6 @@ fn window(args: &[String]) -> std::io::Result<()> { Err(std::process::Command::new(WINDOW).args(args).exec()) } -#[cfg(unix)] -fn engine_start_not_running_message() -> &'static str { - #[cfg(target_os = "macos")] - { - "Kiri's engine isn't running. Open Kiri, or start it with `kiri daemon`" - } - #[cfg(not(target_os = "macos"))] - { - client::not_running_message() - } -} - -/// `kiri start`: Kiri on again after a Stop (the window's, the tray's or -/// the menu bar's), as the window's Start does; the containers Stop held -/// come back. On an engine that wasn't stopped it only wakes the VM. -#[cfg(unix)] -fn engine_start() -> std::io::Result<()> { - #[cfg(target_os = "macos")] - if !client::alive() { - if let Ok(d) = daemon::state_dir() { - let _ = std::fs::remove_file(d.join("stopped")); - } - update::start_engine()?; - } - client::check_alive_with(engine_start_not_running_message())?; - let r = client::request("POST", "/kiri/wake", None)?; - // 404: a Linux host's engine, which has no VM to wake and no Stop. - if !r.ok() && r.status != 404 { - return Err(std::io::Error::other(r.error())); - } - println!("Kiri is started"); - Ok(()) -} - #[cfg(not(unix))] fn engine_version_check() {} @@ -633,7 +609,7 @@ mod tests { fn usage_lists_only_commands_for_this_os() { let help = usage(); let cmds = advertised_subcommands(&help); - for common in ["COMMAND", "start", "doctor", "domains", "storage", "registry", "scan", "diag", "PORT", "share", "k8s", "usb", "machine"] { + for common in ["COMMAND", "start", "engine", "doctor", "domains", "storage", "registry", "scan", "diag", "PORT", "share", "k8s", "usb", "machine"] { assert!(cmds.contains(&common), "help missing `{common}`:\n{help}"); } assert!(help.contains("kiri storage [status | reclaim]"), "help missing `kiri storage`:\n{help}"); @@ -740,6 +716,8 @@ mod tests { // `kiri start --help` / `-h` dispatches to Kiri's Start, while `kiri start web --help` stays Docker's. assert!(matches!(Command::parse(&["start".to_owned(), "--help".to_owned()]), Some(Command::Start(_)))); assert!(matches!(Command::parse(&["start".to_owned(), "-h".to_owned()]), Some(Command::Start(_)))); + assert!(matches!(Command::parse(&["engine".to_owned(), "status".to_owned()]), Some(Command::Engine(_)))); + assert!(matches!(Command::parse(&["engine".to_owned(), "--help".to_owned()]), Some(Command::Engine(_)))); assert!(matches!(Command::parse(&["start".to_owned(), "web".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); assert!(matches!(Command::parse(&["run".to_owned(), "alpine".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); assert!(matches!(Command::parse(&["ps".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 79ffac731..4f91afaf3 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -194,17 +194,33 @@ pub(crate) fn clear_stopped_marker_at(path: &Path) { let _ = std::fs::remove_file(path); } -fn clear_stopped_marker() { +pub(crate) fn write_stopped_marker_at(path: &Path) { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(path, b""); +} + +pub(crate) fn clear_stopped_marker() { if let Some(dir) = std::env::var_os("LOCALAPPDATA") { clear_stopped_marker_at(&stopped_marker_in(&PathBuf::from(dir))); } } -/// Sends `POST /kiri/wake` over an open pipe/stream so a running `kiri-win.exe` -/// clears its in-memory `STOPPED` gate, removes `%LOCALAPPDATA%\Kiri\stopped`, -/// boots WSL, and updates the window/tray immediately. -pub(crate) fn wake_over_stream(mut stream: impl Read + Write) -> io::Result<()> { - stream.write_all(b"POST /kiri/wake HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\nContent-Length: 0\r\n\r\n")?; +pub(crate) fn write_stopped_marker() { + if let Some(dir) = std::env::var_os("LOCALAPPDATA") { + write_stopped_marker_at(&stopped_marker_in(&PathBuf::from(dir))); + } +} + +/// Sends a control `POST` (`POST /kiri/wake` or `POST /kiri/stop`) over an open +/// pipe/stream so a running `kiri-win.exe` updates its stopped gate, marker, +/// WSL distro, and window/tray immediately. +pub(crate) fn post_over_stream(mut stream: impl Read + Write, endpoint: &str) -> io::Result<()> { + write!( + stream, + "POST {endpoint} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\nContent-Length: 0\r\n\r\n" + )?; stream.flush()?; let mut r = BufReader::new(stream); let mut status_line = String::new(); @@ -266,8 +282,16 @@ pub(crate) fn wake_over_stream(mut stream: impl Read + Write) -> io::Result<()> Err(io::Error::other(msg)) } +pub(crate) fn wake_over_stream(stream: impl Read + Write) -> io::Result<()> { + post_over_stream(stream, "/kiri/wake") +} + +pub(crate) fn stop_over_stream(stream: impl Read + Write) -> io::Result<()> { + post_over_stream(stream, "/kiri/stop") +} + #[cfg(windows)] -fn wake_via_pipe(pipe_name: &str) -> Option> { +fn post_via_pipe(pipe_name: &str, endpoint: &str) -> Option> { use std::os::windows::fs::OpenOptionsExt; const ERROR_PIPE_BUSY: i32 = 231; const SECURITY_IDENTIFICATION: u32 = 0x0001_0000; @@ -279,7 +303,7 @@ fn wake_via_pipe(pipe_name: &str) -> Option> { .security_qos_flags(SECURITY_IDENTIFICATION) .open(pipe_name) { - Ok(file) => return Some(wake_over_stream(file)), + Ok(file) => return Some(post_over_stream(file, endpoint)), Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) => { std::thread::sleep(std::time::Duration::from_millis(50)); } @@ -289,8 +313,23 @@ fn wake_via_pipe(pipe_name: &str) -> Option> { None } +#[cfg(windows)] +pub(crate) fn wake_via_pipe(pipe_name: &str) -> Option> { + post_via_pipe(pipe_name, "/kiri/wake") +} + +#[cfg(windows)] +pub(crate) fn stop_via_pipe(pipe_name: &str) -> Option> { + post_via_pipe(pipe_name, "/kiri/stop") +} + #[cfg(not(windows))] -fn wake_via_pipe(_pipe_name: &str) -> Option> { +pub(crate) fn wake_via_pipe(_pipe_name: &str) -> Option> { + None +} + +#[cfg(not(windows))] +pub(crate) fn stop_via_pipe(_pipe_name: &str) -> Option> { None } @@ -486,6 +525,14 @@ mod tests { let err = wake_over_stream(&mut eof).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); + // Stop marker write + POST /kiri/stop over pipe. + super::write_stopped_marker_at(&marker); + assert!(marker.is_file()); + let mut stop_pipe = MockPipe::new(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"); + super::stop_over_stream(&mut stop_pipe).unwrap(); + let stop_wire = String::from_utf8(stop_pipe.sent).unwrap(); + assert!(stop_wire.starts_with("POST /kiri/stop HTTP/1.1\r\n"), "{stop_wire}"); + let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/features.md b/docs/features.md index cef9333b0..4b362884e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -133,7 +133,9 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr override it; the disk grows online on boot and never shrinks) and local names - **Menu bar**: Kiri stays in the menu bar (or the tray on Windows and Linux) when its window closes, with the VM's state, running containers (click one - to open it) and Start/Stop; Settings → Appearance → Closing the window can + to open it) and Start/Stop (`kiri engine start | stop | restart | status [--json]` + controls and inspects the engine from the terminal without waking a sleeping VM); + Settings → Appearance → Closing the window can either keep the window hidden or free its page's memory until opened again - **Kubernetes**: `kiri k8s start` — a single-node k3s cluster in one container, ready in ~20 s, as the `kiri` kubectl context diff --git a/docs/fix-registry.md b/docs/fix-registry.md index fbc82e9fb..fbf7863ae 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,18 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### #983 CLI: add `kiri engine start | stop | restart | status [--json]` across macOS, Linux, and Windows (unreleased) +- Fixes: #983 Add CLI commands to start, stop and inspect the Kiri engine +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/engine_cli.rs`, `crates/kiri-win/src/refuse.rs` + +### #989 macOS & Kubernetes: stop watching `/Users` and `/Volumes` on `kiri-k8s`, coalesce `k3s` timers with `10 ms` `timerslack_ns`, and watch LoadBalancer services instead of polling `kubectl` every 3 s (unreleased) +- Fixes: #989 macOS: idle VM burns a full host core while the Kubernetes cluster is running +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/daemon/engine.rs`, `crates/kiri-init/src/linux/hostopts.rs`, `crates/kiri-init/src/linux/container.rs` + ### Start: evict stale `VmLink::layers` entries and re-send layers when `run` reports `"is not unpacked"` (unreleased) - Fixes: `start-restores-layer` (`docker start` failed with `layer sha256:… is not unpacked` when an unpacked layer directory disappeared on the guest's disk without a VM restart) - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 148531385..d67e3c667 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -372,3 +372,7 @@ crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared machine-prune-keeps #975 docker container prune and docker system prune deleted a stopped kiri machine and everything in its writable layer crates/kiri/src/daemon/vmlink.rs #948 VmLink::call waited without a timeout and Writer::write blocked indefinitely holding the writer mutex when the guest wedged, deadlocking hundreds of kiri-api threads crates/kiri-init/src/linux/container.rs #948 finish_stdio called recv_fd with no timeout on single-threaded kiri-init and exec did not reap a killed child when TTY setup failed +crates/kiri/src/daemon/engine.rs #989 kiri-k8s caused mac_bind_sources to watch all of /Users and /Volumes via FSEvents, spawned kubectl every 3s for LoadBalancer polling, and lacked timer coalescing for k3s's 100ms watch_progress tickers +crates/kiri-init/src/linux/hostopts.rs #989 kiri-init hostopts lacked timerslack_ns support to coalesce k3s background pollers across execve +crates/kiri/src/engine_cli.rs #983 kiri CLI had no `kiri engine start | stop | restart | status [--json]` commands to stop, restart, or inspect the engine without waking a sleeping VM +crates/kiri-win/src/refuse.rs #983 Windows pipe gate did not handle `POST /kiri/stop` idempotently while stopped or synchronize `kiri-win` on external CLI stops