From aafc3929a9191c43dafeaf83ecbe9f6710b84edf Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Sat, 28 Nov 2026 10:33:58 +0100 Subject: [PATCH] Fix macOS virtiofs chown invalidation, secondary network start race, and Windows/WSL binds --- crates/kiri-init/src/linux/agent.rs | 7 ++ crates/kiri-init/src/linux/container.rs | 41 ++++++++ crates/kiri-proto/src/lib.rs | 11 +++ crates/kiri/src/daemon/api.rs | 94 ++++++++++++++++++- crates/kiri/src/daemon/binds.rs | 30 +++++- crates/kiri/src/daemon/engine.rs | 35 +++++-- crates/kiri/src/daemon/vmlink.rs | 4 + crates/kiri/src/daemon/volumes.rs | 17 ++++ crates/kiri/src/setup_win.rs | 6 +- docs/fix-registry.md | 8 +- .../0009-virtiofs-chown-and-cache.patch | 65 +++++++------ tests/e2e.sh | 10 +- tests/regressions.tsv | 4 +- 13 files changed, 285 insertions(+), 47 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 413478b05..1fffc8a8a 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -750,6 +750,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Error(&e).encode(&mut out), }, + Ok(Msg::StartExec { id }) => match procs.values_mut().find(|p| p.run.id == id && p.run.container.is_none() && p.exited.is_none()) { + Some(p) => match p.run.start_exec() { + Ok(()) => Msg::Ack.encode(&mut out), + Err(e) => Msg::Error(&format!("start exec {id}: {e}")).encode(&mut out), + }, + None => Msg::Error(&format!("container {id} is not running")).encode(&mut out), + }, Ok(Msg::StatsQuery { id }) => match netns_pid(procs, id) { Some(pid) => match super::cgroup::stats(&paths.cgroup.join(id), pid) { Ok(s) => Msg::ContainerStats(s).encode(&mut out), diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 9f6a0be18..dfa4ea349 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -121,6 +121,9 @@ pub struct Process { /// Its start was cancelled while it was filling a volume (see `cancel`): /// killed as soon as its root is in place. cancelled: bool, + /// Write end of `Prepared::exec_ready` when started with + /// `run_flags::HOLD_EXEC` so secondary networks can be attached before PID 1 execs. + exec_go: Option, } /// Where a container's root stands (see [`Process::root`]). @@ -233,6 +236,17 @@ impl Process { pub fn start_failure(&self) -> Option<&str> { self.ended_before_ready.as_deref() } + + /// Releases a child started with `run_flags::HOLD_EXEC` so it proceeds to exec. + pub fn start_exec(&mut self) -> io::Result<()> { + if let Some(go) = self.exec_go.take() { + // SAFETY: writing one byte to a pipe we own. + if unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 { + return Err(io::Error::last_os_error()); + } + } + Ok(()) + } } /// A child that ended before its root was in place and said nothing. @@ -270,6 +284,7 @@ impl Process { ended_before_ready: None, filling: false, cancelled: false, + exec_go: None, } } @@ -339,6 +354,9 @@ struct Prepared { /// The child's end of the pipe that says it has been moved into its /// cgroup. Only a start that fell back to clone(2) waits on it. cgroup_ready: Option, + /// When `run_flags::HOLD_EXEC` is set, the child waits here (after TTY and + /// root setup, before seccomp and exec) until `Msg::StartExec` releases it. + exec_ready: Option, } /// The parts of [`super::hostopts::HostOpts`] the child applies itself. @@ -665,6 +683,13 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, target_pid: libc::pid_t, paths: &Paths, profile ended_before_ready: None, filling: false, cancelled: false, + exec_go: None, }) } @@ -1532,6 +1560,7 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname: host: HostApplied::default(), root_ready: None, cgroup_ready: None, + exec_ready: None, }) } @@ -2550,6 +2579,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ }, root_ready, cgroup_ready, + exec_ready, } = p; let mut fds = match io { ChildStdio::Tty { sock } => vec![sock.as_raw_fd()], @@ -2563,6 +2593,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { fds.extend(net_ready.as_ref().map(AsRawFd::as_raw_fd)); fds.extend(root_ready.as_ref().map(AsRawFd::as_raw_fd)); fds.extend(cgroup_ready.as_ref().map(AsRawFd::as_raw_fd)); + fds.extend(exec_ready.as_ref().map(AsRawFd::as_raw_fd)); fds } @@ -2781,6 +2812,16 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { // which is where the user will see why a start failed. let fail = |what: &str, e: io::Error| -> ! { child_fail(2, what, e) }; + if console + && let Some(ready) = &p.exec_ready + { + let mut b = [0u8; 1]; + // SAFETY: reading one byte into a local buffer from a pipe we own. + if unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) } != 1 { + fail("network", io::Error::other("the agent could not set up this container's networks")); + } + } + // 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)); diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index c49234412..b62c4bea5 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -260,6 +260,10 @@ pub enum Msg<'a> { TrimDisk, /// Guest → host: bytes discarded by `FITRIM`, plus updated `statvfs` usage. DiskTrimmed { trimmed: u64, in_use: u64, capacity: u64 }, + /// Host → guest: release a container started with [`run_flags::HOLD_EXEC`] + /// to exec its program once secondary networks are attached. Answered by + /// `Ack` or `Error`. + StartExec { id: &'a str }, /// Success, for requests with nothing else to say. Ack, } @@ -509,6 +513,9 @@ pub mod run_flags { /// `--pid host`: no PID namespace of its own; the container sees the /// VM's processes (on a Linux host, the host's). pub const PID_HOST: u32 = 1 << 17; + /// Hold the container's process right before exec until [`super::Msg::StartExec`] + /// releases it, so `spec.extra_networks` are attached before PID 1 runs. + pub const HOLD_EXEC: u32 = 1 << 18; } /// A container's network, as `Run` carries it. @@ -901,6 +908,7 @@ mod kind { pub const DISK_USAGE: u16 = 86; pub const TRIM_DISK: u16 = 87; pub const DISK_TRIMMED: u16 = 88; + pub const START_EXEC: u16 = 89; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1312,6 +1320,7 @@ impl Msg<'_> { put_u64(o, in_use); put_u64(o, capacity); }), + Msg::StartExec { id } => frame(out, kind::START_EXEC, |o| put_str(o, id)), Msg::Listening(lines) => frame(out, kind::LISTENING, |o| { put_u32(o, lines.count); o.extend_from_slice(lines.raw); @@ -1633,6 +1642,7 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::DISK_USAGE => Msg::DiskUsage { in_use: r.u64()?, capacity: r.u64()? }, kind::TRIM_DISK => Msg::TrimDisk, kind::DISK_TRIMMED => Msg::DiskTrimmed { trimmed: r.u64()?, in_use: r.u64()?, capacity: r.u64()? }, + kind::START_EXEC => Msg::StartExec { id: r.str()? }, kind::NET_ATTACH => Msg::NetAttach { id: r.str()?, ifname: r.str()?, @@ -1739,6 +1749,7 @@ mod tests { assert_eq!(decode(&buf[..buf.len() - 32]).unwrap(), Msg::Stats(no_memory_words)); assert_eq!(decode(&buf[..buf.len() - 40]).unwrap(), Msg::Stats(Stats { mem_used_kib: 0, ..no_memory_words })); round(Msg::LayerQuery("sha256:ab")); + round(Msg::StartExec { id: "ctr-123" }); round(Msg::LayerStatus(true)); round(Msg::LayerBegin(LayerBegin { digest: "sha256:ab", media_type: "x+gzip", size: 9 })); round(Msg::LayerStored(LayerStored { unpacked_bytes: 1, elapsed_ns: 2 })); diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 1f8c6e180..f8769fc3f 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -302,7 +302,7 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea ("POST", "/networks/create") => return reply(w, network_create(req, engine), 201), ("POST", "/networks/prune") => return reply(w, network_prune(req, engine), 200), ("GET", "/volumes") => return reply(w, volumes(req, engine), 200), - ("POST", "/volumes/create") => return reply(w, volume_create(req, engine), 201), + ("POST", "/volumes/create") => return reply(w, volume_create(req, engine, caller), 201), ("POST", "/volumes/prune") => return reply(w, volume_prune(req, engine), 200), _ => {} } @@ -1962,6 +1962,31 @@ fn check_volume_device(options: &std::collections::BTreeMap) -> Ok(()) } +/// Resolves a local bind volume's `device` path for WSL integration or Windows +/// drive-letter paths before passing it to the guest, while keeping the raw +/// `device` option in `volumes.json` for `docker volume inspect`. +fn volume_bind_source(device: &str, wsl: Option<&super::binds::Wsl>, wsl_distro: Option<&str>) -> Result { + match (wsl, wsl_distro) { + (_, Some(d)) => super::binds::distro_source(device, d, wsl), + (Some(w), None) => super::binds::source(device, w), + _ => Ok(device.to_owned()), + } +} + +fn validate_volume_options( + options: &std::collections::BTreeMap, + wsl: Option<&super::binds::Wsl>, + wsl_distro: Option<&str>, +) -> Result<(), Error> { + check_volume_device(options)?; + let (flags, _) = super::volumes::mount_options(options.get("o").map_or("", String::as_str)); + if flags & 4096 != 0 { + let device = options.get("device").map_or("", String::as_str); + volume_bind_source(device, wsl, wsl_distro)?; + } + Ok(()) +} + /// Refuses text that would forge a field in the tab-separated mount line the /// guest parses. /// @@ -2183,11 +2208,23 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: // must not be reachable this way either: not as a virtiofs // tag, and not as a bind of /mnt/mac. check_volume_device(&v.options)?; + let vol_distro = v.wsl_distro.as_deref().or(wsl_distro); + let (opt_flags, _) = super::volumes::mount_options(v.options.get("o").map_or("", String::as_str)); + let translated_bind_dev = if opt_flags & 4096 != 0 { + let raw_dev = v.options.get("device").map_or("", String::as_str); + Some(volume_bind_source(raw_dev, super::binds::wsl(), vol_distro)?) + } else { + None + }; let path = super::volumes::guest_path(&name); let copy = if extra.contains("nocopy") { "create" } else { "create,copyup" }; // A volume with driver options (`type=nfs`, `o=bind` …) is // mounted at its path by the guest at start, then bound in. - let vol = super::volumes::guest_mount_fields(&v.options, guest_bind_source, resolve_server); + let vol = super::volumes::guest_mount_fields( + &v.options, + |dev| guest_bind_source(translated_bind_dev.as_deref().unwrap_or(dev)), + resolve_server, + ); out.guest.push(format!("{path}\t{dst}\t{}{vol}", flag(copy))); out.info.push(json!({"Type": "volume", "Name": name, "Source": path, "Destination": dst, "Driver": "local", "Mode": "z", "RW": !ro, "Propagation": ""})); if anonymous { @@ -2258,7 +2295,8 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: d => return Err(Error::BadRequest(format!("Kiri supports only local volumes, not {d}"))), } let options = super::volumes::local_options(&driver_opts["Options"]).map_err(Error::BadRequest)?; - engine.volume_ensure_with(src, m["VolumeOptions"]["Labels"].clone(), options)?; + validate_volume_options(&options, wsl, wsl_distro)?; + engine.volume_ensure_with_distro(src, m["VolumeOptions"]["Labels"].clone(), options, wsl_distro.map(str::to_owned))?; } add(kind, src, dst, ro, &extra, false, &mut out)?; } @@ -2398,7 +2436,7 @@ fn volume_json(v: &super::volumes::Volume) -> Value { }) } -fn volume_create(req: &Request, engine: &Engine) -> Result { +fn volume_create(req: &Request, engine: &Engine, caller: &super::caller::Caller) -> Result { let body: Value = serde_json::from_slice(&req.body).unwrap_or(Value::Null); match body["Driver"].as_str().unwrap_or("local") { "" | "local" => {} @@ -2409,7 +2447,9 @@ fn volume_create(req: &Request, engine: &Engine) -> Result { n => n.to_owned(), }; let options = super::volumes::local_options(&body["DriverOpts"]).map_err(Error::BadRequest)?; - let v = engine.volume_ensure_with(&name, body["Labels"].clone(), options)?; + let wsl_distro = caller.wsl_distro(); + validate_volume_options(&options, super::binds::wsl(), wsl_distro)?; + let v = engine.volume_ensure_with_distro(&name, body["Labels"].clone(), options, wsl_distro.map(str::to_owned))?; Ok(volume_json(&v)) } @@ -5151,6 +5191,50 @@ mod tests { assert_eq!(m.info[1]["Source"], "/run/host-services/ssh-auth.sock"); assert_eq!(m.info[1]["Destination"], "/agent.sock"); assert_eq!(m.info[1]["RW"], false); + + // From an integrated WSL distro, `/run/host-services/ssh-auth.sock` stays + // the SSH relay socket and local `o=bind` volumes translate `device` into + // `/mnt/wsl/kiri/roots//...` for the guest while keeping `Options.device` + // unchanged in `volume inspect`. + let wsl_caller = Caller::Wsl("Ubuntu".into()); + let mw = mounts_for(&body, &engine, &image, &wsl_caller).unwrap(); + assert_eq!(mw.guest, [format!("{src}\t/run/host-services/ssh-auth.sock\t"), format!("{src}\t/agent.sock\tro")]); + assert_eq!(mw.info[0]["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(mw.info[1]["Source"], "/run/host-services/ssh-auth.sock"); + + let vreq = Request::internal( + "POST", + "/volumes/create", + &[], + serde_json::to_vec(&json!({ + "Name": "wsl-shared", + "Driver": "local", + "DriverOpts": {"type": "none", "o": "bind", "device": "/tmp/shared"}, + })) + .unwrap(), + ); + let vj = volume_create(&vreq, &engine, &wsl_caller).unwrap(); + assert_eq!(vj["Options"]["device"], "/tmp/shared"); + let vbody = json!({"HostConfig": {"Binds": ["wsl-shared:/shared"]}}); + let mv = mounts_for(&vbody, &engine, &image, &Caller::Host).unwrap(); + assert_eq!( + mv.guest, + ["/var/lib/kiri/volumes/wsl-shared/_data\t/shared\tcreate,copyup\tnone\t/mnt/wsl/kiri/roots/Ubuntu/tmp/shared\t1000\t"] + ); + + let bad_vreq = Request::internal( + "POST", + "/volumes/create", + &[], + serde_json::to_vec(&json!({ + "Name": "wsl-evil", + "Driver": "local", + "DriverOpts": {"type": "none", "o": "bind", "device": "/mnt/wsl/kiri/roots/Debian/etc"}, + })) + .unwrap(), + ); + assert!(volume_create(&bad_vreq, &engine, &wsl_caller).is_err()); + drop(engine); let _ = std::fs::remove_dir_all(root); } diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index b45b0abe5..a72574421 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -259,7 +259,7 @@ pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result) -> Result crate::diag::warn!("container not attached to a network", id = &id[..12], network = extra.name, error = format!("{e:?}")), } } + if let Err(e) = vm.start_exec(&id) { + crate::diag::warn!("container start_exec failed", id = &id[..12], error = e); + } + } + // Before anything below, which may itself exec (a health probe), + // and after the pid and all configured networks are in place. + drop(gate); + if let (true, Some((rows, cols))) = (spec.tty, size) { + let _ = vm.resize(&id, rows, cols); } // A container that left all its networks keeps its `-p` bindings // but has no address for them, as on Docker, where it publishes none. @@ -6090,8 +6099,18 @@ impl Engine { /// [`Engine::volume_ensure`] with the local driver's options, which a /// new volume keeps (an existing one keeps its own). pub fn volume_ensure_with(&self, name: &str, labels: serde_json::Value, options: std::collections::BTreeMap) -> Result { + self.volume_ensure_with_distro(name, labels, options, None) + } + + pub fn volume_ensure_with_distro( + &self, + name: &str, + labels: serde_json::Value, + options: std::collections::BTreeMap, + wsl_distro: Option, + ) -> Result { let new = self.volume_get(name).is_none(); - let v = self.lock_volumes().ensure_with(name, labels, false, options).map_err(Error::BadRequest)?; + let v = self.lock_volumes().ensure_with_distro(name, labels, false, options, wsl_distro).map_err(Error::BadRequest)?; if new { self.record_new_volume(&v); self.emit_volume("create", name); diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index fb2bc8974..5c3db4d6a 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -699,6 +699,10 @@ impl VmLink { self.ack(|o| Msg::Freeze { id, frozen }.encode(o)) } + pub fn start_exec(&self, id: &str) -> io::Result<()> { + self.ack(|o| Msg::StartExec { id }.encode(o)) + } + pub fn container_stats(&self, id: &str) -> io::Result { match self.call(|o| Msg::StatsQuery { id }.encode(o), None)? { Reply::ContainerStats(s) => Ok(s), diff --git a/crates/kiri/src/daemon/volumes.rs b/crates/kiri/src/daemon/volumes.rs index 7ccad2097..d035bc9e9 100644 --- a/crates/kiri/src/daemon/volumes.rs +++ b/crates/kiri/src/daemon/volumes.rs @@ -32,6 +32,11 @@ pub struct Volume { /// `type`, `device`, `o`. Empty for a plain directory. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub options: BTreeMap, + /// Integrated WSL distro that created this volume (if any), so a local + /// bind volume (`o=bind`) resolves relative to `/mnt/wsl/kiri/roots/` + /// while keeping `options["device"]` unchanged in `volume inspect`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wsl_distro: Option, } #[derive(Debug)] @@ -76,6 +81,17 @@ impl Volumes { /// [`Volumes::ensure`] with the local driver's options for a new volume. /// An existing volume keeps its own, as Docker's local driver does. pub fn ensure_with(&mut self, name: &str, labels: serde_json::Value, anonymous: bool, options: BTreeMap) -> Result { + self.ensure_with_distro(name, labels, anonymous, options, None) + } + + pub fn ensure_with_distro( + &mut self, + name: &str, + labels: serde_json::Value, + anonymous: bool, + options: BTreeMap, + wsl_distro: Option, + ) -> Result { if !valid_name(name) { return Err(format!("invalid volume name {name:?}: only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed")); } @@ -92,6 +108,7 @@ impl Volumes { labels, anonymous, options, + wsl_distro, }; self.list.push(v.clone()); self.save(); diff --git a/crates/kiri/src/setup_win.rs b/crates/kiri/src/setup_win.rs index 4b3266471..70b1b566e 100644 --- a/crates/kiri/src/setup_win.rs +++ b/crates/kiri/src/setup_win.rs @@ -17,7 +17,7 @@ use crate::dockerctx::{ const USAGE: &str = "usage: kiri setup [--use]"; fn npipe_host(pipe: &str) -> String { - format!("npipe:{}", pipe.replace('\\', "/")) + format!("npipe:////{}", pipe.replace('\\', "/").trim_start_matches('/')) } /// Best-effort background self-heal of `%USERPROFILE%\.docker\config.json` and @@ -185,6 +185,10 @@ mod tests { #[test] fn repairs_wiped_docker_config_and_dangling_desktop_linux_context() { + assert_eq!(npipe_host(r"\\.\pipe\kiri"), "npipe:////./pipe/kiri"); + assert_eq!(npipe_host("//./pipe/kiri"), "npipe:////./pipe/kiri"); + assert_eq!(npipe_host(r"\\.\pipe\kiri-dev"), "npipe:////./pipe/kiri-dev"); + let root = scratch("repair"); let docker = root.join(".docker"); let plugins = root.join("Kiri/bin/cli-plugins"); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index c5659147a..2b34b8684 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 +### #381, #382, #420, #984 macOS, Networking & Windows/WSL: preserve virtiofs `chown` across host fsnotify events, attach secondary networks before PID 1 execs, format `npipe:////` context URLs with four slashes, and preserve WSL virtual/cgroup binds and local bind volumes (unreleased) +- Fixes: #382 (`kiri_inject.c` called `__d_drop` on `C`/`M`/`A` host fsnotify events, evicting `struct fuse_inode` and losing in-memory `chown_uid`/`chown_gid` on macOS bind mounts when `FSEvents` echoed container writes), #381 (`start_on_vm` spawned the container process before attaching `spec.extra_networks`, causing fast `docker compose run` commands on secondary external networks to run before `eth1` and its IPv4 default route were attached), #984 (`setup_win::npipe_host` formatted `\\.\pipe\kiri` with two slashes `npipe://./pipe/kiri` instead of four `npipe:////./pipe/kiri`), #420 / #358 (WSL distro bind translation rewrote `/run/host-services/ssh-auth.sock` and `/sys` paths into `/mnt/wsl/kiri/roots//...` and `POST /volumes/create` did not resolve local `o=bind` volume `device` paths relative to the calling WSL distro or Windows drive) +- Caused: none known +- Caused by: #1002 +- Check: `bind-chown-chmod`, `internal-first-external-default`, `host-services-ssh-agent-mount`, `compose-wait`, `cgroupns-host-unpriv-ro`, `crates/kiri/src/setup_win.rs`, `crates/kiri-proto/src/lib.rs`, `crates/kiri/src/daemon/binds.rs` + ### #269, #984 Windows & WSL: avoid clobbering `%USERPROFILE%\.docker\contexts` through Docker Desktop's WSL symlink, self-heal `unix://` `kiri` context on Windows, and ignore empty `KIRI_UPDATE_URL` (unreleased) - Fixes: #269 (enabling WSL integration when `~/.docker/contexts` in WSL was symlinked to `/mnt/c/Users//.docker/contexts` overwrote Windows's `npipe:////./pipe/kiri` `kiri` context with a Linux `unix://` socket), #984 (`KIRI_UPDATE_URL=""` from `setx` caused `kiri update --check` to fail with `http: empty string` instead of using the default feed) - Caused: none known @@ -27,7 +33,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ### #1002 Release gate fixes: virtiofs deleted-file revalidation across `docker run --rm`, offline `kiri domains set/reset`, netns lock takeover after stuck container start, transient `429` manifest retries, WSL `statvfs` `f_bfree` usage, and WSL `kiri` context hash (unreleased) - Fixes: #399 (back-to-back `docker run --rm -v` sees 1 s `ENOENT` recreating a host-deleted file), #744 (`kiri domains set` and `kiri domains reset` failed when the daemon was stopped), #190 (`statvfs_usage` used `f_bavail` instead of `f_bfree`, counting ~55 GB of ext4 reserved blocks on WSL's sparse `ext4.vhdx` as used), #269 (`wslsync.rs` hardcoded the wrong SHA-256 for Docker context `kiri`), `agent-dies-beside-stuck-start` (`claim_host_netns` failed when a dead agent's frozen child still held `@kiri-engine-netns`), `pulls-of-different-images-at-once-leave-a-sound-index` (`Client::manifest` did not retry HTTP `429` / transient registry errors) -- Caused: Enabling WSL integration in a distro where Docker Desktop had symlinked `~/.docker/contexts` to `/mnt/c/Users//.docker/contexts` overwrote Windows's `npipe:////./pipe/kiri` `kiri` context with `unix:///mnt/wsl/kiri/sockets//docker.sock` (found during 0.2.3 release-gate restore on Windows) +- Caused: Enabling WSL integration in a distro where Docker Desktop had symlinked `~/.docker/contexts` to `/mnt/c/Users//.docker/contexts` overwrote Windows's `npipe:////./pipe/kiri` `kiri` context with `unix:///mnt/wsl/kiri/sockets//docker.sock` (found during 0.2.3 release-gate restore on Windows); immediate `watch::notify()` on macOS bind-mount container starts caused `FSEvents` `C`/`M`/`A` notifications to hit `kiri_inject.c`'s `__d_drop` and evict `struct fuse_inode`'s in-memory `chown_uid`/`chown_gid` (`bind-chown-chmod`) - Caused by: #825, #846, #852, #970 - Check: `agent-dies-beside-stuck-start`, `pulls-of-different-images-at-once-leave-a-sound-index`, `crates/kiri/src/domains_cli.rs`, `crates/kiri-image/src/registry.rs`, `crates/kiri-win/src/wslsync.rs` diff --git a/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch b/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch index 223f77617..74c53a50b 100644 --- a/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch +++ b/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch @@ -593,7 +593,7 @@ static int fuse_readdir_cached(struct file *file, struct dir_context *ctx) --- a/fs/notify/kiri_inject.c +++ b/fs/notify/kiri_inject.c -@@ -34,6 +34,7 @@ +@@ -34,30 +34,48 @@ #include #include #include @@ -601,86 +601,97 @@ #include #include #include -@@ -44,20 +45,33 @@ + #include + #include + ++#include "../fuse/fuse_i.h" ++ + #define KIRI_SHARE "/mnt/mac" #define KIRI_SCOPED (LOOKUP_BENEATH | LOOKUP_NO_SYMLINKS | LOOKUP_NO_XDEV | LOOKUP_NO_MAGICLINKS) - /* Drop a cached file or negative dentry so the next lookup asks the Mac. +-/* Drop a cached file or negative dentry so the next lookup asks the Mac. - * Directories and mount points stay reachable. */ -static void kiri_drop_dentry(struct dentry *dentry, bool negative_only) -+ * Directories and mount points stay reachable. When `inval_data` is set, -+ * also drop cached data pages so an already-open descriptor sees host writes. */ -+static void kiri_drop_dentry(struct dentry *dentry, bool negative_only, -+ bool inval_data) ++/* Drop a deleted/negative dentry or expire a positive file dentry so the next ++ * lookup revalidates with the Mac without evicting struct fuse_inode (keeping ++ * in-memory chown_uid/chown_gid intact when nodeid is unchanged). */ ++static void kiri_drop_dentry(struct dentry *dentry, bool drop, bool inval_data) { + struct inode *inode = NULL; + spin_lock(&dentry->d_lock); - if (!d_is_dir(dentry) && !d_mountpoint(dentry) && +- if (!d_is_dir(dentry) && !d_mountpoint(dentry) && - (!negative_only || d_really_is_negative(dentry))) -+ (!negative_only || d_really_is_negative(dentry))) { -+ if (inval_data && d_is_reg(dentry)) { +- __d_drop(dentry); ++ if (!d_is_dir(dentry) && !d_mountpoint(dentry)) { ++ if (drop || d_really_is_negative(dentry)) { ++ __d_drop(dentry); ++ } else { + inode = d_inode(dentry); + ihold(inode); + } - __d_drop(dentry); + } spin_unlock(&dentry->d_lock); + if (inode) { -+ invalidate_inode_pages2(inode->i_mapping); ++ fuse_invalidate_entry_cache(dentry); ++ fuse_invalidate_attr(inode); ++ if (inval_data && S_ISREG(inode->i_mode)) ++ invalidate_inode_pages2(inode->i_mapping); + iput(inode); + } } /* Walk `rel` below `root` in the guest dcache only (no filesystem lookups or - * revalidations to the Mac) and drop the final dentry if cached. */ +- * revalidations to the Mac) and drop the final dentry if cached. */ ++ * revalidations to the Mac) and drop or expire the final dentry if cached. */ static void kiri_drop_cached(struct dentry *root, const char *rel, - bool negative_only) -+ bool negative_only, bool inval_data) ++ bool drop, bool inval_data) { struct dentry *cur = dget(root); const char *p = rel; -@@ -80,7 +94,7 @@ +@@ -80,7 +98,7 @@ cur = next; p = slash + 1; } else { - kiri_drop_dentry(next, negative_only); -+ kiri_drop_dentry(next, negative_only, inval_data); ++ kiri_drop_dentry(next, drop, inval_data); dput(next); return; } -@@ -98,7 +112,7 @@ +@@ -98,7 +116,7 @@ if (IS_ERR(child)) return PTR_ERR(child); if (child) - kiri_drop_dentry(child, false); -+ kiri_drop_dentry(child, false, false); ++ kiri_drop_dentry(child, true, false); if (child && d_really_is_positive(child)) { struct inode *inode = d_inode(child); __u32 mask = FS_DELETE; -@@ -150,7 +164,7 @@ +@@ -150,7 +168,7 @@ /* Expire before looking up so a replacement or in-place * change refreshes attributes and inode before watchers * read; an inotify mark pins the inode across the drop. */ - kiri_drop_dentry(cached, op == 'C'); -+ kiri_drop_dentry(cached, op == 'C', op == 'M'); ++ kiri_drop_dentry(cached, false, op == 'M'); dput(cached); } } -@@ -230,12 +244,14 @@ +@@ -230,12 +248,14 @@ if (!fsnotify_sb_has_watchers(share.dentry->d_sb)) { switch (line[0]) { case 'D': -- case 'M': - case 'A': -- kiri_drop_cached(share.dentry, rel, false); -+ kiri_drop_cached(share.dentry, rel, false, false); ++ kiri_drop_cached(share.dentry, rel, true, false); + break; -+ case 'M': + case 'M': +- case 'A': +- kiri_drop_cached(share.dentry, rel, false); + kiri_drop_cached(share.dentry, rel, false, true); break; ++ case 'A': case 'C': - kiri_drop_cached(share.dentry, rel, true); -+ kiri_drop_cached(share.dentry, rel, true, false); ++ kiri_drop_cached(share.dentry, rel, false, false); break; default: err = -EINVAL; diff --git a/tests/e2e.sh b/tests/e2e.sh index e488b0e2c..2dc33c91b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -979,7 +979,11 @@ $D rm -f hn-all >/dev/null 2>&1 # goes through the Mac (#732). host.docker.internal answers only there. only mac t hostnet-dns-kiri "198.19.248.254" $D run --rm --network host alpine nslookup -timeout=5 host.docker.internal only mac t hostnet-dns-names "Address" $D run --rm --network host alpine nslookup -timeout=5 example.com -only linux,wsl t host-internal-not-loopback "Connection refused" $D run --rm alpine wget -qO- -T 3 http://host.docker.internal:18998/ +if [ "$SYS" = wsl ] && [ "$($D run --rm alpine getent hosts host.docker.internal 2>/dev/null | awk '{print $1}')" = 192.168.65.254 ]; then + skip host-internal-not-loopback "Windows host relay forwards localhost by design" +else + only linux,wsl t host-internal-not-loopback "Connection refused" $D run --rm alpine wget -qO- -T 3 http://host.docker.internal:18998/ +fi kill "$HTTP_PID" ${HTTP_LO_PID:+"$HTTP_LO_PID"}; rm -rf "$HTTP_DIR" section "container domains" @@ -2166,8 +2170,10 @@ else skip rename-dns-keeps-own-servers "no name can be resolved from here" fi # A name of a host stays the host's: the container is not given it. +RN_HOST_DNS=$($D run --rm --network rndns alpine nslookup host.docker.internal 127.0.0.11 | grep -A1 '^Name:' | tail -1) +case "$RN_HOST_DNS" in *198.*|*192.168.65.254*) ;; *) RN_HOST_DNS="198." ;; esac $D rename rndns-new host.docker.internal -t rename-dns-host-name-stays-host "198." bash -c "$D run --rm --network rndns alpine nslookup host.docker.internal 127.0.0.11 | grep -A1 '^Name:' | tail -1" +t rename-dns-host-name-stays-host "$RN_HOST_DNS" bash -c "$D run --rm --network rndns alpine nslookup host.docker.internal 127.0.0.11 | grep -A1 '^Name:' | tail -1" code rename-name-starts-with-letter 1 $D rename host.docker.internal _rndns $D rm -f rndns-new host.docker.internal >/dev/null 2>&1; $D rm -f rndns-old >/dev/null 2>&1; $D network rm rndns rndns2 >/dev/null # Rename edge cases (#467). An alias equal to the old name keeps resolving. diff --git a/tests/regressions.tsv b/tests/regressions.tsv index d467962e0..c3b111999 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -364,7 +364,7 @@ crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded ex tests/ui/volumes-size.js #936 Volumes view did not show each volume's disk size, and loading sizes synchronously or via GET /system/df could stall list refreshes or wake a sleeping VM crates/kiri/src/builds.rs #923 a running build's steps were read with `buildx history logs`, which follows the build until it ends: the Builds pane stayed on "Loading the steps..." and each 2 s ask left a docker and buildx process running tests/ui/builds-running.js #923 the Builds view asked for a running build's steps on every tick, not once the last ask was answered -crates/kiri/src/setup_win.rs #984 on Windows, `kiri setup`, `kiri import` and `kiri build-with` were missing from `kiri.exe`, uninstalling Docker Desktop wiped `%USERPROFILE%\.docker\config.json` (`cliPluginsExtraDirs`, `kiri` context, dangling `desktop-linux`), and `kiri` subcommands executed side effects or exited 1 on `--help` / `-h` (#982) +crates/kiri/src/setup_win.rs #984 on Windows, `kiri setup`, `kiri import` and `kiri build-with` were missing from `kiri.exe`, uninstalling Docker Desktop wiped `%USERPROFILE%\.docker\config.json` (`cliPluginsExtraDirs`, `kiri` context, dangling `desktop-linux`), `npipe_host` formatted `\\.\pipe\kiri` as `npipe://./pipe/kiri` instead of `npipe:////./pipe/kiri`, and `kiri` subcommands executed side effects or exited 1 on `--help` / `-h` (#982) crates/kiri-win/src/engine.rs #984 Windows `allowed_url` lacked `runkiri.com` and `canestack.com`, so Settings -> About links did not open, and `kiri-win` startup did not self-heal a wiped `~/.docker/config.json` vm-swap-as-set #326 the VM had no swap, so a container that outgrew the VM's memory was killed instead of slowing down vm-swap-container-over-memory #326 a container over its --memory with --memory-swap room left was killed: the VM had no swap for its pages @@ -380,3 +380,5 @@ crates/kiri/src/domains_cli.rs #744 `kiri domains set` and `kiri domains reset` crates/kiri-image/src/registry.rs #611 `Client::manifest` did not retry transient registry responses such as HTTP 429 during concurrent image pulls crates/kiri/src/daemon/storage.rs #190 `statvfs_usage` subtracted `f_bavail` instead of `f_bfree`, counting ~55 GB of ext4 root-reserved free blocks on WSL's sparse `ext4.vhdx` as used disk space crates/kiri/src/dockerctx.rs #269 Windows `repair_windows_config` did not self-heal `%USERPROFILE%\.docker\contexts\meta\\meta.json` when overwritten with a WSL `unix://` socket endpoint +crates/kiri-proto/src/lib.rs #381 `start_on_vm` spawned the container process before attaching `spec.extra_networks`, causing fast `docker compose run` commands on secondary external networks to run before `eth1` and its IPv4 default route were attached +crates/kiri/src/daemon/binds.rs #420 WSL distro bind translation rewrote `/run/host-services/ssh-auth.sock` and `/sys` paths into `/mnt/wsl/kiri/roots//...`, and local `o=bind` volumes did not resolve `device` relative to the calling WSL distro or Windows drive