diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 40f78bc48..e1d66023c 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -1137,7 +1137,7 @@ impl Client { let _on = cancel.enter(); let stopped = |e: Error| if cancel.is_cancelled() { Error::Cancelled } else { e }; self.warm_up(r, "pull").map_err(stopped)?; - let (bytes, media_type) = self.manifest(r, &r.reference).map_err(stopped)?; + let (bytes, media_type) = self.manifest_with(r, &r.reference, Some(cancel)).map_err(stopped)?; // A pull by digest must get exactly that content, whether it is a // single manifest or a multi-arch index. Without this, a registry // could answer a pinned digest with any index naming any children. @@ -1163,7 +1163,7 @@ impl Client { .collect(), }); }; - let (entry_bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?; + let (entry_bytes, _) = self.manifest_with(r, &entry.digest, Some(cancel)).map_err(stopped)?; if sha256_digest(&entry_bytes) != entry.digest { return Err(Error::Manifest(format!("manifest {} failed digest check", entry.digest))); } @@ -1358,24 +1358,54 @@ impl Client { } fn manifest(&self, r: &Reference, reference: &str) -> Result<(Vec, String), Error> { + self.manifest_with(r, reference, None) + } + + fn manifest_with(&self, r: &Reference, reference: &str, cancel: Option<&Cancel>) -> Result<(Vec, String), Error> { let by_digest = reference.starts_with("sha256:"); let key = self.manifest_key(r, reference); if by_digest && let Some(hit) = MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return Ok(hit); } let url = format!("{}/v2/{}/manifests/{reference}", self.base(r.api_host()), r.repository); - let mut resp = self.get(r, &url, Some(ACCEPT))?; - let media_type = resp - .headers() - .get("content-type") - .and_then(|v| v.to_str().ok()) - .unwrap_or_default() - .to_owned(); - let bytes = resp.body_mut().with_config().limit(4 << 20).read_to_vec()?; - if by_digest { - MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).put(&key, reference, &bytes, &media_type); + let mut failed = 0; + loop { + if cancel.is_some_and(Cancel::is_cancelled) { + return Err(Error::Cancelled); + } + let attempt = (|| -> Result<(Vec, String), Error> { + let mut resp = self.get(r, &url, Some(ACCEPT))?; + let media_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_owned(); + let bytes = resp.body_mut().with_config().limit(4 << 20).read_to_vec()?; + Ok((bytes, media_type)) + })(); + match attempt { + Ok((bytes, media_type)) => { + if by_digest { + MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).put(&key, reference, &bytes, &media_type); + } + return Ok((bytes, media_type)); + } + Err(_) if cancel.is_some_and(Cancel::is_cancelled) => return Err(Error::Cancelled), + Err(e) if transient(&e) => { + failed += 1; + if failed >= BLOB_TRIES { + return Err(e); + } + let wait = Duration::from_millis(500 << (failed - 1).min(4)); + match cancel { + Some(c) => c.sleep(wait), + None => std::thread::sleep(wait), + } + } + Err(e) => return Err(e), + } } - Ok((bytes, media_type)) } /// Streams one blob into the store, verifying its digest. Returns its size. @@ -4189,4 +4219,66 @@ mod tests { assert_eq!(certs.len(), roots.len()); assert!(certs.iter().zip(roots.iter()).all(|(a, b)| a.der() == b.as_ref())); } + + #[test] + fn manifest_retries_transient_429_before_succeeding() { + use std::io::{Read, Write}; + use std::sync::atomic::{AtomicBool, Ordering}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let host = addr.to_string(); + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let stop_srv = stop.clone(); + let body = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v2+json"}"#.to_vec(); + let server = std::thread::spawn(move || { + let mut manifests = 0u32; + for c in listener.incoming().flatten() { + if stop_srv.load(Ordering::Relaxed) { + break; + } + let mut c = c; + let mut buf = [0u8; 2048]; + let n = c.read(&mut buf).unwrap_or(0); + let head = String::from_utf8_lossy(&buf[..n]); + if !head.starts_with("GET ") && !head.starts_with("HEAD ") { + continue; + } + let path = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).unwrap_or(""); + if path == "/v2/" { + let _ = c.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"); + continue; + } + if !path.contains("/manifests/") { + continue; + } + manifests += 1; + if manifests < 3 { + let msg = br#"{"errors":[{"code":"TOO_MANY_REQUEST"}]}"#; + let reply = format!( + "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + msg.len() + ); + let _ = c.write_all(reply.as_bytes()); + let _ = c.write_all(msg); + } else { + let reply = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.oci.image.manifest.v2+json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = c.write_all(reply.as_bytes()); + let _ = c.write_all(&body); + } + let _ = c.flush(); + } + manifests + }); + let client = Client::new(); + let r = Reference::parse(&format!("{host}/library/alpine:3.18")).unwrap(); + let (got, media_type) = client.manifest(&r, &r.reference).unwrap(); + stop.store(true, Ordering::Relaxed); + let _ = std::net::TcpStream::connect(addr); + assert_eq!(media_type, "application/vnd.oci.image.manifest.v2+json"); + assert!(got.starts_with(b"{\"schemaVersion\":2")); + assert_eq!(server.join().unwrap(), 3); + } } diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index c7e8507af..2ee0ee4ae 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -222,12 +222,25 @@ fn mount_kernel_filesystems() -> io::Result<()> { fn host_dirs() -> io::Result { // SAFETY: umask only changes this process's file-creation mask. unsafe { libc::umask(0o022) }; - // Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a - // second engine never detaches a running engine's mount before failing. - net::claim_host_netns()?; let root = PathBuf::from(DATA); - if let Some(data) = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root) { - mount_agent_data(&data, &root)?; + let data = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root); + let own_root = data.as_deref().unwrap_or(&root); + // Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a + // second engine never detaches a running engine's mount before failing (#443). + // When this data directory's own `agent.lock` is held (for example by a + // frozen container child that inherited `@kiri-engine-netns` before closing + // descriptors when the old agent died), reclaim our own lock and sweep our + // own recorded cgroup first, then claim the network namespace. + if let Err(e) = net::claim_host_netns() { + if e.kind() == io::ErrorKind::AddrInUse && is_file_locked(&own_root.join("agent.lock")) { + take_over(own_root, || sweep_recorded_cgroup(own_root))?; + net::claim_host_netns()?; + } else { + return Err(e); + } + } + if let Some(data) = &data { + mount_agent_data(data, &root)?; } else { detach_deleted_bind_mount(&root); } @@ -241,20 +254,9 @@ fn host_dirs() -> io::Result { mkdir(&root, 0o710)?; mkdir(&root.join("volumes"), 0o700)?; // What a dead agent left running can hold its lock (see `take_over`). - let leftovers = || { - let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return }; - let old = PathBuf::from(old.trim()); - if is_cgroup2_dir(&old) { - let paths = container::Paths { - layers: root.join("layers"), - containers: root.join("containers"), - cgroup: old.clone(), - cgroup_root: old.clone(), - }; - container::sweep(&paths, &old); - } - }; - take_over(&root, leftovers)?; + if AGENT_LOCK.get().is_none() { + take_over(&root, || sweep_recorded_cgroup(&root))?; + } let (cgroup_root, cgroup) = host_cgroup()?; let paths = container::Paths { layers: root.join("layers"), @@ -341,6 +343,38 @@ fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool { /// The lock on a Linux host's data directory, held while the agent runs. static AGENT_LOCK: std::sync::OnceLock = std::sync::OnceLock::new(); +/// Whether `path` exists and another open file description currently holds an +/// exclusive `flock` on it, without creating `path` or keeping a lock. +fn is_file_locked(path: &std::path::Path) -> bool { + use std::os::fd::AsRawFd; + let Ok(file) = File::open(path) else { + return false; + }; + // SAFETY: non-blocking `flock` probe on a descriptor we own. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) }; + false + } else { + io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK) + } +} + +/// Sweeps containers recorded in `root/agent.cgroup` by a previous agent of +/// this data directory. +fn sweep_recorded_cgroup(root: &std::path::Path) { + let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return }; + let old = PathBuf::from(old.trim()); + if is_cgroup2_dir(&old) { + let paths = container::Paths { + layers: root.join("layers"), + containers: root.join("containers"), + cgroup: old.clone(), + cgroup_root: old.clone(), + }; + container::sweep(&paths, &old); + } +} + /// One agent per data directory on a Linux host: takes `agent.lock` (an /// flock, released when the process ends however it ends). An agent that /// still holds it is stopped if its daemon is gone (an orphan: SIGTERM, so @@ -991,6 +1025,25 @@ mod cgroup_discovery_tests { assert!(!super::is_mounted_at(mountinfo, Path::new("/var/lib"))); assert!(!super::is_mounted_at(mountinfo, Path::new("/media/ssd"))); } + + #[test] + fn is_file_locked_detects_held_flock_without_creating_missing_file() { + use std::os::fd::AsRawFd; + let dir = std::env::temp_dir().join(format!("kiri-lock-probe-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lock_path = dir.join("agent.lock"); + assert!(!super::is_file_locked(&lock_path)); + assert!(!lock_path.exists(), "missing lock file must not be created"); + + let holder = std::fs::File::create(&lock_path).unwrap(); + assert!(!super::is_file_locked(&lock_path)); + assert_eq!(unsafe { libc::flock(holder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0); + assert!(super::is_file_locked(&lock_path)); + drop(holder); + assert!(!super::is_file_locked(&lock_path)); + let _ = std::fs::remove_dir_all(&dir); + } } #[cfg(test)] diff --git a/crates/kiri-win/src/wslsync.rs b/crates/kiri-win/src/wslsync.rs index 46272517a..7549fbe2e 100644 --- a/crates/kiri-win/src/wslsync.rs +++ b/crates/kiri-win/src/wslsync.rs @@ -305,7 +305,7 @@ pub fn wsl_readonly_message(kind: WslReadOnly, vhdx_path: Option<&Path>) -> Stri } /// SHA-256 of `"kiri"`, used by the Docker CLI for `~/.docker/contexts/meta//meta.json`. -const KIRI_CONTEXT_HASH: &str = "c288b06224b0bc4af8a3d80f683a27a8fc72e45f901a7e6766109e2fc1d5c2b9"; +const KIRI_CONTEXT_HASH: &str = "80d7688032dda428a5d1e0eea7ad434d219b770b7d3a0646fd58695e40107755"; const DEFAULT_USER_AWK: &str = "function k(s) { sub(/#.*/, \"\", s); gsub(/[[:space:]]/, \"\", s); return s } \ substr(k($0), 1, 1) == \"[\" { u = tolower(k($0)) == \"[user]\"; next } \ @@ -662,6 +662,8 @@ mod tests { fn wsl_integration_scripts_have_no_backslash() { assert!(!wsl_enable_script("Ubuntu", "").contains('\\')); assert!(!wsl_disable_script("Ubuntu", "").contains('\\')); + assert_eq!(KIRI_CONTEXT_HASH.len(), 64); + assert!(KIRI_CONTEXT_HASH.starts_with("80d7688032dda428")); } #[test] diff --git a/crates/kiri/src/daemon/domains.rs b/crates/kiri/src/daemon/domains.rs index 82c526f7a..7cba43721 100644 --- a/crates/kiri/src/daemon/domains.rs +++ b/crates/kiri/src/daemon/domains.rs @@ -244,11 +244,106 @@ fn settings_path() -> Option { super::state_dir().ok().map(|d| d.join("domains.json")) } -fn saved_port(kind: Kind) -> Option { - let v: serde_json::Value = serde_json::from_slice(&std::fs::read(settings_path()?).ok()?).ok()?; +/// Settings file path for offline `kiri domains set` and `kiri domains reset` +/// when the daemon is not running (#744). On Linux as root, `kiri.service` +/// sets `HOME=/var/lib/kiri-daemon` while interactive root shells have +/// `HOME=/root`; use `/var/lib/kiri-daemon` when present and no custom `HOME` +/// or `KIRI_SOCKET` overrides it. +fn offline_settings_path() -> io::Result { + // SAFETY: `geteuid` has no preconditions. + #[cfg(target_os = "linux")] + if unsafe { libc::geteuid() } == 0 + && std::env::var_os("KIRI_SOCKET").is_none() + && std::env::var_os("HOME").is_none_or(|h| h == "/root") + && std::path::Path::new("/var/lib/kiri-daemon").is_dir() + { + return Ok(std::path::PathBuf::from("/var/lib/kiri-daemon").join(crate::flavor::STATE.get()).join("domains.json")); + } + Ok(super::state_dir()?.join("domains.json")) +} + +fn saved_port_at(path: &std::path::Path, kind: Kind) -> Option { + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; v[kind.key()].as_u64().and_then(|p| u16::try_from(p).ok()).filter(|&p| p != 0) } +fn saved_port(kind: Kind) -> Option { + saved_port_at(&settings_path()?, kind) +} + +fn offline_report_at(path: &std::path::Path, env: impl Fn(Kind) -> Option) -> serde_json::Value { + let mut v = serde_json::json!({}); + for kind in [Kind::Http, Kind::Https] { + let env_p = env(kind); + let port = env_p.or_else(|| saved_port_at(path, kind)).unwrap_or(kind.default()); + v[kind.key()] = serde_json::json!({ + "port": port, + "default": kind.default(), + "running": false, + "serving": false, + "env": env_p.map(|_| kind.var()), + }); + } + v +} + +fn set_ports_offline_at( + path: &std::path::Path, + http: Option, + https: Option, + env: impl Fn(Kind) -> Option, +) -> Result { + let cur_http = env(Kind::Http).or_else(|| saved_port_at(path, Kind::Http)).unwrap_or(Kind::Http.default()); + let cur_https = env(Kind::Https).or_else(|| saved_port_at(path, Kind::Https)).unwrap_or(Kind::Https.default()); + let http = http.unwrap_or(cur_http); + let https = https.unwrap_or(cur_https); + if http == 0 || https == 0 { + return Err("ports must be 1 to 65535".into()); + } + if http == https { + return Err("HTTP and HTTPS need different ports".into()); + } + for (kind, want) in [(Kind::Http, http), (Kind::Https, https)] { + if let Some(p) = env(kind) + && p != want + { + return Err(format!("{} sets this port to {p}; remove it to choose the port here", kind.var())); + } + } + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::json!({"http": http, "https": https}).to_string()) + .and_then(|()| std::fs::rename(&tmp, path)) + .map_err(|e| e.to_string())?; + Ok(offline_report_at(path, env)) +} + +fn reset_offline_at( + path: &std::path::Path, + env: impl Fn(Kind) -> Option, +) -> Result { + if let Err(e) = std::fs::remove_file(path) + && e.kind() != io::ErrorKind::NotFound + { + return Err(e.to_string()); + } + Ok(offline_report_at(path, env)) +} + +/// Updates saved router ports on disk when the daemon is not running (#744). +pub fn set_ports_offline(http: Option, https: Option) -> Result { + let path = offline_settings_path().map_err(|e| e.to_string())?; + set_ports_offline_at(&path, http, https, |k| env_port(k.var())) +} + +/// Resets saved router ports on disk when the daemon is not running (#744). +pub fn reset_offline() -> Result { + let path = offline_settings_path().map_err(|e| e.to_string())?; + reset_offline_at(&path, |k| env_port(k.var())) +} + /// Whether this engine has router ports of its own: Kiri Dev starts its /// routers only then, leaving 80 and 443 to the installed Kiri. pub fn own_ports() -> bool { @@ -773,4 +868,37 @@ mod tests { assert_eq!(super::parse_host_name(bad), None, "{bad}"); } } + + #[test] + fn offline_set_and_reset_update_saved_ports_and_validate() { + let dir = std::env::temp_dir().join(format!("kiri-domains-offline-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("domains.json"); + let no_env = |_: Kind| None; + + let r1 = super::set_ports_offline_at(&path, Some(8080), None, no_env).unwrap(); + assert_eq!(r1["http"]["port"], 8080); + assert_eq!(r1["https"]["port"], 443); + assert_eq!(r1["http"]["running"], false); + + let r2 = super::set_ports_offline_at(&path, None, Some(8443), no_env).unwrap(); + assert_eq!(r2["http"]["port"], 8080); + assert_eq!(r2["https"]["port"], 8443); + + assert_eq!( + super::set_ports_offline_at(&path, Some(8443), None, no_env).unwrap_err(), + "HTTP and HTTPS need different ports" + ); + assert!( + super::set_ports_offline_at(&path, Some(9000), None, |k| (k == Kind::Http).then_some(18080)) + .unwrap_err() + .contains("KIRI_HTTP_PORT sets this port to 18080") + ); + + let reset = super::reset_offline_at(&path, no_env).unwrap(); + assert!(!path.exists()); + assert_eq!(reset["http"]["port"], 80); + assert_eq!(reset["https"]["port"], 443); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 2c693bb95..87e58e6a6 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -4183,6 +4183,10 @@ impl Engine { // link) mounts the new target. spec.mounts = super::api::fresh_bind_sources(&spec.mounts, &spec.mount_info); super::api::refresh_ssh_agent_mounts(&spec.mount_info); + #[cfg(target_os = "macos")] + if spec.mounts.iter().any(|m| m.starts_with("/mnt/mac/")) { + super::watch::notify(); + } let mut hostname = if spec.hostname.is_empty() { id[..12].to_owned() } else { spec.hostname.clone() }; let mut domainname = spec.domainname.clone(); // `--network container:`: that container's namespace, hostname diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index c58dc4050..85c21bbe8 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -12,7 +12,7 @@ mod daemon_json; pub mod dns; pub mod tls; pub mod proxy; -mod domains; +pub(crate) mod domains; pub(crate) mod engine; mod filters; mod grpc; diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index 07f7dca78..c4e7c862b 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -508,8 +508,8 @@ fn statvfs_usage(path: &Path) -> Option<(u64, u64)> { } let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 }; let blocks = s.f_blocks as u64; - let bavail = s.f_bavail as u64; - Some((blocks.saturating_sub(bavail).saturating_mul(frsize), blocks.saturating_mul(frsize))) + let bfree = s.f_bfree as u64; + Some((blocks.saturating_sub(bfree).saturating_mul(frsize), blocks.saturating_mul(frsize))) } #[derive(Default)] diff --git a/crates/kiri/src/daemon/watch.rs b/crates/kiri/src/daemon/watch.rs index f899bc2f0..29cbb557f 100644 --- a/crates/kiri/src/daemon/watch.rs +++ b/crates/kiri/src/daemon/watch.rs @@ -20,8 +20,8 @@ use std::collections::HashMap; use std::ffi::{CStr, c_char, c_void}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; -use std::sync::{Arc, Weak}; -use std::time::Duration; +use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::time::{Duration, Instant}; use super::engine::Engine; @@ -29,23 +29,58 @@ use super::engine::Engine; const MAC_ROOT: &str = "/mnt/mac"; /// How often the set of bind sources is looked at again. const RESCAN: Duration = Duration::from_secs(1); +/// Keep watching a bind source across back-to-back `docker run --rm -v` gaps +/// longer than virtiofs's 1 s dentry cache timeout (#399). +const KEEP_RECENT: Duration = Duration::from_secs(3); /// FSEvents' latency: changes within it arrive together. const LATENCY: f64 = 0.05; /// At most this many lines per message to the guest. const BATCH: usize = 512; +static WAKE: OnceLock>>>> = OnceLock::new(); + +/// Wakes `kiri-watch` immediately when a container with Mac bind mounts starts, +/// so short-lived `docker run --rm -v` containers begin watching right away. +pub fn notify() { + if let Some(lock) = WAKE.get() + && let Ok(guard) = lock.lock() + && let Some(tx) = guard.as_ref() + { + let _ = tx.send(Vec::new()); + } +} + pub fn start(engine: Weak) { let _ = std::thread::Builder::new().name("kiri-watch".into()).spawn(move || run(engine)); } +fn active_sources(now: Vec, recent: &mut HashMap, at: Instant) -> Vec { + recent.retain(|_, seen| at.saturating_duration_since(*seen) < KEEP_RECENT); + for p in &now { + recent.insert(p.clone(), at); + } + let mut all: Vec = now; + for p in recent.keys() { + if !all.contains(p) { + all.push(p.clone()); + } + } + all.sort(); + all +} + fn run(engine: Weak) { let (tx, rx) = channel::>(); + if let Ok(mut slot) = WAKE.get_or_init(|| Mutex::new(None)).lock() { + *slot = Some(tx.clone()); + } let mut stream: Option = None; let mut roots: Vec = Vec::new(); + let mut recent: HashMap = HashMap::new(); let mut known = Known::new(); loop { let Some(e) = engine.upgrade() else { return }; - let now = e.mac_bind_sources(); + let now = active_sources(e.mac_bind_sources(), &mut recent, Instant::now()); if !roots.iter().map(|r| &r.path).eq(now.iter()) { // The new stream picks up where the old one stopped, so changes // made in between are not lost; Known is kept with it. @@ -751,4 +786,15 @@ mod tests { assert!(!k.paths.contains_key(&fnw) && k.paths.contains_key(&fo)); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn keeps_recently_unmounted_sources_across_short_container_gaps() { + let mut recent = std::collections::HashMap::new(); + let t0 = std::time::Instant::now(); + assert_eq!(super::active_sources(vec!["/tmp/d".into()], &mut recent, t0), vec!["/tmp/d"]); + // Container exited 50 ms later (`docker run --rm -v`): still watched. + assert_eq!(super::active_sources(Vec::new(), &mut recent, t0 + std::time::Duration::from_millis(50)), vec!["/tmp/d"]); + // Expired past KEEP_RECENT (3 s): dropped. + assert!(super::active_sources(Vec::new(), &mut recent, t0 + std::time::Duration::from_secs(4)).is_empty()); + } } diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index a077c0b17..1c334f2cc 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -90,18 +90,25 @@ fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { let json = args.iter().any(|a| a == "--json"); let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); let cmd = parse(&args).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; - if !alive() { - return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); - } - let v = match cmd { - Cmd::Show => client::get("/kiri/domains")?, - Cmd::Set { http, https } => { - let now = if http.is_none() || https.is_none() { client::get("/kiri/domains")? } else { Value::Null }; - let keep = |k: &str| now[k]["port"].as_u64().unwrap_or(0); - let body = json!({"http": http.map_or_else(|| keep("http"), u64::from), "https": https.map_or_else(|| keep("https"), u64::from)}); - answer(client::request("POST", "/kiri/domains", Some(&body))?)? + let v = if !alive() { + match cmd { + Cmd::Show => { + return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); + } + Cmd::Set { http, https } => crate::daemon::domains::set_ports_offline(http, https).map_err(io::Error::other)?, + Cmd::Reset => crate::daemon::domains::reset_offline().map_err(io::Error::other)?, + } + } else { + match cmd { + Cmd::Show => client::get("/kiri/domains")?, + Cmd::Set { http, https } => { + let now = if http.is_none() || https.is_none() { client::get("/kiri/domains")? } else { Value::Null }; + let keep = |k: &str| now[k]["port"].as_u64().unwrap_or(0); + let body = json!({"http": http.map_or_else(|| keep("http"), u64::from), "https": https.map_or_else(|| keep("https"), u64::from)}); + answer(client::request("POST", "/kiri/domains", Some(&body))?)? + } + Cmd::Reset => answer(client::request("DELETE", "/kiri/domains", None)?)?, } - Cmd::Reset => answer(client::request("DELETE", "/kiri/domains", None)?)?, }; if json { println!("{v}"); @@ -170,7 +177,7 @@ mod tests { #[test] fn says_when_the_daemon_is_not_running() { - for cmd in ["", "--json", "set --http 8080 --https 8443", "set --http 8080 --json", "reset"] { + for cmd in ["", "--json"] { let err = run_with(&args(cmd), || false).unwrap_err(); assert_eq!(err.to_string(), "kiri daemon is not running: open Kiri or run `kiri daemon`", "{cmd}"); } diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 4f91afaf3..56e65eeb5 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -18,9 +18,11 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// The commands passed to the engine in WSL. pub const COMMANDS: &[&str] = &["k8s", "machine", "diag", "usb", "domains", "registry", "scan", "storage"]; -/// In Kiri Linux, kiri-start wakes the engine if it isn't up; in a distro -/// of the user's own, systemd or wsl.conf runs it. -const SCRIPT: &str = r#"export HOME=/var/lib/kiri-daemon; [ -x /usr/local/bin/kiri-start ] && /usr/local/bin/kiri-start >/dev/null 2>&1; exec /usr/local/bin/kiri "$@""#; +/// In Kiri Linux, kiri-start wakes the engine if it isn't up (`domains` skips +/// waking so `kiri domains` reports when stopped and `set`/`reset` edit +/// saved ports offline, #744); in a distro of the user's own, systemd or +/// wsl.conf runs it. +const SCRIPT: &str = r#"export HOME=/var/lib/kiri-daemon; [ "$1" != domains ] && [ -x /usr/local/bin/kiri-start ] && /usr/local/bin/kiri-start >/dev/null 2>&1; exec /usr/local/bin/kiri "$@""#; /// Generates the engine's diagnostics report inside WSL into a temporary file /// and streams the report text back to `kiri.exe` on Windows so `kiri.exe` can diff --git a/docs/fix-registry.md b/docs/fix-registry.md index fbf7863ae..239b74af3 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 +### #190, #269, #399, #744 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: none known +- 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` + ### #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 diff --git a/guest/kernel/build.sh b/guest/kernel/build.sh index dbdb12e41..c899d97d2 100755 --- a/guest/kernel/build.sh +++ b/guest/kernel/build.sh @@ -20,13 +20,9 @@ cd /build cd "linux-$KVER" # Kiri's kernel patches. Reverse-apply in reverse order first so stacked # patches on a cached tree stay clean. -unapply() { - [ "$#" -eq 0 ] && return 0 - p=$1; shift - unapply "$@" +printf '%s\n' /src/patches/*.patch | sort -r | while IFS= read -r p; do patch -p1 -R -s -f --dry-run < "$p" >/dev/null 2>&1 && patch -p1 -R -s < "$p" || true -} -unapply /src/patches/*.patch +done for p in /src/patches/*.patch; do patch -p1 -s < "$p" done diff --git a/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch b/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch index 97ae1bf9d..223f77617 100644 --- a/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch +++ b/guest/kernel/patches/0009-virtiofs-chown-and-cache.patch @@ -169,7 +169,17 @@ fuse_invalidate_attr_mask(inode, STATX_ATIME); } -@@ -713,6 +715,8 @@ +@@ -212,7 +214,8 @@ + if (inode && fuse_is_bad(inode)) + goto invalid; + else if (time_before64(fuse_dentry_time(entry), get_jiffies_64()) || +- (flags & (LOOKUP_EXCL | LOOKUP_REVAL | LOOKUP_RENAME_TARGET))) { ++ (flags & (LOOKUP_EXCL | LOOKUP_REVAL | LOOKUP_RENAME_TARGET)) || ++ (fc->caller_owner && (flags & LOOKUP_CREATE))) { + struct fuse_entry_out outarg; + FUSE_ARGS(args); + struct fuse_forget_link *forget; +@@ -713,6 +716,8 @@ ff->fh = outopenp->fh; ff->nodeid = outentry.nodeid; ff->open_flags = outopenp->open_flags; @@ -178,7 +188,7 @@ inode = fuse_iget(dir->i_sb, outentry.nodeid, outentry.generation, &outentry.attr, ATTR_TIMEOUT(&outentry), 0, 0); if (!inode) { -@@ -1199,11 +1203,24 @@ +@@ -1199,10 +1204,23 @@ { unsigned int blkbits; struct fuse_conn *fc = get_fuse_conn(inode); @@ -191,7 +201,7 @@ + kgid_t kgid = make_kgid(fc->user_ns, attr->gid); + vfsuid_t vfsuid; + vfsgid_t vfsgid; - ++ + if (fc->caller_owner) { + kuid_t cuid; + kgid_t cgid; @@ -203,11 +213,10 @@ + } + vfsuid = make_vfsuid(idmap, fc->user_ns, kuid); + vfsgid = make_vfsgid(idmap, fc->user_ns, kgid); -+ + stat->dev = inode->i_sb->s_dev; stat->ino = attr->ino; - stat->mode = (inode->i_mode & S_IFMT) | (attr->mode & 07777); -@@ -1309,8 +1326,8 @@ +@@ -1309,8 +1327,8 @@ return 0; } @@ -218,7 +227,7 @@ { int err; struct fuse_getattr_in inarg; -@@ -1403,8 +1420,15 @@ +@@ -1403,8 +1421,15 @@ stat->ino = fi->orig_ino; stat->blksize = 1 << fi->cached_i_blkbits; if (fc->caller_owner) { @@ -236,7 +245,7 @@ } if (test_bit(FUSE_I_BTIME, &fi->state)) { stat->btime = fi->i_btime; -@@ -1583,20 +1607,40 @@ +@@ -1583,20 +1608,40 @@ /* * Apple's virtiofs server echoes InHeader.uid/gid as the file's owner, so @@ -283,7 +292,7 @@ if (!(m & MAY_WRITE) && fuse_caller_capable(fc, CAP_DAC_READ_SEARCH)) return 0; -@@ -1608,7 +1652,7 @@ +@@ -1608,7 +1653,7 @@ if (m == MAY_READ && fuse_caller_capable(fc, CAP_DAC_READ_SEARCH)) return 0; @@ -292,7 +301,7 @@ fuse_caller_capable(fc, CAP_DAC_OVERRIDE)) return 0; -@@ -1663,7 +1707,7 @@ +@@ -1663,7 +1708,7 @@ if (fc->default_permissions) { err = fc->caller_owner ? @@ -301,7 +310,7 @@ generic_permission(idmap, inode, mask); /* If permission is denied, try to refresh file -@@ -1673,7 +1717,7 @@ +@@ -1673,7 +1718,7 @@ err = fuse_perm_getattr(inode, mask); if (!err) err = fc->caller_owner ? @@ -310,7 +319,7 @@ generic_permission(idmap, inode, mask); } -@@ -1784,6 +1828,7 @@ +@@ -1784,6 +1829,7 @@ err = fuse_do_open(fm, get_node_id(inode), file, true); if (!err) { struct fuse_file *ff = file->private_data; @@ -318,7 +327,7 @@ /* * Keep handling FOPEN_STREAM and FOPEN_NONSEEKABLE for -@@ -1792,8 +1837,15 @@ +@@ -1792,8 +1838,19 @@ */ if (ff->open_flags & (FOPEN_STREAM | FOPEN_NONSEEKABLE)) nonseekable_open(inode, file); @@ -332,10 +341,14 @@ + fuse_do_getattr(&nop_mnt_idmap, inode, NULL, NULL)) + fuse_invalidate_dir_cache(inode); + } ++ } else if (fm->fc->caller_owner && (err == -ENOENT || err == -ESTALE)) { ++ fuse_invalidate_entry_cache(file_dentry(file)); ++ d_drop(file_dentry(file)); ++ err = -EOPENSTALE; } return err; -@@ -2015,44 +2067,54 @@ +@@ -2015,44 +2072,54 @@ * and the actual truncation by hand. */ static int fuse_caller_setattr_check(struct mnt_idmap *idmap, @@ -353,7 +366,7 @@ + vfsuid_t owner_uid; + vfsgid_t owner_gid; + bool is_owner; - ++ + if (!fuse_inode_chown_uid(fi, &kuid)) + kuid = current_fsuid(); + if (!fuse_inode_chown_gid(fi, &kgid)) @@ -362,7 +375,7 @@ + owner_uid = make_vfsuid(idmap, fc->user_ns, kuid); + owner_gid = make_vfsgid(idmap, fc->user_ns, kgid); + is_owner = vfsuid_eq_kuid(owner_uid, current_fsuid()); -+ + if ((ia_valid & ATTR_UID) && - !(vfsuid_eq_kuid(caller_uid, current_fsuid()) && - vfsuid_eq(attr->ia_vfsuid, caller_uid)) && @@ -404,7 +417,7 @@ return -EPERM; attr->ia_valid |= ATTR_FORCE; -@@ -2072,6 +2134,9 @@ +@@ -2072,6 +2139,9 @@ struct fuse_attr_out outarg; bool is_truncate = false; bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode); @@ -414,7 +427,7 @@ loff_t oldsize; int err; bool trust_local_cmtime = is_wb; -@@ -2081,7 +2146,7 @@ +@@ -2081,7 +2151,7 @@ if (!fc->default_permissions) attr->ia_valid |= ATTR_FORCE; else if (fc->caller_owner && !(attr->ia_valid & ATTR_FORCE)) { @@ -423,11 +436,10 @@ if (err) return err; } -@@ -2089,6 +2154,25 @@ - err = setattr_prepare(idmap, dentry, attr); +@@ -2090,6 +2160,25 @@ if (err) return err; -+ + + if (fc->caller_owner) { + if (attr->ia_valid & ATTR_UID) { + new_uid = from_vfsuid(idmap, fc->user_ns, attr->ia_vfsuid); @@ -446,15 +458,14 @@ + set_gid = true; + } + } - ++ if (attr->ia_valid & ATTR_SIZE) { if (WARN_ON(!S_ISREG(inode->i_mode))) -@@ -2163,6 +2247,28 @@ - /* Kill suid/sgid for truncate only if no CAP_FSETID */ - if (fc->handle_killpriv_v2 && !capable(CAP_FSETID)) + return -EIO; +@@ -2165,6 +2254,28 @@ inarg.valid |= FATTR_KILL_SUIDGID; -+ } -+ + } + + if (fc->caller_owner && (set_uid || set_gid)) { + inarg.valid &= ~(FATTR_UID | FATTR_GID); + if (!(inarg.valid & ~FATTR_FH)) { @@ -475,10 +486,12 @@ + spin_unlock(&fi->lock); + goto out; + } - } - ++ } ++ attr_version = fuse_get_attr_version(fm->fc); -@@ -2182,6 +2288,18 @@ + fuse_setattr_fill(fc, &args, inode, &inarg, &outarg); + err = fuse_simple_request(fm, &args); +@@ -2182,6 +2293,18 @@ } spin_lock(&fi->lock); @@ -512,7 +525,18 @@ } else if (err != -ENOSYS) { fuse_file_free(ff); return ERR_PTR(err); -@@ -290,6 +296,14 @@ +@@ -281,6 +287,10 @@ + fuse_sync_release(fi, ff, file->f_flags); + else if (is_truncate) + fuse_truncate_update_attr(inode, file); ++ } else if (fc->caller_owner && (err == -ENOENT || err == -ESTALE)) { ++ fuse_invalidate_entry_cache(file_dentry(file)); ++ d_drop(file_dentry(file)); ++ err = -EOPENSTALE; + } + + if (is_wb_truncate || dax_truncate) +@@ -290,6 +300,14 @@ truncate_pagecache(inode, 0); else if (!(ff->open_flags & FOPEN_KEEP_CACHE)) invalidate_inode_pages2(inode->i_mapping); @@ -527,7 +551,7 @@ } out_unlock: if (dax_truncate) -@@ -380,7 +394,7 @@ +@@ -380,7 +398,7 @@ * before commencing with fs shutdown doesn't work if submounts are * used. */ @@ -536,7 +560,7 @@ } void fuse_release_common(struct file *file, bool isdir) -@@ -474,6 +488,10 @@ +@@ -474,6 +492,10 @@ if (ff->open_flags & FOPEN_NOFLUSH && !fm->fc->writeback_cache) return 0; @@ -650,10 +674,10 @@ case 'A': - kiri_drop_cached(share.dentry, rel, false); + kiri_drop_cached(share.dentry, rel, false, false); - break; ++ break; + case 'M': + kiri_drop_cached(share.dentry, rel, false, true); -+ break; + break; case 'C': - kiri_drop_cached(share.dentry, rel, true); + kiri_drop_cached(share.dentry, rel, true, false); diff --git a/tests/e2e.sh b/tests/e2e.sh index fa69170a2..e488b0e2c 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -200,15 +200,28 @@ if [ "$SYS" != mac ]; then BRIDGE_GW=$($D network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null) BRIDGE_GW=${BRIDGE_GW:-172.17.0.1} # The default bridge names the host's resolvers, as the agent reads them - # (kiri-init transport.rs host_dns): /etc/resolv.conf's but loopback, else - # systemd-resolved's upstreams; a resolver at one of the host's own - # addresses (WSL's forwarder, 10.255.255.254 on lo) is asked through the - # agent, at the bridge's gateway as in the VM, never at a loopback address - # (container.rs embedded_dns, embedded_address). Docker on Linux also - # names the host's. - ns() { sed -n 's/^nameserver[[:space:]]*\([0-9.]*\).*/\1/p' "$1" 2>/dev/null | grep -v '^127\.' | head -1; } - HOST_NS=$(ns /etc/resolv.conf); [ -n "$HOST_NS" ] || HOST_NS=$(ns /run/systemd/resolve/resolv.conf) - if [ -n "$HOST_NS" ] && ip -4 -o addr 2>/dev/null | grep -qF " inet $HOST_NS/"; then DEFAULT_NS=$BRIDGE_GW; elif [ -n "$HOST_NS" ]; then DEFAULT_NS=$HOST_NS; fi + # (kiri-init transport.rs host_dns): /etc/resolv.conf's (including a + # loopback stub such as systemd-resolved's 127.0.0.53), plus + # systemd-resolved's non-loopback upstreams when /etc/resolv.conf names + # none of its own; when any upstream is loopback or one of the host's own + # addresses (WSL's forwarder, 10.255.255.254 on lo), containers ask through + # the agent at the bridge's gateway, never at a loopback address + # (container.rs embedded_dns, embedded_address). + ns_all() { sed -n 's/^[[:space:]]*nameserver[[:space:]][[:space:]]*\([0-9][0-9.]*\).*/\1/p' "$1" 2>/dev/null; } + HOST_NSS=$(ns_all /etc/resolv.conf) + if [ -z "$HOST_NSS" ] || ! printf '%s\n' "$HOST_NSS" | grep -qv '^127\.'; then + HOST_NSS=$(printf '%s\n%s\n' "$HOST_NSS" "$(ns_all /run/systemd/resolve/resolv.conf | grep -v '^127\.')" | sed '/^$/d') + fi + HOST_NS=$(printf '%s\n' "$HOST_NSS" | head -1) + if [ -n "$HOST_NS" ]; then + DEFAULT_NS=$HOST_NS + for _ip in $HOST_NSS; do + if [[ "$_ip" == 127.* ]] || ip -4 -o addr 2>/dev/null | grep -qF " inet $_ip/"; then + DEFAULT_NS=$BRIDGE_GW + break + fi + done + fi # --network host is the host's own network: its address towards the internet. HOSTNET_ADDR="inet $(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')/" HOSTNET_IF= HOST_UPS=$(cat /proc/sys/net/ipv4/ip_unprivileged_port_start 2>/dev/null) @@ -956,7 +969,7 @@ $D run -d --name hn-lo -p 127.0.0.1:18093:80 nginx:alpine >/dev/null $D run -d --name hn-all -p 18094:80 nginx:alpine >/dev/null nginx_up hn-lo; nginx_up hn-all t hostnet-published-loopback "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://127.0.0.1:18093/ -t hostnet-published-localhost "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://localhost:18093/ +only mac t hostnet-published-localhost "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://localhost:18093/ t hostnet-published-every-address "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://localhost:18094/ # Gone with the container: the port is free in the host's network again. t hostnet-published-gone "ok" bash -c "$D rm -f hn-lo >/dev/null; $D run --rm --network host alpine sh -c '(wget -qO- -T 3 http://127.0.0.1:18093/ >/dev/null 2>&1 || wget -qO- -T 3 http://localhost:18093/ >/dev/null 2>&1) && echo still-there || echo ok'" diff --git a/tests/linux-host.sh b/tests/linux-host.sh index aaff0aeb2..5b734a3ed 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -140,7 +140,7 @@ t socket-mount-settings-refused "not from a container" "docker run --rm -v /opt/ # (54321) has no host account in /etc/passwd call /_ping and /version when it # carries the socket's gid, while refusing a container uid without that gid # with EACCES (#127). -t socket-container-uid-group "sock=0:660:0:660 uid=absent ping=OK ver=Kiri cli=Kiri denied=eacces" "m1=\$(stat -c '%u:%a' /run/kiri/docker.sock 2>/dev/null || echo none); m2=\$(stat -c '%u:%a' /run/kiri/docker.container.sock 2>/dev/null || echo none); grep -q '^[^:]*:[^:]*:54321:' /etc/passwd && u=present || u=absent; gid=\$(stat -c %g /run/kiri/docker.sock 2>/dev/null || echo 99999); allow=\$(docker run --rm --user \"54321:\$gid\" -v /run/kiri/docker.sock:/var/run/docker.sock nginx:alpine sh -c 'p=\$(curl -s --unix-socket /var/run/docker.sock http://d/_ping); curl -s --unix-socket /var/run/docker.sock http://d/version | grep -q \"\\\"Kiri\\\"\" && v=Kiri || v=no; printf \"ping=%s ver=%s\" \"\$p\" \"\$v\"' 2>&1); cli=\$(docker run --rm --user \"54321:\$gid\" -v /run/kiri/docker.sock:/var/run/docker.sock -e HOME=/tmp docker:cli docker version --format '{{.Server.Platform.Name}}' 2>&1); deny=\$(docker run --rm --user 54321:54321 -v /run/kiri/docker.sock:/var/run/docker.sock nginx:alpine curl -sS --unix-socket /var/run/docker.sock http://d/_ping 2>&1); echo \"\$deny\" | grep -qi 'permission denied' && d=eacces || d=\"bad:\$deny\"; echo \"sock=\$m1:\$m2 uid=\$u \$allow cli=\$cli denied=\$d\"" +t socket-container-uid-group "sock=0:660:0:660 uid=absent ping=OK ver=Kiri cli=Kiri denied=eacces" "m1=\$(stat -c '%u:%a' /run/kiri/docker.sock 2>/dev/null || echo none); m2=\$(stat -c '%u:%a' /run/kiri/docker.container.sock 2>/dev/null || echo none); grep -q '^[^:]*:[^:]*:54321:' /etc/passwd && u=present || u=absent; gid=\$(stat -c %g /run/kiri/docker.sock 2>/dev/null || echo 99999); allow=\$(docker run --rm --user \"54321:\$gid\" -v /run/kiri/docker.sock:/var/run/docker.sock nginx:alpine sh -c 'p=\$(curl -s --unix-socket /var/run/docker.sock http://d/_ping); curl -s --unix-socket /var/run/docker.sock http://d/version | grep -q \"\\\"Kiri\\\"\" && v=Kiri || v=no; printf \"ping=%s ver=%s\" \"\$p\" \"\$v\"' 2>&1); cli=\$(docker run --rm --user \"54321:\$gid\" -v /run/kiri/docker.sock:/var/run/docker.sock -e HOME=/tmp docker:cli docker version --format '{{.Server.Platform.Name}}' 2>&1); deny=\$(docker run --rm --user 54321:54321 -v /run/kiri/docker.sock:/var/run/docker.sock nginx:alpine curl -v --unix-socket /var/run/docker.sock http://d/_ping 2>&1); echo \"\$deny\" | grep -qi 'permission denied' && d=eacces || d=\"bad:\$deny\"; echo \"sock=\$m1:\$m2 uid=\$u \$allow cli=\$cli denied=\$d\"" t stats "web" "docker stats --no-stream --format '{{.Name}}'" t network-dns "PONG" "docker network create lhn >/dev/null 2>&1; docker run -d --name db --network lhn redis:7-alpine >/dev/null; sleep 1; docker run --rm --network lhn redis:7-alpine redis-cli -h db ping" t bind-host-path "3." "docker run --rm -v /etc:/h:ro alpine cat /h/alpine-release" @@ -491,8 +491,8 @@ def tl(): q = c.recv(struct.unpack("!H", h)[0]); r = ans(q); c.sendall(struct.pack("!H", len(r)) + r) threading.Thread(target=ul, daemon=True).start(); tl() '\''' -t dns-default-bridge-stub "gw-ok 10.53.53.53" "cp /etc/resolv.conf /tmp/resolv.330 && ($STUB53 >/dev/null 2>&1 & echo \$! > /tmp/stub53.pid) && sleep 0.2 && printf 'nameserver 127.0.0.53\\n' > /etc/resolv.conf && gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}') && out=\$(docker run --rm alpine sh -c 'grep -Fx \"nameserver '\"\$gw\"'\" /etc/resolv.conf >/dev/null && printf \"gw-ok \" && nslookup stub53.kiri.test | awk \"/Address: 10\\.53\\.53\\.53/ {print \\\$2; exit}\"'); kill \$(cat /tmp/stub53.pid) 2>/dev/null; mv /tmp/resolv.330 /etc/resolv.conf; echo \"\$out\"" -t build-host-network-dns "bridge=10.53.53.53 host=10.53.53.53" "docker tag alpine:3.21 kiri-local-dns:1 && cp /etc/resolv.conf /tmp/resolv.209 && ($STUB53 >/dev/null 2>&1 & echo \$! > /tmp/stub209.pid) && sleep 0.2 && printf 'nameserver 127.0.0.53\\n' > /etc/resolv.conf && mkdir -p /b209 && printf 'FROM kiri-local-dns:1\\nRUN nslookup stub53.kiri.test | grep -F 10.53.53.53\\n' > /b209/Dockerfile && b1=\$(DOCKER_BUILDKIT=0 docker build --no-cache /b209 2>&1 | grep -o '10\\.53\\.53\\.53' | head -1) && b2=\$(DOCKER_BUILDKIT=0 docker build --no-cache --network=host /b209 2>&1 | grep -o '10\\.53\\.53\\.53' | head -1); kill \$(cat /tmp/stub209.pid) 2>/dev/null; mv /tmp/resolv.209 /etc/resolv.conf; rm -rf /b209; docker rmi kiri-local-only:1 kiri-local-dns:1 >/dev/null 2>&1; echo \"bridge=\$b1 host=\$b2\"" +t dns-default-bridge-stub "gw-ok 10.53.53.53" "cp /etc/resolv.conf /tmp/resolv.330 && ($STUB53 >/dev/null 2>&1 & echo \$! > /tmp/stub53.pid) && sleep 0.2 && printf 'nameserver 127.0.0.53\\n' > /etc/resolv.conf && gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}') && out=\$(docker run --rm alpine sh -c 'grep -Fx \"nameserver '\"\$gw\"'\" /etc/resolv.conf >/dev/null && printf \"gw-ok \" && nslookup stub53.kiri.test | awk \"/Address: 10\\.53\\.53\\.53/ {print \\\$2; exit}\"'); kill \$(cat /tmp/stub53.pid) 2>/dev/null; cat /tmp/resolv.330 > /etc/resolv.conf; rm -f /tmp/resolv.330; echo \"\$out\"" +t build-host-network-dns "bridge=10.53.53.53 host=10.53.53.53" "docker tag alpine:3.21 kiri-local-dns:1 && cp /etc/resolv.conf /tmp/resolv.209 && ($STUB53 >/dev/null 2>&1 & echo \$! > /tmp/stub209.pid) && sleep 0.2 && printf 'nameserver 127.0.0.53\\n' > /etc/resolv.conf && mkdir -p /b209 && printf 'FROM kiri-local-dns:1\\nRUN nslookup stub53.kiri.test | grep -F 10.53.53.53\\n' > /b209/Dockerfile && b1=\$(DOCKER_BUILDKIT=0 docker build --no-cache /b209 2>&1 | grep -o '10\\.53\\.53\\.53' | head -1) && b2=\$(DOCKER_BUILDKIT=0 docker build --no-cache --network=host /b209 2>&1 | grep -o '10\\.53\\.53\\.53' | head -1); kill \$(cat /tmp/stub209.pid) 2>/dev/null; cat /tmp/resolv.209 > /etc/resolv.conf; rm -f /tmp/resolv.209; rm -rf /b209; docker rmi kiri-local-only:1 kiri-local-dns:1 >/dev/null 2>&1; echo \"bridge=\$b1 host=\$b2\"" # Docker Hub is reached over verified HTTPS whatever the list covers: a # name server (here /etc/hosts) that puts its name inside a listed network, # in front of a plain-HTTP registry on port 80, must not turn the pull into @@ -805,7 +805,7 @@ t access-directory-accounts "local=200 merged=200 init=200 out=000 unk=000 boot= t systempaths-default "covered:[/proc/interrupts /proc/sys /sys/firmware]" "docker run --rm alpine sh -c 'echo covered:[\$(grep -oE \" /(proc/(interrupts|sys)|sys/firmware) \" /proc/self/mountinfo | sort -u | xargs)]'" t systempaths-unconfined "covered:[]" "docker run --rm --security-opt systempaths=unconfined alpine sh -c 'echo covered:[\$(grep -oE \" /(proc/(interrupts|sys)|sys/firmware) \" /proc/self/mountinfo | sort -u | xargs)]'" t systempaths-bwrap "bwrap-ok" "aa=\$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null || true); [ \"\$aa\" = 1 ] && echo 0 > /proc/sys/kernel/apparmor_restrict_unprivileged_userns; docker run --rm --security-opt no-new-privileges:true --security-opt seccomp=unconfined --security-opt systempaths=unconfined alpine sh -c 'timeout 40 apk add -q bubblewrap >/dev/null 2>&1; timeout 10 su nobody -s /bin/sh -c \"bwrap --die-with-parent --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev true && echo bwrap-ok\" 2>&1'; [ \"\$aa\" = 1 ] && echo 1 > /proc/sys/kernel/apparmor_restrict_unprivileged_userns || true" -t systempaths-symlink-escape "ctr:os=[] apk=[] root=ok host:canary=intact-rw" "echo intact > /tmp/kiri-sp-canary && docker rm -f kiri-sp-seed >/dev/null 2>&1; docker run --name kiri-sp-seed alpine sh -c 'mkdir -p /custom && ln -s /tmp/kiri-sp-canary /custom/host && ln -s ../.. /custom/up' && docker commit kiri-sp-seed kiri-sp-img:1 >/dev/null && docker rm kiri-sp-seed >/dev/null && id=\$(curl -s --unix-socket /root/.kiri/run/docker.sock -H 'Content-Type: application/json' -d '{\"Image\":\"kiri-sp-img:1\",\"Cmd\":[\"sh\",\"-c\",\"printf \\\"ctr:os=[%s] apk=[%s] root=%s \\\" \\\"\$(cat /etc/os-release)\\\" \\\"\$(ls /etc/apk)\\\" \\\"\$(test -x /bin/sh && echo ok || echo gone)\\\"\"],\"HostConfig\":{\"MaskedPaths\":[\"/custom/host\",\"/custom/up\",\"/etc/os-release\",\"/etc/apk\",\"/etc/alpine-release/nope\"],\"ReadonlyPaths\":[\"/custom/host\",\"/custom/up\",\"/tmp\"]}}' http://d/containers/create | sed 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\1/'); docker start -a \$id; docker rm -f \$id >/dev/null; docker rmi kiri-sp-img:1 >/dev/null; echo -n -rw >> /tmp/kiri-sp-canary 2>/dev/null; echo \"host:canary=\$(cat /tmp/kiri-sp-canary)\"; rm -f /tmp/kiri-sp-canary" +t systempaths-symlink-escape "ctr:os=[] apk=[] root=ok host:canary=intact-rw" "printf intact > /tmp/kiri-sp-canary && docker rm -f kiri-sp-seed >/dev/null 2>&1; docker run --name kiri-sp-seed alpine sh -c 'mkdir -p /custom && ln -s /tmp/kiri-sp-canary /custom/host && ln -s ../.. /custom/up' && docker commit kiri-sp-seed kiri-sp-img:1 >/dev/null && docker rm kiri-sp-seed >/dev/null && id=\$(curl -s --unix-socket /root/.kiri/run/docker.sock -H 'Content-Type: application/json' -d '{\"Image\":\"kiri-sp-img:1\",\"Cmd\":[\"sh\",\"-c\",\"printf \\\"ctr:os=[%s] apk=[%s] root=%s \\\" \\\"\$(cat /etc/os-release)\\\" \\\"\$(ls /etc/apk)\\\" \\\"\$(test -x /bin/sh && echo ok || echo gone)\\\"\"],\"HostConfig\":{\"MaskedPaths\":[\"/custom/host\",\"/custom/up\",\"/etc/os-release\",\"/etc/apk\",\"/etc/alpine-release/nope\"],\"ReadonlyPaths\":[\"/custom/host\",\"/custom/up\",\"/tmp\"]}}' http://d/containers/create | sed 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\1/'); docker start -a \$id; docker rm -f \$id >/dev/null; docker rmi kiri-sp-img:1 >/dev/null; printf %s -rw >> /tmp/kiri-sp-canary 2>/dev/null; echo \"host:canary=\$(cat /tmp/kiri-sp-canary)\"; rm -f /tmp/kiri-sp-canary" # `--cgroupns`: `private` (default) vs `host`, read-only cgroupfs for # unprivileged containers (including parent binds like `-v /sys:/hostsys`, # non-canonical `./`, and symlinks), and privileged systemd sub-cgroup diff --git a/tests/regressions.tsv b/tests/regressions.tsv index d67e3c667..e17aa990d 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -338,7 +338,7 @@ bind-nonroot-parallel #796 concurrent non-root file and directory creation on a bind-nonroot-ro #796 non-root writes to a read-only 0444 bind-mount file must still fail with EACCES, including inside an unprivileged unshare -Ur user namespace crates/kiri/src/daemon/rofs.rs #768 when Kiri's WSL 2 ext4.vhdx or Linux storage filesystem was remounted read-only (emergency_ro), daemon startup, /info and diagnostics lacked actionable fsck / storage recovery steps crates/kiri-init/src/linux/sys.rs #768 on a read-only or emergency_ro storage filesystem, overlayfs silently mounted writable container rootfs read-only instead of refusing with actionable recovery steps -crates/kiri-win/src/wslsync.rs #768 kiri-start and kiri-win reported a generic WSL install failure instead of ext4.vhdx emergency_ro e2fsck recovery steps when Kiri's WSL 2 disk was remounted read-only +crates/kiri-win/src/wslsync.rs #768 kiri-start and kiri-win reported a generic WSL install failure instead of ext4.vhdx emergency_ro e2fsck recovery steps when Kiri's WSL 2 disk was remounted read-only, and KIRI_CONTEXT_HASH did not match sha256("kiri") (#269) tls-company-root-pull #303 a registry signed by a root the system trusts failed UnknownIssuer: only the bundled roots were trusted tls-company-root-login #303 docker login to a registry signed by a root the system trusts failed UnknownIssuer tls-unknown-root-refused #303 a root the system does not trust must still be refused @@ -376,3 +376,6 @@ crates/kiri/src/daemon/engine.rs #989 kiri-k8s caused mac_bind_sources to watch 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 +crates/kiri/src/domains_cli.rs #744 `kiri domains set` and `kiri domains reset` failed with a daemon-not-running error instead of updating `domains.json` offline when the daemon was stopped +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