From 06fc8cb699ca4762d6f8ffbd688ec0a5a887ed53 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 12:08:12 +0100 Subject: [PATCH 001/157] Builder: restart an idle running builder after a registry settings change (#329) --- crates/kiri/src/daemon/builder.rs | 45 ++++++++++++++++++++++--------- docs/fix-registry.md | 8 +++++- tests/e2e.sh | 13 +++++++++ tests/linux-host.sh | 1 + 4 files changed, 54 insertions(+), 13 deletions(-) diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index 00e984788..cc3dedbc7 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -533,9 +533,18 @@ pub fn create_for_buildx(engine: &Engine, name: Option<&str>) -> Option (bool, Busy) { + let restart = restart_now(up, BUILDS.load(Ordering::Relaxed) > 0 || execs > 0, stale); + (restart, Busy::new()) +} + /// The builder, made if need be, started and answering. `say` hears what /// takes a while (a pull, a start). -fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result { +fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result<(String, Busy), Error> { if find(engine).is_none() { // Before the lock: a pull must not hold the builder up for others. ensure_image(engine, say)?; @@ -545,12 +554,10 @@ fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result found, None => (create(engine, say)?, Status::Created), }; - // daemon.json edited by hand since the builder started (Settings and - // `kiri registry` refresh it at once): restarted with the new file - // while no build uses it, as buildkitd reads it only when it starts. - let stale = status == Status::Running - && !builder_busy(engine, &id) - && is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine))); + // daemon.json edited by hand, or a setting saved while the builder ran: + // restarted with the new file while no other build uses it, as buildkitd + // reads it only when it starts. + let (stale, busy) = claim_for_build(status == Status::Running, engine.running_execs(&id), stale_now(engine)); if stale { if engine.is_paused(&id) { engine.pause(&id, false)?; @@ -566,7 +573,7 @@ fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result, w: &mut UnixStream, r: &mut Bu *h = format!("{}={host}", &h[..h.len() - mac.len()]); } } - let _busy = Busy::new(); // The context may be left partly unread: the connection closes after. http::begin_stream_with(w, 200, "application/json", http::CLOSE)?; let probe = w.try_clone()?; @@ -1051,7 +1057,7 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu fn run(req: &Request, engine: &Engine, o: &mut Options, r: &mut BufReader, out: &mut Out<'_>, probe: &UnixStream) -> Result, String> { let quiet = o.quiet; - let id = ensure_running(engine, &mut |m| { + let (id, _busy) = ensure_running(engine, &mut |m| { if !quiet { out.stream(&format!("{m}\n")); } @@ -1220,8 +1226,7 @@ pub fn prune(req: &Request, engine: &Engine) -> Result { if find(engine).is_none() { return Ok(json!({"CachesDeleted": [], "SpaceReclaimed": 0})); } - let _busy = Busy::new(); - let id = ensure_running(engine, &mut |_| {})?; + let (id, _busy) = ensure_running(engine, &mut |_| {})?; let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); let (code, text) = engine.exec_capture(&id, &argv)?; if code != 0 { @@ -1376,6 +1381,22 @@ mod tests { assert!(!restart_now(true, false, false)); let at = |s: Step| STOP_THEN_WRITE.iter().position(|x| *x == s).unwrap(); assert!(at(Step::Resume) < at(Step::Stop) && at(Step::Stop) < at(Step::Write), "{STOP_THEN_WRITE:?}"); + + let _g = ENSURE.lock().unwrap_or_else(|e| e.into_inner()); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_first, b1) = claim_for_build(true, 0, true); + assert!(restart_first, "an idle stale builder is restarted before this build marks it busy"); + assert_eq!(BUILDS.load(Ordering::Relaxed), 1); + let (restart_while_busy, b2) = claim_for_build(true, 0, true); + assert!(!restart_while_busy, "a builder another build is using must not be restarted"); + drop((b1, b2)); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_fresh, b3) = claim_for_build(true, 0, false); + assert!(!restart_fresh, "a fresh builder is not restarted"); + drop(b3); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_exec_busy, _b4) = claim_for_build(true, 1, true); + assert!(!restart_exec_busy, "a builder with an active buildx exec is not restarted"); } /// `before_exec` re-checks the builder's state under `ENSURE` (so a waiter diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 833404d8a..45414f835 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 +### Builder: restart an idle running builder after a registry settings change (unreleased) +- Fixes: #329 Support insecure-registries (plain-HTTP and self-signed private registries), and read Docker's daemon.json; #118 Registry mirrors for Docker Hub (Settings + CLI) +- Caused: none known +- Caused by: #119 +- Check: `insecure-selfsigned-build`, `insecure-selfsigned-unlisted-build-refused`, `mirror-build` + ### #608 Mac: the memory balloon leaves the guest its headroom, so containers don't stall every few seconds (unreleased) - Fixes: #509 Containers on a user network get TCP resets under sustained load (Supabase local stack: Kong → PostgREST); #646 kiri-balloon oscillates violently on idle VM: 100% CPU, 18+ TB page-in thrashing, bloated host RAM; #210 macOS: containers report hundreds of GB of block reads while the guest has no page cache - Caused: none known @@ -33,7 +39,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ### #119 Images: registry mirrors for Docker Hub, in Settings and the CLI (unreleased) - Fixes: #118 Registry mirrors for Docker Hub (Settings + CLI); #329 Support insecure-registries (plain-HTTP and self-signed private registries), and read Docker's daemon.json; #611 Could support for pulling images from private repositories be added as soon as possible? -- Caused: none known +- Caused: `build()` and `prune()` in `daemon/builder.rs` took `Busy::new()` before `ensure_running()` checked `!builder_busy()`, so a running builder was never restarted after a mirror or insecure-registry change and `mirror-build` and `insecure-selfsigned-build` failed (found running `tests/linux-host.sh` on Linux 6.8) - Caused by: - - Check: `insecure-http-unlisted-refused`, `insecure-tls-unlisted-refused`, `insecure-login-unlisted-refused`, `insecure-cli-add`, `insecure-cli-refuses-everything`, `insecure-http-pull`, `insecure-http-push`, `insecure-selfsigned-pull`, `insecure-http-login`, `insecure-http-auth-pull`, `insecure-other-port-still-refused`, `insecure-docker-info`, `insecure-build`, `insecure-selfsigned-build`, `insecure-removed-refused`, `insecure-hand-edit`, `insecure-hand-edit-keeps-keys`, `mirror-http-pull`, `mirror-docker-info`, `mirror-build`, `insecure-cli-remove`, `mirror-cli-add`, `hub-downgrade-refused`, `socket-mount-settings-refused`, `mirror-cli-plain-needs-listing`, `insecure-daemon-json` diff --git a/tests/e2e.sh b/tests/e2e.sh index 4f873e50c..117f909a4 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1514,6 +1514,19 @@ if [ -n "$HOSTIP" ]; then t mirror-cli-add "http://$HOSTIP:5056" "$KIRI" registry mirror add "http://$HOSTIP:5056" t mirror-http-pull "3." bash -c "$D pull -q kiri-mirror-only:1 >/dev/null && $D run --rm kiri-mirror-only:1 cat /etc/alpine-release" t mirror-docker-info "http://$HOSTIP:5056/" bash -c "$D info 2>/dev/null | sed -n '/Registry Mirrors/,/^ [A-Z]/p'" + if command -v openssl >/dev/null 2>&1 && openssl req -x509 -newkey rsa:2048 -nodes -days 3 -subj /CN=kiri-other.test -addext subjectAltName=DNS:kiri-other.test -keyout "$REG/other.key" -out "$REG/other.pem" 2>/dev/null; then + chmod 644 "$REG/other.key" + $D run -d --name reg3 -p 5444:5000 -v "$REG:/tls:ro" -e REGISTRY_HTTP_TLS_CERTIFICATE=/tls/other.pem -e REGISTRY_HTTP_TLS_KEY=/tls/other.key registry:2 >/dev/null + for _ in $(seq 50); do curl -sk -m 1 -o /dev/null https://localhost:5444/v2/ && break; sleep 0.2; done + $D tag alpine localhost:5444/team/alp:1 && $D push -q localhost:5444/team/alp:1 >/dev/null && $D rmi localhost:5444/team/alp:1 >/dev/null + t insecure-selfsigned-unlisted-build-refused "refused" bash -c "gw=\$($D inspect reg3 --format '{{.NetworkSettings.IPAddress}}'):5000; mkdir -p \"$REG/bins\" && printf 'FROM %s/team/alp:1\nRUN true\n' \"\$gw\" > \"$REG/bins/Dockerfile\" && (DOCKER_BUILDKIT=0 $D build --no-cache \"$REG/bins\" >/dev/null 2>&1 && echo built || echo refused)" + t insecure-selfsigned-build "dengis-fles" bash -c "gw=\$($D inspect reg3 --format '{{.NetworkSettings.IPAddress}}'):5000; \"$KIRI\" registry insecure add \$gw >/dev/null 2>&1; mkdir -p \"$REG/bins\" && printf 'FROM %s/team/alp:1\nRUN echo self-signed | rev\n' \"\$gw\" > \"$REG/bins/Dockerfile\" && DOCKER_BUILDKIT=0 $D build --no-cache \"$REG/bins\" >\"$REG/b.log\" 2>&1; grep -m1 -o dengis-fles \"$REG/b.log\" || grep -Ei -m3 'error|fail' \"$REG/b.log\"; \"$KIRI\" registry insecure remove \$gw >/dev/null 2>&1" + $D rm -f reg3 >/dev/null + else + skip_setup insecure-selfsigned-unlisted-build-refused "openssl is not installed" + skip_setup insecure-selfsigned-build "openssl is not installed" + fi + t mirror-build "rorrim-tliub" bash -c "gw=\$($D inspect reg2 --format '{{.NetworkSettings.IPAddress}}'):5000; \"$KIRI\" registry mirror remove http://$HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry insecure add \$gw >/dev/null 2>&1; \"$KIRI\" registry mirror add http://\$gw >/dev/null 2>&1; $D rmi kiri-mirror-only:1 >/dev/null 2>&1; mkdir -p \"$REG/bins\" && printf 'FROM kiri-mirror-only:1\nRUN echo built-mirror | rev\n' > \"$REG/bins/Dockerfile\" && DOCKER_BUILDKIT=0 $D build --no-cache \"$REG/bins\" >\"$REG/b.log\" 2>&1; grep -m1 -o rorrim-tliub \"$REG/b.log\" || grep -Ei -m3 'error|fail' \"$REG/b.log\"; \"$KIRI\" registry mirror remove http://\$gw >/dev/null 2>&1; \"$KIRI\" registry insecure remove \$gw >/dev/null 2>&1" "$KIRI" registry mirror remove "http://$HOSTIP:5056" >/dev/null 2>&1; "$KIRI" registry insecure remove "$HOSTIP:5056" >/dev/null 2>&1; $R logout "$HOSTIP:5055" >/dev/null 2>&1 $D rmi kiri-mirror-only:1 >/dev/null 2>&1; $D rm -f reg2 >/dev/null else diff --git a/tests/linux-host.sh b/tests/linux-host.sh index bae608566..cfabe5e18 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -351,6 +351,7 @@ t insecure-docker-info "kiri-trusted.test:5055" "docker info 2>/dev/null | sed - t insecure-build "erucesni-tliub" "gw=\$(docker inspect kiri-reg-http --format '{{.NetworkSettings.IPAddress}}'):5000; /opt/kiri/kiri registry insecure add \$gw >/dev/null 2>&1; mkdir -p /bins && printf \"FROM \$gw/team/alp:1\\nRUN echo built-insecure | rev\\n\" > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache /bins >/tmp/b.log 2>&1; grep -m1 -o erucesni-tliub /tmp/b.log || grep -i -m3 'error\|fail' /tmp/b.log" # The same from a registry on self-signed HTTPS, cold: unchecked HTTPS, # not plain HTTP to its TLS port. +t insecure-selfsigned-unlisted-build-refused "refused" "gw=\$(docker inspect kiri-reg-other --format '{{.NetworkSettings.IPAddress}}'):5000; mkdir -p /bins && printf \"FROM \$gw/team/alp:1\\nRUN true\\n\" > /bins/Dockerfile && (DOCKER_BUILDKIT=0 docker build --no-cache /bins >/dev/null 2>&1 && echo built || echo refused)" t insecure-selfsigned-build "dengis-fles" "gw=\$(docker inspect kiri-reg-other --format '{{.NetworkSettings.IPAddress}}'):5000; /opt/kiri/kiri registry insecure add \$gw >/dev/null 2>&1; printf \"FROM \$gw/team/alp:1\\nRUN echo self-signed | rev\\n\" > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache /bins >/tmp/b.log 2>&1; grep -m1 -o dengis-fles /tmp/b.log || grep -i -m3 'error\|fail' /tmp/b.log" t insecure-cli-remove "kiri-trusted.test:5056" "/opt/kiri/kiri registry insecure remove kiri-trusted.test:5055 kiri-other.test:5444 2>&1" t insecure-removed-refused "refused" "docker rmi kiri-other.test:5444/team/alp:1 >/dev/null 2>&1; docker pull kiri-other.test:5444/team/alp:1 >/dev/null 2>&1 $PULLED" From 9ed367590d648f69be8efb7d053b335f778bba4b Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 13:18:22 +0100 Subject: [PATCH 002/157] Engine: systempaths=unconfined, MaskedPaths and ReadonlyPaths are applied (#378) Co-authored-by: sundarshahi --- crates/kiri-init/src/linux/container.rs | 204 +++++++++++++++++++++++- crates/kiri-init/src/linux/hostopts.rs | 28 ++++ crates/kiri-proto/src/lib.rs | 3 +- crates/kiri/src/daemon/api.rs | 8 +- crates/kiri/src/daemon/hostopts.rs | 98 +++++++++++- docs/fix-registry.md | 6 + tests/e2e.sh | 19 +++ tests/linux-host.sh | 7 + tests/regressions.tsv | 12 ++ 9 files changed, 371 insertions(+), 14 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 8a80ebb98..a0d968838 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -322,6 +322,8 @@ struct HostApplied { rlimits: Vec<(u32, u64, u64)>, groups: Vec, nodes: Vec, + masked: Option>, + readonly: Option>, } /// Docker's default capability set as a mask. @@ -543,7 +545,8 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, target_pid: libc::pid_t, paths: &Paths, profile let mut prepared = prepare(spec.argv, spec.env, spec.cwd, spec.user, None, spec.flags, spec.caps)?; // The container's ulimits and groups apply to its execs too, as with runc. let host = super::hostopts::parse(spec.opts)?; - prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, nodes: Vec::new() }; + prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, ..Default::default() }; // An exec runs under its container's profile, not the default. prepared.profile = profile.to_vec(); let (parent_io, child_io) = stdio(&prepared)?; @@ -1805,7 +1808,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { shm_size: _, init: _, // Paths, numbers and names only. - host: HostApplied { rlimits: _, groups: _, nodes: _ }, + host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ }, root_ready, } = p; let mut fds = match io { @@ -1850,7 +1853,12 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ } let root = inroot::open_root(Path::new(".")).unwrap_or_else(|e| fail("enter rootfs", e)); let root = root.as_fd(); - mount_container_filesystems(p.privileged, p.shm_size).unwrap_or_else(|e| fail("mount", e)); + mount_container_filesystems(p.privileged, p.shm_size, &p.host).unwrap_or_else(|e| fail("mount", e)); + // Taken before user mounts can cover /dev, as the source for MaskedPaths. + let null = (!p.privileged) + .then(|| p.host.masked.as_ref().filter(|m| !m.is_empty())) + .flatten() + .map(|_| dev_null().unwrap_or_else(|e| fail("masked paths", e))); super::hostopts::make_nodes(root, &p.host.nodes).unwrap_or_else(|e| fail("devices", e)); for (src, target) in &p.etc_files { bind_file(root, src, target).unwrap_or_else(|e| fail(&target.to_string_lossy(), e)); @@ -1887,6 +1895,8 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ // before it switches user and before the root goes read-only, so both // `-u 1000 -w /missing` and `--read-only -w /missing` start (#370). make_workdir(root, &p.cwd); + api_paths(root, p.privileged, p.host.readonly.as_deref().unwrap_or_default(), p.host.masked.as_deref().unwrap_or_default(), null.as_ref()) + .unwrap_or_else(|e| fail("masked paths", e)); if let Some(flags) = root_remount_flags(p.readonly_rootfs, p.nodev_root) { // Only the root itself: volumes, tmpfs and /dev stay as they are. sys::mount(c"none", c"/", c"none", flags, None).unwrap_or_else(|e| fail(if p.readonly_rootfs { "read-only root" } else { "nodev root" }, e)); @@ -2126,7 +2136,7 @@ fn root_remount_flags(readonly: bool, nodev: bool) -> Option { /// /dev/pts, /dev/shm, /dev/mqueue and a read-only cgroup view. Relative /// paths: the current directory is the container root. A privileged /// container gets the VM's devices and writable /sys and cgroups instead. -fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()> { +fn mount_container_filesystems(privileged: bool, shm_size: u64, host: &HostApplied) -> io::Result<()> { let nosuid_nodev_noexec = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; let ro = if privileged { 0 } else { libc::MS_RDONLY }; for d in [c"proc", c"sys", c"dev"] { @@ -2185,9 +2195,13 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<() sys::mount(c"mqueue", c"dev/mqueue", c"mqueue", nosuid_nodev_noexec, None)?; sys::mkdir(c"sys/fs/cgroup", 0o755); sys::mount(c"cgroup2", c"sys/fs/cgroup", c"cgroup2", nosuid_nodev_noexec | ro, None)?; - if !privileged { + // An API list replaces Docker's default for that half (see `api_paths`). + if !privileged && host.readonly.is_none() { harden_proc()?; } + if !privileged && host.masked.is_none() { + mask_proc(); + } Ok(()) } @@ -2249,8 +2263,8 @@ fn copy_host_devices(from: &Path, to: &Path) -> io::Result<()> { Ok(()) } -/// Makes the dangerous parts of /proc read-only or hides them, as Docker's -/// default `readonlyPaths` and `maskedPaths` do. The container is real root +/// Makes the dangerous parts of /proc read-only, as Docker's default +/// `readonlyPaths` does. The container is real root /// (no user namespace), and these sysctls and files are not namespaced, so /// without this a container could set `kernel.core_pattern` or /// `kernel.modprobe` and run code on the host. Paths are relative to the @@ -2268,6 +2282,11 @@ fn harden_proc() -> io::Result<()> { let _ = sys::remount(p, ro as libc::c_ulong); } } + Ok(()) +} + +/// Hides what Docker's default `maskedPaths` does, relative to the container root. +fn mask_proc() { // Hide files that leak host memory or kernel addresses, by covering them // with /dev/null (already created above). for p in [c"proc/kcore", c"proc/keys", c"proc/latency_stats", c"proc/timer_list", c"proc/timer_stats", c"proc/sched_debug", c"proc/interrupts"] { @@ -2277,9 +2296,135 @@ fn harden_proc() -> io::Result<()> { for p in [c"proc/scsi", c"proc/acpi", c"proc/asound", c"sys/firmware", c"sys/devices/virtual/powercap"] { let _ = sys::mount(c"tmpfs", p, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k")); } +} + +/// Looks up an existing `path` inside `root` without creating anything, +/// resolving symlinks and `..` against `root` so neither can leave it. +/// Returns the descriptor and whether it is a directory, or `None` when a +/// component is missing, a parent is not a directory, or the path resolves +/// to `root` itself. +fn lookup_existing(root: BorrowedFd<'_>, path: &Path) -> io::Result> { + use std::collections::VecDeque; + use std::ffi::OsString; + use std::path::Component; + + let parts = |p: &std::ffi::OsStr| -> VecDeque { + Path::new(p) + .components() + .filter_map(|c| match c { + Component::Normal(n) => Some(n.to_owned()), + Component::ParentDir => Some(OsString::from("..")), + Component::RootDir | Component::CurDir | Component::Prefix(_) => None, + }) + .collect() + }; + let root_st = fstat_at(root.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + let is_root = |st: &libc::stat| st.st_dev == root_st.st_dev && st.st_ino == root_st.st_ino; + let mut todo = parts(path.as_os_str()); + let mut dirs: Vec = vec![root.try_clone_to_owned()?]; + let mut links = 0u32; + while let Some(name) = todo.pop_front() { + if name == ".." { + if dirs.len() > 1 { + dirs.pop(); + } + continue; + } + let is_last = todo.is_empty(); + let dir = dirs.last().expect("root stays").as_raw_fd(); + let c = CString::new(name.as_os_str().as_bytes()).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?; + let fd = match open_at(dir, &c, libc::O_PATH | libc::O_NOFOLLOW) { + Ok(fd) => fd, + Err(e) if matches!(e.raw_os_error(), Some(libc::ENOENT | libc::ENOTDIR)) => return Ok(None), + Err(e) => return Err(e), + }; + let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + match st.st_mode & libc::S_IFMT { + libc::S_IFLNK => { + links += 1; + if links > 40 { + return Err(io::Error::from_raw_os_error(libc::ELOOP)); + } + let target = read_link_at(fd.as_raw_fd(), c"")?; + let bytes = target.as_bytes(); + if bytes.first() == Some(&b'/') { + dirs.truncate(1); + } + for comp in parts(std::ffi::OsStr::from_bytes(bytes)).into_iter().rev() { + todo.push_front(comp); + } + } + libc::S_IFDIR if !is_last => dirs.push(fd), + libc::S_IFDIR => return Ok((!is_root(&st)).then_some((fd, true))), + _ if is_last => return Ok(Some((fd, false))), + _ => return Ok(None), + } + } + let fd = dirs.pop().expect("root stays"); + let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + Ok((!is_root(&st)).then_some((fd, true))) +} + +/// The API's own `ReadonlyPaths` and `MaskedPaths`, applied after pivot_root as runc does. +fn api_paths(root: BorrowedFd<'_>, privileged: bool, readonly: &[CString], masked: &[CString], null: Option<&OwnedFd>) -> io::Result<()> { + if privileged { + return Ok(()); + } + let proc_fd = |fd: &OwnedFd| CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("no NUL"); + for p in readonly { + let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes())); + let Some((fd, _)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + sys::mount(&target, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?; + // The first descriptor is under the new bind mount; look again to + // reach the mount itself, and keep its nosuid, nodev and noexec flags. + let Some((fd, _)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + // SAFETY: statvfs is plain data; all-zero is a valid value. + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: valid NUL-terminated path and a writable struct. + if unsafe { libc::statvfs(target.as_ptr(), &mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + let keep = st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC); + sys::remount(&target, (libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY) as libc::c_ulong | keep)?; + } + for p in masked { + let null = null.ok_or_else(|| io::Error::other("no /dev/null to mask with"))?; + let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes())); + let Some((fd, is_dir)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + if is_dir { + sys::mount(c"tmpfs", &target, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k"))?; + } else { + let src = proc_fd(null); + sys::mount(&src, &target, c"none", libc::MS_BIND, None)?; + } + } Ok(()) } +/// The container's own /dev/null as an O_PATH descriptor, checked to be device 1:3. +fn dev_null() -> io::Result { + // SAFETY: valid NUL-terminated path; the descriptor is owned right away. + let fd = unsafe { libc::open(c"dev/null".as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor nothing else owns. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + // SAFETY: stat is plain data; all-zero is a valid value. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + // SAFETY: a descriptor we own and a writable struct. + if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + if st.st_mode & libc::S_IFMT != libc::S_IFCHR || st.st_rdev != libc::makedev(1, 3) { + return Err(io::Error::other("/dev/null is not the null device")); + } + Ok(fd) +} + /// `""`, `root`, `1000`, `1000:1000`, `redis`, `redis:redis`: looked up in /// the container's /etc/passwd and /etc/group when not numeric. /// The home directory /etc/passwd gives `uid`. @@ -3341,4 +3486,47 @@ mod tests { let both = super::root_remount_flags(true, true).expect("remounted"); assert_eq!(both & (libc::MS_RDONLY | libc::MS_NODEV), libc::MS_RDONLY | libc::MS_NODEV); } + + /// `MaskedPaths` and `ReadonlyPaths` targets are looked up inside the + /// container's root without creating missing folders: links inside the + /// image work, links pointing outside or to `/` (`../..`) never leave + /// the root or cover `/` itself, and a path under a file is skipped. + #[test] + fn lookup_existing_stays_in_root_and_makes_nothing() { + use std::os::fd::{AsFd, AsRawFd}; + use std::os::unix::fs::symlink; + use std::path::Path; + let (base, root, _vol, outside) = fill_dirs("lookup-existing"); + std::fs::create_dir_all(root.join("etc")).unwrap(); + std::fs::create_dir_all(root.join("usr/lib")).unwrap(); + std::fs::create_dir_all(root.join("var")).unwrap(); + std::fs::create_dir_all(root.join("custom")).unwrap(); + std::fs::write(root.join("usr/lib/os-release"), b"alpine").unwrap(); + std::fs::write(outside.join("secret"), b"host").unwrap(); + symlink("../usr/lib/os-release", root.join("etc/os-release")).unwrap(); + symlink(outside.join("secret"), root.join("custom/out")).unwrap(); + symlink("../../../../../../outside/secret", root.join("custom/rel")).unwrap(); + symlink("../..", root.join("custom/up")).unwrap(); + symlink("/custom/loop_b", root.join("custom/loop_a")).unwrap(); + symlink("/custom/loop_a", root.join("custom/loop_b")).unwrap(); + + let r = super::inroot::open_root(&root).unwrap(); + let (fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/etc/os-release")).unwrap().expect("in-image link"); + assert!(!is_dir); + assert_eq!(std::fs::read(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(), b"alpine"); + let (_fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/var")).unwrap().expect("directory"); + assert!(is_dir); + assert!(super::lookup_existing(r.as_fd(), Path::new("/nope/sub")).unwrap().is_none()); + assert!(!root.join("nope").exists(), "missing parent is not created"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/usr/lib/os-release/sub")).unwrap().is_none(), "parent is a file"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/out")).unwrap().is_none(), "absolute link stays in root"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/rel")).unwrap().is_none(), ".. stops at root"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/up")).unwrap().is_none(), "root itself is not returned"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/")).unwrap().is_none(), "root itself is not returned"); + assert_eq!(super::lookup_existing(r.as_fd(), Path::new("/custom/loop_a")).unwrap_err().raw_os_error(), Some(libc::ELOOP)); + let paths = [std::ffi::CString::new("/etc/os-release").unwrap()]; + assert!(super::api_paths(r.as_fd(), true, &paths, &paths, None).is_ok(), "privileged skips api_paths"); + assert!(super::api_paths(r.as_fd(), false, &[], &paths, None).is_err(), "unprivileged applies masked paths"); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/kiri-init/src/linux/hostopts.rs b/crates/kiri-init/src/linux/hostopts.rs index 6f3131e27..cda5c114a 100644 --- a/crates/kiri-init/src/linux/hostopts.rs +++ b/crates/kiri-init/src/linux/hostopts.rs @@ -62,6 +62,10 @@ pub struct HostOpts { pub rules: Vec, /// `--group-add`: names (looked up in the container's /etc/group) or ids. pub groups: Vec, + /// `MaskedPaths` and `ReadonlyPaths` when the API set them; `None` keeps + /// the default (Docker's lists, or nothing for a privileged container). + pub masked: Option>, + pub readonly: Option>, } fn bad(line: &str) -> io::Error { @@ -110,6 +114,19 @@ pub fn parse(list: StrList<'_>) -> io::Result { } ["devrule", kind, major, minor, perms] => o.rules.push(devices::parse_rule(kind, major, minor, perms).ok_or_else(|| bad(line))?), ["group", g] if !g.is_empty() => o.groups.push((*g).to_owned()), + [kind @ ("masked" | "readonly"), paths @ ..] => { + let paths = paths + .iter() + .map(|p| { + if p.starts_with('/') && !p.split('/').any(|c| c == "..") { + CString::new(*p).map_err(|_| bad(line)) + } else { + Err(bad(line)) + } + }) + .collect::>>()?; + *(if *kind == "masked" { &mut o.masked } else { &mut o.readonly }) = Some(paths); + } _ => return Err(bad(line)), } } @@ -398,6 +415,17 @@ mod tests { assert_eq!(o.devices[0].container, "/dev/fuse"); assert_eq!(o.rules.len(), 1); assert_eq!(o.groups, ["video"]); + assert!(o.masked.is_none() && o.readonly.is_none()); + let buf = list(&["masked", "readonly\t/proc/sys\t/data"]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let o = parse(l).unwrap(); + assert_eq!(o.masked, Some(vec![])); + assert_eq!(o.readonly, Some(vec![c"/proc/sys".to_owned(), c"/data".to_owned()])); + 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!() }; + assert!(parse(l).is_err(), "{bad_path}"); + } for bad in ["sysctl\tnet\tkernel/core_pattern\t|x", "sysctl\tipc\tkernel/../x\t1", "sysctl\tuts\tkernel/hostname\tx", "rlimit\t99\t1\t1", "device\tdev\t/x\trwm", "nope"] { let buf = list(&[bad]); let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 7d7366533..ca0a89937 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -516,7 +516,8 @@ pub struct RunSpec<'a> { pub caps: u64, /// HostConfig settings applied at start, one per line, tab-separated: /// `rlimit res soft hard`, `sysctl ns path value`, `device host - /// container perms`, `devrule type major minor perms`, `group name`. + /// container perms`, `devrule type major minor perms`, `group name`, + /// `masked path…`, `readonly path…`. /// Empty from an older daemon. pub opts: StrList<'a>, /// The container's own seccomp profile, compiled by the daemon to a diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 986363eae..a1c27d1ae 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2693,7 +2693,7 @@ fn list(req: &Request, engine: &Engine) -> Result { fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { let when = |t: Option| t.map_or_else(|| time::ZERO.to_owned(), time::rfc3339); let argv = c.argv(); - json!({ + let mut v = json!({ "Id": c.id, "Created": time::rfc3339(c.created), "Path": argv.first().cloned().unwrap_or_default(), @@ -2773,7 +2773,11 @@ fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { }, "NetworkSettings": network_settings(c, nets), "Mounts": c.spec.mount_info, - }) + }); + for key in ["MaskedPaths", "ReadonlyPaths"] { + v["HostConfig"][key] = super::hostopts::system_paths(&c.spec.host_opts, key, c.spec.privileged); + } + v } fn network_settings(c: &Container, nets: &[super::network::Network]) -> Value { diff --git a/crates/kiri/src/daemon/hostopts.rs b/crates/kiri/src/daemon/hostopts.rs index 51babef9c..40f1df9d7 100644 --- a/crates/kiri/src/daemon/hostopts.rs +++ b/crates/kiri/src/daemon/hostopts.rs @@ -1,13 +1,30 @@ //! HostConfig settings the guest applies when a container starts: -//! `--ulimit`, `--sysctl`, `--device`, `--device-cgroup-rule` and -//! `--group-add`. They are kept as the API gave them (for inspect), checked +//! `--ulimit`, `--sysctl`, `--device`, `--device-cgroup-rule`, +//! `--group-add`, `MaskedPaths` and `ReadonlyPaths`. They are kept as the API gave them (for inspect), checked //! at create with Docker's errors, and handed to the guest at every start as //! the `opts` lines of `Run` and `Exec` (see [`kiri_proto::RunSpec::opts`]). use serde_json::{Value, json}; /// The HostConfig keys kept with a container. -const KEYS: [&str; 5] = ["Ulimits", "Sysctls", "Devices", "DeviceCgroupRules", "GroupAdd"]; +const KEYS: [&str; 7] = ["Ulimits", "Sysctls", "Devices", "DeviceCgroupRules", "GroupAdd", "MaskedPaths", "ReadonlyPaths"]; + +/// Docker's default `MaskedPaths` and `ReadonlyPaths`, as inspect shows them. +const MASKED: [&str; 12] = [ + "/proc/acpi", + "/proc/asound", + "/proc/interrupts", + "/proc/kcore", + "/proc/keys", + "/proc/latency_stats", + "/proc/sched_debug", + "/proc/scsi", + "/proc/timer_list", + "/proc/timer_stats", + "/sys/devices/virtual/powercap", + "/sys/firmware", +]; +const READONLY: [&str; 5] = ["/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger"]; /// `nofile` when the run sets none: what containers get on Docker Desktop /// and on Docker Engine under containerd's `LimitNOFILE=infinity`. Without @@ -46,6 +63,21 @@ pub fn from_host(host: &Value) -> Value { m.insert(k.to_owned(), host[k].clone()); } } + let mut unconfined = host["Privileged"].as_bool().unwrap_or(false); + for opt in strings(&host["SecurityOpt"]) { + if let Some(v) = opt.strip_prefix("systempaths=").or_else(|| opt.strip_prefix("systempaths:")) { + if v == "unconfined" { + unconfined = true; + } else { + m.entry("SecurityOpt".to_owned()).or_insert_with(|| Value::String(opt)); + } + } + } + if unconfined { + for k in ["MaskedPaths", "ReadonlyPaths"] { + m.insert(k.to_owned(), json!([])); + } + } Value::Object(m) } @@ -58,6 +90,18 @@ pub fn inspect(opts: &Value, key: &str) -> Value { } } +/// `MaskedPaths` or `ReadonlyPaths` for inspect: empty for a privileged +/// container, else as given or Docker's defaults. +pub fn system_paths(opts: &Value, key: &str, privileged: bool) -> Value { + if privileged { + return json!([]); + } + match &opts[key] { + Value::Null => json!(if key == "MaskedPaths" { &MASKED[..] } else { &READONLY[..] }), + v => v.clone(), + } +} + /// `--gpus` and Compose `deploy.resources.reservations.devices` arrive as /// DeviceRequests. Kiri has no GPU to give, and saying so beats a container /// that silently runs on the CPU. @@ -131,6 +175,26 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> } out.push(format!("group\t{g}")); } + if let Some(opt) = opts["SecurityOpt"].as_str() { + return Err(format!("invalid --security-opt: {opt:?}")); + } + // `--security-opt systempaths=unconfined` and `--privileged` arrive as both set to []. + for (key, kind) in [("MaskedPaths", "masked"), ("ReadonlyPaths", "readonly")] { + let paths = match &opts[key] { + Value::Null => continue, + Value::Array(a) => a + .iter() + .map(|p| { + p.as_str().filter(|p| { + p.starts_with('/') && !p.contains(['\t', '\n', '\r', '\0']) && !p.split('/').any(|c| c == "..") + }) + }) + .collect::>>(), + _ => None, + }; + let paths = paths.ok_or_else(|| format!("invalid {key}: each entry must be an absolute path"))?; + out.push(std::iter::once(kind).chain(paths).collect::>().join("\t")); + } Ok(out) } @@ -307,4 +371,32 @@ mod tests { assert_eq!(inspect(&kept, "GroupAdd"), Value::Null); assert_eq!(inspect(&Value::Null, "Ulimits"), json!([])); } + + #[test] + fn masked_and_readonly_paths() { + // Not set: no line, so the guest keeps its defaults. + assert_eq!(guest_lines(&json!({}), false).unwrap().len(), 1); + let kept = from_host(&json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked", "readonly"]); + for opt in ["systempaths=unconfined", "systempaths:unconfined"] { + let kept = from_host(&json!({"SecurityOpt": [opt], "MaskedPaths": ["/proc/kcore"], "ReadonlyPaths": ["/proc/sys"]})); + assert_eq!(kept, json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked", "readonly"]); + } + let priv_kept = from_host(&json!({"Privileged": true, "MaskedPaths": ["/proc/kcore"], "ReadonlyPaths": ["/proc/sys"]})); + assert_eq!(priv_kept, json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&priv_kept, false).unwrap()[1..], ["masked", "readonly"]); + let kept = from_host(&json!({"MaskedPaths": ["/proc/kcore", "/etc/secret"]})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked\t/proc/kcore\t/etc/secret"]); + for bad in [json!(["proc/kcore"]), json!(["/../etc"]), json!(["/proc/../etc"]), json!(["/a\tb"]), json!(["/a\rb"]), json!([1]), json!("/proc/kcore")] { + assert!(guest_lines(&json!({"MaskedPaths": bad}), false).is_err(), "{bad}"); + } + assert_eq!( + guest_lines(&from_host(&json!({"SecurityOpt": ["systempaths=bogus"]})), false).unwrap_err(), + "invalid --security-opt: \"systempaths=bogus\"" + ); + assert_eq!(system_paths(&json!({}), "ReadonlyPaths", false), json!(READONLY)); + assert_eq!(system_paths(&json!({}), "MaskedPaths", true), json!([])); + assert_eq!(system_paths(&kept, "MaskedPaths", true), json!([])); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 45414f835..99ae7dc86 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 +### #490 Engine: systempaths=unconfined, MaskedPaths and ReadonlyPaths are applied (unreleased) +- Fixes: #378 Engine: --security-opt systempaths=unconfined is ignored, breaking bubblewrap (bwrap) inside non-privileged containers +- Caused: none known +- Caused by: - +- Check: `systempaths-default`, `systempaths-unconfined`, `systempaths-unconfined-colon`, `systempaths-privileged`, `systempaths-inspect`, `systempaths-inspect-default`, `systempaths-inspect-privileged`, `systempaths-api-lists`, `systempaths-api-bad-rel`, `systempaths-api-bad-dotdot`, `systempaths-bwrap`, `systempaths-symlink-escape` + ### Builder: restart an idle running builder after a registry settings change (unreleased) - Fixes: #329 Support insecure-registries (plain-HTTP and self-signed private registries), and read Docker's daemon.json; #118 Registry mirrors for Docker Hub (Settings + CLI) - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 117f909a4..3a9c988ae 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1920,6 +1920,25 @@ t read-only-volume "ok" bash -c "$D run --rm --read-only -v rovol:/data alpine s t shm-size "256.0M" $D run --rm --shm-size 256m alpine df -h /dev/shm t shm-default "64.0M" $D run --rm alpine df -h /dev/shm t no-new-privs "NoNewPrivs: 1" $D run --rm --security-opt no-new-privileges alpine grep NoNewPrivs /proc/self/status +# Docker's masked and read-only paths: on by default, off with systempaths=unconfined or --privileged. +P='echo covered:[$(grep -oE " /(proc/(interrupts|sys)|sys/firmware) " /proc/self/mountinfo | sort -u | xargs)]' +t systempaths-default "covered:[/proc/interrupts /proc/sys /sys/firmware]" $D run --rm alpine sh -c "$P" +t systempaths-unconfined "covered:[]" $D run --rm --security-opt systempaths=unconfined alpine sh -c "$P" +t systempaths-unconfined-colon "covered:[]" $D run --rm --security-opt systempaths:unconfined alpine sh -c "$P" +t systempaths-privileged "covered:[]" $D run --rm --privileged alpine sh -c "$P" +t systempaths-inspect "[] []" bash -c "$D create --name spi --security-opt systempaths=unconfined alpine >/dev/null; $D inspect -f '{{json .HostConfig.MaskedPaths}} {{json .HostConfig.ReadonlyPaths}}' spi; $D rm spi >/dev/null" +t systempaths-inspect-default '"/proc/kcore"' bash -c "$D create --name spid alpine >/dev/null; $D inspect -f '{{json .HostConfig.MaskedPaths}} {{json .HostConfig.ReadonlyPaths}}' spid; $D rm spid >/dev/null" +t systempaths-inspect-privileged "[] []" bash -c "$D create --name spip --privileged alpine >/dev/null; $D inspect -f '{{json .HostConfig.MaskedPaths}} {{json .HostConfig.ReadonlyPaths}}' spip; $D rm spip >/dev/null" +SPD=$(mktemp -d) +cat > "$SPD/lists.json" <<'EOF' +{"Image":"alpine","Cmd":["sh","-c","echo os:[$(cat /etc/os-release)] apk:[$(ls /etc/apk)]; touch /tmp/x 2>/dev/null && echo tmp-rw || echo tmp-ro; echo covered:[$(grep -oE ' /(proc/(interrupts|sys)|sys/firmware) ' /proc/self/mountinfo | sort -u | xargs)]"],"HostConfig":{"MaskedPaths":["/etc/os-release","/etc/apk","/nope","/etc/alpine-release/nope"],"ReadonlyPaths":["/tmp","/proc/sys","/nope"]}} +EOF +t systempaths-api-lists "os:[] apk:[] tmp-ro covered:[/proc/sys]" bash -c "id=\$(curl -s --unix-socket $SQ -H 'Content-Type: application/json' -d @$SPD/lists.json http://d/containers/create | sed 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\1/'); $D start -a \$id | tr '\n' ' '; $D rm -f \$id >/dev/null" +t systempaths-api-bad-rel "400" curl -s -o /dev/null -w '%{http_code}' --unix-socket "$SOCK" -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["true"],"HostConfig":{"MaskedPaths":["proc/kcore"]}}' http://d/containers/create +t systempaths-api-bad-dotdot "400" curl -s -o /dev/null -w '%{http_code}' --unix-socket "$SOCK" -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["true"],"HostConfig":{"ReadonlyPaths":["/../etc"]}}' http://d/containers/create +rm -rf "$SPD" +# bubblewrap mounts a fresh /proc, which Linux refuses while parts of /proc are covered (#378). +t systempaths-bwrap "bwrap-ok" $D 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' section "UDP ports" $D run -d --name dns -p 15354:53/udp -p 15354:53/tcp alpine sh -c 'apk add -q dnsmasq >/dev/null 2>&1; dnsmasq -k --address=/kiri.test/10.9.8.7' >/dev/null diff --git a/tests/linux-host.sh b/tests/linux-host.sh index cfabe5e18..aa058a4a9 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -666,6 +666,13 @@ PY echo "$out" SH t access-directory-accounts "local=200 merged=200 init=200 out=000 unk=000 boot=200 outage=open hang-close=closed hang-new=000-fast rev-open=closed rev=000 ha=0 ha-name=canon canon=200 nss-local=200 nss-dir=200 nss-out=000" "apk add -q util-linux util-linux-misc iproute2 shadow >/dev/null 2>&1; sh /access-test.sh" +# --security-opt systempaths=unconfined (#378), MaskedPaths and ReadonlyPaths, +# and symlinks in an image at MaskedPaths/ReadonlyPaths (to a host path or +# ../..) never touch the host or cover the container's own /. +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" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 0444e7def..9e9a857e8 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -197,3 +197,15 @@ rename-dns-reused-name #467 a container renamed to a name an earlier container h rename-dns-reused-name-extra-net #467 the same on a network the container was connected to dns-user-net-three-refused-servfail-at-once #455 with three refusing --dns servers on a user network the lookup was not answered until the client gave up dns-user-net-three-silent-servfail-in-time #455 with three silent --dns servers on a user network the lookup was not answered at all, instead of within their waits +systempaths-default #378 a non-privileged container must keep Docker's default masked and read-only paths under /proc and /sys +systempaths-unconfined #378 --security-opt systempaths=unconfined was ignored, leaving /proc and /sys paths covered +systempaths-unconfined-colon #378 --security-opt systempaths:unconfined was ignored, leaving /proc and /sys paths covered +systempaths-privileged #378 a privileged container must not cover /proc or /sys with default masked or read-only mounts +systempaths-inspect #378 inspect did not show empty MaskedPaths and ReadonlyPaths for --security-opt systempaths=unconfined +systempaths-inspect-default #378 inspect did not show Docker's default MaskedPaths and ReadonlyPaths +systempaths-inspect-privileged #378 inspect did not show empty MaskedPaths and ReadonlyPaths for a privileged container +systempaths-api-lists #378 HostConfig.MaskedPaths and ReadonlyPaths from the API were dropped instead of applied +systempaths-api-bad-rel #378 a relative path in HostConfig.MaskedPaths was not refused with 400 +systempaths-api-bad-dotdot #378 a .. component in HostConfig.ReadonlyPaths was not refused with 400 +systempaths-bwrap #378 bubblewrap inside a non-privileged container with --security-opt systempaths=unconfined could not mount a fresh /proc +systempaths-symlink-escape #378 a symlink in the image at a MaskedPaths or ReadonlyPaths entry must resolve inside the container root and never touch the host or cover / From 76a61830530865a33636cf7f151417d9fd3db0ee Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 13:29:23 +0100 Subject: [PATCH 003/157] Guest link: cap oversized replies so a big docker top or directory listing cannot drop the VM (#463) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Đoàn Phương Nam <120766900+DPhngNam@users.noreply.github.com> --- crates/kiri-proto/src/lib.rs | 243 +++++++++++++++++++++++++++++++++-- docs/fix-registry.md | 6 + tests/e2e.sh | 8 ++ tests/linux-host.sh | 4 + tests/regressions.tsv | 1 + 5 files changed, 254 insertions(+), 8 deletions(-) diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index ca0a89937..c7edfcec6 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -25,6 +25,13 @@ pub const MAX_FRAME: usize = 1 << 20; /// Bytes before the payload: length plus kind. pub const HEADER: usize = 6; +/// Largest frame body a sender may emit so the whole frame stays within +/// `MAX_FRAME`. A reply built from guest- or container-controlled content (a +/// directory listing, a `top` table) is capped to this; otherwise one huge +/// reply overflows `MAX_FRAME`, the peer rejects the frame, and the whole VM +/// is declared lost and restarted. +pub const MAX_BODY: usize = MAX_FRAME - HEADER; + /// Largest `Output` chunk; keeps frames well under `MAX_FRAME`. pub const MAX_OUTPUT_CHUNK: usize = 64 * 1024; /// Stdin bytes the host may have sent a process beyond what the guest has @@ -312,10 +319,22 @@ fn put_entry(out: &mut Vec, e: &FsEntry<'_>) { /// Encodes an `FsList` reply from entries. pub fn encode_fs_list(out: &mut Vec, entries: &[FsEntry<'_>]) { frame(out, kind::FS_LIST, |o| { - put_u32(o, entries.len() as u32); + // Cap the reply at MAX_BODY, dropping trailing entries: a directory + // with thousands of long names would otherwise overflow MAX_FRAME and + // make the peer lose the whole VM. + let start = o.len(); + put_u32(o, 0); + let mut n: u32 = 0; for e in entries { + // Encoded entry: 4+name | mode u32 | size u64 | mtime u64 | nsec u32 | ino u64. + let entry_len = 4 + e.name.len() + 4 + 8 + 8 + 4 + 8; + if o.len() - start + entry_len > MAX_BODY { + break; + } put_entry(o, e); + n += 1; } + o[start..start + 4].copy_from_slice(&n.to_le_bytes()); }); } @@ -679,6 +698,29 @@ impl<'a> StrList<'a> { put_str(out, s.as_ref()); } } + + /// Like `put`, but keeps the encoded list within `budget` bytes, dropping + /// trailing items (and truncating a single over-long item on a char + /// boundary) so the frame cannot exceed `MAX_FRAME`. The count written is + /// the number actually encoded. Use for replies whose size the sender does + /// not control, such as `top` or a directory listing. + pub fn put_capped>(out: &mut Vec, items: &[S], budget: usize) { + let start = out.len(); + out.extend_from_slice(&0u32.to_le_bytes()); + let mut n: u32 = 0; + for s in items { + // Leave headroom so at least a truncated first item fits: the + // 4-byte count already written plus a 4-byte length prefix. + let s = s.as_ref(); + let s = &s[..s.floor_char_boundary(budget.saturating_sub(8))]; + if out.len() - start + 4 + s.len() > budget { + break; + } + put_str(out, s); + n += 1; + } + out[start..start + 4].copy_from_slice(&n.to_le_bytes()); + } } mod kind { @@ -832,27 +874,27 @@ pub fn encode_dns_rename>(out: &mut Vec, id: &str, bridge: &st /// Encodes a `Usage` reply from the sender's lines. pub fn encode_usage>(out: &mut Vec, lines: &[S]) { - frame(out, kind::USAGE, |out| StrList::put(out, lines)); + frame(out, kind::USAGE, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Top` reply from the sender's lines. pub fn encode_top>(out: &mut Vec, lines: &[S]) { - frame(out, kind::TOP, |out| StrList::put(out, lines)); + frame(out, kind::TOP, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `UsbNodes` reply from the sender's lines. pub fn encode_usb_nodes>(out: &mut Vec, lines: &[S]) { - frame(out, kind::USB_NODES, |out| StrList::put(out, lines)); + frame(out, kind::USB_NODES, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes an `FsEvents` frame from the sender's `OP\tPATH` lines. pub fn encode_fs_events>(out: &mut Vec, lines: &[S]) { - frame(out, kind::FS_EVENTS, |out| StrList::put(out, lines)); + frame(out, kind::FS_EVENTS, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Listening` reply from the sender's lines. pub fn encode_listening>(out: &mut Vec, lines: &[S]) { - frame(out, kind::LISTENING, |out| StrList::put(out, lines)); + frame(out, kind::LISTENING, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Retain` frame from the sender's ids. @@ -948,7 +990,10 @@ impl Msg<'_> { Msg::Ping(v) => frame(out, kind::PING, |o| put_u64(o, v)), Msg::Pong(v) => frame(out, kind::PONG, |o| put_u64(o, v)), Msg::Shutdown => frame(out, kind::SHUTDOWN, |_| {}), - Msg::Error(s) => frame(out, kind::ERROR, |o| o.extend_from_slice(s.as_bytes())), + Msg::Error(s) => frame(out, kind::ERROR, |o| { + let s = &s[..s.floor_char_boundary(MAX_BODY)]; + o.extend_from_slice(s.as_bytes()); + }), Msg::StatsRequest => frame(out, kind::STATS_REQUEST, |_| {}), Msg::Stats(st) => frame(out, kind::STATS, |o| { for v in [st.uptime_ns, st.mem_total_kib, st.mem_available_kib, st.agent_rss_kib, st.mem_used_kib, st.mem_stall, st.oom_kills] { @@ -1589,7 +1634,7 @@ mod tests { fn the_protocol_version_covers_the_seccomp_field() { // An agent from before `RunSpec::seccomp` says 4, and the host refuses // it (guest.rs compares the Hello's version with this one). - assert!(PROTOCOL >= 5); + const { assert!(PROTOCOL >= 5) }; let mut buf = Vec::new(); Msg::Hello(Hello { protocol: PROTOCOL, init_start_ns: 1, ready_ns: 2, mem_total_kib: 3, mem_available_kib: 4 }).encode(&mut buf); let Msg::Hello(h) = decode(&buf).unwrap() else { panic!() }; @@ -1785,4 +1830,186 @@ mod tests { buf.truncate(buf.len() - 1); assert_eq!(decode(&buf), Err(DecodeError::Truncated)); } + + #[test] + fn oversized_replies_stay_within_max_frame() { + // A single `top` line far larger than MAX_FRAME (a container process + // with a huge cmdline): the frame must stay decodable, not overflow. + let huge = "x".repeat(MAX_FRAME * 2); + let mut buf = Vec::new(); + encode_top(&mut buf, core::slice::from_ref(&huge)); + assert!(buf.len() <= MAX_FRAME, "top frame {} > MAX_FRAME", buf.len()); + assert!(frame_len(&buf[..4].try_into().unwrap()).is_ok()); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + let got: Vec<_> = lines.iter().collect(); + assert_eq!(got.len(), 1); + assert!(got[0].len() < huge.len()); // truncated to fit + + // Many long lines: trailing ones are dropped, the frame still fits. + let many: Vec = (0..5000).map(|_| "y".repeat(500)).collect(); + buf.clear(); + encode_top(&mut buf, &many); + assert!(buf.len() <= MAX_FRAME); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + let kept = lines.iter().count(); + assert!(kept > 0 && kept < many.len()); + + // Same for a directory listing with thousands of max-length names. + let names: Vec = (0..5000).map(|_| "n".repeat(255)).collect(); + let entries: Vec> = names + .iter() + .map(|n| FsEntry { name: n, mode: 0o100644, size: 0, mtime: 0, mtime_nsec: 0, ino: 1 }) + .collect(); + buf.clear(); + encode_fs_list(&mut buf, &entries); + assert!(buf.len() <= MAX_FRAME, "fs_list frame {} > MAX_FRAME", buf.len()); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + let kept = fs_entries(count, raw).count(); + assert!(kept > 0 && kept < entries.len()); + } + + #[test] + fn capped_str_list_replies_fit_at_exact_boundary_and_utf8() { + type ListEnc = fn(&mut Vec, &[String]); + let encoders: &[(&str, ListEnc)] = &[ + ("top", encode_top::), + ("usage", encode_usage::), + ("usb_nodes", encode_usb_nodes::), + ("fs_events", encode_fs_events::), + ("listening", encode_listening::), + ]; + // Exact single-item fit (MAX_BODY - 8 bytes) and 1 byte over. + let exact = "a".repeat(MAX_BODY - 8); + let over = "a".repeat(MAX_BODY - 7); + for &(name, enc) in encoders { + let mut buf = Vec::new(); + enc(&mut buf, core::slice::from_ref(&exact)); + assert_eq!(buf.len(), MAX_FRAME, "{name}: exact fit should hit MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len()), "{name}: exact frame_len"); + assert!(decode(&buf).is_ok(), "{name}: exact decode"); + + buf.clear(); + enc(&mut buf, core::slice::from_ref(&over)); + assert_eq!(buf.len(), MAX_FRAME, "{name}: 1-byte-over should cap to MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len()), "{name}: over frame_len"); + assert!(decode(&buf).is_ok(), "{name}: over decode"); + + // 1.5 MiB of 2-byte (`é`) and 4-byte (`🦀`) UTF-8 at every alignment 0..4. + for ch in ["é", "🦀"] { + for pad in 0..4 { + let mut huge = "p".repeat(pad); + let reps = (MAX_FRAME + MAX_FRAME / 2) / ch.len(); + for _ in 0..reps { + huge.push_str(ch); + } + buf.clear(); + enc(&mut buf, &[huge]); + assert!(buf.len() <= MAX_FRAME, "{name} {ch} pad={pad}: {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + assert!(decode(&buf).is_ok(), "{name} {ch} pad={pad}: decode failed"); + } + } + + // 20,000 entries crossing MAX_FRAME, also when appending after existing bytes in buf. + let many: Vec = (0..20_000).map(|i| format!("line-{i:05}-{}", "z".repeat(80))).collect(); + buf.clear(); + buf.extend_from_slice(b"prefix"); + enc(&mut buf, &many); + let frame = &buf[6..]; + assert!(frame.len() <= MAX_FRAME, "{name}: many frame {} > MAX_FRAME", frame.len()); + assert_eq!(frame_len(&frame[..4].try_into().unwrap()), Ok(frame.len())); + assert!(decode(frame).is_ok(), "{name}: many decode failed"); + } + + // Short first item followed by an oversized second item: keeps the first + // and drops the second cleanly without exceeding MAX_FRAME. + let mut buf = Vec::new(); + encode_top(&mut buf, &["first".to_owned(), "x".repeat(MAX_FRAME * 2), "third".to_owned()]); + assert!(buf.len() <= MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + assert_eq!(lines.iter().collect::>(), ["first"]); + } + + #[test] + fn fs_list_stays_within_max_frame_at_boundary_and_utf8() { + // Each encoded entry takes 36 + name.len() bytes; body starts with 4-byte count. + // Pick an entry name length that lands right on MAX_BODY: + // MAX_BODY = 1_048_570; 4 + 10_485 * 100 (64-byte names) = 1_048_504, + // leaving 66 bytes -> a 30-byte name fills 36 + 30 = 66 bytes to hit + // MAX_BODY (and MAX_FRAME) to the exact byte. + let mut names: Vec = (0..10_485).map(|i| format!("{i:064}")).collect(); + names.push("b".repeat(30)); + names.push("overflow".to_owned()); + let entries: Vec> = names + .iter() + .enumerate() + .map(|(i, n)| FsEntry { name: n, mode: 0o100644, size: i as u64, mtime: 1, mtime_nsec: 2, ino: i as u64 }) + .collect(); + let mut buf = Vec::new(); + encode_fs_list(&mut buf, &entries); + assert_eq!(buf.len(), MAX_FRAME, "exact boundary entries should hit MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + assert_eq!(count as usize, 10_486); + let decoded: Vec<_> = fs_entries(count, raw).collect(); + assert_eq!(decoded, entries[..10_486]); + + // 20,000 entries with max-length multi-byte UTF-8 names. + let utf8_name = "🦀".repeat(63); // 252 bytes (<= NAME_MAX 255) + let utf8_entries: Vec> = (0..20_000) + .map(|i| FsEntry { name: &utf8_name, mode: 0o100644, size: i as u64, mtime: 0, mtime_nsec: 0, ino: i as u64 }) + .collect(); + buf.clear(); + encode_fs_list(&mut buf, &utf8_entries); + assert!(buf.len() <= MAX_FRAME, "utf8 fs_list {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + let kept = fs_entries(count, raw).count(); + assert!(kept > 0 && kept < utf8_entries.len()); + + // Single impossibly huge entry (> MAX_BODY): encodes 0 entries, still decodable. + let giant = "g".repeat(MAX_FRAME); + buf.clear(); + encode_fs_list(&mut buf, &[FsEntry { name: &giant, mode: 0o100644, size: 0, mtime: 0, mtime_nsec: 0, ino: 1 }]); + assert!(buf.len() <= MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + assert_eq!(count, 0); + assert_eq!(fs_entries(count, raw).count(), 0); + } + + #[test] + fn oversized_error_stays_within_max_frame_and_valid_utf8() { + let mut buf = Vec::new(); + let exact = "e".repeat(MAX_BODY); + Msg::Error(&exact).encode(&mut buf); + assert_eq!(buf.len(), MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + assert_eq!(decode(&buf).unwrap(), Msg::Error(&exact)); + + let over = "e".repeat(MAX_BODY + 1); + buf.clear(); + Msg::Error(&over).encode(&mut buf); + assert_eq!(buf.len(), MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + assert_eq!(decode(&buf).unwrap(), Msg::Error(&exact)); + + for ch in ["é", "🦀"] { + for pad in 0..4 { + let mut huge = "p".repeat(pad); + let reps = (MAX_FRAME + MAX_FRAME / 2) / ch.len(); + for _ in 0..reps { + huge.push_str(ch); + } + buf.clear(); + Msg::Error(&huge).encode(&mut buf); + assert!(buf.len() <= MAX_FRAME, "error {ch} pad={pad}: {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::Error(got) = decode(&buf).unwrap() else { panic!() }; + assert!(huge.starts_with(got)); + assert!(got.len() <= MAX_BODY && got.len() >= MAX_BODY - 3); + } + } + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 99ae7dc86..2507ad5cc 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 +### #464 Engine: oversized guest replies are capped to the frame limit instead of stopping the VM (unreleased) +- Fixes: #463 A big `docker top` or Files-tab listing restarts the whole VM +- Caused: none known +- Caused by: - +- Check: `top-frame-cap` + ### #490 Engine: systempaths=unconfined, MaskedPaths and ReadonlyPaths are applied (unreleased) - Fixes: #378 Engine: --security-opt systempaths=unconfined is ignored, breaking bubblewrap (bwrap) inside non-privileged containers - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 3a9c988ae..3d0f41c2e 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1410,6 +1410,14 @@ t rmi-during-save "complete runs" bash -c "f=\$(mktemp); rm -f \$f.go; ( $D save $D rm -f e2e-frame e2e-frame-big >/dev/null 2>&1; $D run -d --name e2e-frame alpine sleep 300 >/dev/null t frame-limit-request-alone "refused alive=yes next=ok" bash -c "python3 -c 'import json; print(json.dumps({\"Image\":\"alpine\",\"Cmd\":[\"true\"],\"Env\":[\"BIG=\"+\"a\"*1200000]}))' | curl -s -o /dev/null --unix-socket '$SOCK' -H 'Content-Type: application/json' -X POST --data-binary @- 'http://d/v1.47/containers/create?name=e2e-frame-big'; c=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket '$SOCK' -X POST http://d/v1.47/containers/e2e-frame-big/start); case \$c in 2*) printf 'started ' ;; *) printf 'refused ' ;; esac; echo alive=\$($D exec e2e-frame echo yes) next=\$($D run --rm alpine echo ok)" $D rm -f e2e-frame e2e-frame-big >/dev/null 2>&1 +# An oversized guest reply (`docker top` on a ~1.3 MB cmdline) stays within the +# frame limit: `docker top` succeeds and both that container and a sibling stay +# running instead of dropping the VM link (#463). +$D rm -f e2e-top-big e2e-top-sib >/dev/null 2>&1 +$D run -d --name e2e-top-sib alpine sleep 300 >/dev/null +$D run -d --name e2e-top-big alpine sh -c 'exec sh -c "sleep 1d;:" $(for i in $(seq 160); do printf "%08000d " 0; done)' >/dev/null +t top-frame-cap "top=0 has=yes big=running sib=running" bash -c "for _ in \$(seq 50); do n=\$($D exec e2e-top-big sh -c 'wc -c < /proc/1/cmdline' 2>/dev/null || echo 0); [ \"\${n:-0}\" -gt 1000000 ] && break; sleep 0.1; done; out=\$($D top e2e-top-big 2>&1); rc=\$?; case \"\$out\" in *'sleep 1d'*) has=yes ;; *) has=no ;; esac; echo top=\$rc has=\$has big=\$($D inspect -f '{{.State.Status}}' e2e-top-big) sib=\$($D inspect -f '{{.State.Status}}' e2e-top-sib)" +$D rm -f e2e-top-big e2e-top-sib >/dev/null 2>&1 # Users as Docker resolves them (#664): a numeric one in /etc/passwd gets # its group, one not listed group 0, a name its own. t user-boundaries "0:0 65534:65534 99999:0 nobody:65534 guest:100 1234:5678" bash -c "for u in 0 65534 99999 nobody guest 1234:5678; do printf '%s:%s ' \"\${u%%:*}\" \"\$($D run --rm -u \$u alpine id -g)\"; done" diff --git a/tests/linux-host.sh b/tests/linux-host.sh index aa058a4a9..b548b30f3 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -673,6 +673,10 @@ t systempaths-default "covered:[/proc/interrupts /proc/sys /sys/firmware]" "dock 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" +# An oversized guest reply (`docker top` on a ~1.3 MB cmdline) stays within the +# frame limit: `docker top` succeeds and both that container and a sibling stay +# running instead of dropping the agent link (#463). +t top-frame-cap "top=0 has=yes big=running sib=running" "docker rm -f lh-top-big lh-top-sib >/dev/null 2>&1; docker run -d --name lh-top-sib alpine sleep 300 >/dev/null && docker run -d --name lh-top-big alpine sh -c 'exec sh -c \"sleep 1d;:\" \$(for i in \$(seq 160); do printf \"%08000d \" 0; done)' >/dev/null && for _ in \$(seq 50); do n=\$(docker exec lh-top-big sh -c 'wc -c < /proc/1/cmdline' 2>/dev/null || echo 0); [ \"\${n:-0}\" -gt 1000000 ] && break; sleep 0.1; done && out=\$(docker top lh-top-big 2>&1); rc=\$?; case \"\$out\" in *'sleep 1d'*) has=yes ;; *) has=no ;; esac; echo top=\$rc has=\$has big=\$(docker inspect -f '{{.State.Status}}' lh-top-big) sib=\$(docker inspect -f '{{.State.Status}}' lh-top-sib); docker rm -f lh-top-big lh-top-sib >/dev/null 2>&1" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 9e9a857e8..ae3a8e699 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -209,3 +209,4 @@ systempaths-api-bad-rel #378 a relative path in HostConfig.MaskedPaths was not r systempaths-api-bad-dotdot #378 a .. component in HostConfig.ReadonlyPaths was not refused with 400 systempaths-bwrap #378 bubblewrap inside a non-privileged container with --security-opt systempaths=unconfined could not mount a fresh /proc systempaths-symlink-escape #378 a symlink in the image at a MaskedPaths or ReadonlyPaths entry must resolve inside the container root and never touch the host or cover / +top-frame-cap #463 a docker top reply over MAX_FRAME (1 MiB) made read_frame drop the VM link and kill every running container From 3cb7a59b55664bf13fc258ee44ddf59a20306160 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 13:40:58 +0100 Subject: [PATCH 004/157] Build mirror: leave a registry's tags to the registry (#57) Co-authored-by: Jonnyan404 --- crates/kiri/src/daemon/mirror.rs | 135 +++++++++++++++++++++++++++++-- docs/fix-registry.md | 6 ++ tests/e2e.sh | 31 ++++++- tests/linux-host.sh | 30 +++++++ tests/regressions.tsv | 2 + 5 files changed, 195 insertions(+), 9 deletions(-) diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index 9cd4c6fe7..623c4e551 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -4,7 +4,10 @@ //! A read-only registry API on 127.0.0.1, which containers reach at //! host.docker.internal. buildkitd.toml names it as a mirror of every //! registry Kiri has images from; a mirror that answers 404 is skipped, so -//! anything not here comes from the registry itself. Paths carry a secret +//! anything not here comes from the registry itself. A tag a registry +//! published is not answered here even when Kiri holds it: the registry, +//! not this machine, knows which platforms it has (see `lookup`). +//! Paths carry a secret //! (`/v2////…`), so other local users can't read //! images through it. Manifests are made from the store's records (layers, //! config), the same bytes for the same image every time. @@ -350,7 +353,7 @@ fn answer(conn: TcpStream, engine: &Engine) -> io::Result<()> { if method != "GET" && method != "HEAD" { return head(&mut w, "405 Method Not Allowed", "", 0); } - match lookup(engine, target.split('?').next().unwrap_or_default(), &token()) { + match lookup(&engine.store, target.split('?').next().unwrap_or_default(), &token()) { Some(Found::Manifest(bytes, digest)) => { head(&mut w, "200 OK", &format!("Content-Type: application/vnd.oci.image.manifest.v1+json\r\nDocker-Content-Digest: {digest}\r\n"), bytes.len() as u64)?; if method == "GET" { @@ -403,22 +406,36 @@ fn parse(path: &str, token: &str) -> Option<(String, String, bool, String)> { (!repo.is_empty() && !reference.is_empty() && !reference.contains('/')).then(|| (registry.to_owned(), repo.to_owned(), kind, reference.to_owned())) } -fn lookup(engine: &Engine, path: &str, token: &str) -> Option { +/// Whether the mirror answers for `i` under its tag. It does for an image no +/// registry has (built, loaded, committed: its digest is its config's), which +/// is the one thing a build cannot get anywhere else. An image a registry +/// published is left to that registry, which knows every platform of the tag; +/// answering with the one platform Kiri pulled would hide the rest. +fn serve_tag(i: &Image) -> bool { + i.repo_digest().is_none() +} + +fn lookup(store: &kiri_image::Store, path: &str, token: &str) -> Option { let (registry, repo, is_manifest, reference) = parse(path, token)?; - let images = engine.store.images().ok()?; + let images = store.images().ok()?; let in_repo = |i: &&Image| Reference::parse(&i.name).is_ok_and(|n| n.registry == registry && n.repository == repo); if is_manifest { if reference.starts_with("sha256:") { - return images.iter().filter(in_repo).find_map(|i| manifest(&engine.store, i).filter(|(_, d)| *d == reference)).map(|(b, d)| Found::Manifest(b, d)); + return images.iter().filter(in_repo).find_map(|i| manifest(store, i).filter(|(_, d)| *d == reference)).map(|(b, d)| Found::Manifest(b, d)); } let wanted = Reference::parse(&format!("{registry}/{repo}:{reference}")).ok()?.short(); - let i = images.iter().find(|i| i.name == wanted)?; - let (b, d) = manifest(&engine.store, i)?; + // A tag a registry published is the registry's to answer: Kiri holds + // the one platform it pulled, and serving that says the tag has no + // other, so a build for another platform takes these binaries and + // fails on them (issue #57). 404 here makes the builder skip this + // mirror and pull the platform it asked for. + let i = images.iter().find(|i| i.name == wanted && serve_tag(i))?; + let (b, d) = manifest(store, i)?; return Some(Found::Manifest(b, d)); } // Only blobs of that repository's images. let owned = images.iter().filter(in_repo).any(|i| i.config_digest == reference || i.layers.iter().any(|l| l.digest == reference)); - let path = engine.store.blob_path(&reference).ok()?; + let path = store.blob_path(&reference).ok()?; (owned && path.is_file()).then_some(Found::Blob(path, reference)) } @@ -536,6 +553,108 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_tag_a_registry_published_is_left_to_it() { + // Pulled: its digest is its manifest's, so a registry has it. + let pulled = Image { name: "alpine:3.20".into(), digest: "sha256:manifest".into(), ..made_here() }; + assert!(!serve_tag(&pulled)); + // Pulled through a configured Docker Hub mirror (#119) or from a multi-arch index. + let mirrored = Image { mirror: Some("mirror.lan:5000".into()), index_digest: Some("sha256:index".into()), ..pulled.clone() }; + assert!(!serve_tag(&mirrored)); + // Another tag in the same repository still carries that repository's digest. + assert!(!serve_tag(&pulled.tagged("alpine:latest".into()))); + // Built, loaded or committed here: nothing else can serve it, platform or not. + assert!(serve_tag(&made_here())); + // Tagged into another repository (docker tag alpine:3.20 mybase:dev): + // that name is not in any registry, so the mirror answers for it. + assert!(serve_tag(&pulled.tagged("mybase:dev".into()))); + } + + #[test] + fn lookup_skips_published_tags_but_serves_local_tags_digests_and_blobs() { + let dir = std::env::temp_dir().join(format!("kiri-mirror-lookup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let write_blob = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let cfg = json!({"architecture": "amd64", "os": "linux", "config": {}}); + let (cfg_digest, _) = write_blob(&serde_json::to_vec(&cfg).unwrap()); + let (layer_digest, layer_size) = write_blob(b"layer-bytes"); + let layers = vec![kiri_image::Layer { digest: layer_digest.clone(), size: layer_size, media_type: "application/vnd.oci.image.layer.v1.tar+gzip".into() }]; + + // 1. Registry-pulled image (also when pulled via a #119 mirror): tag + // lookup returns None (404) so BuildKit falls through to the configured + // mirror or upstream registry, while digest and blob lookups still hit + // the local store so cached layers are not re-downloaded. + let pulled = Image { + name: "alpine:3.20".into(), + digest: format!("sha256:{}", "a".repeat(64)), + index_digest: Some(format!("sha256:{}", "b".repeat(64))), + mirror: Some("mirror.lan:5000".into()), + ..kiri_image::archive::from_config("alpine:3.20".into(), &cfg_digest, &cfg, layers.clone()) + }; + let (_, pulled_manifest_digest) = manifest(&store, &pulled).unwrap(); + store.put_image(pulled.clone()).unwrap(); + + assert!(lookup(&store, "/v2/tok/docker.io/library/alpine/manifests/3.20", "tok").is_none()); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/manifests/{pulled_manifest_digest}"), "tok"), + Some(Found::Manifest(_, d)) if d == pulled_manifest_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/blobs/{layer_digest}"), "tok"), + Some(Found::Blob(_, d)) if d == layer_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/blobs/{cfg_digest}"), "tok"), + Some(Found::Blob(_, d)) if d == cfg_digest + )); + // Another repository cannot read alpine's blobs. + assert!(lookup(&store, &format!("/v2/tok/docker.io/library/other/blobs/{layer_digest}"), "tok").is_none()); + + // 2. Retagged into a local repository (`docker tag alpine:3.20 mybase:dev`): + // served by tag and by blob under the new repository. + store.put_image(pulled.tagged("mybase:dev".into())).unwrap(); + assert!(matches!( + lookup(&store, "/v2/tok/docker.io/library/mybase/manifests/dev", "tok"), + Some(Found::Manifest(_, d)) if d == pulled_manifest_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/mybase/blobs/{layer_digest}"), "tok"), + Some(Found::Blob(_, d)) if d == layer_digest + )); + + // 3. Built, loaded or committed here: served by tag until pushed to a registry. + let local = kiri_image::archive::from_config("localhost:5000/myapp:dev".into(), &cfg_digest, &cfg, layers); + store.put_image(local).unwrap(); + assert!(matches!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok"), Some(Found::Manifest(..)))); + store.set_pushed("localhost:5000/myapp:dev", &cfg_digest, &format!("sha256:{}", "c".repeat(64))).unwrap(); + assert!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok").is_none()); + + let _ = std::fs::remove_dir_all(&dir); + } + + /// An image built here: no registry has it. + fn made_here() -> Image { + let config_digest = "sha256:config".to_owned(); + Image { + name: "myapp:dev".into(), + digest: config_digest.clone(), + index_digest: None, + config_digest, + layers: Vec::new(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: kiri_image::RunConfig::default(), + mirror: None, + } + } + #[test] fn token_file_is_private_from_the_start() { use std::os::unix::fs::PermissionsExt; diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 2507ad5cc..f9666ae80 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 +### Build mirror: leave a registry's tags to the registry (unreleased) +- Fixes: #57 Builds for a foreign platform use the local image of the same tag and ignore --platform (Invalid ELF image for this architecture) +- Caused: none known +- Caused by: - +- Check: `build-platform-pulled-tag`, `build-local-tag` + ### #464 Engine: oversized guest replies are capped to the frame limit instead of stopping the VM (unreleased) - Fixes: #463 A big `docker top` or Files-tab listing restarts the whole VM - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 3d0f41c2e..a2f59ee93 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1522,6 +1522,30 @@ if [ -n "$HOSTIP" ]; then t mirror-cli-add "http://$HOSTIP:5056" "$KIRI" registry mirror add "http://$HOSTIP:5056" t mirror-http-pull "3." bash -c "$D pull -q kiri-mirror-only:1 >/dev/null && $D run --rm kiri-mirror-only:1 cat /etc/alpine-release" t mirror-docker-info "http://$HOSTIP:5056/" bash -c "$D info 2>/dev/null | sed -n '/Registry Mirrors/,/^ [A-Z]/p'" + python3 - 5056 <<'PY' +import gzip, hashlib, io, json, sys, tarfile, urllib.request +u = f"http://localhost:{sys.argv[1]}/v2/library/kiri-mirror-only" +h = lambda b: "sha256:" + hashlib.sha256(b).hexdigest() +put = lambda p, ct, b: urllib.request.urlopen(urllib.request.Request(p, data=b, headers={"Content-Type": ct}, method="PUT")) +def blob(b): + loc = urllib.request.urlopen(urllib.request.Request(f"{u}/blobs/uploads/", method="POST")).headers["Location"] + sep = "&" if "?" in loc else "?" + put(f"{loc}{sep}digest={h(b)}", "application/octet-stream", b) + return h(b) +ms = [] +for a in ("amd64", "arm64"): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w") as t: + d = f"layer-{a}\n".encode(); ti = tarfile.TarInfo("arch"); ti.size = len(d); t.addfile(ti, io.BytesIO(d)) + raw = buf.getvalue(); gz = gzip.compress(raw); ld = blob(gz) + cfg = json.dumps({"architecture": a, "os": "linux", "config": {"Labels": {"plat": f"from-{a}"}}, "rootfs": {"type": "layers", "diff_ids": [h(raw)]}}).encode() + cd = blob(cfg); mt = "application/vnd.docker.distribution.manifest.v2+json" + m = json.dumps({"schemaVersion": 2, "mediaType": mt, "config": {"mediaType": "application/vnd.docker.container.image.v1+json", "digest": cd, "size": len(cfg)}, "layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "digest": ld, "size": len(gz)}]}).encode() + put(f"{u}/manifests/{h(m)}", mt, m) + ms.append({"mediaType": mt, "digest": h(m), "size": len(m), "platform": {"architecture": a, "os": "linux"}}) +lt = "application/vnd.docker.distribution.manifest.list.v2+json" +put(f"{u}/manifests/multi", lt, json.dumps({"schemaVersion": 2, "mediaType": lt, "manifests": ms}).encode()) +PY if command -v openssl >/dev/null 2>&1 && openssl req -x509 -newkey rsa:2048 -nodes -days 3 -subj /CN=kiri-other.test -addext subjectAltName=DNS:kiri-other.test -keyout "$REG/other.key" -out "$REG/other.pem" 2>/dev/null; then chmod 644 "$REG/other.key" $D run -d --name reg3 -p 5444:5000 -v "$REG:/tls:ro" -e REGISTRY_HTTP_TLS_CERTIFICATE=/tls/other.pem -e REGISTRY_HTTP_TLS_KEY=/tls/other.key registry:2 >/dev/null @@ -1535,8 +1559,13 @@ if [ -n "$HOSTIP" ]; then skip_setup insecure-selfsigned-build "openssl is not installed" fi t mirror-build "rorrim-tliub" bash -c "gw=\$($D inspect reg2 --format '{{.NetworkSettings.IPAddress}}'):5000; \"$KIRI\" registry mirror remove http://$HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry insecure add \$gw >/dev/null 2>&1; \"$KIRI\" registry mirror add http://\$gw >/dev/null 2>&1; $D rmi kiri-mirror-only:1 >/dev/null 2>&1; mkdir -p \"$REG/bins\" && printf 'FROM kiri-mirror-only:1\nRUN echo built-mirror | rev\n' > \"$REG/bins/Dockerfile\" && DOCKER_BUILDKIT=0 $D build --no-cache \"$REG/bins\" >\"$REG/b.log\" 2>&1; grep -m1 -o rorrim-tliub \"$REG/b.log\" || grep -Ei -m3 'error|fail' \"$REG/b.log\"; \"$KIRI\" registry mirror remove http://\$gw >/dev/null 2>&1; \"$KIRI\" registry insecure remove \$gw >/dev/null 2>&1" + # A tag a registry published is left to the registry in builds, even when + # one platform of it is already in the local store (#57); an image only in + # the local store is still served from Kiri's mirror. + t build-platform-pulled-tag "resolved-other-platform" bash -c "\"$KIRI\" registry insecure add $HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry mirror add http://$HOSTIP:5056 >/dev/null 2>&1; $D pull -q kiri-mirror-only:multi >/dev/null 2>&1; gw=\$($D inspect reg2 --format '{{.NetworkSettings.IPAddress}}'):5000; \"$KIRI\" registry mirror remove http://$HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry insecure add \$gw >/dev/null 2>&1; \"$KIRI\" registry mirror add http://\$gw >/dev/null 2>&1; here=\$($D version --format '{{.Server.Arch}}') && { [ \"\$here\" = amd64 ] && other=arm64 || other=amd64; } && lhere=\$($D image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:multi) && mkdir -p \"$REG/bins\" && printf 'FROM kiri-mirror-only:multi\nCOPY Dockerfile /df\n' > \"$REG/bins/Dockerfile\" && DOCKER_BUILDKIT=0 $D build -q --no-cache --platform linux/\$other -t kiri-mirror-only:built \"$REG/bins\" >/dev/null 2>&1 && lbuilt=\$($D image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:built) && pbuilt=\$($D image inspect -f '{{.Architecture}} {{index .Config.Labels \"plat\"}}' kiri-mirror-only:built) && [ \"\$pbuilt\" = \"\$other from-\$other\" ] && [ \"\$lbuilt\" != \"\$lhere\" ] && echo resolved-other-platform || echo \"here=\$here got=\$pbuilt lhere=\$lhere lbuilt=\$lbuilt\"; \"$KIRI\" registry mirror remove http://\$gw >/dev/null 2>&1; \"$KIRI\" registry insecure remove \$gw >/dev/null 2>&1" + t build-local-tag "local-still-served" bash -c "if ! $D image inspect kiri-mirror-only:multi >/dev/null 2>&1; then \"$KIRI\" registry insecure add $HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry mirror add http://$HOSTIP:5056 >/dev/null 2>&1; $D pull -q kiri-mirror-only:multi >/dev/null 2>&1; fi; gw=\$($D inspect reg2 --format '{{.NetworkSettings.IPAddress}}'):5000; \"$KIRI\" registry mirror remove http://$HOSTIP:5056 >/dev/null 2>&1; \"$KIRI\" registry insecure add \$gw >/dev/null 2>&1; \"$KIRI\" registry mirror add http://\$gw >/dev/null 2>&1; here=\$($D version --format '{{.Server.Arch}}') && $D tag kiri-mirror-only:multi kiri-local-only:1 && mkdir -p \"$REG/bins\" && printf 'FROM kiri-local-only:1\nCOPY Dockerfile /df2\n' > \"$REG/bins/Dockerfile\" && DOCKER_BUILDKIT=0 $D build -q --no-cache -t kiri-local-only:built \"$REG/bins\" >/dev/null 2>&1 && [ \"\$($D image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-local-only:built)\" = \"from-\$here\" ] && echo local-still-served; \"$KIRI\" registry mirror remove http://\$gw >/dev/null 2>&1; \"$KIRI\" registry insecure remove \$gw >/dev/null 2>&1" "$KIRI" registry mirror remove "http://$HOSTIP:5056" >/dev/null 2>&1; "$KIRI" registry insecure remove "$HOSTIP:5056" >/dev/null 2>&1; $R logout "$HOSTIP:5055" >/dev/null 2>&1 - $D rmi kiri-mirror-only:1 >/dev/null 2>&1; $D rm -f reg2 >/dev/null + $D rmi kiri-mirror-only:1 kiri-mirror-only:multi kiri-mirror-only:built kiri-local-only:1 kiri-local-only:built >/dev/null 2>&1; $D rm -f reg2 >/dev/null else skip insecure-registries "this computer has no network address to reach the registry at" fi diff --git a/tests/linux-host.sh b/tests/linux-host.sh index b548b30f3..49cd326e9 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -360,6 +360,36 @@ t insecure-hand-edit-keeps-keys "kept" "/opt/kiri/kiri registry mirror add http: t mirror-http-pull "Downloaded newer image" "docker pull kiri-mirror-only:1 2>&1" t mirror-docker-info "http://$RIP:5055/" "docker info 2>/dev/null | sed -n '/Registry Mirrors/,/^ [A-Z]/p'" t mirror-build "rorrim-tliub" "gw=\$(docker inspect kiri-reg-http --format '{{.NetworkSettings.IPAddress}}'):5000; /opt/kiri/kiri registry mirror remove http://$RIP:5055 >/dev/null 2>&1; /opt/kiri/kiri registry insecure add \$gw >/dev/null 2>&1; /opt/kiri/kiri registry mirror add http://\$gw >/dev/null 2>&1; docker rmi kiri-mirror-only:1 >/dev/null 2>&1; printf 'FROM kiri-mirror-only:1\\nRUN echo built-mirror | rev\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache /bins >/tmp/b.log 2>&1; grep -m1 -o rorrim-tliub /tmp/b.log || grep -i -m3 'error\|fail' /tmp/b.log" +# A tag a registry published is left to the registry in builds, even when one +# platform of it is already in the local store, so a build for another +# platform gets the platform it asked for (#57); an image only in the local +# store is still served from Kiri's mirror. +MULTI_PUSH='python3 -c '\'' +import gzip, hashlib, io, json, sys, tarfile, urllib.request +u = f"http://localhost:{sys.argv[1]}/v2/library/kiri-mirror-only" +h = lambda b: "sha256:" + hashlib.sha256(b).hexdigest() +put = lambda p, ct, b: urllib.request.urlopen(urllib.request.Request(p, data=b, headers={"Content-Type": ct}, method="PUT")) +def blob(b): + loc = urllib.request.urlopen(urllib.request.Request(f"{u}/blobs/uploads/", method="POST")).headers["Location"] + sep = "&" if "?" in loc else "?" + put(f"{loc}{sep}digest={h(b)}", "application/octet-stream", b) + return h(b) +ms = [] +for a in ("amd64", "arm64"): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w") as t: + d = f"layer-{a}\n".encode(); ti = tarfile.TarInfo("arch"); ti.size = len(d); t.addfile(ti, io.BytesIO(d)) + raw = buf.getvalue(); gz = gzip.compress(raw); ld = blob(gz) + cfg = json.dumps({"architecture": a, "os": "linux", "config": {"Labels": {"plat": f"from-{a}"}}, "rootfs": {"type": "layers", "diff_ids": [h(raw)]}}).encode() + cd = blob(cfg); mt = "application/vnd.docker.distribution.manifest.v2+json" + m = json.dumps({"schemaVersion": 2, "mediaType": mt, "config": {"mediaType": "application/vnd.docker.container.image.v1+json", "digest": cd, "size": len(cfg)}, "layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "digest": ld, "size": len(gz)}]}).encode() + put(f"{u}/manifests/{h(m)}", mt, m) + ms.append({"mediaType": mt, "digest": h(m), "size": len(m), "platform": {"architecture": a, "os": "linux"}}) +lt = "application/vnd.docker.distribution.manifest.list.v2+json" +put(f"{u}/manifests/multi", lt, json.dumps({"schemaVersion": 2, "mediaType": lt, "manifests": ms}).encode()) +'\'' 5055' +t build-platform-pulled-tag "resolved-other-platform" "$MULTI_PUSH && here=\$(docker version --format '{{.Server.Arch}}') && { [ \"\$here\" = amd64 ] && other=arm64 || other=amd64; } && docker pull -q kiri-mirror-only:multi >/dev/null && lhere=\$(docker image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:multi) && printf 'FROM kiri-mirror-only:multi\\nCOPY Dockerfile /df\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache --platform linux/\$other -t kiri-mirror-only:built /bins >/dev/null 2>&1 && lbuilt=\$(docker image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:built) && pbuilt=\$(docker image inspect -f '{{.Architecture}} {{index .Config.Labels \"plat\"}}' kiri-mirror-only:built) && [ \"\$pbuilt\" = \"\$other from-\$other\" ] && [ \"\$lbuilt\" != \"\$lhere\" ] && echo resolved-other-platform || echo \"here=\$here got=\$pbuilt lhere=\$lhere lbuilt=\$lbuilt\"" +t build-local-tag "local-still-served" "here=\$(docker version --format '{{.Server.Arch}}') && docker tag kiri-mirror-only:multi kiri-local-only:1 && printf 'FROM kiri-local-only:1\\nCOPY Dockerfile /df2\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache -t kiri-local-only:built /bins >/dev/null 2>&1 && [ \"\$(docker image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-local-only:built)\" = \"from-\$here\" ] && echo local-still-served; docker rmi kiri-mirror-only:multi kiri-mirror-only:built kiri-local-only:1 kiri-local-only:built >/dev/null 2>&1" # 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 diff --git a/tests/regressions.tsv b/tests/regressions.tsv index ae3a8e699..dc53708a9 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -210,3 +210,5 @@ systempaths-api-bad-dotdot #378 a .. component in HostConfig.ReadonlyPaths was n systempaths-bwrap #378 bubblewrap inside a non-privileged container with --security-opt systempaths=unconfined could not mount a fresh /proc systempaths-symlink-escape #378 a symlink in the image at a MaskedPaths or ReadonlyPaths entry must resolve inside the container root and never touch the host or cover / top-frame-cap #463 a docker top reply over MAX_FRAME (1 MiB) made read_frame drop the VM link and kill every running container +build-platform-pulled-tag #57 a build for another platform from a tag already pulled locally took the local image's platform instead of asking the registry +build-local-tag #57 leaving registry tags to the registry must still serve images built, loaded or tagged only here From a74e67910961f57f2201a3e8cbc40270d0387ff6 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 13:56:13 +0100 Subject: [PATCH 005/157] Engine: warn on seccomp=unconfined that Kiri's host boundary stays (#516) --- crates/kiri/src/daemon/api.rs | 62 ++++++++++++++++++++++++++++++++--- docs/fix-registry.md | 6 ++++ tests/e2e.sh | 7 ++++ tests/linux-host.sh | 6 ++++ tests/regressions.tsv | 5 +++ 5 files changed, 81 insertions(+), 5 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index a1c27d1ae..a4ef93d7f 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2161,6 +2161,15 @@ pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> super::engi l } +/// Returned in `POST /containers/create`'s `Warnings` when the caller asks for +/// `--security-opt seccomp=unconfined` (or `seccomp:unconfined`). Kiri lifts +/// the default syscall filter there, but `kiri-init` still installs the host +/// boundary on both VM and Linux-host containers (no `io_uring`, no `AF_VSOCK` +/// sockets), so workloads that ask for `seccomp=unconfined` to get `io_uring` +/// are told up front instead of failing silently with `EPERM` (#516). +const SECCOMP_UNCONFINED_WARNING: &str = + "seccomp=unconfined lifts the default syscall filter, but Kiri keeps its host boundary: io_uring and vsock sockets stay blocked"; + pub(super) fn create(req: &Request, engine: &Engine) -> Result { let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; let image_name = body["Image"].as_str().unwrap_or_default(); @@ -2168,11 +2177,17 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { return Err(Error::BadRequest("no image specified".into())); } let host = &body["HostConfig"]; + let security_opt = strings(&host["SecurityOpt"]).unwrap_or_default(); // A seccomp profile Kiri cannot apply fails the create, before anything // (volumes) is made for it. - if let super::seccomp::Choice::Profile(json) = super::seccomp::choice(&strings(&host["SecurityOpt"]).unwrap_or_default()).map_err(Error::BadRequest)? { - super::seccomp::compile(json, profile_caps(caps_from(host)?, host["Privileged"].as_bool().unwrap_or(false))).map_err(Error::BadRequest)?; - } + let seccomp_unconfined = match super::seccomp::choice(&security_opt).map_err(Error::BadRequest)? { + super::seccomp::Choice::Profile(json) => { + super::seccomp::compile(json, profile_caps(caps_from(host)?, host["Privileged"].as_bool().unwrap_or(false))).map_err(Error::BadRequest)?; + false + } + super::seccomp::Choice::Unconfined => true, + super::seccomp::Choice::Default => false, + }; let network_mode = match host["NetworkMode"].as_str().unwrap_or("default") { "" | "default" => body["NetworkingConfig"]["EndpointsConfig"].as_object() .and_then(|eps| endpoints_primary(eps.keys().map(String::as_str), |key| engine.lock_net().find(key).map(|n| (n.name.clone(), n.internal)))) @@ -2258,7 +2273,10 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { } extra_hosts.push(format!("{ip}\t{name}")); } - let warnings: Vec<&str> = Vec::new(); + let mut warnings: Vec<&str> = Vec::new(); + if seccomp_unconfined { + warnings.push(SECCOMP_UNCONFINED_WARNING); + } // --ulimit, --sysctl, --device, --device-cgroup-rule, --group-add: // refused now with Docker's error rather than at start. let host_opts = super::hostopts::from_host(host); @@ -2326,7 +2344,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { caps: caps_from(host)?, cap_add: strings(&host["CapAdd"]).unwrap_or_default(), cap_drop: strings(&host["CapDrop"]).unwrap_or_default(), - security_opt: strings(&host["SecurityOpt"]).unwrap_or_default(), + security_opt, readonly_rootfs: host["ReadonlyRootfs"].as_bool().unwrap_or(false), hostname, stop_signal: body["StopSignal"].as_str().filter(|s| !s.is_empty()).map(signal).or_else(|| { @@ -5011,6 +5029,40 @@ mod network_option_tests { let _ = std::fs::remove_dir_all(&dir); } + /// `--security-opt seccomp=unconfined` (and `seccomp:unconfined`) warns in + /// `POST /containers/create`'s `Warnings` that Kiri's host boundary stays + /// in place; default containers, `--privileged` alone, and options where a + /// later `seccomp=` entry overrides `unconfined` produce no warning (#516). + #[test] + fn seccomp_unconfined_warns_that_the_host_boundary_stays() { + let dir = std::env::temp_dir().join(format!("kiri-seccomp-warn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-23T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"]}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + let warnings_for = |host: Value| { + let body = json!({"Image": "demo:local", "HostConfig": host}); + let res = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + res["Warnings"].clone() + }; + let expected = json!([super::SECCOMP_UNCONFINED_WARNING]); + assert_eq!(warnings_for(json!({})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=builtin"]})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp:unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=builtin", "seccomp=unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined", "seccomp=builtin"]})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined", r#"seccomp={"defaultAction":"SCMP_ACT_ALLOW"}"#]})), json!([])); + assert_eq!(warnings_for(json!({"Privileged": true})), json!([])); + assert_eq!(warnings_for(json!({"Privileged": true, "SecurityOpt": ["seccomp=unconfined"]})), expected); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn image_and_container_labels_follow_docker() { let dir = std::env::temp_dir().join(format!("kiri-labels-test-{}", std::process::id())); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index f9666ae80..971e38eec 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 +### Engine: `seccomp=unconfined` warns that Kiri's host boundary stays in place (unreleased) +- Fixes: #516 Apache Iggy can't start: the host-boundary filter blocks io_uring, and `seccomp=unconfined` / `--privileged` can't lift it +- Caused: none known +- Caused by: - +- Check: `seccomp-unconfined-warns`, `seccomp-unconfined-colon-warns`, `seccomp-unconfined-api-warnings`, `seccomp-default-no-warning`, `seccomp-unconfined-io-uring-blocked` + ### Build mirror: leave a registry's tags to the registry (unreleased) - Fixes: #57 Builds for a foreign platform use the local image of the same tag and ignore --platform (Invalid ELF image for this architecture) - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index a2f59ee93..ac057e2f2 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1892,6 +1892,13 @@ t seccomp-on "Seccomp: 2" $D run --rm alpine grep Seccomp: /proc/self/status t seccomp-userns "not permitted" $D run --rm alpine unshare -U true t seccomp-keyctl "not permitted" bash -c "$D run --rm alpine sh -c 'apk add -q keyutils >/dev/null 2>&1; keyctl show 2>&1'" t seccomp-unconfined "userns-ok" $D run --rm --security-opt seccomp=unconfined alpine unshare -U echo userns-ok +# seccomp=unconfined / seccomp:unconfined warns that Kiri's host boundary +# (io_uring and vsock sockets) stays in place, while default containers do not (#516). +t seccomp-unconfined-warns "io_uring and vsock sockets stay blocked" $D run --rm --security-opt seccomp=unconfined alpine true +t seccomp-unconfined-colon-warns "io_uring and vsock sockets stay blocked" $D run --rm --security-opt seccomp:unconfined alpine true +t seccomp-unconfined-api-warnings "io_uring and vsock sockets stay blocked" bash -c "out=\$(curl -s --unix-socket $SQ -H 'Content-Type: application/json' -d '{\"Image\":\"alpine\",\"Cmd\":[\"true\"],\"HostConfig\":{\"SecurityOpt\":[\"seccomp=unconfined\"]}}' http://d/containers/create); id=\$(printf '%s' \"\$out\" | sed -n 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\1/p'); [ -n \"\$id\" ] && $D rm -f \"\$id\" >/dev/null 2>&1; printf '%s\n' \"\$out\"" +t seccomp-default-no-warning "[]" bash -c "out=\$(curl -s --unix-socket $SQ -H 'Content-Type: application/json' -d '{\"Image\":\"alpine\",\"Cmd\":[\"true\"]}' http://d/containers/create); id=\$(printf '%s' \"\$out\" | sed -n 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\1/p'); [ -n \"\$id\" ] && $D rm -f \"\$id\" >/dev/null 2>&1; printf '%s\n' \"\$out\" | sed -n 's/.*\"Warnings\":\(\[[^]]*\]\).*/\1/p'" +t seccomp-unconfined-io-uring-blocked "-1 1" $D run --rm --security-opt seccomp=unconfined python:3.13-alpine python -c 'import ctypes; libc = ctypes.CDLL(None, use_errno=True); r = libc.syscall(425, 1, ctypes.create_string_buffer(120)); print(r, ctypes.get_errno())' t seccomp-privileged-boundary "Seccomp: 2" $D run --rm --privileged alpine grep Seccomp: /proc/self/status t vsock-unconfined "Address family not supported" $D run --rm --security-opt seccomp=unconfined python:3.13-alpine python -c 'import socket; socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)' t vsock-privileged "Address family not supported" $D run --rm --privileged python:3.13-alpine python -c 'import socket; socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)' diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 49cd326e9..1c014f1f3 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -124,6 +124,12 @@ t memory-limit "67108864" "docker run --rm --memory 64m alpine cat /sys/fs/cgrou # was created as root while the container's cgroup directory was still open. t workdir-made-inside-root "outside 0" "find /sys/fs/cgroup /var/lib/kiri /run -name kiri-wd-probe -exec rmdir {} + 2>/dev/null; for n in \$(seq 3 25); do for p in kiri-wd-probe ../kiri-wd-probe; do docker run --rm -w /proc/self/fd/\$n/\$p alpine true >/dev/null 2>&1; done; done; echo outside \$(find /sys/fs/cgroup /var/lib/kiri /run -name kiri-wd-probe 2>/dev/null | wc -l)" t seccomp "Seccomp: 2" "docker run --rm alpine grep Seccomp: /proc/self/status" +# seccomp=unconfined / seccomp:unconfined warns that Kiri's host boundary +# (io_uring and vsock sockets) stays in place (#516). +t seccomp-unconfined-warns "io_uring and vsock sockets stay blocked" "docker run --rm --security-opt seccomp=unconfined alpine unshare -U echo userns-ok" +t seccomp-unconfined-colon-warns "io_uring and vsock sockets stay blocked" "docker run --rm --security-opt seccomp:unconfined alpine true" +t seccomp-unconfined-api-warnings "io_uring and vsock sockets stay blocked" "out=\$(curl -s --unix-socket /root/.kiri/run/docker.sock -H 'Content-Type: application/json' -d '{\"Image\":\"alpine\",\"Cmd\":[\"true\"],\"HostConfig\":{\"SecurityOpt\":[\"seccomp=unconfined\"]}}' http://d/containers/create); id=\$(printf '%s' \"\$out\" | sed -n 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\\1/p'); [ -n \"\$id\" ] && docker rm -f \"\$id\" >/dev/null 2>&1; printf '%s\n' \"\$out\"" +t seccomp-default-no-warning "[]" "out=\$(curl -s --unix-socket /root/.kiri/run/docker.sock -H 'Content-Type: application/json' -d '{\"Image\":\"alpine\",\"Cmd\":[\"true\"]}' http://d/containers/create); id=\$(printf '%s' \"\$out\" | sed -n 's/.*\"Id\":\"\([0-9a-f]*\)\".*/\\1/p'); [ -n \"\$id\" ] && docker rm -f \"\$id\" >/dev/null 2>&1; printf '%s\n' \"\$out\" | sed -n 's/.*\"Warnings\":\(\[[^]]*\]\).*/\\1/p'" t udp "10.9.8.7" "docker run -d --name dns -p 15354:53/udp alpine sh -c 'apk add -q dnsmasq >/dev/null 2>&1; dnsmasq -k --address=/kiri.test/10.9.8.7' >/dev/null; for i in \$(seq 40); do out=\$(nslookup -port=15354 kiri.test 127.0.0.1 2>/dev/null) && break; sleep 0.5; done; echo \"\$out\" | grep -o 10.9.8.7" t ipv6-network "true" "docker network create --ipv6 --subnet fd00:4c:1::/64 lh6 >/dev/null && docker network inspect lh6 -f '{{.EnableIPv6}}'" t ipv6-ping "1 packets received" "docker run -d --name v6a --network lh6 nginx:alpine >/dev/null; docker run --rm --network lh6 alpine ping -6 -c 1 -W 2 v6a" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index dc53708a9..b0fc23763 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -212,3 +212,8 @@ systempaths-symlink-escape #378 a symlink in the image at a MaskedPaths or Reado top-frame-cap #463 a docker top reply over MAX_FRAME (1 MiB) made read_frame drop the VM link and kill every running container build-platform-pulled-tag #57 a build for another platform from a tag already pulled locally took the local image's platform instead of asking the registry build-local-tag #57 leaving registry tags to the registry must still serve images built, loaded or tagged only here +seccomp-unconfined-warns #516 --security-opt seccomp=unconfined gave no warning that Kiri keeps its host boundary (io_uring and vsock sockets stay blocked) +seccomp-unconfined-colon-warns #516 --security-opt seccomp:unconfined gave no warning that Kiri keeps its host boundary +seccomp-unconfined-api-warnings #516 POST /containers/create returned empty Warnings when seccomp=unconfined was passed +seccomp-default-no-warning #516 a default container without seccomp=unconfined must return empty Warnings +seccomp-unconfined-io-uring-blocked #516 io_uring_setup must stay blocked with EPERM even under seccomp=unconfined From 099f22ce83ca3c1969760ca3b0b2d48189bde962 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 14:08:24 +0100 Subject: [PATCH 006/157] Layers: an empty number in a tar header is 0, as in Docker, so servicebus-emulator unpacks (#618) Co-authored-by: Masih Moloodian --- crates/kiri-init/src/linux/layers.rs | 3 +- crates/kiri-init/src/linux/mod.rs | 1 + crates/kiri-init/src/linux/tarnum.rs | 561 +++++++++++++++++++++++++++ docs/fix-registry.md | 6 + tests/e2e.sh | 5 +- tests/lib/tar-empty-numbers.py | 36 ++ tests/linux-host.sh | 4 + tests/regressions.tsv | 1 + 8 files changed, 615 insertions(+), 2 deletions(-) create mode 100644 crates/kiri-init/src/linux/tarnum.rs create mode 100755 tests/lib/tar-empty-numbers.py diff --git a/crates/kiri-init/src/linux/layers.rs b/crates/kiri-init/src/linux/layers.rs index ce663d26b..6f63ba513 100644 --- a/crates/kiri-init/src/linux/layers.rs +++ b/crates/kiri-init/src/linux/layers.rs @@ -165,7 +165,8 @@ fn untar(reader: impl Read, dest: &Path) -> io::Result { fn untar_in(reader: impl Read, dest: &Path, detect_userns: fn() -> bool) -> io::Result { // Only looked at once a device or fifo entry turns up. let mut userns = None; - let mut archive = tar::Archive::new(reader); + // Empty numbers in headers read as 0, as in Docker (#618). + let mut archive = tar::Archive::new(super::tarnum::GoNumbers::new(reader)); archive.set_preserve_permissions(true); archive.set_preserve_ownerships(true); archive.set_preserve_mtime(true); diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index 6a3bc8a57..e26642c91 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -17,6 +17,7 @@ mod relay; mod roots; mod seccomp; mod sys; +mod tarnum; mod transport; mod trim; mod usb; diff --git a/crates/kiri-init/src/linux/tarnum.rs b/crates/kiri-init/src/linux/tarnum.rs new file mode 100644 index 000000000..241c128d7 --- /dev/null +++ b/crates/kiri-init/src/linux/tarnum.rs @@ -0,0 +1,561 @@ +//! Tar numbers as Go's `archive/tar`, so Docker, reads them: a numeric header +//! field that is empty, only NULs or spaces, is 0. tar-rs refuses one +//! ("numeric field was not a number"), and some image builders leave a +//! directory's size, uid and gid empty, so their layers did not unpack (#618). + +use std::io::{self, Read}; + +const BLOCK: usize = 512; + +/// The size field, which tar-rs reads in every header, as (start, end). +const SIZE: (usize, usize) = (124, 136); +/// mode, uid, gid and mtime, which it reads for an entry it unpacks, not for +/// an extension header (PAX, GNU long name): tar-rs itself leaves those +/// empty there. +const ENTRY: [(usize, usize); 4] = [(100, 108), (108, 116), (116, 124), (136, 148)]; +/// devmajor and devminor, which it reads for a device of a ustar or GNU +/// header only. +const DEVICE: [(usize, usize); 2] = [(329, 337), (337, 345)]; +/// realsize, which it reads for a GNU sparse header only. +const REALSIZE: [(usize, usize); 1] = [(483, 495)]; + +/// Passes a tar stream through, writing each empty number of a header as 0 +/// and making that header's checksum again. Only a header whose checksum is +/// right is touched: a broken one goes on as it came, for tar-rs to refuse. +/// Headers are found where tar-rs looks for them: after each entry's data, +/// whose size a PAX `size` record overrides, and after a GNU sparse header's +/// extension blocks. A zero block ends the archive for tar-rs, and from there +/// on everything passes as it is. +pub struct GoNumbers { + inner: R, + block: [u8; BLOCK], + /// The bytes of `block` read, and how many of them have gone out. + len: usize, + at: usize, + /// Bytes of entry data, with padding, before the next header. + data: u64, + /// A GNU sparse extension block comes next. + sparse_ext: bool, + /// The data of the PAX `x` entry being read, and how many unpadded bytes + /// of it remain (tar-rs skips the block padding after it). + pax: Option<(Vec, u64)>, + /// The size a PAX `x` entry gave the entry after it. + pax_size: Option, + passthrough: bool, +} + +impl GoNumbers { + pub fn new(inner: R) -> GoNumbers { + GoNumbers { inner, block: [0; BLOCK], len: 0, at: 0, data: 0, sparse_ext: false, pax: None, pax_size: None, passthrough: false } + } + + /// The next block, read whole if the stream has one. + fn next_block(&mut self) -> io::Result<()> { + let mut len = 0; + while len < BLOCK { + match self.inner.read(&mut self.block[len..]) { + Ok(0) => break, + Ok(n) => len += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + (self.len, self.at) = (len, 0); + if len < BLOCK { + // The end, or a cut-off block tar-rs will report. + self.passthrough = true; + } + Ok(()) + } + + fn header(&mut self) { + let h = &mut self.block; + if h.iter().all(|&b| b == 0) || Some(checksum(h)) != octal(&h[148..156]) { + self.passthrough = true; + return; + } + let ustar = &h[257..263] == b"ustar\0" && &h[263..265] == b"00"; + let gnu = &h[257..263] == b"ustar " && &h[263..265] == b" \0"; + let kind = h[156]; + let extension = matches!(kind, b'L' | b'K' | b'x' | b'g'); + let continues = (ustar || gnu) && matches!(kind, b'L' | b'K' | b'x'); + let device = (ustar || gnu) && matches!(kind, b'3' | b'4'); + let sparse = gnu && kind == b'S'; + let entry: &[(usize, usize)] = if extension { &[] } else { &ENTRY }; + let devices: &[(usize, usize)] = if device { &DEVICE } else { &[] }; + let realsize: &[(usize, usize)] = if sparse { &REALSIZE } else { &[] }; + let mut changed = false; + for &(a, b) in std::iter::once(&SIZE).chain(entry).chain(devices).chain(realsize) { + if h[a..b].iter().all(|&c| c == 0 || c == b' ') { + h[a..b - 1].fill(b'0'); + h[b - 1] = 0; + changed = true; + } + } + if changed { + let sum = format!("{:06o}\0 ", checksum(h)); + h[148..156].copy_from_slice(sum.as_bytes()); + } + + let Some(mut size) = number(&h[SIZE.0..SIZE.1]) else { + self.passthrough = true; + return; + }; + if !continues + && let Some(pax) = self.pax_size.take() + && !extension + { + size = pax; + } + self.sparse_ext = sparse && h[482] == 1; + self.data = size.div_ceil(BLOCK as u64).saturating_mul(BLOCK as u64); + if kind == b'x' && (ustar || gnu) { + self.pax = Some((Vec::new(), size)); + self.end_of_data(); + } + } + + /// An entry's data has all gone: a PAX entry's records take effect. + fn end_of_data(&mut self) { + if self.data == 0 + && let Some((pax, _)) = self.pax.take() + { + self.pax_size = pax_size(&pax); + } + } +} + +impl Read for GoNumbers { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + loop { + if buf.is_empty() { + return Ok(0); + } + if self.at < self.len { + let n = buf.len().min(self.len - self.at); + buf[..n].copy_from_slice(&self.block[self.at..self.at + n]); + self.at += n; + return Ok(n); + } + if self.passthrough { + return self.inner.read(buf); + } + if self.sparse_ext { + self.next_block()?; + self.sparse_ext = self.len == BLOCK && self.block[504] == 1; + continue; + } + if self.data > 0 { + let want = buf.len().min(usize::try_from(self.data).unwrap_or(usize::MAX)); + let n = self.inner.read(&mut buf[..want])?; + if n == 0 { + return Ok(0); + } + if let Some((pax, left)) = &mut self.pax { + let take = (n as u64).min(*left) as usize; + pax.extend_from_slice(&buf[..take]); + *left -= take as u64; + } + self.data -= n as u64; + self.end_of_data(); + return Ok(n); + } + self.next_block()?; + if !self.passthrough { + self.header(); + } + } + } +} + +/// The header's checksum as tar-rs reckons it: its bytes, the checksum field +/// counted as spaces. +fn checksum(h: &[u8; BLOCK]) -> u64 { + h[..148].iter().chain(&h[156..]).map(|&b| u64::from(b)).sum::() + 8 * 32 +} + +/// An octal field as tar-rs reads it: up to its first NUL, spaces trimmed. +fn octal(field: &[u8]) -> Option { + let text = field.split(|&b| b == 0).next().unwrap_or_default(); + u64::from_str_radix(std::str::from_utf8(text).ok()?.trim(), 8).ok() +} + +/// A numeric field, octal or (high bit set) base-256, as tar-rs reads it. +fn number(field: &[u8]) -> Option { + if field[0] & 0x80 == 0 { + return octal(field); + } + let (first, rest) = if field.len() == 8 { (u64::from(field[0] ^ 0x80), &field[1..]) } else { (0, &field[field.len() - 8..]) }; + Some(rest.iter().fold(first, |n, &b| (n << 8) | u64::from(b))) +} + +/// The `size` record of PAX extension data, the first one, as tar-rs takes it. +fn pax_size(data: &[u8]) -> Option { + for line in data.split(|&b| b == b'\n') { + if line.is_empty() { + break; + } + let space = line.iter().position(|&b| b == b' ')?; + let len: usize = std::str::from_utf8(&line[..space]).ok()?.parse().ok()?; + if line.len() + 1 != len { + return None; + } + let rest = &line[space + 1..]; + let eq = rest.iter().position(|&b| b == b'=')?; + if &rest[..eq] == b"size" { + return std::str::from_utf8(&rest[eq + 1..]).ok()?.parse().ok(); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn header(path: &str, kind: tar::EntryType, size: u64) -> tar::Header { + let mut h = tar::Header::new_ustar(); + h.set_path(path).unwrap(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(0o755); + h.set_uid(0); + h.set_gid(0); + h.set_mtime(1); + h.set_cksum(); + h + } + + /// What the servicebus-emulator layer has (#618): a directory whose size, + /// uid and gid are all NULs, its checksum right. + fn blank(h: &mut tar::Header) { + let b = h.as_mut_bytes(); + b[108..136].fill(0); + let sum = format!("{:06o}\0 ", checksum(b)); + b[148..156].copy_from_slice(sum.as_bytes()); + } + + fn archive(blank_dir: bool) -> Vec { + let mut b = tar::Builder::new(Vec::new()); + // A PAX header first, as in the layer, and a long name after it. + b.append_pax_extensions([("mtime", &b"1.5"[..])]).unwrap(); + let mut dir = header("app", tar::EntryType::Directory, 0); + if blank_dir { + blank(&mut dir); + } + b.append(&dir, io::empty()).unwrap(); + let long = format!("app/{}", "n".repeat(120)); + b.append_data(&mut header("x", tar::EntryType::Regular, 5), &long, &b"hello"[..]).unwrap(); + b.append(&header("app/b", tar::EntryType::Regular, 600), &[7u8; 600][..]).unwrap(); + b.into_inner().unwrap() + } + + fn entries(bytes: &[u8]) -> io::Result)>> { + let mut a = tar::Archive::new(GoNumbers::new(bytes)); + let mut out = Vec::new(); + for e in a.entries()? { + let mut e = e?; + let mut data = Vec::new(); + e.read_to_end(&mut data)?; + out.push((e.path()?.to_string_lossy().into_owned(), e.header().uid()?, data)); + } + Ok(out) + } + + #[test] + fn empty_numbers_read_as_zero_like_go() { + let bytes = archive(true); + let err = tar::Archive::new(&bytes[..]).entries().unwrap().find_map(Result::err).expect("tar-rs alone refuses it"); + assert!(err.to_string().contains("numeric field was not a number"), "{err}"); + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["app", &format!("app/{}", "n".repeat(120)), "app/b"]); + assert_eq!(got[0].1, 0, "an empty uid is root's"); + assert_eq!(got[1].2, b"hello"); + assert_eq!(got[2].2, [7u8; 600]); + } + + /// Passes `bytes` through, failing at the first byte that changed. + fn assert_unchanged(bytes: &[u8]) { + let mut out = Vec::new(); + GoNumbers::new(bytes).read_to_end(&mut out).unwrap(); + if let Some(i) = out.iter().zip(bytes).position(|(a, b)| a != b) { + panic!("byte {i} (block {}, offset {}) changed: {:?} -> {:?}", i / BLOCK, i % BLOCK, bytes[i] as char, out[i] as char); + } + assert_eq!(out.len(), bytes.len()); + } + + #[test] + fn a_complete_archive_passes_unchanged() { + let bytes = archive(false); + assert_unchanged(&bytes); + } + + #[test] + fn data_that_looks_like_a_header_is_left_alone() { + // A file holding a header with empty numbers, then a PAX size that + // makes the next entry's data longer than its header says. + let mut inner = header("fake", tar::EntryType::Directory, 0); + blank(&mut inner); + let mut b = tar::Builder::new(Vec::new()); + b.append(&header("tarball", tar::EntryType::Regular, 512), &inner.as_bytes()[..]).unwrap(); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + b.append(&header("sized", tar::EntryType::Regular, 0), &inner.as_bytes()[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + assert_unchanged(&bytes); + } + + #[test] + fn a_header_with_a_wrong_checksum_is_not_mended() { + let mut bytes = archive(true); + // The directory's header follows the PAX header and its data. + let dir = bytes.chunks(BLOCK).position(|b| b.starts_with(b"app\0")).unwrap() * BLOCK; + bytes[dir + 150] ^= 1; + assert_unchanged(&bytes); + assert!(entries(&bytes).is_err()); + } + + #[test] + fn numbers_and_pax_records_parse_as_in_tar_rs() { + assert_eq!(octal(b"0000755\0"), Some(0o755)); + assert_eq!(octal(b" 755 \0\0\0"), Some(0o755)); + assert_eq!(octal(b"\0\0\0\0"), None); + assert_eq!(number(&[0x80, 0, 0, 0, 0, 0, 1, 0]), Some(256)); + assert_eq!(number(&[0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1]), Some(513)); + assert_eq!(pax_size(b"20 path=a/b/c/d/e/f\n12 size=600\n"), Some(600)); + assert_eq!(pax_size(b"12 size=600\n11 size=10\n"), Some(600)); + assert_eq!(pax_size(b"28 mtime=1768240195.7895585\n\0\0\0"), None); + assert_eq!(pax_size(b"99 size=1\n"), None); + assert_eq!(pax_size(b"11 size=512"), None, "missing trailing newline"); + assert_eq!(pax_size(b"24 comment=a\n12 size=512\n"), None, "embedded newline breaks line length"); + assert_eq!(pax_size(b"11 foobar!\n12 size=512\n"), None, "record without '=' aborts parsing"); + } + + /// A reader that yields at most `step` bytes at a time, and `Interrupted` + /// every other call, as a decompressor or pipe may. + struct Trickle<'a> { + bytes: &'a [u8], + step: usize, + tick: usize, + } + + impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.tick += 1; + if self.tick.is_multiple_of(2) { + return Err(io::Error::from(io::ErrorKind::Interrupted)); + } + let n = buf.len().min(self.step).min(self.bytes.len()); + buf[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + Ok(n) + } + } + + #[test] + fn short_reads_and_interrupted_reads_stay_in_sync() { + let raw = archive(true); + let mut expected = Vec::new(); + GoNumbers::new(&raw[..]).read_to_end(&mut expected).unwrap(); + + for step in [1, 7, 73, 511, 512, 513] { + let mut r = GoNumbers::new(Trickle { bytes: &raw, step, tick: 0 }); + let mut got = Vec::new(); + let mut chunk = vec![0u8; step]; + loop { + match r.read(&mut chunk) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(&chunk[..n]), + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => panic!("step {step}: {e}"), + } + } + assert_eq!(got, expected, "step {step}"); + } + } + + #[test] + fn pax_size_tracks_tar_rs_across_global_longname_and_padding() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // 1. PAX `x` followed by GNU `L` longname: `x`'s size=512 still applies + // to the regular file after `L`, so its 512-byte payload (a blank-number + // header) is left untouched, while `real` after it is mended. + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + let long = format!("dir/{}", "l".repeat(120)); + let mut lhdr = tar::Header::new_gnu(); + lhdr.set_entry_type(tar::EntryType::GNULongName); + lhdr.set_size(long.len() as u64 + 1); + lhdr.set_cksum(); + let mut ldata = long.clone().into_bytes(); + ldata.push(0); + b.append(&lhdr, &ldata[..]).unwrap(); + let mut bytes = b.into_inner().unwrap(); + bytes.truncate(bytes.len() - 2 * BLOCK); + bytes.extend_from_slice(header("short", tar::EntryType::Regular, 0).as_bytes()); + let payload_at = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[payload_at..payload_at + BLOCK], fake.as_bytes(), "file payload after PAX x + GNU L must not be touched"); + let got = entries(&bytes).unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].0, long); + assert_eq!(got[0].2, fake.as_bytes()); + assert_eq!(got[1].0, "after"); + + // 2. PAX `x` (size=512) followed by PAX global `g` (size=0): tar-rs + // yields `g` and drops `x`'s pax_extensions, so the next entry + // ("zero", header size=0) has 0 bytes of data, and `real` right + // after it is a header that must be mended. + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + let mut bytes = b.into_inner().unwrap(); + bytes.truncate(bytes.len() - 2 * BLOCK); + let mut g = header("pax_global", tar::EntryType::XGlobalHeader, 0); + g.set_cksum(); + bytes.extend_from_slice(g.as_bytes()); + bytes.extend_from_slice(header("zero", tar::EntryType::Regular, 0).as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["pax_global", "zero", "after"]); + + // 3. PAX `x` whose unpadded size is 11 ("11 foo=bar\n"), with + // "12 size=512\n" hidden in the 512-byte block padding after byte 11: + // tar-rs reads only 11 bytes of `x`, so "zero" has size 0 and `real` + // right after it is a header that must be mended. + let mut x = tar::Header::new_ustar(); + x.set_entry_type(tar::EntryType::XHeader); + x.set_size(11); + x.set_cksum(); + let mut xblock = [0u8; BLOCK]; + xblock[..23].copy_from_slice(b"11 foo=bar\n12 size=512\n"); + let mut bytes = Vec::new(); + bytes.extend_from_slice(x.as_bytes()); + bytes.extend_from_slice(&xblock); + bytes.extend_from_slice(header("zero", tar::EntryType::Regular, 0).as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["zero", "after"]); + } + + #[test] + fn base256_size_and_symlink_with_nonzero_size_keep_payload_untouched() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // 1. Regular file with GNU base-256 size = 512 holding `fake` as data. + let mut h256 = header("big", tar::EntryType::Regular, 0); + h256.as_mut_bytes()[124..136].copy_from_slice(&[0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]); + h256.set_cksum(); + + // 2. Symlink (`2`) with non-zero size = 512: tar-rs advances `self.next` + // past the 512-byte data block (`fake`), so GoNumbers must treat it + // as data and not mutate it, then mend `real` after it. + let mut sym = header("sym", tar::EntryType::Symlink, 512); + sym.set_link_name("target").unwrap(); + sym.set_cksum(); + + // 3. Character device (`3`) with empty mode, uid, gid, size, mtime, + // devmajor and devminor. + let mut chr = header("null", tar::EntryType::Char, 0); + { + let b = chr.as_mut_bytes(); + b[100..148].fill(0); + b[329..345].fill(0); + let sum = format!("{:06o}\0 ", checksum(b)); + b[148..156].copy_from_slice(sum.as_bytes()); + } + + let mut bytes = Vec::new(); + bytes.extend_from_slice(h256.as_bytes()); + let p1 = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(sym.as_bytes()); + let p2 = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(chr.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[p1..p1 + BLOCK], fake.as_bytes(), "base-256 file payload must not be mutated"); + assert_eq!(&out[p2..p2 + BLOCK], fake.as_bytes(), "symlink skipped data block must not be mutated"); + + let mut a = tar::Archive::new(GoNumbers::new(&bytes[..])); + let mut names = Vec::new(); + for e in a.entries().unwrap() { + let e = e.unwrap(); + if e.header().entry_type().is_character_special() { + assert_eq!(e.header().device_major().unwrap(), Some(0)); + assert_eq!(e.header().device_minor().unwrap(), Some(0)); + } + names.push(e.path().unwrap().to_string_lossy().into_owned()); + } + assert_eq!(names, ["big", "sym", "null", "after"]); + } + + #[test] + fn gnu_sparse_extended_headers_and_data_stay_in_sync() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // GNU sparse header ('S') with isextended = 1 (offset 482), two + // GnuExtSparseHeader blocks (first with offset 504 = 1, second with 0), + // and 1 block (512 bytes) of sparse data holding `fake`. + let mut sp = tar::Header::new_gnu(); + sp.set_path("sparse.bin").unwrap(); + sp.set_entry_type(tar::EntryType::GNUSparse); + sp.set_mode(0o644); + sp.set_uid(0); + sp.set_gid(0); + sp.set_mtime(1); + sp.set_size(512); + { + let gnu = sp.as_gnu_mut().unwrap(); + gnu.sparse[0].set_offset(0); + gnu.sparse[0].set_length(512); + gnu.set_is_extended(true); + gnu.set_real_size(512); + } + sp.set_cksum(); + + let mut ext1 = [0u8; BLOCK]; + ext1[504] = 1; + let ext2 = [0u8; BLOCK]; + + let mut bytes = Vec::new(); + bytes.extend_from_slice(sp.as_bytes()); + bytes.extend_from_slice(&ext1); + bytes.extend_from_slice(&ext2); + let payload_at = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[payload_at..payload_at + BLOCK], fake.as_bytes(), "sparse file payload must not be mutated"); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].0, "sparse.bin"); + assert_eq!(got[0].2, fake.as_bytes()); + assert_eq!(got[1].0, "after"); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 971e38eec..a0f937ece 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 +### #673 Layers: an empty number in a tar header is 0, as in Docker, so servicebus-emulator unpacks (unreleased) +- Fixes: #618 Layers: an empty number in a tar header is 0, as in Docker, so servicebus-emulator unpacks +- Caused: none known +- Caused by: - +- Check: `import-empty-numbers` + ### Engine: `seccomp=unconfined` warns that Kiri's host boundary stays in place (unreleased) - Fixes: #516 Apache Iggy can't start: the host-boundary filter blocks io_uring, and `seccomp=unconfined` / `--privileged` can't lift it - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index ac057e2f2..f17654ab7 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1648,7 +1648,10 @@ t import-bad-change "not a valid change command" bash -c "$D export ren2 | $D im # A directory keeps its time from the layer, after files are unpacked into # it too, as on Docker (#676). t import-dir-mtime "1000000000" bash -c "$D export ren2 | python3 -c 'import io,sys,tarfile; s=tarfile.open(fileobj=sys.stdin.buffer,mode=\"r|*\"); o=tarfile.open(fileobj=sys.stdout.buffer,mode=\"w|\"); [o.addfile(m,s.extractfile(m) if m.isreg() else None) for m in s]; d=tarfile.TarInfo(\"dated\"); d.type,d.mode,d.mtime=tarfile.DIRTYPE,0o755,1000000000; o.addfile(d); f=tarfile.TarInfo(\"dated/f\"); f.mtime=1000000000; o.addfile(f,io.BytesIO()); o.close()' | $D import - kiri-test/imported:7 >/dev/null && $D run --rm kiri-test/imported:7 stat -c %Y /dated" -$D rmi kiri-test/imported:1 kiri-test/imported:2 kiri-test/imported:3 kiri-test/imported:7 >/dev/null 2>&1 +# A layer whose directory has empty size, uid and gid fields: Docker reads an +# empty number as 0 (#618, mcr.microsoft.com/azure-messaging/servicebus-emulator). +t import-empty-numbers "ok 0:0" bash -c "$D export ren2 | python3 \"$(dirname "$0")/lib/tar-empty-numbers.py\" | $D import - kiri-test/imported:6 >/dev/null && $D run --rm kiri-test/imported:6 sh -c 'cat /empty-numbers/ok; stat -c %u:%g /empty-numbers' | tr '\\n' ' '" +$D rmi kiri-test/imported:1 kiri-test/imported:2 kiri-test/imported:3 kiri-test/imported:6 kiri-test/imported:7 >/dev/null 2>&1 t commit "sha256:" $D commit -c 'CMD ["cat","/added"]' -c 'ENV KIRI=1' ren2 kiri-test/committed:1 t commit-runs "hi" $D run --rm kiri-test/committed:1 t commit-env "KIRI=1" $D run --rm kiri-test/committed:1 env diff --git a/tests/lib/tar-empty-numbers.py b/tests/lib/tar-empty-numbers.py new file mode 100755 index 000000000..2dee6d2f9 --- /dev/null +++ b/tests/lib/tar-empty-numbers.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Copies the tar archive on stdin to stdout with a directory added, +/empty-numbers, whose size, uid and gid fields are all NUL bytes, its +checksum right, and a file in it, /empty-numbers/ok, holding "ok". Some image +builders write directories so (mcr.microsoft.com/azure-messaging/ +servicebus-emulator): Docker reads an empty number as 0 (#618). + + docker export c | python3 tests/lib/tar-empty-numbers.py | docker import - img +""" +import io +import sys +import tarfile + +src = tarfile.open(fileobj=sys.stdin.buffer, mode="r|*") +buf = io.BytesIO() +dst = tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) +for m in src: + dst.addfile(m, src.extractfile(m) if m.isreg() else None) +at = dst.offset +d = tarfile.TarInfo("empty-numbers") +d.type, d.mode, d.mtime = tarfile.DIRTYPE, 0o755, 1 +dst.addfile(d) +f = tarfile.TarInfo("empty-numbers/ok") +f.size, f.mode, f.mtime = 3, 0o644, 1 +dst.addfile(f, io.BytesIO(b"ok\n")) +dst.close() + +out = bytearray(buf.getvalue()) +# Its header, after a PAX header if tarfile wrote one. +at = next(i for i in range(at, len(out), 512) if out[i:i + 100].rstrip(b"\0") in (b"empty-numbers", b"empty-numbers/")) +h = out[at:at + 512] +h[108:136] = bytes(28) # uid, gid and size +h[148:156] = b" " * 8 +h[148:156] = b"%06o\0 " % sum(h) +out[at:at + 512] = h +sys.stdout.buffer.write(out) diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 1c014f1f3..852932413 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -87,6 +87,10 @@ t failed-start-frees-root "gone mounts=0" "docker rm -f kiri-badsysctl >/dev/nul t failed-start-no-dns "none" "docker network create kiri-dnsfail >/dev/null 2>&1; docker rm -f kiri-dnsbad >/dev/null 2>&1; docker run -d --name kiri-dnsbad --network kiri-dnsfail --sysctl net.ipv4.kiri_no_such_key=1 alpine sleep 60 >/dev/null 2>&1; docker run --rm --network kiri-dnsfail alpine sh -c 'nslookup kiri-dnsbad 2>&1 | grep -qE \"^Address: [0-9.]+\$\" && echo answered || echo none'; docker rm -f kiri-dnsbad >/dev/null 2>&1; docker network rm kiri-dnsfail >/dev/null" t cp-stopped-unmounts "after=0" "id=\$(docker create alpine true); docker cp /etc/hostname \$id:/f >/dev/null; for i in \$(seq 20); do [ \$($mounts) = 0 ] && break; sleep 0.1; done; echo after=\$($mounts); docker rm \$id >/dev/null" t commit-renamed-dir "kept" "docker rm -f kiri-rename >/dev/null 2>&1; docker run --name kiri-rename alpine mv /etc/apk /etc/apk2; docker commit kiri-rename kiri-rename-test >/dev/null; docker rm -f kiri-rename >/dev/null; docker run --rm kiri-rename-test sh -c 'test -f /etc/apk2/repositories && echo kept'; docker rmi kiri-rename-test >/dev/null" +# A layer whose directory has empty size, uid and gid fields: Docker reads an +# empty number as 0 (#618, mcr.microsoft.com/azure-messaging/servicebus-emulator). +$D cp "$(dirname "$0")/lib/tar-empty-numbers.py" "$N":/tar-empty-numbers.py >/dev/null +t import-empty-numbers "ok 0:0" "id=\$(docker create alpine true); docker export \$id | python3 /tar-empty-numbers.py | docker import - kiri-test/empty-numbers:1 >/dev/null && docker run --rm kiri-test/empty-numbers:1 sh -c 'cat /empty-numbers/ok; stat -c %u:%g /empty-numbers' | tr '\\n' ' '; docker rm \$id >/dev/null; docker rmi kiri-test/empty-numbers:1 >/dev/null 2>&1" # A container and an exec each lead their own session, so killpg from inside # never reaches the daemon (#191). t session-own "SID=1" "docker run --rm alpine sh -c 'echo SID=\$(cut -d\" \" -f6 /proc/1/stat)'" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index b0fc23763..345865dfd 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -217,3 +217,4 @@ seccomp-unconfined-colon-warns #516 --security-opt seccomp:unconfined gave no wa seccomp-unconfined-api-warnings #516 POST /containers/create returned empty Warnings when seccomp=unconfined was passed seccomp-default-no-warning #516 a default container without seccomp=unconfined must return empty Warnings seccomp-unconfined-io-uring-blocked #516 io_uring_setup must stay blocked with EPERM even under seccomp=unconfined +import-empty-numbers #618 a layer whose header left size, uid or gid empty did not unpack: "numeric field was not a number" (servicebus-emulator) From a7c2a1e375474b197f57cc6adeffffa420ca2057 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 14:30:21 +0100 Subject: [PATCH 007/157] Copy: keep the archive's owners on PUT /containers/{id}/archive, as Docker does (#594) Co-authored-by: Randy Fay --- crates/kiri-init/src/linux/copy.rs | 235 +++++++++++++++++++++++++---- crates/kiri-proto/src/lib.rs | 6 +- crates/kiri/src/daemon/api.rs | 12 +- docs/fix-registry.md | 6 + tests/e2e.sh | 19 ++- tests/linux-host.sh | 6 + tests/regressions.tsv | 3 + 7 files changed, 251 insertions(+), 36 deletions(-) diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index f96b688f8..dcd1a9edd 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -272,41 +272,21 @@ fn ask(chan: &OwnedFd, kind: char, spec: &CopySpec<'_>) -> io::Result<()> { /// Unpacks the archive that follows into `spec.path`, a directory. fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { - let dest = std::path::Path::new(spec.path); + let (path, user) = if spec.flags & copy_flags::KEEP_OWNERS != 0 { + spec.path.split_once('\0').unwrap_or((spec.path, "")) + } else { + (spec.path, "") + }; + let dest = std::path::Path::new(path); match fs::metadata(dest) { Ok(m) if m.is_dir() => {} - Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {}", spec.path))), - Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id))), + Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {path}"))), + Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {path} in container {}", spec.id))), } + let owner = if user.is_empty() { None } else { Some(resolve_copy_user_in(std::path::Path::new("/"), user)?) }; let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) }; let mut reader = BufReader::with_capacity(256 * 1024, source); - { - let mut archive = tar::Archive::new(&mut reader); - archive.set_preserve_permissions(true); - archive.set_preserve_mtime(true); - archive.set_preserve_ownerships(spec.flags & copy_flags::KEEP_OWNERS != 0); - archive.set_unpack_xattrs(false); - archive.set_overwrite(true); - for entry in archive.entries()? { - let mut entry = entry?; - if spec.flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 { - let target = dest.join(entry.path()?); - if let Ok(m) = fs::symlink_metadata(&target) { - if m.is_dir() != entry.header().entry_type().is_dir() { - return Err(io::Error::new( - io::ErrorKind::AlreadyExists, - format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }), - )); - } - } - } - let path = entry.path()?.into_owned(); - // `docker cp` and the classic build's context keep a time of 0. - if entry.unpack_in(dest)? { - super::layers::keep_zero_time(dest, &path, entry.header())?; - } - } - } + unpack_in(&mut reader, dest, spec.flags, owner)?; // The archive's trailing padding: read it so the host's writes complete. io::copy(&mut reader, &mut io::sink())?; drop(reader); @@ -315,6 +295,115 @@ fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { conn.write_all(&out) } +/// Moby's `applyTarCopyUserOptions` (`getUIDGID`): resolves a container's +/// non-empty `Config.User` (`user[:group]`) against its `/etc/passwd` and +/// `/etc/group` when `copyUIDGID` (`docker cp -a`) is set. +fn resolve_copy_user_in(root: &std::path::Path, user: &str) -> io::Result<(libc::uid_t, libc::gid_t)> { + let (u, g) = user.split_once(':').unwrap_or((user, "")); + let (mut uid, mut gid) = (0, 0); + if !u.is_empty() { + let passwd = fs::read_to_string(root.join("etc/passwd")).unwrap_or_default(); + if let Ok(id) = u.parse::() + && id <= i32::MAX as u32 + { + uid = id; + gid = passwd + .lines() + .find_map(|l| { + let mut f = l.split(':'); + (f.nth(2)?.parse::().ok()? == id).then(|| f.next()?.parse::().ok()).flatten() + }) + .unwrap_or(0); + } else { + (uid, gid) = passwd + .lines() + .find_map(|l| { + let mut f = l.split(':'); + if f.next()? != u { + return None; + } + Some((f.nth(1)?.parse::().ok()?, f.next()?.parse::().ok()?)) + }) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up user {u:?} in container")))?; + } + } + if !g.is_empty() { + if let Ok(id) = g.parse::() + && id <= i32::MAX as u32 + { + gid = id; + } else { + let group = fs::read_to_string(root.join("etc/group")).unwrap_or_default(); + gid = group + .lines() + .find_map(|l| { + let mut f = l.split(':'); + if f.next()? != g { + return None; + } + f.nth(1)?.parse::().ok() + }) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up group {g:?} in container")))?; + } + } + Ok((uid, gid)) +} + +fn unpack_in(reader: impl Read, dest: &std::path::Path, flags: u32, owner: Option<(libc::uid_t, libc::gid_t)>) -> io::Result<()> { + let mut archive = tar::Archive::new(reader); + archive.set_preserve_permissions(true); + archive.set_preserve_mtime(true); + // Moby's `defaultTarCopyOptions` preserves the archive's header UID/GID + // (`ChownOpts == nil`); when `copyUIDGID` (`docker cp -a`) is set on a + // container with a non-empty `Config.User`, `applyTarCopyUserOptions` + // sets `ChownOpts` (`owner`) to chown every unpacked entry to that user. + archive.set_preserve_ownerships(owner.is_none()); + archive.set_unpack_xattrs(false); + archive.set_overwrite(true); + for entry in archive.entries()? { + let mut entry = entry?; + if flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 { + let target = dest.join(entry.path()?); + if let Ok(m) = fs::symlink_metadata(&target) + && m.is_dir() != entry.header().entry_type().is_dir() + { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }), + )); + } + } + let path = entry.path()?.into_owned(); + // `docker cp` and the classic build's context keep a time of 0. + if entry.unpack_in(dest)? { + if let Some((uid, gid)) = owner + && !entry.header().entry_type().is_pax_global_extensions() + { + let mut file_dst = dest.to_path_buf(); + for part in path.components() { + if let std::path::Component::Normal(p) = part { + file_dst.push(p); + } + } + if file_dst != dest { + let c = sys::cstr(&file_dst)?; + // SAFETY: valid NUL-terminated path inside the container chroot. + sys::check(unsafe { libc::lchown(c.as_ptr(), uid, gid) } as _, "lchown")?; + if !fs::symlink_metadata(&file_dst)?.file_type().is_symlink() + && let Ok(mode) = entry.header().mode() + && mode & 0o6000 != 0 + { + // SAFETY: valid NUL-terminated non-symlink path. + sys::check(unsafe { libc::chmod(c.as_ptr(), (mode & 0o7777) as libc::mode_t) } as _, "chmod")?; + } + } + } + super::layers::keep_zero_time(dest, &path, entry.header())?; + } + } + Ok(()) +} + /// A `copy_flags::CHUNKED` archive: chunks of `len: u32 LE | bytes`, read /// as one stream that ends at the empty chunk, with the connection still /// open for the answer. @@ -640,4 +729,90 @@ mod tests { let err = Chunks::new(&wire[..]).read_to_end(&mut Vec::new()).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); } + + #[test] + fn unpack_in_keeps_owners_and_does_not_chown_symlink_targets() { + // SAFETY: a plain getter. + if unsafe { libc::geteuid() } != 0 { + eprintln!("skipped: needs root to keep owners"); + return; + } + let dest = std::env::temp_dir().join(format!("kiri-copy-owners-{}", std::process::id())); + let _ = fs::remove_dir_all(&dest); + fs::create_dir_all(&dest).unwrap(); + fs::write(dest.join("target"), b"stay").unwrap(); + std::os::unix::fs::symlink("target", dest.join("replaced")).unwrap(); + + let mut b = tar::Builder::new(Vec::new()); + let h = |kind: tar::EntryType, size: u64, mode: u32| { + let mut h = tar::Header::new_gnu(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(mode); + h.set_uid(1234); + h.set_gid(1235); + h.set_mtime(1_700_000_000); + h.set_cksum(); + h + }; + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750), "dir", &[][..]).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 3, 0o600), "dir/owned.pem", &b"key"[..]).unwrap(); + b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777), "link", "target").unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 3, 0o640), "replaced", &b"new"[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + + unpack_in(&bytes[..], &dest, 0, None).unwrap(); + + let meta = |p: &str| fs::symlink_metadata(dest.join(p)).unwrap(); + let dir = meta("dir"); + assert_eq!((dir.uid(), dir.gid(), dir.mode() & 0o777), (1234, 1235, 0o750)); + let pem = meta("dir/owned.pem"); + assert_eq!((pem.uid(), pem.gid(), pem.mode() & 0o777), (1234, 1235, 0o600)); + assert_eq!(fs::read(dest.join("dir/owned.pem")).unwrap(), b"key"); + let link = meta("link"); + assert!(link.file_type().is_symlink()); + assert_eq!((link.uid(), link.gid()), (1234, 1235)); + let replaced = meta("replaced"); + assert!(replaced.file_type().is_file()); + assert_eq!((replaced.uid(), replaced.gid(), replaced.mode() & 0o777), (1234, 1235, 0o640)); + assert_eq!(fs::read(dest.join("replaced")).unwrap(), b"new"); + let target = meta("target"); + assert_eq!((target.uid(), target.gid()), (0, 0)); + assert_eq!(fs::read(dest.join("target")).unwrap(), b"stay"); + + unpack_in(&bytes[..], &dest, 0, Some((2375, 2376))).unwrap(); + assert_eq!((meta("dir").uid(), meta("dir").gid()), (2375, 2376)); + assert_eq!((meta("dir/owned.pem").uid(), meta("dir/owned.pem").gid(), meta("dir/owned.pem").mode() & 0o777), (2375, 2376, 0o600)); + assert_eq!((meta("link").uid(), meta("link").gid()), (2375, 2376)); + assert_eq!((meta("target").uid(), meta("target").gid()), (0, 0)); + + let _ = fs::remove_dir_all(&dest); + } + + #[test] + fn resolve_copy_user_matches_moby_get_uid_gid() { + let root = std::env::temp_dir().join(format!("kiri-copy-user-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(root.join("etc")).unwrap(); + fs::write(root.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\ntestuser:x:2375:2376::/home/testuser:/bin/sh\n").unwrap(); + fs::write(root.join("etc/group"), "root:x:0:\ntestgroup:x:2376:\n").unwrap(); + + for (spec, want) in [ + ("7777:", (7777, 0)), + (":7777", (0, 7777)), + ("2375", (2375, 2376)), + ("7777", (7777, 0)), + ("2375:2376", (2375, 2376)), + ("testuser:testgroup", (2375, 2376)), + ("testuser", (2375, 2376)), + ("testuser:7777", (2375, 7777)), + ("7777:testgroup", (7777, 2376)), + ] { + assert_eq!(resolve_copy_user_in(&root, spec).unwrap(), want, "{spec}"); + } + assert!(resolve_copy_user_in(&root, "nosuchuser").is_err()); + assert!(resolve_copy_user_in(&root, "testuser:nosuchgroup").is_err()); + + let _ = fs::remove_dir_all(&root); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index c7edfcec6..45ea7fbb7 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -260,7 +260,11 @@ pub mod copy_op { } pub mod copy_flags { - /// Keep the archive's owners (`docker cp -a`); otherwise root owns everything. + /// `docker cp -a` (`copyUIDGID`): chown unpacked entries to the + /// container's `Config.User` when one is set (Moby's + /// `applyTarCopyUserOptions`), sent as `"\0"` in + /// `CopySpec::path`. Without `-a`, or when `Config.User` is empty, the + /// archive's header UID/GID are kept. pub const KEEP_OWNERS: u32 = 1; /// Refuse to replace a directory with a file or the reverse. pub const NO_OVERWRITE_DIR_NON_DIR: u32 = 2; diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index a4ef93d7f..7bc9c58ac 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -3464,11 +3464,15 @@ fn upload_reader<'a>(head: Vec, rest: impl io::Read + 'a) -> Result) -> io::Result { use kiri_proto::copy_flags; - let path = req.query("path").unwrap_or("/"); + let raw_path = req.query("path").unwrap_or("/"); let mut flags = copy_flags::CHUNKED; - if req.flag("copyUIDGID") { + let path = if req.flag("copyUIDGID") { flags |= copy_flags::KEEP_OWNERS; - } + let user = engine.with(id, |c| c.spec.user.clone()).unwrap_or_default(); + if user.is_empty() { raw_path.to_owned() } else { format!("{raw_path}\0{user}") } + } else { + raw_path.to_owned() + }; if req.flag("noOverwriteDirNonDir") { flags |= copy_flags::NO_OVERWRITE_DIR_NON_DIR; } @@ -3485,7 +3489,7 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: return Ok(Next::Close); } }; - let stream = match engine.copy(id, kiri_proto::copy_op::IN, path, flags) { + let stream = match engine.copy(id, kiri_proto::copy_op::IN, &path, flags) { Ok(s) => s, Err(e) => { error_closing(w, e)?; diff --git a/docs/fix-registry.md b/docs/fix-registry.md index a0f937ece..9902450db 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 +### #595 Copy: keep the archive's owners on PUT /containers/{id}/archive, and chown to Config.User on copyUIDGID (unreleased) +- Fixes: #594 PUT /containers/{id}/archive (docker cp) gives files to root; Docker keeps the archive's owners +- Caused: none known +- Caused by: - +- Check: `cp-in-keeps-owner`, `cp-in-keeps-dir-and-symlink-owner`, `cp-in-copy-uidgid` + ### #673 Layers: an empty number in a tar header is 0, as in Docker, so servicebus-emulator unpacks (unreleased) - Fixes: #618 Layers: an empty number in a tar header is 0, as in Docker, so servicebus-emulator unpacks - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index f17654ab7..0b19aaa29 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1245,7 +1245,24 @@ $D run -d --name cpc alpine sleep 120 >/dev/null t cp-in-file "one" bash -c "$D cp $CPD/a.txt cpc:/tmp/ && $D exec cpc cat /tmp/a.txt" t cp-in-dir "two" bash -c "$D cp $CPD/dir cpc:/tmp/ && $D exec cpc cat /tmp/dir/sub/b.txt" t cp-in-rename "one" bash -c "$D cp $CPD/a.txt cpc:/tmp/renamed.txt && $D exec cpc cat /tmp/renamed.txt" -t cp-in-root-owner "0 0" bash -c "$D exec cpc stat -c '%u %g' /tmp/a.txt" +# The archive's owners are kept, as Docker keeps them without -a (#594): DDEV +# puts its mkcert key (mode 0600) in a container this way for the web user, +# and a symlink's owner is set on the link itself, never on its target. +OWNED='import io,sys,tarfile +b=io.BytesIO(); t=tarfile.open(fileobj=b,mode="w"); f=tarfile.TarInfo("owned.pem"); f.size=3; f.mode=0o600; f.uid=1234; f.gid=1235 +t.addfile(f,io.BytesIO(b"key")); t.close(); sys.stdout.buffer.write(b.getvalue())' +t cp-in-keeps-owner "1234 1235 600 key" bash -c "python3 -c '$OWNED' | $D cp - cpc:/tmp/ && echo \$($D exec cpc stat -c '%u %g %a' /tmp/owned.pem) \$($D exec -u 1234 cpc cat /tmp/owned.pem)" +OWNED_TREE='import io,sys,tarfile +b=io.BytesIO(); t=tarfile.open(fileobj=b,mode="w") +d=tarfile.TarInfo("owned-dir"); d.type=tarfile.DIRTYPE; d.mode=0o750; d.uid=1234; d.gid=1235; t.addfile(d) +s=tarfile.TarInfo("owned-link"); s.type=tarfile.SYMTYPE; s.linkname="/etc/hostname"; s.uid=1234; s.gid=1235; t.addfile(s) +f=tarfile.TarInfo("owned-over"); f.size=3; f.mode=0o640; f.uid=1234; f.gid=1235; t.addfile(f,io.BytesIO(b"new")) +t.close(); sys.stdout.buffer.write(b.getvalue())' +t cp-in-keeps-dir-and-symlink-owner "dir=1234:1235:750 link=1234:1235 over=1234:1235:regular file targets=0:0:0:0" bash -c "$D exec cpc ln -sf /etc/alpine-release /tmp/owned-over && python3 -c '$OWNED_TREE' | curl -s --unix-socket $(printf %q "$SOCK") -X PUT --data-binary @- 'http://d/v1.47/containers/cpc/archive?path=/tmp' && $D exec cpc sh -c 'echo \"dir=\$(stat -c %u:%g:%a /tmp/owned-dir) link=\$(stat -c %u:%g /tmp/owned-link) over=\$(stat -c %u:%g:%F /tmp/owned-over) targets=\$(stat -c %u:%g /etc/hostname):\$(stat -c %u:%g /etc/alpine-release)\"'" +# With -a (copyUIDGID), Moby's applyTarCopyUserOptions chowns unpacked entries +# to the container's Config.User when set, while keeping tar header owners +# without -a or when Config.User is empty. +t cp-in-copy-uidgid "no-a=1234:1235 with-a=1000:1000 default-a=1234:1235" bash -c "$D run -d --name cpu -u 1000:1000 alpine sleep 120 >/dev/null && python3 -c '$OWNED' | $D cp - cpu:/tmp/ && $D cp -a $CPD/a.txt cpu:/tmp/a.txt && python3 -c '$OWNED' | $D cp -a - cpc:/tmp/ && echo \"no-a=\$($D exec cpu stat -c %u:%g /tmp/owned.pem) with-a=\$($D exec cpu stat -c %u:%g /tmp/a.txt) default-a=\$($D exec cpc stat -c %u:%g /tmp/owned.pem)\"; $D rm -f cpu >/dev/null 2>&1" # A time of 0 stays 0, as Docker unpacks it (the tar crate would make it 1). t cp-in-zero-time "time 0" bash -c "echo z > $CPD/z && TZ=UTC touch -t 197001010000.00 $CPD/z && tar -C $CPD -cf - z | $D cp - cpc:/tmp/ && echo time \$($D exec cpc stat -c %Y /tmp/z)" t cp-out-file "fromctr" bash -c "$D exec cpc sh -c 'echo fromctr > /etc/motd2' && $D cp cpc:/etc/motd2 $CPD/ && cat $CPD/motd2" diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 852932413..340651d89 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -96,6 +96,12 @@ t import-empty-numbers "ok 0:0" "id=\$(docker create alpine true); docker export t session-own "SID=1" "docker run --rm alpine sh -c 'echo SID=\$(cut -d\" \" -f6 /proc/1/stat)'" t exec-session-own "own" "docker exec web sh -c 's=\$(cut -d\" \" -f6 /proc/\$\$/stat); [ \"\$s\" = \"\$\$\" ] && echo own || echo \"session \$s\"'" t cp "copied" "echo copied > /tmp/x && docker cp /tmp/x web:/tmp/x && docker exec web cat /tmp/x" +# PUT /containers/{id}/archive and docker cp keep the archive's owners without +# copyUIDGID (-a), as Docker does (#594), and lchown symlinks without touching +# their targets; with -a (copyUIDGID), entries are chowned to Config.User when set. +t cp-in-keeps-owner "1234 1235 600 key" "rm -rf /tmp/cpo && mkdir -p /tmp/cpo && printf key > /tmp/cpo/owned.pem && chmod 600 /tmp/cpo/owned.pem && chown 1234:1235 /tmp/cpo/owned.pem && tar -C /tmp/cpo -cf - owned.pem | docker cp - web:/tmp/ && echo \$(docker exec web stat -c '%u %g %a' /tmp/owned.pem) \$(docker exec -u 1234 web cat /tmp/owned.pem)" +t cp-in-keeps-dir-and-symlink-owner "dir=1234:1235:750 link=1234:1235 over=1234:1235:regular file targets=0:0:0:0" "mkdir -p /tmp/cpo/owned-dir && chmod 750 /tmp/cpo/owned-dir && ln -sf /etc/hostname /tmp/cpo/owned-link && printf new > /tmp/cpo/owned-over && chmod 640 /tmp/cpo/owned-over && chown -Rh 1234:1235 /tmp/cpo && docker exec web ln -sf /etc/alpine-release /tmp/owned-over && tar -C /tmp/cpo -cf - owned-dir owned-link owned-over | curl -s --unix-socket /root/.kiri/run/docker.sock -X PUT --data-binary @- 'http://d/v1.47/containers/web/archive?path=/tmp' && docker exec web sh -c 'echo \"dir=\$(stat -c %u:%g:%a /tmp/owned-dir) link=\$(stat -c %u:%g /tmp/owned-link) over=\$(stat -c %u:%g:%F /tmp/owned-over) targets=\$(stat -c %u:%g /etc/hostname):\$(stat -c %u:%g /etc/alpine-release)\"'" +t cp-in-copy-uidgid "no-a=1234:1235 with-a=1000:1000 default-a=1234:1235" "docker rm -f cpu >/dev/null 2>&1; docker run -d --name cpu -u 1000:1000 alpine sleep 120 >/dev/null && tar -C /tmp/cpo -cf - owned.pem | docker cp - cpu:/tmp/ && docker cp -a /tmp/x cpu:/tmp/x && tar -C /tmp/cpo -cf - owned.pem | docker cp -a - web:/tmp/ && echo \"no-a=\$(docker exec cpu stat -c %u:%g /tmp/owned.pem) with-a=\$(docker exec cpu stat -c %u:%g /tmp/x) default-a=\$(docker exec web stat -c %u:%g /tmp/owned.pem)\"; rm -rf /tmp/cpo; docker rm -f cpu >/dev/null 2>&1" # What Testcontainers needs (#222, #121); see tests/testcontainers-api.py. for c in version cmd keepalive close follow follow-created timestamps; do t "testcontainers-$c" "ok $c" "for i in \$(seq 60); do command -v python3 >/dev/null && break; sleep 1; done; python3 /testcontainers-api.py /root/.kiri/run/docker.sock $c" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 345865dfd..f45c79d54 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -218,3 +218,6 @@ seccomp-unconfined-api-warnings #516 POST /containers/create returned empty Warn seccomp-default-no-warning #516 a default container without seccomp=unconfined must return empty Warnings seccomp-unconfined-io-uring-blocked #516 io_uring_setup must stay blocked with EPERM even under seccomp=unconfined import-empty-numbers #618 a layer whose header left size, uid or gid empty did not unpack: "numeric field was not a number" (servicebus-emulator) +cp-in-keeps-owner #594 PUT /containers/{id}/archive and docker cp without -a gave files to root instead of keeping the archive's owners, so a mode-0600 file uploaded for a non-root user (DDEV's mkcert CA key) was unreadable to that user +cp-in-keeps-dir-and-symlink-owner #594 PUT /containers/{id}/archive without copyUIDGID must keep directory and symlink owners from the tar headers without chowning symlink targets +cp-in-copy-uidgid #594 PUT /containers/{id}/archive with copyUIDGID (docker cp -a) must chown unpacked entries to the container's Config.User when set while keeping tar header owners without -a or when Config.User is empty From fdfb4b9e578bee89b9d2fba683469533e74cca2e Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 14:59:42 +0100 Subject: [PATCH 008/157] Linux: run on a hybrid cgroup tree on stock WSL 2 and older hosts (#277) --- crates/kiri-init/src/linux/agent.rs | 7 +- crates/kiri-init/src/linux/cgroup.rs | 99 +++++++- crates/kiri-init/src/linux/container.rs | 7 +- crates/kiri-init/src/linux/mod.rs | 289 +++++++++++++++++++++--- crates/kiri-init/src/linux/sys.rs | 12 + docs/fix-registry.md | 6 + tests/linux-host.sh | 80 +++++++ tests/regressions.tsv | 1 + 8 files changed, 464 insertions(+), 37 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index e329e1a8c..cf0e4032c 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -1546,7 +1546,12 @@ mod running_tests { let mut procs = HashMap::new(); let mut dns = super::super::dns::Dns::default(); let mut failed = HashMap::new(); - let paths = super::Paths { layers: "/l".into(), containers: "/c".into(), cgroup: "/g".into() }; + let paths = super::Paths { + layers: "/l".into(), + containers: "/c".into(), + cgroup: "/g".into(), + cgroup_root: "/sys/fs/cgroup".into(), + }; procs.insert(300, new_proc(Process::starting_for_test("c1", 300, r.into(), None), 0, 0)); assert_eq!(super::running_rootfs(&procs, &paths, "c1"), Some("/c/c1/rootfs".into()), "not /proc/300/root, which is the agent's own root"); assert_eq!(super::running_rootfs(&procs, &paths, "nope"), None); diff --git a/crates/kiri-init/src/linux/cgroup.rs b/crates/kiri-init/src/linux/cgroup.rs index bf7c4fdbe..ab95013f3 100644 --- a/crates/kiri-init/src/linux/cgroup.rs +++ b/crates/kiri-init/src/linux/cgroup.rs @@ -2,24 +2,51 @@ //! `docker update`), freezing (`docker pause`), and what `docker stats` and //! `docker top` read. -use std::fs; -use std::io; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; use std::path::Path; use kiri_proto::{ContainerStats, Limits}; use super::sys; +/// Writes a single cgroup v2 control file without `O_CREAT`: on kernfs, +/// `O_CREAT` against a missing control file fails with `EACCES` instead of +/// `ENOENT`. When a controller is held by cgroup v1 (stock WSL 2 hybrid +/// tree) or not delegated to this cgroup, its control files do not exist; +/// skip them instead of failing container start, and note when an explicit +/// limit could not be applied. +fn write_control(dir: &Path, file: &str, value: &str, requested: bool) -> io::Result<()> { + match OpenOptions::new().write(true).truncate(true).open(dir.join(file)) { + Ok(mut f) => f.write_all(value.as_bytes()).map_err(|e| io::Error::new(e.kind(), format!("{file}: {e}"))), + Err(e) if e.kind() == io::ErrorKind::NotFound => { + if requested { + eprintln!("kiri-init: {file} unavailable in this cgroup v2 hierarchy (controller held by cgroup v1 or not delegated); skipping limit"); + } + Ok(()) + } + Err(e) => Err(io::Error::new(e.kind(), format!("{file}: {e}"))), + } +} + /// Writes the limits into the cgroup. Zero fields mean "no limit". pub fn apply_limits(dir: &Path, l: &Limits) -> io::Result<()> { - let write = |file: &str, value: String| fs::write(dir.join(file), value).map_err(|e| io::Error::new(e.kind(), format!("{file}: {e}"))); - write("memory.max", if l.memory_max == 0 { "max".into() } else { l.memory_max.to_string() })?; + if !dir.is_dir() { + return Err(io::Error::new(io::ErrorKind::NotFound, format!("{}: cgroup directory not found", dir.display()))); + } + let mem = if l.memory_max == 0 { "max".into() } else { l.memory_max.to_string() }; + write_control(dir, "memory.max", &mem, l.memory_max != 0)?; // No swap in the VM: a limit is a limit. - let _ = fs::write(dir.join("memory.swap.max"), "0"); + if let Ok(mut f) = OpenOptions::new().write(true).truncate(true).open(dir.join("memory.swap.max")) { + let _ = f.write_all(b"0"); + } let period = if l.cpu_period == 0 { 100_000 } else { l.cpu_period }; - write("cpu.max", if l.cpu_quota == 0 { format!("max {period}") } else { format!("{} {period}", l.cpu_quota) })?; - write("cpu.weight", if l.cpu_weight == 0 { "100".into() } else { l.cpu_weight.clamp(1, 10_000).to_string() })?; - write("pids.max", if l.pids_max == 0 { "max".into() } else { l.pids_max.to_string() })?; + let cpu_max = if l.cpu_quota == 0 { format!("max {period}") } else { format!("{} {period}", l.cpu_quota) }; + write_control(dir, "cpu.max", &cpu_max, l.cpu_quota != 0)?; + let cpu_weight = if l.cpu_weight == 0 { "100".into() } else { l.cpu_weight.clamp(1, 10_000).to_string() }; + write_control(dir, "cpu.weight", &cpu_weight, l.cpu_weight != 0)?; + let pids = if l.pids_max == 0 { "max".into() } else { l.pids_max.to_string() }; + write_control(dir, "pids.max", &pids, l.pids_max != 0)?; Ok(()) } @@ -249,4 +276,60 @@ mod tests { assert_eq!(keyed("low 0\nhigh 0\nmax 3\noom 2\noom_kill 1\noom_group_kill 0\n", "oom_kill"), 1); assert_eq!(keyed("pgfault 9\noom_kill 0\n", "oom_kill"), 0); } + + fn temp_cgroup(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("kiri-cg-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn apply_limits_writes_all_files_when_controllers_exist() { + let dir = temp_cgroup("all"); + for f in ["memory.max", "memory.swap.max", "cpu.max", "cpu.weight", "pids.max"] { + fs::write(dir.join(f), "").unwrap(); + } + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 0 }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.max")).unwrap(), "67108864"); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "0"); + assert_eq!(fs::read_to_string(dir.join("cpu.max")).unwrap(), "50000 100000"); + assert_eq!(fs::read_to_string(dir.join("cpu.weight")).unwrap(), "250"); + assert_eq!(fs::read_to_string(dir.join("pids.max")).unwrap(), "64"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_skips_missing_controllers_on_hybrid_tree() { + // Hybrid cgroup v2 directory whose controllers are bound to v1: none of + // memory.max, cpu.max, cpu.weight or pids.max exist. + let dir = temp_cgroup("hybrid"); + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 134_217_728 }; + apply_limits(&dir, &lim).unwrap(); + // OpenOptions without O_CREAT must not create fake files either. + assert!(!dir.join("memory.max").exists()); + assert!(!dir.join("cpu.max").exists()); + assert!(!dir.join("pids.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_writes_available_subset_of_controllers() { + let dir = temp_cgroup("subset"); + fs::write(dir.join("pids.max"), "").unwrap(); + let lim = Limits { memory_max: 67_108_864, pids_max: 32, ..Default::default() }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("pids.max")).unwrap(), "32"); + assert!(!dir.join("memory.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_errors_when_cgroup_dir_is_missing() { + let missing = std::env::temp_dir().join(format!("kiri-cg-missing-{}", std::process::id())); + let _ = fs::remove_dir_all(&missing); + let err = apply_limits(&missing, &Limits { memory_max: 67_108_864, ..Default::default() }).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::NotFound); + } } diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index a0d968838..81a6ffd94 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -59,6 +59,9 @@ pub struct Paths { pub layers: PathBuf, pub containers: PathBuf, pub cgroup: PathBuf, + /// The mounted cgroup v2 hierarchy root (`/sys/fs/cgroup`, or + /// `/sys/fs/cgroup/unified` on a hybrid host such as stock WSL 2). + pub cgroup_root: PathBuf, } /// A process the agent started: a container's PID 1, or an exec. @@ -935,8 +938,8 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile let init_cgroup; if cloned.as_ref().is_err_and(|e| e.kind() == io::ErrorKind::ResourceBusy) { let rel = fs::read_to_string(format!("/proc/{target_pid}/cgroup")).unwrap_or_default(); - let rel = rel.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim_start_matches('/').to_owned(); - init_cgroup = fs::File::open(std::path::Path::new("/sys/fs/cgroup").join(&rel)); + let rel = rel.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim().trim_start_matches('/').to_owned(); + init_cgroup = fs::File::open(paths.cgroup_root.join(&rel)); match &init_cgroup { Ok(fd) => { let retry = CloneArgs { cgroup: fd.as_raw_fd() as u64, ..args }; diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index e26642c91..17c28566d 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -164,13 +164,24 @@ fn host_dirs() -> io::Result { let leftovers = || { let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return }; let old = PathBuf::from(old.trim()); - if old.starts_with("/sys/fs/cgroup") { - let paths = container::Paths { layers: root.join("layers"), containers: root.join("containers"), cgroup: old.clone() }; + 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)?; - let paths = container::Paths { layers: root.join("layers"), containers: root.join("containers"), cgroup: host_cgroup()? }; + let (cgroup_root, cgroup) = host_cgroup()?; + let paths = container::Paths { + layers: root.join("layers"), + containers: root.join("containers"), + cgroup, + cgroup_root, + }; mkdir(&paths.layers, 0o700)?; mkdir(&paths.containers, 0o700)?; // What an agent that died uncleanly left running: under the cgroup it @@ -178,7 +189,7 @@ fn host_dirs() -> io::Result { let record = root.join("agent.cgroup"); if let Ok(old) = std::fs::read_to_string(&record) { let old = PathBuf::from(old.trim()); - if old != paths.cgroup && old.starts_with("/sys/fs/cgroup") { + if old != paths.cgroup && is_cgroup2_dir(&old) { container::sweep(&paths, &old); } } @@ -272,6 +283,111 @@ fn is_daemon(pid: libc::pid_t) -> bool { pid > 1 && std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| c.split(|b| *b == 0).any(|a| a == b"daemon")) } +fn is_cgroup2_dir(path: &std::path::Path) -> bool { + path.is_absolute() && path.is_dir() && sys::is_cgroup2(path) +} + +/// The cgroup v2 path relative to the unified hierarchy root from `/proc/self/cgroup`. +fn cgroup2_rel(proc_cgroup: &str) -> String { + proc_cgroup.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("/").trim().trim_start_matches('/').to_owned() +} + +/// Unescapes `/proc/self/mountinfo` octal escapes (`\040`, `\011`, `\012`, `\134`). +fn unescape_mount_path(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 3 < bytes.len() + && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b)) + { + let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0'); + out.push(val); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Writable `cgroup2` mounts visible in `/proc/self/mountinfo`, ordered by +/// preference: `/sys/fs/cgroup`, `/sys/fs/cgroup/unified` (stock WSL 2 and +/// hybrid systemd), other mounts under `/sys/fs/cgroup/`, then any other +/// top-level (`root == "/"`) mount. Overmounted entries (for example `tmpfs` +/// stacked over an earlier `cgroup2` mount) are excluded because only the last +/// mount on each path is active. +fn cgroup2_mounts(mountinfo: &str) -> Vec { + struct Entry { + fstype: String, + root: String, + rw: bool, + } + let has_ro = |opts: &str| opts.split(',').any(|o| o == "ro"); + let mut active: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let mut b = before.split_whitespace(); + let (Some(_id), Some(_parent), Some(_dev), Some(root), Some(mp), Some(mopts)) = + (b.next(), b.next(), b.next(), b.next(), b.next(), b.next()) + else { + continue; + }; + let mut a = after.split_whitespace(); + let (Some(fstype), Some(_src), Some(sopts)) = (a.next(), a.next(), a.next()) else { continue }; + let mp = unescape_mount_path(mp); + active.insert( + mp, + Entry { fstype: fstype.to_owned(), root: unescape_mount_path(root), rw: !has_ro(mopts) && !has_ro(sopts) }, + ); + } + let mut found: Vec<(u8, PathBuf)> = active + .into_iter() + .filter(|(mp, e)| e.fstype == "cgroup2" && e.rw && mp != DATA && !mp.starts_with("/var/lib/kiri/")) + .map(|(mp, e)| { + let tier = if mp == "/sys/fs/cgroup" { + 0 + } else if mp == "/sys/fs/cgroup/unified" { + 1 + } else if mp.starts_with("/sys/fs/cgroup/") && e.root == "/" { + 2 + } else if e.root == "/" { + 3 + } else { + 4 + }; + (tier, PathBuf::from(mp)) + }) + .collect(); + found.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + found.into_iter().map(|(_, p)| p).collect() +} + +/// Finds an already-mounted writable `cgroup2` hierarchy (unified +/// `/sys/fs/cgroup`, stock WSL 2's `/sys/fs/cgroup/unified`, or another +/// mountpoint), or mounts one when none is present yet. +fn cgroup2_root() -> io::Result { + let is_usable = |p: &std::path::Path| sys::is_cgroup2(p) && p.join("cgroup.controllers").exists(); + let default = PathBuf::from("/sys/fs/cgroup"); + if is_usable(&default) { + return Ok(default); + } + if let Ok(mountinfo) = std::fs::read_to_string("/proc/self/mountinfo") { + for cand in cgroup2_mounts(&mountinfo) { + if is_usable(&cand) { + return Ok(cand); + } + } + } + let unified = PathBuf::from("/sys/fs/cgroup/unified"); + if is_usable(&unified) { + return Ok(unified); + } + mount_cgroup2(&default) +} + /// The cgroup containers go under on a Linux host, chosen as dockerd and /// containerd choose theirs on cgroup v2: /// @@ -290,12 +406,17 @@ fn is_daemon(pid: libc::pid_t) -> bool { /// /// Started again from inside a `kiri-host` leaf (the daemon stays there /// when its agent restarts), it is not nested again. -fn host_cgroup() -> io::Result { +/// +/// Returns `(cgroup_root, containers_cgroup)`. On a hybrid cgroup tree +/// (stock WSL 2, where `/sys/fs/cgroup` is a tmpfs holding v1 mounts and +/// `cgroup2` is at `/sys/fs/cgroup/unified`), `cgroup_root` is that +/// `cgroup2` mountpoint rather than `/sys/fs/cgroup`. +fn host_cgroup() -> io::Result<(PathBuf, PathBuf)> { let own = std::fs::read_to_string("/proc/self/cgroup")?; - let rel = own.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("/").trim().trim_start_matches('/').to_owned(); - let root = PathBuf::from("/sys/fs/cgroup"); - if !root.join("cgroup.controllers").exists() { - mount_cgroup2(&root)?; + let rel = cgroup2_rel(&own); + let root = cgroup2_root()?; + if root != std::path::Path::new("/sys/fs/cgroup") { + eprintln!("kiri-init: using cgroup v2 at {}", root.display()); } let own = root.join(&rel); let mut base = own.clone(); @@ -319,18 +440,18 @@ fn host_cgroup() -> io::Result { if root.join("cgroup.type").exists() { to_leaf(procs(&root)); } - root - } else if delegated(&own, &procs(&own)) { + root.clone() + } else if own.is_dir() && delegated(&own, &procs(&own)) { if own != base.join("kiri-host") { to_leaf(procs(&own)); } base } else { - root + root.clone() }; let kiri = base.join("kiri"); containers_cgroup(&kiri); - Ok(kiri) + Ok((root, kiri)) } /// Makes the cgroup containers go under, with the controllers handed down @@ -348,18 +469,54 @@ pub fn containers_cgroup(kiri: &std::path::Path) { } } -/// `ip netns exec` mounts a fresh /sys for its network namespace, without -/// the cgroup tree, and every container start then failed with ENOENT. An -/// empty /sys/fs/cgroup gets cgroup2 mounted on it (in that command's -/// private mount namespace, so nothing outside changes); anything else -/// there (cgroup v1) fails the start now, saying why. -fn mount_cgroup2(root: &std::path::Path) -> io::Result<()> { - let empty = std::fs::read_dir(root).map(|mut d| d.next().is_none()); - match empty { - Ok(true) => mount(c"cgroup2", c"/sys/fs/cgroup", c"cgroup2", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, None) - .map_err(|e| io::Error::new(e.kind(), format!("/sys/fs/cgroup has no cgroup tree (ip netns exec remounts /sys) and mounting cgroup2 there failed: {e}"))), - Ok(false) => Err(io::Error::new(io::ErrorKind::Unsupported, "Kiri needs cgroup v2 at /sys/fs/cgroup (this machine has cgroup v1 or a hybrid tree there)")), - Err(e) => Err(io::Error::new(e.kind(), format!("/sys/fs/cgroup: {e}; Kiri needs cgroup v2 mounted there"))), +/// Mounts `cgroup2` when none is mounted yet: +/// - An empty `/sys/fs/cgroup` (e.g. `ip netns exec` remounted a fresh `/sys`) +/// gets `cgroup2` mounted directly on `/sys/fs/cgroup`. +/// - A non-empty `/sys/fs/cgroup` (e.g. a cgroup v1 tree without +/// `/sys/fs/cgroup/unified` mounted yet) leaves the existing v1 mounts +/// untouched and mounts `cgroup2` at `/sys/fs/cgroup/unified`, falling back +/// to `/run/kiri/cgroup` if `/sys/fs/cgroup` is not writable. +fn mount_cgroup2(root: &std::path::Path) -> io::Result { + let flags = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; + let is_empty = |p: &std::path::Path| std::fs::read_dir(p).map(|mut d| d.next().is_none()); + let try_mount = |target: &std::path::Path| -> io::Result<()> { + let t = sys::cstr(target)?; + mount(c"cgroup2", &t, c"cgroup2", flags, None) + }; + match is_empty(root) { + Ok(true) => { + try_mount(root).map_err(|e| { + io::Error::new( + e.kind(), + format!("/sys/fs/cgroup has no cgroup tree (ip netns exec remounts /sys) and mounting cgroup2 there failed: {e}"), + ) + })?; + return Ok(root.to_path_buf()); + } + Ok(false) => {} + Err(e) => { + return Err(io::Error::new(e.kind(), format!("/sys/fs/cgroup: {e}; Kiri needs cgroup v2 mounted there"))); + } + } + let mut last_err = None; + for candidate in [root.join("unified"), PathBuf::from("/run/kiri/cgroup")] { + let _ = std::fs::create_dir_all(&candidate); + if is_empty(&candidate).unwrap_or(false) { + match try_mount(&candidate) { + Ok(()) => return Ok(candidate), + Err(e) => last_err = Some((candidate, e)), + } + } + } + match last_err { + Some((p, e)) => Err(io::Error::new( + e.kind(), + format!("Kiri needs cgroup v2; no cgroup2 mount was found and mounting cgroup2 at {} failed: {e}", p.display()), + )), + None => Err(io::Error::new( + io::ErrorKind::Unsupported, + "Kiri needs cgroup v2; no cgroup2 mount was found and neither /sys/fs/cgroup/unified nor /run/kiri/cgroup was available", + )), } } @@ -371,7 +528,7 @@ fn delegated(own: &std::path::Path, pids: &[String]) -> bool { return true; } let (me, parent) = (std::process::id().to_string(), std::os::unix::process::parent_id().to_string()); - pids.iter().all(|p| *p == me || *p == parent) + !pids.is_empty() && pids.iter().all(|p| *p == me || *p == parent) } /// Mounts the data disk (or a tmpfs without one), creates the layer and @@ -401,6 +558,7 @@ fn data_dirs() -> io::Result { layers: root.join("layers"), containers: root.join("containers"), cgroup: PathBuf::from("/sys/fs/cgroup/kiri"), + cgroup_root: PathBuf::from("/sys/fs/cgroup"), }; std::fs::create_dir_all(&paths.layers)?; std::fs::create_dir_all(&paths.containers)?; @@ -592,3 +750,82 @@ mod meminfo_tests { assert_eq!(super::parse_vmstat_balloon_kib("nr_free_pages 100\n", 4), None); } } + +#[cfg(test)] +mod cgroup_discovery_tests { + use std::path::{Path, PathBuf}; + + #[test] + fn stock_wsl2_hybrid_mountinfo_picks_unified() { + let mountinfo = "\ +28 24 0:26 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755 +29 28 0:27 / /sys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +30 28 0:28 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuset +31 28 0:29 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpu +32 28 0:30 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory +33 28 0:31 / /sys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,pids +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/sys/fs/cgroup/unified")]); + } + + #[test] + fn overmounted_cgroup2_at_root_is_skipped_for_unified() { + // Simulates tmpfs stacked over an earlier /sys/fs/cgroup cgroup2 mount + // (as happens in a mount namespace or hybrid remount): only the active + // topmost mount per path counts. + let mountinfo = "\ +37 27 0:32 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime shared:10 - cgroup2 cgroup2 rw,nsdelegate +200 37 0:60 / /sys/fs/cgroup rw,relatime - tmpfs tmpfs rw,mode=755 +201 200 0:32 / /sys/fs/cgroup/unified rw,relatime - cgroup2 cgroup2 rw,nsdelegate +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/sys/fs/cgroup/unified")]); + } + + #[test] + fn pure_v2_mount_is_preferred_over_secondary_mounts() { + let mountinfo = "\ +37 27 0:32 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +90 27 0:32 / /sys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +91 27 0:32 / /run/kiri/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +"; + assert_eq!( + super::cgroup2_mounts(mountinfo), + vec![ + PathBuf::from("/sys/fs/cgroup"), + PathBuf::from("/sys/fs/cgroup/unified"), + PathBuf::from("/run/kiri/cgroup"), + ] + ); + } + + #[test] + fn readonly_and_container_cgroup2_mounts_are_ignored() { + let mountinfo = "\ +40 28 0:27 / /sys/fs/cgroup/unified ro,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +41 28 0:27 / /sys/fs/cgroup/other rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 ro +42 28 0:27 / /var/lib/kiri/containers/abc/rootfs/sys/fs/cgroup rw - cgroup2 cgroup2 rw +43 28 0:27 / /run/kiri/cgroup rw,nosuid,nodev,noexec - cgroup2 cgroup2 rw +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/run/kiri/cgroup")]); + } + + #[test] + fn mountinfo_octal_escapes_are_decoded() { + assert_eq!(super::unescape_mount_path(r"/mnt/my\040dir\134sub"), r"/mnt/my dir\sub"); + } + + #[test] + fn cgroup2_rel_parses_hybrid_proc_cgroup() { + let wsl_root = "15:name=systemd:/\n2:memory:/\n1:cpuset:/\n0::/\n"; + assert_eq!(super::cgroup2_rel(wsl_root), ""); + let systemd_hybrid = "12:memory:/system.slice/kiri.service\n0::/system.slice/kiri.service\n"; + assert_eq!(super::cgroup2_rel(systemd_hybrid), "system.slice/kiri.service"); + } + + #[test] + fn delegated_requires_non_empty_pids_for_non_service_cgroup() { + assert!(!super::delegated(Path::new("/sys/fs/cgroup/unified/init.scope"), &[])); + assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/system.slice/kiri.service"), &[])); + assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/custom"), &[std::process::id().to_string()])); + } +} diff --git a/crates/kiri-init/src/linux/sys.rs b/crates/kiri-init/src/linux/sys.rs index 72bc6b5c6..1bc6e6d42 100644 --- a/crates/kiri-init/src/linux/sys.rs +++ b/crates/kiri-init/src/linux/sys.rs @@ -112,6 +112,18 @@ pub fn umount_lazy(target: &Path) -> io::Result<()> { check(unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) } as _, "umount").map(drop) } +/// Linux's `CGROUP2_SUPER_MAGIC` (``). +const CGROUP2_SUPER_MAGIC: i64 = 0x6367_7270; + +/// Whether `path` sits on a mounted `cgroup2` filesystem. +pub fn is_cgroup2(path: &Path) -> bool { + let Ok(c) = cstr(path) else { return false }; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: statfs writes into `st`. + unsafe { libc::statfs(c.as_ptr(), &mut st) == 0 && st.f_type as i64 == CGROUP2_SUPER_MAGIC } +} + pub fn mkdir(p: &CStr, mode: libc::mode_t) { // SAFETY: `p` is a valid NUL-terminated string. EEXIST is expected and fine. unsafe { libc::mkdir(p.as_ptr(), mode) }; diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 9902450db..e912c3afb 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 +### Engine: run containers on a hybrid cgroup tree such as stock WSL 2 (unreleased) +- Fixes: #277 Windows: containers fail on a stock WSL2 — Kiri Linux boots a hybrid cgroup tree, so `kiri-init` exits 1 +- Caused: none known +- Caused by: - +- Check: `wsl-hybrid-cgroup` + ### #595 Copy: keep the archive's owners on PUT /containers/{id}/archive, and chown to Config.User on copyUIDGID (unreleased) - Fixes: #594 PUT /containers/{id}/archive (docker cp) gives files to root; Docker keeps the archive's owners - Caused: none known diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 340651d89..dcb203306 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -723,6 +723,86 @@ t systempaths-symlink-escape "ctr:os=[] apk=[] root=ok host:canary=intact-rw" "e # frame limit: `docker top` succeeds and both that container and a sibling stay # running instead of dropping the agent link (#463). t top-frame-cap "top=0 has=yes big=running sib=running" "docker rm -f lh-top-big lh-top-sib >/dev/null 2>&1; docker run -d --name lh-top-sib alpine sleep 300 >/dev/null && docker run -d --name lh-top-big alpine sh -c 'exec sh -c \"sleep 1d;:\" \$(for i in \$(seq 160); do printf \"%08000d \" 0; done)' >/dev/null && for _ in \$(seq 50); do n=\$(docker exec lh-top-big sh -c 'wc -c < /proc/1/cmdline' 2>/dev/null || echo 0); [ \"\${n:-0}\" -gt 1000000 ] && break; sleep 0.1; done && out=\$(docker top lh-top-big 2>&1); rc=\$?; case \"\$out\" in *'sleep 1d'*) has=yes ;; *) has=no ;; esac; echo top=\$rc has=\$has big=\$(docker inspect -f '{{.State.Status}}' lh-top-big) sib=\$(docker inspect -f '{{.State.Status}}' lh-top-sib); docker rm -f lh-top-big lh-top-sib >/dev/null 2>&1" +# Stock WSL 2 mounts a hybrid cgroup tree: tmpfs on /sys/fs/cgroup, cgroup2 on +# /sys/fs/cgroup/unified, and v1 controllers alongside it (leaving unified's +# cgroup.controllers empty). kiri-init must find or mount cgroup2 and run +# containers (including resource flags, exec, stats, top, pause, update, stop/rm) +# without failing (#277). +$D exec -i "$N" sh -c 'cat > /hybrid-cgroup-test.sh' <<'SH' +#!/bin/sh +set -u +export DOCKER_HOST=unix:///root/.kiri/run/docker.sock +docker save alpine:latest -o /tmp/alpine277.tar >/dev/null 2>&1 || { echo "save-failed"; exit 1; } +export KIRI_BIN=/opt/kiri/kiri + +cat > /tmp/exercise277.sh <<'EOF' +#!/bin/sh +set -u +mount -t tmpfs t /var/lib/kiri && mount -t tmpfs t /root && ip link set lo up +"$KIRI_BIN" daemon >/tmp/lh277.log 2>&1 & +p=$! +export DOCKER_HOST=unix:///root/.kiri/run/docker.sock +for i in $(seq 60); do docker version >/dev/null 2>&1 && break; sleep 0.2; done +docker load -q -i /tmp/alpine277.tar >/dev/null 2>&1 || { kill $p 2>/dev/null; wait $p 2>/dev/null; echo load-fail; exit 0; } +ok=ok +docker run --rm alpine true >/dev/null 2>&1 || ok=run-fail +[ "$ok" = ok ] && { docker run --rm --memory 64m --cpus 1 --pids-limit 50 --shm-size 128m alpine true >/dev/null 2>&1 || ok=limits-fail; } +if [ "$ok" = ok ]; then + cid=$(docker run -d alpine sleep 60 2>/dev/null) || ok=bg-fail + [ "$ok" = ok ] && { docker exec "$cid" true >/dev/null 2>&1 || ok=exec-fail; } + [ "$ok" = ok ] && { docker stats --no-stream --format "{{.Name}}" "$cid" >/dev/null 2>&1 || ok=stats-fail; } + [ "$ok" = ok ] && { docker top "$cid" >/dev/null 2>&1 || ok=top-fail; } + [ "$ok" = ok ] && { docker pause "$cid" >/dev/null 2>&1 && docker unpause "$cid" >/dev/null 2>&1 || ok=pause-fail; } + [ "$ok" = ok ] && { docker update --memory 128m "$cid" >/dev/null 2>&1 || ok=update-fail; } + [ "$ok" = ok ] && { docker stop -t 1 "$cid" >/dev/null 2>&1 && docker rm "$cid" >/dev/null 2>&1 || ok=stop-fail; } +fi +kill $p 2>/dev/null; wait $p 2>/dev/null +echo "$ok" +EOF +chmod +x /tmp/exercise277.sh + +s1=$(unshare --mount --propagation private --net --fork sh -c ' + mount -t tmpfs -o mode=755 tmpfs /sys/fs/cgroup + mkdir -p /sys/fs/cgroup/unified /sys/fs/cgroup/systemd /sys/fs/cgroup/freezer /sys/fs/cgroup/devices /sys/fs/cgroup/cpu /sys/fs/cgroup/memory /sys/fs/cgroup/pids + mount -t cgroup2 -o nsdelegate cgroup2 /sys/fs/cgroup/unified + mount -t cgroup -o none,name=systemd cgroup /sys/fs/cgroup/systemd 2>/dev/null || true + mount -t cgroup -o freezer cgroup /sys/fs/cgroup/freezer 2>/dev/null || true + mount -t cgroup -o devices cgroup /sys/fs/cgroup/devices 2>/dev/null || true + /tmp/exercise277.sh +') + +mkdir -p /sys/fs/cgroup/kiri-lh277/sub +s2=$(sh -c ' + echo $$ > /sys/fs/cgroup/kiri-lh277/sub/cgroup.procs + exec unshare --cgroup --mount --propagation private --net --fork sh -c " + mount -t tmpfs -o mode=755 tmpfs /sys/fs/cgroup + mkdir -p /sys/fs/cgroup/unified /sys/fs/cgroup/cpu /sys/fs/cgroup/memory /sys/fs/cgroup/pids + mount -t cgroup2 -o nsdelegate cgroup2 /sys/fs/cgroup/unified + ctrl=\$(cat /sys/fs/cgroup/unified/cgroup.controllers) + [ -z \"\$ctrl\" ] || { echo \"unexpected-ctrl:\$ctrl\"; exit 0; } + /tmp/exercise277.sh + " +') +rmdir /sys/fs/cgroup/kiri-lh277/sub/kiri-host /sys/fs/cgroup/kiri-lh277/sub/kiri /sys/fs/cgroup/kiri-lh277/sub /sys/fs/cgroup/kiri-lh277 2>/dev/null || true + +s3=$(unshare --mount --propagation private --net --fork sh -c ' + mount -t tmpfs -o mode=755 tmpfs /sys/fs/cgroup + mkdir -p /sys/fs/cgroup/cpu /sys/fs/cgroup/memory /sys/fs/cgroup/pids + mount -t tmpfs t /var/lib/kiri && mount -t tmpfs t /root && ip link set lo up + "$KIRI_BIN" daemon >/tmp/lh277-v1.log 2>&1 & + p=$! + export DOCKER_HOST=unix:///root/.kiri/run/docker.sock + for i in $(seq 60); do docker version >/dev/null 2>&1 && break; sleep 0.2; done + docker load -q -i /tmp/alpine277.tar >/dev/null 2>&1 || { kill $p 2>/dev/null; wait $p 2>/dev/null; echo load-fail; exit 0; } + docker run --rm alpine true >/dev/null 2>&1 && ok=ok || ok=run-fail + kill $p 2>/dev/null; wait $p 2>/dev/null + echo "$ok" +') + +rm -f /tmp/alpine277.tar /tmp/exercise277.sh /tmp/lh277.log /tmp/lh277-v1.log +echo "hybrid=$s1 noctrl=$s2 v1only=$s3" +SH +t wsl-hybrid-cgroup "hybrid=ok noctrl=ok v1only=ok" "apk add -q util-linux util-linux-misc iproute2 >/dev/null 2>&1; sh /hybrid-cgroup-test.sh" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index f45c79d54..96efcd760 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -221,3 +221,4 @@ import-empty-numbers #618 a layer whose header left size, uid or gid empty did n cp-in-keeps-owner #594 PUT /containers/{id}/archive and docker cp without -a gave files to root instead of keeping the archive's owners, so a mode-0600 file uploaded for a non-root user (DDEV's mkcert CA key) was unreadable to that user cp-in-keeps-dir-and-symlink-owner #594 PUT /containers/{id}/archive without copyUIDGID must keep directory and symlink owners from the tar headers without chowning symlink targets cp-in-copy-uidgid #594 PUT /containers/{id}/archive with copyUIDGID (docker cp -a) must chown unpacked entries to the container's Config.User when set while keeping tar header owners without -a or when Config.User is empty +wsl-hybrid-cgroup #277 on stock WSL 2 (hybrid /sys/fs/cgroup tmpfs + /sys/fs/cgroup/unified cgroup2, with controllers held by v1), kiri-init exited 1 and containers failed to start From ee55f2a9911be4f4876b6650ee303c4e8c16c0c7 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 15:10:16 +0100 Subject: [PATCH 009/157] Linux: keep the SSH agent socket under /run/kiri, not /run/host-services (#420) Co-authored-by: Urdemonlord --- crates/kiri-init/src/linux/relay.rs | 133 +++++++++++++++++++++++++--- crates/kiri/src/daemon/api.rs | 81 ++++++++++++++++- docs/fix-registry.md | 6 ++ tests/e2e.sh | 4 + tests/linux-host.sh | 6 ++ tests/regressions.tsv | 2 + 6 files changed, 217 insertions(+), 15 deletions(-) diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index 12576ec02..c03271b89 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -430,29 +430,89 @@ impl Relay { /// SSH agent forwarding: containers that mount this socket reach the Mac's /// SSH agent. Each connection is relayed over vsock; keys never leave the Mac. pub const SSH_AGENT_SOCK: &str = "/run/host-services/ssh-auth.sock"; +/// The same socket on a Linux host: under Kiri's own runtime directory, not +/// the host's /run/host-services, which Docker Desktop for Linux also uses +/// for its docker.proxy.sock. Creating that directory root 0700 stopped +/// Docker Desktop from starting (#420), so on a host process the agent +/// never creates or chmods it. +pub const HOST_SSH_AGENT_SOCK: &str = "/run/kiri/host-services/ssh-auth.sock"; pub const SSH_VSOCK_PORT: u32 = 1027; +/// Where the agent listens for SSH agent connections: the VM's +/// /run/host-services, or Kiri's own directory on a Linux host. +fn ssh_agent_sock() -> &'static str { + ssh_agent_sock_for(super::transport::is_host_process()) +} + +fn ssh_agent_sock_for(host_process: bool) -> &'static str { + if host_process { HOST_SSH_AGENT_SOCK } else { SSH_AGENT_SOCK } +} + pub fn listen_ssh_agent() -> io::Result { - std::fs::create_dir_all("/run/host-services")?; - let _ = std::fs::remove_file(SSH_AGENT_SOCK); - // SAFETY: plain unix socket setup; the fd is owned immediately. + listen_ssh_agent_at(ssh_agent_sock()) +} + +fn listen_ssh_agent_at(sock_path: &str) -> io::Result { + use std::os::unix::fs::DirBuilderExt; + let (dir, sock_name) = match sock_path.rsplit_once('/') { + Some((d, name)) if !name.is_empty() => (if d.is_empty() { "/" } else { d }, name), + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid socket path: {sock_path}"))), + }; + if let Some((parent, _)) = dir.rsplit_once('/') + && !parent.is_empty() + { + std::fs::create_dir_all(parent)?; + } + match std::fs::DirBuilder::new().mode(0o700).create(dir) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + // SAFETY: plain unix socket setup against a directory fd opened with O_NOFOLLOW; fds are owned immediately. unsafe { - // The socket below is 0777 for any user in a container. On a Linux - // host this directory is the host's own, so only root, which - // bind-mounts the socket into containers, may reach it by path. - let dir = std::ffi::CString::new("/run/host-services").expect("no NUL"); - sys::check(libc::chmod(dir.as_ptr(), 0o700) as _, "chmod /run/host-services")?; - let fd = sys::check(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; - let sock = OwnedFd::from_raw_fd(fd as RawFd); + // The socket below is 0777 for any user in a container. This + // directory is the agent's own (the VM's /run/host-services, or + // Kiri's /run/kiri/host-services on a Linux host), so only root, + // which bind-mounts the socket into containers, may reach it by path. + // Opened with O_DIRECTORY | O_NOFOLLOW before unlinking or binding so + // a symlink there is refused without touching its target. + let dir_c = std::ffi::CString::new(dir).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in directory path"))?; + let sock_c = std::ffi::CString::new(sock_name).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in socket name"))?; + let dfd = sys::check( + libc::open(dir_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) as _, + &format!("open {dir}"), + )?; + let dfd = OwnedFd::from_raw_fd(dfd as RawFd); + if libc::geteuid() == 0 { + sys::check(libc::fchown(dfd.as_raw_fd(), 0, 0) as _, &format!("chown {dir}"))?; + } + sys::check(libc::fchmod(dfd.as_raw_fd(), 0o700) as _, &format!("chmod {dir}"))?; + if libc::unlinkat(dfd.as_raw_fd(), sock_c.as_ptr(), 0) != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ENOENT) { + return Err(e); + } + } let mut a: libc::sockaddr_un = std::mem::zeroed(); a.sun_family = libc::AF_UNIX as libc::sa_family_t; - for (d, s) in a.sun_path.iter_mut().zip(SSH_AGENT_SOCK.bytes()) { + if sock_path.len() >= a.sun_path.len() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("socket path too long: {sock_path}"))); + } + let proc_dir = format!("/proc/self/fd/{}", dfd.as_raw_fd()); + let proc_sock = format!("{proc_dir}/{sock_name}"); + let bind_path = if proc_sock.len() < a.sun_path.len() && std::path::Path::new(&proc_dir).exists() { + proc_sock.as_str() + } else { + sock_path + }; + for (d, s) in a.sun_path.iter_mut().zip(bind_path.bytes()) { *d = s as libc::c_char; } + let fd = sys::check(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; + let sock = OwnedFd::from_raw_fd(fd as RawFd); sys::check(libc::bind(sock.as_raw_fd(), (&a as *const libc::sockaddr_un).cast(), std::mem::size_of::() as u32) as _, "bind")?; // Any user in a container may use it, as with Docker Desktop. - let path = std::ffi::CString::new(SSH_AGENT_SOCK).expect("no NUL"); - libc::chmod(path.as_ptr(), 0o777); + sys::check(libc::fchmodat(dfd.as_raw_fd(), sock_c.as_ptr(), 0o777, 0) as _, &format!("chmod {sock_path}"))?; sys::check(libc::listen(sock.as_raw_fd(), 64) as _, "listen")?; Ok(sock) } @@ -539,4 +599,51 @@ mod tests { let full = buf.len() + 4; assert_eq!(super::read_frame_into(r.as_raw_fd(), &mut buf, full).unwrap(), 1); } + + #[test] + fn ssh_agent_socket_stays_out_of_the_host_run_host_services() { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + // In the VM the socket is the VM's own /run/host-services; on a Linux + // host it moves under Kiri's /run/kiri, so Docker Desktop for Linux + // keeps its docker.proxy.sock there (#420). + assert_eq!(super::ssh_agent_sock_for(false), "/run/host-services/ssh-auth.sock"); + assert_eq!(super::ssh_agent_sock_for(true), "/run/kiri/host-services/ssh-auth.sock"); + + let root = std::path::PathBuf::from(format!("/tmp/kiri-ssh-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let sock = root.join("kiri/host-services/ssh-auth.sock"); + let sock_str = sock.to_str().unwrap(); + let listener = super::listen_ssh_agent_at(sock_str).unwrap(); + assert!(!root.join("host-services").exists(), "sibling host-services must not be created"); + let dir_mode = std::fs::metadata(root.join("kiri/host-services")).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o700, "parent directory must be 0700 so unprivileged host users cannot traverse it"); + let meta = std::fs::symlink_metadata(&sock).unwrap(); + assert!(meta.file_type().is_socket()); + assert_eq!(meta.permissions().mode() & 0o777, 0o777); + drop(listener); + + // An existing broader directory is tightened to 0700 and a stale socket is replaced. + std::fs::set_permissions(root.join("kiri/host-services"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let listener = super::listen_ssh_agent_at(sock_str).unwrap(); + let dir_mode = std::fs::metadata(root.join("kiri/host-services")).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o700); + drop(listener); + + // A symlink at the host-services directory is refused without chmodding + // its target or unlinking an existing file inside it. + std::fs::remove_dir_all(root.join("kiri/host-services")).unwrap(); + let victim = root.join("victim"); + std::fs::create_dir(&victim).unwrap(); + std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o755)).unwrap(); + let canary = victim.join("ssh-auth.sock"); + std::fs::write(&canary, b"keep").unwrap(); + std::os::unix::fs::symlink(&victim, root.join("kiri/host-services")).unwrap(); + assert!(super::listen_ssh_agent_at(sock_str).is_err()); + assert_eq!(std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777, 0o755); + assert_eq!(std::fs::read(&canary).unwrap(), b"keep", "symlink target contents must not be unlinked"); + + let long = format!("{}/{}", root.display(), "a".repeat(120)); + assert_eq!(super::listen_ssh_agent_at(&long).unwrap_err().kind(), std::io::ErrorKind::InvalidInput); + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 7bc9c58ac..6111f17f2 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -1366,6 +1366,23 @@ fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Re /// The VM path containers mount to reach the Mac's SSH agent (Docker /// Desktop's and OrbStack's name for it). const SSH_AGENT_SOCK: &str = "/run/host-services/ssh-auth.sock"; +const HOST_SSH_AGENT_SOCK: &str = "/run/kiri/host-services/ssh-auth.sock"; + +/// What the guest is given for that bind: the VM's path, or on a Linux host +/// where the agent listens, under Kiri's own /run/kiri. The host's +/// /run/host-services belongs to Docker Desktop for Linux, and the agent +/// never creates it there (#420). Inspect still shows the path asked for. +fn ssh_agent_source() -> &'static str { + ssh_agent_source_for(cfg!(target_os = "linux")) +} + +fn ssh_agent_source_for(linux: bool) -> &'static str { + if linux { HOST_SSH_AGENT_SOCK } else { SSH_AGENT_SOCK } +} + +fn is_ssh_agent_sock(src: &str) -> bool { + src.starts_with('/') && lexical_path(src) == SSH_AGENT_SOCK +} /// A container's mounts, worked out at create time. struct Mounts { @@ -1466,6 +1483,9 @@ fn fresh_bind_sources_with(guest: &[String], info: &[Value], engine_socket: impl let Some((old, rest)) = line.split_once('\t') else { return line.clone() }; let src = info.get(idx).filter(|i| paired && i["Type"] == "bind").and_then(|i| i["Source"].as_str()); if !mac { + if is_ssh_agent_sock(old) || src.is_some_and(is_ssh_agent_sock) { + return format!("{}\t{rest}", ssh_agent_source_for(!mac)); + } let given = src.and_then(&engine_socket).or_else(|| old.starts_with('/').then(|| engine_socket(old)).flatten()); return given.map_or_else(|| line.clone(), |given| format!("{given}\t{rest}")); } @@ -1655,8 +1675,8 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result { - out.guest.push(format!("{src}\t{dst}\t{}", flag(""))); + "bind" if is_ssh_agent_sock(src) => { + out.guest.push(format!("{}\t{dst}\t{}", ssh_agent_source(), flag(""))); out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); } "bind" => { @@ -3869,6 +3889,31 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// Both `-v /run/host-services/ssh-auth.sock:...` and `--mount type=bind,source=/run/host-services/ssh-auth.sock,...` + /// resolve to `ssh_agent_source()` for the guest while keeping `/run/host-services/ssh-auth.sock` + /// in inspect, without needing `/run/host-services` to exist on the host (#420). + #[test] + fn ssh_agent_mounts_resolve_without_touching_host_run_host_services() { + let (root, engine) = engine_in("ssh-agent-mounts", false); + let image = test_image("ssh:1"); + let body = json!({ + "HostConfig": { + "Binds": ["/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock"], + "Mounts": [{"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Target": "/agent.sock", "ReadOnly": true}], + } + }); + let m = mounts(&body, &engine, &image).unwrap(); + let src = ssh_agent_source(); + assert_eq!(m.guest, [format!("{src}\t/run/host-services/ssh-auth.sock\t"), format!("{src}\t/agent.sock\tro")]); + assert_eq!(m.info[0]["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(m.info[0]["RW"], true); + 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); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// `--pid`: empty and `host` as given, `container:` kept with the /// full id; anything else, or an unknown container, refused. #[test] @@ -5241,6 +5286,38 @@ mod network_option_tests { assert!(super::check_volume_device(&opts(&[])).is_ok()); } + #[test] + fn ssh_agent_bind_uses_the_agent_host_path_on_linux() { + // The guest is told where the agent listens: the VM's path, or + // Kiri's own /run/kiri on a Linux host (#420). + assert_eq!(super::ssh_agent_source_for(false), "/run/host-services/ssh-auth.sock"); + assert_eq!(super::ssh_agent_source_for(true), "/run/kiri/host-services/ssh-auth.sock"); + assert_eq!( + super::ssh_agent_source(), + if cfg!(target_os = "linux") { "/run/kiri/host-services/ssh-auth.sock" } else { "/run/host-services/ssh-auth.sock" } + ); + assert!(super::is_ssh_agent_sock("/run/host-services/ssh-auth.sock")); + assert!(super::is_ssh_agent_sock("/run/host-services//ssh-auth.sock")); + assert!(super::is_ssh_agent_sock("/run/./host-services/ssh-auth.sock")); + assert!(!super::is_ssh_agent_sock("run/host-services/ssh-auth.sock")); + // A container made before #420 with /run/host-services/ssh-auth.sock + // in its saved guest mount line gets /run/kiri/host-services/ssh-auth.sock + // when started on Linux, while inspect keeps the path asked for. + let guest = vec!["/run/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro".to_owned()]; + let info = vec![serde_json::json!({"Type": "bind", "Source": "/run/host-services/ssh-auth.sock"})]; + assert_eq!( + super::fresh_bind_sources_with(&guest, &info, |_| None, false), + ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] + ); + assert_eq!(super::fresh_bind_sources_with(&guest, &[], |_| None, false), ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"]); + let slash_guest = vec!["/run/host-services//ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro".to_owned()]; + assert_eq!( + super::fresh_bind_sources_with(&slash_guest, &[], |_| None, false), + ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] + ); + assert_eq!(super::fresh_bind_sources_with(&guest, &info, |_| None, true), guest); + } + /// `--add-host name:ip` and `--hostname` are written into the container's /// /etc/hosts by the guest, so neither may add a line of its own. #[test] diff --git a/docs/fix-registry.md b/docs/fix-registry.md index e912c3afb..f54272ac9 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 +### #571 Linux: keep the SSH agent socket under /run/kiri, not /run/host-services (unreleased) +- Fixes: #420 Linux host: engine creates /run/host-services as root 0700, so Docker Desktop for Linux can't start +- Caused: none known +- Caused by: - +- Check: `host-services-untouched`, `host-services-ssh-agent-mount` + ### Engine: run containers on a hybrid cgroup tree such as stock WSL 2 (unreleased) - Fixes: #277 Windows: containers fail on a stock WSL2 — Kiri Linux boots a hybrid cgroup tree, so `kiri-init` exits 1 - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 0b19aaa29..6c2844ed8 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1024,6 +1024,10 @@ code bind-mount-missing 125 $D run --rm --mount type=bind,source=/kiri/does/not/ # host the daemon's umask (0027) must not shut out the user whose mount it is. t bind-v-creates "made 755 755" bash -c "$D run --rm -v $BIND/new/dir:/n alpine true && [ -d $BIND/new/dir ] && perl -e 'print q(made); printf q( %o), (stat)[2] & 07777 for @ARGV' $BIND/new $BIND/new/dir" t bind-file "from the mac" $D run --rm -v "$BIND/hello.txt:/etc/greeting" alpine cat /etc/greeting +# Docker Desktop's SSH agent mount path (/run/host-services/ssh-auth.sock) works +# through -v and --mount for non-root container users too, while inspect shows +# the path asked for (#420). +t host-services-ssh-agent-mount "sock1=ok sock2=ok src=/run/host-services/ssh-auth.sock" bash -c "id=\$($D create -u 1000:1000 -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=bind,source=/run/host-services/ssh-auth.sock,target=/ssh2.sock alpine sh -c 'test -S /run/host-services/ssh-auth.sock && test -w /run/host-services/ssh-auth.sock && s1=ok || s1=no; test -S /ssh2.sock && test -w /ssh2.sock && s2=ok || s2=no; printf \"sock1=%s sock2=%s \" \"\$s1\" \"\$s2\"'); src=\$($D inspect -f '{{(index .Mounts 0).Source}}' \$id); $D start -a \$id; $D rm -f \$id >/dev/null; echo \"src=\$src\"" # A file made, changed and deleted on the Mac raises inotify events in the # container, as one made there does: file watchers (Vite, webpack, nodemon) # pick up saves made in an editor on the Mac. inotifyd prints n (created), diff --git a/tests/linux-host.sh b/tests/linux-host.sh index dcb203306..d45b81a30 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -803,6 +803,12 @@ rm -f /tmp/alpine277.tar /tmp/exercise277.sh /tmp/lh277.log /tmp/lh277-v1.log echo "hybrid=$s1 noctrl=$s2 v1only=$s3" SH t wsl-hybrid-cgroup "hybrid=ok noctrl=ok v1only=ok" "apk add -q util-linux util-linux-misc iproute2 >/dev/null 2>&1; sh /hybrid-cgroup-test.sh" +# On a Linux host the SSH-agent relay listens at /run/kiri/host-services/ssh-auth.sock +# (inside root:root 0700 /run/kiri/host-services, unreachable by unprivileged host +# users) and never creates or chmods /run/host-services, which Docker Desktop for +# Linux uses for docker.proxy.sock (#420). +t host-services-untouched "absent=yes kiri=root:root:700:socket host-unpriv=denied dd=65534:65534:755:no-kiri-sock:rm-ok" "absent=\$([ ! -e /run/host-services ] && echo yes || echo no); kdir=\$(stat -c '%U:%G:%a' /run/kiri/host-services 2>/dev/null); ksock=\$(stat -c '%F' /run/kiri/host-services/ssh-auth.sock 2>/dev/null); su nobody -s /bin/sh -c 'test -e /run/kiri/host-services/ssh-auth.sock' 2>/dev/null && unpriv=reached || unpriv=denied; mkdir -p /run/host-services && chown 65534:65534 /run/host-services && chmod 755 /run/host-services && : > /run/host-services/docker.proxy.sock && chown 65534:65534 /run/host-services/docker.proxy.sock; $POST http://d/kiri/stop >/dev/null && $POST http://d/kiri/wake >/dev/null && docker run --rm -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock alpine test -S /run/host-services/ssh-auth.sock; dd_dir=\$(stat -c '%u:%g:%a' /run/host-services 2>/dev/null); [ ! -e /run/host-services/ssh-auth.sock ] && dd_sock=no-kiri-sock || dd_sock=clobbered; su nobody -s /bin/sh -c 'rm /run/host-services/docker.proxy.sock' 2>/dev/null && dd_rm=rm-ok || dd_rm=rm-denied; rm -rf /run/host-services; echo \"absent=\$absent kiri=\$kdir:\$ksock host-unpriv=\$unpriv dd=\$dd_dir:\$dd_sock:\$dd_rm\"" +t host-services-ssh-agent-mount "sock1=ok sock2=ok src=/run/host-services/ssh-auth.sock host-absent=yes" "id=\$(docker create -u 1000:1000 -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=bind,source=/run/host-services/ssh-auth.sock,target=/ssh2.sock alpine sh -c 'test -S /run/host-services/ssh-auth.sock && test -w /run/host-services/ssh-auth.sock && s1=ok || s1=no; test -S /ssh2.sock && test -w /ssh2.sock && s2=ok || s2=no; printf \"sock1=%s sock2=%s \" \"\$s1\" \"\$s2\"'); src=\$(docker inspect -f '{{(index .Mounts 0).Source}}' \$id); docker start -a \$id; docker rm -f \$id >/dev/null; [ ! -e /run/host-services ] && ha=yes || ha=no; echo \"src=\$src host-absent=\$ha\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 96efcd760..0d4dd3eac 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -222,3 +222,5 @@ cp-in-keeps-owner #594 PUT /containers/{id}/archive and docker cp without -a gav cp-in-keeps-dir-and-symlink-owner #594 PUT /containers/{id}/archive without copyUIDGID must keep directory and symlink owners from the tar headers without chowning symlink targets cp-in-copy-uidgid #594 PUT /containers/{id}/archive with copyUIDGID (docker cp -a) must chown unpacked entries to the container's Config.User when set while keeping tar header owners without -a or when Config.User is empty wsl-hybrid-cgroup #277 on stock WSL 2 (hybrid /sys/fs/cgroup tmpfs + /sys/fs/cgroup/unified cgroup2, with controllers held by v1), kiri-init exited 1 and containers failed to start +host-services-untouched #420 on a Linux host kiri-init created /run/host-services as root 0700, locking Docker Desktop for Linux out of /run/host-services/docker.proxy.sock +host-services-ssh-agent-mount #420 containers mounting /run/host-services/ssh-auth.sock must still get the agent's SSH relay socket while the host's /run/host-services is left alone From 6b16d45a4818bfb9dc796e3e97965f787c99c223 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 15:21:07 +0100 Subject: [PATCH 010/157] Copy: preserve directory-contents paths for docker cp (#617) Co-authored-by: Andre Kurait --- crates/kiri-init/src/linux/copy.rs | 200 ++++++++++++++++++++++++++-- docs/fix-registry.md | 6 + tests/archive-directory-contents.py | 109 +++++++++++++++ tests/e2e.sh | 2 + tests/linux-host.sh | 3 + tests/regressions.tsv | 2 + 6 files changed, 314 insertions(+), 8 deletions(-) create mode 100755 tests/archive-directory-contents.py diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index dcd1a9edd..6ddaac2db 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -11,6 +11,7 @@ use std::fs; use std::io::{self, BufReader, BufWriter, Read, Write}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt}; use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, copy_flags, copy_op}; @@ -442,13 +443,22 @@ impl Read for Chunks { /// Answers with the path's metadata; for `OUT` an archive of it follows. fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { - let path = std::path::Path::new(spec.path); + // Docker archives a path with its "." and ".." resolved by name, but + // stats it as given. + let cleaned; + let source = if spec.op == copy_op::OUT && !spec.path.is_empty() { + cleaned = archived(spec.path); + cleaned.as_str() + } else { + spec.path + }; + let path = std::path::Path::new(source); let meta = fs::symlink_metadata(path) .map_err(|_| io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id)))?; let link = if meta.file_type().is_symlink() { fs::read_link(path)?.to_string_lossy().into_owned() } else { String::new() }; - let name = path.file_name().map_or_else(|| "/".to_owned(), |n| n.to_string_lossy().into_owned()); + let name = base(source); let entry = FsEntry { - name: &name, + name, mode: meta.mode(), size: meta.len(), mtime: meta.mtime(), @@ -465,18 +475,58 @@ fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { { let mut b = tar::Builder::new(&mut w); b.follow_symlinks(false); - // The root itself archives as its contents under ".". - let top = if name == "/" { "." } else { name.as_str() }; if meta.is_dir() { - append_tree(&mut b, path, std::path::Path::new(top))?; + append_tree(&mut b, path, std::path::Path::new(name))?; } else { - append_one(&mut b, path, std::path::Path::new(top), &meta)?; + append_one(&mut b, path, std::path::Path::new(name), &meta)?; } b.finish()?; } w.flush() } +/// The last component of `path` as Docker names it: "." and ".." are kept, +/// and the root is "/". +fn base(path: &str) -> &str { + path.trim_end_matches('/').rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or("/") +} + +/// The path an archive is read from: `path` with its dots resolved by name. +/// Where that names nothing, `path` as given, so that every path found +/// before is still found: the window follows a start script's relative +/// link by asking for the link's directory, "..", and the rest, and behind +/// a linked directory (/bin on many images) only the kernel finds that. +fn archived(path: &str) -> String { + let cleaned = clean(path); + if fs::symlink_metadata(&cleaned).is_ok() { cleaned } else { path.to_owned() } +} + +/// `path` from the root, with "." and ".." resolved by name. A final "." (a +/// directory's contents) and a trailing "/" (a link's directory) are kept. +fn clean(path: &str) -> String { + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop(); + } + name => parts.push(name), + } + } + let mut cleaned = format!("/{}", parts.join("/")); + if base(path) == "." { + if !cleaned.ends_with('/') { + cleaned.push('/'); + } + cleaned.push('.'); + } + if path.ends_with('/') && !cleaned.ends_with('/') { + cleaned.push('/'); + } + cleaned +} + /// Like `append_dir_all`, but sockets (which tar cannot hold) are skipped, /// and the kernel's /proc and /sys archive as empty directories. fn append_tree(b: &mut tar::Builder, src: &std::path::Path, name: &std::path::Path) -> io::Result<()> { @@ -521,11 +571,16 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st if ft.is_socket() { return Ok(()); } + // A directory's contents under "./" and the root's under "/" keep those names. + let verbatim = name.as_os_str().as_bytes().starts_with(b"./") || name.has_root(); if ft.is_file() { let mut h = tar::Header::new_gnu(); h.set_metadata(meta); h.set_mode(mode_bits(meta)); let mut f = fs::File::open(src)?; + if verbatim { + return append_contents(b, &mut h, name, None, &mut f); + } return b.append_data(&mut h, name, &mut f); } if ft.is_dir() || ft.is_symlink() || ft.is_fifo() || ft.is_char_device() || ft.is_block_device() { @@ -534,18 +589,53 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st h.set_mode(mode_bits(meta)); h.set_size(0); if ft.is_symlink() { - return b.append_link(&mut h, name, fs::read_link(src)?); + let link = fs::read_link(src)?; + if verbatim { + return append_contents(b, &mut h, name, Some(&link), io::empty()); + } + return b.append_link(&mut h, name, link); } if ft.is_char_device() || ft.is_block_device() { let rdev = meta.rdev(); h.set_device_major(libc::major(rdev))?; h.set_device_minor(libc::minor(rdev))?; } + if verbatim { + return append_contents(b, &mut h, name, None, io::empty()); + } return b.append_data(&mut h, name, io::empty()); } Ok(()) } +/// tar's path setter drops "./" and refuses a leading "/". Docker's client +/// needs "./" when it rebases a directory-contents archive into a destination +/// that does not exist, and puts the new name in front of the root's "/". +/// These paths come from append_tree's "." or "/" plus directory entry names. +fn append_contents(b: &mut tar::Builder, h: &mut tar::Header, name: &std::path::Path, link: Option<&std::path::Path>, data: impl Read) -> io::Result<()> { + fn field(b: &mut tar::Builder, slot: &mut [u8], bytes: &[u8], kind: u8) -> io::Result<()> { + if bytes.len() > slot.len() { + let mut long = tar::Header::new_gnu(); + long.set_path("././@LongLink")?; + long.set_entry_type(tar::EntryType::new(kind)); + long.set_mode(0o644); + long.set_size(bytes.len() as u64 + 1); + long.set_cksum(); + b.append(&long, bytes.chain(io::repeat(0).take(1)))?; + } + slot.fill(0); + let count = bytes.len().min(slot.len()); + slot[..count].copy_from_slice(&bytes[..count]); + Ok(()) + } + field(b, &mut h.as_old_mut().name, name.as_os_str().as_bytes(), b'L')?; + if let Some(link) = link { + field(b, &mut h.as_old_mut().linkname, link.as_os_str().as_bytes(), b'K')?; + } + h.set_cksum(); + b.append(h, data) +} + fn done(conn: &mut fs::File) -> io::Result<()> { let mut out = Vec::new(); Msg::CopyDone.encode(&mut out); @@ -713,6 +803,100 @@ fn read_frame(conn: &mut impl Read, buf: &mut Vec) -> io::Result<()> { mod tests { use super::*; + #[test] + fn contents_keep_dot_prefix_and_long_names() { + for length in [4, 98, 99, 100, 101, 255] { + let name = format!("./{}", "a".repeat(length)); + let link = "../".to_owned() + &"b".repeat(length); + let mut bytes = Vec::new(); + { + let mut archive = tar::Builder::new(&mut bytes); + let mut header = tar::Header::new_gnu(); + header.set_entry_type(tar::EntryType::Symlink); + header.set_size(0); + append_contents(&mut archive, &mut header, std::path::Path::new(&name), Some(std::path::Path::new(&link)), io::empty()).unwrap(); + archive.finish().unwrap(); + } + let mut archive = tar::Archive::new(bytes.as_slice()); + let mut entries = archive.entries().unwrap(); + let entry = entries.next().unwrap().unwrap(); + assert_eq!(entry.path_bytes().as_ref(), name.as_bytes()); + assert_eq!(entry.link_name_bytes().unwrap().as_ref(), link.as_bytes()); + assert!(entries.next().is_none()); + } + } + + #[test] + fn archived_paths_resolve_dots_by_name_and_stats_keep_them() { + for (path, cleaned, name) in [ + ("/t/dir", "/t/dir", "dir"), + ("/t/dir/", "/t/dir/", "dir"), + ("/t/dir/.", "/t/dir/.", "."), + ("/t/dir/./", "/t/dir/./", "."), + ("/t/dir//.", "/t/dir/.", "."), + ("/t/dir/sub/..", "/t/dir", "dir"), + ("/t/dir/sub/../", "/t/dir/", "dir"), + ("/t/dir/sub/../.", "/t/dir/.", "."), + ("/t/link/../dir", "/t/dir", "dir"), + ("t/dir/..", "/t", "t"), + ("../../t/dir/.", "/t/dir/.", "."), + ("/", "/", "/"), + ("//", "/", "/"), + ("/.", "/.", "."), + ("/..", "/", "/"), + ("/etc/..", "/", "/"), + ("/etc/../.", "/.", "."), + (".", "/.", "."), + ("..", "/", "/"), + ] { + assert_eq!(clean(path), cleaned, "{path}"); + assert_eq!(base(cleaned), name, "{path}"); + } + for (path, name) in [("/t/dir/sub/..", ".."), ("/t/dir/sub/../", ".."), ("/t/dir/.", "."), ("/t/dir/", "dir"), ("/", "/"), ("//", "/"), ("/..", "..")] { + assert_eq!(base(path), name, "{path}"); + } + } + + #[test] + fn a_path_only_the_kernel_finds_is_archived_as_given() { + let dir = std::env::temp_dir().join(format!("kiri-archived-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("usr/bin")).unwrap(); + fs::create_dir_all(dir.join("usr/share")).unwrap(); + fs::create_dir_all(dir.join("share")).unwrap(); + fs::write(dir.join("usr/share/start.sh"), "").unwrap(); + fs::write(dir.join("usr/share/both"), "").unwrap(); + fs::write(dir.join("share/both"), "").unwrap(); + std::os::unix::fs::symlink("usr/bin", dir.join("bin")).unwrap(); + let at = |rest: &str| format!("{}/{rest}", dir.display()); + // By name this is share/start.sh, which is not there: the kernel's stays. + assert_eq!(archived(&at("bin/../share/start.sh")), at("bin/../share/start.sh")); + // Where the path by name is there, it is the one, as in Docker. + assert_eq!(archived(&at("bin/../share/both")), at("share/both")); + assert_eq!(archived(&at("usr/bin/..")), at("usr")); + // Nothing either way: the path as given, for the error to name. + assert_eq!(archived(&at("bin/../none")), at("bin/../none")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn root_and_contents_entries_keep_their_prefix() { + let root = std::path::Path::new("/"); + let meta = fs::symlink_metadata(root).unwrap(); + let names = ["/", "/etc", ".", "./etc", "etc"]; + let mut bytes = Vec::new(); + { + let mut archive = tar::Builder::new(&mut bytes); + for name in names { + append_one(&mut archive, root, std::path::Path::new(name), &meta).unwrap(); + } + archive.finish().unwrap(); + } + let mut archive = tar::Archive::new(bytes.as_slice()); + let got: Vec<_> = archive.entries().unwrap().map(|entry| String::from_utf8(entry.unwrap().path_bytes().into_owned()).unwrap()).collect(); + assert_eq!(got, names); + } + #[test] fn chunks_end_at_the_empty_chunk_and_leave_the_rest() { let wire = [&3u32.to_le_bytes()[..], b"abc", &2u32.to_le_bytes(), b"de", &0u32.to_le_bytes(), b"after"].concat(); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index f54272ac9..431cc22eb 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 +### #137 Archives: preserve directory-contents paths for docker cp (unreleased) +- Fixes: #617 `docker cp container:/dir/. dest` copies the folder itself instead of its contents +- Caused: none known +- Caused by: - +- Check: `archive-directory-contents`, `cp-out-dot` + ### #571 Linux: keep the SSH agent socket under /run/kiri, not /run/host-services (unreleased) - Fixes: #420 Linux host: engine creates /run/host-services as root 0700, so Docker Desktop for Linux can't start - Caused: none known diff --git a/tests/archive-directory-contents.py b/tests/archive-directory-contents.py new file mode 100755 index 000000000..036ae9c41 --- /dev/null +++ b/tests/archive-directory-contents.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Check Docker's directory-versus-contents archive naming, including path stat.""" +import base64 +import contextlib +import http.client +import io +import json +import os +import socket +import subprocess +import sys +import tarfile +import tempfile +import urllib.parse +from pathlib import Path + +DIRECTORY = "archive-directory-contents" +# Longer than a tar header's 100-byte name and link fields. +LONG_NAME = "n" * 120 +LONG_TARGET = "t" * 130 +ENTRIES = ["file", "link", "longlink", LONG_NAME, "sub"] + + +def check(path, image): + cli = ["docker", "-H", "unix://" + path] + + def run(*args): + return subprocess.run(cli + list(args), check=True, capture_output=True, timeout=30).stdout + + @contextlib.contextmanager + def archive(method, source): + connection = http.client.HTTPConnection("localhost", timeout=5) + connection.sock = socket.socket(socket.AF_UNIX) + connection.sock.settimeout(5) + connection.sock.connect(path) + try: + connection.request(method, "/v1.47/containers/" + cid + "/archive?path=" + + urllib.parse.quote(source, safe="")) + response = connection.getresponse() + assert response.status == 200, (method, source, response.status, response.read()) + yield json.loads(base64.b64decode(response.getheader("X-Docker-Container-Path-Stat"))), response + finally: + connection.close() + + cid = run("run", "-d", "--network", "none", image, "sleep", "120").decode().strip() + try: + run("exec", cid, "sh", "-c", + "cd /tmp && mkdir -p {0}/sub && printf content > {0}/file && printf long > {0}/{1}" + " && ln -s /etc {0}/link && ln -s {2} {0}/longlink".format(DIRECTORY, LONG_NAME, LONG_TARGET)) + for state in ("running", "stopped"): + if state == "stopped": + run("stop", "-t", "0", cid) + run("wait", cid) + # Docker resolves ".." by name before it archives a path, so the + # parent of "link" is this directory, not the root "link" points + # into. A stat reports the last component as it was given. + for suffix, name in (("", DIRECTORY), ("/", DIRECTORY), ("/.", "."), ("/./", "."), + ("/sub/..", DIRECTORY), ("/sub/../", DIRECTORY), ("/sub/../.", "."), + ("/link/..", DIRECTORY)): + source = "/tmp/" + DIRECTORY + suffix + with archive("HEAD", source) as (stat, _): + assert stat["name"] == source.rstrip("/").rsplit("/", 1)[1], (state, source, stat) + with archive("GET", source) as (stat, response): + assert stat["name"] == name, (state, source, stat) + with tarfile.open(fileobj=io.BytesIO(response.read())) as members: + expected = [name] + [name + "/" + entry for entry in ENTRIES] + assert members.getnames() == expected, (state, source, members.getnames()) + assert members.extractfile(name + "/file").read() == b"content" + assert members.extractfile(name + "/" + LONG_NAME).read() == b"long" + assert members.getmember(name + "/longlink").linkname == LONG_TARGET + print("PASS", state, source, flush=True) + # The root's entries start with "/": Docker's client puts the new + # name in front of them. Only the first few are read. + for source in ("/", "/tmp/.."): + with archive("GET", source) as (stat, response): + assert stat["name"] == "/", (state, source, stat) + with tarfile.open(fileobj=response, mode="r|") as members: + names = [member.name for member, _ in zip(members, range(3))] + # Python reads the root directory's own "/" as "". + assert names[0] == "" and len(names) == 3, (state, source, names) + assert all(entry.startswith("/") for entry in names[1:]), (state, source, names) + print("PASS", state, source, flush=True) + # Docker rebases "." to this new destination name. Every child + # must keep "./" for that rebase to include it in the directory. + with tempfile.TemporaryDirectory(prefix="kiri-archive-contents-") as destination: + copied = Path(destination) / "new-directory" + run("cp", cid + ":/tmp/" + DIRECTORY + "/.", str(copied)) + assert (copied / "file").read_bytes() == b"content" + assert (copied / LONG_NAME).read_bytes() == b"long" + assert os.readlink(copied / "longlink") == LONG_TARGET + assert not (Path(destination) / "file").exists() + print("PASS", state, "docker cp into new directory", flush=True) + # The client rebases the directory's own name here. + parent = Path(destination) / "parent-directory" + run("cp", cid + ":/tmp/" + DIRECTORY + "/sub/..", str(parent)) + assert (parent / "file").read_bytes() == b"content" + assert sorted(os.listdir(destination)) == ["new-directory", "parent-directory"] + print("PASS", state, "docker cp of a parent into new directory", flush=True) + finally: + result = subprocess.run(cli + ["rm", "-f", cid], capture_output=True, timeout=30) + if result.returncode: + if sys.exc_info()[0] is None: + result.check_returncode() + else: + print("Cleanup failed:", result.stderr.decode(errors="replace"), file=sys.stderr) + + +if __name__ == "__main__": + check(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "alpine") diff --git a/tests/e2e.sh b/tests/e2e.sh index 6c2844ed8..305a042f3 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -369,6 +369,7 @@ t output-bytes "5488895" bash -c "$D run --rm alpine sh -c 'seq 1 800000' | wc - t killed-by-signal "137" $D run --rm alpine sh -c 'sh -c "kill -9 \$\$"; echo $?' section "run: config" +code archive-directory-contents 0 python3 "$(dirname "$0")/archive-directory-contents.py" "$SOCK" t env "bar" $D run --rm -e FOO=bar alpine sh -c 'echo $FOO' t env-image "PATH=/usr/local/sbin" $D run --rm alpine env t workdir "/tmp" $D run --rm -w /tmp alpine pwd @@ -1271,6 +1272,7 @@ t cp-in-copy-uidgid "no-a=1234:1235 with-a=1000:1000 default-a=1234:1235" bash - t cp-in-zero-time "time 0" bash -c "echo z > $CPD/z && TZ=UTC touch -t 197001010000.00 $CPD/z && tar -C $CPD -cf - z | $D cp - cpc:/tmp/ && echo time \$($D exec cpc stat -c %Y /tmp/z)" t cp-out-file "fromctr" bash -c "$D exec cpc sh -c 'echo fromctr > /etc/motd2' && $D cp cpc:/etc/motd2 $CPD/ && cat $CPD/motd2" t cp-out-dir "deep" bash -c "$D exec cpc sh -c 'mkdir -p /opt/x/y; echo deep > /opt/x/y/z' && $D cp cpc:/opt/x $CPD/xx && cat $CPD/xx/y/z" +t cp-out-dot "hi no-out" bash -c "$D exec cpc sh -c 'mkdir -p /out; echo hi > /out/a.txt' && mkdir -p $CPD/dst && $D cp cpc:/out/. $CPD/dst && echo \"\$(cat $CPD/dst/a.txt) \$([ ! -e $CPD/dst/out ] && echo no-out || echo has-out)\"" t cp-out-stdout "alpine-release" bash -c "$D cp cpc:/etc/alpine-release - | tar -t" t cp-out-symlink "-> " bash -c "$D exec cpc ln -sf /etc/alpine-release /tmp/rel && $D cp cpc:/tmp/rel - | tar -tv" t cp-big "match" bash -c "head -c 30000000 /dev/urandom > $CPD/big && $D cp $CPD/big cpc:/tmp/big && a=\$($SHA $CPD/big | cut -c1-64); b=\$($D exec cpc sha256sum /tmp/big | cut -c1-64); [ \$a = \$b ] && echo match" diff --git a/tests/linux-host.sh b/tests/linux-host.sh index d45b81a30..ae246799d 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -21,6 +21,7 @@ $D run -d --name "$N" --privileged --tmpfs /run -v "$N":/var/lib/kiri -v "$N"-st up() { for _ in $(seq 180); do $D exec "$N" sh -c 'DOCKER_HOST=unix:///root/.kiri/run/docker.sock docker version' >/dev/null 2>&1 && break; sleep 1; done; } up $D cp "$(dirname "$0")/testcontainers-api.py" "$N":/testcontainers-api.py >/dev/null +$D cp "$(dirname "$0")/archive-directory-contents.py" "$N":/archive-directory-contents.py >/dev/null $D cp "$(dirname "$0")/lib/images.sh" "$N":/images.sh >/dev/null $D exec -e KIRI_TEST_REGISTRY="$KIRI_REG" "$N" sh -c '. /images.sh; export DOCKER_HOST=unix:///root/.kiri/run/docker.sock; kiri_seed_images $KIRI_IMAGES_LINUX_HOST' || echo "linux-host: an image could not be fetched; the checks that run it will fail" @@ -102,6 +103,8 @@ t cp "copied" "echo copied > /tmp/x && docker cp /tmp/x web:/tmp/x && docker exe t cp-in-keeps-owner "1234 1235 600 key" "rm -rf /tmp/cpo && mkdir -p /tmp/cpo && printf key > /tmp/cpo/owned.pem && chmod 600 /tmp/cpo/owned.pem && chown 1234:1235 /tmp/cpo/owned.pem && tar -C /tmp/cpo -cf - owned.pem | docker cp - web:/tmp/ && echo \$(docker exec web stat -c '%u %g %a' /tmp/owned.pem) \$(docker exec -u 1234 web cat /tmp/owned.pem)" t cp-in-keeps-dir-and-symlink-owner "dir=1234:1235:750 link=1234:1235 over=1234:1235:regular file targets=0:0:0:0" "mkdir -p /tmp/cpo/owned-dir && chmod 750 /tmp/cpo/owned-dir && ln -sf /etc/hostname /tmp/cpo/owned-link && printf new > /tmp/cpo/owned-over && chmod 640 /tmp/cpo/owned-over && chown -Rh 1234:1235 /tmp/cpo && docker exec web ln -sf /etc/alpine-release /tmp/owned-over && tar -C /tmp/cpo -cf - owned-dir owned-link owned-over | curl -s --unix-socket /root/.kiri/run/docker.sock -X PUT --data-binary @- 'http://d/v1.47/containers/web/archive?path=/tmp' && docker exec web sh -c 'echo \"dir=\$(stat -c %u:%g:%a /tmp/owned-dir) link=\$(stat -c %u:%g /tmp/owned-link) over=\$(stat -c %u:%g:%F /tmp/owned-over) targets=\$(stat -c %u:%g /etc/hostname):\$(stat -c %u:%g /etc/alpine-release)\"'" t cp-in-copy-uidgid "no-a=1234:1235 with-a=1000:1000 default-a=1234:1235" "docker rm -f cpu >/dev/null 2>&1; docker run -d --name cpu -u 1000:1000 alpine sleep 120 >/dev/null && tar -C /tmp/cpo -cf - owned.pem | docker cp - cpu:/tmp/ && docker cp -a /tmp/x cpu:/tmp/x && tar -C /tmp/cpo -cf - owned.pem | docker cp -a - web:/tmp/ && echo \"no-a=\$(docker exec cpu stat -c %u:%g /tmp/owned.pem) with-a=\$(docker exec cpu stat -c %u:%g /tmp/x) default-a=\$(docker exec web stat -c %u:%g /tmp/owned.pem)\"; rm -rf /tmp/cpo; docker rm -f cpu >/dev/null 2>&1" +t cp-out-dot "hi no-out" "docker exec web sh -c 'mkdir -p /out; echo hi > /out/a.txt' && rm -rf /tmp/cpdot && mkdir -p /tmp/cpdot && docker cp web:/out/. /tmp/cpdot && echo \"\$(cat /tmp/cpdot/a.txt) \$([ ! -e /tmp/cpdot/out ] && echo no-out || echo has-out)\"; rm -rf /tmp/cpdot" +t archive-directory-contents "PASS stopped docker cp of a parent into new directory" "python3 /archive-directory-contents.py /root/.kiri/run/docker.sock" # What Testcontainers needs (#222, #121); see tests/testcontainers-api.py. for c in version cmd keepalive close follow follow-created timestamps; do t "testcontainers-$c" "ok $c" "for i in \$(seq 60); do command -v python3 >/dev/null && break; sleep 1; done; python3 /testcontainers-api.py /root/.kiri/run/docker.sock $c" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 0d4dd3eac..49359c827 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -224,3 +224,5 @@ cp-in-copy-uidgid #594 PUT /containers/{id}/archive with copyUIDGID (docker cp - wsl-hybrid-cgroup #277 on stock WSL 2 (hybrid /sys/fs/cgroup tmpfs + /sys/fs/cgroup/unified cgroup2, with controllers held by v1), kiri-init exited 1 and containers failed to start host-services-untouched #420 on a Linux host kiri-init created /run/host-services as root 0700, locking Docker Desktop for Linux out of /run/host-services/docker.proxy.sock host-services-ssh-agent-mount #420 containers mounting /run/host-services/ssh-auth.sock must still get the agent's SSH relay socket while the host's /run/host-services is left alone +archive-directory-contents #617 GET /containers/{id}/archive normalized away a trailing /., dropped ./ from directory-contents entries, and did not resolve .. by name or keep / on root entries +cp-out-dot #617 docker cp container:/out/. dst copied the folder itself (dst/out/a.txt) instead of its contents (dst/a.txt) From d9f5239b423d3f4c22215c2217d2d0fa44fdc3c7 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 15:30:26 +0100 Subject: [PATCH 011/157] Import: keep volume xattrs with GNU tar (#485) Co-authored-by: Chukwuebuka (Gaus Octavio) <56232734+Chukwuebuka-2003@users.noreply.github.com> --- crates/kiri/src/import.rs | 470 +++++++++++++++++++++++++++++++------- docs/fix-registry.md | 6 + tests/import.sh | 58 ++++- tests/regressions.tsv | 1 + 4 files changed, 447 insertions(+), 88 deletions(-) diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index 71f12d964..d212d332d 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -1,10 +1,11 @@ //! Moving to Kiri from OrbStack or Docker Desktop: images, volumes and //! containers, copied through the docker CLI so each engine speaks its own //! API. The source is only read: `docker save` for images, `inspect` for -//! containers, and for a volume `docker cp` out of a container that mounts -//! it read-only, is never started and is removed after (that keeps file -//! owners, which a copy through the Finder would lose). Containers arrive -//! stopped. +//! containers, and for a volume a short-lived official GNU tar helper that +//! mounts it read-only and is removed after (keeping file owners and `user.*` +//! extended attributes, which `docker cp` or a copy through the Finder would +//! lose; falling back to `docker cp` when offline without GNU tar). +//! Containers arrive stopped. use std::io::{self, Read, Write}; use std::path::PathBuf; @@ -174,7 +175,14 @@ fn has(ctx: &str, kind: &str, name: &str) -> bool { /// `from` piped through `retar` (in this process) into `to`, both docker /// commands already set up; the first failure that explains the others. -fn pipe(mut from: Command, mut to: Command, from_ctx: &str, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { +fn pipe(from: Command, to: Command, from_ctx: &str, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { + pipe_with(from, to, from_ctx, false, retar) +} + +/// [`pipe`]; when `allow_file_changed` is set (`--force` with GNU tar), GNU +/// tar's exit status 1 ("file changed as we read it") is accepted once the +/// tar stream itself reached its end and the writer succeeded. +fn pipe_with(mut from: Command, mut to: Command, from_ctx: &str, allow_file_changed: bool, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { let mut from = from.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; let mut out = from.stdout.take().ok_or_else(|| io::Error::other("no output from docker"))?; let mut to = match to.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn() { @@ -205,7 +213,8 @@ fn pipe(mut from: Command, mut to: Command, from_ctx: &str, retar: impl FnOnce(& } drop((out, into)); let written = to.wait()?.success(); - let read = from.wait()?.success(); + let from_status = from.wait()?; + let read = from_status.success() || (allow_file_changed && copied.is_ok() && from_status.code() == Some(1)); let to_said = to_said.join().unwrap_or_default(); let from_said = from_said.join().unwrap_or_default(); // A writer that stopped reading breaks the reader's pipe: its reason first. @@ -359,10 +368,34 @@ fn retar(mut from: impl Read, mut to: impl Write, name: Option<&str>) -> io::Res } } -/// Official images with `tar` and `sh`: one of these does Kiri's half of a -/// volume copy. +/// Official images with `tar` and `sh`: any of these can inspect volumes or +/// unpack when offline; the GNU tar ones ([`GNU_TAR_IMAGES`]) preserve +/// extended attributes on both ends of a volume copy (#485). const TAR_IMAGES: [&str; 4] = ["alpine", "busybox", "debian", "ubuntu"]; +/// BusyBox tar (alpine, busybox) silently drops `user.*` xattrs, which is +/// where Supabase Storage keeps object metadata: reads then fail with +/// ENODATA. Both ends of a volume copy use an official GNU tar image (#485). +const GNU_TAR_IMAGES: [&str; 2] = ["debian", "ubuntu"]; + +/// xattrs travel as pax records: the format and `--xattrs` are both needed +/// when writing them, and `--numeric-owner` keeps raw UID/GID across +/// differing `/etc/passwd` tables. Passed as argv, so `*` is literal. +const STORE_XATTRS: [&str; 4] = ["--numeric-owner", "--format=pax", "--xattrs", "--xattrs-include=*"]; + +/// Only `user.*` is portable to apply on the other engine; system-defined +/// namespaces (security, trusted) are not (GNU tar's extraction default). +/// `--numeric-owner` keeps raw UID/GID across differing `/etc/passwd` tables. +const RESTORE_XATTRS: &str = "--numeric-owner --xattrs '--xattrs-include=user.*'"; + +/// Whether an official image name is one of [`GNU_TAR_IMAGES`]. An +/// official digest for the very same repository is checked separately in +/// [`pick_helper_matching`], so a look-alike still cannot be run (#506). +fn gnu_tar(name: &str) -> bool { + let repo = name.rsplit_once(':').filter(|(_, tag)| !tag.contains('/')).map_or(name, |(r, _)| r); + GNU_TAR_IMAGES.iter().any(|base| repo == *base || repo.ends_with(&format!("/{base}"))) +} + /// Whether a `RepoDigests` entry shows the engine pulled the image from an /// official repository of [`TAR_IMAGES`]: Docker Hub's, or one of its two /// public mirrors, by digest. A name or a tag says nothing (anyone can give @@ -377,55 +410,142 @@ fn official(repo_digest: &str) -> bool { homes.iter().any(|home| repo.strip_prefix(home).is_some_and(|base| TAR_IMAGES.contains(&base))) } -/// The name to run Kiri's half of a volume copy by: a `repo:tag` of the -/// first of `images` (Kiri's image list: `RepoTags`, `RepoDigests`) whose +/// A `repo:tag` of the first of `images` (`RepoTags`, `RepoDigests`) whose /// own record shows it was pulled under that name from an official -/// repository ([`official`]). Run by that name, it is that record. -fn pick_helper(images: &[Value]) -> Option { +/// repository ([`official`]). When `only_gnu` is set, only [`GNU_TAR_IMAGES`] +/// qualify. +fn pick_helper_matching(images: &[Value], only_gnu: bool) -> Option { let strings = |v: &Value| v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::>(); images.iter().find_map(|i| { let digests = strings(&i["RepoDigests"]); strings(&i["RepoTags"]).into_iter().find(|name| { let Some((repo, _)) = name.rsplit_once(':').filter(|(_, tag)| !tag.is_empty() && !tag.contains('/')) else { return false }; - digests.iter().any(|d| official(d) && d.split_once('@').is_some_and(|(r, _)| r == repo)) + (!only_gnu || gnu_tar(name)) && digests.iter().any(|d| official(d) && d.split_once('@').is_some_and(|(r, _)| r == repo)) }) }) } -/// [`pick_helper`] of the images Kiri has, read once from its API. -fn helper_in_kiri() -> io::Result> { +/// Official GNU tar helper (`debian`, `ubuntu`), verified by digest (#506). +fn pick_gnu_helper(images: &[Value]) -> Option { + pick_helper_matching(images, true) +} + +/// The name to run a volume helper by: an official GNU tar image when +/// present, else any official [`TAR_IMAGES`] image (for volume inspection or +/// offline fallback). +fn pick_helper(images: &[Value]) -> Option { + pick_gnu_helper(images).or_else(|| pick_helper_matching(images, false)) +} + +/// Kiri's image records (`RepoTags`, `RepoDigests`), read once from its API. +fn kiri_images() -> io::Result> { let r = client::request("GET", "/images/json", None)?; if !r.ok() { return Err(io::Error::other(format!("kiri: {}", r.error()))); } - Ok(r.json().as_array().and_then(|images| pick_helper(images))) + Ok(r.json().as_array().cloned().unwrap_or_default()) +} + +/// [`pick_helper`] of the images Kiri has (GNU tar preferred, else +/// alpine/busybox). +fn helper_in_kiri() -> io::Result> { + Ok(pick_helper(&kiri_images()?)) +} + +/// [`pick_gnu_helper`] of the images Kiri has (official debian/ubuntu only). +fn gnu_helper_in_kiri() -> io::Result> { + Ok(pick_gnu_helper(&kiri_images()?)) } -/// When Kiri last failed to fetch a helper: tried once per import, not -/// once per volume. +/// Pull an official GNU tar image (`debian:trixie`) into `ctx`, preferring +/// public mirrors over Docker Hub and never overwriting an existing local +/// `debian:trixie` tag. +fn pull_gnu_image(ctx: &str) -> bool { + let pull = |name: &str| { + cli().is_ok_and(|mut c| { + c.args(["--context", ctx, "pull", "-q", name]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }) + }; + pull("mirror.gcr.io/library/debian:trixie") + || pull("public.ecr.aws/docker/library/debian:trixie") + || (!has(ctx, "image", "debian:trixie") && pull("debian:trixie")) +} + +/// When Kiri last failed to fetch a GNU tar helper: tried once per import, +/// not once per volume. static PULL_FAILED: std::sync::Mutex> = std::sync::Mutex::new(None); -/// [`helper_in_kiri`], else busybox fetched by Kiri: from the public mirror, -/// else from Docker Hub when no image of the person's is called that. -/// Nothing is taken from the source. +/// [`gnu_helper_in_kiri`], else Debian fetched by Kiri: from a public mirror, +/// else from Docker Hub when no image of the person's is called that. When +/// offline, falls back to an official `alpine`/`busybox` already in Kiri so +/// volume import still works without xattrs (#376). Nothing is taken from +/// the source. fn helper() -> io::Result { - if let Some(name) = helper_in_kiri()? { + if let Some(name) = gnu_helper_in_kiri()? { return Ok(name); } - let none = || io::Error::other("Kiri needs one small official image to unpack volumes with: pull alpine or busybox in Kiri (docker pull alpine) and import again. A re-tagged or loaded copy does not count"); + let none = || io::Error::other("Kiri needs one official GNU tar image to unpack volumes with: pull debian in Kiri (docker pull debian:trixie) and import again. A re-tagged or loaded copy does not count"); let mut failed = PULL_FAILED.lock().unwrap_or_else(|e| e.into_inner()); if failed.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(60)) { - return Err(none()); + return helper_in_kiri()?.ok_or_else(none); } let kiri = crate::flavor::CONTEXT.get(); - let pull = |name: &str| cli().is_ok_and(|mut c| c.args(["--context", kiri, "pull", "-q", name]).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())); - if (pull("mirror.gcr.io/library/busybox") || (!has(kiri, "image", "busybox:latest") && pull("busybox"))) - && let Some(name) = helper_in_kiri()? + if pull_gnu_image(kiri) + && let Some(name) = gnu_helper_in_kiri()? { return Ok(name); } *failed = Some(std::time::Instant::now()); - Err(none()) + helper_in_kiri()?.ok_or_else(none) +} + +/// Official GNU tar image already present on the source engine `ctx`, +/// verified by `RepoDigests` just like Kiri's helper (#506). +fn gnu_helper_in_source(ctx: &str) -> io::Result> { + let rows = json_lines(ctx, &["image", "ls", "--no-trunc", "--format", "{{json .}}"])?; + let mut ids: Vec = Vec::new(); + for v in &rows { + let repo = v["Repository"].as_str().unwrap_or(""); + let id = v["ID"].as_str().unwrap_or(""); + if !id.is_empty() && gnu_tar(repo) && !ids.iter().any(|x| x == id) { + ids.push(id.to_owned()); + } + } + if ids.is_empty() { + return Ok(None); + } + let mut args = vec!["image", "inspect", "--format", r#"{"RepoTags":{{json .RepoTags}},"RepoDigests":{{json .RepoDigests}}}"#]; + let id_refs: Vec<&str> = ids.iter().map(String::as_str).collect(); + args.extend(id_refs); + let inspected = json_lines_found(ctx, &args)?; + Ok(pick_gnu_helper(&inspected)) +} + +/// When pulling the source's GNU tar helper last failed: `(context, when)`. +static SRC_PULL_FAILED: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// An official GNU tar image on `ctx`, pulled if needed and verified by +/// `RepoDigests` (#485, #506). Returns `None` when offline or unable to pull, +/// so volume copy falls back to `docker cp` instead of failing (#376). +fn source_gnu_helper(ctx: &str) -> io::Result> { + if let Some(name) = gnu_helper_in_source(ctx)? { + return Ok(Some(name)); + } + let mut failed = SRC_PULL_FAILED.lock().unwrap_or_else(|e| e.into_inner()); + if failed.as_ref().is_some_and(|(c, t)| c == ctx && t.elapsed() < std::time::Duration::from_secs(60)) { + return Ok(None); + } + if pull_gnu_image(ctx) + && let Some(name) = gnu_helper_in_source(ctx)? + { + return Ok(Some(name)); + } + *failed = Some((ctx.to_owned(), std::time::Instant::now())); + Ok(None) } /// The label on the containers an import makes for itself. @@ -544,8 +664,8 @@ pub fn volume_with(source: &str, name: &str, force: bool) -> io::Result<()> { return Err(io::Error::other(why)); } let img = match kiri_img { - Some(img) => img, - None => helper()?, + Some(img) if gnu_tar(&img) => img, + _ => helper()?, }; if state.is_none() { state = Some(kiri_states(&[name.to_owned()], &img)?[0].1); @@ -569,61 +689,111 @@ pub fn volume_with(source: &str, name: &str, force: bool) -> io::Result<()> { return Err(io::Error::other(why)); } } - // Nothing runs on the source: a container that is made and never - // started mounts the volume read-only (`volume-nocopy`: its image's - // files don't go in), from any image there and never pulled, and - // `docker cp` reads it as an archive with owners, modes and links as - // they are. It goes after, with any anonymous volume its image made; - // one an import that was stopped left behind goes first. - let names = image_names(ctx)?; - let reader_image = match names.first() { - Some(n) => n.clone(), - None => json_lines(ctx, &["image", "ls", "--format", "{{json .ID}}"])? - .first() - .and_then(|v| v.as_str().map(str::to_owned)) - .ok_or_else(|| io::Error::other(format!("{ctx} has no image to read volumes through; pull any image there and import again")))?, - }; + let src_gnu = if gnu_tar(&img) { source_gnu_helper(ctx)? } else { None }; let reader = format!("kiri-import-{name}"); let leftover = json_lines(ctx, &["inspect", "--type", "container", "--format", "{{json .Config.Labels}}", &reader]).unwrap_or_default(); if leftover.first().is_some_and(|l| l["dev.kiri.import-helper"] == "1") { let _ = cli()?.args(["--context", ctx, "rm", "-fv", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); } - // At a path no image can have a VOLUME of its own at or under. - use std::hash::BuildHasher; - let at = format!("/kiri-import-{:016x}", std::collections::hash_map::RandomState::new().hash_one(name)); - let mount = format!("type=volume,src={name},dst={at},readonly,volume-nocopy"); - let made = cli()? - .args(["--context", ctx, "create", "--name", &reader, "--pull", "never", "--network", "none", "--label", HELPER, "--entrypoint", &at, "--mount", &mount, &reader_image]) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .output()?; - if !made.status.success() { - return Err(io::Error::other(format!("{ctx}: {}", String::from_utf8_lossy(&made.stderr).trim()))); - } - let copied = copy_volume(ctx, &format!("{reader}:{at}/."), name, &img); - let _ = cli()?.args(["--context", ctx, "rm", "-v", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + let copied = if let Some(src_img) = src_gnu { + // GNU tar in an official helper on the source reads the volume + // read-only (`volume-nocopy`: no image files go in) and puts numeric + // owners and `user.*` xattrs in the stream; `docker cp` leaves xattrs + // out (#485). + let mount = format!("type=volume,src={name},dst=/from,readonly,volume-nocopy"); + let mut read = cli()?; + read.args(volume_reader_args(ctx, &reader, &mount, &src_img)); + let r = copy_volume(read, ctx, name, &img, force); + if r.is_err() { + let _ = cli()?.args(["--context", ctx, "rm", "-fv", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + r + } else { + // Offline / no official GNU tar helper on both engines: fall back to + // a stopped reader + `docker cp` so volume import still works (#376) + // without running any unverified image on the source (#506). + eprintln!("kiri: importing volume {name} without extended attributes (no official Debian or Ubuntu image available on both engines)"); + let names = image_names(ctx)?; + let reader_image = match names.first() { + Some(n) => n.clone(), + None => json_lines(ctx, &["image", "ls", "--format", "{{json .ID}}"])? + .first() + .and_then(|v| v.as_str().map(str::to_owned)) + .ok_or_else(|| io::Error::other(format!("{ctx} has no image to read volumes through; pull any image there and import again")))?, + }; + // At a path no image can have a VOLUME of its own at or under. + use std::hash::BuildHasher; + let at = format!("/kiri-import-{:016x}", std::collections::hash_map::RandomState::new().hash_one(name)); + let mount = format!("type=volume,src={name},dst={at},readonly,volume-nocopy"); + let made = cli()? + .args(["--context", ctx, "create", "--name", &reader, "--pull", "never", "--network", "none", "--label", HELPER, "--entrypoint", &at, "--mount", &mount, &reader_image]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output()?; + if !made.status.success() { + return Err(io::Error::other(format!("{ctx}: {}", String::from_utf8_lossy(&made.stderr).trim()))); + } + let mut read = cli()?; + read.args(["--context", ctx, "cp", &format!("{reader}:{at}/."), "-"]); + let r = copy_volume(read, ctx, name, &img, false); + let _ = cli()?.args(["--context", ctx, "rm", "-v", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + r + }; copied.map_err(|e| io::Error::other(format!("{e}; {name} is unfinished in Kiri: the next import empties it and copies it again, replacing what is in it then"))) } -/// `docker cp` out of the reader on the source, through [`retar`], untarred -/// into the volume by a helper on Kiri that removes itself. The helper -/// marks the volume unfinished first (emptying what an unfinished copy -/// left), and the mark goes only once every part of the copy succeeded. -fn copy_volume(ctx: &str, from: &str, name: &str, img: &str) -> io::Result<()> { +/// GNU tar in an official helper on the source, streaming the volume with +/// numeric owners and xattrs. `--entrypoint tar` guarantees the image's own +/// entrypoint never runs instead of `tar`. +fn volume_reader_args<'a>(ctx: &'a str, reader: &'a str, mount: &'a str, img: &'a str) -> Vec<&'a str> { + let mut args = vec![ + "--context", + ctx, + "run", + "--rm", + "--name", + reader, + "--network", + "none", + "--label", + HELPER, + "--pull", + "never", + "--mount", + mount, + "--entrypoint", + "tar", + img, + ]; + args.extend(STORE_XATTRS); + args.extend(["-C", "/from", "-cf", "-", "."]); + args +} + +/// Shell script run in Kiri's helper container to clear an unfinished copy, +/// mark the volume unfinished, and unpack the tar stream from stdin. +fn restore_script(with_gnu_tar: bool) -> String { + let flags = if with_gnu_tar { format!(" {RESTORE_XATTRS}") } else { String::new() }; + format!( + r#"set -e; cd /to; if [ -e {m} ]; then find . -mindepth 1 -maxdepth 1 ! -name {m} -exec rm -rf -- {{}} + || true; for f in .[!.]* ..?* *; do if [ "$f" != {m} ] && {{ [ -e "$f" ] || [ -L "$f" ]; }}; then echo "could not empty the volume: $f is left" >&2; exit 1; fi; done; fi; touch {m}; tar{flags} -xpf -"#, + m = UNFINISHED + ) +} + +/// A tar stream out of the reader on the source, through [`retar`], untarred +/// into the volume by a helper on Kiri that removes itself. The helper marks +/// the volume unfinished first (emptying what an unfinished copy left), and +/// the mark goes only once every part of the copy succeeded. +fn copy_volume(read: Command, ctx: &str, name: &str, img: &str, allow_file_changed: bool) -> io::Result<()> { let kiri = crate::flavor::CONTEXT.get(); let dst_mount = format!("{name}:/to"); - let mut read = cli()?; - read.args(["--context", ctx, "cp", from, "-"]); let mut write = cli()?; // Emptied in one pass, all but the mark (a folder by that name counts as // it); anything still there after, hidden names too, stops the copy with // the mark left on. - let script = format!( - r#"set -e; cd /to; if [ -e {m} ]; then find . -mindepth 1 -maxdepth 1 ! -name {m} -exec rm -rf -- {{}} + || true; for f in .[!.]* ..?* *; do if [ "$f" != {m} ] && {{ [ -e "$f" ] || [ -L "$f" ]; }}; then echo "could not empty the volume: $f is left" >&2; exit 1; fi; done; fi; touch {m}; tar -xpf -"#, - m = UNFINISHED - ); + let script = restore_script(gnu_tar(img)); write.args(["--context", kiri, "run", "--rm", "-i", "--network", "none", "--label", HELPER, "-v", &dst_mount, "--pull", "never", "--entrypoint", "sh", img, "-c", &script]); - pipe(read, write, ctx, |from, to| retar(from, to, None))?; + pipe_with(read, write, ctx, allow_file_changed, |from, to| retar(from, to, None))?; let done = cli()?.args(["--context", kiri, "run", "--rm", "--network", "none", "--label", HELPER, "-v", &dst_mount, "--pull", "never", "--entrypoint", "rm", img, "-rf", "--", &format!("/to/{UNFINISHED}")]).stdout(Stdio::null()).stderr(Stdio::piped()).output()?; if !done.status.success() { return Err(io::Error::other(format!("kiri: {}", String::from_utf8_lossy(&done.stderr).trim()))); @@ -974,12 +1144,14 @@ mod tests { assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything, false)); } - // Kiri's half of a volume copy runs only an image the engine pulled - // from an official repository, as its repo digests show: never one - // that only has a name like one, wherever it came from. + // Volume helpers run only an image the engine pulled from an official + // repository, as its repo digests show: never one that only has a name + // like one, wherever it came from (#506). GNU tar helpers (debian, ubuntu) + // are preferred over alpine/busybox (#485); alpine/busybox remain a + // fallback for inspection or offline use (#376). #[test] fn only_an_official_image_helps() { - use super::{official, pick_helper}; + use super::{official, pick_gnu_helper, pick_helper}; use serde_json::json; let d = format!("@sha256:{}", "ab12".repeat(16)); for good in ["busybox", "library/alpine", "docker.io/library/debian", "mirror.gcr.io/library/ubuntu", "public.ecr.aws/docker/library/busybox"] { @@ -988,8 +1160,10 @@ mod tests { let look_alikes = [ "ghcr.io/x/library/busybox", "localhost:5000/library/alpine", + "localhost:5000/debian", "localhost/x/library/busybox", "evil/alpine", + "evil/debian", "docker.io/evil/alpine", "mirror.gcr.io/evil/library/alpine", "public.ecr.aws/x/library/alpine", @@ -1003,26 +1177,160 @@ mod tests { for bad in ["busybox", "busybox:1", "busybox@sha256:abc", &format!("busybox@sha512:{}", "a".repeat(64)), &format!("busybox@sha256:{}", "A".repeat(64))] { assert!(!official(bad), "{bad}"); } - // Kiri's image list: one record per name, each with its own digests. + // Image list: one record per name, each with its own digests. let rec = |name: &str, digests: &[String]| json!({"Id": format!("sha256:{}", "c".repeat(64)), "RepoTags": [name], "RepoDigests": digests}); let records = [ // Untagged: a load or build without a name. rec(&format!("sha256:{}", "c".repeat(64)), &[]), rec("localhost/imp-x/library/busybox:9", &[]), - // Re-tagged from the official one: no digest of its own. + // Re-tagged from an official image: no digest of its own. rec("alpine:latest", &[]), - // Called busybox, its digest another repository's. + rec("debian:trixie", &[]), + // Called busybox/debian, its digest another repository's. rec("busybox:1", &[format!("evil/tools{d}")]), + rec("debian:1", &[format!("evil/debian{d}")]), // An official digest under a name of another repository. rec("evil/alpine:1", &[format!("alpine{d}")]), + rec("evil/debian:1", &[format!("debian{d}")]), rec("ghcr.io/x/library/busybox:1", &[format!("ghcr.io/x/library/busybox{d}")]), rec("mirror.gcr.io/library/alpine:latest", &[format!("mirror.gcr.io/library/alpine{d}")]), rec("busybox:latest", &[format!("busybox{d}")]), + // Official GNU tar images: preferred over alpine/busybox. + rec("mirror.gcr.io/library/debian:latest", &[format!("mirror.gcr.io/library/debian{d}")]), + rec("ubuntu:latest", &[format!("ubuntu{d}")]), ]; - assert_eq!(pick_helper(&records), Some("mirror.gcr.io/library/alpine:latest".into())); - assert_eq!(pick_helper(&records[..6]), None); - assert_eq!(pick_helper(&records[7..]), Some("busybox:latest".into())); - assert_eq!(pick_helper(&[json!({"RepoTags": null, "RepoDigests": [format!("busybox{d}")]})]), None); + assert_eq!(pick_helper(&records), Some("mirror.gcr.io/library/debian:latest".into())); + assert_eq!(pick_gnu_helper(&records), Some("mirror.gcr.io/library/debian:latest".into())); + assert_eq!(pick_helper(&records[..9]), None); + assert_eq!(pick_gnu_helper(&records[..11]), None); + // Offline fallback: alpine/busybox still work for pick_helper when no GNU tar image is present. + assert_eq!(pick_helper(&records[..11]), Some("mirror.gcr.io/library/alpine:latest".into())); + assert_eq!(pick_helper(&records[10..11]), Some("busybox:latest".into())); + assert_eq!(pick_gnu_helper(&records[12..]), Some("ubuntu:latest".into())); + assert_eq!(pick_helper(&[json!({"RepoTags": null, "RepoDigests": [format!("debian{d}")]})]), None); + } + + // #485: both ends of a volume copy carry xattrs and numeric owners when + // using GNU tar helpers, pass `--entrypoint tar` on the source, and fall + // back to plain `tar -xpf -` when an offline helper is alpine/busybox. + #[test] + fn volume_copy_keeps_xattrs() { + assert!(super::gnu_tar("debian:trixie")); + assert!(super::gnu_tar("debian")); + assert!(super::gnu_tar("mirror.gcr.io/library/ubuntu:24.04")); + assert!(super::gnu_tar("public.ecr.aws/docker/library/debian:trixie")); + assert!(super::gnu_tar("localhost:5000/debian")); + assert!(!super::gnu_tar("alpine:latest")); + assert!(!super::gnu_tar("busybox:latest")); + assert!(!super::gnu_tar("mydebian:latest")); + let args = super::volume_reader_args("desktop-linux", "kiri-import-pg", "type=volume,src=pg,dst=/from,readonly,volume-nocopy", "debian:trixie"); + let ep = args.iter().position(|a| *a == "--entrypoint").expect("missing --entrypoint"); + assert_eq!(args.get(ep + 1), Some(&"tar")); + assert_eq!(args.get(ep + 2), Some(&"debian:trixie")); + for flag in super::STORE_XATTRS { + assert!(args.contains(&flag), "missing {flag}"); + } + assert!(args.contains(&"--numeric-owner")); + assert!(args.contains(&"--network")); + assert!(args.contains(&"none")); + assert!(args.contains(&"--pull")); + assert!(args.contains(&"never")); + let gnu_script = super::restore_script(true); + assert!(gnu_script.contains("--numeric-owner"), "{gnu_script}"); + assert!(gnu_script.contains("--xattrs"), "{gnu_script}"); + assert!(gnu_script.contains("'--xattrs-include=user.*'"), "{gnu_script}"); + assert!(gnu_script.ends_with(" -xpf -"), "{gnu_script}"); + let fallback_script = super::restore_script(false); + assert!(!fallback_script.contains("--xattrs"), "{fallback_script}"); + assert!(fallback_script.ends_with("tar -xpf -"), "{fallback_script}"); + } + + // #485: `retar` passes `SCHILY.xattr.*` pax records through byte-for-byte + // (including JSON, empty and binary values) while still propagating high + // uid/gid into the ustar header. + #[cfg(not(windows))] + #[test] + fn retar_preserves_xattr_pax_records() { + let mut b = tar::Builder::new(Vec::new()); + let json_meta = br#"{"contentType":"image/png","cacheControl":"max-age=3600"}"#; + b.append_pax_extensions([ + ("SCHILY.xattr.user.test", &b"hello-xattr"[..]), + ("SCHILY.xattr.user.metadata", json_meta.as_slice()), + ("SCHILY.xattr.user.empty", &b""[..]), + ("uid", &b"3000000"[..]), + ("gid", &b"3000001"[..]), + ]) + .unwrap(); + let mut h = tar::Header::new_ustar(); + h.set_size(5); + h.set_mode(0o640); + h.set_uid(0); + h.set_gid(0); + h.set_cksum(); + b.append_data(&mut h, "obj", &b"hello"[..]).unwrap(); + // Second entry with a binary xattr value containing NUL, high bytes + // and a newline followed by `size=99` (must not spoof the entry size). + let bin_val = b"\x00\xff\nsize=99"; + b.append_pax_extensions([("SCHILY.xattr.user.bin", bin_val.as_slice()), ("uid", &b"1234"[..])]).unwrap(); + let mut h2 = tar::Header::new_ustar(); + h2.set_size(2); + h2.set_mode(0o600); + h2.set_cksum(); + b.append_data(&mut h2, "bin", &b"ok"[..]).unwrap(); + let input = b.into_inner().unwrap(); + let mut out = Vec::new(); + super::retar(input.as_slice(), &mut out, None).unwrap(); + assert_eq!(out.len(), input.len()); + // The pax blocks pass through byte-for-byte unchanged, including binary values. + assert_eq!(out[..1024], input[..1024]); + assert!(out.windows(bin_val.len()).any(|w| w == bin_val)); + let mut ar = tar::Archive::new(out.as_slice()); + let mut e = ar.entries().unwrap().next().unwrap().unwrap(); + assert_eq!(e.header().uid().unwrap(), 3_000_000); + assert_eq!(e.header().gid().unwrap(), 3_000_001); + let exts: Vec<(String, Vec)> = e + .pax_extensions() + .unwrap() + .unwrap() + .map(|r| { + let r = r.unwrap(); + (r.key().unwrap().to_owned(), r.value_bytes().to_vec()) + }) + .collect(); + assert!(exts.contains(&("SCHILY.xattr.user.test".into(), b"hello-xattr".to_vec())), "{exts:?}"); + assert!(exts.contains(&("SCHILY.xattr.user.metadata".into(), json_meta.to_vec())), "{exts:?}"); + assert!(exts.contains(&("SCHILY.xattr.user.empty".into(), Vec::new())), "{exts:?}"); + } + + // Source tar failures fail the import rather than silently importing a + // partial volume; only `--force` (`allow_file_changed`) tolerates GNU tar + // exit code 1 after a complete, valid archive. + #[cfg(not(windows))] + #[test] + fn pipe_propagates_reader_and_writer_errors() { + use std::process::Command; + let sh = |script: &str| { + let mut c = Command::new("sh"); + c.args(["-c", script]); + c + }; + let empty_tar = "dd if=/dev/zero bs=1024 count=1 2>/dev/null"; + let sink = "cat >/dev/null"; + // Clean stream, both exit 0: ok. + super::pipe_with(sh(empty_tar), sh(sink), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap(); + // Source exits 1 without allow_file_changed: error. + let err = super::pipe_with(sh(&format!("{empty_tar}; echo changed >&2; exit 1")), sh(sink), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("changed"), "{err}"); + // Source exits 1 WITH allow_file_changed and complete tar: ok. + super::pipe_with(sh(&format!("{empty_tar}; echo changed >&2; exit 1")), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).unwrap(); + // Source exits 1 WITH allow_file_changed but truncated/empty output: error. + assert!(super::pipe_with(sh("echo boom >&2; exit 1"), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).is_err()); + // Source exits 2 (fatal tar error) even WITH allow_file_changed: error. + let err = super::pipe_with(sh(&format!("{empty_tar}; echo fatal >&2; exit 2")), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("fatal"), "{err}"); + // Writer exits non-zero: error. + let err = super::pipe_with(sh(empty_tar), sh("cat >/dev/null; echo diskfull >&2; exit 1"), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("diskfull"), "{err}"); } // #377: an image only pinned by digest is listed by that reference. diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 431cc22eb..7ec0e7524 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 +### #524 Import: keep volume xattrs with GNU tar (unreleased) +- Fixes: #485 kiri import loses user.* extended attributes on named volumes (Supabase Storage 500 ENODATA) +- Caused: none known +- Caused by: - +- Check: `import-volume-xattrs` + ### #137 Archives: preserve directory-contents paths for docker cp (unreleased) - Fixes: #617 `docker cp container:/dir/. dest` copies the folder itself instead of its contents - Caused: none known diff --git a/tests/import.sh b/tests/import.sh index b76711797..59919f10e 100755 --- a/tests/import.sh +++ b/tests/import.sh @@ -62,8 +62,9 @@ ANON=() PINNED= PINNED_OURS= PINNED_KIRI_OURS= -# What Kiri has before: read once both engines answer. Until then the -# cleanup removes no image from Kiri. +# What both engines have before: read once both answer. Until then cleanup +# removes no image that wasn't explicitly fetched here. +SRC_HAD= KIRI_HAD= # A Kiri container of ours goes with the 64-hex volumes the import gave it. kiri_rm() { @@ -80,7 +81,7 @@ OURS_C="imp-digest imp-net-joiner imp-net-target imp-vol-user imp-vol-writer imp LOOKALIKE=localhost/imp-x/library/busybox:9 UNTAGGED_ID= LA_DIR= -OURS_V="imp-vol-la imp-vol-la-new imp-vol-data imp-vol-named imp-vol-keep imp-vol-busy imp-vol-huge imp-vol-cut imp-probe" +OURS_V="imp-vol-la imp-vol-la-new imp-vol-data imp-vol-xattrs imp-vol-named imp-vol-keep imp-vol-busy imp-vol-huge imp-vol-cut imp-probe" cleanup() { kiri_rm $OURS_C "${S[@]}" rm -fv $OURS_C >/dev/null 2>&1 @@ -98,11 +99,17 @@ cleanup() { [ -n "$PINNED_OURS" ] && "${S[@]}" rmi "$PINNED" >/dev/null 2>&1 for i in ${FETCHED_SRC[@]+"${FETCHED_SRC[@]}"}; do "${S[@]}" rmi "$i" >/dev/null 2>&1; done for i in ${FETCHED_KIRI[@]+"${FETCHED_KIRI[@]}"}; do "${K[@]}" rmi "$i" >/dev/null 2>&1; done - # What the imports brought into Kiri: the test image, helper images. + # What the imports brought into either engine: the test image, helper images. + if [ -n "$SRC_HAD" ]; then + for i in $("${S[@]}" image ls --format '{{.Repository}}:{{.Tag}}' 2>/dev/null); do + [[ "$SRC_HAD" == *" $i "* ]] && continue + [[ "$i" =~ ^((mirror\.gcr\.io|public\.ecr\.aws/docker)/library/)?(alpine|busybox|debian|ubuntu): ]] && "${S[@]}" rmi "$i" >/dev/null 2>&1 + done + fi [ -n "$KIRI_HAD" ] || return 0 for i in $("${K[@]}" image ls --format '{{.Repository}}:{{.Tag}}' 2>/dev/null); do [[ "$KIRI_HAD" == *" $i "* ]] && continue - [[ "$i" == "$TOOL" || "$i" =~ ^(alpine|busybox|debian|ubuntu): ]] && "${K[@]}" rmi "$i" >/dev/null 2>&1 + [[ "$i" == "$TOOL" || "$i" =~ ^((mirror\.gcr\.io|public\.ecr\.aws/docker)/library/)?(alpine|busybox|debian|ubuntu): ]] && "${K[@]}" rmi "$i" >/dev/null 2>&1 done } cleanup @@ -110,6 +117,8 @@ trap cleanup EXIT "${S[@]}" version >/dev/null 2>&1 || { echo "import: the source $SRC does not answer"; exit 1; } "${K[@]}" version >/dev/null 2>&1 || { echo "import: Kiri ($DOCKER_CONTEXT) does not answer"; exit 1; } +had=$("${S[@]}" image ls --format '{{.Repository}}:{{.Tag}}') || { echo "import: could not list $SRC's images"; exit 1; } +SRC_HAD=" $(echo "$had" | tr '\n' ' ') " had=$("${K[@]}" image ls --format '{{.Repository}}:{{.Tag}}') || { echo "import: could not list Kiri's images"; exit 1; } KIRI_HAD=" $(echo "$had" | tr '\n' ' ') " # The kiri under test must be the Kiri under test: else imports would land @@ -215,6 +224,41 @@ got=$("${K[@]}" run --rm --network none -v imp-vol-data:/d:ro alpine sh -c "$LIS t vol-exact-copy "same files" bash -c '[ "$1" = "$2" ] && echo "same files" || diff <(echo "$1") <(echo "$2")' _ "$want" "$got" t vol-copy-has-files "hard" echo "$got" +section "#485 volume import keeps user.* extended attributes (Supabase Storage)" +fetch "$SRC" python:3.13-alpine || { echo "import: could not get python:3.13-alpine on $SRC"; exit 1; } +fetch "$DOCKER_CONTEXT" python:3.13-alpine || { echo "import: could not get python:3.13-alpine on Kiri"; exit 1; } +"${S[@]}" volume create imp-vol-xattrs >/dev/null +"${S[@]}" run --rm --network none -v imp-vol-xattrs:/d python:3.13-alpine python3 -c ' +import os +os.makedirs("/d/sub", exist_ok=True) +with open("/d/obj", "wb") as f: f.write(b"supabase-blob") +os.chmod("/d/obj", 0o640) +os.chown("/d/obj", 1234, 5678) +os.setxattr("/d/obj", "user.test", b"hello-xattr") +os.setxattr("/d/obj", "user.metadata", b"{\"contentType\":\"image/png\"}") +os.setxattr("/d/obj", "user.empty", b"") +os.setxattr("/d/sub", "user.dir", b"dir-val") +with open("/d/far", "wb") as f: f.write(b"far") +os.chown("/d/far", 3000000, 3000001) +os.setxattr("/d/far", "user.highuid", b"ok") +' +t import-volume-xattrs-runs "volume imp-vol-xattrs: done" "$KIRI" import "$SRC" volume imp-vol-xattrs +t import-volume-xattrs "xattrs-ok" "${K[@]}" run --rm --network none -v imp-vol-xattrs:/d:ro python:3.13-alpine python3 -c ' +import os, stat +st = os.lstat("/d/obj") +assert open("/d/obj", "rb").read() == b"supabase-blob" +assert stat.S_IMODE(st.st_mode) == 0o640 +assert (st.st_uid, st.st_gid) == (1234, 5678) +assert os.getxattr("/d/obj", "user.test") == b"hello-xattr" +assert os.getxattr("/d/obj", "user.metadata") == b"{\"contentType\":\"image/png\"}" +assert os.getxattr("/d/obj", "user.empty") == b"" +assert os.getxattr("/d/sub", "user.dir") == b"dir-val" +fst = os.lstat("/d/far") +assert (fst.st_uid, fst.st_gid) == (3000000, 3000001) +assert os.getxattr("/d/far", "user.highuid") == b"ok" +print("xattrs-ok") +' + section "#376 an empty volume in Kiri is not \"already in Kiri\"; a container brings its volumes" "${S[@]}" volume create imp-vol-named >/dev/null "${S[@]}" run --name imp-vol-user --network none --entrypoint sh -v imp-vol-named:/named -v /anon "$TOOL" -c 'echo named > /named/f; echo anon > /anon/f' @@ -254,13 +298,13 @@ else cut() { "$@" > /tmp/imp-cut.$$ 2>&1 & local pid=$! i - for i in $(seq 300); do pgrep -f "kiri-import-imp-vol-cut:|imp-vol-cut:/from" >/dev/null && break; sleep 0.1; done + for i in $(seq 300); do pgrep -f "kiri-import-imp-vol-cut|imp-vol-cut:/from" >/dev/null && break; sleep 0.1; done sleep 1 # Kiri's helpers while the copy runs: what each was given and runs. for c in $("${K[@]}" ps -q --filter label=dev.kiri.import-helper=1); do "${K[@]}" inspect -f '{{.Config.Image}} {{.Image}} {{json .Config.Entrypoint}}' "$c" done > /tmp/imp-cut-seen.$$ 2>&1 - pkill -f "kiri-import-imp-vol-cut:|imp-vol-cut:/from" + pkill -f "kiri-import-imp-vol-cut|imp-vol-cut:/from" wait $pid cat /tmp/imp-cut.$$; rm -f /tmp/imp-cut.$$ } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 49359c827..fc1b0c1ed 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -226,3 +226,4 @@ host-services-untouched #420 on a Linux host kiri-init created /run/host-service host-services-ssh-agent-mount #420 containers mounting /run/host-services/ssh-auth.sock must still get the agent's SSH relay socket while the host's /run/host-services is left alone archive-directory-contents #617 GET /containers/{id}/archive normalized away a trailing /., dropped ./ from directory-contents entries, and did not resolve .. by name or keep / on root entries cp-out-dot #617 docker cp container:/out/. dst copied the folder itself (dst/out/a.txt) instead of its contents (dst/a.txt) +import-volume-xattrs #485 kiri import used docker cp and BusyBox tar, silently dropping user.* extended attributes on named volumes (Supabase Storage 500 ENODATA) From 293073470211fc99af23ef229f4e62a08ac58c35 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 15:39:46 +0100 Subject: [PATCH 012/157] Windows: the window's own refresh no longer keeps the VM awake (#668) Co-authored-by: Karthik P --- crates/kiri-win/src/client.rs | 251 +++++++++++++++++++++++++++++++--- crates/kiri-win/src/engine.rs | 38 ++++- crates/kiri-win/src/main.rs | 2 +- crates/kiri-win/src/update.rs | 2 +- docs/fix-registry.md | 6 + 5 files changed, 269 insertions(+), 30 deletions(-) diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index a8e461b2c..fe215bbe6 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -3,14 +3,71 @@ //! crates/kiri/src/client.rs over the unix socket: one short connection //! per request, and long-lived ones for `/events`, logs and stats. +#![cfg_attr(not(windows), allow(dead_code))] + use std::io::{self, BufRead, BufReader, Read, Write}; -use std::sync::{Arc, OnceLock}; +#[cfg(windows)] +use std::sync::Arc; +use std::sync::OnceLock; use std::time::Duration; use serde_json::Value; +#[cfg(windows)] use crate::pipe::Pipe; +#[cfg(test)] +mod mock { + use std::cell::RefCell; + use std::collections::VecDeque; + use std::io::{self, Cursor, Read, Write}; + use std::sync::{Arc, Mutex}; + + pub struct Recorded { + pub wire: Arc>>, + pub reply: Cursor>, + } + + impl Read for Recorded { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reply.read(buf) + } + } + + impl Write for Recorded { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.wire.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + type Queue = VecDeque<(Arc>>, Vec)>; + thread_local! { + static QUEUE: RefCell = const { RefCell::new(VecDeque::new()) }; + } + + pub fn push(reply: &[u8]) -> Arc>> { + let wire = Arc::new(Mutex::new(Vec::new())); + QUEUE.with(|q| q.borrow_mut().push_back((wire.clone(), reply.to_vec()))); + wire + } + + pub fn take() -> Option { + QUEUE.with(|q| q.borrow_mut().pop_front()).map(|(wire, reply)| Recorded { wire, reply: Cursor::new(reply) }) + } +} + +/// Queues one canned HTTP response for the next client call on this thread, +/// returning the buffer that captures the request bytes written to the wire. +#[cfg(test)] +pub(crate) fn mock_reply(reply: &[u8]) -> std::sync::Arc>> { + mock::push(reply) +} + static PIPE: OnceLock = OnceLock::new(); /// The pipe the daemon is served on (once, at start). @@ -23,6 +80,7 @@ pub fn pipe() -> String { PIPE.get().cloned().unwrap_or_else(|| r"\\.\pipe\kiri".to_owned()) } +#[cfg(windows)] fn connect() -> io::Result> { Pipe::open(PIPE.get().map_or(r"\\.\pipe\kiri", String::as_str)).map(Arc::new) } @@ -30,17 +88,49 @@ fn connect() -> io::Result> { /// A connection as a byte stream. With `timeout`, a read that gets nothing /// for that long fails (TimedOut) instead of waiting on: for the ping, which /// gates the engine thread at start and must never hang it. -struct Conn(Arc, Option); +enum Conn { + #[cfg(windows)] + Pipe(Arc, Option), + #[cfg(test)] + Mock(mock::Recorded), +} + +fn open_conn(timeout: Option) -> io::Result { + #[cfg(test)] + if let Some(m) = mock::take() { + let _ = timeout; + return Ok(Conn::Mock(m)); + } + #[cfg(windows)] + { + Ok(Conn::Pipe(connect()?, timeout)) + } + #[cfg(not(windows))] + { + let _ = timeout; + Err(io::Error::new(io::ErrorKind::NotConnected, "no mock response queued")) + } +} impl Read for Conn { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.read_client(buf, self.1) + match self { + #[cfg(windows)] + Conn::Pipe(p, timeout) => p.read_client(buf, *timeout), + #[cfg(test)] + Conn::Mock(m) => m.read(buf), + } } } impl Write for Conn { fn write(&mut self, buf: &[u8]) -> io::Result { - Write::write(&mut &*self.0, buf) + match self { + #[cfg(windows)] + Conn::Pipe(p, _) => Write::write(&mut &**p, buf), + #[cfg(test)] + Conn::Mock(m) => m.write(buf), + } } fn flush(&mut self) -> io::Result<()> { @@ -150,7 +240,7 @@ const QUICK: Duration = Duration::from_secs(3); /// `request_with`, failing (TimedOut) when a read waits longer than `timeout`. pub fn request_within(method: &str, path: &str, body: Option<&Value>, background: bool, timeout: Option) -> io::Result { line_safe(path)?; - let mut s = Conn(connect()?, timeout); + let mut s = open_conn(timeout)?; let payload = body.map(Value::to_string).unwrap_or_default(); write!( s, @@ -193,8 +283,9 @@ pub fn get(path: &str) -> io::Result { } /// A GET of the window's own refresh, failing after QUICK without an answer. +/// Marked as the window's own, so the refresh never keeps the VM awake. pub fn get_quick(path: &str) -> io::Result { - let r = request_within("GET", path, None, false, Some(QUICK))?; + let r = request_within("GET", path, None, true, Some(QUICK))?; if !r.ok() { return Err(io::Error::other(r.error())); } @@ -212,6 +303,7 @@ pub fn get_background(path: &str) -> io::Result { } /// The docker CLI Kiri ships, as the Mac's `docker_cli` (for builds.rs). +#[cfg(windows)] pub fn docker_cli() -> Option { Some(crate::detail::docker_cli()) } @@ -219,11 +311,13 @@ pub fn docker_cli() -> Option { /// A POST whose answer is a stream of JSON lines (`/images/create`), each /// given to `on_line` as it arrives; returns the HTTP status. As the Mac's /// client::post_lines. +#[cfg(windows)] pub fn post_lines(path: &str, on_line: impl FnMut(Value)) -> io::Result { post_lines_with(path, None, on_line) } /// `post_lines` with a registry sign-in (`X-Registry-Auth`, base64url) for a pull. +#[cfg(windows)] pub fn post_lines_with(path: &str, auth: Option<&str>, on_line: impl FnMut(Value)) -> io::Result { post_lines_closable(path, auth, |_| {}, on_line) } @@ -231,6 +325,7 @@ pub fn post_lines_with(path: &str, auth: Option<&str>, on_line: impl FnMut(Value /// `post_lines_with`, handing `opened` a Closer for the connection once it /// is made, so another thread can stop the request (Cancel on a pull). A /// stopped read ends as if the body had. +#[cfg(windows)] pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(Closer), mut on_line: impl FnMut(Value)) -> io::Result { line_safe(path)?; if let Some(a) = auth { @@ -239,7 +334,7 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(C let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); let pipe = connect()?; opened(Closer(pipe.clone())); - let mut s = Conn(pipe, None); + let mut s = Conn::Pipe(pipe, None); write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n")?; let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; @@ -270,21 +365,23 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(C } /// Whether the daemon answers at all, waiting for a start the bridge has -/// under way (Start). +/// under way (Start). Marked as the window's own, as on the Mac, so status +/// and diagnostic checks never keep an idle VM awake. pub fn alive() -> bool { - request_within("GET", "/_ping", None, false, Some(PING_WAIT)).is_ok_and(|r| r.ok()) + request_within("GET", "/_ping", None, true, Some(PING_WAIT)).is_ok_and(|r| r.ok()) } /// `alive`, for the event watcher: false after QUICK without an answer. pub fn alive_quick() -> bool { - request_within("GET", "/_ping", None, false, Some(QUICK)).is_ok_and(|r| r.ok()) + request_within("GET", "/_ping", None, true, Some(QUICK)).is_ok_and(|r| r.ok()) } /// A long-lived streamed response (`/events`, `logs?follow=1`, `stats`), /// read chunk by chunk. `closer` ends it from another thread. #[derive(Debug)] pub struct Stream { - pipe: Arc, + #[cfg(windows)] + pipe: Option>, reader: BufReader, } @@ -304,9 +401,11 @@ impl Read for ConnReader { } /// Ends a Stream's wait from another thread. +#[cfg(windows)] #[derive(Debug, Clone)] pub struct Closer(Arc); +#[cfg(windows)] impl Closer { pub fn close(&self) { self.0.cancel(); @@ -315,20 +414,34 @@ impl Closer { impl Stream { pub fn open(path: &str) -> io::Result { + Self::open_with(path, false) + } + + fn open_with(path: &str, background: bool) -> io::Result { line_safe(path)?; - let pipe = connect()?; - let mut s = Conn(pipe.clone(), None); - write!(s, "GET {path} HTTP/1.1\r\nHost: kiri\r\n\r\n")?; + let mut s = open_conn(None)?; + #[cfg(windows)] + let pipe = match &s { + Conn::Pipe(p, _) => Some(p.clone()), + #[cfg(test)] + Conn::Mock(_) => None, + }; + write!(s, "GET {path} HTTP/1.1\r\nHost: kiri\r\n{}\r\n", background_header(background))?; let mut reader = BufReader::new(ConnReader(s)); let (status, _, chunked) = head(&mut reader)?; if status != 200 || !chunked { return Err(io::Error::other(format!("{path}: HTTP {status}"))); } - Ok(Stream { pipe, reader }) + Ok(Stream { + #[cfg(windows)] + pipe, + reader, + }) } + #[cfg(windows)] pub fn closer(&self) -> Closer { - Closer(self.pipe.clone()) + Closer(self.pipe.as_ref().expect("stream backed by a pipe").clone()) } pub fn next(&mut self) -> Option> { @@ -338,16 +451,16 @@ impl Stream { /// Calls `on_event` for each event until the connection ends or it returns false. pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { - let mut s = Stream::open("/events")?; + let mut s = Stream::open_with("/events", true)?; let mut pending = Vec::new(); while let Some(c) = s.next() { pending.extend_from_slice(&c); while let Some(i) = pending.iter().position(|&b| b == b'\n') { let line: Vec = pending.drain(..=i).collect(); - if let Ok(v) = serde_json::from_slice::(&line) { - if !on_event(v) { - return Ok(()); - } + if let Ok(v) = serde_json::from_slice::(&line) + && !on_event(v) + { + return Ok(()); } } } @@ -358,6 +471,7 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { /// arrives unframed, read from this, until it ends. `closer()` ends a read /// that waits (a log that follows) from another thread; the exec itself /// goes on in the container. +#[cfg(windows)] #[derive(Debug)] pub struct Exec { pub id: String, @@ -365,18 +479,21 @@ pub struct Exec { reader: BufReader, } +#[cfg(windows)] impl Exec { pub fn closer(&self) -> Closer { Closer(self.pipe.clone()) } } +#[cfg(windows)] impl Read for Exec { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.reader.read(buf) } } +#[cfg(windows)] impl BufRead for Exec { fn fill_buf(&mut self) -> io::Result<&[u8]> { self.reader.fill_buf() @@ -389,6 +506,7 @@ impl BufRead for Exec { /// Starts `cmd` in a running container, through the exec API with a /// terminal; `background` marks it as the window's own. +#[cfg(windows)] pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result { line_safe(container)?; let created = request_with("POST", &format!("/containers/{container}/exec"), Some(&serde_json::json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": true})), background)?; @@ -397,7 +515,7 @@ pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result } let id = created.json()["Id"].as_str().unwrap_or_default().to_owned(); let pipe = connect()?; - let mut s = Conn(pipe.clone(), None); + let mut s = Conn::Pipe(pipe.clone(), None); let body = r#"{"Detach":false,"Tty":true}"#; write!( s, @@ -415,6 +533,7 @@ pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result /// Runs `cmd` in a running container and returns (exit code, output), /// through the exec API with a terminal, so output arrives unframed. +#[cfg(windows)] pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let mut e = exec_start(container, cmd, false)?; let mut out = Vec::new(); @@ -422,3 +541,91 @@ pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let code = get(&format!("/exec/{}/json", e.id))?["ExitCode"].as_i64().unwrap_or(-1); Ok((code, String::from_utf8_lossy(&out).replace("\r\n", "\n"))) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const OK_JSON: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"; + const OK_PING: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"; + const OK_CHUNKED: &[u8] = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; + + fn wire_text(buf: &std::sync::Arc>>) -> String { + String::from_utf8(buf.lock().unwrap().clone()).unwrap() + } + + #[test] + fn background_polls_carry_the_background_header() { + let info = mock_reply(OK_JSON); + get_quick("/info").unwrap(); + let req = wire_text(&info); + assert!(req.starts_with("GET /info HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_quick must mark background: {req}"); + + let list = mock_reply(OK_JSON); + get_quick("/containers/json?all=1").unwrap(); + let req = wire_text(&list); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_quick lists must mark background: {req}"); + + let proxy_get = mock_reply(OK_JSON); + get_background("/kiri/proxy").unwrap(); + let req = wire_text(&proxy_get); + assert!(req.starts_with("GET /kiri/proxy HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_background must mark background: {req}"); + + let proxy_put = mock_reply(OK_JSON); + let body = json!({"http": null, "https": null}); + request_with("PUT", "/kiri/proxy/system", Some(&body), true).unwrap(); + let req = wire_text(&proxy_put); + assert!(req.starts_with("PUT /kiri/proxy/system HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "background proxy push must mark background: {req}"); + } + + #[test] + fn alive_and_events_carry_the_background_header() { + let ping = mock_reply(OK_PING); + assert!(alive()); + let req = wire_text(&ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive must mark background: {req}"); + + let quick_ping = mock_reply(OK_PING); + assert!(alive_quick()); + let req = wire_text(&quick_ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive_quick must mark background: {req}"); + + let ev = mock_reply(OK_CHUNKED); + events(|_| false).unwrap(); + let req = wire_text(&ev); + assert!(req.starts_with("GET /events HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "events must mark background: {req}"); + } + + #[test] + fn foreground_requests_omit_the_background_header() { + let fg_get = mock_reply(OK_JSON); + get("/info").unwrap(); + let req = wire_text(&fg_get); + assert!(req.starts_with("GET /info HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "foreground get must not mark background: {req}"); + + let wake = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + request("POST", "/kiri/wake", None).unwrap(); + let req = wire_text(&wake); + assert!(req.starts_with("POST /kiri/wake HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "POST /kiri/wake must not mark background: {req}"); + + let start = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + request("POST", "/containers/c1/start", None).unwrap(); + let req = wire_text(&start); + assert!(!req.contains("X-Kiri-Background"), "foreground POST must not mark background: {req}"); + + let logs = mock_reply(OK_CHUNKED); + let _ = Stream::open("/containers/c1/logs?follow=1").unwrap(); + let req = wire_text(&logs); + assert!(req.starts_with("GET /containers/c1/logs?follow=1 HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "foreground Stream::open must not mark background: {req}"); + } +} diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 0b1bafaf2..5848b91cd 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -309,7 +309,7 @@ fn wakes(launch: bool, stopped: Option) -> bool { /// Whether Kiri was stopped (Stop in the window or the tray): then it stays /// off until Start. None when the engine's /info did not answer. fn stopped() -> Option { - client::get("/info").ok().map(|i| i["KiriStopped"] == true) + client::get_background("/info").ok().map(|i| i["KiriStopped"] == true) } /// The daemon's wake; a Linux host has no VM to wake, which is fine. @@ -999,6 +999,28 @@ mod tests { assert!(!allowed_url("https://evil.example/#.kiri.localhost")); assert!(!allowed_url("ftp://localhost/")); } + + #[test] + fn background_engine_checks_mark_background_and_wake_does_not() { + let info = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n{\"KiriStopped\":true}"); + assert_eq!(super::stopped(), Some(true)); + let req = String::from_utf8(info.lock().unwrap().clone()).unwrap(); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "stopped() must mark background: {req}"); + + let wake_wire = super::client::mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + super::wake().unwrap(); + let req = String::from_utf8(wake_wire.lock().unwrap().clone()).unwrap(); + assert!(req.starts_with("POST /kiri/wake HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "wake() must not mark background: {req}"); + + let proxy_get = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{\"settings\":{}}"); + let proxy_put = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); + super::push_windows_proxy(serde_json::json!({"http": null, "https": null, "no_proxy": [], "pac": false}), |_| std::collections::HashMap::new()); + let get_req = String::from_utf8(proxy_get.lock().unwrap().clone()).unwrap(); + let put_req = String::from_utf8(proxy_put.lock().unwrap().clone()).unwrap(); + assert!(get_req.starts_with("GET /kiri/proxy HTTP/1.1\r\n") && get_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{get_req}"); + assert!(put_req.starts_with("PUT /kiri/proxy/system HTTP/1.1\r\n") && put_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{put_req}"); + } } /// The page's "fonts" event, made once (the window asks each time Settings @@ -1437,10 +1459,14 @@ fn windows_proxy() -> Value { /// Tells the daemon what Windows' proxy is. A proxy on Windows' own /// 127.0.0.1 (Windows' or one set in Settings → Network) is reached through -/// the relay (relay.rs), and the daemon gets its ports too. +/// the relay (relay.rs), and the daemon gets its ports too. Sent every +/// minute, so marked as the window's own: it never keeps the VM awake. pub(crate) fn send_windows_proxy() { - let mut body = windows_proxy(); - let custom = client::get("/kiri/proxy").map(|v| v["settings"].clone()).unwrap_or_default(); + push_windows_proxy(windows_proxy(), crate::relay::ports); +} + +fn push_windows_proxy(mut body: Value, relay_ports: impl FnOnce(&[u16]) -> std::collections::HashMap) { + let custom = client::get_background("/kiri/proxy").map(|v| v["settings"].clone()).unwrap_or_default(); let mut targets: Vec = [&body["http"], &body["https"], &custom["http"], &custom["https"]] .iter() .filter_map(|v| v.as_str()) @@ -1448,9 +1474,9 @@ pub(crate) fn send_windows_proxy() { .collect(); targets.sort_unstable(); targets.dedup(); - let relay = crate::relay::ports(&targets); + let relay = relay_ports(&targets); body["relay"] = relay.iter().map(|(t, l)| (t.to_string(), json!(l))).collect::>().into(); - let _ = client::request("PUT", "/kiri/proxy/system", Some(&body)); + let _ = client::request_with("PUT", "/kiri/proxy/system", Some(&body), true); } /// Settings → Domains: reads (or moves, then reads) the routers' ports. The diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index b184c761b..f4d8028c9 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -25,7 +25,7 @@ mod assemble; #[cfg(windows)] #[path = "../../kiri/src/ui/lang.rs"] mod lang; -#[cfg(windows)] +#[cfg(any(windows, test))] mod client; #[cfg(windows)] mod detail; diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index d8d7f2acb..a93b91e65 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -634,7 +634,7 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result Option { - crate::client::request("GET", "/version", None).ok().filter(|r| r.ok()).and_then(|r| crate::client::kiri_version(&r.json()).map(str::to_owned)) + crate::client::get_background("/version").ok().and_then(|v| crate::client::kiri_version(&v).map(str::to_owned)) } static CATCH_UP: crate::wslsync::CatchUp = crate::wslsync::CatchUp::new(); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 7ec0e7524..bb2b1756d 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 +### #723 Windows: the window's own refresh no longer keeps the VM awake (unreleased) +- Fixes: #668 Windows: the window's own refresh keeps the VM from sleeping +- Caused: none known +- Caused by: - +- Check: none + ### #524 Import: keep volume xattrs with GNU tar (unreleased) - Fixes: #485 kiri import loses user.* extended attributes on named volumes (Supabase Storage 500 ENODATA) - Caused: none known From 5fa739aeff49a1775a86d0151a721c8be1d25c65 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 16:05:45 +0100 Subject: [PATCH 013/157] Containers: fall back to clone when seccomp blocks clone3 (#529) Co-authored-by: AnandNair4 --- crates/kiri-init/src/linux/container.rs | 186 +++++++++++++++++++++--- crates/kiri-init/src/linux/sys.rs | 177 +++++++++++++++++++++- docs/fix-registry.md | 6 + tests/linux-host.sh | 67 +++++++++ tests/regressions.tsv | 1 + 5 files changed, 418 insertions(+), 19 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 81a6ffd94..b9b61b3a7 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1,9 +1,11 @@ //! Starts containers and execs. //! -//! A container is one clone3 straight into fresh namespaces and its cgroup; -//! the child sets up its root and execs. An exec joins a running container's -//! namespaces and cgroup the same way. No runc, no shim, no extra fork: -//! every process is a direct child of the agent, so waiting just works. +//! A container is one clone3 straight into fresh namespaces and its cgroup +//! (or, where clone3 is blocked, one clone that the agent then moves into +//! its cgroup); the child sets up its root and execs. An exec joins a +//! running container's namespaces and cgroup the same way. No runc, no shim, +//! no extra fork: every process is a direct child of the agent, so waiting +//! just works. use std::ffi::{CStr, CString}; use std::fs; @@ -317,6 +319,9 @@ struct Prepared { /// made, `pivot_root` done), so a start is not reported before an exec /// can join its mount namespace (#311). root_ready: Option, + /// 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, } /// The parts of [`super::hostopts::HostOpts`] the child applies itself. @@ -576,6 +581,10 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

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

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

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

e, } }; + if !cloned.into_cgroup { + // clone(2) cannot put the child in its cgroup: do it now, before it + // mounts anything and its limits have to apply. The child waits on + // the pipe until this write is done. + fs::write(cgroup.join("cgroup.procs"), pid.to_string()) + .map_err(|e| kill_child(io::Error::new(e.kind(), format!("cgroup: {e}"))))?; + // SAFETY: one byte to a pipe we own: "you are in your cgroup". + if unsafe { libc::write(cgroup_go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 { + return Err(kill_child(io::Error::last_os_error())); + } + } + drop(cgroup_go); // Before `pivot_root`, an exec joining its mount namespace gets the // agent's `/etc/passwd`, and an image user such as `dev` is unknown // (#311). So the start waits for the root, briefly (ROOT_READY_WAIT): @@ -918,6 +943,10 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile // An exec runs under its container's profile, not the default. prepared.profile = profile.to_vec(); let (parent_io, child_io) = stdio(&prepared)?; + // The child waits here until the agent has moved it into its cgroup, for + // a start that clone3 could not place there itself. + let (child_cgroup_ready, cgroup_go) = sys::pipe()?; + prepared.cgroup_ready = Some(child_cgroup_ready); let args = CloneArgs { flags: CLONE_INTO_CGROUP, exit_signal: libc::SIGCHLD as u64, @@ -937,9 +966,8 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile // no processes. Join the one its init lives in, as runc does. let init_cgroup; if cloned.as_ref().is_err_and(|e| e.kind() == io::ErrorKind::ResourceBusy) { - let rel = fs::read_to_string(format!("/proc/{target_pid}/cgroup")).unwrap_or_default(); - let rel = rel.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim().trim_start_matches('/').to_owned(); - init_cgroup = fs::File::open(paths.cgroup_root.join(&rel)); + let (rel, dir) = proc_cgroup(&paths.cgroup_root, target_pid); + init_cgroup = fs::File::open(dir); match &init_cgroup { Ok(fd) => { let retry = CloneArgs { cgroup: fd.as_raw_fd() as u64, ..args }; @@ -949,12 +977,36 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile Err(e) => cloned = Err(io::Error::new(e.kind(), format!("cgroup {rel}: {e}"))), } } - if let Ok(0) = cloned { - exec_child(&prepared, &namespaces, &child_io); + if let Ok(c) = &cloned + && c.pid == 0 + { + exec_child(&prepared, &namespaces, &child_io, !c.into_cgroup); } let restored = sys::setns(own_pid_ns.as_raw_fd(), libc::CLONE_NEWPID); - let pid = cloned?; - restored?; + drop(prepared.cgroup_ready.take()); + let child = cloned?; + let pid = child.pid; + if let Err(e) = restored { + // SAFETY: killing and reaping the child we just cloned. + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } + return Err(e); + } + if !child.into_cgroup { + // clone(2) cannot put the exec in the container's cgroup: do it now, + // then let it join the container's namespaces. + if let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, &cgroup_go) { + // SAFETY: killing and reaping the child we just cloned. + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } + return Err(e); + } + } + drop(cgroup_go); drop(cgroup_fd); let (stdin, stdout, stderr) = finish_stdio(parent_io, child_io).map_err(|e| { // SAFETY: killing the child we just cloned. @@ -982,6 +1034,38 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile }) } +/// The cgroup v2 directory (under `cgroup_root`) where `pid` lives, and +/// its hierarchy-relative path for error messages. +fn proc_cgroup(cgroup_root: &Path, pid: libc::pid_t) -> (String, PathBuf) { + let text = fs::read_to_string(format!("/proc/{pid}/cgroup")).unwrap_or_default(); + cgroup_of_proc(cgroup_root, &text) +} + +fn cgroup_of_proc(cgroup_root: &Path, proc_cgroup: &str) -> (String, PathBuf) { + let rel = proc_cgroup.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim().trim_start_matches('/').to_owned(); + let dir = if rel.is_empty() { cgroup_root.to_path_buf() } else { cgroup_root.join(&rel) }; + (rel, dir) +} + +/// Moves a child started with clone(2) into `cgroup`, then lets it go on. +/// `init_pid`: the container's init, whose cgroup is used when the +/// container's own cgroup takes no processes (Docker in Docker, BuildKit +/// move theirs into sub-cgroups), as runc does. +fn move_child(cgroup: &Path, cgroup_root: &Path, pid: libc::pid_t, init_pid: libc::pid_t, go: &OwnedFd) -> io::Result<()> { + if let Err(e) = fs::write(cgroup.join("cgroup.procs"), pid.to_string()) { + if e.kind() != io::ErrorKind::ResourceBusy { + return Err(e); + } + let (rel, dir) = proc_cgroup(cgroup_root, init_pid); + fs::write(dir.join("cgroup.procs"), pid.to_string()).map_err(|e| io::Error::new(e.kind(), format!("joining cgroup {rel}: {e}")))?; + } + // SAFETY: one byte to a pipe we own: "you are in your cgroup". + if unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + /// Unmounts a container and, for `--rm`, deletes its writable layer. /// Runs after the exit has been reported, off the critical path. Execs have /// nothing to undo. @@ -1214,6 +1298,7 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname: init: flags & run_flags::INIT != 0, host: HostApplied::default(), root_ready: None, + cgroup_ready: None, }) } @@ -1780,7 +1865,8 @@ fn report_fd(io: &ChildStdio) -> RawFd { /// The descriptors a container's child, right after its clone, still uses /// of those it inherited: its standard streams (or terminal socket), which /// are also where it reports a failure; the network namespace it joins; -/// the pipes it says "root ready" on and waits for its network on. Every +/// the pipes it says "root ready" on, waits for its network on, and waits +/// for its cgroup placement on. Every /// other descriptor it uses it opens itself, later (its root, the image's /// tree, its terminal). Standard input, output and error (0, 1, 2) always /// stay. Every field of `Prepared` is named, so a descriptor added to it @@ -1813,6 +1899,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { // Paths, numbers and names only. host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ }, root_ready, + cgroup_ready, } = p; let mut fds = match io { ChildStdio::Tty { sock } => vec![sock.as_raw_fd()], @@ -1825,12 +1912,15 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { fds.extend(net_join.as_ref().map(AsRawFd::as_raw_fd)); 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 } /// Runs in the cloned child: PID 1 of the container, in its own namespaces /// and cgroup. Never returns: it execs or exits 127 with a message. -fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)]) -> ! { +/// `fallback`: clone3 was blocked, so clone(2) made this child: it is not +/// in its cgroup yet and has no cgroup namespace of its own. +fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)], fallback: bool) -> ! { // First of all: the clone gave this child a copy of every descriptor // the agent had open, and filling a new volume can take seconds while // the agent goes on. Held here, a network's DNS socket keeps its @@ -1845,6 +1935,20 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ let err = report_fd(io); let fail = |what: &str, e: io::Error| -> ! { child_fail(err, what, e) }; + if fallback { + // The agent moves us into the container's cgroup, then unshares a + // cgroup namespace rooted there, as clone3 with CLONE_INTO_CGROUP + // would have done before we ran anything. + if let Some(ready) = &p.cgroup_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("cgroup", io::Error::other("the agent could not move this container into its cgroup")); + } + } + sys::unshare(libc::CLONE_NEWCGROUP).unwrap_or_else(|e| fail("cgroup namespace", e)); + } + // Mount events must not leak back into the agent's namespace. sys::remount(c"/", libc::MS_REC | libc::MS_PRIVATE).unwrap_or_else(|e| fail("make mounts private", e)); if let Some(ns) = &p.net_join { @@ -1932,8 +2036,19 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ /// Runs in the cloned child of an exec: joins the container's remaining /// namespaces (the PID namespace was set before clone), then execs. -fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio) -> ! { +/// `fallback`: clone3 was blocked, so it waits until the agent has moved it +/// into the container's cgroup. +fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio, fallback: bool) -> ! { let err = report_fd(io); + if fallback + && let Some(ready) = &p.cgroup_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 { + child_fail(err, "cgroup", io::Error::other("the agent could not move this exec into its cgroup")); + } + } for (fd, kind) in namespaces { sys::setns(fd.as_raw_fd(), *kind).unwrap_or_else(|e| child_fail(err, "join container", e)); } @@ -3532,4 +3647,41 @@ mod tests { assert!(super::api_paths(r.as_fd(), false, &[], &paths, None).is_err(), "unprivileged applies masked paths"); let _ = std::fs::remove_dir_all(&base); } + + /// When clone3 is blocked (#529), `move_child` writes the child's PID to + /// `cgroup.procs` and signals `cgroup_go`; when a container's root cgroup + /// refuses processes (`EBUSY`), `cgroup_of_proc` resolves the container + /// init's cgroup under `paths.cgroup_root`, including hybrid trees (#277). + #[test] + fn move_child_places_fallback_child_and_resolves_hybrid_init_cgroup() { + use std::os::fd::AsRawFd; + use std::path::Path; + let dir = std::env::temp_dir().join(format!("kiri-move-child-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cgroup.procs"), b"").unwrap(); + let (ready, go) = super::sys::pipe().unwrap(); + super::move_child(&dir, &dir, 4242, 1, &go).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join("cgroup.procs")).unwrap(), "4242"); + let mut b = [0u8; 1]; + // SAFETY: reading the byte move_child just wrote to the pipe. + assert_eq!(unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) }, 1); + assert_eq!(&b, b"g"); + let _ = std::fs::remove_dir_all(&dir); + + let unified = Path::new("/sys/fs/cgroup"); + assert_eq!( + super::cgroup_of_proc(unified, "0::/kiri/c1/init\n"), + ("kiri/c1/init".to_owned(), unified.join("kiri/c1/init")) + ); + let hybrid = Path::new("/sys/fs/cgroup/unified"); + assert_eq!( + super::cgroup_of_proc(hybrid, "2:devices:/\n1:name=systemd:/\n0::/kiri/c1/sub\n"), + ("kiri/c1/sub".to_owned(), hybrid.join("kiri/c1/sub")) + ); + assert_eq!( + super::cgroup_of_proc(hybrid, "1:name=systemd:/\n0::/\n"), + (String::new(), hybrid.to_path_buf()) + ); + } } diff --git a/crates/kiri-init/src/linux/sys.rs b/crates/kiri-init/src/linux/sys.rs index 1bc6e6d42..8b542b4dd 100644 --- a/crates/kiri-init/src/linux/sys.rs +++ b/crates/kiri-init/src/linux/sys.rs @@ -193,17 +193,77 @@ pub struct CloneArgs { pub const CLONE_INTO_CGROUP: u64 = 0x2_0000_0000; +/// A started child: its pid, and whether clone3 placed it in its cgroup. +pub struct Cloned { + pub pid: libc::pid_t, + /// False when the child was started with clone(2): the caller must move + /// it into `CloneArgs::cgroup` itself before letting it run. + pub into_cgroup: bool, +} + +/// Whether clone3 is unavailable rather than refusing this request: an old +/// kernel answers ENOSYS, and a seccomp filter (Docker's and Android's) may +/// answer ENOSYS or EPERM. glibc and runc fall back to clone(2) for these. +fn clone3_unavailable(errno: Option) -> bool { + matches!(errno, Some(code) if code == libc::ENOSYS || code == libc::EPERM) +} + +/// The clone(2) flags for `args`: clone3-only flags above 32 bits +/// (CLONE_INTO_CGROUP, CLONE_CLEAR_SIGHAND) and fields clone(2) has no place +/// for (the cgroup, a pidfd, set_tid, tls) are dropped, and clone3's separate +/// exit signal goes back into the low byte of the flags. CLONE_NEWCGROUP +/// goes too: clone3 places the child in its cgroup before making it, so the +/// namespace is rooted there; clone(2) cannot, and a namespace made now +/// would be rooted at the agent's cgroup. The caller unshares it after +/// moving the child. +fn clone_flags(args: &CloneArgs) -> libc::c_ulong { + ((args.flags & 0xffff_ffff & !(libc::CLONE_NEWCGROUP as u64)) | (args.exit_signal & 0xff)) as libc::c_ulong +} + /// Like fork(), but straight into new namespaces and a cgroup. Returns 0 in /// the child and the child's pid in the parent. /// +/// Uses clone3(2), which puts the child in its cgroup atomically. Where +/// clone3 is blocked (an old kernel, or a seccomp filter answering ENOSYS or +/// EPERM, as on Android/Droidspaces, #529), it falls back to clone(2), as +/// glibc and runc do, and reports `into_cgroup: false`. clone(2) cannot make +/// the cgroup namespace either, so the caller must move the child into its +/// cgroup and unshare CLONE_NEWCGROUP before it proceeds. +/// /// # Safety /// The caller must be single-threaded, as with fork(): the child gets a copy /// of this thread only, so no other thread may hold a lock it needs. -pub unsafe fn clone3(args: &CloneArgs) -> io::Result { +pub unsafe fn clone3(args: &CloneArgs) -> io::Result { // SAFETY: `args` is a valid clone_args of the size passed; the caller // upholds the single-thread requirement. let ret = unsafe { libc::syscall(libc::SYS_clone3, args as *const CloneArgs, std::mem::size_of::()) }; - check(ret, "clone3").map(|p| p as libc::pid_t) + if ret >= 0 { + return Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: true }); + } + let e = io::Error::last_os_error(); + if !clone3_unavailable(e.raw_os_error()) { + return Err(io::Error::new(e.kind(), format!("clone3: {e}"))); + } + // SAFETY: as above. clone(2) has no cgroup, pidfd, set_tid, stack or tls + // arguments here: the child runs on a copy of this thread's stack, like + // fork(). Passing 0 for the four arguments after `flags` is identical on + // x86_64 and aarch64 (CONFIG_CLONE_BACKWARDS). The caller upholds + // single-threadedness, which that requires. + let ret = unsafe { + libc::syscall(libc::SYS_clone, clone_flags(args), 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong) + }; + if ret < 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("clone: {e}"))); + } + Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: false }) +} + +/// Makes this thread's namespace view like `unshare(2)`: a new cgroup +/// namespace here is rooted at the caller's cgroup. +pub fn unshare(flags: libc::c_int) -> io::Result<()> { + // SAFETY: plain syscall on the calling thread. + check(unsafe { libc::unshare(flags) } as _, "unshare").map(drop) } /// The engine's own message as one line of the container's log: a value @@ -568,4 +628,117 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); assert_eq!(super::exec_failure(file.to_str().unwrap(), &err, super::Found { exists: true, dir: false }, false).0, 126, "{err}"); } + + /// Only a clone3 that is blocked (a seccomp filter answering ENOSYS or + /// EPERM, as Docker's and Android's do, #529) falls back to clone(2); + /// a refusal of the request itself is reported as it is. + #[test] + fn only_a_blocked_clone3_falls_back() { + let f = super::clone3_unavailable; + assert!(f(Some(libc::ENOSYS))); + assert!(f(Some(libc::EPERM))); + for code in [libc::EINVAL, libc::EBUSY, libc::EAGAIN, libc::ENOMEM] { + assert!(!f(Some(code)), "errno {code}"); + } + assert!(!f(None)); + } + + /// clone(2) cannot take CLONE_INTO_CGROUP (or any >32-bit clone3 flag such + /// as CLONE_CLEAR_SIGHAND), and a CLONE_NEWCGROUP made before the child is + /// in its cgroup would be rooted at the agent's, so all of those are + /// dropped; clone3's exit signal goes in the low byte, as clone(2) expects. + #[test] + fn clone2_flags_drop_what_it_cannot_place() { + const CLONE_CLEAR_SIGHAND: u64 = 0x1_0000_0000; + let args = super::CloneArgs { + flags: (libc::CLONE_NEWPID | libc::CLONE_NEWCGROUP) as u64 | super::CLONE_INTO_CGROUP | CLONE_CLEAR_SIGHAND, + exit_signal: libc::SIGCHLD as u64, + ..Default::default() + }; + let flags = super::clone_flags(&args) as u64; + assert_eq!(flags & libc::CLONE_NEWPID as u64, libc::CLONE_NEWPID as u64); + assert_eq!(flags & super::CLONE_INTO_CGROUP, 0); + assert_eq!(flags & CLONE_CLEAR_SIGHAND, 0); + assert_eq!(flags & libc::CLONE_NEWCGROUP as u64, 0); + assert_eq!(flags & 0xff, libc::SIGCHLD as u64); + } + + /// The real thing: a seccomp filter answering ENOSYS or EPERM for clone3, + /// as Android's and Docker's do (#529), must fall back to clone(2) instead + /// of failing the start. The filter is installed in a child process of + /// this test binary, so it does not outlive the test. + #[test] + fn blocked_clone3_falls_back_to_clone() { + if let Some(val) = std::env::var_os("KIRI_CLONE3_SEccomp") { + let code = if val == "EPERM" { libc::EPERM } else { libc::ENOSYS }; + install_clone3_denial(code); + // SAFETY: this helper process runs no other thread, as clone(2) + // without CLONE_VM needs; the child only calls _exit. + let cloned = unsafe { + super::clone3(&super::CloneArgs { exit_signal: libc::SIGCHLD as u64, ..Default::default() }) + } + .expect("a blocked clone3 must fall back to clone"); + assert!(!cloned.into_cgroup, "clone(2) cannot place the child in a cgroup"); + if cloned.pid == 0 { + // SAFETY: _exit neither unwinds nor runs destructors. + unsafe { libc::_exit(0) }; + } + let mut status = 0; + // SAFETY: waiting for the child just cloned. + let waited = unsafe { libc::waitpid(cloned.pid, &mut status, 0) }; + assert_eq!(waited, cloned.pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, "child status {status}"); + return; + } + let module = module_path!(); + let module = module.split_once("::").map_or(module, |(_, m)| m); + let name = format!("{module}::blocked_clone3_falls_back_to_clone"); + for kind in ["1", "EPERM"] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &name, "--nocapture", "--test-threads=1"]) + .env("KIRI_CLONE3_SEccomp", kind) + .output() + .expect("spawn this test binary"); + assert!( + out.status.success(), + "the clone3-blocked helper ({kind}) failed:\n{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + } + } + + /// Installs a seccomp filter that makes clone3 return `errno`. + fn install_clone3_denial(errno: i32) { + #[repr(C)] + struct Insn { + code: u16, + jt: u8, + jf: u8, + k: u32, + } + #[repr(C)] + struct Prog { + len: u16, + filter: *const Insn, + } + const LD_W_ABS: u16 = 0x20; + const JEQ_K: u16 = 0x15; + const RET_K: u16 = 0x06; + const RET_ALLOW: u32 = 0x7fff_0000; + const RET_ERRNO: u32 = 0x0005_0000; + let insns = [ + Insn { code: LD_W_ABS, jt: 0, jf: 0, k: 0 }, // seccomp_data.nr + Insn { code: JEQ_K, jt: 0, jf: 1, k: libc::SYS_clone3 as u32 }, + Insn { code: RET_K, jt: 0, jf: 0, k: RET_ERRNO | errno as u32 }, + Insn { code: RET_K, jt: 0, jf: 0, k: RET_ALLOW }, + ]; + let prog = Prog { len: insns.len() as u16, filter: insns.as_ptr() }; + // SAFETY: valid prctl calls; `prog` lives until they return. + unsafe { + assert_eq!(libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0, "no_new_privs: {}", io::Error::last_os_error()); + let n = libc::prctl(libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER as libc::c_ulong, &prog); + assert_eq!(n, 0, "seccomp: {}", io::Error::last_os_error()); + } + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index bb2b1756d..df83f717e 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 +### #549 Engine: fall back to clone(2) when seccomp blocks clone3 (unreleased) +- Fixes: #529 Containers fail to start with `clone3: Function not implemented (os error 38)` when seccomp blocks `clone3` +- Caused: none known +- Caused by: - +- Check: `clone3-seccomp-fallback` + ### #723 Windows: the window's own refresh no longer keeps the VM awake (unreleased) - Fixes: #668 Windows: the window's own refresh keeps the VM from sleeping - Caused: none known diff --git a/tests/linux-host.sh b/tests/linux-host.sh index ae246799d..4cd6d16df 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -812,6 +812,73 @@ t wsl-hybrid-cgroup "hybrid=ok noctrl=ok v1only=ok" "apk add -q util-linux util- # Linux uses for docker.proxy.sock (#420). t host-services-untouched "absent=yes kiri=root:root:700:socket host-unpriv=denied dd=65534:65534:755:no-kiri-sock:rm-ok" "absent=\$([ ! -e /run/host-services ] && echo yes || echo no); kdir=\$(stat -c '%U:%G:%a' /run/kiri/host-services 2>/dev/null); ksock=\$(stat -c '%F' /run/kiri/host-services/ssh-auth.sock 2>/dev/null); su nobody -s /bin/sh -c 'test -e /run/kiri/host-services/ssh-auth.sock' 2>/dev/null && unpriv=reached || unpriv=denied; mkdir -p /run/host-services && chown 65534:65534 /run/host-services && chmod 755 /run/host-services && : > /run/host-services/docker.proxy.sock && chown 65534:65534 /run/host-services/docker.proxy.sock; $POST http://d/kiri/stop >/dev/null && $POST http://d/kiri/wake >/dev/null && docker run --rm -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock alpine test -S /run/host-services/ssh-auth.sock; dd_dir=\$(stat -c '%u:%g:%a' /run/host-services 2>/dev/null); [ ! -e /run/host-services/ssh-auth.sock ] && dd_sock=no-kiri-sock || dd_sock=clobbered; su nobody -s /bin/sh -c 'rm /run/host-services/docker.proxy.sock' 2>/dev/null && dd_rm=rm-ok || dd_rm=rm-denied; rm -rf /run/host-services; echo \"absent=\$absent kiri=\$kdir:\$ksock host-unpriv=\$unpriv dd=\$dd_dir:\$dd_sock:\$dd_rm\"" t host-services-ssh-agent-mount "sock1=ok sock2=ok src=/run/host-services/ssh-auth.sock host-absent=yes" "id=\$(docker create -u 1000:1000 -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=bind,source=/run/host-services/ssh-auth.sock,target=/ssh2.sock alpine sh -c 'test -S /run/host-services/ssh-auth.sock && test -w /run/host-services/ssh-auth.sock && s1=ok || s1=no; test -S /ssh2.sock && test -w /ssh2.sock && s2=ok || s2=no; printf \"sock1=%s sock2=%s \" \"\$s1\" \"\$s2\"'); src=\$(docker inspect -f '{{(index .Mounts 0).Source}}' \$id); docker start -a \$id; docker rm -f \$id >/dev/null; [ ! -e /run/host-services ] && ha=yes || ha=no; echo \"src=\$src host-absent=\$ha\"" +# When an outer seccomp filter blocks clone3 with ENOSYS or EPERM (Android / +# Droidspaces, older Docker profiles; #529), kiri-init falls back to clone(2), +# moves the child into its cgroup, unshares CLONE_NEWCGROUP before mounting +# /sys/fs/cgroup, and places docker exec in the container's cgroup (or its +# init's sub-cgroup when the root cgroup refuses processes). +$D exec -i "$N" sh -c 'cat > /clone3-seccomp-test.sh' <<'SH' +#!/bin/sh +set -u +export DOCKER_HOST=unix:///root/.kiri/run/docker.sock +docker save alpine:latest -o /tmp/alpine529.tar >/dev/null 2>&1 || { echo "save-failed"; exit 1; } +export KIRI_BIN=/opt/kiri/kiri + +cat > /tmp/deny-clone3.py <<'PY' +import ctypes, errno, os, struct, sys +code = getattr(errno, sys.argv[1]) +insns = struct.pack( + "=HBBIHBBIHBBIHBBI", + 0x20, 0, 0, 0, + 0x15, 0, 1, 435, + 0x06, 0, 0, 0x00050000 | code, + 0x06, 0, 0, 0x7fff0000, +) +buf = ctypes.create_string_buffer(insns, len(insns)) +class Prog(ctypes.Structure): + _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.c_void_p)] +prog = Prog(4, ctypes.addressof(buf)) +libc = ctypes.CDLL(None, use_errno=True) +if libc.prctl(22, 2, ctypes.byref(prog), 0, 0) != 0: + sys.exit(ctypes.get_errno()) +os.execvp(sys.argv[2], sys.argv[2:]) +PY + +cat > /tmp/exercise529.sh <<'EOF' +#!/bin/sh +set -u +err=$1 +mount -t tmpfs t /var/lib/kiri && mount -t tmpfs t /root && ip link set lo up +python3 /tmp/deny-clone3.py "$err" "$KIRI_BIN" daemon >/tmp/lh529.log 2>&1 & +p=$! +export DOCKER_HOST=unix:///root/.kiri/run/docker.sock +for i in $(seq 60); do docker version >/dev/null 2>&1 && break; sleep 0.2; done +docker load -q -i /tmp/alpine529.tar >/dev/null 2>&1 || { kill $p 2>/dev/null; wait $p 2>/dev/null; echo load-fail; exit 1; } +r1=$(docker run --rm --memory 64m alpine sh -c 'printf "%s:%s" "$(cat /sys/fs/cgroup/memory.max)" "$(cat /proc/1/cgroup)"' 2>&1) || { + kill $p 2>/dev/null; wait $p 2>/dev/null; echo "run-fail:$r1"; exit 1 +} +cid=$(docker run -d --privileged --memory 64m alpine sleep 60 2>&1) || { + kill $p 2>/dev/null; wait $p 2>/dev/null; echo "bg-fail:$cid"; exit 1 +} +r2=$(docker exec "$cid" sh -c 'printf "%s:%s" "$(cat /sys/fs/cgroup/memory.max)" "$(cat /proc/self/cgroup)"' 2>&1) || { + docker rm -f "$cid" >/dev/null 2>&1; kill $p 2>/dev/null; wait $p 2>/dev/null; echo "exec-fail:$r2"; exit 1 +} +r3=$(docker exec "$cid" sh -c 'mkdir -p /sys/fs/cgroup/sub && echo 1 > /sys/fs/cgroup/sub/cgroup.procs && echo $$ > /sys/fs/cgroup/sub/cgroup.procs && echo +pids > /sys/fs/cgroup/cgroup.subtree_control' 2>&1 && + docker exec "$cid" cat /proc/self/cgroup 2>&1) || { + docker rm -f "$cid" >/dev/null 2>&1; kill $p 2>/dev/null; wait $p 2>/dev/null; echo "sub-fail:$r3"; exit 1 +} +docker rm -f "$cid" >/dev/null 2>&1 +kill $p 2>/dev/null; wait $p 2>/dev/null +echo "$r1|$r2|$r3" +EOF +chmod +x /tmp/exercise529.sh + +e1=$(unshare --mount --propagation private --net --fork /tmp/exercise529.sh ENOSYS) +e2=$(unshare --mount --propagation private --net --fork /tmp/exercise529.sh EPERM) +rm -f /tmp/alpine529.tar /tmp/deny-clone3.py /tmp/exercise529.sh /tmp/lh529.log +echo "enosys=$e1 eperm=$e2" +SH +t clone3-seccomp-fallback "enosys=67108864:0::/|67108864:0::/|0::/sub eperm=67108864:0::/|67108864:0::/|0::/sub" "apk add -q util-linux util-linux-misc iproute2 python3 >/dev/null 2>&1; sh /clone3-seccomp-test.sh" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index fc1b0c1ed..a733ca02a 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -227,3 +227,4 @@ host-services-ssh-agent-mount #420 containers mounting /run/host-services/ssh-au archive-directory-contents #617 GET /containers/{id}/archive normalized away a trailing /., dropped ./ from directory-contents entries, and did not resolve .. by name or keep / on root entries cp-out-dot #617 docker cp container:/out/. dst copied the folder itself (dst/out/a.txt) instead of its contents (dst/a.txt) import-volume-xattrs #485 kiri import used docker cp and BusyBox tar, silently dropping user.* extended attributes on named volumes (Supabase Storage 500 ENODATA) +clone3-seccomp-fallback #529 when an outer seccomp filter blocks clone3 with ENOSYS or EPERM (Android/Droidspaces, restricted Docker), containers and docker exec failed to start instead of falling back to clone(2) From 3bf031630682c1cc5e796ed34853af04cffd0fb0 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 16:15:00 +0100 Subject: [PATCH 014/157] Finder: expose container symlinks as links and omit /proc and /sys (#648) Co-authored-by: talaatmagdyx --- crates/kiri-init/src/linux/agent.rs | 7 ++ crates/kiri-init/src/linux/fsview.rs | 125 ++++++++++++++++++++++---- crates/kiri-proto/src/lib.rs | 10 +++ crates/kiri/src/daemon/engine.rs | 6 ++ crates/kiri/src/daemon/nfs.rs | 128 ++++++++++++++++++++++++++- crates/kiri/src/daemon/vmlink.rs | 7 ++ docs/fix-registry.md | 6 ++ tests/e2e.sh | 2 + tests/regressions.tsv | 2 + 9 files changed, 271 insertions(+), 22 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index cf0e4032c..434e1380c 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -789,6 +789,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Error(&format!("container {id} is not running")).encode(&mut out), }, + Ok(Msg::FsReadLink { id, path }) => match running_rootfs(procs, paths, id) { + Some(root) => match super::fsview::read_link(&root, path, &mut fs_buf) { + Ok(()) => Msg::FsData(&fs_buf).encode(&mut out), + Err(e) => Msg::Error(&format!("readlink {path}: {e}")).encode(&mut out), + }, + None => Msg::Error(&format!("container {id} is not running")).encode(&mut out), + }, Ok(other) => Msg::Error(&format!("unexpected {other:?}")).encode(&mut out), // A frame the host expects no reply to gets none, decoded // or not: an answer would be read as the next one's reply. diff --git a/crates/kiri-init/src/linux/fsview.rs b/crates/kiri-init/src/linux/fsview.rs index c84c85cba..bf0b47bee 100644 --- a/crates/kiri-init/src/linux/fsview.rs +++ b/crates/kiri-init/src/linux/fsview.rs @@ -2,6 +2,14 @@ //! from the Mac. Every path is resolved with openat2(RESOLVE_IN_ROOT): the //! container's root is `/` even for symlinks inside it, so nothing outside //! the container is reachable. +//! +//! Links are shown as links, never as what they point at (#648): a folder +//! link that leads back up, as in /sys (`virtio5/subsystem/drivers/…/virtio5`) +//! or Debian's `/usr/bin/X11 -> .`, made an endless tree that Spotlight, +//! Finder and backup tools walked until the path got too long, keeping the +//! VM busy. Tree walkers don't follow links. The kernel's own filesystems +//! (/proc, /sys and the like) are not shown at all: they hold the kernel's +//! state, not the container's files, and are large and loop on themselves. use std::ffi::CString; use std::io; @@ -71,23 +79,55 @@ fn stat_fd(fd: RawFd) -> io::Result { Ok(st) } -/// Metadata of `path`, following symlinks. RESOLVE_IN_ROOT keeps every link -/// inside the container (`/` in a link means the container's root), so a -/// link to a directory browses like the directory. A dangling link reports -/// as itself. +/// Whether `fd` is on one of the kernel's own filesystems: proc, sysfs and +/// what is mounted under them (cgroup, debugfs, tracefs, securityfs, bpf, +/// pstore, configfs, binfmt_misc, fusectl), devpts and mqueue. +fn kernel_fs(fd: RawFd) -> bool { + const MAGIC: [u64; 14] = [ + 0x9fa0, 0x6265_6572, 0x0027_e0eb, 0x6367_7270, 0x6462_6720, 0x7472_6163, 0x7365_6673, + 0xcafe_4a11, 0x6165_676c, 0x6265_6570, 0x4249_4e4d, 0x6573_5543, 0x1cd1, 0x1980_0202, + ]; + // SAFETY: fstatfs into a zeroed statfs. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + let ok = unsafe { libc::fstatfs(fd, &mut st) } == 0; + ok && MAGIC.contains(&(st.f_type as u64)) +} + +/// `open_in`, for what the browser shows: the kernel's filesystems are not +/// there. +fn open_shown(root: RawFd, path: &str, flags: i32) -> io::Result { + let fd = open_in(root, path, flags)?; + if kernel_fs(fd.as_raw_fd()) { + return Err(io::Error::from_raw_os_error(libc::ENOENT)); + } + Ok(fd) +} + +/// Metadata of `path` itself: a link reports as a link (see the module). pub fn stat(rootfs: &Path, path: &str) -> io::Result { let root = root_of(rootfs)?; - let fd = match open_in(root.as_raw_fd(), path, libc::O_PATH) { - Ok(fd) => fd, - Err(_) => open_in(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?, - }; + let fd = open_shown(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?; Ok(Meta::from(&stat_fd(fd.as_raw_fd())?)) } +/// Where the link `path` points, as it says it. +pub fn read_link(rootfs: &Path, path: &str, buf: &mut Vec) -> io::Result<()> { + let root = root_of(rootfs)?; + let fd = open_shown(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?; + buf.resize(libc::PATH_MAX as usize, 0); + // SAFETY: readlinkat of the link itself (an O_PATH descriptor and an + // empty name) into a buffer we own. + let n = unsafe { libc::readlinkat(fd.as_raw_fd(), c"".as_ptr(), buf.as_mut_ptr().cast(), buf.len()) }; + sys::check(n as _, "readlink")?; + buf.truncate(n as usize); + Ok(()) +} + /// A directory's entries, sorted by name, at most `MAX_ENTRIES`. pub fn list(rootfs: &Path, path: &str) -> io::Result> { let root = root_of(rootfs)?; - let dir = open_in(root.as_raw_fd(), path, libc::O_RDONLY | libc::O_DIRECTORY)?; + let dir = open_shown(root.as_raw_fd(), path, libc::O_RDONLY | libc::O_DIRECTORY)?; + let dev = stat_fd(dir.as_raw_fd())?.st_dev; let mut out = Vec::new(); // /proc/self/fd/N names the directory we already resolved safely. for entry in std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd()))? { @@ -99,15 +139,16 @@ pub fn list(rootfs: &Path, path: &str) -> io::Result> { if unsafe { libc::fstatat(dir.as_raw_fd(), c.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) } != 0 { continue; } - if st.st_mode & libc::S_IFMT == libc::S_IFLNK { - // Show what the link points at, resolved inside the container. - let target = format!("{}/{}", path.trim_end_matches('/'), name); - if let Ok(meta) = stat(rootfs, &target) { - out.push((name, meta)); - if out.len() >= MAX_ENTRIES { - break; + // Another filesystem is mounted here: left out if it is the kernel's. + if st.st_dev != dev && st.st_mode & libc::S_IFMT == libc::S_IFDIR { + // SAFETY: openat relative to the resolved directory, not following links. + let fd = unsafe { libc::openat(dir.as_raw_fd(), c.as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if fd >= 0 { + // SAFETY: openat returned a fresh descriptor. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + if kernel_fs(fd.as_raw_fd()) { + continue; } - continue; } } out.push((name, Meta::from(&st))); @@ -127,7 +168,7 @@ pub fn list(rootfs: &Path, path: &str) -> io::Result> { /// stopped every container's exec and start until it ended. pub fn read(rootfs: &Path, path: &str, offset: u64, len: usize, buf: &mut Vec) -> io::Result<()> { let root = root_of(rootfs)?; - let found = open_in(root.as_raw_fd(), path, libc::O_PATH)?; + let found = open_shown(root.as_raw_fd(), path, libc::O_PATH)?; if stat_fd(found.as_raw_fd())?.st_mode & libc::S_IFMT != libc::S_IFREG { return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); } @@ -186,4 +227,52 @@ mod tests { assert_eq!(buf, b"lo"); let _ = std::fs::remove_dir_all(&dir); } + + // #648: a link is a link, so a folder link back up (Debian's + // /usr/bin/X11 -> .) no longer makes an endless tree. + #[test] + fn links_are_shown_as_links() { + let dir = std::env::temp_dir().join(format!("kiri-fsview-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("usr/bin")).unwrap(); + std::os::unix::fs::symlink(".", dir.join("usr/bin/X11")).unwrap(); + std::os::unix::fs::symlink("/usr/bin", dir.join("bin")).unwrap(); + std::os::unix::fs::symlink("../../../../../../usr/bin", dir.join("escape")).unwrap(); + let link = |m: super::Meta| m.mode & libc::S_IFMT == libc::S_IFLNK; + + let list = super::list(&dir, "/usr/bin").unwrap(); + assert_eq!(list.iter().map(|(n, m)| (n.as_str(), link(*m))).collect::>(), [("X11", true)]); + assert!(link(super::stat(&dir, "/usr/bin/X11").unwrap())); + assert!(link(super::stat(&dir, "/bin").unwrap())); + assert!(link(super::stat(&dir, "/escape").unwrap())); + // A link on the way is still followed inside the container: only + // the last name is shown as itself. + assert!(link(super::stat(&dir, "/bin/X11").unwrap())); + assert!(link(super::stat(&dir, "/escape/X11").unwrap())); + let mut buf = Vec::new(); + super::read_link(&dir, "/usr/bin/X11", &mut buf).unwrap(); + assert_eq!(buf, b"."); + super::read_link(&dir, "/bin", &mut buf).unwrap(); + assert_eq!(buf, b"/usr/bin"); + super::read_link(&dir, "/escape/X11", &mut buf).unwrap(); + assert_eq!(buf, b"."); + assert!(super::read_link(&dir, "/usr", &mut buf).is_err(), "not a link"); + let _ = std::fs::remove_dir_all(&dir); + } + + // #648: /proc and /sys are the kernel's, not the container's files. + #[test] + fn the_kernels_filesystems_are_not_shown() { + let root = std::path::Path::new("/"); + let names: Vec = super::list(root, "/").unwrap().into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().any(|n| n == "etc"), "{names:?}"); + assert!(!names.iter().any(|n| n == "proc" || n == "sys"), "{names:?}"); + for p in ["/proc", "/proc/self/status", "/sys", "/sys/kernel"] { + assert_eq!(super::stat(root, p).map_err(|e| e.kind()).err(), Some(ErrorKind::NotFound), "{p}"); + } + assert!(super::list(root, "/sys").is_err()); + let mut buf = Vec::new(); + assert!(super::read(root, "/proc/self/status", 0, 16, &mut buf).is_err()); + assert!(super::stat(root, "/etc").is_ok()); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 45ea7fbb7..20d359975 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -150,6 +150,9 @@ pub enum Msg<'a> { /// Host → guest: up to `len` bytes from `offset`. Answered by `FsData` or `Error`. FsRead { id: &'a str, path: &'a str, offset: u64, len: u32 }, FsData(&'a [u8]), + /// Host → guest: where a link inside a running container's root points, + /// as the link says it. Answered by `FsData` or `Error`. + FsReadLink { id: &'a str, path: &'a str }, /// Guest → host: memory is tight right now (a PSI trigger fired); grow /// the VM's memory. No reply. MemoryPressure, @@ -789,6 +792,7 @@ mod kind { pub const AWAIT_START: u16 = 79; pub const CANCEL_START: u16 = 80; pub const DNS_RENAME: u16 = 81; + pub const FS_READ_LINK: u16 = 82; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1120,6 +1124,10 @@ impl Msg<'_> { put_u32(o, len); }), Msg::FsData(d) => frame(out, kind::FS_DATA, |o| put_bytes(o, d)), + Msg::FsReadLink { id, path } => frame(out, kind::FS_READ_LINK, |o| { + put_str(o, id); + put_str(o, path); + }), Msg::MemoryPressure => frame(out, kind::MEMORY_PRESSURE, |_| {}), Msg::RemoveVolume { name } => frame(out, kind::REMOVE_VOLUME, |o| put_str(o, name)), Msg::RemoveBridge { bridge } => frame(out, kind::REMOVE_BRIDGE, |o| put_str(o, bridge)), @@ -1420,6 +1428,7 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::FS_STAT_REQUEST => Msg::FsStatRequest { id: r.str()?, path: r.str()? }, kind::FS_STAT => Msg::FsStat(read_entry(&mut r)?), kind::FS_LIST_REQUEST => Msg::FsListRequest { id: r.str()?, path: r.str()? }, + kind::FS_READ_LINK => Msg::FsReadLink { id: r.str()?, path: r.str()? }, kind::FS_LIST => { let count = r.u32()?; let start = r.pos; @@ -1755,6 +1764,7 @@ mod tests { round(Msg::FsStat(FsEntry { name: "etc", mode: 0o40755, size: 4096, mtime: 1_700_000_000, mtime_nsec: 5, ino: 77 })); round(Msg::FsRead { id: "c1", path: "/etc/os-release", offset: 10, len: 4096 }); round(Msg::FsData(b"NAME=Alpine")); + round(Msg::FsReadLink { id: "c1", path: "/usr/bin/X11" }); round(Msg::MemoryPressure); round(Msg::RemoveVolume { name: "pgdata" }); round(Msg::RemoveBridge { bridge: "kiri3" }); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 462b173cb..3b32dda4e 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -3651,6 +3651,12 @@ impl Engine { self.vm()?.fs_read(id, path, offset, len) } + /// For the Finder view (macOS). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub fn fs_read_link(&self, id: &str, path: &str) -> io::Result> { + self.vm()?.fs_read_link(id, path) + } + /// A stream into the guest relay towards `ip:port`. pub fn relay_to(&self, ip: [u8; 4], port: u16) -> io::Result { let vm = self.vm()?; diff --git a/crates/kiri/src/daemon/nfs.rs b/crates/kiri/src/daemon/nfs.rs index 7d87c1a2d..053e16414 100644 --- a/crates/kiri/src/daemon/nfs.rs +++ b/crates/kiri/src/daemon/nfs.rs @@ -40,10 +40,10 @@ const NOENT: u32 = 2; const IO: u32 = 5; const ACCES: u32 = 13; const NOTDIR: u32 = 20; +const INVAL: u32 = 22; const ROFS: u32 = 30; const STALE: u32 = 70; const BADHANDLE: u32 = 10001; -const NOTSUPP: u32 = 10004; /// The export's filesystem id, `KIRI`. const FSID: u64 = 0x4b49_5249; @@ -558,9 +558,8 @@ impl Server<'_> { } } 5 => { - // Links are followed inside the container, so none are shown. - a.opaque()?; - o.u32(NOTSUPP).bool(false); + let fh = a.opaque()?; + self.read_link(fh, o); } 6 => { let fh = a.opaque()?; @@ -768,6 +767,34 @@ impl Server<'_> { } } + /// READLINK. Links are served as links (#648), pointing where they do + /// inside the container: see `in_container`. + fn read_link(&self, fh: &[u8], o: &mut Out) { + let at = match self.attr(fh) { + Ok(a) => a, + Err(e) => { + o.u32(e).bool(false); + return; + } + }; + let (Ok(Node::File { id, path }), true) = (self.node(fh), at.link) else { + o.u32(INVAL); + at.post_op(o); + return; + }; + match self.engine.fs_read_link(&id, &path) { + Ok(target) => { + o.u32(OK); + at.post_op(o); + o.opaque(in_container(&path, &String::from_utf8_lossy(&target)).as_bytes()); + } + Err(e) => { + o.u32(errno(e)); + at.post_op(o); + } + } + } + fn readdir(&mut self, fh: &[u8; 16], cookie: u64, count: u32, plus: bool, o: &mut Out) { let dir_attr = match self.attr(fh) { Ok(a) => a, @@ -840,6 +867,30 @@ impl Server<'_> { } } +/// The link at `link`'s `target`, made relative so that the Mac resolves it +/// inside the container's folder: `/` in a link is the container's root, +/// not the Mac's, and `..` stops at that root, as in the container. A link +/// to `/etc/hosts` at `/usr/x` reads `../etc/hosts`. +fn in_container(link: &str, target: &str) -> String { + let target = target.split('\0').next().unwrap_or(""); + let depth = link.split('/').filter(|c| !c.is_empty()).count().saturating_sub(1); + let (mut up, mut down) = if target.starts_with('/') { (depth, Vec::new()) } else { (0, Vec::new()) }; + for c in target.split('/') { + match c { + "" | "." => {} + ".." => { + if down.pop().is_none() && up < depth { + up += 1; + } + } + c => down.push(c), + } + } + let mut out = vec![".."; up]; + out.extend(down); + if out.is_empty() { ".".into() } else { out.join("/") } +} + fn garbage(xid: u32) -> Vec { let mut o = Out::default(); o.u32(xid).u32(1).u32(0).u32(0).u32(0).u32(4); // GARBAGE_ARGS @@ -892,6 +943,75 @@ mod tests { assert!(allowed(&a)); } + /// A link resolves inside its container's folder, never into the Mac's. + #[test] + fn links_point_inside_the_container() { + assert_eq!(in_container("/usr/bin/X11", "."), "."); + assert_eq!(in_container("/bin", "usr/bin"), "usr/bin"); + assert_eq!(in_container("/usr/x", "/etc/hosts"), "../etc/hosts"); + assert_eq!(in_container("/lib64", "/"), "."); + assert_eq!(in_container("/a/b/c", "/"), "../.."); + assert_eq!(in_container("/sys/bus/virtio/devices/virtio5/subsystem", "../../../bus/virtio"), "../../../bus/virtio"); + // Above the root is the root, as in the container. + assert_eq!(in_container("/etc/x", "../../../../etc/passwd"), "../etc/passwd"); + assert_eq!(in_container("/etc/x", "/../../etc/passwd"), "../etc/passwd"); + assert_eq!(in_container("/a/l", "b/../../../c"), "../c"); + assert_eq!(in_container("/l", "a/../../../.."), "."); + assert_eq!(in_container("/a/b/l", "///Users/victim/.ssh/id_rsa"), "../../Users/victim/.ssh/id_rsa"); + assert_eq!(in_container("/a/b/l", "../../../../Users/victim/.ssh"), "../../Users/victim/.ssh"); + assert_eq!(in_container("/a/l", "/a/b/../c"), "../a/c"); + assert_eq!(in_container("/a/l", "sub/.."), "."); + assert_eq!(in_container("/l", ""), "."); + assert_eq!(in_container("/a/l", "..\0/../../etc/passwd"), ".."); + assert_eq!(in_container("/a/l", &String::from_utf8_lossy(b"/etc/\xff/hosts")), "../etc/\u{fffd}/hosts"); + let long = format!("/{}", "a/".repeat(1024)); + assert_eq!(in_container("/usr/l", &long), format!("../{}", vec!["a"; 1024].join("/"))); + + // Chained symlinks evaluated by the Mac's VFS from ~/Kiri/ + // never step above ~/Kiri/. + let links = HashMap::from([ + ("/dir1", "."), + ("/a/b", ".."), + ("/a/root", "/"), + ("/a/c/up", "../../../.."), + ("/a/escape1", "b/../../../../Users/victim/.ssh"), + ("/a/escape2", "root/../../../../etc/passwd"), + ("/a/c/escape3", "up/../../.."), + ("/escape4", "dir1/../../.."), + ("/escape5", "a/b/../.."), + ]); + let host_root = ["Users", "victim", "Kiri", "ctr"]; + for (&start_link, &raw_target) in &links { + let parent_parts: Vec<&str> = start_link.split('/').filter(|c| !c.is_empty()).collect(); + let mut cur: Vec = host_root.iter().chain(&parent_parts[..parent_parts.len() - 1]).map(|s| (*s).to_owned()).collect(); + let rewritten = in_container(start_link, raw_target); + let mut queue: std::collections::VecDeque = rewritten.split('/').map(str::to_owned).collect(); + let mut hops = 0; + while let Some(comp) = queue.pop_front() { + match comp.as_str() { + "" | "." => {} + ".." => { + cur.pop(); + } + name => { + cur.push(name.to_owned()); + assert!(cur.iter().map(String::as_str).ge(host_root), "{start_link} -> {raw_target} ({rewritten}) escaped to {cur:?}"); + let cpath = format!("/{}", cur[host_root.len()..].join("/")); + if let Some(&next_target) = links.get(cpath.as_str()) { + hops += 1; + assert!(hops <= 16, "symlink loop"); + cur.pop(); // resolve relative to the symlink's parent directory + for step in in_container(&cpath, next_target).split('/').rev() { + queue.push_front(step.to_owned()); + } + } + } + } + assert!(cur.len() >= host_root.len() && cur[..host_root.len()] == host_root, "{start_link} -> {raw_target} ({rewritten}) escaped to {cur:?}"); + } + } + } + #[test] fn xdr_opaque_is_padded() { let mut o = Out::default(); diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index e2e81ea18..605b83226 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -674,6 +674,13 @@ impl VmLink { } } + pub fn fs_read_link(&self, id: &str, path: &str) -> io::Result> { + match self.call(|o| Msg::FsReadLink { id, path }.encode(o), None)? { + Reply::FsData(d) => Ok(d), + other => Err(io::Error::other(format!("expected FsData, got {other:?}"))), + } + } + pub fn stats(&self) -> io::Result { match self.call(|o| Msg::StatsRequest.encode(o), None)? { Reply::Stats(s) => Ok(s), diff --git a/docs/fix-registry.md b/docs/fix-registry.md index df83f717e..1220a7ebd 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 +### #655 Finder: show container symlinks as symlinks and omit /proc and /sys (unreleased) +- Fixes: #648 Finder mount (~/Kiri) causes 100% CPU via infinite directory recursion on container symlinks +- Caused: none known +- Caused by: - +- Check: `finder-symlink-is-link`, `finder-no-proc-sys` + ### #549 Engine: fall back to clone(2) when seccomp blocks clone3 (unreleased) - Fixes: #529 Containers fail to start with `clone3: Function not implemented (os error 38)` when seccomp blocks `clone3` - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 305a042f3..aa960ef57 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -989,6 +989,8 @@ needs finder t finder-root "docker-entrypoint.sh" ls "$KF/fsv" needs finder t finder-read "Alpine Linux" cat "$KF/fsv/etc/os-release" needs finder t finder-hash "match" bash -c "$D exec fsv sh -c 'head -c 3000000 /dev/urandom > /tmp/r.bin'; a=\$($D exec fsv sha256sum /tmp/r.bin | cut -c1-64); b=\$($SHA $KFQ/fsv/tmp/r.bin | cut -c1-64); [ \"\$a\" = \"\$b\" ] && echo match" needs finder t finder-symlink-inside "docker-entrypoint.sh" bash -c "$D exec fsv ln -s / /loop && ls $KFQ/fsv/loop/" +needs finder t finder-symlink-is-link "link . Alpine Linux" bash -c "$D exec fsv ln -sf ../../../../etc/os-release /tmp/escape && [ -L $KFQ/fsv/loop ] && [ -L $KFQ/fsv/tmp/escape ] && printf 'link %s ' \"\$(readlink $KFQ/fsv/loop)\" && grep -o 'Alpine Linux' $KFQ/fsv/tmp/escape | head -1" +needs finder t finder-no-proc-sys "hidden" bash -c "! ls $KFQ/fsv | grep -qxE 'proc|sys' && ! ls $KFQ/fsv/proc >/dev/null 2>&1 && ! ls $KFQ/fsv/sys >/dev/null 2>&1 && echo hidden" needs finder code finder-readonly 1 bash -c "echo x > $KFQ/fsv/tmp/written" t finder-mounted "nfs" bash -c "mount | grep -F \" on $KF \"" # A file rewritten in place (same path, same size) must never read stale. diff --git a/tests/regressions.tsv b/tests/regressions.tsv index a733ca02a..31dea535f 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -228,3 +228,5 @@ archive-directory-contents #617 GET /containers/{id}/archive normalized away a t cp-out-dot #617 docker cp container:/out/. dst copied the folder itself (dst/out/a.txt) instead of its contents (dst/a.txt) import-volume-xattrs #485 kiri import used docker cp and BusyBox tar, silently dropping user.* extended attributes on named volumes (Supabase Storage 500 ENODATA) clone3-seccomp-fallback #529 when an outer seccomp filter blocks clone3 with ENOSYS or EPERM (Android/Droidspaces, restricted Docker), containers and docker exec failed to start instead of falling back to clone(2) +finder-symlink-is-link #648 the Finder NFS mount reported container symlinks as their targets instead of symlinks, so directory symlink loops (/usr/bin/X11 -> .) caused infinite Finder and Spotlight recursion +finder-no-proc-sys #648 the Finder NFS mount exposed the kernel's /proc and /sys filesystems, whose symlink cycles and pseudo-files kept Spotlight and the VM at 100% CPU From e323ac020bfa5d9f5282c680140c26abafc8f81e Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 16:49:17 +0100 Subject: [PATCH 015/157] Docs: list healthchecks, Compose build/wait/conditions, bind volumes, and two build notes (#361) Co-authored-by: Alex Alvord <325058966+cloudlabworks@users.noreply.github.com> --- docs/features.md | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/docs/features.md b/docs/features.md index ac3fe67d5..523f519fd 100644 --- a/docs/features.md +++ b/docs/features.md @@ -11,7 +11,9 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr `--restart`, `--entrypoint`), `exec`, `logs`, `attach`, `stop`, `kill`, `restart`, `rm`, `wait`, `rename`, `pause`/`unpause`, `update`, `stats`, `top`, `diff`, `export`, `commit`, `cp` (both ways, running or not), - `container prune`; records survive a daemon restart; filters on every list + `container prune`; records survive a daemon restart; filters on every list; + healthchecks (`--health-cmd` and the other `--health-*` options, including + `--health-start-interval`; `ps --filter health=`) - **Limits and security**: `--memory`, `--cpus`, `--cpu-shares`, `--pids-limit`, `--shm-size`; Docker's default capabilities and a default seccomp filter; `--cap-add`/`--cap-drop`, `--privileged`, `--read-only`, @@ -45,7 +47,8 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr `kiri domains set --http 8080 --https 8443` moves them with no restart, `kiri domains reset` puts back 80 and 443 - **Storage**: named and anonymous volumes, bind mounts of Mac paths - (virtiofs), `--tmpfs`, `--mount`, `volume` commands + (virtiofs), `--tmpfs`, `--mount`, `volume` commands; local volumes that + bind a folder (`driver_opts: {type: none, o: bind, device: /path}`) - **Images**: `pull` (with `docker login` credentials), `push`, `tag`, `save`, `load`, `history`, `search`, `image prune`, `system df`; **amd64 images run through Rosetta**, `--platform` honoured @@ -91,8 +94,12 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr certificate is reached only once it is listed, as with Docker - **Builds**: `docker build` / `buildx build` through BuildKit running in a Kiri container (buildx's docker-container driver), stopped when idle; - on Apple silicon, amd64 build steps run through Rosetta too -- **Compose**: `up`, `down`, `ps`, `logs`, `exec`, multiple networks, events + `--platform` for one platform at a time; on Apple silicon, amd64 build + steps run through Rosetta too +- **Compose**: `up` (with `--build` and `--wait`), `down`, `ps`, `logs`, + `exec`, `build:`, healthchecks, `depends_on` conditions + (`service_healthy`, `service_completed_successfully`), `platform:`, + multiple networks, events - **USB devices (beta)**: the USB tab hands a device (a serial adapter, a Zigbee stick, a development board) to your containers on Mac, Windows and Linux, and shows where it is inside Linux with the `--device` line to @@ -174,3 +181,26 @@ unless the Mac already has a docker CLI. (`--add-host name:172.18.0.1` on Windows and Linux, the default bridge's gateway; `198.19.248.254` on a Mac) or `DOCKER_BUILDKIT=0`, where Kiri maps `host-gateway` itself. + +- **`docker build --platform linux/amd64,linux/arm64` fails** with + `docker exporter does not currently support exporting manifest lists`: + Kiri's builder loads one platform into Kiri per build. Build each + platform with its own `--platform`, or write all of them to an OCI + archive with `-o type=oci,dest=image.tar` (Kiri's `docker load` does not + read OCI archives). + +- **A build that cannot reach a registry says `not found`.** When BuildKit + cannot reach the registry (for example, no DNS in the builder), a base + image from a registry fails with `failed to resolve source metadata for + docker.io/library/alpine:3.15: docker.io/library/alpine:3.15: not found`, + even if `docker pull` already fetched that tag or digest + (`FROM alpine:3.13@sha256:...`). Kiri's builder asks Kiri's image mirror + first; the mirror serves only images no registry has (built, loaded, + committed, or tagged into another repository) and answers 404 for + registry tags and digests so BuildKit resolves them from the registry. + When the registry then can't be reached, BuildKit reports the mirror's + "not found" instead of the network error. A docker-container builder + with no mirror shows the real cause (`dial tcp: lookup + registry-1.docker.io ...`). The builder runs on the default bridge, so + check from a container there: + `docker run --rm alpine nslookup registry-1.docker.io`. From e3e0c9e7e0a8ef62cd2649efa40fcdad4abd9fa4 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 17:00:33 +0100 Subject: [PATCH 016/157] Containers: expose Docker's /.dockerenv marker for SDK detection (#131) Co-authored-by: Andre Kurait --- crates/kiri-init/src/linux/container.rs | 75 ++++++++++++++ crates/kiri-init/src/linux/copy.rs | 126 +++++++++++++++++++++--- docs/fix-registry.md | 6 ++ tests/e2e.sh | 21 ++++ tests/linux-host.sh | 17 ++++ tests/regressions.tsv | 9 ++ 6 files changed, 239 insertions(+), 15 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index b9b61b3a7..727b29b48 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -43,6 +43,9 @@ const LAST_CAP: u32 = 40; const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; +/// The file Docker puts in every container's root, relative to that root. +pub const MARKER: &CStr = c".dockerenv"; + /// What networking the agent can offer a new container right now. pub struct NetCtx<'a> { pub bridges: &'a mut Bridges, @@ -1853,6 +1856,28 @@ fn bind_file(root: BorrowedFd<'_>, src: &CStr, target: &CStr) -> io::Result<()> sys::mount(src, &at.proc_path(), c"none", libc::MS_BIND, None) } +/// Docker's `/.dockerenv`: an empty file, 0755, owned by root. Whatever the +/// image (or an earlier start) has there stays as it is: O_EXCL never +/// follows a link, so one that points out of the container is not written +/// through, and a link or directory there does not fail the start. +fn make_marker(root: BorrowedFd<'_>) -> io::Result<()> { + // SAFETY: valid directory fd and NUL-terminated name. + let fd = unsafe { libc::openat(root.as_raw_fd(), MARKER.as_ptr(), libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0o755) }; + if fd >= 0 { + // SAFETY: the descriptor opened just above, owned by nothing else; + // openat applies the process's umask, so set 0755 explicitly. + unsafe { + libc::fchmod(fd, 0o755); + libc::close(fd); + } + return Ok(()); + } + match io::Error::last_os_error() { + e if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), + e => Err(e), + } +} + /// Where the child reports a failure before it has execed: the stderr pipe, /// or the pty socket (the agent reads text there instead of a descriptor). fn report_fd(io: &ChildStdio) -> RawFd { @@ -1970,6 +1995,10 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ for (src, target) in &p.etc_files { bind_file(root, src, target).unwrap_or_else(|e| fail(&target.to_string_lossy(), e)); } + // SDKs use Docker's marker to detect container execution when cgroup + // namespaces hide the host's cgroup path. Made before changing user or + // making the root filesystem read-only. + make_marker(root).unwrap_or_else(|e| fail("container marker", e)); // The image's tree without the mounts made on it, for filling new // volumes; closed (and so unmounted) once they are all in place. let image = if p.mounts.iter().any(|m| m.copy_up) { image_tree() } else { None }; @@ -3393,6 +3422,52 @@ mod tests { assert!(super::joined_user_network("", kiri).is_none(), "no file to speak of"); } + /// The marker is made empty where the root has none. What is there + /// already stays: a file (a restart), a directory, and a link, whose + /// target outside the root is neither made nor touched. + #[test] + fn marker_is_made_once_and_never_through_a_link() { + use std::os::fd::AsFd; + use std::os::unix::fs::MetadataExt; + let base = std::env::temp_dir().join(format!("kiri-marker-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (plain, linked, linked_existing, dir) = (base.join("plain"), base.join("linked"), base.join("linked-existing"), base.join("dir")); + let marker = |root: &std::path::Path| root.join(super::MARKER.to_str().unwrap()); + let make = |root: &std::path::Path| super::make_marker(super::inroot::open_root(root).unwrap().as_fd()); + for root in [&plain, &linked, &linked_existing, &dir] { + std::fs::create_dir_all(root).unwrap(); + } + + make(&plain).unwrap(); + let meta = std::fs::symlink_metadata(marker(&plain)).unwrap(); + assert!(meta.is_file() && meta.len() == 0); + assert_eq!(meta.mode() & 0o7777, 0o755); + std::fs::write(marker(&plain), b"kept").unwrap(); + set_mode(&marker(&plain), 0o640); + make(&plain).unwrap(); + assert_eq!(std::fs::read(marker(&plain)).unwrap(), b"kept"); + assert_eq!(mode_of(&marker(&plain)), 0o640); + + std::os::unix::fs::symlink(base.join("outside"), marker(&linked)).unwrap(); + make(&linked).unwrap(); + assert!(std::fs::symlink_metadata(marker(&linked)).unwrap().file_type().is_symlink()); + assert!(!base.join("outside").exists(), "made through the link"); + + let existing = base.join("existing"); + std::fs::write(&existing, b"host").unwrap(); + set_mode(&existing, 0o600); + std::os::unix::fs::symlink(&existing, marker(&linked_existing)).unwrap(); + make(&linked_existing).unwrap(); + assert!(std::fs::symlink_metadata(marker(&linked_existing)).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&existing).unwrap(), b"host"); + assert_eq!(mode_of(&existing), 0o600); + + std::fs::create_dir(marker(&dir)).unwrap(); + make(&dir).unwrap(); + assert!(marker(&dir).is_dir()); + std::fs::remove_dir_all(&base).unwrap(); + } + #[test] fn mounts_go_parents_first_whatever_order_they_came_in() { let m = |t: &str| super::Mount { source: None, target: std::ffi::CString::new(t).unwrap(), ro: false, dir: true, copy_up: false, tmpfs_opts: None, tmpfs_flags: 0 }; diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index 6ddaac2db..0f7534735 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -19,7 +19,7 @@ use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, copy_flags, copy_op}; use std::cell::RefCell; use std::path::PathBuf; -use super::container::Paths; +use super::container::{self, Paths}; use super::sys; /// A copy child as the agent sees it: its end of the child's socket pair @@ -673,6 +673,38 @@ fn is_opaque(path: &std::path::Path) -> bool { n == 1 && v[0] == b'y' } +/// The marker as the agent made it at start: not a change the container +/// made, so Docker shows it in neither `docker diff` nor a committed layer. +/// Once the container has written to it or changed its mode or owner, it is +/// a change like any other. +fn is_marker(rel: &std::path::Path, m: &fs::Metadata) -> bool { + is_marker_attr(rel, m.file_type().is_file(), m.len(), m.mode(), m.uid(), m.gid()) +} + +fn is_marker_attr(rel: &std::path::Path, is_file: bool, len: u64, mode: u32, uid: u32, gid: u32) -> bool { + rel.as_os_str().as_encoded_bytes() == container::MARKER.to_bytes() + && is_file + && len == 0 + && mode & 0o7777 == 0o755 + && uid == 0 + && gid == 0 +} + +fn in_lower_layers(lowers: &[OwnedFd], rel: &std::path::Path) -> bool { + for l in lowers { + let Some(rel) = rel.to_str() else { continue }; + let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue }; + // SAFETY: fstat into a zeroed stat on a descriptor we own. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { + continue; + } + let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0; + return !whiteout; + } + false +} + /// `docker diff` and `docker commit`, from the writable layer. fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Result<()> { if spec.layers.is_empty() { @@ -692,6 +724,7 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res (fd >= 0).then(|| unsafe { OwnedFd::from_raw_fd(fd) }) }) .collect(); + let in_lower = |rel: &std::path::Path| in_lower_layers(&lowers, rel); // A running container writes its upper layer while we walk it, and could // swap a directory for a link to `/` between our look and our read // (`docker diff`, `commit --pause=false`). Inside a chroot of the layer @@ -721,6 +754,9 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res for e in names.into_iter().rev() { let r = rel.join(e.file_name()); let Ok(m) = fs::symlink_metadata(e.path()) else { continue }; + if is_marker(&r, &m) && !in_lower(&r) { + continue; + } if m.is_dir() { stack.push(r.clone()); } @@ -730,20 +766,6 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res entries.sort_by(|a, b| a.0.cmp(&b.0)); done(conn)?; if spec.op == copy_op::DIFF { - let in_lower = |rel: &std::path::Path| { - for l in &lowers { - let Some(rel) = rel.to_str() else { continue }; - let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue }; - // SAFETY: fstat into a zeroed stat on a descriptor we own. - let mut st: libc::stat = unsafe { std::mem::zeroed() }; - if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { - continue; - } - let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0; - return !whiteout; - } - false - }; let mut w = BufWriter::new(&mut *conn); for (rel, m) in &entries { let kind = if is_whiteout(m) { @@ -999,4 +1021,78 @@ mod tests { let _ = fs::remove_dir_all(&root); } + + #[test] + fn only_an_untouched_root_marker_is_skipped_by_diff_and_commit() { + use std::os::unix::fs::PermissionsExt; + + let p = std::path::Path::new; + assert!(is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p("sub/.dockerenv"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p("added"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), false, 0, 0o120755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 2, 0o100755, 0, 0)); + // `chmod 600 /.dockerenv`, `rm && touch` (0644), or special mode bits. + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100600, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100644, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o101755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o104755, 0, 0)); + // `chown 1000:1000 /.dockerenv` (or uid-only / gid-only changes). + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 1000)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 1000)); + + let base = std::env::temp_dir().join(format!("kiri-copy-marker-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + fs::create_dir_all(base.join("sub")).unwrap(); + let meta = |rel: &str| fs::symlink_metadata(base.join(rel)).unwrap(); + + fs::write(base.join(".dockerenv"), b"").unwrap(); + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap(); + let m = meta(".dockerenv"); + assert_eq!(is_marker(p(".dockerenv"), &m), m.uid() == 0 && m.gid() == 0); + assert!(!is_marker(p("sub/.dockerenv"), &m)); + assert!(!is_marker(p("added"), &m)); + + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o600)).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap(); + fs::write(base.join(".dockerenv"), b"hi").unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::remove_file(base.join(".dockerenv")).unwrap(); + std::os::unix::fs::symlink("/outside", base.join(".dockerenv")).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::remove_file(base.join(".dockerenv")).unwrap(); + fs::create_dir(base.join(".dockerenv")).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + // Truncating an image-provided `/.dockerenv` to 0 bytes leaves an empty + // `0755 0:0` file in `upper`, which must not be skipped when a lower + // layer already has `/.dockerenv`. + let lower_clean = base.join("lower-clean"); + let lower_image = base.join("lower-image"); + fs::create_dir_all(&lower_clean).unwrap(); + fs::create_dir_all(&lower_image).unwrap(); + fs::write(lower_image.join(".dockerenv"), b"from-image\n").unwrap(); + let open_dir = |dir: &std::path::Path| { + let c = sys::cstr(dir).unwrap(); + // SAFETY: plain open of a temp directory we just created. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: fresh descriptor. + unsafe { OwnedFd::from_raw_fd(fd) } + }; + let clean_lowers = [open_dir(&lower_clean)]; + let image_lowers = [open_dir(&lower_image)]; + assert!(!in_lower_layers(&clean_lowers, p(".dockerenv"))); + assert!(in_lower_layers(&image_lowers, p(".dockerenv"))); + let skip = |lowers: &[OwnedFd]| is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0) && !in_lower_layers(lowers, p(".dockerenv")); + assert!(skip(&clean_lowers)); + assert!(!skip(&image_lowers)); + + let _ = fs::remove_dir_all(&base); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 1220a7ebd..45409860b 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 +### #131 Containers: expose /.dockerenv for SDK detection (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: `container-marker`, `container-marker-nonroot`, `container-marker-readonly`, `container-marker-readonly-nonroot`, `container-marker-restart`, `container-marker-link`, `diff-no-marker`, `export-has-marker`, `commit-no-marker` + ### #655 Finder: show container symlinks as symlinks and omit /proc and /sys (unreleased) - Fixes: #648 Finder mount (~/Kiri) causes 100% CPU via infinite directory recursion on container symlinks - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index aa960ef57..77d97418a 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -421,6 +421,14 @@ t hostname-underscore "db_master" $D run --rm --hostname db_master alpine hostna t hostname-newline-refused "invalid hostname" $D run --rm --hostname $'db\n10.0.0.9 evil' alpine cat /etc/hosts t add-host-underscore "10.1.2.3" $D run --rm --add-host my_app.local:10.1.2.3 alpine getent hosts my_app.local t pid1 "1" $D run --rm alpine sh -c 'echo $$' +t container-marker "regular empty file 755 0:0" $D run --rm alpine stat -c '%F %a %u:%g' /.dockerenv +t container-marker-nonroot "marker-ok" $D run --rm -u 1000 alpine sh -c 'test -f /.dockerenv && test -r /.dockerenv && test ! -s /.dockerenv && echo marker-ok' +t container-marker-readonly "marker-ok" $D run --rm --read-only alpine sh -c 'test -f /.dockerenv && test ! -s /.dockerenv && echo marker-ok' +t container-marker-readonly-nonroot "marker-ok" $D run --rm --read-only -u 1000 alpine sh -c 'test -f /.dockerenv && test -r /.dockerenv && test ! -s /.dockerenv && echo marker-ok' +# The second start finds the marker the first one made. +t container-marker-restart "marker-ok" bash -c "$D run --name e2e-marker alpine sh -c 'test -f /.dockerenv && test ! -s /.dockerenv && echo marker-ok' >/dev/null && $D start -a e2e-marker; $D rm -f e2e-marker >/dev/null" +# An image with a link there starts, and nothing is made where the link points. +t container-marker-link "link-ok" bash -c "$D run --name e2e-marker alpine sh -c 'rm /.dockerenv && ln -s /outside/marker /.dockerenv' && $D commit e2e-marker kiri-test/marker-link >/dev/null && $D run --rm kiri-test/marker-link sh -c 'test -L /.dockerenv && test ! -e /outside && echo link-ok'; $D rm -f e2e-marker >/dev/null; $D rmi kiri-test/marker-link >/dev/null" t proc "PID" $D run --rm alpine ps t dev-null "ok" $D run --rm alpine sh -c 'echo x > /dev/null && echo ok' t dev-null-nonroot "ok" $D run --rm -u 1000 alpine sh -c 'echo x > /dev/null && head -c 1 /dev/urandom >/dev/null && echo ok' @@ -1658,6 +1666,10 @@ t diff-deleted "D /etc/motd" $D diff ren2 t diff-changed "C /etc/profile" $D diff ren2 t export "bin/busybox" bash -c "$D export ren2 | tar -t | grep -x bin/busybox" t export-has-change "added" bash -c "$D export ren2 | tar -t | grep -x added" +# The marker is the engine's, not a change: exported with the rest, but in +# neither the diff nor a committed layer. +t diff-no-marker "marker lines: 0" bash -c "echo marker lines: \$($D diff ren2 | grep -c dockerenv)" +t export-has-marker ".dockerenv" bash -c "$D export ren2 | tar -t | grep -Fx .dockerenv" # docker import (#461): the export back as a one-layer image, plain or gzip. t import "sha256:" bash -c "$D export ren2 | $D import -c 'CMD [\"cat\",\"/added\"]' -c 'ENV KIRI=1' -m 'from ren2' - kiri-test/imported:1" t import-runs "hi" $D run --rm kiri-test/imported:1 @@ -1678,6 +1690,15 @@ t import-dir-mtime "1000000000" bash -c "$D export ren2 | python3 -c 'import io, t import-empty-numbers "ok 0:0" bash -c "$D export ren2 | python3 \"$(dirname "$0")/lib/tar-empty-numbers.py\" | $D import - kiri-test/imported:6 >/dev/null && $D run --rm kiri-test/imported:6 sh -c 'cat /empty-numbers/ok; stat -c %u:%g /empty-numbers' | tr '\\n' ' '" $D rmi kiri-test/imported:1 kiri-test/imported:2 kiri-test/imported:3 kiri-test/imported:6 kiri-test/imported:7 >/dev/null 2>&1 t commit "sha256:" $D commit -c 'CMD ["cat","/added"]' -c 'ENV KIRI=1' ren2 kiri-test/committed:1 +t commit-no-marker "clean" bash -c "$D save kiri-test/committed:1 | python3 -c 'import io, sys, tarfile +names = [] +image = tarfile.open(fileobj=io.BytesIO(sys.stdin.buffer.read())) +for blob in filter(tarfile.TarInfo.isfile, image): + try: + names += tarfile.open(fileobj=image.extractfile(blob)).getnames() + except tarfile.TarError: + pass +print(\"clean\" if \"added\" in names and not {\".dockerenv\", \"./.dockerenv\"} & set(names) else names)'" t commit-runs "hi" $D run --rm kiri-test/committed:1 t commit-env "KIRI=1" $D run --rm kiri-test/committed:1 env t commit-whiteout "gone" bash -c "$D run --rm kiri-test/committed:1 sh -c 'test -e /etc/motd || echo gone'" diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 4cd6d16df..aa6d46677 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -48,6 +48,12 @@ else fi t run "3." "docker run --rm alpine cat /etc/alpine-release" t home "/root" "docker run --rm alpine sh -c 'echo \$HOME'" +t container-marker "regular empty file 755 0:0" "docker run --rm alpine stat -c '%F %a %u:%g' /.dockerenv" +t container-marker-nonroot "marker-ok" "docker run --rm -u 1000 alpine sh -c 'test -f /.dockerenv && test -r /.dockerenv && test ! -s /.dockerenv && echo marker-ok'" +t container-marker-readonly "marker-ok" "docker run --rm --read-only alpine sh -c 'test -f /.dockerenv && test ! -s /.dockerenv && echo marker-ok'" +t container-marker-readonly-nonroot "marker-ok" "docker run --rm --read-only -u 1000 alpine sh -c 'test -f /.dockerenv && test -r /.dockerenv && test ! -s /.dockerenv && echo marker-ok'" +t container-marker-restart "marker-ok" "docker rm -f lh-marker >/dev/null 2>&1; docker run --name lh-marker alpine sh -c 'test -f /.dockerenv && test ! -s /.dockerenv && echo marker-ok' >/dev/null && docker start -a lh-marker; docker rm -f lh-marker >/dev/null" +t container-marker-link "link-ok" "docker rm -f lh-marker >/dev/null 2>&1; docker run --name lh-marker alpine sh -c 'rm /.dockerenv && ln -s /outside/marker /.dockerenv' && docker commit lh-marker kiri-test/marker-link >/dev/null && docker run --rm kiri-test/marker-link sh -c 'test -L /.dockerenv && test ! -e /outside' && test ! -e /outside && echo link-ok; docker rm -f lh-marker >/dev/null; docker rmi kiri-test/marker-link >/dev/null 2>&1" t internet "Example Domain" "docker run --rm alpine wget -qO- -T 10 http://example.com" t port "Welcome to nginx" "docker run -d --name web -p 18081:80 nginx:alpine >/dev/null; for i in \$(seq 30); do curl -s localhost:18081 && break; sleep 0.3; done" t exec "nginx version" "docker exec web nginx -v" @@ -88,6 +94,17 @@ t failed-start-frees-root "gone mounts=0" "docker rm -f kiri-badsysctl >/dev/nul t failed-start-no-dns "none" "docker network create kiri-dnsfail >/dev/null 2>&1; docker rm -f kiri-dnsbad >/dev/null 2>&1; docker run -d --name kiri-dnsbad --network kiri-dnsfail --sysctl net.ipv4.kiri_no_such_key=1 alpine sleep 60 >/dev/null 2>&1; docker run --rm --network kiri-dnsfail alpine sh -c 'nslookup kiri-dnsbad 2>&1 | grep -qE \"^Address: [0-9.]+\$\" && echo answered || echo none'; docker rm -f kiri-dnsbad >/dev/null 2>&1; docker network rm kiri-dnsfail >/dev/null" t cp-stopped-unmounts "after=0" "id=\$(docker create alpine true); docker cp /etc/hostname \$id:/f >/dev/null; for i in \$(seq 20); do [ \$($mounts) = 0 ] && break; sleep 0.1; done; echo after=\$($mounts); docker rm \$id >/dev/null" t commit-renamed-dir "kept" "docker rm -f kiri-rename >/dev/null 2>&1; docker run --name kiri-rename alpine mv /etc/apk /etc/apk2; docker commit kiri-rename kiri-rename-test >/dev/null; docker rm -f kiri-rename >/dev/null; docker run --rm kiri-rename-test sh -c 'test -f /etc/apk2/repositories && echo kept'; docker rmi kiri-rename-test >/dev/null" +t diff-no-marker "marker lines: 0" "docker rm -f lh-mkr >/dev/null 2>&1; docker run --name lh-mkr alpine sh -c 'echo hi > /added' && echo marker lines: \$(docker diff lh-mkr | grep -c dockerenv)" +t export-has-marker ".dockerenv" "docker export lh-mkr | tar -t | grep -Fx .dockerenv" +t commit-no-marker "clean" "docker commit lh-mkr kiri-test/marker-committed:1 >/dev/null && docker save kiri-test/marker-committed:1 | python3 -c 'import io, sys, tarfile +names = [] +image = tarfile.open(fileobj=io.BytesIO(sys.stdin.buffer.read())) +for blob in filter(tarfile.TarInfo.isfile, image): + try: + names += tarfile.open(fileobj=image.extractfile(blob)).getnames() + except tarfile.TarError: + pass +print(\"clean\" if \"added\" in names and not {\".dockerenv\", \"./.dockerenv\"} & set(names) else names)'; docker rm -f lh-mkr >/dev/null; docker rmi kiri-test/marker-committed:1 >/dev/null 2>&1" # A layer whose directory has empty size, uid and gid fields: Docker reads an # empty number as 0 (#618, mcr.microsoft.com/azure-messaging/servicebus-emulator). $D cp "$(dirname "$0")/lib/tar-empty-numbers.py" "$N":/tar-empty-numbers.py >/dev/null diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 31dea535f..9c7baa83b 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -230,3 +230,12 @@ import-volume-xattrs #485 kiri import used docker cp and BusyBox tar, silently d clone3-seccomp-fallback #529 when an outer seccomp filter blocks clone3 with ENOSYS or EPERM (Android/Droidspaces, restricted Docker), containers and docker exec failed to start instead of falling back to clone(2) finder-symlink-is-link #648 the Finder NFS mount reported container symlinks as their targets instead of symlinks, so directory symlink loops (/usr/bin/X11 -> .) caused infinite Finder and Spotlight recursion finder-no-proc-sys #648 the Finder NFS mount exposed the kernel's /proc and /sys filesystems, whose symlink cycles and pseudo-files kept Spotlight and the VM at 100% CPU +container-marker #131 containers lacked /.dockerenv (empty regular file, 0755, root:root), breaking SDK container detection under cgroup v2 namespaces +container-marker-nonroot #131 /.dockerenv must exist and be readable by non-root container users +container-marker-readonly #131 /.dockerenv must be created before a --read-only rootfs is remounted read-only +container-marker-readonly-nonroot #131 /.dockerenv must exist and be readable on a --read-only rootfs for non-root users +container-marker-restart #131 restarting a container that already has /.dockerenv must succeed and keep the marker +container-marker-link #131 a symlink at /.dockerenv in the image must not be followed on container start +diff-no-marker #131 an untouched /.dockerenv created by the engine must not appear in docker diff +export-has-marker #131 docker export must include /.dockerenv as Docker does +commit-no-marker #131 docker commit must not include an untouched /.dockerenv in the committed layer From 462f6bb9955a1219746872d87638147efc5868c7 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 17:10:34 +0100 Subject: [PATCH 017/157] Linux: disable WebKitGTK damage propagation so the window does not go blank (#587) Co-authored-by: Antony Nyagah --- crates/kiri/src/ui/gtk.rs | 198 ++++++++++++++++++++++++++++++++++++++ docs/fix-registry.md | 6 ++ 2 files changed, 204 insertions(+) diff --git a/crates/kiri/src/ui/gtk.rs b/crates/kiri/src/ui/gtk.rs index d630ab87d..93dfe46c2 100644 --- a/crates/kiri/src/ui/gtk.rs +++ b/crates/kiri/src/ui/gtk.rs @@ -7,6 +7,7 @@ //! quits the window only: the engine is a system service and keeps running. use std::cell::RefCell; +use std::ffi::{CStr, c_char, c_int, c_void}; use std::io; use std::sync::mpsc; @@ -72,6 +73,7 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { // animation, which cost 26% of a core idle where there is no GPU // (a VM; software GL), against under 1.5% without it. settings.set_hardware_acceleration_policy(webkit2gtk::HardwareAccelerationPolicy::Never); + whole_frames(&settings); settings.set_enable_write_console_messages_to_stdout(cfg!(debug_assertions)); } webview.load_html(&super::assemble::page(PAGE, super::prefs()["lang"].as_str()), None); @@ -93,6 +95,91 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { Ok(()) } +/// Turns off WebKit's `PropagateDamagingInformation`. With it on and no GPU +/// compositing (see `run`), WebKitGTK 2.52 and 2.54 hand GTK only each frame's +/// repainted rectangles, and GTK 3 clears the rest of the view to the +/// window's own background: hover a row and the main pane goes blank, +/// leaving only the strip and the status bar. An opaque view background +/// (`page_background`) did not stop it. With propagation off WebKit marks the +/// whole view as changed in every frame, which costs next to nothing here +/// since the CPU is already drawing the frame. +/// +/// The feature API is WebKitGTK 2.42 and the bindings stop at 2.40, so it is +/// looked up at run time: on an older WebKit, or one without the feature, +/// this does nothing. +fn whole_frames(settings: &webkit2gtk::Settings) { + let (Some(all), Some(len), Some(get), Some(id), Some(set), Some(unref)) = ( + sym(c"webkit_settings_get_all_features"), + sym(c"webkit_feature_list_get_length"), + sym(c"webkit_feature_list_get"), + sym(c"webkit_feature_get_identifier"), + sym(c"webkit_settings_set_feature_enabled"), + sym(c"webkit_feature_list_unref"), + ) else { + return; + }; + // SAFETY: the symbols have the signatures WebKitGTK 2.42 documents; the + // list is ours until unref, and its features live as long as it does. + unsafe { + let api = FeatureApi { + all: std::mem::transmute::<*mut c_void, AllFeatures>(all), + len: std::mem::transmute::<*mut c_void, ListLen>(len), + get: std::mem::transmute::<*mut c_void, ListGet>(get), + id: std::mem::transmute::<*mut c_void, Identifier>(id), + set: std::mem::transmute::<*mut c_void, SetEnabled>(set), + unref: std::mem::transmute::<*mut c_void, Unref>(unref), + }; + api.disable_damage_propagation(settings.as_ptr().cast()); + } +} + +type AllFeatures = unsafe extern "C" fn() -> *mut c_void; +type ListLen = unsafe extern "C" fn(*mut c_void) -> usize; +type ListGet = unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void; +type Identifier = unsafe extern "C" fn(*mut c_void) -> *const c_char; +type SetEnabled = unsafe extern "C" fn(*mut c_void, *mut c_void, c_int); +type Unref = unsafe extern "C" fn(*mut c_void); + +struct FeatureApi { + all: AllFeatures, + len: ListLen, + get: ListGet, + id: Identifier, + set: SetEnabled, + unref: Unref, +} + +impl FeatureApi { + /// # Safety + /// `self` must hold functions matching WebKitGTK 2.42's `WebKitFeatureList` + /// C ABI, and `settings` must be a valid `WebKitSettings *` for `self.set`. + unsafe fn disable_damage_propagation(&self, settings: *mut c_void) { + // SAFETY: caller guarantees the function pointers and settings pointer. + unsafe { + let list = (self.all)(); + if list.is_null() { + return; + } + for i in 0..(self.len)(list) { + let feature = (self.get)(list, i); + if !feature.is_null() { + let name = (self.id)(feature); + if !name.is_null() && CStr::from_ptr(name) == c"PropagateDamagingInformation" { + (self.set)(settings, feature, 0); + } + } + } + (self.unref)(list); + } + } +} + +fn sym(name: &CStr) -> Option<*mut c_void> { + // SAFETY: a lookup by name in the already-loaded process symbols. + let p = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) }; + (!p.is_null()).then_some(p) +} + fn icon() -> Option { let loader = PixbufLoader::new(); loader.write(ICON_PNG).ok()?; @@ -235,3 +322,114 @@ pub(super) fn font_families(mono: bool) -> Vec { names.dedup(); names } + +#[cfg(test)] +mod tests { + use std::ffi::{c_char, c_int, c_void}; + use std::ptr; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::{FeatureApi, sym}; + + #[test] + fn sym_finds_loaded_symbols_and_rejects_missing_ones() { + assert!(sym(c"dlsym").is_some()); + assert!(sym(c"webkit_no_such_symbol_in_kiri").is_none()); + } + + #[test] + fn disable_damage_propagation_toggles_only_matching_feature_and_unrefs_list() { + static UNREFS: AtomicUsize = AtomicUsize::new(0); + static CALLS: AtomicUsize = AtomicUsize::new(0); + static LAST_SETTINGS: AtomicUsize = AtomicUsize::new(0); + static LAST_FEATURE: AtomicUsize = AtomicUsize::new(0); + static LAST_ENABLED: AtomicUsize = AtomicUsize::new(99); + + unsafe extern "C" fn all() -> *mut c_void { + 0x1000 as *mut c_void + } + unsafe extern "C" fn len(list: *mut c_void) -> usize { + assert_eq!(list, 0x1000 as *mut c_void); + 4 + } + unsafe extern "C" fn get(list: *mut c_void, idx: usize) -> *mut c_void { + assert_eq!(list, 0x1000 as *mut c_void); + match idx { + 0 => ptr::null_mut(), + 1 => 0x2001 as *mut c_void, + 2 => 0x2002 as *mut c_void, + 3 => 0x2003 as *mut c_void, + _ => unreachable!(), + } + } + unsafe extern "C" fn id(feature: *mut c_void) -> *const c_char { + match feature as usize { + 0x2001 => ptr::null(), + 0x2002 => c"AcceleratedCompositing".as_ptr(), + 0x2003 => c"PropagateDamagingInformation".as_ptr(), + _ => unreachable!(), + } + } + unsafe extern "C" fn set(settings: *mut c_void, feature: *mut c_void, enabled: c_int) { + CALLS.fetch_add(1, Ordering::SeqCst); + LAST_SETTINGS.store(settings as usize, Ordering::SeqCst); + LAST_FEATURE.store(feature as usize, Ordering::SeqCst); + LAST_ENABLED.store(enabled as usize, Ordering::SeqCst); + } + unsafe extern "C" fn unref(list: *mut c_void) { + assert_eq!(list, 0x1000 as *mut c_void); + UNREFS.fetch_add(1, Ordering::SeqCst); + } + + let api = FeatureApi { + all, + len, + get, + id, + set, + unref, + }; + // SAFETY: the test callbacks above expect these sentinel pointers. + unsafe { api.disable_damage_propagation(0x9000 as *mut c_void) }; + assert_eq!(CALLS.load(Ordering::SeqCst), 1); + assert_eq!(LAST_SETTINGS.load(Ordering::SeqCst), 0x9000); + assert_eq!(LAST_FEATURE.load(Ordering::SeqCst), 0x2003); + assert_eq!(LAST_ENABLED.load(Ordering::SeqCst), 0); + assert_eq!(UNREFS.load(Ordering::SeqCst), 1); + } + + #[test] + fn disable_damage_propagation_ignores_null_feature_list() { + static UNREFS: AtomicUsize = AtomicUsize::new(0); + unsafe extern "C" fn all() -> *mut c_void { + ptr::null_mut() + } + unsafe extern "C" fn len(_: *mut c_void) -> usize { + unreachable!() + } + unsafe extern "C" fn get(_: *mut c_void, _: usize) -> *mut c_void { + unreachable!() + } + unsafe extern "C" fn id(_: *mut c_void) -> *const c_char { + unreachable!() + } + unsafe extern "C" fn set(_: *mut c_void, _: *mut c_void, _: c_int) { + unreachable!() + } + unsafe extern "C" fn unref(_: *mut c_void) { + UNREFS.fetch_add(1, Ordering::SeqCst); + } + + let api = FeatureApi { + all, + len, + get, + id, + set, + unref, + }; + // SAFETY: `all` returns null so no pointer is dereferenced. + unsafe { api.disable_damage_propagation(ptr::null_mut()) }; + assert_eq!(UNREFS.load(Ordering::SeqCst), 0); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 45409860b..3ce09586e 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 +### #171 Linux: the window no longer goes blank on hover with WebKitGTK 2.54 (unreleased) +- Fixes: #587 Kiri doesn't render UI +- Caused: none known +- Caused by: - +- Check: none + ### #131 Containers: expose /.dockerenv for SDK detection (unreleased) - Fixes: no issue - Caused: none known From 3e40e545178ff2da6a0bef3dff54c213e269ad80 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 17:18:47 +0100 Subject: [PATCH 018/157] Networks: NetworkMode bridge with EndpointsConfig joins only those networks, as Docker does (#727) Co-authored-by: Anmol Sharma --- crates/kiri/src/daemon/api.rs | 121 +++++++++++++++++++++++++++++++++- docs/fix-registry.md | 6 ++ tests/linux-host.sh | 2 +- tests/testcontainers-api.py | 16 ++++- 4 files changed, 140 insertions(+), 5 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 6111f17f2..a16cbd310 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2036,7 +2036,7 @@ fn command(entry: Option>, cmd: Option>, image_entry: &[ }) } -/// The primary network when NetworkMode is empty or `default`: the first +/// The primary network when NetworkMode is empty, `default` or `bridge`: the first /// resolved endpoint's name, unless bridge is listed. No match keeps bridge. /// Unknown endpoints are left for create to reject. `keys` come from the /// request's JSON map, so they are sorted and "first" is the same every time. @@ -2208,8 +2208,11 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { super::seccomp::Choice::Unconfined => true, super::seccomp::Choice::Default => false, }; + // NetworkMode `bridge` too: Docker joins only the endpoints' networks + // when there are any, whatever the mode names (k3d sends `bridge` with + // its cluster network, #727), unless they list bridge. let network_mode = match host["NetworkMode"].as_str().unwrap_or("default") { - "" | "default" => body["NetworkingConfig"]["EndpointsConfig"].as_object() + "" | "default" | "bridge" => body["NetworkingConfig"]["EndpointsConfig"].as_object() .and_then(|eps| endpoints_primary(eps.keys().map(String::as_str), |key| engine.lock_net().find(key).map(|n| (n.name.clone(), n.internal)))) .unwrap_or_else(|| "bridge".to_owned()), m => m.to_owned(), @@ -4070,6 +4073,120 @@ mod tests { assert!(asked.borrow().iter().all(|k| !k.starts_with("container:")), "a container: key was looked up as a network"); } + /// `POST /containers/create` network selection across `HostConfig.NetworkMode` + /// and `NetworkingConfig.EndpointsConfig` (#407, #727). + #[test] + fn create_network_mode_with_endpoints_config() { + let (root, engine) = engine_in("create-net-endpoints", false); + let image = test_image("net-ep:1"); + engine.store.put_image(image.clone()).unwrap(); + let k3d = engine.lock_net().create("k3d-net", Default::default()).unwrap(); + engine.lock_net().create("custom-a", Default::default()).unwrap(); + engine.lock_net().create("custom-b", Default::default()).unwrap(); + engine.lock_net().create("back-net", super::super::network::Settings { internal: true, ..Default::default() }).unwrap(); + + let make = |name: &str, body: Value| -> Result<(String, Value), Error> { + let req = Request::internal("POST", "/containers/create", &[("name", name)], serde_json::to_vec(&body).unwrap()); + let created = create(&req, &engine)?; + let id = created["Id"].as_str().unwrap().to_owned(); + let inspected = container_inspect(&engine, &id)?; + Ok((id, inspected)) + }; + let net_names = |inspected: &Value| -> Vec { + let mut names: Vec = inspected["NetworkSettings"]["Networks"].as_object().unwrap().keys().cloned().collect(); + names.sort(); + names + }; + + // 1. NetworkMode "bridge" + non-empty EndpointsConfig without bridge -> joins ONLY k3d-net. + let (id1, ins1) = make("bridge-k3d", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {"Aliases": ["node-0"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins1), ["k3d-net"]); + assert_eq!(ins1["NetworkSettings"]["Networks"]["k3d-net"]["Aliases"], json!(["node-0"])); + engine.with(&id1, |c| { + assert_eq!(c.spec.network_mode, "k3d-net"); + assert!(c.spec.extra_networks.is_empty()); + }).unwrap(); + + // Same when EndpointsConfig names the network by ID, and with internal + outside networks. + let (_, ins1_id) = make("bridge-k3d-id", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {k3d.id.as_str(): {}, "back-net": {}}}, + })).unwrap(); + assert_eq!(net_names(&ins1_id), ["back-net", "k3d-net"]); + assert_eq!(ins1_id["HostConfig"]["NetworkMode"], "k3d-net", "outside network beats internal"); + + // 2. NetworkMode "bridge" + EndpointsConfig including both bridge and k3d-net -> joins BOTH. + let (id2, ins2) = make("bridge-and-k3d", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {"bridge": {}, "k3d-net": {"Aliases": ["both"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins2), ["bridge", "k3d-net"]); + assert_eq!(ins2["NetworkSettings"]["Networks"]["k3d-net"]["Aliases"], json!(["both"])); + engine.with(&id2, |c| { + assert_eq!(c.spec.network_mode, "bridge"); + assert_eq!(c.spec.extra_networks.len(), 1); + assert_eq!(c.spec.extra_networks[0].name, "k3d-net"); + }).unwrap(); + + // 3. NetworkMode "bridge" + empty or absent EndpointsConfig -> joins bridge as usual. + for (name, body) in [ + ("bridge-empty-eps", json!({"Image": "net-ep:1", "Cmd": ["true"], "HostConfig": {"NetworkMode": "bridge"}, "NetworkingConfig": {"EndpointsConfig": {}}})), + ("bridge-no-eps", json!({"Image": "net-ep:1", "Cmd": ["true"], "HostConfig": {"NetworkMode": "bridge"}})), + ] { + let (id, ins) = make(name, body).unwrap(); + assert_eq!(net_names(&ins), ["bridge"], "{name}"); + engine.with(&id, |c| { + assert_eq!(c.spec.network_mode, "bridge", "{name}"); + assert!(c.spec.extra_networks.is_empty(), "{name}"); + }).unwrap(); + } + + // 4. Named user network in NetworkMode + another in EndpointsConfig -> keeps NetworkMode primary + extra. + let (id4, ins4) = make("custom-a-and-b", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "custom-a"}, + "NetworkingConfig": {"EndpointsConfig": {"custom-b": {"Aliases": ["b-alias"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins4), ["custom-a", "custom-b"]); + assert_eq!(ins4["NetworkSettings"]["Networks"]["custom-b"]["Aliases"], json!(["b-alias"])); + engine.with(&id4, |c| { + assert_eq!(c.spec.network_mode, "custom-a"); + assert_eq!(c.spec.extra_networks.len(), 1); + assert_eq!(c.spec.extra_networks[0].name, "custom-b"); + }).unwrap(); + + // 5. Special NetworkModes ("host", "none", "container:") with EndpointsConfig stay unaffected / rejected. + let (id_host, _) = make("host-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "host"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })).unwrap(); + engine.with(&id_host, |c| assert_eq!(c.spec.network_mode, "host")).unwrap(); + + let (id_none, _) = make("none-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "none"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })).unwrap(); + engine.with(&id_none, |c| assert_eq!(c.spec.network_mode, "none")).unwrap(); + + let err_ctr = make("ctr-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": format!("container:{id1}")}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })); + assert!(matches!(err_ctr, Err(Error::BadRequest(ref m)) if m.contains("sharing network namespace")), "{err_ctr:?}"); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn archive_uploads_are_sniffed() { assert_eq!(upload_compression(&[0x1f, 0x8b, 8, 0, 0, 0]), Upload::Gzip); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 3ce09586e..f1ef9733f 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 +### #728 Networks: NetworkMode bridge with other networks in EndpointsConfig joins only those, as Docker does (unreleased) +- Fixes: #727 Engine: `NetworkMode: "bridge"` + one `EndpointsConfig` network joins both networks with bridge DNS, so `k3d cluster create` agents can't reach the server +- Caused: none known +- Caused by: - +- Check: `testcontainers-endpoints` + ### #171 Linux: the window no longer goes blank on hover with WebKitGTK 2.54 (unreleased) - Fixes: #587 Kiri doesn't render UI - Caused: none known diff --git a/tests/linux-host.sh b/tests/linux-host.sh index aa6d46677..f37d08749 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -123,7 +123,7 @@ t cp-in-copy-uidgid "no-a=1234:1235 with-a=1000:1000 default-a=1234:1235" "docke t cp-out-dot "hi no-out" "docker exec web sh -c 'mkdir -p /out; echo hi > /out/a.txt' && rm -rf /tmp/cpdot && mkdir -p /tmp/cpdot && docker cp web:/out/. /tmp/cpdot && echo \"\$(cat /tmp/cpdot/a.txt) \$([ ! -e /tmp/cpdot/out ] && echo no-out || echo has-out)\"; rm -rf /tmp/cpdot" t archive-directory-contents "PASS stopped docker cp of a parent into new directory" "python3 /archive-directory-contents.py /root/.kiri/run/docker.sock" # What Testcontainers needs (#222, #121); see tests/testcontainers-api.py. -for c in version cmd keepalive close follow follow-created timestamps; do +for c in version cmd keepalive close follow follow-created timestamps endpoints; do t "testcontainers-$c" "ok $c" "for i in \$(seq 60); do command -v python3 >/dev/null && break; sleep 1; done; python3 /testcontainers-api.py /root/.kiri/run/docker.sock $c" done t socket-mount-reaches-kiri "Kiri" "docker run --rm -v /root/.kiri/run/docker.sock:/var/run/docker.sock docker:cli docker version --format '{{.Server.Platform.Name}}'" diff --git a/tests/testcontainers-api.py b/tests/testcontainers-api.py index 893fec5fc..cd073acf7 100644 --- a/tests/testcontainers-api.py +++ b/tests/testcontainers-api.py @@ -323,7 +323,7 @@ def check_endpoints(): # NetworkingConfig.EndpointsConfig. Docker joins that network and not # bridge, so its embedded DNS answers the aliases (#407). c = Conn() - for name in ("tc-api-net-web", "tc-api-net-client"): + for name in ("tc-api-net-web", "tc-api-net-client", "tc-api-net-bridge-mode"): c.request("DELETE", f"/containers/{name}?force=1") c.request("DELETE", "/networks/tc-api-net") status, _, data = c.request("POST", "/networks/create", {"Name": "tc-api-net"}) @@ -339,6 +339,18 @@ def check_endpoints(): assert networks == ["tc-api-net"], f"networks {networks}, want only tc-api-net" _, status, _, out = exec_start(Conn(), ids["tc-api-net-client"], ["getent", "hosts", "tc-web"]) assert status == 200 and re.search(rb"\d+\.\d+\.\d+\.\d+\s+tc-web", out), f"the alias did not resolve: {out!r}" + # k3d sends NetworkMode "bridge" with its cluster network in + # EndpointsConfig. Docker still joins only that network, so the nodes + # find each other by name through its embedded DNS (#727). + bridged = fresh(c, "tc-api-net-bridge-mode", ["sleep", "600"], HostConfig={"NetworkMode": "bridge"}, + NetworkingConfig={"EndpointsConfig": {"tc-api-net": {}}}) + status, _, data = c.request("POST", f"/containers/{bridged}/start") + assert status == 204, f"start {status} {data[:200]!r}" + _, _, d = c.request("GET", f"/containers/{bridged}/json") + networks = sorted(json.loads(d)["NetworkSettings"]["Networks"]) + assert networks == ["tc-api-net"], f"NetworkMode bridge: networks {networks}, want only tc-api-net" + _, status, _, out = exec_start(Conn(), bridged, ["getent", "hosts", "tc-web"]) + assert status == 200 and re.search(rb"\d+\.\d+\.\d+\.\d+\s+tc-web", out), f"NetworkMode bridge: the alias did not resolve: {out!r}" # Two networks, the internal one sorted first: the default route must go # by the one that reaches outside, as Docker picks its gateway. c.request("DELETE", "/containers/tc-api-net-two?force=1") @@ -358,7 +370,7 @@ def check_endpoints(): gateway = networks["tc-api-net-z-front"]["Gateway"] _, status, _, out = exec_start(Conn(), two, ["ip", "route"]) assert status == 200 and re.search(rb"default via " + re.escape(gateway.encode()) + rb"\b", out), f"no default route by {gateway} (the outside network): {out!r}" - return "joins only the networks named in EndpointsConfig, its alias resolves, and an internal one doesn't take the default route" + return "joins only the networks named in EndpointsConfig (NetworkMode \"\" or \"bridge\"), its alias resolves, and an internal one doesn't take the default route" def check_copy_after_start(): From 2388cd5cc1bc2106e02b7ec546383de09625ba58 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 17:41:31 +0100 Subject: [PATCH 019/157] Engine: inspect gives back HostConfig's Binds, Mounts and Tmpfs, so a recreate keeps its volumes (#610) Co-authored-by: Elyter --- crates/kiri/src/daemon/api.rs | 340 ++++++++++++++++++++++++++++++- crates/kiri/src/daemon/engine.rs | 5 + docs/fix-registry.md | 6 + tests/e2e.sh | 10 + tests/linux-host.sh | 4 + tests/regressions.tsv | 3 + 6 files changed, 366 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index a16cbd310..c698f80a4 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -1842,6 +1842,80 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result Value { + let host = &body["HostConfig"]; + let mut volumes = serde_json::Map::new(); + for given in [&body["Volumes"], &image_cfg["config"]["Volumes"]] { + for path in given.as_object().into_iter().flat_map(|m| m.keys()) { + volumes.entry(path.clone()).or_insert_with(|| json!({})); + } + } + json!({ + "Binds": host["Binds"], + "Mounts": host["Mounts"], + "Tmpfs": host["Tmpfs"], + "Volumes": if volumes.is_empty() { Value::Null } else { Value::Object(volumes) }, + }) +} + +/// [`mount_request`] for inspect. A container saved before it was kept has +/// only Docker's `Mounts` entries, so they are made from those: a bind or a +/// named volume as a `Binds` line, a tmpfs in `Tmpfs` (or `Mounts` when +/// read-only), an anonymous volume in `Volumes` (or `Mounts` when read-only), +/// never leaking generated anonymous volume IDs or internal paths. +fn inspect_mounts(spec: &Spec, is_anon_volume: impl Fn(&str) -> bool) -> Value { + if !spec.mount_request.is_null() { + return spec.mount_request.clone(); + } + let (mut binds, mut mounts, mut tmpfs, mut volumes) = (Vec::new(), Vec::new(), serde_json::Map::new(), serde_json::Map::new()); + let mut seen = std::collections::HashSet::new(); + for m in &spec.mount_info { + let dst = m["Destination"].as_str().unwrap_or_default(); + if dst.is_empty() || !seen.insert(dst.trim_end_matches('/').to_owned()) { + continue; + } + let rw = m["RW"] != false; + let ro = if rw { "" } else { ":ro" }; + match (m["Type"].as_str(), m["Name"].as_str()) { + (Some("bind"), _) => { + let src = m["Source"].as_str().unwrap_or_default(); + if !src.is_empty() { + binds.push(format!("{src}:{dst}{ro}")); + } + } + (Some("volume"), Some(name)) if spec.anon_volumes.iter().any(|a| a == name) || is_anon_volume(name) => { + if rw { + volumes.insert(dst.to_owned(), json!({})); + } else { + mounts.push(json!({"Type": "volume", "Target": dst, "ReadOnly": true})); + } + } + (Some("volume"), Some(name)) if !name.is_empty() => { + binds.push(format!("{name}:{dst}{ro}")); + } + (Some("tmpfs"), _) => { + if rw { + tmpfs.insert(dst.to_owned(), json!("")); + } else { + mounts.push(json!({"Type": "tmpfs", "Target": dst, "ReadOnly": true})); + } + } + _ => {} + } + } + let or_null = |v: Value, empty: bool| if empty { Value::Null } else { v }; + json!({ + "Binds": or_null(json!(binds), binds.is_empty()), + "Mounts": or_null(json!(mounts), mounts.is_empty()), + "Tmpfs": or_null(json!(tmpfs), tmpfs.is_empty()), + "Volumes": or_null(json!(volumes), volumes.is_empty()), + }) +} + fn volume_json(v: &super::volumes::Volume) -> Value { json!({ "Name": v.name, @@ -2402,6 +2476,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { pid_mode, mounts: mounts.guest, mount_info: mounts.info, + mount_request: mount_request(&body, &image_cfg), volumes: mounts.volumes, anon_volumes: mounts.anon, restart: RestartPolicy { @@ -2643,8 +2718,9 @@ fn container_inspect(engine: &Engine, key: &str) -> Result { let id = engine.resolve(key)?; let networks: Vec = engine.lock_net().all().to_vec(); let health = engine.health(&id); + let anon_vols: Vec = engine.volume_list().into_iter().filter(|v| v.anonymous).map(|v| v.name).collect(); engine.with(&id, |c| { - let mut v = inspect(c, &networks); + let mut v = inspect(c, &networks, &anon_vols); v["NetworkSettings"]["Networks"] = endpoints(c, &networks); // The old top-level fields describe the default bridge only. if c.spec.network_mode == "bridge" { @@ -2731,7 +2807,7 @@ fn list(req: &Request, engine: &Engine) -> Result { Ok(Value::Array(rows.into_iter().map(|(_, v)| v).collect())) } -fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { +fn inspect(c: &Container, nets: &[super::network::Network], anon_vols: &[String]) -> Value { let when = |t: Option| t.map_or_else(|| time::ZERO.to_owned(), time::rfc3339); let argv = c.argv(); let mut v = json!({ @@ -2818,6 +2894,12 @@ fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { for key in ["MaskedPaths", "ReadonlyPaths"] { v["HostConfig"][key] = super::hostopts::system_paths(&c.spec.host_opts, key, c.spec.privileged); } + // Set apart: more keys in the macro above pass its recursion limit. + let mounts = inspect_mounts(&c.spec, |name| anon_vols.iter().any(|a| a == name)); + v["Config"]["Volumes"] = mounts["Volumes"].clone(); + for key in ["Binds", "Mounts", "Tmpfs"] { + v["HostConfig"][key] = mounts[key].clone(); + } v } @@ -5229,6 +5311,260 @@ mod network_option_tests { let _ = std::fs::remove_dir_all(&dir); } + /// Creates a container from `body` (on an image with a VOLUME line) and + /// returns its inspect, as `docker inspect` shows it. + fn inspect_after_create(name: &str, body: Value) -> Value { + let dir = std::env::temp_dir().join(format!("kiri-inspect-mounts-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"], "Volumes": {"/var/lib/img": {}}}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + let mut body = body; + body["Image"] = json!("demo:local"); + let id = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v = container_inspect(&engine, &id).unwrap(); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + v + } + + /// `-v` and Compose's short syntax arrive as Binds, `--mount` and the + /// long syntax as Mounts, `--tmpfs` as Tmpfs. Docker gives each back as + /// it came, and tools that recreate a container (Watchtower, Portainer, + /// Arcane) copy HostConfig: without them the new container has no volumes (#610). + #[test] + fn inspect_gives_back_binds_mounts_and_tmpfs_as_created() { + let src = std::env::temp_dir().join(format!("kiri-inspect-src-{}", std::process::id())); + std::fs::create_dir_all(&src).unwrap(); + let src = src.to_str().unwrap().to_owned(); + let binds = json!([ + format!("{src}:/b:ro"), + "k610vol:/data:rw", + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + ]); + let mounts = json!([ + {"Type": "bind", "Source": src, "Target": "/b2", "ReadOnly": true}, + {"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Target": "/ssh2.sock", "ReadOnly": true}, + {"Type": "volume", "Source": "k610other", "Target": "/data2", "ReadOnly": true, "VolumeOptions": {"NoCopy": true}}, + {"Type": "volume", "Target": "/anon2", "VolumeOptions": {}}, + {"Type": "tmpfs", "Target": "/t", "TmpfsOptions": {"SizeBytes": 1048576}}, + ]); + let tmpfs = json!({"/t2": "size=2m"}); + let v = inspect_after_create("given", json!({"HostConfig": {"Binds": binds, "Mounts": mounts, "Tmpfs": tmpfs}})); + assert_eq!(v["HostConfig"]["Binds"], binds); + assert_eq!(v["HostConfig"]["Mounts"], mounts); + assert_eq!(v["HostConfig"]["Tmpfs"], tmpfs); + assert_eq!(v["Config"]["Volumes"], json!({"/var/lib/img": {}})); + // HostConfig must never leak internal volume or relay socket paths. + let hc_text = v["HostConfig"].to_string(); + assert!(!hc_text.contains("/var/lib/kiri/volumes/"), "HostConfig leaked volume path: {hc_text}"); + assert!(!hc_text.contains("/run/kiri/host-services/ssh-auth.sock"), "HostConfig leaked host ssh relay path: {hc_text}"); + assert!(!hc_text.contains("/run/host-services/docker.sock"), "HostConfig leaked vm docker relay path: {hc_text}"); + assert!(!hc_text.contains("docker.container.sock"), "HostConfig leaked container socket path: {hc_text}"); + let _ = std::fs::remove_dir_all(&src); + } + + /// With no mounts asked for, Docker shows none. + #[test] + fn inspect_without_mounts_shows_none() { + let v = inspect_after_create("none", json!({"HostConfig": {}})); + assert_eq!(v["HostConfig"]["Binds"], Value::Null); + assert_eq!(v["HostConfig"]["Mounts"], Value::Null); + assert_eq!(v["HostConfig"]["Tmpfs"], Value::Null); + assert_eq!(v["Config"]["Volumes"], json!({"/var/lib/img": {}})); + } + + /// `-v /path` arrives in Config.Volumes; Docker's inspect lists it there + /// with the image's VOLUME lines, never in HostConfig.Binds under its + /// generated 64-hex volume ID, so a recreate makes fresh anonymous volumes. + #[test] + fn inspect_lists_anonymous_volumes_in_config_volumes() { + let v = inspect_after_create("anon", json!({"Volumes": {"/anon": {}}, "HostConfig": {}})); + assert_eq!(v["Config"]["Volumes"], json!({"/anon": {}, "/var/lib/img": {}})); + assert_eq!(v["HostConfig"]["Binds"], Value::Null); + assert_eq!(v["HostConfig"]["Mounts"], Value::Null); + assert_eq!(v["HostConfig"]["Tmpfs"], Value::Null); + } + + /// Recreating a container directly from its inspect `Config` + `HostConfig` + /// verbatim (as Watchtower, Portainer and Arcane do) succeeds with no + /// duplicate mount points and keeps named volumes, `:ro`, `ReadOnly: true`, + /// tmpfs, and socket paths while giving anonymous volumes fresh IDs (#610). + #[test] + fn inspect_recreate_round_trip_keeps_mounts_without_duplicates() { + let dir = std::env::temp_dir().join(format!("kiri-inspect-recreate-{}", std::process::id())); + let src = std::env::temp_dir().join(format!("kiri-inspect-recreate-src-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&src); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&src).unwrap(); + let src_s = src.to_str().unwrap().to_owned(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"], "Volumes": {"/var/lib/img": {}, "/img-overridden": {}}}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + + let body = json!({ + "Image": "demo:local", + "Volumes": {"/anon": {}}, + "HostConfig": { + "Binds": [ + format!("{src_s}:/b:ro"), + "k610vol:/data", + "k610img:/img-overridden", + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + ], + "Mounts": [ + {"Type": "bind", "Source": src_s, "Target": "/b2", "ReadOnly": true}, + {"Type": "volume", "Source": "k610rovol", "Target": "/rovol", "ReadOnly": true}, + {"Type": "tmpfs", "Target": "/t", "TmpfsOptions": {"SizeBytes": 1048576}}, + ], + "Tmpfs": {"/t2": "size=2m"}, + } + }); + let id1 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v1 = container_inspect(&engine, &id1).unwrap(); + + let mut recreate = v1["Config"].clone(); + recreate["HostConfig"] = v1["HostConfig"].clone(); + let id2 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&recreate).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v2 = container_inspect(&engine, &id2).unwrap(); + + assert_eq!(v2["HostConfig"]["Binds"], v1["HostConfig"]["Binds"]); + assert_eq!(v2["HostConfig"]["Mounts"], v1["HostConfig"]["Mounts"]); + assert_eq!(v2["HostConfig"]["Tmpfs"], v1["HostConfig"]["Tmpfs"]); + assert_eq!(v2["Config"]["Volumes"], json!({"/anon": {}, "/var/lib/img": {}, "/img-overridden": {}})); + + // Top-level Mounts has every expected destination exactly once. + let mounts2 = v2["Mounts"].as_array().unwrap(); + let dsts: Vec<&str> = mounts2.iter().map(|m| m["Destination"].as_str().unwrap()).collect(); + let unique: std::collections::HashSet<&str> = dsts.iter().copied().collect(); + assert_eq!(dsts.len(), unique.len(), "duplicate mount targets after recreate: {dsts:?}"); + let find = |dst: &str| mounts2.iter().find(|m| m["Destination"] == dst).unwrap_or_else(|| panic!("missing {dst}")); + assert_eq!(find("/b")["RW"], false); + assert_eq!(find("/b2")["RW"], false); + assert_eq!(find("/data")["Name"], "k610vol"); + assert_eq!(find("/img-overridden")["Name"], "k610img"); + assert_eq!(find("/rovol")["Name"], "k610rovol"); + assert_eq!(find("/rovol")["RW"], false); + assert_eq!(find("/var/run/docker.sock")["Source"], "/var/run/docker.sock"); + assert_eq!(find("/run/host-services/ssh-auth.sock")["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(find("/t")["Type"], "tmpfs"); + assert_eq!(find("/t2")["Type"], "tmpfs"); + // Anonymous volumes get fresh IDs on recreate instead of being pinned in Binds. + let anon1 = v1["Mounts"].as_array().unwrap().iter().find(|m| m["Destination"] == "/anon").unwrap()["Name"].as_str().unwrap(); + let anon2 = find("/anon")["Name"].as_str().unwrap(); + assert_ne!(anon1, anon2, "recreated container must get a fresh anonymous volume"); + assert!(!v1["HostConfig"]["Binds"].to_string().contains(anon1)); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&src); + } + + /// A container saved before `mount_request` was kept has only Docker's + /// `Mounts` entries: its Binds, Mounts, Tmpfs and anonymous volumes are + /// made from those without leaking `/var/lib/kiri/volumes/...`, internal + /// socket paths, or anonymous 64-hex IDs, and recreating from inspect works. + #[test] + fn inspect_of_an_older_container_derives_its_mounts() { + let root = std::env::temp_dir().join(format!("kiri-inspect-older-{}", std::process::id())); + let src = std::env::temp_dir().join(format!("kiri-inspect-older-src-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(&src); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&src).unwrap(); + let src_s = src.to_str().unwrap().to_owned(); + let engine = super::super::engine::boot_without_vm(&root); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"]}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + let image = kiri_image::archive::from_config("older:1".into(), &digest, &cfg, Vec::new()); + engine.store.put_image(image.clone()).unwrap(); + // An anonymous volume borrowed via --volumes-from lives in volumes.json + // as anonymous even when not listed on this container's anon_volumes. + let borrowed_anon = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + engine.volume_ensure(borrowed_anon, json!({}), true).unwrap(); + let spec: super::super::engine::Spec = serde_json::from_value(json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": ["named", "namedro", borrowed_anon], "anon_volumes": ["0123abcd", "deadbeef"], + "mount_info": [ + {"Type": "bind", "Source": src_s, "Destination": "/src", "Mode": "", "RW": false, "Propagation": "rprivate"}, + {"Type": "bind", "Source": "/var/run/docker.sock", "Destination": "/var/run/docker.sock", "Mode": "", "RW": true, "Propagation": "rprivate"}, + {"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Destination": "/run/host-services/ssh-auth.sock", "Mode": "", "RW": true, "Propagation": "rprivate"}, + {"Type": "volume", "Name": "named", "Source": "/var/lib/kiri/volumes/named/_data", "Destination": "/data", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "volume", "Name": "namedro", "Source": "/var/lib/kiri/volumes/namedro/_data", "Destination": "/dataro", "Driver": "local", "Mode": "z", "RW": false, "Propagation": ""}, + {"Type": "volume", "Name": "0123abcd", "Source": "/var/lib/kiri/volumes/0123abcd/_data", "Destination": "/anon", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "volume", "Name": "deadbeef", "Source": "/var/lib/kiri/volumes/deadbeef/_data", "Destination": "/anonro", "Driver": "local", "Mode": "z", "RW": false, "Propagation": ""}, + {"Type": "volume", "Name": borrowed_anon, "Source": format!("/var/lib/kiri/volumes/{borrowed_anon}/_data"), "Destination": "/borrowed", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "tmpfs", "Source": "", "Destination": "/t", "Mode": "", "RW": true, "Propagation": ""}, + {"Type": "tmpfs", "Source": "", "Destination": "/tro", "Mode": "", "RW": false, "Propagation": ""}, + ], + })).unwrap(); + let id = engine.create(Some("older".into()), spec, &image).unwrap(); + let v = container_inspect(&engine, &id).unwrap(); + assert_eq!( + v["HostConfig"]["Binds"], + json!([ + format!("{src_s}:/src:ro"), + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + "named:/data", + "namedro:/dataro:ro", + ]) + ); + assert_eq!( + v["HostConfig"]["Mounts"], + json!([ + {"Type": "volume", "Target": "/anonro", "ReadOnly": true}, + {"Type": "tmpfs", "Target": "/tro", "ReadOnly": true}, + ]) + ); + assert_eq!(v["HostConfig"]["Tmpfs"], json!({"/t": ""})); + assert_eq!(v["Config"]["Volumes"], json!({"/anon": {}, "/borrowed": {}})); + let hc_text = v["HostConfig"].to_string(); + assert!(!hc_text.contains("/var/lib/kiri/volumes/")); + assert!(!hc_text.contains("0123abcd")); + assert!(!hc_text.contains("deadbeef")); + assert!(!hc_text.contains(borrowed_anon)); + + // Recreating from the legacy container's inspect succeeds with no duplicates. + let mut recreate = v["Config"].clone(); + recreate["HostConfig"] = v["HostConfig"].clone(); + let id2 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&recreate).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v2 = container_inspect(&engine, &id2).unwrap(); + let dsts: Vec<&str> = v2["Mounts"].as_array().unwrap().iter().map(|m| m["Destination"].as_str().unwrap()).collect(); + let unique: std::collections::HashSet<&str> = dsts.iter().copied().collect(); + assert_eq!(dsts.len(), unique.len(), "duplicate mount targets after legacy recreate: {dsts:?}"); + assert_eq!(dsts.len(), 10); + + drop(engine); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(&src); + } + #[test] fn image_and_container_labels_follow_docker() { let dir = std::env::temp_dir().join(format!("kiri-labels-test-{}", std::process::id())); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 3b32dda4e..d98f38ac6 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -373,6 +373,11 @@ pub struct Spec { /// For `inspect`: Docker's `Mounts` entries. #[serde(default)] pub mount_info: Vec, + /// For `inspect`: HostConfig's `Binds`, `Mounts` and `Tmpfs` as create + /// gave them, and `Volumes` (Config's, with the image's VOLUME lines). + /// Null for a container saved before they were kept (#610). + #[serde(default)] + pub mount_request: serde_json::Value, /// Named volumes it uses (kept while it exists), and the anonymous ones /// created for it (deleted with it on `--rm` or `rm -v`). #[serde(default)] diff --git a/docs/fix-registry.md b/docs/fix-registry.md index f1ef9733f..e0b2dc04b 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 +### #759 Engine: inspect gives back HostConfig's Binds, Mounts and Tmpfs, so a recreate keeps its volumes (unreleased) +- Fixes: #610 Engine: `docker inspect` drops `HostConfig.Binds`, `HostConfig.Mounts`, `HostConfig.Tmpfs` and `Config.Volumes`, so Watchtower, Portainer and Arcane lose volumes and binds when recreating containers +- Caused: none known +- Caused by: - +- Check: `inspect-binds`, `inspect-mounts-tmpfs`, `inspect-recreate-mounts` + ### #728 Networks: NetworkMode bridge with other networks in EndpointsConfig joins only those, as Docker does (unreleased) - Fixes: #727 Engine: `NetworkMode: "bridge"` + one `EndpointsConfig` network joins both networks with bridge DNS, so `k3d cluster create` agents can't reach the server - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 77d97418a..493d225fb 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1093,6 +1093,16 @@ t volumes-from-unknown "No such container: vfnosuch" bash -c "o=\$($D run --rm - # The anonymous volume stays while another container still uses it. t volumes-from-anon-kept "got:a" bash -c "$D rm -v vfsrc >/dev/null; $D run --rm --volumes-from vfdst alpine sh -c 'echo got:\$(cat /anon/f)'" $D rm -f -v vfsrc vfdst >/dev/null 2>&1; $D volume rm tvfrom $VFANON >/dev/null 2>&1 +# Inspect gives back the mounts as create got them, in HostConfig and in +# Config.Volumes. Watchtower, Portainer and Arcane recreate a container from +# its inspect, and so keep its binds, volumes, tmpfs and sockets (#610). +$D rm -f -v hcm hcm2 >/dev/null 2>&1 +$D run --rm -v thcm:/data -v thcmro:/rodata alpine sh -c 'echo kept > /data/f; echo rokept > /rodata/f' +$D create --name hcm -v "$BIND:/bind:ro" -v thcm:/data -v /anon -v /var/run/docker.sock:/var/run/docker.sock -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=volume,source=thcmro,target=/rodata,readonly --mount type=tmpfs,target=/t --tmpfs /t2:size=1m alpine sh -c 'd=$(cat /data/f 2>/dev/null || echo MISSING); r=$(cat /rodata/f 2>/dev/null || echo MISSING); b=$(cat /bind/hello.txt 2>/dev/null || echo MISSING); (echo x > /bind/w) 2>&1 | grep -qi "read-only" && bro=ro || bro=bad; (echo x > /rodata/w) 2>&1 | grep -qi "read-only" && vro=ro || vro=bad; mount | grep -q "tmpfs on /t " && t1=ok || t1=no; mount | grep -q "tmpfs on /t2 " && t2=ok || t2=no; test -S /var/run/docker.sock && ds=ok || ds=no; test -S /run/host-services/ssh-auth.sock && ss=ok || ss=no; echo "$d|$r|$b|bro=$bro|vro=$vro|t1=$t1|t2=$t2|ds=$ds|ss=$ss"' >/dev/null +t inspect-binds "ok" bash -c "$D inspect -f '{{json .HostConfig.Binds}}' hcm | python3 -c 'import json, sys; got = set(json.load(sys.stdin) or []); want = {sys.argv[1], \"thcm:/data\", \"/var/run/docker.sock:/var/run/docker.sock\", \"/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock\"}; print(\"ok\" if got == want else sorted(got))' \"$BIND:/bind:ro\"" +t inspect-mounts-tmpfs 'ok {"/t2":"size=1m"} {"/anon":{}}' bash -c "m=\$($D inspect -f '{{json .HostConfig.Mounts}}' hcm | python3 -c 'import json, sys; ms = json.load(sys.stdin) or []; ok = len(ms) == 2 and {\"Type\": \"volume\", \"Source\": \"thcmro\", \"Target\": \"/rodata\", \"ReadOnly\": True} in ms and {\"Type\": \"tmpfs\", \"Target\": \"/t\"} in ms; print(\"ok\" if ok else ms)'); echo \"\$m \$($D inspect -f '{{json .HostConfig.Tmpfs}} {{json .Config.Volumes}}' hcm)\"" +t inspect-recreate-mounts "code=201 kept|rokept|from the mac|bro=ro|vro=ro|t1=ok|t2=ok|ds=ok|ss=ok anon=fresh" bash -c "a1=\$($D inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' hcm); b=\$(curl -s --unix-socket '$SOCK' http://d/v1.47/containers/hcm/json | python3 -c 'import json, sys; c = json.load(sys.stdin); print(json.dumps(dict(c[\"Config\"], HostConfig=c[\"HostConfig\"])))'); code=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket '$SOCK' -X POST -H 'Content-Type: application/json' -d \"\$b\" 'http://d/v1.47/containers/create?name=hcm2'); out=\$($D start -a hcm2); a2=\$($D inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' hcm2); [ -n \"\$a1\" ] && [ -n \"\$a2\" ] && [ \"\$a1\" != \"\$a2\" ] && an=fresh || an=\"same:\$a1:\$a2\"; echo \"code=\$code \$out anon=\$an\"" +$D rm -f -v hcm hcm2 >/dev/null 2>&1; $D volume rm thcm thcmro >/dev/null 2>&1 t anon-from-image "volume:/var/lib/postgresql/data" bash -c "$D run -d --name pgv -e POSTGRES_PASSWORD=x postgres:17-alpine >/dev/null; $D inspect -f '{{range .Mounts}}{{.Type}}:{{.Destination}}{{end}}' pgv" # Waits for the entrypoint's "init process complete" and then a working query, # not for pg_isready: on first start Postgres runs a temporary server to diff --git a/tests/linux-host.sh b/tests/linux-host.sh index f37d08749..037907177 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -896,6 +896,10 @@ rm -f /tmp/alpine529.tar /tmp/deny-clone3.py /tmp/exercise529.sh /tmp/lh529.log echo "enosys=$e1 eperm=$e2" SH t clone3-seccomp-fallback "enosys=67108864:0::/|67108864:0::/|0::/sub eperm=67108864:0::/|67108864:0::/|0::/sub" "apk add -q util-linux util-linux-misc iproute2 python3 >/dev/null 2>&1; sh /clone3-seccomp-test.sh" +# Inspect returns HostConfig.Binds, HostConfig.Mounts, HostConfig.Tmpfs and +# Config.Volumes so recreating a container from its inspect JSON (Watchtower, +# Portainer, Arcane) keeps volumes, :ro, tmpfs and socket binds (#610). +t inspect-recreate-mounts "binds=ok code=201 kept|rokept|from-host|bro=ro|vro=ro|t1=ok|t2=ok|ds=ok|ss=ok anon=fresh" "docker rm -f -v lhcm lhcm2 >/dev/null 2>&1; docker volume rm lthcm lthcmro >/dev/null 2>&1; rm -rf /tmp/k610-bind && mkdir -p /tmp/k610-bind && echo from-host > /tmp/k610-bind/hello.txt; docker run --rm -v lthcm:/data -v lthcmro:/rodata alpine sh -c 'echo kept > /data/f; echo rokept > /rodata/f'; docker create --name lhcm -v /tmp/k610-bind:/bind:ro -v lthcm:/data -v /anon -v /var/run/docker.sock:/var/run/docker.sock -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=volume,source=lthcmro,target=/rodata,readonly --mount type=tmpfs,target=/t --tmpfs /t2:size=1m alpine sh -c 'd=\$(cat /data/f 2>/dev/null || echo MISSING); r=\$(cat /rodata/f 2>/dev/null || echo MISSING); b=\$(cat /bind/hello.txt 2>/dev/null || echo MISSING); (echo x > /bind/w) 2>&1 | grep -qi \"read-only\" && bro=ro || bro=bad; (echo x > /rodata/w) 2>&1 | grep -qi \"read-only\" && vro=ro || vro=bad; mount | grep -q \"tmpfs on /t \" && t1=ok || t1=no; mount | grep -q \"tmpfs on /t2 \" && t2=ok || t2=no; test -S /var/run/docker.sock && ds=ok || ds=no; test -S /run/host-services/ssh-auth.sock && ss=ok || ss=no; echo \"\$d|\$r|\$b|bro=\$bro|vro=\$vro|t1=\$t1|t2=\$t2|ds=\$ds|ss=\$ss\"' >/dev/null; binds=\$(docker inspect -f '{{json .HostConfig.Binds}}' lhcm | python3 -c 'import json, sys; got = set(json.load(sys.stdin) or []); want = {\"/tmp/k610-bind:/bind:ro\", \"lthcm:/data\", \"/var/run/docker.sock:/var/run/docker.sock\", \"/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock\"}; print(\"ok\" if got == want else sorted(got))'); a1=\$(docker inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' lhcm); b=\$(curl -s --unix-socket /root/.kiri/run/docker.sock http://d/v1.47/containers/lhcm/json | python3 -c 'import json, sys; c = json.load(sys.stdin); print(json.dumps(dict(c[\"Config\"], HostConfig=c[\"HostConfig\"])))'); code=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket /root/.kiri/run/docker.sock -X POST -H 'Content-Type: application/json' -d \"\$b\" 'http://d/v1.47/containers/create?name=lhcm2'); out=\$(docker start -a lhcm2); a2=\$(docker inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' lhcm2); [ -n \"\$a1\" ] && [ -n \"\$a2\" ] && [ \"\$a1\" != \"\$a2\" ] && an=fresh || an=\"same:\$a1:\$a2\"; docker rm -f -v lhcm lhcm2 >/dev/null 2>&1; docker volume rm lthcm lthcmro >/dev/null 2>&1; rm -rf /tmp/k610-bind; echo \"binds=\$binds code=\$code \$out anon=\$an\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 9c7baa83b..655ea42e6 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -239,3 +239,6 @@ container-marker-link #131 a symlink at /.dockerenv in the image must not be fol diff-no-marker #131 an untouched /.dockerenv created by the engine must not appear in docker diff export-has-marker #131 docker export must include /.dockerenv as Docker does commit-no-marker #131 docker commit must not include an untouched /.dockerenv in the committed layer +inspect-binds #610 docker inspect omitted HostConfig.Binds, dropping -v binds, named volumes and socket paths on container recreate +inspect-mounts-tmpfs #610 docker inspect omitted HostConfig.Mounts, HostConfig.Tmpfs and Config.Volumes +inspect-recreate-mounts #610 recreating a container from its inspect Config and HostConfig (Watchtower, Portainer, Arcane) lost its volumes, read-only binds, tmpfs and socket mounts From b829e91b85d59fadc11667e5a5675f6d1f714d76 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 18:06:41 +0100 Subject: [PATCH 020/157] Networks: give secondary external networks an IPv4 default route and hand over on disconnect (#381) Co-authored-by: Supersynergy --- crates/kiri-init/src/linux/agent.rs | 12 ++- crates/kiri-init/src/linux/container.rs | 8 ++ crates/kiri-init/src/linux/net.rs | 107 ++++++++++++++++++++++-- crates/kiri-init/src/linux/netlink.rs | 36 ++++---- docs/fix-registry.md | 6 ++ tests/e2e.sh | 34 ++++++++ tests/linux-host.sh | 12 +++ tests/regressions.tsv | 9 ++ 8 files changed, 202 insertions(+), 22 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 434e1380c..d288407c9 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -698,6 +698,8 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Ack.encode(&mut out), + Ok(()) => { + if let Some(p) = procs.get_mut(&pid) { + // Unplugged already: a route that cannot move is no reason to fail the disconnect. + if let Err(e) = net::hand_over_default_routes(pid, &mut p.run.uplinks, &host_if) { + eprintln!("kiri-init: moving {id}'s default route after a disconnect: {e}"); + } + } + Msg::Ack.encode(&mut out) + } Err(e) => Msg::Error(&format!("disconnect: {e}")).encode(&mut out), } } diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 727b29b48..5689b3b3b 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -90,6 +90,9 @@ pub struct Process { /// network namespace would otherwise keep them, and the address that /// goes back to the pool, alive. pub veths: Vec, + /// Its non-internal networks, in the order they were plugged in: which + /// one takes the default route when the one holding it is disconnected. + pub uplinks: Vec, /// Inode of its own network namespace, or of the one it joined; 0 for /// the host's and for execs. Says whether a namespace outlives this /// container (see `teardown`). @@ -253,6 +256,7 @@ impl Process { tty: false, dns_entries: Vec::new(), veths: Vec::new(), + uplinks: Vec::new(), netns: 0, joins_netns: false, seccomp: Vec::new(), @@ -722,6 +726,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

return Err(kill_child(e)), } let mut veths = Vec::new(); + let mut uplinks = Vec::new(); // Names, AAAA records and `--dns` servers to give the DNS server, once // nothing can fail any more: a failed start must not leave its names // answering (#325). Nothing is answered before then anyway, since the @@ -747,6 +752,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

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

, target_pid: libc::pid_t, paths: &Paths, profile tty: prepared.tty, dns_entries: Vec::new(), veths: Vec::new(), + uplinks: Vec::new(), netns: 0, joins_netns: false, seccomp: Vec::new(), diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index f64305e63..16909a694 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -81,6 +81,67 @@ impl Plug { } } +/// A network a container can reach the outside through: one that is not +/// `--internal`, with the gateways it offers. Kept per running container, in +/// the order its networks were plugged in, so that a disconnect can hand the +/// default route on to the next one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Uplink { + /// Host side of its veth, which names the attachment on a disconnect. + pub veth: String, + /// Its interface in the container: `eth0`, `eth1` … + pub ifname: String, + pub v4: Option<[u8; 4]>, + pub v6: Option<[u8; 16]>, +} + +impl Uplink { + /// None for an internal network, which never gives a default route. + pub fn of(veth: &str, ifname: &str, gateway: [u8; 4], v6: Option, plug: Plug) -> Option { + let v4 = (!plug.internal && !plug.no_ipv4).then_some(gateway); + let v6 = v6.filter(|_| !plug.internal).map(|v| v.gateway); + (v4.is_some() || v6.is_some()).then(|| Uplink { veth: veth.to_owned(), ifname: ifname.to_owned(), v4, v6 }) + } +} + +/// The uplinks that hold the IPv4 and the IPv6 default route: for each, the +/// first one plugged in that has it. `attach` adds every uplink's route and +/// the kernel keeps the first (the later ones are EEXIST), so this is the +/// same choice. Docker would take the network whose name sorts first among +/// equals; keeping the first is steadier: plugging in a network never moves +/// a running container's traffic. +pub fn route_holders(uplinks: &[Uplink]) -> (Option<&Uplink>, Option<&Uplink>) { + (uplinks.iter().find(|u| u.v4.is_some()), uplinks.iter().find(|u| u.v6.is_some())) +} + +/// Takes the attachment whose host veth is `veth` out of `uplinks`, after it +/// was unplugged. If it held a default route, the next uplink gets it, as +/// Docker moves the default gateway when a container leaves that network; +/// with none left the container has no default route, as on internal-only +/// networks. The kernel dropped the old route with the interface. +pub fn hand_over_default_routes(pid: libc::pid_t, uplinks: &mut Vec, veth: &str) -> io::Result<()> { + let (old4, old6) = route_holders(uplinks); + let (was4, was6) = (old4.is_some_and(|u| u.veth == veth), old6.is_some_and(|u| u.veth == veth)); + uplinks.retain(|u| u.veth != veth); + if !was4 && !was6 { + return Ok(()); + } + let (new4, new6) = route_holders(uplinks); + let (new4, new6) = (new4.filter(|_| was4), new6.filter(|_| was6)); + if new4.is_none() && new6.is_none() { + return Ok(()); + } + let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + let mut inner = Netlink::open_in(&netns)?; + if let Some(u) = new4 { + netlink::replace_default_route(&mut inner, netlink::index_in(&netns, &u.ifname)?, u.v4.unwrap_or_default())?; + } + if let Some(u) = new6 { + netlink::replace_default_route6(&mut inner, netlink::index_in(&netns, &u.ifname)?, u.v6.unwrap_or_default())?; + } + Ok(()) +} + pub fn ip6_str(a: [u8; 16]) -> String { std::net::Ipv6Addr::from(a).to_string() } @@ -714,11 +775,13 @@ pub fn attach_container( attach(bridges, bridge, host_ifname, pid, 0, ip, prefix, gateway, mac, v6, plug) } -/// Plugs the container into `bridge` as `eth{n}`. Only `eth0` gets the -/// default route; more networks add their subnets, as with Docker. The -/// first network with IPv6 gives the IPv6 default route. An `internal` -/// network gives no default route at all, so traffic beyond it fails at -/// once (unreachable), as with Docker. On a network without IPv6 the +/// Plugs the container into `bridge` as `eth{n}`. The first non-internal +/// network with IPv4 gives the IPv4 default route, even when it is not +/// `eth0` (an internal network first, an outside one second); later ones +/// keep it, and only add their subnets. The same goes for IPv6. An +/// `internal` network never gives a default route, so traffic beyond it +/// fails at once (unreachable), as with Docker. `hand_over_default_routes` +/// moves a route on when its network is disconnected. On a network without IPv6 the /// interface has IPv6 off (no link-local address), as Docker does. On an /// IPv6-only network `ip` is only the name the container is kept by (its /// MAC is made from it): neither the interface nor the bridge gets it. @@ -749,7 +812,7 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc: netlink::add_address6(&mut inner, index, v.ip, v.prefix)?; } netlink::set_up(&mut inner, index)?; - if n == 0 && !internal && !no_ipv4 { + if !internal && !no_ipv4 { netlink::add_default_route(&mut inner, index, gateway)?; } if let Some(v) = v6.filter(|_| !internal) { @@ -839,4 +902,36 @@ fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 000000 // Only the unreachable default on lo: no IPv6 uplink. assert_eq!(default_route6_iface(&routes.lines().skip(2).collect::>().join("\n")), None); } + + fn up(veth: &str, v4: bool, v6: bool) -> Uplink { + Uplink { veth: veth.into(), ifname: veth.into(), v4: v4.then_some([10, 0, 0, 1]), v6: v6.then_some([0xfd; 16]) } + } + + #[test] + fn internal_networks_are_no_uplink() { + let v6 = Some(Ip6 { ip: [0xfd; 16], prefix: 64, gateway: [0xfd; 16] }); + assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, no_ipv4: false }), None); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], None, Plug::default()).unwrap(); + assert_eq!((u.ifname.as_str(), u.v4, u.v6), ("eth1", Some([10, 0, 0, 1]), None)); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { internal: false, no_ipv4: true }).unwrap(); + assert_eq!((u.v4, u.v6), (None, Some([0xfd; 16]))); + } + + #[test] + fn the_first_uplink_with_each_family_holds_its_default_route() { + let ups = [up("a", false, true), up("b", true, false), up("c", true, true)]; + let (r4, r6) = route_holders(&ups); + assert_eq!((r4.map(|u| u.veth.as_str()), r6.map(|u| u.veth.as_str())), (Some("b"), Some("a"))); + assert_eq!(route_holders(&[]), (None, None)); + } + + #[test] + fn a_disconnect_that_takes_no_default_route_touches_nothing() { + // The pid is never used: nothing to hand over, so no namespace is opened. + let mut ups = vec![up("a", true, true), up("b", true, true)]; + hand_over_default_routes(-1, &mut ups, "b").unwrap(); + assert_eq!(ups, [up("a", true, true)]); + hand_over_default_routes(-1, &mut ups, "a").unwrap(); + assert!(ups.is_empty()); + } } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 69fbb926b..1dd81942b 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -350,30 +350,36 @@ pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> /// The IPv6 default route through `gateway` on `index`. The first network /// with IPv6 a container joins keeps it: a second one is EEXIST, left be. pub fn add_default_route6(nl: &mut Netlink, index: i32, gateway: [u8; 16]) -> io::Result<()> { - let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); - let mut rt = [0u8; 12]; - rt[0] = libc::AF_INET6 as u8; - rt[4] = libc::RT_TABLE_MAIN; - rt[5] = libc::RTPROT_BOOT; - rt[6] = libc::RT_SCOPE_UNIVERSE; - rt[7] = libc::RTN_UNICAST; - m.raw(&rt).attr(RTA_GATEWAY, &gateway).attr_u32(RTA_OIF, index as u32); - match nl.request(&mut [m]) { - Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), - r => r, - } + default_route(nl, libc::AF_INET6, &gateway, index, NLM_F_EXCL) } +/// The IPv4 default route through `gateway` on `index`. As with IPv6 the +/// first non-internal network keeps it: without EXCL Linux would take a +/// second default of the same metric, and send through either. pub fn add_default_route(nl: &mut Netlink, index: i32, gateway: [u8; 4]) -> io::Result<()> { - let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE); + default_route(nl, libc::AF_INET, &gateway, index, NLM_F_EXCL) +} + +/// Moves the IPv4 default route to `gateway` on `index`, or adds it. +pub fn replace_default_route(nl: &mut Netlink, index: i32, gateway: [u8; 4]) -> io::Result<()> { + default_route(nl, libc::AF_INET, &gateway, index, NLM_F_REPLACE) +} + +/// Moves the IPv6 default route to `gateway` on `index`, or adds it. +pub fn replace_default_route6(nl: &mut Netlink, index: i32, gateway: [u8; 16]) -> io::Result<()> { + default_route(nl, libc::AF_INET6, &gateway, index, NLM_F_REPLACE) +} + +fn default_route(nl: &mut Netlink, family: i32, gateway: &[u8], index: i32, flags: u16) -> io::Result<()> { + let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE | flags); // struct rtmsg: family, dst_len, src_len, tos, table, protocol, scope, type, flags. let mut rt = [0u8; 12]; - rt[0] = libc::AF_INET as u8; + rt[0] = family as u8; rt[4] = libc::RT_TABLE_MAIN; rt[5] = libc::RTPROT_BOOT; rt[6] = libc::RT_SCOPE_UNIVERSE; rt[7] = libc::RTN_UNICAST; - m.raw(&rt).attr(RTA_GATEWAY, &gateway).attr_u32(RTA_OIF, index as u32); + m.raw(&rt).attr(RTA_GATEWAY, gateway).attr_u32(RTA_OIF, index as u32); match nl.request(&mut [m]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, diff --git a/docs/fix-registry.md b/docs/fix-registry.md index e0b2dc04b..e8fbe20ff 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 +### #193 Networks: give secondary external networks an IPv4 default route and hand default routes over on disconnect (unreleased) +- Fixes: #381 macOS: no IPv4 default route when an internal network occupies eth0 +- Caused: none known +- Caused by: - +- Check: `connect-keeps-default`, `internal-first-no-default`, `internal-first-external-default`, `internal-first-external-restart`, `disconnect-last-external-no-default`, `internal-first-second-external`, `disconnect-hands-default-on`, `internal-first-ipv6-no-default`, `disconnect-hands-ipv6-default-on` + ### #759 Engine: inspect gives back HostConfig's Binds, Mounts and Tmpfs, so a recreate keeps its volumes (unreleased) - Fixes: #610 Engine: `docker inspect` drops `HostConfig.Binds`, `HostConfig.Mounts`, `HostConfig.Tmpfs` and `Config.Volumes`, so Watchtower, Portainer and Arcane lose volumes and binds when recreating containers - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 493d225fb..e20390de6 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1724,7 +1724,9 @@ $D rm -f ren2 >/dev/null; $D rmi kiri-test/committed:1 kiri-test/committed:2 kir section "network connect and disconnect" $D network create na >/dev/null; $D network create nb >/dev/null $D run -d --name multi --network na nginx:alpine >/dev/null; sleep 0.3 +FIRST_DEFAULT=$($D exec multi ip -4 route show default) t connect "eth1" bash -c "$D network connect --alias web2 nb multi && $D exec multi ip -o link" +t connect-keeps-default "$FIRST_DEFAULT" $D exec multi ip -4 route show default t connect-dns-alias "Welcome" $D run --rm --network nb alpine wget -qO- -T 3 http://web2 t connect-dns-name "Welcome" $D run --rm --network nb alpine wget -qO- -T 3 http://multi t connect-inspect "na nb" bash -c "$D inspect -f '{{range \$k, \$v := .NetworkSettings.Networks}}{{\$k}} {{end}}' multi" @@ -1734,6 +1736,38 @@ code connect-twice 1 $D network connect nb multi t disconnect "no-eth1" bash -c "$D network disconnect nb multi && ($D exec multi ip -o link | grep -q eth1 && echo still || echo no-eth1)" t disconnect-dns-gone "bad address" $D run --rm --network nb alpine wget -qO- -T 2 http://web2 t compose-multi-net "PONG" bash -c "d=\$(mktemp -d); printf 'services:\n db:\n image: redis:7-alpine\n networks: [back]\n app:\n image: redis:7-alpine\n command: sh -c \"sleep 1; redis-cli -h db ping; sleep 30\"\n networks: [front, back]\nnetworks:\n front: {}\n back: {}\n' > \$d/compose.yaml; cd \$d && $D compose -p kirinet up -d >/dev/null 2>&1; sleep 3; $D compose -p kirinet logs app; $D compose -p kirinet down >/dev/null 2>&1; rm -rf \$d" +# An internal primary network must not prevent a later external network +# from supplying IPv4 egress, including when all attachments are restored. +$D network create --internal ni >/dev/null +$D run -d --name late-egress --network ni alpine sleep 60 >/dev/null +t internal-first-no-default "none" $D exec late-egress sh -c 'ip -4 route show default | grep -q default && echo default || echo none' +$D network connect na late-egress +EXTERNAL_GATEWAY=$($D network inspect na -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') +t internal-first-external-default "default via $EXTERNAL_GATEWAY dev eth1" $D exec late-egress ip -4 route show default +$D restart -t 1 late-egress >/dev/null +t internal-first-external-restart "default via $EXTERNAL_GATEWAY dev eth1" $D exec late-egress ip -4 route show default +# Leaving the only outside network takes the route; a second outside network +# keeps it where it is; leaving the network that holds it hands it on, as +# Docker does. +$D network disconnect na late-egress +t disconnect-last-external-no-default "none" $D exec late-egress sh -c 'ip -4 route show default | grep -q default && echo default || echo none' +$D network connect na late-egress +$D network connect nb late-egress +t internal-first-second-external "default via $EXTERNAL_GATEWAY dev eth1" $D exec late-egress ip -4 route show default +NB_GATEWAY=$($D network inspect nb -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') +$D network disconnect na late-egress +t disconnect-hands-default-on "default via $NB_GATEWAY dev eth2" $D exec late-egress ip -4 route show default +$D rm -f late-egress >/dev/null; $D network rm ni >/dev/null +$D network create --internal --ipv6 --subnet fd00:193:0::/64 ni6 >/dev/null +$D network create --ipv6 --subnet fd00:193:1::/64 --gateway fd00:193:1::1 na6 >/dev/null +$D network create --ipv6 --subnet fd00:193:2::/64 --gateway fd00:193:2::1 nb6 >/dev/null +$D run -d --name late-egress6 --network ni6 alpine sleep 60 >/dev/null +t internal-first-ipv6-no-default "none" $D exec late-egress6 sh -c 'ip -6 route show default | grep -q default && echo default || echo none' +$D network connect na6 late-egress6 +$D network connect nb6 late-egress6 +$D network disconnect na6 late-egress6 +t disconnect-hands-ipv6-default-on "default via fd00:193:2::1 dev eth2" $D exec late-egress6 ip -6 route show default +$D rm -f late-egress6 >/dev/null; $D network rm ni6 na6 nb6 >/dev/null $D rm -f multi >/dev/null; $D network rm na nb >/dev/null # A rename has to replace the guest's DNS names too: the new name resolves # and the old one stops, as with Docker's embedded DNS, on every network the diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 037907177..e958399a6 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -168,6 +168,18 @@ t ipv6-host-nat "masquerade" "apk add -q nftables >/dev/null 2>&1; nft list tabl t ipv6-port "Welcome to nginx" "docker run -d --name web6 -p 18082:80 nginx:alpine >/dev/null; for i in \$(seq 30); do curl -sg 'http://[::1]:18082' && break; sleep 0.3; done" t ipv6-cleanup "gone" "docker rm -f v6a web6 >/dev/null; docker network rm lh6 >/dev/null; for i in \$(seq 20); do nft list table ip6 kiri >/dev/null 2>&1 || { echo gone; break; }; sleep 0.1; done" t ipv6-forwarding-restored "0" "cat /proc/sys/net/ipv6/conf/all/forwarding" +# Secondary external networks get the default route when eth0 is --internal, +# keep the first default route when another external network joins, and hand +# the IPv4/IPv6 default route on when the network holding it is disconnected (#381, #193). +t connect-keeps-default "same" "docker network create lh-na >/dev/null && docker network create lh-nb >/dev/null && docker run -d --name lh-multi --network lh-na alpine sleep 60 >/dev/null && first=\$(docker exec lh-multi ip -4 route show default) && docker network connect lh-nb lh-multi && [ \"\$(docker exec lh-multi ip -4 route show default)\" = \"\$first\" ] && echo same || echo changed; docker rm -f lh-multi >/dev/null" +t internal-first-no-default "none" "docker network create --internal lh-ni >/dev/null && docker run -d --name lh-late --network lh-ni alpine sleep 60 >/dev/null && (docker exec lh-late ip -4 route show default | grep -q default && echo default || echo none)" +t internal-first-external-default "eth1-ok" "docker network connect lh-na lh-late && gw=\$(docker network inspect lh-na -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker exec lh-late ip -4 route show default | grep -q \"default via \$gw dev eth1\" && echo eth1-ok" +t internal-first-external-restart "eth1-ok" "docker restart -t 1 lh-late >/dev/null && gw=\$(docker network inspect lh-na -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker exec lh-late ip -4 route show default | grep -q \"default via \$gw dev eth1\" && echo eth1-ok" +t disconnect-last-external-no-default "none" "docker network disconnect lh-na lh-late && (docker exec lh-late ip -4 route show default | grep -q default && echo default || echo none)" +t internal-first-second-external "1:eth1-ok" "docker network connect lh-na lh-late && docker network connect lh-nb lh-late && gw=\$(docker network inspect lh-na -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && n=\$(docker exec lh-late ip -4 route show default | wc -l | tr -d ' ') && docker exec lh-late ip -4 route show default | grep -q \"default via \$gw dev eth1\" && echo \"\$n:eth1-ok\"" +t disconnect-hands-default-on "eth2-ok" "docker network disconnect lh-na lh-late && gw=\$(docker network inspect lh-nb -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker exec lh-late ip -4 route show default | grep -q \"default via \$gw dev eth2\" && echo eth2-ok; docker rm -f lh-late >/dev/null; docker network rm lh-ni lh-na lh-nb >/dev/null" +t internal-first-ipv6-no-default "none" "docker network create --internal --ipv6 --subnet fd00:193:0::/64 lh-ni6 >/dev/null && docker network create --ipv6 --subnet fd00:193:1::/64 --gateway fd00:193:1::1 lh-na6 >/dev/null && docker network create --ipv6 --subnet fd00:193:2::/64 --gateway fd00:193:2::1 lh-nb6 >/dev/null && docker run -d --name lh-late6 --network lh-ni6 alpine sleep 60 >/dev/null && (docker exec lh-late6 ip -6 route show default | grep -q default && echo default || echo none)" +t disconnect-hands-ipv6-default-on "default via fd00:193:2::1 dev eth2" "docker network connect lh-na6 lh-late6 && docker network connect lh-nb6 lh-late6 && docker network disconnect lh-na6 lh-late6 && docker exec lh-late6 ip -6 route show default; docker rm -f lh-late6 >/dev/null; docker network rm lh-ni6 lh-na6 lh-nb6 >/dev/null" # A build's --add-host host-gateway is the bridge gateway, as for docker run (not the Mac VM's 198.19.248.254). t build-host-gateway "GW-OK" "gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}'); mkdir -p /bhg && printf 'FROM $KIRI_REG/alpine:3.21\\nRUN grep -w hgw /etc/hosts\\n' > /bhg/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache --add-host hgw:host-gateway /bhg 2>&1 | grep -q \"\$gw\" && echo GW-OK" # A privileged container must not touch the host's /dev. The kernel has one diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 655ea42e6..861f2c795 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -242,3 +242,12 @@ commit-no-marker #131 docker commit must not include an untouched /.dockerenv in inspect-binds #610 docker inspect omitted HostConfig.Binds, dropping -v binds, named volumes and socket paths on container recreate inspect-mounts-tmpfs #610 docker inspect omitted HostConfig.Mounts, HostConfig.Tmpfs and Config.Volumes inspect-recreate-mounts #610 recreating a container from its inspect Config and HostConfig (Watchtower, Portainer, Arcane) lost its volumes, read-only binds, tmpfs and socket mounts +connect-keeps-default #381 connecting a second external network must keep the first external network's IPv4 default route without adding a duplicate +internal-first-no-default #381 an --internal network on eth0 must never supply an IPv4 default route +internal-first-external-default #381 a container with an --internal network on eth0 and an external network on eth1 got no IPv4 default route +internal-first-external-restart #381 restarting a container whose eth0 is --internal and eth1 is external must restore the IPv4 default route on eth1 +disconnect-last-external-no-default #381 disconnecting the last external network must leave a container on --internal networks with no default route +internal-first-second-external #381 attaching a second external network after an --internal primary network must keep the first external network's default route +disconnect-hands-default-on #381 disconnecting the external network that holds the IPv4 default route must hand the default route over to the next remaining external network +internal-first-ipv6-no-default #381 an --internal IPv6 network on eth0 must never supply an IPv6 default route +disconnect-hands-ipv6-default-on #381 disconnecting the external IPv6 network that holds the IPv6 default route must hand the default route over to the next remaining external IPv6 network From 09a83f431e91db846c19c7a0c4c9e87681a8cd2d Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 18:17:40 +0100 Subject: [PATCH 021/157] Engine: inspect keeps an exposed port's protocol, UDP included (#620) Co-authored-by: JEONG KITAE --- crates/kiri/src/daemon/api.rs | 159 ++++++++++++++++++++++++------- crates/kiri/src/daemon/engine.rs | 53 ++++++++++- docs/fix-registry.md | 6 ++ tests/e2e.sh | 3 + tests/linux-host.sh | 3 + tests/regressions.tsv | 1 + 6 files changed, 189 insertions(+), 36 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index c698f80a4..243210be0 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -1316,14 +1316,19 @@ fn pull_hint(e: &kiri_image::registry::Error, registry: &str, proxy: Option<&str /// `-p` (`HostConfig.PortBindings`) and `-P` (`PublishAllPorts`: every port /// the image or `--expose` declares, on a free host port). -fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result, Error> { +fn port_bindings(body: &Value, exposed: &[String]) -> Result, Error> { let parse = |key: &str| -> Result<(u16, String), Error> { let (port, proto) = key.split_once('/').unwrap_or((key, "tcp")); - let port = port.parse().map_err(|_| Error::BadRequest(format!("invalid port {key}")))?; + let port: u16 = port + .parse() + .ok() + .filter(|&p| p > 0 && port.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(|| Error::BadRequest(format!("invalid port {key}")))?; + let proto = proto.to_ascii_lowercase(); if proto != "tcp" && proto != "udp" { return Err(Error::BadRequest(format!("Kiri forwards TCP and UDP ports, not {key}"))); } - Ok((port, proto.to_owned())) + Ok((port, proto)) }; let mut out = Vec::new(); if let Some(map) = body["HostConfig"]["PortBindings"].as_object() { @@ -1344,17 +1349,8 @@ fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Re } } if body["HostConfig"]["PublishAllPorts"].as_bool() == Some(true) { - let mut exposed: Vec = body["ExposedPorts"].as_object().map(|m| m.keys().cloned().collect()).unwrap_or_default(); - // The image's own EXPOSE lines live in its config blob. - if let Ok(bytes) = engine.store.read_config(&image.config_digest) { - if let Ok(cfg) = serde_json::from_slice::(&bytes) { - if let Some(m) = cfg["config"]["ExposedPorts"].as_object() { - exposed.extend(m.keys().cloned()); - } - } - } for key in exposed { - let Ok((container_port, proto)) = parse(&key) else { continue }; + let Ok((container_port, proto)) = parse(key) else { continue }; if !out.iter().any(|b| b.container_port == container_port && b.proto == proto) { out.push(super::ports::Binding { container_port, proto, host_ip: String::new(), host_port: 0 }); } @@ -1992,17 +1988,16 @@ fn volumes(req: &Request, engine: &Engine) -> Result { Ok(json!({"Volumes": list, "Warnings": []})) } -/// The TCP ports an image declares (EXPOSE) plus `--expose`. -fn exposed_ports(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Vec { - let mut keys: Vec = body["ExposedPorts"].as_object().map(|m| m.keys().cloned().collect()).unwrap_or_default(); - if let Ok(bytes) = engine.store.read_config(&image.config_digest) { - if let Ok(cfg) = serde_json::from_slice::(&bytes) { - if let Some(m) = cfg["config"]["ExposedPorts"].as_object() { - keys.extend(m.keys().cloned()); +/// The image's and create request's ExposedPorts keys; a bare port means TCP. +fn exposed_ports(body: &Value, image_cfg: &Value) -> Vec { + let mut ports = Vec::new(); + for map in [body["ExposedPorts"].as_object(), image_cfg["config"]["ExposedPorts"].as_object()].into_iter().flatten() { + for key in map.keys() { + if let Some(norm) = super::engine::normalize_exposed_key(key) { + ports.push(norm); } } } - let mut ports: Vec = keys.iter().filter(|k| k.ends_with("/tcp") || !k.contains('/')).filter_map(|k| k.split('/').next()?.parse().ok()).collect(); ports.sort_unstable(); ports.dedup(); ports @@ -2036,13 +2031,13 @@ fn inspect_bindings(ports: &[super::ports::Binding]) -> Value { /// Config.ExposedPorts: the image's and `--expose`'s ports, and every /// published one, as Docker lists them (`"80/tcp": {}`); null with none, /// as Docker leaves it out. -fn inspect_exposed(ports: &[super::ports::Binding], exposed: &[u16]) -> Value { +fn inspect_exposed(ports: &[super::ports::Binding], exposed: &[String]) -> Value { let mut m = serde_json::Map::new(); for b in ports { m.insert(format!("{}/{}", b.container_port, b.proto), json!({})); } - for p in exposed { - m.entry(format!("{p}/tcp")).or_insert_with(|| json!({})); + for key in exposed { + m.entry(key.clone()).or_insert_with(|| json!({})); } if m.is_empty() { Value::Null } else { Value::Object(m) } } @@ -2061,7 +2056,7 @@ fn ports_map(c: &Container) -> Value { /// given) every exposed or `-p` port that has none as a key with a null value /// (`"80/tcp": null`), as Docker shows them. Traefik's docker provider picks /// a container's port from these keys alone. -fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option<(&[super::ports::Binding], &[u16])>) -> Value { +fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option<(&[super::ports::Binding], &[String])>) -> Value { let mut m = serde_json::Map::new(); for (b, ip, port) in bound { let key = format!("{}/{}", b.container_port, b.proto); @@ -2074,8 +2069,8 @@ fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option< for b in asked { m.entry(format!("{}/{}", b.container_port, b.proto)).or_insert(Value::Null); } - for p in exposed { - m.entry(format!("{p}/tcp")).or_insert(Value::Null); + for key in exposed { + m.entry(key.clone()).or_insert(Value::Null); } } Value::Object(m) @@ -2400,7 +2395,8 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { let healthcheck = healthcheck_from(&body, &image_cfg)?; let (entrypoint, cmd) = command(strings(&body["Entrypoint"]), strings(&body["Cmd"]), &image.config.entrypoint, &image.config.cmd)?; let mounts = mounts(&body, engine, &image)?; - let ports = port_bindings(&body, engine, &image)?; + let exposed = exposed_ports(&body, &image_cfg); + let ports = port_bindings(&body, &exposed)?; if !ports.is_empty() && network_mode == "none" { return Err(Error::BadRequest("a container with --network none cannot publish ports".into())); } @@ -2470,7 +2466,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { aliases, extra_hosts, ports, - exposed: exposed_ports(&body, engine, &image), + exposed, host_opts, volumes_from: strings(&host["VolumesFrom"]).unwrap_or_default(), pid_mode, @@ -5153,6 +5149,105 @@ mod network_option_tests { } } + #[test] + fn inspect_keeps_exposed_protocols_from_the_image_and_create() { + let dir = std::env::temp_dir().join(format!("kiri-exposed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({ + "architecture": "arm64", "os": "linux", + "config": {"Cmd": ["true"], "ExposedPorts": {"53/udp": {}, "132/SCTP": {}, "0/tcp": {}, "bad/udp": {}}} + }); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:dns".into(), &digest, &cfg, Vec::new())).unwrap(); + + let udp = json!({"53/udp": [{"HostIp": "127.0.0.1", "HostPort": "5353"}]}); + for bindings in [json!({}), udp.clone()] { + let body = json!({ + "Image": "demo:dns", + "ExposedPorts": { + "53": {}, "53/TCP": {}, "5353/UDP": {}, + "0": {}, "0/udp": {}, "70000/tcp": {}, "+53/tcp": {}, "53/": {}, "53/udp/extra": {}, "53/u dp": {} + }, + "HostConfig": {"PortBindings": bindings} + }); + let created = create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + let id = created["Id"].as_str().unwrap(); + let inspected = container_inspect(&engine, id).unwrap(); + assert_eq!(inspected["Config"]["ExposedPorts"], json!({"132/sctp": {}, "53/tcp": {}, "53/udp": {}, "5353/udp": {}})); + assert_eq!(inspected["HostConfig"]["PortBindings"], bindings); + engine + .with(id, |c| { + // Deterministic normalized order in stored Spec.exposed. + assert_eq!(c.spec.exposed, ["132/sctp", "53/tcp", "53/udp", "5353/udp"]); + let bound: Vec<_> = c.spec.ports.iter().map(|b| (b.clone(), b.host_ip.clone(), b.host_port)).collect(); + assert_eq!( + ports_map_of(&bound, Some((&c.spec.ports, &c.spec.exposed))), + json!({"132/sctp": null, "53/tcp": null, "53/udp": bindings["53/udp"], "5353/udp": null}) + ); + }) + .unwrap(); + } + + // PublishAllPorts (-P) publishes exposed TCP and UDP ports (normalizing case), + // skips non-TCP/UDP protocols like SCTP without failing, and keeps explicit bindings. + let body = json!({ + "Image": "demo:dns", + "ExposedPorts": {"53": {}, "5353/UDP": {}}, + "HostConfig": {"PublishAllPorts": true, "PortBindings": udp} + }); + let created = create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + let id = created["Id"].as_str().unwrap(); + engine + .with(id, |c| { + let mut got: Vec<_> = c.spec.ports.iter().map(|b| (b.container_port, b.proto.as_str(), b.host_port)).collect(); + got.sort_unstable(); + assert_eq!(got, [(53, "tcp", 0), (53, "udp", 5353), (5353, "udp", 0)]); + }) + .unwrap(); + + // Domain routing picks only TCP exposed ports, ignoring UDP and SCTP. + let dom_body = json!({"Image": "demo:dns", "ExposedPorts": {"53": {}, "5353/UDP": {}}}); + let created = create(&Request::internal("POST", "/containers/create", &[("name", "dnsdom")], serde_json::to_vec(&dom_body).unwrap()), &engine).unwrap(); + let dom_id = created["Id"].as_str().unwrap(); + engine.mark_running_for_test(dom_id, [10, 88, 0, 2]); + let target = engine.route("dnsdom.kiri.localhost").expect("running container domain target"); + assert_eq!(target.exposed, [53]); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn exposed_ports_in_old_and_new_specs_round_trip() { + let mut record = json!({ + "image": "demo:dns", "image_id": "sha256:0123", "entrypoint": [], "cmd": ["true"], "env": [], + "cwd": "/", "user": "", "auto_remove": false, "network_mode": "bridge", "labels": {}, "exposed": [53, 8080] + }); + let old: Spec = serde_json::from_value(record.clone()).unwrap(); + assert_eq!(inspect_exposed(&old.ports, &old.exposed), json!({"53/tcp": {}, "8080/tcp": {}})); + assert_eq!(ports_map_of(&[], Some((&old.ports, &old.exposed))), json!({"53/tcp": null, "8080/tcp": null})); + assert_eq!(serde_json::to_value(&old).unwrap()["exposed"], json!(["53/tcp", "8080/tcp"])); + + record["exposed"] = json!(["132/sctp", "53/tcp", "53/udp"]); + let new: Spec = serde_json::from_value(record.clone()).unwrap(); + let saved = serde_json::to_vec(&new).unwrap(); + let loaded: Spec = serde_json::from_slice(&saved).unwrap(); + assert_eq!(serde_json::to_value(&loaded).unwrap()["exposed"], record["exposed"]); + assert_eq!(inspect_exposed(&loaded.ports, &loaded.exposed), json!({"132/sctp": {}, "53/tcp": {}, "53/udp": {}})); + + // Mixed legacy/new/uppercase/duplicate/invalid entries normalize cleanly, and null is empty. + record["exposed"] = json!([53, "53", "53/TCP", "53/UDP", 0, "0/udp", "bad"]); + let mixed: Spec = serde_json::from_value(record.clone()).unwrap(); + assert_eq!(mixed.exposed, ["53/tcp", "53/udp"]); + + record["exposed"] = Value::Null; + let null_spec: Spec = serde_json::from_value(record).unwrap(); + assert!(null_spec.exposed.is_empty()); + } + #[test] fn container_network_mode_refuses_what_docker_refuses() { assert!(container_mode_allowed(&json!({"HostConfig": {"NetworkMode": "container:web"}}), "web").is_ok()); @@ -5162,13 +5257,13 @@ mod network_option_tests { assert_eq!(inspect_bindings(&ports), json!({"80/tcp": [{"HostIp": "", "HostPort": "8080"}, {"HostIp": "127.0.0.1", "HostPort": ""}], "53/udp": [{"HostIp": "", "HostPort": "5353"}]})); assert_eq!(inspect_bindings(&[]), json!({})); assert_eq!(inspect_exposed(&[], &[]), Value::Null); - assert_eq!(inspect_exposed(&ports, &[80, 9000]), json!({"80/tcp": {}, "53/udp": {}, "9000/tcp": {}})); + assert_eq!(inspect_exposed(&ports, &["80/tcp".into(), "9000/tcp".into()]), json!({"80/tcp": {}, "53/udp": {}, "9000/tcp": {}})); // NetworkSettings.Ports: published ports with their addresses, exposed // ones without as null keys (#492); none at all while not running. let bound = [(b(80, "tcp", "", 8080), "0.0.0.0".to_string(), 8080)]; - assert_eq!(ports_map_of(&[], Some((&[], &[80]))), json!({"80/tcp": null})); + assert_eq!(ports_map_of(&[], Some((&[], &["80/tcp".into()]))), json!({"80/tcp": null})); assert_eq!( - ports_map_of(&bound, Some((&ports, &[80, 9000]))), + ports_map_of(&bound, Some((&ports, &["80/tcp".into(), "9000/tcp".into()]))), json!({"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}], "53/udp": null, "9000/tcp": null}) ); assert_eq!(ports_map_of(&[], None), json!({})); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index d98f38ac6..a229e6e87 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -363,9 +363,9 @@ pub struct Spec { /// `-p` bindings. #[serde(default)] pub ports: Vec, - /// TCP ports the image (or `--expose`) declares; picks the domain's port. - #[serde(default)] - pub exposed: Vec, + /// Port/protocol keys the image or `--expose` declares. + #[serde(default, deserialize_with = "deserialize_exposed")] + pub exposed: Vec, /// Bind mounts as the guest takes them: `source\ttarget\tflags`, where /// `source` is a path inside the VM. #[serde(default)] @@ -474,6 +474,43 @@ pub struct Spec { pub pid_mode: String, } +/// Normalizes an ExposedPorts key (`"53"`, `"53/UDP"`, `"132/sctp"`) to +/// `"/"`, ignoring port 0 and malformed entries. +pub(super) fn normalize_exposed_key(key: &str) -> Option { + let (port, proto) = key.split_once('/').unwrap_or((key, "tcp")); + if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let port: u16 = port.parse().ok()?; + if port == 0 || proto.is_empty() || !proto.bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + Some(format!("{port}/{}", proto.to_ascii_lowercase())) +} + +/// Older containers.json records stored only TCP port numbers. +fn deserialize_exposed<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Port { + Key(String), + Tcp(u16), + } + + let mut ports: Vec = Option::>::deserialize(deserializer)? + .unwrap_or_default() + .into_iter() + .filter_map(|port| match port { + Port::Key(key) => normalize_exposed_key(&key), + Port::Tcp(0) => None, + Port::Tcp(port) => Some(format!("{port}/tcp")), + }) + .collect(); + ports.sort_unstable(); + ports.dedup(); + Ok(ports) +} + /// One `--link name:alias`. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Link { @@ -3634,10 +3671,18 @@ impl Engine { id: c.id.clone(), label: c.spec.labels.get("dev.kiri.http.port").and_then(|v| v.as_str()).and_then(|p| p.parse().ok()), published: c.spec.ports.iter().filter(|b| b.proto != "udp").map(|b| b.container_port).collect(), - exposed: c.spec.exposed.clone(), + exposed: c.spec.exposed.iter().filter_map(|key| key.strip_suffix("/tcp")?.parse().ok()).collect(), }) } + #[cfg(test)] + pub(super) fn mark_running_for_test(&self, id: &str, ip: [u8; 4]) { + let mut st = self.lock(); + let c = st.containers.get_mut(id).unwrap(); + c.status = Status::Running; + c.ip = Some(ip); + } + /// For the Finder view (macOS). #[cfg_attr(not(target_os = "macos"), allow(dead_code))] pub fn fs_stat(&self, id: &str, path: &str) -> io::Result { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index e8fbe20ff..504d3933a 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 +### #620 Engine: inspect keeps an exposed port's protocol, UDP included (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: `inspect-exposed-udp` + ### #193 Networks: give secondary external networks an IPv4 default route and hand default routes over on disconnect (unreleased) - Fixes: #381 macOS: no IPv4 default route when an internal network occupies eth0 - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index e20390de6..fa960213e 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -893,6 +893,9 @@ code port-ipv6-only-not-v4 7 curl -s -m 2 http://127.0.0.1:18183 # Traefik's docker provider picks the port from these keys (#492). t port-exposed-null '{"80/tcp":null,"9000/tcp":null}' bash -c "$D run -d --name pubx --expose 9000 nginx:alpine >/dev/null; $D inspect -f '{{json .NetworkSettings.Ports}}' pubx" t port-exposed-stopped '{}' bash -c "$D stop -t 1 pubx >/dev/null; $D inspect -f '{{json .NetworkSettings.Ports}}' pubx" +# Exposed ports keep their protocol from the image and --expose, UDP and SCTP +# included, in both Config.ExposedPorts and NetworkSettings.Ports (#620). +t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"132/sctp":null,"53/tcp":null,"53/udp":null,"5353/udp":null}' bash -c "$D create --name pubudp-base alpine true >/dev/null && $D commit -c 'EXPOSE 53/udp 132/sctp' pubudp-base kiri-exp-udp:1 >/dev/null && $D run -d --name pubudp --expose 53 --expose 5353/udp kiri-exp-udp:1 sleep 60 >/dev/null && out=\$($D inspect -f '{{json .Config.ExposedPorts}} {{json .NetworkSettings.Ports}}' pubudp); $D rm -f pubudp pubudp-base >/dev/null 2>&1; $D rmi kiri-exp-udp:1 >/dev/null 2>&1; echo \"\$out\"" $D rm -f pub pub2 puball pub6 pubx >/dev/null code port-closed-after-stop 7 curl -s -m 2 http://localhost:18180 diff --git a/tests/linux-host.sh b/tests/linux-host.sh index e958399a6..4139ec2f4 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -912,6 +912,9 @@ t clone3-seccomp-fallback "enosys=67108864:0::/|67108864:0::/|0::/sub eperm=6710 # Config.Volumes so recreating a container from its inspect JSON (Watchtower, # Portainer, Arcane) keeps volumes, :ro, tmpfs and socket binds (#610). t inspect-recreate-mounts "binds=ok code=201 kept|rokept|from-host|bro=ro|vro=ro|t1=ok|t2=ok|ds=ok|ss=ok anon=fresh" "docker rm -f -v lhcm lhcm2 >/dev/null 2>&1; docker volume rm lthcm lthcmro >/dev/null 2>&1; rm -rf /tmp/k610-bind && mkdir -p /tmp/k610-bind && echo from-host > /tmp/k610-bind/hello.txt; docker run --rm -v lthcm:/data -v lthcmro:/rodata alpine sh -c 'echo kept > /data/f; echo rokept > /rodata/f'; docker create --name lhcm -v /tmp/k610-bind:/bind:ro -v lthcm:/data -v /anon -v /var/run/docker.sock:/var/run/docker.sock -v /run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock --mount type=volume,source=lthcmro,target=/rodata,readonly --mount type=tmpfs,target=/t --tmpfs /t2:size=1m alpine sh -c 'd=\$(cat /data/f 2>/dev/null || echo MISSING); r=\$(cat /rodata/f 2>/dev/null || echo MISSING); b=\$(cat /bind/hello.txt 2>/dev/null || echo MISSING); (echo x > /bind/w) 2>&1 | grep -qi \"read-only\" && bro=ro || bro=bad; (echo x > /rodata/w) 2>&1 | grep -qi \"read-only\" && vro=ro || vro=bad; mount | grep -q \"tmpfs on /t \" && t1=ok || t1=no; mount | grep -q \"tmpfs on /t2 \" && t2=ok || t2=no; test -S /var/run/docker.sock && ds=ok || ds=no; test -S /run/host-services/ssh-auth.sock && ss=ok || ss=no; echo \"\$d|\$r|\$b|bro=\$bro|vro=\$vro|t1=\$t1|t2=\$t2|ds=\$ds|ss=\$ss\"' >/dev/null; binds=\$(docker inspect -f '{{json .HostConfig.Binds}}' lhcm | python3 -c 'import json, sys; got = set(json.load(sys.stdin) or []); want = {\"/tmp/k610-bind:/bind:ro\", \"lthcm:/data\", \"/var/run/docker.sock:/var/run/docker.sock\", \"/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock\"}; print(\"ok\" if got == want else sorted(got))'); a1=\$(docker inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' lhcm); b=\$(curl -s --unix-socket /root/.kiri/run/docker.sock http://d/v1.47/containers/lhcm/json | python3 -c 'import json, sys; c = json.load(sys.stdin); print(json.dumps(dict(c[\"Config\"], HostConfig=c[\"HostConfig\"])))'); code=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket /root/.kiri/run/docker.sock -X POST -H 'Content-Type: application/json' -d \"\$b\" 'http://d/v1.47/containers/create?name=lhcm2'); out=\$(docker start -a lhcm2); a2=\$(docker inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' lhcm2); [ -n \"\$a1\" ] && [ -n \"\$a2\" ] && [ \"\$a1\" != \"\$a2\" ] && an=fresh || an=\"same:\$a1:\$a2\"; docker rm -f -v lhcm lhcm2 >/dev/null 2>&1; docker volume rm lthcm lthcmro >/dev/null 2>&1; rm -rf /tmp/k610-bind; echo \"binds=\$binds code=\$code \$out anon=\$an\"" +# Exposed ports keep their protocol from the image and --expose, UDP and SCTP +# included, in both Config.ExposedPorts and NetworkSettings.Ports (#620). +t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"132/sctp":null,"53/tcp":null,"53/udp":null,"5353/udp":null}' "docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; docker create --name lhudp-base alpine true >/dev/null && docker commit -c 'EXPOSE 53/udp 132/sctp' lhudp-base kiri-lh-udp:1 >/dev/null && docker run -d --name lhudp --expose 53 --expose 5353/udp kiri-lh-udp:1 sleep 60 >/dev/null && out=\$(docker inspect -f '{{json .Config.ExposedPorts}} {{json .NetworkSettings.Ports}}' lhudp); docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; echo \"\$out\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device: an image layer with a diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 861f2c795..30ca7d3f5 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -251,3 +251,4 @@ internal-first-second-external #381 attaching a second external network after an disconnect-hands-default-on #381 disconnecting the external network that holds the IPv4 default route must hand the default route over to the next remaining external network internal-first-ipv6-no-default #381 an --internal IPv6 network on eth0 must never supply an IPv6 default route disconnect-hands-ipv6-default-on #381 disconnecting the external IPv6 network that holds the IPv6 default route must hand the default route over to the next remaining external IPv6 network +inspect-exposed-udp #620 docker inspect dropped non-TCP exposed ports (such as 53/udp or 132/sctp) from Config.ExposedPorts and NetworkSettings.Ports From a4ac820d9e179eac6b25b58b6a4d397b49031a07 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 18:43:16 +0100 Subject: [PATCH 022/157] Linux: bind-mount standard devices and clamp default limits when Kiri runs in a user namespace (#597) Co-authored-by: Randy Fay --- crates/kiri-init/src/linux/container.rs | 230 ++++++++++++++++++++++-- docs/fix-registry.md | 6 + tests/linux-host.sh | 24 ++- tests/regressions.tsv | 2 + 4 files changed, 241 insertions(+), 21 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 5689b3b3b..3e471384d 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -572,7 +572,18 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

! { // While still root with every capability: raising a hard limit needs // CAP_SYS_RESOURCE. - super::hostopts::set_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e)); + apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e)); for cap in 0..=LAST_CAP { if !p.privileged && p.caps & (1 << cap) == 0 { @@ -2316,22 +2327,19 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64, host: &HostAppli if privileged { copy_host_devices(Path::new("/dev"), Path::new("dev"))?; } - for (name, major, minor) in [ - (c"dev/null", 1, 3), - (c"dev/zero", 1, 5), - (c"dev/full", 1, 7), - (c"dev/random", 1, 8), - (c"dev/urandom", 1, 9), - (c"dev/tty", 5, 0), + for (host, name, major, minor) in [ + (c"/dev/null", c"dev/null", 1, 3), + (c"/dev/zero", c"dev/zero", 1, 5), + (c"/dev/full", c"dev/full", 1, 7), + (c"/dev/random", c"dev/random", 1, 8), + (c"/dev/urandom", c"dev/urandom", 1, 9), + (c"/dev/tty", c"dev/tty", 5, 0), ] { - if privileged { + if privileged && is_char_dev(name) { // Copied from the host already. continue; } - sys::mknod(name, libc::S_IFCHR | 0o666, major, minor)?; - // mknod applies the umask; every user in the container needs these. - // SAFETY: valid NUL-terminated path. - unsafe { libc::chmod(name.as_ptr(), 0o666) }; + make_or_bind_dev(host, name, major, minor)?; } // The host's /proc still, before the pivot. for (target, link) in dev_links(Path::new("/proc/kcore").exists()) { @@ -2360,6 +2368,117 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64, host: &HostAppli Ok(()) } +/// The default `nofile` soft and hard limit the daemon sends when a run sets +/// no `--ulimit nofile=...` of its own. +const DEFAULT_NOFILE: u64 = 1_048_576; +const DEFAULT_PING_MAX: u64 = 2_147_483_647; + +/// The highest group id in the `/proc/self/gid_map` extent that maps 0, +/// clamped to `2147483647`. In the initial user namespace (`0 0 4294967295`) +/// this is `2147483647`; in a user namespace (`0 0 65536`) the kernel refuses +/// any upper bound that is not mapped (`EINVAL` on `ping_group_range`, #597). +fn ping_group_max(gid_map: &str) -> u64 { + for line in gid_map.lines() { + let mut f = line.split_whitespace(); + if let (Some("0"), Some(_outer), Some(count)) = (f.next(), f.next(), f.next()) + && let Ok(n) = count.parse::() + && n > 0 + { + return (n - 1).min(DEFAULT_PING_MAX); + } + } + DEFAULT_PING_MAX +} + +/// Caps the default `nofile` limit (`1048576:1048576`) to `rlim_max` when the +/// engine's own hard limit is lower (as in a user namespace or a nested +/// container with a `524288` ceiling, where raising past it is refused). An +/// explicit `--ulimit nofile=...` is left as given, so a lower value applies +/// and one above `rlim_max` still fails with the kernel's error. +fn cap_default_nofile(rlimits: &mut [(u32, u64, u64)], rlim_max: u64) -> bool { + let mut capped = false; + if rlim_max > 0 && rlim_max < DEFAULT_NOFILE { + for (res, soft, hard) in rlimits { + if *res == libc::RLIMIT_NOFILE as u32 && *soft == DEFAULT_NOFILE && *hard == DEFAULT_NOFILE { + *soft = rlim_max; + *hard = rlim_max; + capped = true; + } + } + } + capped +} + +/// Applies resource limits, falling back to the engine's own hard `nofile` +/// limit if the default `1048576` is refused with `EPERM` (#597). +fn apply_rlimits(rlimits: &[(u32, u64, u64)]) -> io::Result<()> { + match super::hostopts::set_rlimits(rlimits) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => { + let mut rl = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; + // SAFETY: valid writable rlimit struct. + if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rl) } != 0 { + return Err(e); + } + let mut capped = rlimits.to_vec(); + if !cap_default_nofile(&mut capped, rl.rlim_max) { + return Err(e); + } + super::hostopts::set_rlimits(&capped) + } + Err(e) => Err(e), + } +} + +/// Whether `path` already exists as a character device node (never following a symlink). +fn is_char_dev(path: &CStr) -> bool { + fstat_at(libc::AT_FDCWD, path, libc::AT_SYMLINK_NOFOLLOW) + .is_ok_and(|st| st.st_mode & libc::S_IFMT == libc::S_IFCHR) +} + +/// Creates a standard character device node at `target` on the container's +/// fresh `/dev` tmpfs, or, when `mknod` is refused in a user namespace +/// (`EPERM`), bind-mounts `host` onto a newly created empty file at `target`, +/// as runc does (#597). +fn make_or_bind_dev(host: &CStr, target: &CStr, major: u32, minor: u32) -> io::Result<()> { + match sys::mknod(target, libc::S_IFCHR | 0o666, major, minor) { + Ok(()) => { + // mknod applies the umask; every user in the container needs these. + // SAFETY: valid NUL-terminated path. + unsafe { libc::chmod(target.as_ptr(), 0o666) }; + Ok(()) + } + Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => { + let (host_fd, target_fd) = prepare_dev_bind(host, target)?; + let src = CString::new(format!("/proc/self/fd/{}", host_fd.as_raw_fd())).expect("no NUL"); + let dst = CString::new(format!("/proc/self/fd/{}", target_fd.as_raw_fd())).expect("no NUL"); + sys::mount(&src, &dst, c"none", libc::MS_BIND, None) + } + Err(e) => Err(e), + } +} + +/// Verifies that `host` is a real character device (not a symlink or other +/// file) and creates an empty regular mountpoint file at `target` without +/// following symlinks or overwriting an existing entry. +fn prepare_dev_bind(host: &CStr, target: &CStr) -> io::Result<(OwnedFd, OwnedFd)> { + let host_fd = open_at(libc::AT_FDCWD, host, libc::O_PATH | libc::O_NOFOLLOW)?; + let st = fstat_at(host_fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + if st.st_mode & libc::S_IFMT != libc::S_IFCHR { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} is not a character device", host.to_string_lossy()), + )); + } + let target_fd = open_at_mode( + libc::AT_FDCWD, + target, + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW, + 0o666, + )?; + Ok((host_fd, target_fd)) +} + /// The links runc makes in a container's /dev (relative to its root): /// /dev/core only when the host has /proc/kcore, as runc checks. fn dev_links(kcore: bool) -> Vec<(&'static CStr, &'static CStr)> { @@ -3767,4 +3886,89 @@ mod tests { (String::new(), hybrid.to_path_buf()) ); } + + /// In a user namespace or nested container whose hard `nofile` limit is + /// below the default `1048576` (#597), only the default `nofile` entry is + /// clamped to `rlim_max`; explicit `--ulimit nofile=...` values and other + /// resources stay untouched. + #[test] + fn cap_default_nofile_clamps_only_the_default_nofile_limit() { + let nofile = libc::RLIMIT_NOFILE as u32; + let nproc = libc::RLIMIT_NPROC as u32; + let mut lims = vec![(nproc, 100, 200), (nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]; + assert!(super::cap_default_nofile(&mut lims, 524_288)); + assert_eq!(lims, [(nproc, 100, 200), (nofile, 524_288, 524_288)]); + + let mut high_host = vec![(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]; + assert!(!super::cap_default_nofile(&mut high_host, super::DEFAULT_NOFILE)); + assert!(!super::cap_default_nofile(&mut high_host, 2_097_152)); + assert!(!super::cap_default_nofile(&mut high_host, 0)); + assert_eq!(high_host, [(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]); + + let mut explicit = vec![(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)]; + assert!(!super::cap_default_nofile(&mut explicit, 524_288)); + assert_eq!( + explicit, + [(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)] + ); + assert_eq!(super::ping_group_max(" 0 0 4294967295\n"), super::DEFAULT_PING_MAX); + assert_eq!(super::ping_group_max(" 0 0 65536\n"), 65_535); + assert_eq!(super::ping_group_max(" 0 1000 1\n 1 100000 65536\n"), 0); + assert_eq!(super::ping_group_max(""), super::DEFAULT_PING_MAX); + } + + /// When `mknod` is refused in a user namespace (#597), `prepare_dev_bind` + /// verifies the host source is a real character device (never following a + /// symlink) and creates the mountpoint file with `O_CREAT | O_EXCL | + /// O_NOFOLLOW` so a symlink or existing file at the target is refused. + #[test] + fn prepare_dev_bind_verifies_char_device_and_refuses_symlinks() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::symlink; + + let (base, dev, _vol, outside) = fill_dirs("dev-bind"); + let cstr = |p: &std::path::Path| CString::new(p.as_os_str().as_bytes()).unwrap(); + + let target = dev.join("null"); + let (_h, _t) = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).expect("fresh target with /dev/null"); + assert!(std::fs::symlink_metadata(&target).unwrap().is_file()); + assert!(super::is_char_dev(c"/dev/null")); + assert!(!super::is_char_dev(&cstr(&target))); + + // Existing file at target is refused with EEXIST. + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + + // Symlink at target (to an existing outside file or dangling) is refused and never followed. + let victim = outside.join("victim"); + std::fs::write(&victim, b"untouched").unwrap(); + let link_existing = dev.join("zero"); + symlink(&victim, &link_existing).unwrap(); + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_existing)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + assert_eq!(std::fs::read(&victim).unwrap(), b"untouched"); + + let gone = outside.join("gone"); + let link_dangling = dev.join("full"); + symlink(&gone, &link_dangling).unwrap(); + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_dangling)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + assert!(!gone.exists()); + + // Non-character-device host sources (regular file, directory, symlink to /dev/null) are refused before creating target. + let fake_chr = outside.join("fake"); + std::fs::write(&fake_chr, b"").unwrap(); + let link_chr = outside.join("null-link"); + symlink("/dev/null", &link_chr).unwrap(); + assert!(!super::is_char_dev(&cstr(&link_chr))); + for bad_src in [&fake_chr, &outside, &link_chr] { + let unmade = dev.join("unmade"); + let e = super::prepare_dev_bind(&cstr(bad_src), &cstr(&unmade)).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput); + assert!(!unmade.exists(), "target must not be created when source is invalid"); + } + + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 504d3933a..c5b1813b7 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 +### #597 Linux host: start containers when the engine runs in a user namespace (unreleased) +- Fixes: #597 Linux host: containers fail to start when the engine runs in a user namespace (`mknod dev/null: Operation not permitted`, default `nofile` above `rlim_max`) +- Caused: none known +- Caused by: - +- Check: `userns-run`, `userns-run-privileged` + ### #620 Engine: inspect keeps an exposed port's protocol, UDP included (unreleased) - Fixes: no issue - Caused: none known diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 4139ec2f4..2e7910ec2 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -917,13 +917,14 @@ t inspect-recreate-mounts "binds=ok code=201 kept|rokept|from-host|bro=ro|vro=ro t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"132/sctp":null,"53/tcp":null,"53/udp":null,"5353/udp":null}' "docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; docker create --name lhudp-base alpine true >/dev/null && docker commit -c 'EXPOSE 53/udp 132/sctp' lhudp-base kiri-lh-udp:1 >/dev/null && docker run -d --name lhudp --expose 53 --expose 5353/udp kiri-lh-udp:1 sleep 60 >/dev/null && out=\$(docker inspect -f '{{json .Config.ExposedPorts}} {{json .NetworkSettings.Ports}}' lhudp); docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; echo \"\$out\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), -# where the kernel refuses mknod of a device: an image layer with a -# character and a block device, a fifo and a file still unpacks, the devices -# left out as Docker leaves them out and the fifo made. Before, the whole -# layer failed ("mknod: Operation not permitted"). That engine runs alone in -# its own container, in a new user namespace (root mapped to root, 65536 -# ids, so /proc/self/uid_map is not "0 0 4294967295") with its own mount -# and network namespaces, and only unpacks: docker load, then docker create. +# where the kernel refuses mknod of a device and raising nofile past the +# outer hard limit (524288): an image layer with a character and a block +# device, a fifo and a file still unpacks, the devices left out as Docker +# leaves them out and the fifo made; and both plain and --privileged +# containers start with /dev/null, /dev/urandom and the outer nofile limit. +# That engine runs alone in its own container, in a new user namespace (root +# mapped to root, 65536 ids, so /proc/self/uid_map is not "0 0 4294967295") +# with its own mount and network namespaces. U="$N-userns" # t, for output got elsewhere than the engine's container. check() { @@ -932,6 +933,7 @@ check() { $D rm -f "$U" >/dev/null 2>&1 $D run -d --name "$U" --privileged --tmpfs /run -v "$BIN:/opt/kiri:ro" alpine sleep 1d >/dev/null $D exec "$U" sh -c 'apk add -q util-linux-misc python3 docker-cli >/dev/null 2>&1' +$D save alpine:latest | $D exec -i "$U" sh -c 'cat > /alpine.tar' $D exec -i "$U" sh -c 'cat > /mkimage.py' <<'PY' import hashlib, io, json, tarfile layer = io.BytesIO() @@ -952,15 +954,21 @@ if ! $D exec "$U" unshare -U -r true 2>/dev/null; then echo " SKIP userns-layer-devices: no user namespace can be made on this host" else got=$($D exec "$U" unshare --user --map-users=0:0:65536 --map-groups=0:0:65536 --setuid=0 --setgid=0 --mount --propagation private --net --fork sh -c ' + ulimit -n 524288 python3 /mkimage.py mkdir -p /var/lib/kiri && mount -t tmpfs t /var/lib/kiri && mount -t tmpfs t /root && ip link set lo up /opt/kiri/kiri daemon > /tmp/engine.log 2>&1 & export DOCKER_HOST=unix:///root/.kiri/run/docker.sock for i in $(seq 120); do docker version >/dev/null 2>&1 && break; sleep 0.25; done docker load -i /devices.tar >/dev/null && docker create kiri-nodes:1 >/dev/null || exit - cd /var/lib/kiri/layers/*/ && for f in dev/kiri-null dev/kiri-loop pipe after; do printf "%s=" $f; stat -c %F $f 2>/dev/null || echo none; done | tr "\n" " " + (cd /var/lib/kiri/layers/*/ && for f in dev/kiri-null dev/kiri-loop pipe after; do printf "%s=" $f; stat -c %F $f 2>/dev/null || echo none; done | tr "\n" " ") + docker load -q -i /alpine.tar >/dev/null + printf "\nrun="; docker run --rm alpine sh -c '\''cat /dev/null; head -c 4 /dev/urandom | wc -c; ulimit -n'\'' 2>&1 | tr "\n" ":" + printf "\npriv="; docker run --rm --privileged alpine sh -c '\''cat /dev/null; head -c 4 /dev/urandom | wc -c'\'' 2>&1 | tr "\n" ":" kill %1' 2>&1 | tr -d '\r') check userns-layer-devices "dev/kiri-null=none dev/kiri-loop=none pipe=fifo after=regular file" "$got" + check userns-run "run=4:524288:" "$got" + check userns-run-privileged "priv=4:" "$got" fi $D rm -f "$U" >/dev/null echo "$PASS passed, $FAIL failed" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 30ca7d3f5..cd2046853 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -252,3 +252,5 @@ disconnect-hands-default-on #381 disconnecting the external network that holds t internal-first-ipv6-no-default #381 an --internal IPv6 network on eth0 must never supply an IPv6 default route disconnect-hands-ipv6-default-on #381 disconnecting the external IPv6 network that holds the IPv6 default route must hand the default route over to the next remaining external IPv6 network inspect-exposed-udp #620 docker inspect dropped non-TCP exposed ports (such as 53/udp or 132/sctp) from Config.ExposedPorts and NetworkSettings.Ports +userns-run #597 when the Linux engine runs inside a user namespace (nested Docker, Coder, Sysbox), container start failed on mknod /dev/null (EPERM) and on raising the default nofile rlimit past the engine's hard limit +userns-run-privileged #597 when the Linux engine runs inside a user namespace, --privileged containers skipped standard /dev nodes after copy_host_devices failed mknod with EPERM From 3151106054ee6e6a220607b051e8618394f52bbe Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 18:51:47 +0100 Subject: [PATCH 023/157] Linux: a memory limit gets as much swap again, and --memory-swap is applied, as on Docker (#523) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nguyễn Đức --- crates/kiri-init/src/linux/cgroup.rs | 36 ++++++-- crates/kiri-proto/src/lib.rs | 46 ++++++++-- crates/kiri/src/daemon/api.rs | 124 ++++++++++++++++++++++++++- crates/kiri/src/daemon/engine.rs | 25 ++++++ crates/kiri/src/daemon/ops.rs | 2 +- docs/fix-registry.md | 6 ++ tests/e2e.sh | 31 +++++++ tests/linux-host.sh | 3 + tests/regressions.tsv | 4 + 9 files changed, 258 insertions(+), 19 deletions(-) diff --git a/crates/kiri-init/src/linux/cgroup.rs b/crates/kiri-init/src/linux/cgroup.rs index ab95013f3..c51a0984c 100644 --- a/crates/kiri-init/src/linux/cgroup.rs +++ b/crates/kiri-init/src/linux/cgroup.rs @@ -36,9 +36,13 @@ pub fn apply_limits(dir: &Path, l: &Limits) -> io::Result<()> { } let mem = if l.memory_max == 0 { "max".into() } else { l.memory_max.to_string() }; write_control(dir, "memory.max", &mem, l.memory_max != 0)?; - // No swap in the VM: a limit is a limit. + // Docker's `--memory-swap`, worked out by the daemon. The VM has no swap, + // so it matters on a Linux host, which may. A kernel without swap or a + // hybrid cgroup tree without the memory controller has no such file; open + // without `O_CREAT` so we never create fake files or hit kernfs `EACCES`. if let Ok(mut f) = OpenOptions::new().write(true).truncate(true).open(dir.join("memory.swap.max")) { - let _ = f.write_all(b"0"); + let swap = if l.swap_max == kiri_proto::NO_LIMIT { "max".into() } else { l.swap_max.to_string() }; + let _ = f.write_all(swap.as_bytes()); } let period = if l.cpu_period == 0 { 100_000 } else { l.cpu_period }; let cpu_max = if l.cpu_quota == 0 { format!("max {period}") } else { format!("{} {period}", l.cpu_quota) }; @@ -290,30 +294,50 @@ mod tests { for f in ["memory.max", "memory.swap.max", "cpu.max", "cpu.weight", "pids.max"] { fs::write(dir.join(f), "").unwrap(); } - let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 0 }; + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 0, swap_max: 67_108_864 }; apply_limits(&dir, &lim).unwrap(); assert_eq!(fs::read_to_string(dir.join("memory.max")).unwrap(), "67108864"); - assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "0"); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "67108864"); assert_eq!(fs::read_to_string(dir.join("cpu.max")).unwrap(), "50000 100000"); assert_eq!(fs::read_to_string(dir.join("cpu.weight")).unwrap(), "250"); assert_eq!(fs::read_to_string(dir.join("pids.max")).unwrap(), "64"); + + // Zero swap (`--memory-swap == --memory`) and unlimited swap (`-1`). + apply_limits(&dir, &Limits { swap_max: 0, ..lim }).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "0"); + apply_limits(&dir, &Limits { swap_max: kiri_proto::NO_LIMIT, ..lim }).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "max"); let _ = fs::remove_dir_all(&dir); } #[test] fn apply_limits_skips_missing_controllers_on_hybrid_tree() { // Hybrid cgroup v2 directory whose controllers are bound to v1: none of - // memory.max, cpu.max, cpu.weight or pids.max exist. + // memory.max, memory.swap.max, cpu.max, cpu.weight or pids.max exist. let dir = temp_cgroup("hybrid"); - let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 134_217_728 }; + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 134_217_728, swap_max: 67_108_864 }; apply_limits(&dir, &lim).unwrap(); // OpenOptions without O_CREAT must not create fake files either. assert!(!dir.join("memory.max").exists()); + assert!(!dir.join("memory.swap.max").exists()); assert!(!dir.join("cpu.max").exists()); assert!(!dir.join("pids.max").exists()); let _ = fs::remove_dir_all(&dir); } + #[test] + fn apply_limits_skips_missing_swap_file_when_memory_exists() { + // Kernel without swap accounting (or VM kernel with no swap): memory.max + // exists, memory.swap.max does not. + let dir = temp_cgroup("no-swap"); + fs::write(dir.join("memory.max"), "").unwrap(); + let lim = Limits { memory_max: 67_108_864, swap_max: 33_554_432, ..Default::default() }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.max")).unwrap(), "67108864"); + assert!(!dir.join("memory.swap.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn apply_limits_writes_available_subset_of_controllers() { let dir = temp_cgroup("subset"); diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 20d359975..316973001 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -51,8 +51,9 @@ pub const INPUT_WINDOW: usize = 4 << 20; /// the container's root is in place. 7 added `CancelStart`, which has no /// reply: an older agent's "unexpected" error would be taken as the reply /// to the next request. 8 added `DnsRename`, another no-reply message, for -/// the same reason. -pub const PROTOCOL: u16 = 8; +/// the same reason. 9 added `Limits::swap_max`: an older agent would read +/// the limits one field short. +pub const PROTOCOL: u16 = 9; /// Most names a `DnsRename` may carry: a name, its aliases and a hostname. pub const MAX_DNS_NAMES: usize = 256; @@ -554,9 +555,10 @@ pub struct RunSpec<'a> { pub seccomp: &'a [u8], } -/// cgroup limits (`--memory`, `--cpus`, `--cpu-shares`, `--pids-limit`). -/// Zero means no limit. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +/// cgroup limits (`--memory`, `--memory-swap`, `--cpus`, `--cpu-shares`, +/// `--pids-limit`). Zero means no limit, except `swap_max` where `0` means no +/// swap and [`NO_LIMIT`] means no limit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Limits { pub memory_max: u64, /// CPU time allowed per `cpu_period` microseconds (`--cpus 1.5` is 150000/100000). @@ -567,6 +569,17 @@ pub struct Limits { pub pids_max: u32, /// `--shm-size` in bytes; 0 means 64 MiB. pub shm_size: u64, + /// cgroup v2 `memory.swap.max` in bytes, [`NO_LIMIT`] for `max`. + pub swap_max: u64, +} + +/// A limit of `max`. +pub const NO_LIMIT: u64 = u64::MAX; + +impl Default for Limits { + fn default() -> Self { + Self { memory_max: 0, cpu_quota: 0, cpu_period: 0, cpu_weight: 0, pids_max: 0, shm_size: 0, swap_max: NO_LIMIT } + } } fn put_limits(out: &mut Vec, l: &Limits) { @@ -576,10 +589,19 @@ fn put_limits(out: &mut Vec, l: &Limits) { put_u32(out, l.cpu_weight); put_u32(out, l.pids_max); put_u64(out, l.shm_size); + put_u64(out, l.swap_max); } fn read_limits(r: &mut Reader<'_>) -> Result { - Ok(Limits { memory_max: r.u64()?, cpu_quota: r.u64()?, cpu_period: r.u32()?, cpu_weight: r.u32()?, pids_max: r.u32()?, shm_size: r.u64()? }) + Ok(Limits { + memory_max: r.u64()?, + cpu_quota: r.u64()?, + cpu_period: r.u32()?, + cpu_weight: r.u32()?, + pids_max: r.u32()?, + shm_size: r.u64()?, + swap_max: r.u64()?, + }) } /// One container's resource use, read from its cgroup and network namespace. @@ -1602,10 +1624,11 @@ mod tests { fn run_spec_lists_survive_encoding() { let mut buf = Vec::new(); let net = Net { bridge: "kiri0", ip: [172, 17, 0, 2], prefix: 16, gateway: [172, 17, 0, 1], extra_hosts: &["1.2.3.4 x"], dns_names: &["web"], opts: &["netns=c0", "nameserver=8.8.8.8"] }; - let limits = Limits { memory_max: 256 << 20, cpu_quota: 150_000, cpu_period: 100_000, cpu_weight: 100, pids_max: 64, shm_size: 1 << 20 }; + let limits = Limits { memory_max: 256 << 20, cpu_quota: 150_000, cpu_period: 100_000, cpu_weight: 100, pids_max: 64, shm_size: 1 << 20, swap_max: 512 << 20 }; encode_run(&mut buf, "c1", &["sha256:top", "sha256:base"], &["echo", "hi"], &["A=1"], "/", "", "c1", 3, net, &["/a\t/b\tro"], &limits, 0b101, &["rlimit\t7\t1024\t2048"], &[]); let Msg::Run(r) = decode(&buf).unwrap() else { panic!() }; assert_eq!(r.id, "c1"); + assert_eq!(r.limits, limits); assert_eq!(r.layers.iter().collect::>(), ["sha256:top", "sha256:base"]); assert_eq!(r.argv.iter().collect::>(), ["echo", "hi"]); assert_eq!(r.env.len(), 1); @@ -1758,6 +1781,13 @@ mod tests { const { assert!(PROTOCOL >= 8) }; } + #[test] + fn the_protocol_version_covers_swap_max() { + // An agent from before `Limits::swap_max` reads the limits one field short. + const { assert!(PROTOCOL >= 9) }; + assert_eq!(Limits::default().swap_max, NO_LIMIT); + } + #[test] fn fs_messages_survive_encoding() { round(Msg::FsStatRequest { id: "c1", path: "/etc" }); @@ -1770,7 +1800,7 @@ mod tests { round(Msg::RemoveBridge { bridge: "kiri3" }); round(Msg::CopyStat { entry: FsEntry { name: "hosts", mode: 0o100644, size: 9, mtime: 3, mtime_nsec: 4, ino: 5 }, link: "" }); round(Msg::CopyDone); - round(Msg::Update { id: "c1", limits: Limits { memory_max: 1, cpu_quota: 2, cpu_period: 3, cpu_weight: 4, pids_max: 5, shm_size: 6 } }); + round(Msg::Update { id: "c1", limits: Limits { memory_max: 1, cpu_quota: 2, cpu_period: 3, cpu_weight: 4, pids_max: 5, shm_size: 6, swap_max: NO_LIMIT } }); round(Msg::Freeze { id: "c1", frozen: true }); round(Msg::StatsQuery { id: "c1" }); round(Msg::ContainerStats(ContainerStats { read_ns: 1, mem_current: 2, online_cpus: 4, rx_bytes: 9, io_write_bytes: 11, ..Default::default() })); diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 243210be0..b36b4c42c 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2226,11 +2226,30 @@ pub(super) fn cpu_weight(shares: u64) -> u32 { ((w * 1e9).round() / 1e9).ceil() as u32 } -pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> super::engine::Limits { +pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> Result { let mut l = base; + // Normalize pre-#545 containers (`memory_max > 0, memory_swap == 0`) to + // Docker's effective `2 * memory` limit before checking updates against it. + l.memory_swap = l.memory_swap(); + // Docker's checks for `--memory-swap`, in Docker's words. + let swap = h["MemorySwap"].as_i64().filter(|s| *s != 0); if let Some(m) = h["Memory"].as_u64().filter(|m| *m > 0) { + if swap.is_none() && l.memory_swap > 0 && m > l.memory_swap as u64 { + return Err(Error::BadRequest("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time".into())); + } l.memory_max = m; } + if let Some(s) = swap { + if s > 0 && l.memory_max == 0 { + return Err(Error::BadRequest("You should always set the Memory limit when using Memoryswap limit, see usage".into())); + } + if s > 0 && (s as u64) < l.memory_max { + return Err(Error::BadRequest("Minimum memoryswap limit should be larger than memory limit, see usage".into())); + } + l.memory_swap = s.max(-1); + } + // Only a memory limit: as much swap again, which Docker writes down. + l.memory_swap = l.memory_swap(); if let Some(n) = h["NanoCpus"].as_u64().filter(|n| *n > 0) { // --cpus 1.5 → 150 ms of CPU time every 100 ms. l.cpu_period = 100_000; @@ -2247,7 +2266,7 @@ pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> super::engi if let Some(p) = h["PidsLimit"].as_i64().filter(|p| *p > 0) { l.pids_max = p as u32; } - l + Ok(l) } /// Returned in `POST /containers/create`'s `Warnings` when the caller asks for @@ -2374,6 +2393,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { let host_opts = super::hostopts::from_host(host); super::hostopts::guest_lines(&host_opts, network_mode == "host").map_err(Error::BadRequest)?; super::hostopts::check_device_requests(host).map_err(Error::BadRequest)?; + let limits = super::engine::Limits { shm_size: host["ShmSize"].as_u64().unwrap_or(0), ..limits_from(host, super::engine::Limits::default())? }; if let Some(s) = body["StopSignal"].as_str().filter(|s| !s.is_empty()) { parse_signal(s)?; } @@ -2433,7 +2453,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { user: pick("User", &image.config.user), auto_remove: host["AutoRemove"].as_bool().unwrap_or(false), privileged: host["Privileged"].as_bool().unwrap_or(false), - limits: super::engine::Limits { shm_size: host["ShmSize"].as_u64().unwrap_or(0), ..limits_from(host, super::engine::Limits::default()) }, + limits, caps: caps_from(host)?, cap_add: strings(&host["CapAdd"]).unwrap_or_default(), cap_drop: strings(&host["CapDrop"]).unwrap_or_default(), @@ -2891,6 +2911,7 @@ fn inspect(c: &Container, nets: &[super::network::Network], anon_vols: &[String] v["HostConfig"][key] = super::hostopts::system_paths(&c.spec.host_opts, key, c.spec.privileged); } // Set apart: more keys in the macro above pass its recursion limit. + v["HostConfig"]["MemorySwap"] = json!(c.spec.limits.memory_swap()); let mounts = inspect_mounts(&c.spec, |name| anon_vols.iter().any(|a| a == name)); v["Config"]["Volumes"] = mounts["Volumes"].clone(); for key in ["Binds", "Mounts", "Tmpfs"] { @@ -5138,7 +5159,7 @@ mod network_option_tests { for (shares, weight) in [(2, 1), (512, 59), (1024, 100), (4096, 303), (262_144, 10_000), (1, 1), (999_999, 10_000)] { assert_eq!(super::cpu_weight(shares), weight, "{shares}"); } - let l = super::limits_from(&json!({"CpuShares": 1024}), Default::default()); + let l = super::limits_from(&json!({"CpuShares": 1024}), Default::default()).unwrap(); assert_eq!((l.cpu_shares, l.cpu_weight), (1024, 100)); // Rises with the shares, never backwards. let mut last = 0; @@ -5886,6 +5907,101 @@ mod network_option_tests { assert!(!super::valid_hosts_name(bad), "{bad:?}"); } } + + /// `--memory-swap` as Docker Engine takes it (#523): memory plus swap, + /// twice the memory when not given, -1 for unlimited swap. + #[test] + fn memory_swap_is_memory_plus_swap_as_in_docker() { + let create = |h: Value| limits_from(&h, super::super::engine::Limits::default()); + let swap = |l: super::super::engine::Limits| l.wire().swap_max; + const G: u64 = 1 << 30; + + let l = create(json!({"Memory": 4 * G})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (8 * G as i64, 4 * G)); + let l = create(json!({"Memory": 4 * G, "MemorySwap": 6 * G})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (6 * G as i64, 2 * G)); + let l = create(json!({"Memory": 4 * G, "MemorySwap": 4 * G})).unwrap(); + assert_eq!(swap(l), 0, "--memory-swap equal to --memory: no swap"); + let l = create(json!({"Memory": 4 * G, "MemorySwap": -1})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + let l = create(json!({"MemorySwap": -1})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + let l = create(json!({})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (0, kiri_proto::NO_LIMIT), "no memory limit, no swap limit"); + assert_eq!(l.wire(), kiri_proto::Limits::default(), "unlimited container matches wire default"); + + // Overflow near i64::MAX: 2 * Memory saturates at i64::MAX without wrapping or panicking. + let five_eb: u64 = 5 << 60; + let l = create(json!({"Memory": five_eb})).unwrap(); + assert_eq!(l.memory_swap, i64::MAX); + assert_eq!(swap(l), (i64::MAX as u64) - five_eb); + let l = create(json!({"Memory": i64::MAX as u64})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (i64::MAX, 0)); + let l = create(json!({"Memory": u64::MAX})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (i64::MAX, 0)); + + let bad = |h: Value| match create(h) { + Err(Error::BadRequest(m)) => m, + other => panic!("{other:?}"), + }; + assert!(bad(json!({"MemorySwap": G})).starts_with("You should always set the Memory limit")); + assert!(bad(json!({"Memory": 2 * G, "MemorySwap": G})).starts_with("Minimum memoryswap limit")); + + // docker update keeps what it isn't given, and refuses a memory + // limit above the memory plus swap already set. + let base = create(json!({"Memory": 4 * G, "MemorySwap": 6 * G})).unwrap(); + let l = limits_from(&json!({"Memory": 0, "MemorySwap": 0, "NanoCpus": 2_000_000_000u64}), base).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (4 * G, 6 * G as i64, 2 * G), "updating --cpus keeps custom MemorySwap"); + let l = limits_from(&json!({"Memory": 5 * G}), base).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (5 * G, 6 * G as i64, G)); + let l = limits_from(&json!({"Memory": 4 * G, "MemorySwap": 8 * G}), base).unwrap(); + assert_eq!(swap(l), 4 * G); + let l = limits_from(&json!({"MemorySwap": -1}), base).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + match limits_from(&json!({"Memory": 7 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + match limits_from(&json!({"MemorySwap": 2 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Minimum memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + match limits_from(&json!({"Memory": 8 * G, "MemorySwap": 6 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Minimum memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + let no_mem = create(json!({})).unwrap(); + match limits_from(&json!({"MemorySwap": G}), no_mem) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("You should always set the Memory limit"), "{m}"), + other => panic!("{other:?}"), + } + + // Updating --memory or --cpus when base.memory_swap == -1 keeps -1 (unlimited swap). + let unlim = create(json!({"Memory": 4 * G, "MemorySwap": -1})).unwrap(); + let l = limits_from(&json!({"Memory": 512 << 20}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (512 << 20, -1, kiri_proto::NO_LIMIT)); + let l = limits_from(&json!({"Memory": 8 * G}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (8 * G, -1, kiri_proto::NO_LIMIT)); + let l = limits_from(&json!({"NanoCpus": 2_000_000_000u64}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (4 * G, -1, kiri_proto::NO_LIMIT)); + + // Updating Memory above i64::MAX against an i64::MAX MemorySwap is refused. + let huge = create(json!({"Memory": five_eb})).unwrap(); + match limits_from(&json!({"Memory": u64::MAX}), huge) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + + // Saved before `memory_swap`: Docker's default, not no swap, and updates honour it. + let old: super::super::engine::Limits = serde_json::from_value(json!({"memory_max": G, "cpu_quota": 0, "cpu_period": 0, "cpu_weight": 0, "pids_max": 0})).unwrap(); + assert_eq!((old.memory_swap(), swap(old)), (2 * G as i64, G)); + let l = limits_from(&json!({"Memory": 3 * G / 2}), old).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (3 * G / 2, 2 * G as i64, G / 2)); + match limits_from(&json!({"Memory": 3 * G}), old) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + } } #[cfg(test)] diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index a229e6e87..a8414c663 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -534,9 +534,33 @@ pub struct Limits { /// kernel gets `cpu_weight`. 0 when not set, or saved before 0.2.3. #[serde(default)] pub cpu_shares: u64, + /// `--memory-swap`, as Docker's `HostConfig.MemorySwap`: memory plus + /// swap in bytes, -1 for no swap limit, 0 for none given. + #[serde(default)] + pub memory_swap: i64, } impl Limits { + /// `HostConfig.MemorySwap` as Docker reports it: twice the memory limit + /// when only that was given (containers saved before `memory_swap` too). + pub fn memory_swap(&self) -> i64 { + if self.memory_max > 0 && self.memory_swap == 0 { + i64::try_from(self.memory_max).unwrap_or(i64::MAX).saturating_mul(2) + } else { + self.memory_swap + } + } + + /// The cgroup's `memory.swap.max`: what `memory_swap` allows beyond the + /// memory limit. No memory limit, no swap limit, as with Docker. + fn swap_max(&self) -> u64 { + match self.memory_swap() { + _ if self.memory_max == 0 => kiri_proto::NO_LIMIT, + s if s < 0 => kiri_proto::NO_LIMIT, + s => (s as u64).saturating_sub(self.memory_max), + } + } + pub fn wire(&self) -> kiri_proto::Limits { kiri_proto::Limits { memory_max: self.memory_max, @@ -545,6 +569,7 @@ impl Limits { cpu_weight: self.cpu_weight, pids_max: self.pids_max, shm_size: self.shm_size, + swap_max: self.swap_max(), } } } diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index e60ac71d3..0202c71e8 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -147,7 +147,7 @@ fn top(req: &Request, engine: &Engine, key: &str) -> Result { fn update(req: &Request, engine: &Engine, key: &str) -> Result { let b = body(req)?; let base = engine.with(key, |c| c.spec.limits)?; - let limits = super::api::limits_from(&b, base); + let limits = super::api::limits_from(&b, base)?; let restart = b["RestartPolicy"]["Name"].as_str().filter(|n| !n.is_empty()).map(|n| super::engine::RestartPolicy { name: n.to_owned(), max_retries: b["RestartPolicy"]["MaximumRetryCount"].as_u64().unwrap_or(0) as u32, diff --git a/docs/fix-registry.md b/docs/fix-registry.md index c5b1813b7..d8562b9b7 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 +### #545 Linux: a memory limit gets as much swap again, and `--memory-swap` is applied, as on Docker (unreleased) +- Fixes: #523 Linux: containers with `--memory` get `memory.swap.max = 0` and `--memory-swap` is ignored; #690 +- Caused: none known +- Caused by: - +- Check: `limit-memory-swap`, `limit-memory-swap-inspect`, `limit-memory-swap-refused`, `limit-memory-swap-update` + ### #597 Linux host: start containers when the engine runs in a user namespace (unreleased) - Fixes: #597 Linux host: containers fail to start when the engine runs in a user namespace (`mknod dev/null: Operation not permitted`, default `nofile` above `rlim_max`) - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index fa960213e..b55fc35ac 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1635,6 +1635,22 @@ t ulimit-set-inspect '[{"Name":"nproc","Hard":200,"Soft":100}]' bash -c "$D crea t limit-shares-default "100 100" bash -c "echo \$($D run --rm --cpu-shares 1024 alpine cat /sys/fs/cgroup/cpu.weight) \$($D run --rm alpine cat /sys/fs/cgroup/cpu.weight)" t limit-shares-inspect "512" $D inspect -f '{{.HostConfig.CpuShares}}' lim t limit-inspect "134217728 500000000 50" $D inspect -f '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}} {{.HostConfig.PidsLimit}}' lim +# --memory gets as much swap again by default, and --memory-swap is applied and +# validated as on Docker (#523, #690). +t limit-memory-swap-inspect "268435456 201326592 134217728 -1 0" bash -c " + a=\$($D inspect -f '{{.HostConfig.MemorySwap}}' lim) + b=\$($D create --memory 128m --memory-swap 192m alpine true); bv=\$($D inspect -f '{{.HostConfig.MemorySwap}}' \$b); $D rm \$b >/dev/null + c=\$($D create --memory 128m --memory-swap 128m alpine true); cv=\$($D inspect -f '{{.HostConfig.MemorySwap}}' \$c); $D rm \$c >/dev/null + d=\$($D create --memory 128m --memory-swap -1 alpine true); dv=\$($D inspect -f '{{.HostConfig.MemorySwap}}' \$d); $D rm \$d >/dev/null + e=\$($D create alpine true); ev=\$($D inspect -f '{{.HostConfig.MemorySwap}}' \$e); $D rm \$e >/dev/null + echo \"\$a \$bv \$cv \$dv \$ev\" +" +t limit-memory-swap-refused "nomem=ok small=ok over=ok" bash -c " + $D create --memory-swap 64m alpine true 2>&1 | grep -q 'You should always set the Memory limit' && nm=ok || nm=bad + $D create --memory 128m --memory-swap 64m alpine true 2>&1 | grep -q 'Minimum memoryswap limit' && sm=ok || sm=bad + $D update --memory 512m lim 2>&1 | grep -q 'Memory limit should be smaller than already set memoryswap limit' && ov=ok || ov=bad + echo \"nomem=\$nm small=\$sm over=\$ov\" +" t oom-kill "137" bash -c "$D run --rm --memory 32m alpine sh -c 'tail /dev/zero' >/dev/null 2>&1; echo \$?" t stats "128MiB" $D stats --no-stream --format '{{.MemUsage}}' lim t stats-pids "PIDS" $D stats --no-stream lim @@ -1666,6 +1682,21 @@ t update-memory "268435456" bash -c "$D update --memory 256m lim >/dev/null && $ t update-cpus "200000 100000" bash -c "$D update --cpus 2 lim >/dev/null && $D exec lim cat /sys/fs/cgroup/cpu.max" t update-kept "268435456" bash -c "$D restart -t 1 lim >/dev/null && $D exec lim cat /sys/fs/cgroup/memory.max" t update-restart-policy "always" bash -c "$D update --restart always lim >/dev/null && $D inspect -f '{{.HostConfig.RestartPolicy.Name}}' lim" +t limit-memory-swap-update "201326592:335544320:ok 201326592:335544320:ok 201326592:-1:ok 268435456:-1:ok" bash -c " + $D rm -f lim-sw >/dev/null 2>&1 + $D run -d --name lim-sw --memory 128m alpine sleep 60 >/dev/null + sw() { $D exec lim-sw sh -c \"[ ! -e /sys/fs/cgroup/memory.swap.max ] && echo ok || { v=\\\$(cat /sys/fs/cgroup/memory.swap.max); [ \\\"\\\$v\\\" = \\\"\$1\\\" ] && echo ok || echo bad:\\\$v; }\"; } + $D update --memory 192m --memory-swap 320m lim-sw >/dev/null + s1=\"\$($D inspect -f '{{.HostConfig.Memory}}:{{.HostConfig.MemorySwap}}' lim-sw):\$(sw 134217728)\" + $D update --cpus 1 lim-sw >/dev/null + s2=\"\$($D inspect -f '{{.HostConfig.Memory}}:{{.HostConfig.MemorySwap}}' lim-sw):\$(sw 134217728)\" + $D update --memory-swap -1 lim-sw >/dev/null + s3=\"\$($D inspect -f '{{.HostConfig.Memory}}:{{.HostConfig.MemorySwap}}' lim-sw):\$(sw max)\" + $D update --memory 256m lim-sw >/dev/null + s4=\"\$($D inspect -f '{{.HostConfig.Memory}}:{{.HostConfig.MemorySwap}}' lim-sw):\$(sw max)\" + $D rm -f lim-sw >/dev/null + echo \"\$s1 \$s2 \$s3 \$s4\" +" t stop-paused "exited" bash -c "$D pause lim >/dev/null; $D stop -t 2 lim >/dev/null && $D inspect -f '{{.State.Status}}' lim" $D rm -f lim >/dev/null diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 2e7910ec2..0caf6dbd0 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -915,6 +915,9 @@ t inspect-recreate-mounts "binds=ok code=201 kept|rokept|from-host|bro=ro|vro=ro # Exposed ports keep their protocol from the image and --expose, UDP and SCTP # included, in both Config.ExposedPorts and NetworkSettings.Ports (#620). t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"132/sctp":null,"53/tcp":null,"53/udp":null,"5353/udp":null}' "docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; docker create --name lhudp-base alpine true >/dev/null && docker commit -c 'EXPOSE 53/udp 132/sctp' lhudp-base kiri-lh-udp:1 >/dev/null && docker run -d --name lhudp --expose 53 --expose 5353/udp kiri-lh-udp:1 sleep 60 >/dev/null && out=\$(docker inspect -f '{{json .Config.ExposedPorts}} {{json .NetworkSettings.Ports}}' lhudp); docker rm -f lhudp lhudp-base >/dev/null 2>&1; docker rmi kiri-lh-udp:1 >/dev/null 2>&1; echo \"\$out\"" +# --memory gets as much swap again by default, and --memory-swap is applied to +# memory.swap.max on run and update, as on Docker (#523, #690). +t limit-memory-swap "def=268435456:ok custom=201326592:ok zero=134217728:ok unlim=-1:ok none=0:ok upd=335544320:ok cpus=335544320:ok uunlim=-1:ok umem=-1:ok bad=ok:ok:ok" "docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 lhswu >/dev/null 2>&1; sw() { docker exec \"\$1\" sh -c \"[ ! -e /sys/fs/cgroup/memory.swap.max ] && echo ok || { v=\\\$(cat /sys/fs/cgroup/memory.swap.max); [ \\\"\\\$v\\\" = \\\"\$2\\\" ] && echo ok || echo bad:\\\$v; }\"; }; docker run -d --name lhsw0 alpine sleep 60 >/dev/null; docker run -d --name lhsw1 --memory 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw2 --memory 128m --memory-swap 192m alpine sleep 60 >/dev/null; docker run -d --name lhsw3 --memory 128m --memory-swap 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw4 --memory 128m --memory-swap -1 alpine sleep 60 >/dev/null; none=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw0):\$(sw lhsw0 max); def=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); custom=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw2):\$(sw lhsw2 67108864); zero=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw3):\$(sw lhsw3 0); unlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw4):\$(sw lhsw4 max); docker update --memory 512m lhsw1 2>&1 | grep -q 'Memory limit should be smaller than already set memoryswap limit' && b1=ok || b1=bad; docker create --memory-swap 64m alpine true 2>&1 | grep -q 'You should always set the Memory limit' && b2=ok || b2=bad; docker create --memory 128m --memory-swap 64m alpine true 2>&1 | grep -q 'Minimum memoryswap limit' && b3=ok || b3=bad; docker update --memory 192m --memory-swap 320m lhsw1 >/dev/null; upd=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --cpus 1 lhsw1 >/dev/null; cpus=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --memory-swap -1 lhsw1 >/dev/null; uunlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker update --memory 256m lhsw1 >/dev/null; umem=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 >/dev/null 2>&1; echo \"def=\$def custom=\$custom zero=\$zero unlim=\$unlim none=\$none upd=\$upd cpus=\$cpus uunlim=\$uunlim umem=\$umem bad=\$b1:\$b2:\$b3\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device and raising nofile past the diff --git a/tests/regressions.tsv b/tests/regressions.tsv index cd2046853..a36845280 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -254,3 +254,7 @@ disconnect-hands-ipv6-default-on #381 disconnecting the external IPv6 network th inspect-exposed-udp #620 docker inspect dropped non-TCP exposed ports (such as 53/udp or 132/sctp) from Config.ExposedPorts and NetworkSettings.Ports userns-run #597 when the Linux engine runs inside a user namespace (nested Docker, Coder, Sysbox), container start failed on mknod /dev/null (EPERM) and on raising the default nofile rlimit past the engine's hard limit userns-run-privileged #597 when the Linux engine runs inside a user namespace, --privileged containers skipped standard /dev nodes after copy_host_devices failed mknod with EPERM +limit-memory-swap-inspect #523 containers with --memory reported HostConfig.MemorySwap 0 instead of 2x memory and dropped --memory-swap (#690) +limit-memory-swap-refused #523 invalid --memory-swap values on create and update were accepted instead of refused with Docker's error messages (#690) +limit-memory-swap-update #523 docker update dropped --memory-swap or failed to keep an existing custom or unlimited swap limit (#690) +limit-memory-swap #523 every container with --memory was pinned to memory.swap.max = 0 instead of getting Docker's 2x default or --memory-swap (#690) From 41c775597fecf45007a6a0a563612013c2873e80 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 19:23:05 +0100 Subject: [PATCH 024/157] Bench: fail the API benchmark on curl errors instead of timing failed runs (#669) Co-authored-by: Urdemonlord --- bench/api.sh | 24 +++++++++++++++--------- docs/fix-registry.md | 6 ++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/bench/api.sh b/bench/api.sh index bc7a41abf..0be36ec68 100644 --- a/bench/api.sh +++ b/bench/api.sh @@ -2,22 +2,28 @@ # Engine-only latency: one container lifecycle (create, start, wait, delete) # and one exec, straight over the Docker API with curl, no docker CLI. # SOCK=/run/dockerd-bench.sock bench/api.sh docker-engine -set -u +set -euo pipefail label=$1; S=${SOCK:?}; OUT=${OUT:-$(dirname "$0")/results}; RUNS=${RUNS:-30} -c() { curl -s --unix-socket "$S" "$@"; } +mkdir -p "$OUT" +c() { curl -fsS --unix-socket "$S" "$@"; } +id="" +trap '[[ -n "$id" ]] && c -X DELETE "http://x/containers/$id?force=true" >/dev/null || true' EXIT c -X POST -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["true"]}' http://x/containers/create >/dev/null cat > /tmp/api-run.sh </dev/null; c -X POST http://x/containers/\$id/wait >/dev/null; c -X DELETE http://x/containers/\$id >/dev/null +c -X POST http://x/containers/\$id/start >/dev/null && c -X POST http://x/containers/\$id/wait >/dev/null && c -X DELETE http://x/containers/\$id >/dev/null R id=$(c -X POST -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["sleep","600"]}' http://x/containers/create | jq -r .Id); c -X POST "http://x/containers/$id/start" >/dev/null cat > /tmp/api-exec.sh </dev/null R -hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-run.json" 'bash /tmp/api-run.sh' >/dev/null 2>&1 -hyperfine --ignore-failure --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-exec.json" 'bash /tmp/api-exec.sh' >/dev/null 2>&1 -c -X DELETE "http://x/containers/$id?force=true" >/dev/null -printf '%-14s API run %4s ms (min %4s) API exec %4s ms (min %4s)\n' "$label" $(jq -r '.results[0] | "\(.median*1000|round) \(.min*1000|round)"' "$OUT/$label.api-run.json") $(jq -r '.results[0] | "\(.median*1000|round) \(.min*1000|round)"' "$OUT/$label.api-exec.json") +out=$(hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-run.json" 'bash /tmp/api-run.sh' 2>&1) || { printf '%s\n' "$out" >&2; exit 1; } +out=$(hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-exec.json" 'bash /tmp/api-exec.sh' 2>&1) || { printf '%s\n' "$out" >&2; exit 1; } +ms() { jq -r ".results[0] | (.summary.time_wall_clock // .) | .$1 * 1000 | round" "$OUT/$label.$2.json"; } +r_med=$(ms median api-run); r_min=$(ms min api-run); e_med=$(ms median api-exec); e_min=$(ms min api-exec) +printf '%-14s API run %4s ms (min %4s) API exec %4s ms (min %4s)\n' "$label" "$r_med" "$r_min" "$e_med" "$e_min" diff --git a/docs/fix-registry.md b/docs/fix-registry.md index d8562b9b7..f0bfcdea4 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 +### #779 Bench: fail the API benchmark on curl errors instead of timing failed runs (unreleased) +- Fixes: #669 `bench/api.sh` passes `--ignore-failure` to `hyperfine` on `api-exec`, masking curl failures and recording time-to-failure as valid timings +- Caused: none known +- Caused by: - +- Check: none + ### #545 Linux: a memory limit gets as much swap again, and `--memory-swap` is applied, as on Docker (unreleased) - Fixes: #523 Linux: containers with `--memory` get `memory.swap.max = 0` and `--memory-swap` is ignored; #690 - Caused: none known From 3aa0e208c8e50a788049d31d5c6dfcddef819862 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 19:30:39 +0100 Subject: [PATCH 025/157] Stats: report cgroup CPU throttling periods and time in container stats (#537) Co-authored-by: grvwy <147989282+grvwy@users.noreply.github.com> --- crates/kiri-init/src/linux/cgroup.rs | 32 ++++++++++++++++++++- crates/kiri-proto/src/lib.rs | 41 +++++++++++++++++++++++++-- crates/kiri/src/daemon/ops.rs | 42 +++++++++++++++++++++++++++- docs/fix-registry.md | 6 ++++ tests/e2e.sh | 8 ++++++ tests/linux-host.sh | 2 ++ tests/regressions.tsv | 1 + 7 files changed, 128 insertions(+), 4 deletions(-) diff --git a/crates/kiri-init/src/linux/cgroup.rs b/crates/kiri-init/src/linux/cgroup.rs index c51a0984c..c19601aa9 100644 --- a/crates/kiri-init/src/linux/cgroup.rs +++ b/crates/kiri-init/src/linux/cgroup.rs @@ -67,8 +67,20 @@ pub fn freeze(dir: &Path, frozen: bool) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::TimedOut, "the container did not freeze in time")) } +fn keyed_opt(text: &str, key: &str) -> Option { + text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok()) +} + fn keyed(text: &str, key: &str) -> u64 { - text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok()).unwrap_or(0) + keyed_opt(text, key).unwrap_or(0) +} + +/// CPU throttling counters from `cpu.stat`: `(nr_periods, nr_throttled, throttled_usec)`. +/// cgroup v2 reports `throttled_usec` in microseconds; cgroup v1 reports +/// `throttled_time` in nanoseconds. +fn cpu_throttling(cpu_stat: &str) -> (u64, u64, u64) { + let throttled_usec = keyed_opt(cpu_stat, "throttled_usec").unwrap_or_else(|| keyed(cpu_stat, "throttled_time") / 1000); + (keyed(cpu_stat, "nr_periods"), keyed(cpu_stat, "nr_throttled"), throttled_usec) } /// What the cgroup holds and cannot give back, in bytes: anonymous, shared @@ -114,6 +126,7 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result { let read = |f: &str| fs::read_to_string(dir.join(f)).unwrap_or_default(); let cpu = read("cpu.stat"); let mem_stat = read("memory.stat"); + let (cpu_periods, cpu_throttled_periods, cpu_throttled_usec) = cpu_throttling(&cpu); let mut s = ContainerStats { read_ns: sys::boottime_ns(), mem_current: read("memory.current").trim().parse().unwrap_or(0), @@ -122,6 +135,9 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result { cpu_usage_usec: keyed(&cpu, "usage_usec"), cpu_user_usec: keyed(&cpu, "user_usec"), cpu_system_usec: keyed(&cpu, "system_usec"), + cpu_periods, + cpu_throttled_periods, + cpu_throttled_usec, pids: read("pids.current").trim().parse().unwrap_or(0), // SAFETY: sysconf has no preconditions. online_cpus: unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }.max(1) as u32, @@ -349,6 +365,20 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn cpu_throttling_reads_v2_and_v1_formats() { + let v2 = "usage_usec 12345\nuser_usec 10000\nsystem_usec 2345\nnr_periods 12\nnr_throttled 5\nthrottled_usec 43210\n"; + assert_eq!(cpu_throttling(v2), (12, 5, 43_210)); + + let v2_zero = "usage_usec 500\nnr_periods 4\nnr_throttled 0\nthrottled_usec 0\n"; + assert_eq!(cpu_throttling(v2_zero), (4, 0, 0)); + + let v1 = "nr_periods 12\nnr_throttled 5\nthrottled_time 43210000\n"; + assert_eq!(cpu_throttling(v1), (12, 5, 43_210)); + + assert_eq!(cpu_throttling(""), (0, 0, 0)); + } + #[test] fn apply_limits_errors_when_cgroup_dir_is_missing() { let missing = std::env::temp_dir().join(format!("kiri-cg-missing-{}", std::process::id())); diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 316973001..36c6e6522 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -627,6 +627,9 @@ pub struct ContainerStats { pub tx_packets: u64, pub io_read_bytes: u64, pub io_write_bytes: u64, + pub cpu_periods: u64, + pub cpu_throttled_periods: u64, + pub cpu_throttled_usec: u64, } fn put_container_stats(o: &mut Vec, s: &ContainerStats) { @@ -638,10 +641,13 @@ fn put_container_stats(o: &mut Vec, s: &ContainerStats) { for v in [s.rx_bytes, s.rx_packets, s.tx_bytes, s.tx_packets, s.io_read_bytes, s.io_write_bytes] { put_u64(o, v); } + for v in [s.cpu_periods, s.cpu_throttled_periods, s.cpu_throttled_usec] { + put_u64(o, v); + } } fn read_container_stats(r: &mut Reader<'_>) -> Result { - Ok(ContainerStats { + let mut stats = ContainerStats { read_ns: r.u64()?, mem_current: r.u64()?, mem_max: r.u64()?, @@ -658,7 +664,15 @@ fn read_container_stats(r: &mut Reader<'_>) -> Result/dev/null | head -1" +# Container stats carry cgroup CPU throttling counters in Docker units (#537). +t stats-cpu-throttling "ok" bash -c " + $D rm -f lim-thr >/dev/null 2>&1 + id=\$($D run -d --name lim-thr --cpus 0.1 alpine sh -c 'i=0; while [ \$i -lt 200000 ]; do i=\$((i+1)); done; sleep 10') + out=\$(curl -s --unix-socket $(printf %q "$SOCK") \"http://d/v1.47/containers/\$id/stats?stream=false\" | python3 -c 'import json, sys; td = json.load(sys.stdin)[\"cpu_stats\"][\"throttling_data\"]; print(\"ok\" if td[\"periods\"] > 0 and td[\"throttled_periods\"] > 0 and td[\"throttled_time\"] > 0 else td)') + $D rm -f lim-thr >/dev/null 2>&1 + echo \"\$out\" +" t top "nginx: master process" $D top lim t top-ps-titles "PPID" $D top lim # ps_args picks ps's columns, as Docker runs ps with them (#348). diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 0caf6dbd0..ea3b0ae3e 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -918,6 +918,8 @@ t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"1 # --memory gets as much swap again by default, and --memory-swap is applied to # memory.swap.max on run and update, as on Docker (#523, #690). t limit-memory-swap "def=268435456:ok custom=201326592:ok zero=134217728:ok unlim=-1:ok none=0:ok upd=335544320:ok cpus=335544320:ok uunlim=-1:ok umem=-1:ok bad=ok:ok:ok" "docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 lhswu >/dev/null 2>&1; sw() { docker exec \"\$1\" sh -c \"[ ! -e /sys/fs/cgroup/memory.swap.max ] && echo ok || { v=\\\$(cat /sys/fs/cgroup/memory.swap.max); [ \\\"\\\$v\\\" = \\\"\$2\\\" ] && echo ok || echo bad:\\\$v; }\"; }; docker run -d --name lhsw0 alpine sleep 60 >/dev/null; docker run -d --name lhsw1 --memory 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw2 --memory 128m --memory-swap 192m alpine sleep 60 >/dev/null; docker run -d --name lhsw3 --memory 128m --memory-swap 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw4 --memory 128m --memory-swap -1 alpine sleep 60 >/dev/null; none=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw0):\$(sw lhsw0 max); def=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); custom=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw2):\$(sw lhsw2 67108864); zero=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw3):\$(sw lhsw3 0); unlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw4):\$(sw lhsw4 max); docker update --memory 512m lhsw1 2>&1 | grep -q 'Memory limit should be smaller than already set memoryswap limit' && b1=ok || b1=bad; docker create --memory-swap 64m alpine true 2>&1 | grep -q 'You should always set the Memory limit' && b2=ok || b2=bad; docker create --memory 128m --memory-swap 64m alpine true 2>&1 | grep -q 'Minimum memoryswap limit' && b3=ok || b3=bad; docker update --memory 192m --memory-swap 320m lhsw1 >/dev/null; upd=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --cpus 1 lhsw1 >/dev/null; cpus=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --memory-swap -1 lhsw1 >/dev/null; uunlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker update --memory 256m lhsw1 >/dev/null; umem=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 >/dev/null 2>&1; echo \"def=\$def custom=\$custom zero=\$zero unlim=\$unlim none=\$none upd=\$upd cpus=\$cpus uunlim=\$uunlim umem=\$umem bad=\$b1:\$b2:\$b3\"" +# Container stats carry cgroup CPU throttling counters in Docker units (#537). +t stats-cpu-throttling "ok" "docker rm -f lhthr >/dev/null 2>&1; id=\$(docker run -d --name lhthr --cpus 0.1 alpine sh -c 'i=0; while [ \$i -lt 200000 ]; do i=\$((i+1)); done; sleep 10'); out=\$(curl -s --unix-socket /root/.kiri/run/docker.sock \"http://d/v1.47/containers/\$id/stats?stream=false\" | python3 -c 'import json, sys; td = json.load(sys.stdin)[\"cpu_stats\"][\"throttling_data\"]; print(\"ok\" if td[\"periods\"] > 0 and td[\"throttled_periods\"] > 0 and td[\"throttled_time\"] > 0 else td)'); docker rm -f lhthr >/dev/null 2>&1; echo \"\$out\"" $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device and raising nofile past the diff --git a/tests/regressions.tsv b/tests/regressions.tsv index a36845280..5bb6ba96a 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -258,3 +258,4 @@ limit-memory-swap-inspect #523 containers with --memory reported HostConfig.Memo limit-memory-swap-refused #523 invalid --memory-swap values on create and update were accepted instead of refused with Docker's error messages (#690) limit-memory-swap-update #523 docker update dropped --memory-swap or failed to keep an existing custom or unlimited swap limit (#690) limit-memory-swap #523 every container with --memory was pinned to memory.swap.max = 0 instead of getting Docker's 2x default or --memory-swap (#690) +stats-cpu-throttling #537 container stats always reported zero for cpu_stats.throttling_data even when a CPU-limited container was throttled From ba01465c25ece79b397faaaa43e4ab9c14d36898 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 21:04:13 +0100 Subject: [PATCH 026/157] Daemon: log memory-kill figures, relieve balloon first, and attribute requested stops (#474) Co-authored-by: meutex <342316034+meutex@users.noreply.github.com> --- crates/kiri-init/src/linux/agent.rs | 6 +- crates/kiri-proto/src/lib.rs | 48 +++- crates/kiri/src/daemon/engine.rs | 332 +++++++++++++++++++++++++++- crates/kiri/src/daemon/vmlink.rs | 9 +- crates/kiri/src/k8s.rs | 4 + docs/fix-registry.md | 6 + 6 files changed, 381 insertions(+), 24 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index d288407c9..dfb4abcbf 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -8,7 +8,7 @@ use std::io::{self, Read, Write}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::path::Path; -use kiri_proto::{Exited, MAX_OUTPUT_CHUNK, Msg, Stats, Stream}; +use kiri_proto::{Exited, MAX_OUTPUT_CHUNK, MemoryPressure, Msg, Stats, Stream}; use super::container::{self, NetCtx, Paths, Process, Root}; use super::net::{self, Bridges, Dhcp}; @@ -270,8 +270,10 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap= std::time::Duration::from_millis(100) { last_pressure = std::time::Instant::now(); + let (_, mem_available_kib, _) = meminfo_full(); + let (mem_stall, _) = super::cgroup::memory_trouble(); out.clear(); - Msg::MemoryPressure.encode(&mut out); + Msg::MemoryPressure(MemoryPressure { mem_available_kib, mem_stall }).encode(&mut out); conn.write_all(&out)?; } continue; diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 36c6e6522..d1a1b2fb6 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -52,8 +52,10 @@ pub const INPUT_WINDOW: usize = 4 << 20; /// reply: an older agent's "unexpected" error would be taken as the reply /// to the next request. 8 added `DnsRename`, another no-reply message, for /// the same reason. 9 added `Limits::swap_max`: an older agent would read -/// the limits one field short. -pub const PROTOCOL: u16 = 9; +/// the limits one field short. 10 added a payload on `MemoryPressure` +/// (MemAvailable and PSI full avg10): an older agent's bare `MemoryPressure` +/// has neither field, so decode rejects it as truncated. +pub const PROTOCOL: u16 = 10; /// Most names a `DnsRename` may carry: a name, its aliases and a hostname. pub const MAX_DNS_NAMES: usize = 256; @@ -155,8 +157,9 @@ pub enum Msg<'a> { /// as the link says it. Answered by `FsData` or `Error`. FsReadLink { id: &'a str, path: &'a str }, /// Guest → host: memory is tight right now (a PSI trigger fired); grow - /// the VM's memory. No reply. - MemoryPressure, + /// the VM's memory, and carry the readings that go with a memory kill. + /// No reply. + MemoryPressure(MemoryPressure), /// Host → guest: delete a named volume's data. No reply. RemoveVolume { name: &'a str }, /// Host → guest, first frame on a connection to [`COPY_PORT`]: copy @@ -706,6 +709,16 @@ pub struct Exited<'a> { pub oom_killed: bool, } +/// What the guest sends with [`Msg::MemoryPressure`]: the readings behind a +/// memory kill, so the host can log the numbers in the same event. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MemoryPressure { + /// MemAvailable from /proc/meminfo, in KiB. + pub mem_available_kib: u64, + /// PSI "full avg10" in hundredths of a percent (see `Stats::mem_stall`). + pub mem_stall: u64, +} + /// A list of strings borrowed from a frame. Iterate it; it never allocates. #[derive(Clone, Copy, PartialEq, Eq, Default)] pub struct StrList<'a> { @@ -1164,7 +1177,10 @@ impl Msg<'_> { put_str(o, id); put_str(o, path); }), - Msg::MemoryPressure => frame(out, kind::MEMORY_PRESSURE, |_| {}), + Msg::MemoryPressure(p) => frame(out, kind::MEMORY_PRESSURE, |o| { + put_u64(o, p.mem_available_kib); + put_u64(o, p.mem_stall); + }), Msg::RemoveVolume { name } => frame(out, kind::REMOVE_VOLUME, |o| put_str(o, name)), Msg::RemoveBridge { bridge } => frame(out, kind::REMOVE_BRIDGE, |o| put_str(o, bridge)), Msg::DnsRename { id, bridge, ip, ip6, v4, names } => frame(out, kind::DNS_RENAME, |o| { @@ -1475,7 +1491,10 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { } kind::FS_READ => Msg::FsRead { id: r.str()?, path: r.str()?, offset: r.u64()?, len: r.u32()? }, kind::FS_DATA => Msg::FsData(r.bytes()?), - kind::MEMORY_PRESSURE => Msg::MemoryPressure, + kind::MEMORY_PRESSURE => Msg::MemoryPressure(MemoryPressure { + mem_available_kib: r.u64()?, + mem_stall: r.u64()?, + }), kind::REMOVE_VOLUME => Msg::RemoveVolume { name: r.str()? }, kind::REMOVE_BRIDGE => Msg::RemoveBridge { bridge: r.str()? }, kind::DNS_RENAME => { @@ -1825,6 +1844,21 @@ mod tests { assert_eq!(Limits::default().swap_max, NO_LIMIT); } + #[test] + fn memory_pressure_payload_survives_encoding_and_covers_protocol() { + // An agent from before `MemoryPressure`'s payload sends a bare frame + // with neither field; the host rejects it on `Hello`. + const { assert!(PROTOCOL >= 10) }; + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 0, mem_stall: 0 })); + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 524_288, mem_stall: 1234 })); + let mut bare = Vec::new(); + frame(&mut bare, kind::MEMORY_PRESSURE, |_| {}); + assert_eq!(decode(&bare), Err(DecodeError::Truncated)); + let mut half = Vec::new(); + frame(&mut half, kind::MEMORY_PRESSURE, |o| put_u64(o, 4096)); + assert_eq!(decode(&half), Err(DecodeError::Truncated)); + } + #[test] fn fs_messages_survive_encoding() { round(Msg::FsStatRequest { id: "c1", path: "/etc" }); @@ -1832,7 +1866,7 @@ mod tests { round(Msg::FsRead { id: "c1", path: "/etc/os-release", offset: 10, len: 4096 }); round(Msg::FsData(b"NAME=Alpine")); round(Msg::FsReadLink { id: "c1", path: "/usr/bin/X11" }); - round(Msg::MemoryPressure); + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 1, mem_stall: 2 })); round(Msg::RemoveVolume { name: "pgdata" }); round(Msg::RemoveBridge { bridge: "kiri3" }); round(Msg::CopyStat { entry: FsEntry { name: "hosts", mode: 0o100644, size: 9, mtime: 3, mtime_nsec: 4, ino: 5 }, link: "" }); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index a8414c663..bf063c75b 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1287,6 +1287,9 @@ pub struct Engine { /// What the guest last used, in bytes (0 while asleep): the balloon's /// measure, without the pages the balloon itself holds. memory_used: std::sync::atomic::AtomicU64, + /// The guest's last MemAvailable from /proc/meminfo, in KiB (0 while + /// asleep): the figure behind a memory kill's log line. + mem_available_kib: std::sync::atomic::AtomicU64, /// How starved of memory the guest is: PSI "full avg10" in hundredths /// of a percent (0 while asleep), and processes killed for memory since it booted. memory_stall: std::sync::atomic::AtomicU64, @@ -1296,6 +1299,11 @@ pub struct Engine { cpu_permyriad: std::sync::atomic::AtomicU32, /// `docker events`: recent ones for `--since`, and who is listening. events: Mutex, + /// The op under which each container is being stopped (a restartvm, a + /// recreate, `kiri k8s set`), so its exit is attributed to that + /// operation instead of a memory kill. Cleared on exit, destroy, restart + /// or VM loss. + stopping_ops: Mutex>, /// Kubernetes LoadBalancer services published on the Mac's localhost: /// (port, protocol) → its forward. k8s_lb: Mutex>, @@ -1334,6 +1342,26 @@ struct Events { listeners: Vec>, } +/// Diagnostic classification for a container exit (`Engine::classify_exit`). +#[derive(Debug, PartialEq, Eq)] +enum ExitLog { + MemoryKill { + name: String, + exit_code: i32, + mem_available_mib: u64, + psi_full_avg10: u64, + /// `(target_mib, ceiling_mib)` on macOS after balloon relief; `None` on + /// Linux hosts, which have no balloon. + balloon: Option<(u64, u64)>, + }, + OpStop { + kind: String, + name: String, + exit_code: i32, + op: String, + }, +} + impl std::fmt::Debug for Engine { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Engine") @@ -1407,10 +1435,12 @@ impl Engine { cpus: std::sync::atomic::AtomicUsize::new(vm_cpus()), memory_target: Mutex::new(ceiling), memory_used: std::sync::atomic::AtomicU64::new(0), + mem_available_kib: std::sync::atomic::AtomicU64::new(0), memory_stall: std::sync::atomic::AtomicU64::new(0), oom_kills: std::sync::atomic::AtomicU64::new(0), cpu_permyriad: std::sync::atomic::AtomicU32::new(0), events: Mutex::new(Events::default()), + stopping_ops: Mutex::new(HashMap::new()), k8s_lb: Mutex::new(HashMap::new()), k8s_routes: Mutex::new(None), k8s_fwd: Mutex::new(HashMap::new()), @@ -1891,6 +1921,7 @@ impl Engine { let Some(vm) = self.link.lock().unwrap_or_else(|e| e.into_inner()).clone() else { return false }; self.sleeping.store(true, std::sync::atomic::Ordering::SeqCst); self.memory_used.store(0, std::sync::atomic::Ordering::Relaxed); + self.mem_available_kib.store(0, std::sync::atomic::Ordering::Relaxed); self.memory_stall.store(0, std::sync::atomic::Ordering::Relaxed); vm.shutdown(); // Let the guest flush its disk and power off before the VM is dropped. @@ -2372,6 +2403,7 @@ impl Engine { let mut restart_in = None; let mut persist = false; let mut closed_ports = None; + let mut exited_name = None; let actor = st.containers.get(id).map(|c| (c.spec.image.clone(), container_attrs(c))); // Exited before its start made it live: its `start` first. let start_owed = st.containers.get_mut(id).is_some_and(|c| std::mem::take(&mut c.start_owed)); @@ -2387,9 +2419,7 @@ impl Engine { c.oom_killed = oom; // Stopped by the daemon's shutdown, not by the app. c.vm_stopped = SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst); - if oom { - crate::diag::warn!("container killed for memory", name = c.name.clone(), exit_code = code); - } + exited_name = Some(c.name.clone()); c.exits += 1; c.live = false; if let Some(ip) = c.ip.take() { @@ -2436,6 +2466,14 @@ impl Engine { note_removed(&mut st, id, code); } drop(st); + // Relieve the balloon and log the exit outside `self.state` so + // neither `memory_target`, `link` nor `stopping_ops` is ever + // nested under it, and before the exit is reported to waiters. + if let Some(name) = exited_name { + self.log_exit(id, &name, code, oom); + } else { + self.clear_stopping_op(id); + } if let Some((image, attrs)) = actor { if start_owed { self.emit_container_with("start", id, &image, attrs.clone(), &[]); @@ -2488,7 +2526,11 @@ impl Engine { }); } } - Event::Pressure => self.grow_memory(), + Event::Pressure { mem_available_kib, mem_stall } => { + self.mem_available_kib.store(mem_available_kib, std::sync::atomic::Ordering::Relaxed); + self.memory_stall.store(mem_stall, std::sync::atomic::Ordering::Relaxed); + self.grow_memory(); + } Event::Lost => { let end = vm_end(self.sleeping.load(std::sync::atomic::Ordering::SeqCst), SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst)); let crashed = end == VmEnd::Crashed; @@ -2542,6 +2584,7 @@ impl Engine { } drop(st); drop(closed); + self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take(); @@ -2590,6 +2633,7 @@ impl Engine { let ceiling = engine.ceiling(); let used = estimate_used(&stats, ceiling, *target, if cfg!(target_os = "macos") { 0 } else { self_rss() }); engine.memory_used.store(used, std::sync::atomic::Ordering::Relaxed); + engine.mem_available_kib.store(stats.mem_available_kib, std::sync::atomic::Ordering::Relaxed); engine.memory_stall.store(stats.mem_stall, std::sync::atomic::Ordering::Relaxed); engine.oom_kills.store(stats.oom_kills, std::sync::atomic::Ordering::Relaxed); if !cfg!(target_os = "macos") { @@ -2604,16 +2648,105 @@ impl Engine { } fn grow_memory(&self) { + if !cfg!(target_os = "macos") { + return; + } + // Take `link` before `memory_target`, matching `start_balloon`. + let vm = self.awake(); let mut target = self.memory_target.lock().unwrap_or_else(|e| e.into_inner()); let next = target.saturating_add(MEMORY_GROW).min(self.ceiling()); if next != *target { *target = next; - if let Some(vm) = self.awake() { + if let Some(vm) = vm { vm.set_memory_target(next); } } } + /// Before a container is reported stopped for memory, give the guest + /// every byte it can have: deflate the balloon so the target equals the + /// ceiling, and log the relief (old and new target). A memory stop is + /// only reported once the log shows target == ceiling. The Mac is the + /// only place with a balloon to deflate; a Linux host never claims one. + fn relieve_memory(&self) { + if !cfg!(target_os = "macos") { + return; + } + let ceiling = self.ceiling(); + let vm = self.awake(); + let old = { + let mut target = self.memory_target.lock().unwrap_or_else(|e| e.into_inner()); + let old = *target; + if old == ceiling { + return; + } + *target = ceiling; + if let Some(vm) = vm { + vm.set_memory_target(ceiling); + } + old + }; + crate::diag::info!("balloon relieved for a memory kill", target_mib_old = old >> 20, target_mib = ceiling >> 20); + } + + /// Classifies a container exit for diagnostic logging, consuming any + /// tracked stopping op and relieving the balloon first on a macOS memory + /// kill. Must not be called while holding `self.state`. + fn classify_exit(&self, id: &str, name: &str, code: i32, oom: bool) -> Option { + let stopping_op = self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + if oom { + // Deflate first: a memory stop is only reported once the target + // equals the ceiling, so the guest had every byte it could have. + self.relieve_memory(); + let mem_available_mib = self.mem_available_kib.load(std::sync::atomic::Ordering::Relaxed) >> 10; + let psi_full_avg10 = self.memory_stall.load(std::sync::atomic::Ordering::Relaxed); + let balloon = cfg!(target_os = "macos").then(|| { + let ceiling_mib = self.ceiling() >> 20; + (ceiling_mib, ceiling_mib) + }); + Some(ExitLog::MemoryKill { name: name.to_owned(), exit_code: code, mem_available_mib, psi_full_avg10, balloon }) + } else if let Some(op) = stopping_op { + // A stop Kiri issued under an operation (a restartvm, a recreate, + // `kiri k8s set`): logged as that operation, not as a memory kill. + let kind = op.split('-').next().filter(|k| !k.is_empty()).unwrap_or("op").to_owned(); + Some(ExitLog::OpStop { kind, name: name.to_owned(), exit_code: code, op }) + } else { + None + } + } + + fn log_exit(&self, id: &str, name: &str, code: i32, oom: bool) { + match self.classify_exit(id, name, code, oom) { + Some(ExitLog::MemoryKill { name, exit_code, mem_available_mib, psi_full_avg10, balloon: Some((target_mib, ceiling_mib)) }) => { + crate::diag::warn!( + "container killed for memory", + name = name, + exit_code = exit_code, + mem_available_mib = mem_available_mib, + target_mib = target_mib, + ceiling_mib = ceiling_mib, + balloon_mib = 0, + psi_full_avg10 = psi_full_avg10, + killed_by = "kernel", + ); + } + Some(ExitLog::MemoryKill { name, exit_code, mem_available_mib, psi_full_avg10, balloon: None }) => { + crate::diag::warn!( + "container killed for memory", + name = name, + exit_code = exit_code, + mem_available_mib = mem_available_mib, + psi_full_avg10 = psi_full_avg10, + killed_by = "kernel", + ); + } + Some(ExitLog::OpStop { kind, name, exit_code, op }) => { + crate::diag::info!(format!("container stopped by {kind}"), name = name, exit_code = exit_code, killed_by = "kiri", op = op); + } + None => {} + } + } + /// (ceiling, current target) in bytes. On a Linux host there is no VM /// of Kiri's to bound: both are the machine's memory (in WSL, the memory /// .wslconfig gives it), so the window shows use against what is there. @@ -3003,6 +3136,7 @@ impl Engine { let halted = self.halting(); (out.0, out.1, out.2, out.3, out.4, (out.5.0, out.5.1, earlier, halted)) }; + self.clear_stopping_op(&id); let (gate, exits, earlier, halted_at_claim) = gate; // A bind source that is a link is followed again at every start, as // Docker does: re-pointing it between runs (a `current` release @@ -4411,10 +4545,14 @@ impl Engine { // "already stopped" (304). return Ok(cancelled || ended_start); } + self.note_stopping_op(&[id.as_str()]); self.emit_container("kill", &id, &[("signal", (libc::SIGTERM).to_string())]); let sig = self.lock().containers.get(&id).and_then(|c| c.spec.stop_signal).unwrap_or(libc::SIGTERM as u32); - if let Some(vm) = self.awake() { - vm.kill(&id, sig)?; + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, sig) + { + self.clear_stopping_op(&id); + return Err(e.into()); } let deadline = std::time::Instant::now() + timeout; let mut st = self.lock(); @@ -4545,9 +4683,13 @@ impl Engine { *killing = killing.wrapping_add(1); self.mark_stopped(&id); } + self.note_stopping_op(&[id.as_str()]); self.emit_container("kill", &id, &[("signal", signal.to_string())]); - if let Some(vm) = self.awake() { - vm.kill(&id, signal)?; + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, signal) + { + self.clear_stopping_op(&id); + return Err(e.into()); } // Like Docker: a SIGKILL returns only once the exit is recorded, so // an immediate inspect, start or rm sees the container stopped. @@ -4580,8 +4722,12 @@ impl Engine { ))); } self.mark_stopped(&id); - if let Some(vm) = self.awake() { - vm.kill(&id, libc::SIGKILL as u32)?; + self.note_stopping_op(&[id.as_str()]); + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, libc::SIGKILL as u32) + { + self.clear_stopping_op(&id); + return Err(e.into()); } let mut st = self.lock(); while st.containers.get(&id).is_some_and(|c| c.status == Status::Running) { @@ -4600,6 +4746,7 @@ impl Engine { } st.execs.retain(|_, e| e.container_id != id); drop(st); + self.clear_stopping_op(&id); self.changed.notify_all(); let anon = self.unshared(removed.as_ref().map(|c| c.spec.anon_volumes.clone()).unwrap_or_default()); if let Some(c) = &removed { @@ -4847,6 +4994,31 @@ impl Engine { self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running) } + /// Remembers the op under which these containers are being stopped, so + /// their exits are attributed to that operation (a restartvm, a recreate, + /// `kiri k8s set`) rather than a memory kill. Clears any earlier op when + /// stopped outside an op, so a stale entry cannot misattribute a later + /// exit. + fn note_stopping_op(&self, ids: &[&str]) { + let mut ops = self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()); + match crate::diag::op() { + Some(op) => { + for id in ids { + ops.insert((*id).to_owned(), op.clone()); + } + } + None => { + for id in ids { + ops.remove(*id); + } + } + } + } + + fn clear_stopping_op(&self, id: &str) { + self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + } + /// Records a stop asked for by the user. True when that cancelled a /// restart its policy had pending. fn mark_stopped(&self, id: &str) -> bool { @@ -5636,6 +5808,8 @@ impl Engine { fn stop_together(&self, vm: &VmLink, ids: &[String], how: Stopping) -> Vec { let engine = how == Stopping::Engine; let t0 = std::time::Instant::now(); + let id_refs: Vec<&str> = ids.iter().map(String::as_str).collect(); + self.note_stopping_op(&id_refs); // (id, when to SIGKILL it, when it was SIGKILLed) let mut pending: Vec<(String, std::time::Instant, Option)> = Vec::new(); for id in ids { @@ -7920,3 +8094,139 @@ mod cpu_tests { assert_eq!(super::vm_cpus(), allowed()); } } + +#[cfg(test)] +mod exit_log_tests { + use super::*; + + fn engine_with_container(name: &str) -> (Arc, String, PathBuf) { + let dir = std::env::temp_dir().join(format!("kiri-exit-log-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = boot_without_vm(&dir); + let image = Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "test:local", "image_id": "sha256:test", "entrypoint": [], "cmd": ["sleep", "60"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap(); + let id = engine.create(Some(name.into()), spec, &image).unwrap(); + engine.lock().containers.get_mut(&id).unwrap().status = Status::Running; + (engine, id, dir) + } + + #[test] + fn kernel_oom_logs_memory_readings_relieves_balloon_and_clears_stopping_op() { + let (engine, id, dir) = engine_with_container("oom"); + let ceiling = engine.ceiling(); + let shrunk = ceiling / 2; + *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = shrunk; + // Pressure carries MemAvailable (KiB) and PSI full avg10. + engine.on_event(Event::Pressure { mem_available_kib: 64 * 1024, mem_stall: 842 }); + assert_eq!(engine.mem_available_kib.load(std::sync::atomic::Ordering::Relaxed), 64 * 1024); + assert_eq!(engine.memory_stall.load(std::sync::atomic::Ordering::Relaxed), 842); + // Set target below ceiling again so we directly verify `relieve_memory` on OOM. + *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = shrunk; + // Even if a stopping op was recorded earlier, kernel OOM wins and still + // consumes the stale op entry. + { + let _op = crate::diag::enter_op("restartvm-1234".into()); + engine.note_stopping_op(&[id.as_str()]); + } + let expected_balloon = cfg!(target_os = "macos").then_some((ceiling >> 20, ceiling >> 20)); + assert_eq!( + engine.classify_exit(&id, "oom", 137, true), + Some(ExitLog::MemoryKill { + name: "oom".into(), + exit_code: 137, + mem_available_mib: 64, + psi_full_avg10: 842, + balloon: expected_balloon, + }) + ); + let after_target = *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()); + if cfg!(target_os = "macos") { + assert_eq!(after_target, ceiling, "macOS must deflate balloon to ceiling before reporting a memory kill"); + } else { + assert_eq!(after_target, shrunk, "non-macOS hosts have no balloon to touch"); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "OOM exit cleared stopping_ops"); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn op_stop_attributes_to_op_while_ordinary_sigkill_is_not_misattributed() { + let (engine, id, dir) = engine_with_container("ops"); + // Kiri-initiated stops under `restartvm-...` and `k8s-...` attribute to that op. + for (op, expected_kind) in [("restartvm-a1b2", "restartvm"), ("k8s-c3d4", "k8s"), ("k8sset-e5f6", "k8sset")] { + { + let _guard = crate::diag::enter_op(op.into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert_eq!( + engine.classify_exit(&id, "ops", 137, false), + Some(ExitLog::OpStop { kind: expected_kind.into(), name: "ops".into(), exit_code: 137, op: op.into() }) + ); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + } + // Ordinary SIGKILL (exit 137, oom_killed = false, no op): neither OOM nor op stop. + assert_eq!(engine.classify_exit(&id, "ops", 137, false), None); + + // A stale op from an earlier stop is cleared when a later stop arrives with no op. + { + let _guard = crate::diag::enter_op("restartvm-9999".into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id)); + engine.note_stopping_op(&[id.as_str()]); + assert_eq!(engine.classify_exit(&id, "ops", 137, false), None); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn stopping_ops_are_cleaned_up_on_exit_destroy_and_vm_loss() { + // 1. Real kill under an op + Event::Exited cleans up stopping_ops. + let (engine, id, dir) = engine_with_container("cleanup-exit"); + { + let _op = crate::diag::enter_op("k8sset-1111".into()); + engine.kill(&id, libc::SIGTERM as u32).unwrap(); + } + assert_eq!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).get(&id).map(String::as_str), Some("k8sset-1111")); + engine.on_event(Event::Exited { id: &id, code: 143, oom: false }); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + + // 2. Destroying a stopped container with a stale op cleans it up. + { + let _op = crate::diag::enter_op("restartvm-2222".into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id)); + engine.remove(&id, false, false).unwrap(); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + + // 3. VM loss clears every tracked op. + { + let _op = crate::diag::enter_op("restartvm-3333".into()); + engine.note_stopping_op(&["orphan-a", "orphan-b"]); + } + assert_eq!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).len(), 2); + engine.on_event(Event::Lost); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index 605b83226..aed1b48c1 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -63,8 +63,9 @@ pub enum Event<'a> { Output { id: &'a str, stream: Stream, data: &'a [u8] }, /// `oom` when the kernel killed a process in it for memory. Exited { id: &'a str, code: i32, oom: bool }, - /// The guest is short of memory right now. - Pressure, + /// The guest is short of memory right now, and what it can see: the + /// readings that go with a memory kill. + Pressure { mem_available_kib: u64, mem_stall: u64 }, /// The connection is gone: the VM stopped. Lost, } @@ -275,8 +276,8 @@ impl VmLink { wins.add(id, bytes as usize); continue; } - Ok(Msg::MemoryPressure) => { - on_event(Event::Pressure); + Ok(Msg::MemoryPressure(p)) => { + on_event(Event::Pressure { mem_available_kib: p.mem_available_kib, mem_stall: p.mem_stall }); continue; } Ok(Msg::LayerStatus(have)) => Reply::LayerStatus(have), diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 6c7684ad1..35a83fbf1 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -194,6 +194,10 @@ fn ok(r: io::Result) -> io::Result { pub fn run(args: &[String]) -> io::Result<()> { let what = args.first().map(String::as_str).unwrap_or(""); let logged = matches!(what, "start" | "stop" | "delete" | "set"); + // A recreate from the command line (`kiri k8s set`) is attributed to this + // op, so the node's stop is logged as `k8s set`, not as a memory kill. A + // child the window started already has its own op (KIRI_OP). + let _op = (logged && crate::diag::op().is_none()).then(|| crate::diag::enter_op(crate::diag::new_op(&format!("k8s{what}")))); if logged { crate::diag::info!(format!("Kubernetes {what}")); } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index cdff8724f..d298dda4b 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 +### #484 Daemon: log memory-kill figures, relieve the balloon first, and attribute op stops (unreleased) +- Fixes: #474 Daemon: log memory-kill figures and attribute Kiri-initiated stops to their operation +- Caused: none known +- Caused by: - +- Check: none + ### #537 Engine: report cgroup CPU throttling in container stats (unreleased) - Fixes: no issue - Caused: none known From 42e3a4f88cc189ba32e168484963eb7478ea73f4 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 21:22:38 +0100 Subject: [PATCH 027/157] DNS: answer Go clients' SRV lookups locally and reply SERVFAIL on timeouts (#715) Co-authored-by: Chukwuebuka (Gaus Octavio) <56232734+Chukwuebuka-2003@users.noreply.github.com> --- crates/kiri-init/src/linux/dns.rs | 269 +++++++++++++++++++++++++----- docs/fix-registry.md | 6 + tests/e2e.sh | 4 + tests/regressions.tsv | 1 + 4 files changed, 239 insertions(+), 41 deletions(-) diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index 3ca8b5b0b..fa76c9bc7 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -444,14 +444,26 @@ impl Dns { // where another project's service has it too (#294). // The host's names are the host's whatever a container is called: // a name registered for one of them is never answered. - let is_host = HOST_NAMES.contains(&name.as_str()); + let known = |n: &str| { + HOST_NAMES.contains(&n) + || self.servers[server].bridges.iter().any(|b| self.names.get(b).is_some_and(|t| t.contains_key(n)) || self.names6.get(b).is_some_and(|t| t.contains_key(n))) + }; + // gRPC's SRV lookup of `_grpclb._tcp.` names a container on + // this network (or the host). Answer NODATA for the service here: + // there are no SRV records, and forwarding the query would leave + // Go's resolver waiting for an upstream we can't rely on (#715). + // A registered alias starting with `_` (such as `_app.web` alongside + // `web`) is answered with its own records, not taken for a selector. + let service = if known(&name) { None } else { service_base(&name, known) }; + let lookup = service.unwrap_or(&name); + let is_host = HOST_NAMES.contains(&lookup); let bridge = self.servers[server] .bridges .iter() - .filter(|b| !is_host && (self.names.get(*b).is_some_and(|t| t.contains_key(&name)) || self.names6.get(*b).is_some_and(|t| t.contains_key(&name)))) + .filter(|b| !is_host && (self.names.get(*b).is_some_and(|t| t.contains_key(lookup)) || self.names6.get(*b).is_some_and(|t| t.contains_key(lookup)))) .min_by_key(|b| self.networks.get(*b).map_or(b.as_str(), String::as_str)); - let addrs = bridge.and_then(|b| self.names.get(b)).and_then(|t| t.get(&name)); - let addrs6 = bridge.and_then(|b| self.names6.get(b)).and_then(|t| t.get(&name)); + let addrs = bridge.and_then(|b| self.names.get(b)).and_then(|t| t.get(lookup)); + let addrs6 = bridge.and_then(|b| self.names6.get(b)).and_then(|t| t.get(lookup)); // The host's names answer A with the host's address, and AAAA with // no records: the host relay is IPv4 only. let addrs = match addrs { @@ -463,8 +475,11 @@ impl Dns { if addrs.is_none() && addrs6.is_none() { return None; } - let a: &[[u8; 4]] = if qtype == 1 || qtype == 255 { addrs.map_or(&[], Vec::as_slice) } else { &[] }; - let aaaa: &[([u8; 4], [u8; 16])] = if qtype == 28 || qtype == 255 { addrs6.map_or(&[], Vec::as_slice) } else { &[] }; + // A service name has no records of its own: the container it + // belongs to has the addresses, and the caller looks those up by + // the container's name. + let a: &[[u8; 4]] = if service.is_none() && (qtype == 1 || qtype == 255) { addrs.map_or(&[], Vec::as_slice) } else { &[] }; + let aaaa: &[([u8; 4], [u8; 16])] = if service.is_none() && (qtype == 28 || qtype == 255) { addrs6.map_or(&[], Vec::as_slice) } else { &[] }; let mut r = Vec::with_capacity(end + 16 * a.len() + 28 * aaaa.len()); r.extend_from_slice(&q[0..2]); // id r.extend_from_slice(&[0x81, 0x80]); // response, recursion desired + available @@ -489,14 +504,15 @@ impl Dns { fn forward(&mut self, server: usize, q: &[u8], client: libc::sockaddr_in, upstream: &[[u8; 4]]) { let now = Instant::now(); - // A query with the container's own servers past its deadline is - // answered SERVFAIL here too, before the slots are counted. + // A query past its deadline is answered SERVFAIL here too, before + // the slots are counted: `on_readable` runs before `on_timer`. for at in (0..self.pending.len()).rev() { - if self.pending[at].own.is_some() && now.duration_since(self.pending[at].started) >= OWN_DEADLINE { + let p = &self.pending[at]; + let (from, wait) = if p.own.is_some() { (p.started, OWN_DEADLINE) } else { (p.sent, FORWARD_TIMEOUT) }; + if now.duration_since(from) >= wait { self.fail(at); } } - self.pending.retain(|p| p.own.is_some() || now.duration_since(p.sent) < FORWARD_TIMEOUT); let key = self.servers[server].container.map_or(client.sin_addr.s_addr.to_ne_bytes(), |(_, owner)| owner); let own = self.clients.get(&key).map(|v| (v.len(), v.first().copied())); let Some((_, _, end)) = parse_question(q) else { @@ -533,18 +549,17 @@ impl Dns { // No resolver yet, or it can't be reached: the host, if allowed. let (sock, relayed) = match sock { Some(s) => (s, false), - None if may_relay => match self.relay_stream(&msg) { + None => match may_relay.then(|| self.relay_stream(&msg)).flatten() { Some(s) => (s, true), - None => return, - }, - // None of its own can be sent to: SERVFAIL, not silence. - None if own.is_some() => { - if let Some(s) = self.servers.get(server) { - send_to(s.sock.as_raw_fd(), &servfail(id_of(q), rd(q), &q[12..end]), &client); + // No upstream that can be sent to and no host relay (none on + // a Linux host, not used for `--dns`, or backing off): + // answer at once rather than leave Go's resolver to time + // out waiting for a reply that will never come (#715). + None => { + send_to(self.servers[server].sock.as_raw_fd(), &servfail(id, rd(q), &q[12..end]), &client); + return; } - return; - } - None => return, + }, }; let p = Pending { sock, @@ -606,15 +621,10 @@ impl Dns { /// The server a query is with can't be reached or refused: the next of /// the container's own, else the host if the query may go through it, - /// else (its own servers all failed) SERVFAIL to the client. + /// else SERVFAIL to the client. fn hand_over(&mut self, at: usize) { - if self.ask_next_own(at) { - return; - } - if self.pending[at].own.is_some() { + if !self.ask_next_own(at) && !self.relay(at) { self.fail(at); - } else { - self.relay(at); } } @@ -628,9 +638,9 @@ impl Dns { } /// Sends pending query `at` again, through the host, once. - fn relay(&mut self, at: usize) { + fn relay(&mut self, at: usize) -> bool { if !self.pending[at].may_relay { - return; + return false; } self.pending[at].may_relay = false; let query = std::mem::take(&mut self.pending[at].query); @@ -641,6 +651,9 @@ impl Dns { p.sock = stream; p.relayed = Some(Vec::new()); p.sent = Instant::now(); + true + } else { + false } } @@ -675,13 +688,14 @@ impl Dns { if msg.len() >= 12 && u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(&msg, p) { self.answered(at, &mut msg); } else { - self.pending.swap_remove(at); + // A reply we can't use is still better answered than + // dropped: the client would only wait for its timeout. + self.fail(at); } } - // Gone before a whole reply: the client asks again. - None if eof => { - self.pending.swap_remove(at); - } + // Gone before a whole reply: answer SERVFAIL now, as with any + // other upstream that didn't answer (#715). + None if eof => self.fail(at), None => self.pending[at].relayed = Some(got), } } @@ -728,7 +742,9 @@ impl Dns { } else if p.may_relay && now.duration_since(p.sent) >= FALLBACK_AFTER { self.relay(at); } else if now.duration_since(p.sent) >= FORWARD_TIMEOUT { - self.pending.swap_remove(at); + // An upstream that never answered must not leave the + // client to hit its own timeout with no reply at all. + self.fail(at); } } } @@ -739,16 +755,17 @@ impl Dns { let left = |from: Instant, wait: Duration| wait.saturating_sub(now.duration_since(from)); self.pending .iter() - .filter_map(|p| { + .map(|p| { let due = if p.own.is_some() { left(p.sent, OWN_WAIT).min(left(p.started, OWN_DEADLINE)) } else if p.may_relay { - left(p.sent, FALLBACK_AFTER) + left(p.sent, FALLBACK_AFTER).min(left(p.sent, FORWARD_TIMEOUT)) } else { - // Swept by the next lookup (or `on_timer`), no wake-up for it. - return None; + // Even with no relay left, the query must be answered + // when its timeout expires, not only on the next lookup. + left(p.sent, FORWARD_TIMEOUT) }; - Some(wait_ms(due)) + wait_ms(due) }) .min() .unwrap_or(-1) @@ -906,6 +923,25 @@ fn parse_question(q: &[u8]) -> Option<(String, u16, usize)> { Some((name, qtype, i + 4)) } +/// The container (or host) name a service query is about, when every label +/// before it is a non-empty underscore selector: gRPC looks up +/// `_grpclb._tcp.` as an SRV record before asking for the name's A +/// records. Such a name belongs to this network, so it is answered here +/// (NODATA) rather than forwarded to an upstream that may never answer (#715). +fn service_base(name: &str, known: impl Fn(&str) -> bool) -> Option<&str> { + let mut rest = name; + while let Some((label, tail)) = rest.split_once('.') { + if label.len() <= 1 || !label.starts_with('_') { + return None; + } + if known(tail) { + return Some(tail); + } + rest = tail; + } + None +} + #[cfg(test)] mod tests { use super::{Dns, Pending, Server, response_matches, udp_socket}; @@ -944,6 +980,147 @@ mod tests { assert!(dns.servers.is_empty()); } + /// #715: gRPC looks up `_grpclb._tcp.` before the name's A + /// records. The service belongs to this network, so answer NODATA + /// instead of forwarding a query only an upstream can time out on. + #[test] + fn service_names_of_known_containers_are_answered_nodata() { + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + dns.register("kiri1", ["temporal", "api.myproj"].iter(), [10, 5, 0, 3]); + let v6 = [0xfd, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4]; + dns.register("kiri1", ["_app.temporal"].iter(), [10, 5, 0, 4]); + dns.register6("kiri1", ["_app.temporal"].iter(), [10, 5, 0, 4], v6); + for name in ["_grpclb._tcp.temporal", "_http._tcp.api.myproj", "_grpclb._tcp._app.temporal", "_grpclb._tcp.host.docker.internal"] { + for qtype in [33, 1, 28] { + let q = query(name, qtype); + let r = dns.answer(0, &q).unwrap_or_else(|| panic!("{name} (qtype {qtype}) is answered here, not forwarded")); + assert_eq!((r[3] & 0x0f, answers(&r, q.len()).len()), (0, 0), "{name} (qtype {qtype}): NOERROR with no records"); + assert_eq!(&r[12..q.len()], &q[12..], "the question is echoed back"); + } + } + // A registered alias starting with `_` answers its own A/AAAA records, not NODATA. + let q = query("_app.temporal", 1); + assert_eq!(answers(&dns.answer(0, &q).unwrap(), q.len()), [(1, vec![10, 5, 0, 4])]); + let q6 = query("_app.temporal", 28); + assert_eq!(answers(&dns.answer(0, &q6).unwrap(), q6.len()), [(28, v6.to_vec())]); + // A service under a name we don't know, or with a non-selector label, is forwarded. + for unknown in ["_grpclb._tcp.other", "foo._tcp.temporal", "_.temporal", "_grpclb._.temporal"] { + assert!(dns.answer(0, &query(unknown, 33)).is_none(), "{unknown} must not match"); + } + } + + /// #715: a forwarded query whose upstream never answers must get a + /// SERVFAIL rather than being dropped, leaving Go's resolver to hit + /// its own timeout with no reply at all from 127.0.0.11. + #[test] + fn a_forwarded_query_that_times_out_gets_servfail() { + use std::os::fd::AsRawFd; + use std::time::{Duration, Instant}; + let bind = |ip: [u8; 4]| { + let s = udp_socket().unwrap(); + let a = super::sockaddr(ip, 0); + assert_eq!(unsafe { libc::bind(s.as_raw_fd(), (&a as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) }, 0, "bind"); + s + }; + let addr = |fd: i32| { + let mut a: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as u32; + unsafe { libc::getsockname(fd, (&mut a as *mut libc::sockaddr_in).cast(), &mut len) }; + a + }; + let server = bind([127, 0, 0, 3]); + let client = bind([127, 0, 0, 1]); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: server, container: None }); + let q = query("example.com", 1); + dns.forward(0, &q, addr(client.as_raw_fd()), &[[127, 0, 0, 65]]); + let p = dns.pending.last_mut().expect("forwarded"); + p.sent = Instant::now() - Duration::from_secs(10); + p.may_relay = false; // no host relay left to wait for + dns.on_timer(); + assert!(dns.pending.is_empty(), "the query is done"); + let mut buf = [0u8; 512]; + let n = { + let mut got = None; + for _ in 0..100 { + let n = unsafe { libc::recv(client.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), 0) }; + if n > 12 { + got = Some(n); + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + got.expect("the client got a reply") + }; + assert_eq!(&buf[2..4], &[0x81, 0x82], "recursion available, SERVFAIL"); + assert_eq!(&buf[12..n as usize], &q[12..], "the question is echoed back"); + } + + /// `on_readable` runs before `on_timer`: a retry arriving at or after + /// `FORWARD_TIMEOUT` must answer the expired query SERVFAIL rather than + /// sweeping it silently. + #[test] + fn an_expired_query_is_answered_servfail_when_the_next_arrives() { + let ip = [127, 0, 0, 66]; + let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); + let (client, from) = client(); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let mut first = query("example.com", 1); + first[0..2].copy_from_slice(&0x1111u16.to_be_bytes()); + dns.forward(0, &first, from, &[ip]); + dns.pending[0].sent = Instant::now() - super::FORWARD_TIMEOUT; + let mut retry = query("example.com", 1); + retry[0..2].copy_from_slice(&0x2222u16.to_be_bytes()); + dns.forward(0, &retry, from, &[ip]); + assert_eq!(dns.pending.len(), 1, "only the retry stays in flight"); + assert_eq!(dns.pending[0].id, 0x2222); + assert_eq!(told(&client, 1000), Some((0x1111, 2)), "the expired query got SERVFAIL"); + } + + /// On a Linux host (`relay == false`, `own.is_none()`), a query with no + /// upstream or an upstream that cannot be sent to is answered SERVFAIL + /// at once rather than dropped silently. + #[test] + fn a_query_with_no_reachable_upstream_is_answered_servfail_at_once() { + let (client, from) = client(); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + for (id, upstream) in [(0x3333u16, &[][..]), (0x4444, &[[255, 255, 255, 255]][..])] { + let mut q = query("example.com", 1); + q[0..2].copy_from_slice(&id.to_be_bytes()); + dns.forward(0, &q, from, upstream); + assert!(dns.pending.is_empty()); + assert_eq!(told(&client, 1000), Some((id, 2)), "id {id:#x} got SERVFAIL at once"); + } + } + + /// When the UDP upstream refuses the packet (`ECONNREFUSED`) and no host + /// relay can take it (either `relay == false` on a Linux host or the + /// host relay is unavailable), the query is answered SERVFAIL at once + /// rather than waiting `FORWARD_TIMEOUT` on a dead socket. + #[test] + fn a_refused_upstream_with_no_host_relay_answers_servfail_at_once() { + use std::os::fd::AsRawFd; + let (client, from) = client(); + let refused_ip = [127, 0, 0, 67]; + for (id, relay) in [(0x5555u16, false), (0x6666, true)] { + let mut dns = Dns { relay, ..Default::default() }; + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let mut q = query("example.com", 1); + q[0..2].copy_from_slice(&id.to_be_bytes()); + dns.forward(0, &q, from, &[refused_ip]); + assert_eq!(dns.pending.len(), 1); + let fd = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd); + dns.on_readable(fd, &[refused_ip]); + assert!(dns.pending.is_empty(), "relay={relay}: no dead entry left waiting"); + assert_eq!(told(&client, 1000), Some((id, 2)), "relay={relay}: SERVFAIL at once"); + assert_eq!(dns.relay_down_until.is_some(), relay); + } + } + /// #294: a container on its project's network and on a shared one, both /// with a `db`, joining the shared one first. Docker searches the /// networks by name, whatever the join order. @@ -1722,7 +1899,10 @@ mod tests { let mut dns = Dns::default(); assert_eq!(dns.timeout_ms(), -1, "nothing pending"); dns.pending.push(pending()); - assert_eq!(dns.timeout_ms(), -1, "nothing to hand over"); + // With no host to try, the query still needs a wake-up at its + // timeout so it gets a SERVFAIL instead of being left unanswered. + let t = dns.timeout_ms(); + assert!((4000..=5000).contains(&t), "only the forward wait: {t}"); let mut p = pending(); p.may_relay = true; dns.pending.push(p); @@ -1733,6 +1913,13 @@ mod tests { assert_eq!(dns.timeout_ms(), 0); dns.on_timer(); assert!(!dns.pending[1].may_relay); + let t = dns.timeout_ms(); + assert!((3000..=5000).contains(&t), "the relayed query still has its wait: {t}"); + for p in &mut dns.pending { + p.sent = Instant::now() - super::FORWARD_TIMEOUT; + } + dns.on_timer(); + assert!(dns.pending.is_empty(), "both queries answered at their timeout"); assert_eq!(dns.timeout_ms(), -1); } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index d298dda4b..9e450366b 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 +### #715 DNS: Go clients' SRV lookups are answered here, and forwarded lookups are never silently dropped (unreleased) +- Fixes: #715 Go gRPC clients (RoadRunner's Temporal plugin) fail with "context deadline exceeded" resolving container names via 127.0.0.11 while getent/nslookup/dig work +- Caused: none known +- Caused by: - +- Check: `dns-user-net-srv-nodata` + ### #484 Daemon: log memory-kill figures, relieve the balloon first, and attribute op stops (unreleased) - Fixes: #474 Daemon: log memory-kill figures and attribute Kiri-initiated stops to their operation - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index eea6bfd87..daead30b0 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -808,6 +808,10 @@ t dns-user-net-ipv6-only-names "10.231.0.10" $D run --rm --network ipamnet --dns # ones within the 4 s each is given (12 s in all, as with Docker). $D rm -f kiri-e2e-dig-seed >/dev/null 2>&1 $D run --name kiri-e2e-dig-seed alpine apk add --no-cache bind-tools >/dev/null 2>&1 && $D commit kiri-e2e-dig-seed kiri-e2e-dig >/dev/null && $D rm -f kiri-e2e-dig-seed >/dev/null +# #715: gRPC looks up `_grpclb._tcp.` before the name's A records. +# The service is on this network, so it is answered NODATA here rather than +# forwarded: a silent --dns server must not turn the lookup into a timeout. +t dns-user-net-srv-nodata "NOERROR 0" $D run --rm --network ipamnet --dns 192.0.2.1 kiri-e2e-dig sh -c 'o=$(dig +tries=1 +time=2 _grpclb._tcp.fixed. SRV); s=$(echo "$o" | grep -o "status: [A-Z]*"); a=$(echo "$o" | grep -o "ANSWER: [0-9]*"); echo "${s#status: } ${a#ANSWER: }"' t dns-user-net-three-refused-servfail-at-once "SERVFAIL fast" $D run --rm --network ipamnet --dns 10.231.0.10 --dns 10.231.0.10 --dns 10.231.0.10 kiri-e2e-dig sh -c 's=$(date +%s); a=$(dig +tries=1 +time=20 example.com | grep -o "status: [A-Z]*"); [ $(( $(date +%s) - s )) -le 2 ] && echo "${a#status: } fast" || echo "${a#status: } slow"' t dns-user-net-three-silent-servfail-in-time "SERVFAIL in time" $D run --rm --network ipamnet --dns 192.0.2.1 --dns 192.0.2.2 --dns 192.0.2.3 kiri-e2e-dig sh -c 's=$(date +%s); a=$(dig +tries=1 +time=20 example.com | grep -o "status: [A-Z]*"); [ $(( $(date +%s) - s )) -le 14 ] && echo "${a#status: } in time" || echo "${a#status: } late"' $D rmi kiri-e2e-dig >/dev/null 2>&1 diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 5bb6ba96a..d5cb3168f 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -111,6 +111,7 @@ user-net-own-dns-upstream #624 a container running its own DNS server must still dns-user-net-next-after-refusal #455 on a user network a --dns server that refused ended the lookup: the next --dns server was never asked dns-user-net-all-refused-fails-at-once #455 when every --dns server of a container on a user network refused, the lookup waited for the client to give up instead of failing dns-user-net-next-after-silence #455 on a user network a --dns server that never answered ended the lookup: the next --dns server was never asked +dns-user-net-srv-nodata #715 gRPC's `_grpclb._tcp.` SRV lookup was forwarded instead of answered NODATA, so Go's resolver timed out on 127.0.0.11 and gRPC shut the channel down top-l #625 docker top -l was refused or gave the wrong columns top-l-values #625 docker top -l gave wrong values top-efl-cmd #625 docker top -efl gave the wrong command column From 3bbf813dab8a4b6776c55d6c69ab19cb3ed86a56 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 21:34:21 +0100 Subject: [PATCH 028/157] Host relay: close open proxy connections when the relay stream ends (#515) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/hostrelay.rs | 314 ++++++++++++++++++++++++++++++++--- docs/fix-registry.md | 6 + 2 files changed, 294 insertions(+), 26 deletions(-) diff --git a/crates/kiri/src/hostrelay.rs b/crates/kiri/src/hostrelay.rs index ad3a4565c..0ad8e0abb 100644 --- a/crates/kiri/src/hostrelay.rs +++ b/crates/kiri/src/hostrelay.rs @@ -95,20 +95,66 @@ struct Entry { stream: Option, } +#[derive(Default)] +struct State { + closed: bool, + entries: HashMap, +} + /// The connections open through one relay, by id. #[derive(Default)] -pub struct Conns(Mutex>); +pub struct Conns(Mutex); + +struct CloseAll(Arc); + +impl Drop for CloseAll { + fn drop(&mut self) { + self.0.close_all(); + } +} impl Conns { - fn map(&self) -> std::sync::MutexGuard<'_, HashMap> { + fn state(&self) -> std::sync::MutexGuard<'_, State> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// A new connection: what arrives for it waits here until it is made. - fn open(&self, id: u32) -> Receiver { + fn open(&self, id: u32) -> Option> { let (tx, rx) = sync_channel(QUEUE); - self.map().insert(id, Entry { tx, stream: None }); - rx + let prev = { + let mut s = self.state(); + if s.closed { + return None; + } + s.entries.insert(id, Entry { tx, stream: None }) + }; + if let Some(prev) = prev + && let Some(stream) = prev.stream + { + let _ = stream.shutdown(Shutdown::Both); + } + Some(rx) + } + + fn close(&self, id: u32) -> bool { + let Some(e) = self.state().entries.remove(&id) else { return false }; + if let Some(s) = e.stream { + let _ = s.shutdown(Shutdown::Both); + } + true + } + + fn close_all(&self) { + let entries = { + let mut s = self.state(); + s.closed = true; + std::mem::take(&mut s.entries) + }; + for (_, e) in entries { + if let Some(s) = e.stream { + let _ = s.shutdown(Shutdown::Both); + } + } } /// A frame for one of the connections. @@ -117,22 +163,17 @@ impl Conns { DATA => Op::Data(data), EOF => Op::Eof, CLOSE => { - if let Some(e) = self.map().remove(&id) - && let Some(s) = e.stream - { - let _ = s.shutdown(Shutdown::Both); - } + self.close(id); return; } _ => return, }; // Sent outside the lock: a full queue waits for its own writer only. - let tx = self.map().get(&id).map(|e| e.tx.clone()); + let tx = self.state().entries.get(&id).map(|e| e.tx.clone()); if let Some(tx) = tx { let _ = tx.send(op); } } - } /// Joins `stream` to connection `id`: what it reads goes to the other end @@ -140,17 +181,23 @@ impl Conns { fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpStream) { let _ = stream.set_nodelay(true); let (Ok(reader), Ok(writer)) = (stream.try_clone(), stream.try_clone()) else { - conns.map().remove(&id); + conns.close(id); let _ = send(out, CLOSE, id, &[]); return; }; - match conns.map().get_mut(&id) { - Some(e) => e.stream = Some(stream), - // Closed while it was being made. - None => { - let _ = stream.shutdown(Shutdown::Both); - return; + let (attached, to_shutdown) = { + let mut s = conns.state(); + match s.entries.get_mut(&id) { + Some(e) => (true, e.stream.replace(stream)), + // Closed while it was being made. + None => (false, Some(stream)), } + }; + if let Some(s) = to_shutdown { + let _ = s.shutdown(Shutdown::Both); + } + if !attached { + return; } // Each half that ends counts; the second one forgets the connection. let halves = Arc::new(AtomicU8::new(0)); @@ -159,7 +206,7 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS let halves = halves.clone(); move || { if halves.fetch_add(1, Ordering::SeqCst) == 1 { - conns.map().remove(&id); + conns.close(id); } } }; @@ -172,7 +219,7 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS Op::Data(d) => { if writer.write_all(&d).is_err() { let _ = writer.shutdown(Shutdown::Both); - c.map().remove(&id); + c.close(id); let _ = send(&o, CLOSE, id, &[]); return; } @@ -193,18 +240,21 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS loop { match reader.read(&mut buf) { Ok(0) => { - let _ = send(&o, EOF, id, &[]); + if send(&o, EOF, id, &[]).is_err() { + c.close(id); + } break; } Ok(n) => { if send(&o, DATA, id, &buf[..n]).is_err() { + c.close(id); break; } } Err(e) if e.kind() == io::ErrorKind::Interrupted => {} Err(_) => { // Gone while the other end may still be sending: say so. - if c.map().remove(&id).is_some() { + if c.close(id) { let _ = send(&o, CLOSE, id, &[]); } break; @@ -219,6 +269,7 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS /// connection over `out`, until kiri-win goes, and the listeners with it. pub fn listen_side(input: impl Read, out: &Out) -> io::Result<()> { let conns = Arc::new(Conns::default()); + let _close = CloseAll(conns.clone()); let next = Arc::new(AtomicU32::new(1)); let mut listening: HashMap = HashMap::new(); let mut r = BufReader::with_capacity(CHUNK, input); @@ -254,8 +305,13 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> for s in l.incoming() { let Ok(s) = s else { continue }; let id = next.fetch_add(1, Ordering::SeqCst); - let rx = conns.open(id); + let Some(rx) = conns.open(id) else { + let _ = s.shutdown(Shutdown::Both); + return; + }; if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { + conns.close(id); + let _ = s.shutdown(Shutdown::Both); return; } attach(&conns, &out, id, rx, s); @@ -268,6 +324,7 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> /// on the ports `allowed` names, and hands LISTENING replies to `listening`. pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, listening: impl Fn(u16, u16)) -> io::Result<()> { let conns = Arc::new(Conns::default()); + let _close = CloseAll(conns.clone()); let mut r = BufReader::with_capacity(CHUNK, input); while let Some((kind, id, data)) = read_frame(&mut r)? { match kind { @@ -278,12 +335,12 @@ pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, lis continue; }; // Data that arrives while it dials waits in the queue. - let rx = conns.open(id); + let Some(rx) = conns.open(id) else { continue }; let (c, o) = (conns.clone(), out.clone()); std::thread::spawn(move || match dial(target) { Ok(s) => attach(&c, &o, id, rx, s), Err(_) => { - c.map().remove(&id); + c.close(id); let _ = send(&o, CLOSE, id, &[]); } }); @@ -453,4 +510,209 @@ mod tests { let mut buf = [0u8; 1]; assert!(matches!(c.read(&mut buf), Ok(0) | Err(_))); } + + fn assert_closed(conn: &mut TcpStream) { + conn.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + let mut buf = [0u8; 1]; + let res = conn.read(&mut buf); + assert!( + matches!(res, Ok(0)) + || matches!(res, Err(ref e) if !matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)), + "expected closed socket, got {res:?}" + ); + } + + #[test] + fn ending_the_relay_closes_its_open_connections() { + // dial_side: open proxy socket closes when the frame stream hits EOF. + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(dial_out); + assert_closed(&mut conn); + + // listen_side: open client socket closes when the frame stream hits EOF. + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let listen_out: Out = Arc::new(Mutex::new(out_tx)); + let o = listen_out.clone(); + let h = std::thread::spawn(move || listen_side(in_rx, &o)); + + send(&in_out, LISTEN, 0, &port.to_be_bytes()).unwrap(); + let Some((LISTENING, 0, reply)) = read_frame(&mut out_rx).unwrap() else { panic!("expected LISTENING") }; + let local = port_of(&reply, 2).unwrap(); + let mut client = TcpStream::connect(("127.0.0.1", local)).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((OPEN, 1, port.to_be_bytes().to_vec()))); + client.write_all(b"y").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"y".to_vec()))); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(listen_out); + assert_closed(&mut client); + } + + #[test] + fn ending_the_relay_with_a_full_queue_tears_down_without_deadlocking() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + // Fill the socket send buffer and the sync_channel(QUEUE) buffer without reading from conn. + let chunk = vec![b'a'; CHUNK * 4]; + for _ in 0..QUEUE { + send(&in_out, DATA, 1, &chunk).unwrap(); + } + + drop(in_out); + h.join().unwrap().unwrap(); + drop(dial_out); + // Drain any kernel-buffered bytes and confirm the socket was shut down. + conn.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + let mut buf = vec![0u8; CHUNK * 4]; + loop { + match conn.read(&mut buf) { + Ok(0) => break, + Ok(_) => continue, + Err(e) => { + assert!( + !matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock), + "expected closed socket after full queue EOF, got {e:?}" + ); + break; + } + } + } + + // Also verify teardown when all QUEUE slots of sync_channel(QUEUE) are 100% full (TrySendError::Full). + let conns = Arc::new(Conns::default()); + let (_out_rx, out_tx) = io::pipe().unwrap(); + let out: Out = Arc::new(Mutex::new(out_tx)); + let rx = conns.open(1).unwrap(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + let tx = conns.state().entries.get(&1).unwrap().tx.clone(); + while tx.try_send(Op::Data(chunk.clone())).is_ok() { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(matches!(tx.try_send(Op::Data(vec![b'z'])), Err(std::sync::mpsc::TrySendError::Full(_)))); + drop(tx); + conns.close_all(); + assert!(conns.state().entries.is_empty()); + assert!(conns.open(2).is_none()); + peer.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(_) => continue, + Err(e) => { + assert!(!matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)); + break; + } + } + } + } + + #[test] + fn broken_frame_output_pipe_cleans_up_the_connection() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + // Break the output pipe while the input stream stays open. + drop(out_rx); + let _ = conn.write_all(b"y"); + assert_closed(&mut conn); + + drop(in_out); + h.join().unwrap().unwrap(); + + // Direct Conns check: a broken output pipe removes the entry from Conns. + let conns = Arc::new(Conns::default()); + let (out_rx, out_tx) = io::pipe().unwrap(); + drop(out_rx); + let out: Out = Arc::new(Mutex::new(out_tx)); + let rx = conns.open(1).unwrap(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + assert!(conns.state().entries.contains_key(&1)); + peer.write_all(b"z").unwrap(); + assert_closed(&mut peer); + assert!(conns.state().entries.is_empty()); + } + + #[test] + fn connections_attaching_or_arriving_after_close_all_are_shut_down() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (_out_rx, out_tx) = io::pipe().unwrap(); + let out: Out = Arc::new(Mutex::new(out_tx)); + + // 1. An in-flight connection opened before close_all() that reaches attach() after close_all(). + let conns = Arc::new(Conns::default()); + let rx = conns.open(1).unwrap(); + conns.close_all(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + assert_closed(&mut peer); + assert!(conns.state().entries.is_empty()); + + // 2. A new TCP connection arriving at listen_side's listener after listen_side has torn down. + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let listen_out: Out = Arc::new(Mutex::new(out_tx)); + let o = listen_out.clone(); + let h = std::thread::spawn(move || listen_side(in_rx, &o)); + + send(&in_out, LISTEN, 0, &port.to_be_bytes()).unwrap(); + let Some((LISTENING, 0, reply)) = read_frame(&mut out_rx).unwrap() else { panic!("expected LISTENING") }; + let local = port_of(&reply, 2).unwrap(); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(listen_out); + + if let Ok(mut late) = TcpStream::connect(("127.0.0.1", local)) { + assert_closed(&mut late); + } + assert!(read_frame(&mut out_rx).unwrap().is_none(), "no OPEN frame emitted after teardown"); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 9e450366b..f68d3f12e 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 +### #515 Host relay: close open proxy connections when the relay stream ends (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #715 DNS: Go clients' SRV lookups are answered here, and forwarded lookups are never silently dropped (unreleased) - Fixes: #715 Go gRPC clients (RoadRunner's Temporal plugin) fail with "context deadline exceeded" resolving container names via 127.0.0.11 while getent/nslookup/dig work - Caused: none known From 6d8e6549ca5465880281e047e08e12b4464efa87 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 21:44:07 +0100 Subject: [PATCH 029/157] Copy: mount non-running containers' volumes and binds and enforce read-only refusals (#245) --- crates/kiri-init/src/linux/container.rs | 20 +- crates/kiri-init/src/linux/copy.rs | 417 ++++++++++++++++++++++-- crates/kiri-proto/src/lib.rs | 37 ++- crates/kiri/src/daemon/api.rs | 19 +- crates/kiri/src/daemon/builder.rs | 2 +- crates/kiri/src/daemon/engine.rs | 68 +++- crates/kiri/src/daemon/http.rs | 1 + docs/fix-registry.md | 6 + tests/e2e.sh | 80 ++++- tests/regressions.tsv | 8 + 10 files changed, 610 insertions(+), 48 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 3e471384d..46fc88476 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1517,7 +1517,7 @@ pub(super) fn use_embedded_dns(id: &str, is_kiri: impl Fn([u8; 4]) -> bool) -> i } /// One mount, resolved before clone. -struct Mount { +pub(super) struct Mount { /// A guest path, or None for a tmpfs. source: Option, /// Relative to the container root (the child mounts before pivot_root). @@ -1533,12 +1533,22 @@ struct Mount { tmpfs_flags: libc::c_ulong, } +impl Mount { + pub(super) fn is_tmpfs(&self) -> bool { + self.tmpfs_opts.is_some() + } + + pub(super) fn is_copy_up(&self) -> bool { + self.copy_up + } +} + /// `source\ttarget\tflags` entries. Flags: `ro`, `create` (make the source /// directory), `copyup`, `tmpfs` (source ignored) and tmpfs options and /// flags (`noexec`, `exec`, `nosuid`, …; later ones win). A volume with /// driver options adds `\ttype\tdevice\tflags(hex)\tdata`, and is mounted /// at its source first. -fn parse_mounts(list: StrList<'_>) -> io::Result> { +pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> { let mut out = Vec::with_capacity(list.len()); for m in list.iter() { let bad = || io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}")); @@ -1600,7 +1610,7 @@ fn depth(target: &CStr) -> usize { /// A tmpfs's mount flags from its flag words, in order, so `exec` after /// Docker's default `noexec` wins. -fn tmpfs_flags(words: &[&str]) -> libc::c_ulong { +pub(super) fn tmpfs_flags(words: &[&str]) -> libc::c_ulong { let mut f = 0; for w in words { match *w { @@ -1624,7 +1634,7 @@ fn tmpfs_flags(words: &[&str]) -> libc::c_ulong { /// pivot_root), creating the target as a directory or an empty file. The /// target is looked up inside `root`, so an image's symlink cannot point /// the mount, the copy-up or the new directory outside the container. -fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) -> io::Result<()> { +pub(super) fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) -> io::Result<()> { let t = Path::new(std::ffi::OsStr::from_bytes(m.target.to_bytes())); if let Some(opts) = &m.tmpfs_opts { let at = inroot::open(root, t, Last::Dir)?; @@ -1706,7 +1716,7 @@ fn same_dir(a: &inroot::Found, b: &inroot::Found) -> bool { /// root) without the mounts on it: the image as it is under any bind. /// None where the kernel has no open_tree (before Linux 5.2); volumes are /// then filled from what the path shows, as before. -fn image_tree() -> Option { +pub(super) fn image_tree() -> Option { const OPEN_TREE_CLONE: libc::c_uint = 1; // SAFETY: a valid NUL-terminated path; the result is a new descriptor or -1. let fd = unsafe { libc::syscall(libc::SYS_open_tree, libc::AT_FDCWD, c".".as_ptr(), OPEN_TREE_CLONE | libc::O_CLOEXEC as libc::c_uint) }; diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index 0f7534735..c9f550c09 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -8,18 +8,19 @@ //! child asks for it over a socket pair of its own, so a copy and a start at //! the same moment share one mount (see `roots`, #227). +use std::cell::RefCell; +use std::error::Error as StdError; use std::fs; use std::io::{self, BufReader, BufWriter, Read, Write}; -use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt}; +use std::path::{Path, PathBuf}; -use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, copy_flags, copy_op}; - -use std::cell::RefCell; -use std::path::PathBuf; +use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, StrList, copy_flags, copy_op}; use super::container::{self, Paths}; +use super::inroot; use super::sys; /// A copy child as the agent sees it: its end of the child's socket pair @@ -191,11 +192,13 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa // These read the writable layer itself, next to the image's layers. copy_op::DIFF | copy_op::COMMIT => layer_job(&mut conn, &spec, paths), _ => { - if let Err(e) = enter(&spec, running, paths, &chan) { - return reply_error(&mut conn, &format!("container {}: {e}", spec.id)); - } + let mounts = match enter(&spec, running, paths, &chan) { + Ok(m) => m, + Err(e) => return reply_error(&mut conn, &format!("container {}: {e}", spec.id)), + }; + drop(chan); match spec.op { - copy_op::IN => copy_in(&mut conn, &spec), + copy_op::IN => copy_in(&mut conn, &spec, &mounts), copy_op::OUT | copy_op::STAT => copy_out(&mut conn, &spec), copy_op::EXPORT => export(&mut conn), op => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unknown copy op {op}"))), @@ -208,9 +211,59 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa } } -/// Makes the container's root this process's `/`. -fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> { - let root = match running.iter().find(|(id, _)| *id == spec.id) { +/// A mount active in the container's root view, used by `copy_in` to refuse +/// writes into read-only mounts and to overwrite bind-mounted files in place. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MountAccess { + target: PathBuf, + ro: bool, + tmpfs: bool, +} + +/// Normalizes an absolute mount target path (`"/data/"` → `"/data"`, `"/"` stays `"/"`). +fn clean_mount_target(target: &str) -> String { + let parts: Vec<&str> = target.split('/').filter(|c| !c.is_empty() && *c != ".").collect(); + format!("/{}", parts.join("/")) +} + +/// Pure parsing of `CopySpec::mounts` (no filesystem I/O): validates each line +/// and sorts parent-first, matching `container::parse_mounts`. +fn parse_mount_access(list: StrList<'_>) -> io::Result> { + let mut out = Vec::with_capacity(list.len()); + for m in list.iter() { + let f: Vec<&str> = m.split('\t').collect(); + if f.len() != 3 && f.len() != 7 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}"))); + } + let (given_target, words) = (f[1], f[2]); + if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}"))); + } + let flags: Vec<&str> = words.split(',').filter(|w| !w.is_empty()).collect(); + let tmpfs = flags.contains(&"tmpfs"); + let ro = if tmpfs { container::tmpfs_flags(&flags) & libc::MS_RDONLY != 0 } else { flags.contains(&"ro") }; + out.push(MountAccess { target: PathBuf::from(clean_mount_target(given_target)), ro, tmpfs }); + } + out.sort_by_key(|m| m.target.components().count()); + Ok(out) +} + +/// Resolves each mount's target inside the container chroot so symlinks in +/// mount target paths (e.g. `/var/run/cfg` → `/run/cfg`) match canonicalized +/// destination paths. +fn resolve_mount_targets(access: &mut [MountAccess]) { + for m in access { + if let Ok(real) = fs::canonicalize(&m.target) { + m.target = real; + } + } +} + +/// Makes the container's root this process's `/`, assembling non-tmpfs volumes +/// and bind mounts in a private mount namespace when the container is not +/// running (except for `EXPORT`, which reads only the overlay rootfs). +fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result> { + match running.iter().find(|(id, _)| *id == spec.id) { // An export is the container's own filesystem, without its mounts: // the overlay the agent mounted for it. // It may have stopped since: then the root is mounted for it. @@ -221,24 +274,70 @@ fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, ch } ask(chan, 'm', spec)?; } - paths.containers.join(spec.id).join("rootfs") + chroot_into(&paths.containers.join(spec.id).join("rootfs"))?; + Ok(Vec::new()) } - // Through /proc the root shows the container's mounts (volumes) too. - // The copy holds the container's root meanwhile, so a restart can't - // mount a second one over the same layer while it still writes. + // Through /proc the root shows the container's live mounts (including + // tmpfs). The copy holds the container's root meanwhile, so a restart + // can't mount a second one over the same layer while it still writes. Some((_, pid)) => { let _ = ask(chan, 'h', spec); - std::path::PathBuf::from(format!("/proc/{pid}/root")) + let mut access = parse_mount_access(spec.mounts)?; + chroot_into(&PathBuf::from(format!("/proc/{pid}/root")))?; + resolve_mount_targets(&mut access); + Ok(access) } None => { if spec.layers.is_empty() { return Err(io::Error::new(io::ErrorKind::NotFound, "no such container")); } ask(chan, 'm', spec)?; - paths.containers.join(spec.id).join("rootfs") + let rootfs = paths.containers.join(spec.id).join("rootfs"); + if spec.op == copy_op::EXPORT { + chroot_into(&rootfs)?; + return Ok(Vec::new()); + } + // A stopped or created container has no live tmpfs mounts. + let mut access = parse_mount_access(spec.mounts)?; + access.retain(|m| !m.tmpfs); + if !access.is_empty() { + // Assemble mounts strictly inside this short-lived child's own + // mount namespace so nothing ever leaks into the agent's. + sys::unshare(libc::CLONE_NEWNS)?; + sys::remount(c"/", libc::MS_REC | libc::MS_SLAVE)?; + let mut mounts = container::parse_mounts(spec.mounts)?; + mounts.retain(|m| !m.is_tmpfs()); + let rootfs_c = sys::cstr(&rootfs)?; + // SAFETY: valid NUL-terminated path. + unsafe { sys::check(libc::chdir(rootfs_c.as_ptr()) as _, "chdir")? }; + let root = inroot::open_root(Path::new("."))?; + let image = if mounts.iter().any(container::Mount::is_copy_up) { container::image_tree() } else { None }; + for m in &mounts { + container::apply_mount(root.as_fd(), image.as_ref().map(|f| f.as_fd()), m)?; + } + drop(image); + drop(root); + if spec.op == copy_op::IN && spec.flags & copy_flags::READONLY_ROOTFS != 0 { + // Defense in depth: remount only the rootfs mount read-only + // in our private namespace, leaving writable mounts rw. + sys::mount(c"none", c".", c"none", libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY, None)?; + } + // SAFETY: valid NUL-terminated paths. + unsafe { + sys::check(libc::chroot(c".".as_ptr()) as _, "chroot")?; + sys::check(libc::chdir(c"/".as_ptr()) as _, "chdir")?; + } + } else { + chroot_into(&rootfs)?; + } + resolve_mount_targets(&mut access); + Ok(access) } - }; - let c = sys::cstr(&root)?; + } +} + +fn chroot_into(root: &Path) -> io::Result<()> { + let c = sys::cstr(root)?; // SAFETY: valid NUL-terminated paths. unsafe { sys::check(libc::chroot(c.as_ptr()) as _, "chroot")?; @@ -271,8 +370,125 @@ fn ask(chan: &OwnedFd, kind: char, spec: &CopySpec<'_>) -> io::Result<()> { } } +/// Refuses writes when the innermost mount containing `canonical_path` is +/// read-only, or when `canonical_path` is outside every mount and the +/// container has `--read-only`. +fn check_writable(canonical_path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Result<()> { + let innermost = mounts + .iter() + .filter(|m| canonical_path == m.target || canonical_path.starts_with(&m.target)) + .max_by_key(|m| m.target.components().count()); + match innermost { + Some(m) if m.ro => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only")), + Some(_) => Ok(()), + None if readonly_rootfs => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: container rootfs is marked read-only")), + None => Ok(()), + } +} + +/// Resolves a tar entry's target path under `canonical_dest`, following +/// existing symlinks in parent components (inside the container chroot) while +/// keeping the final component unfollowed (since unpacking replaces a final +/// symlink rather than writing through it). +fn resolve_entry_target(canonical_dest: &Path, entry_path: &Path) -> PathBuf { + let mut parts: Vec<&std::ffi::OsStr> = Vec::new(); + for c in entry_path.components() { + match c { + std::path::Component::Normal(p) => parts.push(p), + std::path::Component::ParentDir => { + parts.pop(); + } + std::path::Component::CurDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {} + } + } + let Some((last, parents)) = parts.split_last() else { + return canonical_dest.to_path_buf(); + }; + let mut cur = canonical_dest.to_path_buf(); + let mut exists = true; + for part in parents { + cur.push(part); + if exists { + match fs::canonicalize(&cur) { + Ok(real) => cur = real, + Err(_) => exists = false, + } + } + } + cur.push(last); + cur +} + +fn is_erofs(e: &io::Error) -> bool { + if e.raw_os_error() == Some(libc::EROFS) { + return true; + } + let mut cur: Option<&(dyn StdError + 'static)> = e.source(); + while let Some(src) = cur { + if src.downcast_ref::().is_some_and(|ioe| ioe.raw_os_error() == Some(libc::EROFS)) { + return true; + } + cur = src.source(); + } + false +} + +fn map_erofs(e: io::Error, path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Error { + if !is_erofs(&e) { + return e; + } + match check_writable(path, mounts, readonly_rootfs) { + Err(ro) => ro, + Ok(()) => io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only"), + } +} + +/// Overwrites an existing bind-mounted regular file in place: `unlink(2)` on a +/// file bind mount fails with `EBUSY`, so `tar::Entry::unpack_in` cannot +/// replace it by remove-and-recreate. +fn unpack_mount_file(entry: &mut tar::Entry<'_, R>, target: &Path, owner: Option<(libc::uid_t, libc::gid_t)>) -> io::Result<()> { + let c = sys::cstr(target)?; + // SAFETY: valid NUL-terminated path; O_NOFOLLOW never follows a symlink, + // and O_NONBLOCK avoids blocking if a FIFO was swapped in. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_WRONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor owned only here. + let mut file = fs::File::from(unsafe { OwnedFd::from_raw_fd(fd) }); + // SAFETY: plain zeroed stat filled from our own descriptor. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + sys::check(unsafe { libc::fstat(file.as_raw_fd(), &mut st) } as _, "fstat")?; + if st.st_mode & libc::S_IFMT != libc::S_IFREG { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "mount target is not a regular file")); + } + // SAFETY: valid regular-file descriptor we own. + sys::check(unsafe { libc::ftruncate(file.as_raw_fd(), 0) } as _, "ftruncate")?; + io::copy(entry, &mut file)?; + if let Some((uid, gid)) = owner { + // SAFETY: valid descriptor we own. + sys::check(unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } as _, "fchown")?; + } else if let (Ok(uid), Ok(gid)) = (entry.header().uid(), entry.header().gid()) { + // SAFETY: valid descriptor we own; best-effort like tar::Archive. + unsafe { libc::fchown(file.as_raw_fd(), uid as libc::uid_t, gid as libc::gid_t) }; + } + if let Ok(mode) = entry.header().mode() { + // SAFETY: valid descriptor we own. + sys::check(unsafe { libc::fchmod(file.as_raw_fd(), (mode & 0o7777) as libc::mode_t) } as _, "fchmod")?; + } + if let Ok(mtime) = entry.header().mtime() { + let times = [ + libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }, + libc::timespec { tv_sec: mtime as _, tv_nsec: 0 }, + ]; + // SAFETY: valid descriptor and 2-element timespec array. + unsafe { libc::futimens(file.as_raw_fd(), times.as_ptr()) }; + } + Ok(()) +} + /// Unpacks the archive that follows into `spec.path`, a directory. -fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { +fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>, mounts: &[MountAccess]) -> io::Result<()> { let (path, user) = if spec.flags & copy_flags::KEEP_OWNERS != 0 { spec.path.split_once('\0').unwrap_or((spec.path, "")) } else { @@ -284,10 +500,13 @@ fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {path}"))), Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {path} in container {}", spec.id))), } + let canonical_dest = fs::canonicalize(dest)?; + let readonly_rootfs = spec.flags & copy_flags::READONLY_ROOTFS != 0; + check_writable(&canonical_dest, mounts, readonly_rootfs)?; let owner = if user.is_empty() { None } else { Some(resolve_copy_user_in(std::path::Path::new("/"), user)?) }; let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) }; let mut reader = BufReader::with_capacity(256 * 1024, source); - unpack_in(&mut reader, dest, spec.flags, owner)?; + unpack_in(&mut reader, dest, &canonical_dest, spec.flags, owner, mounts, readonly_rootfs)?; // The archive's trailing padding: read it so the host's writes complete. io::copy(&mut reader, &mut io::sink())?; drop(reader); @@ -350,7 +569,15 @@ fn resolve_copy_user_in(root: &std::path::Path, user: &str) -> io::Result<(libc: Ok((uid, gid)) } -fn unpack_in(reader: impl Read, dest: &std::path::Path, flags: u32, owner: Option<(libc::uid_t, libc::gid_t)>) -> io::Result<()> { +fn unpack_in( + reader: impl Read, + dest: &std::path::Path, + canonical_dest: &std::path::Path, + flags: u32, + owner: Option<(libc::uid_t, libc::gid_t)>, + mounts: &[MountAccess], + readonly_rootfs: bool, +) -> io::Result<()> { let mut archive = tar::Archive::new(reader); archive.set_preserve_permissions(true); archive.set_preserve_mtime(true); @@ -363,10 +590,19 @@ fn unpack_in(reader: impl Read, dest: &std::path::Path, flags: u32, owner: Optio archive.set_overwrite(true); for entry in archive.entries()? { let mut entry = entry?; + let path = entry.path()?.into_owned(); + let etype = entry.header().entry_type(); + let check_path = if !etype.is_pax_global_extensions() && !etype.is_pax_local_extensions() { + let resolved = resolve_entry_target(canonical_dest, &path); + check_writable(&resolved, mounts, readonly_rootfs)?; + Some(resolved) + } else { + None + }; if flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 { - let target = dest.join(entry.path()?); + let target = dest.join(&path); if let Ok(m) = fs::symlink_metadata(&target) - && m.is_dir() != entry.header().entry_type().is_dir() + && m.is_dir() != etype.is_dir() { return Err(io::Error::new( io::ErrorKind::AlreadyExists, @@ -374,11 +610,19 @@ fn unpack_in(reader: impl Read, dest: &std::path::Path, flags: u32, owner: Optio )); } } - let path = entry.path()?.into_owned(); + if let Some(ref resolved) = check_path + && etype.is_file() + && mounts.iter().any(|m| m.target == *resolved) + && fs::symlink_metadata(resolved).is_ok_and(|m| m.file_type().is_file()) + { + unpack_mount_file(&mut entry, resolved, owner).map_err(|e| map_erofs(e, resolved, mounts, readonly_rootfs))?; + continue; + } // `docker cp` and the classic build's context keep a time of 0. - if entry.unpack_in(dest)? { + let target_for_err = check_path.as_deref().unwrap_or(canonical_dest); + if entry.unpack_in(dest).map_err(|e| map_erofs(e, target_for_err, mounts, readonly_rootfs))? { if let Some((uid, gid)) = owner - && !entry.header().entry_type().is_pax_global_extensions() + && !etype.is_pax_global_extensions() { let mut file_dst = dest.to_path_buf(); for part in path.components() { @@ -967,7 +1211,7 @@ mod tests { b.append_data(&mut h(tar::EntryType::Regular, 3, 0o640), "replaced", &b"new"[..]).unwrap(); let bytes = b.into_inner().unwrap(); - unpack_in(&bytes[..], &dest, 0, None).unwrap(); + unpack_in(&bytes[..], &dest, &dest, 0, None, &[], false).unwrap(); let meta = |p: &str| fs::symlink_metadata(dest.join(p)).unwrap(); let dir = meta("dir"); @@ -986,7 +1230,7 @@ mod tests { assert_eq!((target.uid(), target.gid()), (0, 0)); assert_eq!(fs::read(dest.join("target")).unwrap(), b"stay"); - unpack_in(&bytes[..], &dest, 0, Some((2375, 2376))).unwrap(); + unpack_in(&bytes[..], &dest, &dest, 0, Some((2375, 2376)), &[], false).unwrap(); assert_eq!((meta("dir").uid(), meta("dir").gid()), (2375, 2376)); assert_eq!((meta("dir/owned.pem").uid(), meta("dir/owned.pem").gid(), meta("dir/owned.pem").mode() & 0o777), (2375, 2376, 0o600)); assert_eq!((meta("link").uid(), meta("link").gid()), (2375, 2376)); @@ -1095,4 +1339,117 @@ mod tests { let _ = fs::remove_dir_all(&base); } + + #[test] + fn parse_mount_access_sorts_parents_first_and_tracks_ro_and_tmpfs() { + let mut buf = Vec::new(); + kiri_proto::encode_copy( + &mut buf, + copy_op::IN, + "c1", + "/", + 0, + &["sha256:a"], + &[ + "/v/sub\t/app/sub/\tro", + "/v/app\t/app\tcreate,copyup", + "tmpfs\t/tmp\ttmpfs,noexec,ro", + "tmpfs\t/run\ttmpfs,ro,rw", + ], + ); + let Msg::Copy(spec) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let got = parse_mount_access(spec.mounts).unwrap(); + assert_eq!( + got, + [ + MountAccess { target: PathBuf::from("/app"), ro: false, tmpfs: false }, + MountAccess { target: PathBuf::from("/tmp"), ro: true, tmpfs: true }, + MountAccess { target: PathBuf::from("/run"), ro: false, tmpfs: true }, + MountAccess { target: PathBuf::from("/app/sub"), ro: true, tmpfs: false }, + ] + ); + let mut bad = Vec::new(); + kiri_proto::encode_copy(&mut bad, copy_op::IN, "c1", "/", 0, &[], &["/src\t../escape\tro"]); + let Msg::Copy(bad_spec) = kiri_proto::decode(&bad).unwrap() else { panic!() }; + assert!(parse_mount_access(bad_spec.mounts).is_err()); + } + + #[test] + fn check_writable_enforces_innermost_mount_and_readonly_rootfs() { + let m = |target: &str, ro: bool| MountAccess { target: PathBuf::from(target), ro, tmpfs: false }; + let mounts = [m("/app", false), m("/app/ro", true), m("/app/ro/rw", false), m("/ro", true)]; + let err = |p: &str, ro_root: bool| check_writable(Path::new(p), &mounts, ro_root).unwrap_err().to_string(); + + assert_eq!(err("/ro", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/ro/sub/f", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/app/ro", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/app/ro/file", false), "forbidden: mounted volume is marked read-only"); + // Component boundary: `/app/ro2` is under `/app` (rw), not `/app/ro`. + assert!(check_writable(Path::new("/app/ro2/file"), &mounts, true).is_ok()); + // Writable nested mount inside a read-only mount succeeds. + assert!(check_writable(Path::new("/app/ro/rw"), &mounts, true).is_ok()); + assert!(check_writable(Path::new("/app/ro/rw/x"), &mounts, true).is_ok()); + // Path outside every mount: refused iff `--read-only`. + assert!(check_writable(Path::new("/etc"), &mounts, false).is_ok()); + assert_eq!(err("/etc", true), "forbidden: container rootfs is marked read-only"); + // Writable mount on a `--read-only` rootfs succeeds. + assert!(check_writable(Path::new("/app/file"), &mounts, true).is_ok()); + // `:ro` mount on a `--read-only` rootfs reports the mounted volume error. + assert_eq!(err("/ro/x", true), "forbidden: mounted volume is marked read-only"); + } + + #[test] + fn unpack_in_refuses_ro_mounts_and_overwrites_file_mounts_in_place() { + let base = std::env::temp_dir().join(format!("kiri-copy-ro-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let root = base.join("root"); + fs::create_dir_all(root.join("ro")).unwrap(); + fs::create_dir_all(root.join("rw")).unwrap(); + fs::create_dir_all(root.join("etc")).unwrap(); + fs::write(root.join("etc/app.conf"), b"old").unwrap(); + fs::write(root.join("etc/ro.conf"), b"stay").unwrap(); + std::os::unix::fs::symlink(root.join("etc"), root.join("rw/to_etc")).unwrap(); + let canonical_root = fs::canonicalize(&root).unwrap(); + let mounts = [ + MountAccess { target: canonical_root.join("ro"), ro: true, tmpfs: false }, + MountAccess { target: canonical_root.join("rw"), ro: false, tmpfs: false }, + MountAccess { target: canonical_root.join("etc/app.conf"), ro: false, tmpfs: false }, + MountAccess { target: canonical_root.join("etc/ro.conf"), ro: true, tmpfs: false }, + ]; + let tar_file = |name: &str, data: &[u8]| { + let mut b = tar::Builder::new(Vec::new()); + let mut h = tar::Header::new_gnu(); + h.set_entry_type(tar::EntryType::Regular); + h.set_size(data.len() as u64); + h.set_mode(0o640); + h.set_mtime(0); + h.set_cksum(); + b.append_data(&mut h, name, data).unwrap(); + b.into_inner().unwrap() + }; + + // Entry targeting a `:ro` file bind mount is refused before writing. + let bytes = tar_file("ro.conf", b"pwn"); + let err = unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap_err(); + assert_eq!(err.to_string(), "forbidden: mounted volume is marked read-only"); + assert_eq!(fs::read(canonical_root.join("etc/ro.conf")).unwrap(), b"stay"); + + // Entry escaping a `:rw` volume through a symlink to a `--read-only` rootfs is refused. + let bytes = tar_file("to_etc/pwn", b"bad"); + let err = unpack_in(&bytes[..], &canonical_root.join("rw"), &canonical_root.join("rw"), 0, None, &mounts, true).unwrap_err(); + assert_eq!(err.to_string(), "forbidden: container rootfs is marked read-only"); + assert!(!canonical_root.join("etc/pwn").exists()); + + // Entry targeting a `:rw` file bind mount overwrites in place (keeping inode and zero mtime). + let before_ino = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap().ino(); + let bytes = tar_file("app.conf", b"updated"); + unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap(); + let after = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap(); + assert_eq!(after.ino(), before_ino, "file bind mount must be overwritten in place, not unlinked"); + assert_eq!(fs::read(canonical_root.join("etc/app.conf")).unwrap(), b"updated"); + assert_eq!(after.mtime(), 0); + assert_eq!(after.mode() & 0o777, 0o640); + + let _ = fs::remove_dir_all(&base); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index d1a1b2fb6..5357d59fe 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -281,6 +281,9 @@ pub mod copy_flags { /// Intel Mac with macOS 14 passes a half-close on as a full one, and the /// guest's answer fails with EPIPE. pub const CHUNKED: u32 = 4; + /// `IN`: the container has `--read-only` (`HostConfig.ReadonlyRootfs`), so + /// writes outside writable mounts are refused. + pub const READONLY_ROOTFS: u32 = 8; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -290,16 +293,21 @@ pub struct CopySpec<'a> { pub path: &'a str, pub flags: u32, pub layers: StrList<'a>, + /// The container's mounts (`source\ttarget\tflags[\t…]`, as in + /// [`RunSpec::mounts`]). Empty from an older daemon, and empty for + /// `EXPORT`, `DIFF` and `COMMIT`. + pub mounts: StrList<'a>, } /// Encodes a `Copy` frame from the sender's side. -pub fn encode_copy>(out: &mut Vec, op: u8, id: &str, path: &str, flags: u32, layers: &[S]) { +pub fn encode_copy>(out: &mut Vec, op: u8, id: &str, path: &str, flags: u32, layers: &[S], mounts: &[S]) { frame(out, kind::COPY, |o| { o.push(op); put_str(o, id); put_str(o, path); put_u32(o, flags); StrList::put(o, layers); + StrList::put(o, mounts); }); } @@ -1199,6 +1207,8 @@ impl Msg<'_> { put_u32(o, c.flags); put_u32(o, c.layers.count); o.extend_from_slice(c.layers.raw); + put_u32(o, c.mounts.count); + o.extend_from_slice(c.mounts.raw); }), Msg::CopyStat { entry, link } => frame(out, kind::COPY_STAT, |o| { put_entry(o, &entry); @@ -1512,7 +1522,15 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { } Msg::DnsRename { id, bridge, ip, ip6, v4, names } } - kind::COPY => Msg::Copy(CopySpec { op: r.u8()?, id: r.str()?, path: r.str()?, flags: r.u32()?, layers: r.list()? }), + kind::COPY => Msg::Copy(CopySpec { + op: r.u8()?, + id: r.str()?, + path: r.str()?, + flags: r.u32()?, + layers: r.list()?, + // Trailing list; absent from an older daemon. + mounts: if r.remaining() >= 4 { r.list()? } else { StrList::default() }, + }), kind::COPY_STAT => Msg::CopyStat { entry: read_entry(&mut r)?, link: r.str()? }, kind::COPY_DONE => Msg::CopyDone, kind::UPDATE => Msg::Update { id: r.str()?, limits: read_limits(&mut r)? }, @@ -1916,13 +1934,24 @@ mod tests { round(Msg::Uplink { ip: [192, 168, 64, 18], gateway: [192, 168, 64, 1] }); round(Msg::Ack); let mut buf = Vec::new(); - encode_copy(&mut buf, copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS, &["sha256:a", "sha256:b"]); + let mounts = ["/var/lib/kiri/volumes/pg/_data\t/var/lib/postgresql/data\tcreate,copyup", "/host/cfg\t/etc/app\tro"]; + encode_copy(&mut buf, copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS | copy_flags::READONLY_ROOTFS, &["sha256:a", "sha256:b"], &mounts); let Msg::Copy(c) = decode(&buf).unwrap() else { panic!() }; - assert_eq!((c.op, c.id, c.path, c.flags), (copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS)); + assert_eq!((c.op, c.id, c.path, c.flags), (copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS | copy_flags::READONLY_ROOTFS)); assert_eq!(c.layers.iter().collect::>(), ["sha256:a", "sha256:b"]); + assert_eq!(c.mounts.iter().collect::>(), mounts); let mut again = Vec::new(); Msg::Copy(c).encode(&mut again); assert_eq!(buf, again); + // An older daemon's Copy frame without the mount list still decodes. + let mut old = Vec::new(); + encode_copy(&mut old, copy_op::OUT, "c1", "/etc", 0, &["sha256:a"], &[]); + old.truncate(old.len() - 4); + let len = (old.len() - 4) as u32; + old[..4].copy_from_slice(&len.to_le_bytes()); + let Msg::Copy(old_c) = decode(&old).unwrap() else { panic!() }; + assert_eq!(old_c.layers.iter().collect::>(), ["sha256:a"]); + assert!(old_c.mounts.is_empty()); let mut buf = Vec::new(); let entries = [ FsEntry { name: "a", mode: 0o100644, size: 1, mtime: 2, mtime_nsec: 9, ino: 1 }, diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index b36b4c42c..3a3599008 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -115,6 +115,7 @@ fn status_of(e: Error) -> (u16, String) { Error::Conflict(m) => (409, m), Error::BadRequest(m) => (400, m), Error::Unauthorized(m) => (401, m), + Error::Forbidden(m) => (403, m), Error::Io(e) => (500, e.to_string()), } } @@ -3403,6 +3404,8 @@ pub(super) fn send_chunks(archive: &mut dyn io::Read, to_guest: &mut impl io::Wr pub(super) fn copy_error(m: &str) -> Error { if let Some(m) = m.strip_prefix("notfound: ") { Error::NotFound(m.to_owned()) + } else if let Some(m) = m.strip_prefix("forbidden: ") { + Error::Forbidden(m.to_owned()) } else if let Some(m) = m.strip_prefix("notdir: ") { Error::BadRequest(m.to_owned()) } else if m.contains("no such container") { @@ -3459,7 +3462,11 @@ fn archive_get(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> // HEAD answers carry no body, so the reason goes nowhere; the CLI // reports "no such file" from the status alone. if req.method == "HEAD" { - let status = match copy_error(m) { Error::NotFound(_) => 404, _ => 400 }; + let status = match copy_error(m) { + Error::NotFound(_) => 404, + Error::Forbidden(_) => 403, + _ => 400, + }; http::head_only(w, status, "")?; return Ok(Next::KeepAlive); } @@ -4789,6 +4796,16 @@ mod tests { assert_eq!((got, at), (archive, wire.len())); } + #[test] + fn copy_error_maps_readonly_refusals_to_forbidden_403() { + for msg in ["mounted volume is marked read-only", "container rootfs is marked read-only"] { + let err = copy_error(&format!("forbidden: {msg}")); + assert_eq!(status_of(err), (403, msg.to_owned())); + } + assert_eq!(status_of(copy_error("notfound: Could not find the file /x in container c1")), (404, "Could not find the file /x in container c1".to_owned())); + assert_eq!(status_of(copy_error("notdir: extraction point is not a directory: /x")), (400, "extraction point is not a directory: /x".to_owned())); + } + #[test] fn intel_macs_refuse_images_without_amd64() { let p = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index cc3dedbc7..3a2721dc7 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -1063,7 +1063,7 @@ fn run(req: &Request, engine: &Engine, o: &mut Options, r: &mut BufReader m, + Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) | Error::Forbidden(m) => m, Error::Io(e) => e.to_string(), })?; let dir = format!("{WORK}/{}", super::engine::random_hex(8)); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index bf063c75b..16058bc70 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1374,6 +1374,7 @@ pub enum Error { Conflict(String), BadRequest(String), Unauthorized(String), + Forbidden(String), Io(io::Error), } @@ -3893,20 +3894,32 @@ impl Engine { /// Opens a `docker cp` session with the guest for a container, running /// or not: the request frame is sent, the caller does the rest. pub fn copy(&self, key: &str, op: u8, path: &str, flags: u32) -> Result { - self.wait_for_start(&self.resolve(key)?); + let use_mounts = matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT); + let (self_gate, shared_gates) = { + let st = self.lock(); + let id = resolve(&st, key)?; + let c = st.containers.get(&id).expect("resolved"); + let shared = if use_mounts { shared_volume_gates(&st, &id, &c.spec) } else { Vec::new() }; + (c.start_gate.clone(), shared) + }; + self_gate.wait(); + for gate in shared_gates { + gate.wait(); + } // Looked up after the wait: a `--rm` start that failed meanwhile has // removed the container, and a copy must not then write into a // folder made again for a container that no longer exists. - let (id, layers) = { + let (id, layers, spec) = { let st = self.lock(); let id = resolve(&st, key)?; - let layers = st.containers.get(&id).map(|c| c.layers.clone()).unwrap_or_default(); - (id, layers) + let c = st.containers.get(&id).expect("resolved"); + (id, c.layers.clone(), c.spec.clone()) }; + let (mounts, flags) = copy_mounts_and_flags(&spec, op, flags); let vm = self.vm()?; let stream = vm.connect(kiri_proto::COPY_PORT)?; let mut out = Vec::new(); - kiri_proto::encode_copy(&mut out, op, &id, path, flags, &layers); + kiri_proto::encode_copy(&mut out, op, &id, path, flags, &layers, &mounts); std::io::Write::write_all(&mut std::fs::File::from(stream.fd.try_clone()?), &out)?; Ok(stream) } @@ -5776,9 +5789,26 @@ fn close_monitor(h: &mut HealthRun) { } } +/// Mounts and flags carried on a guest `Copy` frame. Archive ops (`IN`, `OUT`, +/// `STAT`) carry the container's mounts (with refreshed bind sources) and +/// `READONLY_ROOTFS` for `IN`; `EXPORT`, `DIFF` and `COMMIT` operate on the +/// container's rootfs/layer alone, without mounts. +fn copy_mounts_and_flags(spec: &Spec, op: u8, flags: u32) -> (Vec, u32) { + if !matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT) { + return (Vec::new(), flags); + } + let mounts = super::api::fresh_bind_sources(&spec.mounts, &spec.mount_info); + let flags = if op == kiri_proto::copy_op::IN && spec.readonly_rootfs { + flags | kiri_proto::copy_flags::READONLY_ROOTFS + } else { + flags + }; + (mounts, flags) +} + fn error_text(e: &Error) -> String { match e { - Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) => m.clone(), + Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) | Error::Forbidden(m) => m.clone(), Error::Io(e) => e.to_string(), } } @@ -7356,6 +7386,32 @@ mod start_wait_tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn copy_mounts_and_flags_scope_mounts_and_readonly_rootfs() { + let (engine, id, dir) = engine("copy-mounts"); + let mut s = engine.lock().containers[&id].spec.clone(); + s.mounts = vec![ + "/var/lib/kiri/volumes/pg/_data\t/var/lib/postgresql/data\tcreate,copyup".into(), + "tmpfs\t/tmp\ttmpfs,noexec,nosuid,nodev".into(), + ]; + s.readonly_rootfs = true; + let (mounts, flags) = copy_mounts_and_flags(&s, kiri_proto::copy_op::IN, kiri_proto::copy_flags::CHUNKED); + assert_eq!(mounts, s.mounts); + assert_eq!(flags, kiri_proto::copy_flags::CHUNKED | kiri_proto::copy_flags::READONLY_ROOTFS); + for op in [kiri_proto::copy_op::OUT, kiri_proto::copy_op::STAT] { + let (mounts, flags) = copy_mounts_and_flags(&s, op, 0); + assert_eq!(mounts, s.mounts); + assert_eq!(flags, 0); + } + for op in [kiri_proto::copy_op::EXPORT, kiri_proto::copy_op::DIFF, kiri_proto::copy_op::COMMIT] { + let (mounts, flags) = copy_mounts_and_flags(&s, op, 0); + assert!(mounts.is_empty(), "op {op} must not mount volumes/binds"); + assert_eq!(flags, 0); + } + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + /// The exit of a container whose start waited for its root can be /// reported before the start ends: it is then not made live (the next /// run's early input would go straight to a guest with no process for diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index 1fc1b3fca..a7e7ab8f4 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -394,6 +394,7 @@ fn reason(status: u16) -> &'static str { 204 => "No Content", 304 => "Not Modified", 400 => "Bad Request", + 403 => "Forbidden", 404 => "Not Found", 409 => "Conflict", 413 => "Request Entity Too Large", diff --git a/docs/fix-registry.md b/docs/fix-registry.md index f68d3f12e..613b15344 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 +### #245 Engine: mount volumes and binds for `docker cp` on non-running containers and refuse read-only archive writes (unreleased) +- Fixes: #245 `docker cp` on a created or stopped container ignores named volumes and bind mounts, and `PUT /containers/{id}/archive` does not refuse read-only mounts or `--read-only` rootfs with 403 Forbidden +- Caused: none known +- Caused by: - +- Check: `cp-created-volume-out`, `cp-created-volume-in`, `cp-created-volume-copyup`, `cp-created-bind-mounts`, `cp-created-nested-mounts`, `cp-ro-volume-refused`, `cp-ro-rootfs-refused`, `cp-created-symlink-confined` + ### #515 Host relay: close open proxy connections when the relay stream ends (unreleased) - Fixes: no issue - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index daead30b0..76d6c1d8b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1308,7 +1308,85 @@ code cp-into-missing-dir 1 $D cp "$CPD/a.txt" cpc:/nodir/ $D create --name cpcreated alpine cat /tmp/a.txt >/dev/null t cp-into-created "one" bash -c "$D cp $CPD/a.txt cpcreated:/tmp/ && $D start -a cpcreated" t cp-from-stopped "a.txt" bash -c "$D cp cpcreated:/tmp/a.txt - | tar -t" -$D rm -f cpc cpcreated >/dev/null; rm -rf "$CPD" +# Non-running containers mount their volumes and binds (excluding tmpfs) for +# `docker cp`, populate fresh empty volumes from the image unless `nocopy` is +# set, keep `docker export` rootfs-only, and refuse `PUT /archive` on `:ro` +# mounts and `--read-only` rootfs with 403 (#245). +mkdir -p "$CPD/bdir" "$CPD/outer" "$CPD/inner" +echo host-dir > "$CPD/bdir/fromhost.txt" +echo host-file > "$CPD/bfile.txt" +echo updated-file > "$CPD/updated.txt" +echo ro-orig > "$CPD/rofile.txt" +echo outer-v > "$CPD/outer/outer.txt" +echo inner-v > "$CPD/inner/inner.txt" +echo add-in > "$CPD/add.txt" +tar -C "$CPD" -cf "$CPD/a.tar" a.txt +$D volume rm cpv-pg cpv-new cpv-nocopy cpv-ro cpv-rw cpv-sym >/dev/null 2>&1 || true +$D run --rm -v cpv-pg:/var/lib/postgresql/data alpine sh -c 'echo 17 > /var/lib/postgresql/data/PG_VERSION' >/dev/null +$D create --name cpv-created -v cpv-pg:/var/lib/postgresql/data alpine true >/dev/null +t cp-created-volume-out "17" bash -c "$D cp cpv-created:/var/lib/postgresql/data/PG_VERSION - | tar -xO" +t cp-created-volume-in "one export=0" bash -c "$D cp $CPD/a.txt cpv-created:/var/lib/postgresql/data/staged.conf && echo \"\$($D run --rm -v cpv-pg:/d alpine cat /d/staged.conf) export=\$($D export cpv-created | tar -t | grep -cE 'PG_VERSION|staged.conf')\"" +$D create --name cpv-new-c -v cpv-new:/etc/apk alpine true >/dev/null +$D create --name cpv-nocopy-c -v cpv-nocopy:/etc/apk:nocopy alpine true >/dev/null +t cp-created-volume-copyup "copyup=1 filled=1 nocopy=1" bash -c "c=\$($D cp cpv-new-c:/etc/apk/repositories - | tar -xO | head -n1 | grep -c alpine); f=\$($D run --rm -v cpv-new:/d alpine head -n1 /d/repositories | grep -c alpine); $D cp cpv-nocopy-c:/etc/apk/repositories - >/dev/null 2>&1; n=\$?; echo \"copyup=\$c filled=\$f nocopy=\$n\"" +$D create --name cp-bind-c -v "$CPD/bdir:/mnt/bdir" -v "$CPD/bfile.txt:/mnt/bfile.txt" --tmpfs /etc/apk alpine true >/dev/null +t cp-created-bind-mounts "dir-out=host-dir dir-in=one file-out=host-file file-in=updated-file tmpfs=1" bash -c "do=\$($D cp cp-bind-c:/mnt/bdir/fromhost.txt - | tar -xO); $D cp $CPD/a.txt cp-bind-c:/mnt/bdir/staged.txt && di=\$(cat $CPD/bdir/staged.txt); fo=\$($D cp cp-bind-c:/mnt/bfile.txt - | tar -xO); $D cp $CPD/updated.txt cp-bind-c:/mnt/bfile.txt && fi=\$(cat $CPD/bfile.txt); tf=\$($D cp cp-bind-c:/etc/apk/repositories - | tar -xO | head -n1 | grep -c alpine); echo \"dir-out=\$do dir-in=\$di file-out=\$fo file-in=\$fi tmpfs=\$tf\"" +$D create --name cp-nest-c -v "$CPD/inner:/app/sub" -v "$CPD/outer:/app" alpine true >/dev/null +t cp-created-nested-mounts "outer=outer-v inner=inner-v in=add-in clean=1" bash -c "o=\$($D cp cp-nest-c:/app/outer.txt - | tar -xO); i=\$($D cp cp-nest-c:/app/sub/inner.txt - | tar -xO); $D cp $CPD/add.txt cp-nest-c:/app/sub/add.txt && a=\$(cat $CPD/inner/add.txt); c=\$([ ! -e $CPD/outer/sub/add.txt ] && echo 1 || echo 0); echo \"outer=\$o inner=\$i in=\$a clean=\$c\"" +$D run --rm -v cpv-ro:/d alpine sh -c 'echo keep > /d/keep.txt' >/dev/null +$D create --name cp-ro-c -v cpv-ro:/ro:ro -v "$CPD/rofile.txt:/mnt/rofile.txt:ro" alpine true >/dev/null +$D run -d --name cp-ro-r -v cpv-ro:/ro:ro -v "$CPD/rofile.txt:/mnt/rofile.txt:ro" alpine sleep 120 >/dev/null +t cp-ro-volume-refused "c-vol=403:mounted volume is marked read-only r-vol=403:mounted volume is marked read-only c-file=403:mounted volume is marked read-only r-file=403:mounted volume is marked read-only orig=ro-orig" bash -c " + put() { curl -s -w '\n%{http_code}' --unix-socket $(printf %q "$SOCK") -X PUT --data-binary @\"\$2\" \"http://d/v1.47/containers/\$1/archive?path=\$3\"; } + tar -C $CPD -cf $CPD/rofile.tar rofile.txt + for tag in c:cp-ro-c r:cp-ro-r; do + k=\${tag%%:*}; n=\${tag#*:} + out=\$(put \"\$n\" $CPD/a.tar /ro); code=\${out##*\$'\n'}; body=\${out%\$'\n'*}; msg=\$(printf '%s' \"\$body\" | sed -n 's/.*\"message\":\"\\([^\"]*\\)\".*/\\1/p') + printf '%s-vol=%s:%s ' \"\$k\" \"\$code\" \"\$msg\" + done + for tag in c:cp-ro-c r:cp-ro-r; do + k=\${tag%%:*}; n=\${tag#*:} + out=\$(put \"\$n\" $CPD/rofile.tar /mnt); code=\${out##*\$'\n'}; body=\${out%\$'\n'*}; msg=\$(printf '%s' \"\$body\" | sed -n 's/.*\"message\":\"\\([^\"]*\\)\".*/\\1/p') + printf '%s-file=%s:%s ' \"\$k\" \"\$code\" \"\$msg\" + done + printf 'orig=%s\n' \"\$(cat $CPD/rofile.txt)\" +" +$D create --name cp-roroot-c --read-only -v cpv-rw:/rw alpine true >/dev/null +$D run -d --name cp-roroot-r --read-only -v cpv-rw:/rw alpine sleep 120 >/dev/null +t cp-ro-rootfs-refused "c-root=403:container rootfs is marked read-only r-root=403:container rootfs is marked read-only rw=cp-roroot-c.txt,cp-roroot-r.txt," bash -c " + put() { curl -s -w '\n%{http_code}' --unix-socket $(printf %q "$SOCK") -X PUT --data-binary @$CPD/a.tar \"http://d/v1.47/containers/\$1/archive?path=/tmp\"; } + for tag in c:cp-roroot-c r:cp-roroot-r; do + k=\${tag%%:*}; n=\${tag#*:} + out=\$(put \"\$n\"); code=\${out##*\$'\n'}; body=\${out%\$'\n'*}; msg=\$(printf '%s' \"\$body\" | sed -n 's/.*\"message\":\"\\([^\"]*\\)\".*/\\1/p') + $D cp $CPD/a.txt \"\$n:/rw/\$n.txt\" >/dev/null + printf '%s-root=%s:%s ' \"\$k\" \"\$code\" \"\$msg\" + done + printf 'rw=%s\n' \"\$($D run --rm -v cpv-rw:/d alpine sh -c 'ls /d | sort | tr \"\\n\" ,')\" +" +python3 - "$CPD/sym.tar" <<'PY' +import hashlib, io, json, sys, tarfile +layer = io.BytesIO() +with tarfile.open(fileobj=layer, mode="w", format=tarfile.GNU_FORMAT) as t: + for d in ["etc/", "mnt/"]: + i = tarfile.TarInfo(d); i.type = tarfile.DIRTYPE; i.mode = 0o755; t.addfile(i) + f = tarfile.TarInfo("etc/from-image"); f.size = 8; f.mode = 0o644; t.addfile(f, io.BytesIO(b"in-image")) + s1 = tarfile.TarInfo("mnt/escape-mount"); s1.type = tarfile.SYMTYPE; s1.linkname = "/etc"; t.addfile(s1) + s2 = tarfile.TarInfo("mnt/escape-copy"); s2.type = tarfile.SYMTYPE; s2.linkname = "/etc/from-image"; t.addfile(s2) +lb = layer.getvalue() +cfg = json.dumps({"os":"linux","config":{"Cmd":["/bin/true"]},"rootfs":{"type":"layers","diff_ids":["sha256:"+hashlib.sha256(lb).hexdigest()]}}).encode() +c = hashlib.sha256(cfg).hexdigest() + ".json" +man = json.dumps([{"Config":c,"RepoTags":["kiri-cp-sym:1"],"Layers":["layer.tar"]}]).encode() +with tarfile.open(sys.argv[1], "w") as t: + for n, d in [("layer.tar", lb), (c, cfg), ("manifest.json", man)]: + i = tarfile.TarInfo(n); i.size = len(d); t.addfile(i, io.BytesIO(d)) +PY +$D load -q -i "$CPD/sym.tar" >/dev/null +$D create --name cp-sym-c -v cpv-sym:/mnt/escape-mount kiri-cp-sym:1 >/dev/null +t cp-created-symlink-confined "vol=one img=in-image" bash -c "$D cp $CPD/a.txt cp-sym-c:/mnt/escape-mount/inside.txt && echo \"vol=\$($D run --rm -v cpv-sym:/d alpine cat /d/inside.txt) img=\$($D cp -L cp-sym-c:/mnt/escape-copy - | tar -xO)\"" +$D rm -f cpc cpcreated cpv-created cpv-new-c cpv-nocopy-c cp-bind-c cp-nest-c cp-ro-c cp-ro-r cp-roroot-c cp-roroot-r cp-sym-c >/dev/null 2>&1 +$D rmi kiri-cp-sym:1 >/dev/null 2>&1 || true +$D volume rm cpv-pg cpv-new cpv-nocopy cpv-ro cpv-rw cpv-sym >/dev/null 2>&1 || true +rm -rf "$CPD" section "privileged" t priv-caps "000001ffffffffff" $D run --rm --privileged alpine grep CapEff /proc/self/status diff --git a/tests/regressions.tsv b/tests/regressions.tsv index d5cb3168f..764da86cd 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -260,3 +260,11 @@ limit-memory-swap-refused #523 invalid --memory-swap values on create and update limit-memory-swap-update #523 docker update dropped --memory-swap or failed to keep an existing custom or unlimited swap limit (#690) limit-memory-swap #523 every container with --memory was pinned to memory.swap.max = 0 instead of getting Docker's 2x default or --memory-swap (#690) stats-cpu-throttling #537 container stats always reported zero for cpu_stats.throttling_data even when a CPU-limited container was throttled +cp-created-volume-out #245 GET /containers/{id}/archive (docker cp out) on a created or stopped container opened only the overlay rootfs without mounting named volumes, returning 404 for files in the volume (Supabase CLI PG_VERSION check) +cp-created-volume-in #245 PUT /containers/{id}/archive (docker cp in) on a created or stopped container wrote into the overlay under the mountpoint instead of into the mounted named volume, while docker export must stay rootfs-only +cp-created-volume-copyup #245 docker cp on a created container with a fresh empty named volume did not populate it from the image directory (unless nocopy is set) +cp-created-bind-mounts #245 docker cp out of and into a created or stopped container ignored directory and file bind mounts (while tmpfs mounts must remain unmounted when not running) +cp-created-nested-mounts #245 docker cp on a created or stopped container with nested mounts must apply mounts parent-first regardless of argument order +cp-ro-volume-refused #245 PUT /containers/{id}/archive into a read-only (:ro) volume or bind mount on a running or stopped container must fail with 403 Forbidden and "mounted volume is marked read-only" before writing +cp-ro-rootfs-refused #245 PUT /containers/{id}/archive onto a --read-only container rootfs must fail with 403 Forbidden and "container rootfs is marked read-only" while allowing writes into :rw volumes +cp-created-symlink-confined #245 mount target lookup and docker cp path resolution on a non-running container must confine symlinks inside the container rootfs without escaping onto the host or VM filesystem From 90564368d801745dbc0a5b6cdf90e136bafa82d7 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 22:02:36 +0100 Subject: [PATCH 030/157] Guest kernel: link the arm64 vDSO with both hash tables for macOS 14's Rosetta (#344) --- docs/fix-registry.md | 6 ++++++ .../0007-arm64-vdso-both-hash-tables.patch | 18 ++++++++++++++++++ tests/e2e.sh | 6 ++++++ tests/regressions.tsv | 1 + 4 files changed, 31 insertions(+) create mode 100644 guest/kernel/patches/0007-arm64-vdso-both-hash-tables.patch diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 613b15344..3dfc5db7a 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 +### #344 Guest kernel: link the arm64 vDSO with both hash tables for macOS 14's Rosetta (unreleased) +- Fixes: #344 macOS 14 (Apple silicon): every linux/amd64 container aborts with Rosetta "Failed to find vdso DT_HASH" +- Caused: none known +- Caused by: - +- Check: `rosetta-vdso-dt-hash` + ### #245 Engine: mount volumes and binds for `docker cp` on non-running containers and refuse read-only archive writes (unreleased) - Fixes: #245 `docker cp` on a created or stopped container ignores named volumes and bind mounts, and `PUT /containers/{id}/archive` does not refuse read-only mounts or `--read-only` rootfs with 403 Forbidden - Caused: none known diff --git a/guest/kernel/patches/0007-arm64-vdso-both-hash-tables.patch b/guest/kernel/patches/0007-arm64-vdso-both-hash-tables.patch new file mode 100644 index 000000000..1ad8d38e0 --- /dev/null +++ b/guest/kernel/patches/0007-arm64-vdso-both-hash-tables.patch @@ -0,0 +1,18 @@ +# Header: Linux 6.12 and later dropped --hash-style=sysv from the arm64 vDSO +# link flags, leaving the choice of symbol hash table to the linker. Debian's +# linker emits only DT_GNU_HASH, and Apple's Rosetta for Linux on macOS 14 +# looks up vDSO symbols through DT_HASH ("assertion failed [hash_table != +# nullptr]: Failed to find vdso DT_HASH"), so no linux/amd64 container could +# start there. Link the arm64 vDSO with --hash-style=both, as x86 already +# does, so it carries both DT_HASH and DT_GNU_HASH. +--- a/arch/arm64/kernel/vdso/Makefile ++++ b/arch/arm64/kernel/vdso/Makefile +@@ -21,7 +21,7 @@ + # potential future proofing if we end up with internal calls to the exported + # routines, as x86 does (see 6f121e548f83 ("x86, vdso: Reimplement vdso.so + # preparation in build-time C")). +-ldflags-y := -shared -soname=linux-vdso.so.1 \ ++ldflags-y := -shared -soname=linux-vdso.so.1 --hash-style=both \ + -Bsymbolic --build-id=sha1 -n $(btildflags-y) + + ifdef CONFIG_LD_ORPHAN_WARN diff --git a/tests/e2e.sh b/tests/e2e.sh index 76d6c1d8b..8d3d2216a 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2088,6 +2088,12 @@ needs amd64 t rosetta-node "v22" $D run --rm --platform linux/amd64 node:22-alpi # image here, so on Apple silicon this reads what Rosetta was handed. On a # Linux host the kernel is the host's, not Kiri's. only mac t rosetta-no-auxv-29 "no type 29" $D run --rm alpine sh -c 'od -An -v -tu8 -w16 /proc/self/auxv | awk "\$1 == 29 { n++ } END { print n ? \"type 29 given\" : \"no type 29\" }"' +# Rosetta on macOS 14 looks up arm64 vDSO symbols through DT_HASH ("Failed to +# find vdso DT_HASH", #344): the guest kernel links its vDSO with +# --hash-style=both so PT_DYNAMIC carries both DT_HASH (4) and DT_GNU_HASH +# (0x6ffffef5). python:3.13-alpine is the native image here, so on Apple +# silicon this reads the arm64 vDSO that Rosetta itself is handed. +only mac t rosetta-vdso-dt-hash "DT_HASH+DT_GNU_HASH" $D run --rm python:3.13-alpine python -c 'import ctypes, itertools, struct; libc = ctypes.CDLL(None); libc.getauxval.restype = ctypes.c_ulong; b, rd = libc.getauxval(33), ctypes.string_at; phoff, = struct.unpack_from("/dev/null) # A set-up line, not part of the check: with KIRI_TEST_ONLY the checks after diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 764da86cd..901656fe8 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -268,3 +268,4 @@ cp-created-nested-mounts #245 docker cp on a created or stopped container with n cp-ro-volume-refused #245 PUT /containers/{id}/archive into a read-only (:ro) volume or bind mount on a running or stopped container must fail with 403 Forbidden and "mounted volume is marked read-only" before writing cp-ro-rootfs-refused #245 PUT /containers/{id}/archive onto a --read-only container rootfs must fail with 403 Forbidden and "container rootfs is marked read-only" while allowing writes into :rw volumes cp-created-symlink-confined #245 mount target lookup and docker cp path resolution on a non-running container must confine symlinks inside the container rootfs without escaping onto the host or VM filesystem +rosetta-vdso-dt-hash #344 the arm64 guest kernel vDSO was linked with DT_GNU_HASH only, so macOS 14's Rosetta aborted every linux/amd64 container with "Failed to find vdso DT_HASH" From 16afb4a80d76d71af47aeb4cafa94f51ecba1518 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 22:29:20 +0100 Subject: [PATCH 031/157] Daemon: reclaim unused unpacked VM layers when images or containers go (#722) --- crates/kiri-init/src/linux/agent.rs | 5 +- crates/kiri-init/src/linux/layers.rs | 114 +++++++++- crates/kiri-init/src/linux/roots.rs | 64 ++++-- crates/kiri-proto/src/lib.rs | 4 +- crates/kiri/src/daemon/api.rs | 6 + crates/kiri/src/daemon/builder.rs | 1 + crates/kiri/src/daemon/engine.rs | 306 +++++++++++++++++++++++++-- crates/kiri/src/daemon/ops.rs | 8 +- crates/kiri/src/daemon/vmlink.rs | 9 + docs/fix-registry.md | 6 + tests/e2e.sh | 3 + tests/linux-host.sh | 43 ++++ tests/regressions.tsv | 3 + 13 files changed, 533 insertions(+), 39 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index dfb4abcbf..5d5d90a1f 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -619,7 +619,10 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { - layers::retain(&paths.layers, keep.iter()); + // Any layer currently mounted as a lowerdir of a running + // container or copy job stays until its mount is released. + let mounted = super::roots::in_use_layers(); + layers::retain(&paths.layers, keep.iter().chain(mounted.iter().map(String::as_str))); continue; } Ok(Msg::SetTime(ns)) => { diff --git a/crates/kiri-init/src/linux/layers.rs b/crates/kiri-init/src/linux/layers.rs index 6f63ba513..9160c7179 100644 --- a/crates/kiri-init/src/linux/layers.rs +++ b/crates/kiri-init/src/linux/layers.rs @@ -91,25 +91,91 @@ fn sync_fs(path: &Path) -> io::Result<()> { /// Deletes every layer not in `keep` (blob digests), every layer without /// its marker, and whatever an unpack left half-done. Anything that isn't /// one of those names is left alone. +/// +/// The `.done` marker is removed before the layer directory so a layer +/// stops counting as present immediately, even if deleting its directory is +/// interrupted. pub fn retain<'a>(root: &Path, keep: impl Iterator) { let keep: std::collections::HashSet<&str> = keep.filter_map(|d| hex(d).ok()).collect(); let Ok(entries) = fs::read_dir(root) else { return }; + let mut leftovers = Vec::new(); + let mut seen = std::collections::HashSet::new(); for entry in entries.flatten() { let name = entry.file_name(); let Some(name) = name.to_str() else { continue }; - let leftover = name.starts_with(".tmp-") || name.starts_with(".stale-"); - let (h, is_marker) = match name.strip_suffix(".done") { - Some(h) => (h, true), - None => (name, false), - }; - let layer = h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()); - if !leftover && !layer { + if name.starts_with(".tmp-") || name.starts_with(".stale-") { + leftovers.push(entry.path()); continue; } - let whole = layer && root.join(h).is_dir() && root.join(format!("{h}.done")).is_file(); - if leftover || !keep.contains(h) || !whole { - let path = entry.path(); - let _ = if is_marker || !path.is_dir() { fs::remove_file(&path) } else { fs::remove_dir_all(&path) }; + let h = name.strip_suffix(".done").unwrap_or(name); + if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) { + seen.insert(h.to_owned()); + } + } + for path in leftovers { + remove_entry(&path); + } + for h in seen { + let dir = root.join(&h); + let mark = root.join(format!("{h}.done")); + let whole = dir.is_dir() && mark.is_file(); + if !keep.contains(h.as_str()) || !whole { + // Marker first: once gone, `present()` returns false even if + // removing the directory fails or is cut short. + remove_entry(&mark); + remove_entry(&dir); + } + } +} + +/// Removes a file, symlink or directory tree in the layer store. On +/// `PermissionDenied` inside a layer tree (read-only directories without +/// `CAP_DAC_OVERRIDE`), makes directories writable and retries once. +fn remove_entry(path: &Path) { + let meta = match fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == io::ErrorKind::NotFound => return, + Err(e) => { + eprintln!("kiri-init: stat {}: {e}", path.display()); + return; + } + }; + if !meta.file_type().is_dir() { + if let Err(e) = fs::remove_file(path) + && e.kind() != io::ErrorKind::NotFound + { + eprintln!("kiri-init: remove {}: {e}", path.display()); + } + return; + } + match fs::remove_dir_all(path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => { + make_dirs_writable(path); + if let Err(e) = fs::remove_dir_all(path) + && e.kind() != io::ErrorKind::NotFound + { + eprintln!("kiri-init: remove {}: {e}", path.display()); + } + } + Err(e) => eprintln!("kiri-init: remove {}: {e}", path.display()), + } +} + +/// Grants owner rwx on every real directory under `root` so `remove_dir_all` +/// can unlink entries inside read-only image directories. Symlinks are never +/// followed. +fn make_dirs_writable(root: &Path) { + use std::os::unix::fs::PermissionsExt; + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)); + let Ok(entries) = fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + if entry.file_type().is_ok_and(|t| t.is_dir()) { + stack.push(entry.path()); + } } } } @@ -1489,6 +1555,32 @@ mod tests { let _ = fs::remove_dir_all(&root); } + /// Layers with read-only subdirectories (Go module caches, Nix stores) + /// are still removed along with their `.done` markers, and orphan `.done` + /// markers without a layer directory go too (#722). + #[test] + fn retain_removes_readonly_layer_dirs_and_orphan_markers() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("retain-ro"); + let blob = layer_blob(&[("sub/file", b"hello")]); + send(&root, D1, &blob); + send(&root, D2, &blob); + // Make D2's subdirectory read-only (0555) so plain remove_dir_all + // fails when running without CAP_DAC_OVERRIDE. + let sub = dir(&root, D2).unwrap().join("sub"); + fs::set_permissions(&sub, fs::Permissions::from_mode(0o555)).unwrap(); + // An orphan `.done` marker with no directory beside it. + let orphan = "4".repeat(64); + fs::write(root.join(format!("{orphan}.done")), b"").unwrap(); + + retain(&root, [D1].into_iter()); + assert!(present(&root, D1), "referenced layer stays"); + assert!(!dir(&root, D2).unwrap().exists(), "unreferenced read-only layer dir must go"); + assert!(!marker(&root, D2).unwrap().exists(), "unreferenced layer .done marker must go"); + assert!(!root.join(format!("{orphan}.done")).exists(), "orphan .done marker must go"); + let _ = fs::remove_dir_all(&root); + } + /// Device nodes and fifos come out as such, numbers, owner and mode kept, /// not as the empty files the tar crate would make of them. #[test] diff --git a/crates/kiri-init/src/linux/roots.rs b/crates/kiri-init/src/linux/roots.rs index b91d037c3..02c79d67b 100644 --- a/crates/kiri-init/src/linux/roots.rs +++ b/crates/kiri-init/src/linux/roots.rs @@ -23,6 +23,9 @@ struct Root { /// Removed (`docker rm`, `--rm`) while in use: its files go with the /// last user. remove: bool, + /// Unpacked layer hex digests mounted as lowerdirs for this root, kept + /// safe from live `RetainLayers` until the mount goes away. + layers: Vec, } /// What letting go of a root leaves to do. @@ -37,10 +40,20 @@ struct Table(HashMap); impl Table { /// True when this is the first user, who must mount it. - fn take(&mut self, base: &Path) -> bool { + fn take(&mut self, base: &Path, layers: &[&str]) -> bool { let r = self.0.entry(base.to_owned()).or_default(); r.users += 1; - r.users == 1 + if r.users == 1 { + r.layers = layers.iter().filter_map(|d| super::layers::hex(d).ok().map(str::to_owned)).collect(); + true + } else { + false + } + } + + /// Layer hex digests currently held by any active overlay mount. + fn in_use_layers(&self) -> Vec { + self.0.values().filter(|r| r.users > 0).flat_map(|r| r.layers.iter().cloned()).collect() } /// One more user of a root already mounted; false if it isn't. @@ -98,12 +111,17 @@ thread_local! { pub fn acquire(paths: &Paths, id: &str, layers: &[&str]) -> io::Result { container::valid_id(id)?; let base = paths.containers.join(id); - if !TABLE.with_borrow_mut(|t| t.take(&base)) { + if !TABLE.with_borrow_mut(|t| t.take(&base, layers)) { return Ok(base.join("rootfs")); } container::mount_rootfs(paths, id, layers).inspect_err(|_| TABLE.with_borrow_mut(|t| t.forget(&base))) } +/// Layer hex digests currently held by any active overlay mount. +pub fn in_use_layers() -> Vec { + TABLE.with_borrow(Table::in_use_layers) +} + /// Holds a root that is mounted now (a running container's), for a copy /// into it; an error when it isn't mounted. pub fn hold(paths: &Paths, id: &str) -> io::Result { @@ -157,20 +175,20 @@ mod tests { #[test] fn the_first_user_mounts_and_the_last_unmounts() { let (mut t, a) = (Table::default(), Path::new("/c/a")); - assert!(t.take(a), "the container starts: it mounts"); - assert!(!t.take(a), "a copy meanwhile uses the same mount"); + assert!(t.take(a, &[]), "the container starts: it mounts"); + assert!(!t.take(a, &[]), "a copy meanwhile uses the same mount"); assert_eq!(t.give(a), Some(Left::InUse), "the copy ends: still running"); assert_eq!(t.give(a), Some(Left::Unmount { remove: false }), "the container exits"); assert_eq!(t.give(a), None, "nothing left to let go"); - assert!(t.take(a), "a later start mounts again"); + assert!(t.take(a, &[]), "a later start mounts again"); } #[test] fn a_root_removed_in_use_goes_with_its_last_user() { let (mut t, a) = (Table::default(), Path::new("/c/a")); assert!(t.doom(a), "not in use: removed now"); - t.take(a); - t.take(a); + t.take(a, &[]); + t.take(a, &[]); assert!(!t.doom(a)); assert_eq!(t.give(a), Some(Left::InUse)); assert_eq!(t.give(a), Some(Left::Unmount { remove: true })); @@ -180,10 +198,10 @@ mod tests { fn a_copy_into_a_running_container_keeps_its_root_past_a_restart() { let (mut t, a) = (Table::default(), Path::new("/c/a")); assert!(!t.hold(a), "nothing mounted: nothing to hold"); - t.take(a); + t.take(a, &[]); assert!(t.hold(a)); assert_eq!(t.give(a), Some(Left::InUse), "the container exits: the copy still writes"); - assert!(!t.take(a), "the restart shares it instead of mounting again"); + assert!(!t.take(a, &[]), "the restart shares it instead of mounting again"); assert_eq!(t.give(a), Some(Left::InUse)); assert_eq!(t.give(a), Some(Left::Unmount { remove: false })); } @@ -191,8 +209,30 @@ mod tests { #[test] fn a_failed_mount_is_not_counted() { let (mut t, a) = (Table::default(), Path::new("/c/a")); - assert!(t.take(a)); + assert!(t.take(a, &[])); + t.forget(a); + assert!(t.take(a, &[]), "the next user mounts"); + } + + #[test] + fn in_use_layers_tracks_mounted_roots_until_release() { + let (mut t, a) = (Table::default(), Path::new("/c/a")); + let h1 = "a".repeat(64); + let h2 = "b".repeat(64); + let d1 = format!("sha256:{h1}"); + let d2 = format!("sha256:{h2}"); + assert!(t.in_use_layers().is_empty()); + assert!(t.take(a, &[d1.as_str(), d2.as_str()])); + assert_eq!(t.in_use_layers(), vec![h1.clone(), h2.clone()]); + // A second user (e.g. docker cp) keeps the same layers mounted. + assert!(!t.take(a, &[])); + assert_eq!(t.give(a), Some(Left::InUse)); + assert_eq!(t.in_use_layers(), vec![h1, h2]); + assert_eq!(t.give(a), Some(Left::Unmount { remove: false })); + assert!(t.in_use_layers().is_empty()); + // A failed mount drops its layers too. + assert!(t.take(a, &[d1.as_str()])); t.forget(a); - assert!(t.take(a), "the next user mounts"); + assert!(t.in_use_layers().is_empty()); } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 5357d59fe..eb3fdfafe 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -133,8 +133,8 @@ pub enum Msg<'a> { /// Sent once after connecting. No reply. Retain(StrList<'a>), /// Host → guest: delete every unpacked layer except these (by blob - /// digest), and any left half-written. Sent once after connecting, - /// before anything runs. No reply. + /// digest), and any left half-written. Sent on connect and after images + /// or containers stop referencing layers. No reply. RetainLayers(StrList<'a>), /// Asks how much disk the guest's layers, containers and volumes use. UsageQuery, diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 3a3599008..a155c74fa 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -724,6 +724,7 @@ fn image_remove(engine: &Engine, name: &str, force: bool) -> Result Result<(), Error> let full = format!("{repo}:{tag}"); let name = Reference::parse(&full).map(|r| r.short()).map_err(|e| Error::BadRequest(format!("invalid reference format: {e}")))?; engine.store.put_image(i.tagged(name.clone()))?; + engine.prune_layers(); engine.emit_image("tag", &i.config_digest, &name); Ok(()) } @@ -763,6 +765,7 @@ fn image_load(req: &Request, engine: &Engine, w: &mut UnixStream, r: &mut BufRea }; match loaded { Ok(images) => { + engine.prune_layers(); http::begin_stream_with(w, 200, "application/json", http::CLOSE)?; for i in &images { engine.emit_image("load", &i.config_digest, &i.name); @@ -850,6 +853,7 @@ fn import(req: &Request, engine: &Engine, stdin: &mut dyn io::Read) -> Result { + engine.prune_layers(); // Docker reports the digest it was asked for: the index's, if any. line(json!({"status": format!("Digest: {}", image.index_digest.as_ref().unwrap_or(&image.digest))})); line(json!({"status": format!("Status: Downloaded newer image for {}", image.name)})); @@ -2400,6 +2405,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { } let image = engine.image(image_name)?.ok_or_else(|| Error::NotFound(format!("No such image: {image_name}")))?; + let _layer_pin = engine.pin_layers(image.layers.iter().map(|l| l.digest.as_str())); if let Some(why) = intel_mac_refusal(image_name, std::slice::from_ref(&image.platform)) { return Err(Error::BadRequest(why)); } diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index 3a2721dc7..41bd711ac 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -1027,6 +1027,7 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu let result = run(req, engine, &mut o, r, &mut out, &probe); match result { Ok(images) => { + engine.prune_layers(); let id = images[0].config_digest.clone(); let short: String = id.trim_start_matches("sha256:").chars().take(12).collect(); out.line(json!({"aux": {"ID": id}})); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 16058bc70..b49bbe383 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1184,6 +1184,33 @@ struct State { removed: VecDeque<(String, i32)>, /// `State.Health` of containers with a healthcheck, by id. health: HashMap, + /// Unpacked layer digests pinned by in-flight creates (from image lookup + /// until the container is inserted into `containers`), with refcounts so + /// concurrent `prune_layers` never deletes a layer being unpacked (#722). + pinned_layers: HashMap, +} + +/// Keeps layer digests in `retained_layers` until dropped (see `Engine::pin_layers`). +pub(super) struct LayerPin<'a> { + engine: &'a Engine, + digests: Vec, +} + +impl Drop for LayerPin<'_> { + fn drop(&mut self) { + if self.digests.is_empty() { + return; + } + let mut st = self.engine.lock(); + for d in &self.digests { + if let Some(n) = st.pinned_layers.get_mut(d) { + *n -= 1; + if *n == 0 { + st.pinned_layers.remove(d); + } + } + } + } } /// Set while the daemon shuts down: exits then are not restarts. @@ -1589,18 +1616,8 @@ impl Engine { // the image list can't be read, rather than deleting everything, and // while a damaged copy of it is kept: images cut from the list may // still be someone's (#440). - let image_damage = self.store.index_damage(); - match self.store.images() { - _ if keep.is_none() => {} - _ if !matches!(image_damage, Ok(None)) => { - crate::diag::warn!("kept every unpacked layer: the image list was damaged", detail = image_damage_message(&image_damage, self.store.root()).unwrap_or_default()); - } - Ok(images) => { - let mut layers: std::collections::BTreeSet = images.iter().flat_map(|i| i.layers.iter().map(|l| l.digest.clone())).collect(); - layers.extend(self.lock().containers.values().flat_map(|c| c.layers.iter().cloned())); - vm.retain_layers(&layers.into_iter().collect::>())?; - } - Err(e) => crate::diag::warn!("kept every unpacked layer: images unreadable", error = e), + if let Some(layers) = self.retained_layers() { + vm.retain_layers(&layers)?; } *self.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = ceiling; self.sleeping.store(false, std::sync::atomic::Ordering::SeqCst); @@ -2459,10 +2476,12 @@ impl Engine { }; let mut anon = Vec::new(); let mut removed_log = None; + let mut removed_layers = Vec::new(); if remove { if let Some(c) = st.containers.remove(id) { anon = c.spec.anon_volumes; removed_log = Some(c.log); + removed_layers = c.layers; } note_removed(&mut st, id, code); } @@ -2503,6 +2522,16 @@ impl Engine { } }); } + // If this `--rm` container was the last holder of layers from + // an overwritten image, prune them off the reader thread (#722). + if !removed_layers.is_empty() + && self.has_unlisted_layer(&removed_layers) + && let Some(me) = self.me.get().and_then(Weak::upgrade) + { + let _ = std::thread::Builder::new().name("kiri-layer-gc".into()).spawn(move || { + me.prune_layers(); + }); + } self.changed.notify_all(); if persist { self.save(); @@ -2875,6 +2904,79 @@ impl Engine { Ok(ancestor_ids(&self.store.images()?, values)) } + /// Keeps `digests` in `retained_layers` until the returned guard drops, + /// so a concurrent `prune_layers` cannot delete layers while a container + /// is being created from them (#722). + pub(super) fn pin_layers<'a>(&'a self, digests: impl IntoIterator) -> LayerPin<'a> { + let digests: Vec = digests.into_iter().map(str::to_owned).collect(); + if !digests.is_empty() { + let mut st = self.lock(); + for d in &digests { + *st.pinned_layers.entry(d.clone()).or_insert(0) += 1; + } + } + LayerPin { engine: self, digests } + } + + /// Every layer digest the guest must keep (every image's, every running + /// and stopped container's, and every in-flight create's). `None` when + /// either list is damaged or unreadable: then nothing is deleted (#440). + fn retained_layers(&self) -> Option> { + if self.keeps_everything() { + return None; + } + let image_damage = self.store.index_damage(); + if !matches!(image_damage, Ok(None)) { + crate::diag::warn!( + "kept every unpacked layer: the image list was damaged", + detail = image_damage_message(&image_damage, self.store.root()).unwrap_or_default() + ); + return None; + } + let images = match self.store.images() { + Ok(images) => images, + Err(e) => { + crate::diag::warn!("kept every unpacked layer: images unreadable", error = e); + return None; + } + }; + let mut layers: std::collections::BTreeSet = images + .iter() + .flat_map(|i| i.layers.iter().map(|l| l.digest.clone())) + .collect(); + let st = self.lock(); + layers.extend(st.containers.values().flat_map(|c| c.layers.iter().cloned())); + layers.extend(st.pinned_layers.keys().cloned()); + drop(st); + Some(layers.into_iter().collect()) + } + + /// Whether any digest in `layers` is no longer listed by any image in the + /// store: removing a container that held it may now free the unpacked layer. + fn has_unlisted_layer(&self, layers: &[String]) -> bool { + let Ok(images) = self.store.images() else { return false }; + layers.iter().any(|d| !images.iter().any(|i| i.layers.iter().any(|l| &l.digest == d))) + } + + /// Deletes unpacked layers in the guest that no image, container or + /// in-flight create uses any more (#722). Does not boot a sleeping VM: + /// the next boot runs the same pass (`vm_inner`). Waits for the guest + /// (`ping`), so an immediate `docker system df` or listing of + /// `/var/lib/kiri/layers` sees the space freed. + pub fn prune_layers(&self) { + let Some(vm) = self.awake() else { return }; + if let Err(e) = self.prune_layers_with(|keep| vm.retain_layers(keep).and_then(|()| vm.ping())) { + crate::diag::warn!("unpacked layers left for the next boot", error = e); + } + } + + /// Runs a live `retain_layers` pass serialized with `ensure_layers`. + fn prune_layers_with(&self, send: impl FnOnce(&[String]) -> io::Result<()>) -> io::Result<()> { + let _one_at_a_time = self.layers.lock().unwrap_or_else(|e| e.into_inner()); + let Some(keep) = self.retained_layers() else { return Ok(()) }; + send(&keep) + } + /// Sends the guest every layer of these (digest, media type) it doesn't /// have unpacked, from the blob store. fn ensure_layers<'a>(&self, vm: &VmLink, layers: impl Iterator) -> io::Result<()> { @@ -2918,6 +3020,7 @@ impl Engine { /// Records a container and makes sure its layers are in the guest, so /// `start` has nothing left to do but run it. pub fn create(&self, name: Option, spec: Spec, image: &Image) -> Result { + let _pin = self.pin_layers(image.layers.iter().map(|l| l.digest.as_str())); if !image.layers.is_empty() { let vm = self.vm()?; self.ensure_layers(&vm, image.layers.iter().map(|l| (l.digest.as_str(), l.media_type.as_str())))?; @@ -4780,6 +4883,12 @@ impl Engine { { crate::diag::warn!("writable layer left for the next boot", id = id, error = e); } + if let Some(c) = &removed + && !c.layers.is_empty() + && self.has_unlisted_layer(&c.layers) + { + self.prune_layers(); + } if with_volumes { for v in anon { self.delete_volume_data(&v); @@ -8128,6 +8237,179 @@ mod leave_first_network_tests { } } +#[cfg(test)] +mod layer_gc_tests { + use super::*; + + fn hex_digest(c: &str) -> String { + format!("sha256:{}", c.repeat(64)) + } + + fn test_image(name: &str, cfg: &str, layers: &[&str]) -> Image { + Image { + mirror: None, + name: name.into(), + digest: hex_digest(cfg), + index_digest: None, + config_digest: hex_digest(cfg), + layers: layers + .iter() + .map(|d| kiri_image::Layer { digest: (*d).into(), size: 1024, media_type: "application/vnd.oci.image.layer.v1.tar".into() }) + .collect(), + size: layers.len() as u64 * 1024, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + } + } + + fn insert_container(engine: &Engine, id: &str, image_id: &str, layers: Vec, status: Status) { + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "demo:1", "image_id": image_id, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + })) + .unwrap(); + let mut st = engine.lock(); + st.containers.insert( + id.into(), + Container { + lifecycle: Arc::new(Mutex::new(0)), + names_sync: Arc::default(), + start_gate: Arc::default(), + id: id.into(), + name: format!("c-{id}"), + layers, + spec, + created: SystemTime::now(), + status, + started: None, + 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: 0, + forwards: None, + live: false, + early_input: Vec::new(), + early_close: false, + start_owed: false, + paused: false, + extra_ips: Vec::new(), + extra_ifs: Vec::new(), + ip6: None, + extra_ip6s: Vec::new(), + log: Arc::new(Mutex::new(super::super::logfile::Log::new( + super::super::logfile::dir(engine.store.root(), id), + &Default::default(), + ))), + attached: Vec::new(), + }, + ); + } + + /// Live layer GC keeps layers referenced by remaining images, running + /// containers, stopped containers and in-flight creates, while dropping + /// layers only a removed or overwritten image used (#722). + #[test] + fn retained_layers_keeps_images_containers_and_in_flight_pins() { + let root = std::env::temp_dir().join(format!("kiri-layer-gc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let engine = boot_without_vm(&root); + + let (shared, only_a, only_b, stopped_l, running_l, inflight_l) = + (hex_digest("1"), hex_digest("2"), hex_digest("3"), hex_digest("4"), hex_digest("5"), hex_digest("6")); + engine.store.put_image(test_image("a:1", "a", &[&shared, &only_a])).unwrap(); + engine.store.put_image(test_image("b:1", "b", &[&shared, &only_b])).unwrap(); + insert_container(&engine, "stopped1", &hex_digest("c"), vec![stopped_l.clone()], Status::Exited); + insert_container(&engine, "running1", &hex_digest("d"), vec![running_l.clone()], Status::Running); + + // Removing a:1 drops only_a, while shared stays for b:1 and container layers stay. + engine.store.remove_image("a:1").unwrap(); + let mut sent = Vec::new(); + engine.prune_layers_with(|keep| { + sent = keep.to_vec(); + Ok(()) + }).unwrap(); + let mut want = vec![shared.clone(), only_b.clone(), stopped_l.clone(), running_l.clone()]; + want.sort(); + assert_eq!(sent, want); + + // An in-flight create pins its layers across prune_layers even if the + // image disappears before the container is inserted, and overlapping + // pins are reference-counted. + let p1 = engine.pin_layers([inflight_l.as_str()]); + let p2 = engine.pin_layers([inflight_l.as_str()]); + assert!(engine.retained_layers().unwrap().contains(&inflight_l)); + drop(p1); + assert!(engine.retained_layers().unwrap().contains(&inflight_l), "second pin still holds it"); + drop(p2); + assert!(!engine.retained_layers().unwrap().contains(&inflight_l), "gone once last pin drops"); + + // has_unlisted_layer detects when removing a container frees a layer + // whose image was already overwritten or removed, and stays false for + // layers still in store.images(). + assert!(!engine.has_unlisted_layer(&[shared.clone(), only_b.clone()])); + assert!(engine.has_unlisted_layer(&[shared.clone(), stopped_l.clone()])); + + // Removing the stopped container drops stopped_l from the retained set. + engine.remove("stopped1", false, false).unwrap(); + assert!(!engine.retained_layers().unwrap().contains(&stopped_l)); + assert!(engine.retained_layers().unwrap().contains(&running_l)); + + // Overwriting b:1 drops only_b immediately from the retained set. + let fresh = hex_digest("7"); + engine.store.put_image(test_image("b:1", "e", &[&shared, &fresh])).unwrap(); + let kept = engine.retained_layers().unwrap(); + assert!(!kept.contains(&only_b)); + assert!(kept.contains(&shared) && kept.contains(&fresh) && kept.contains(&running_l)); + + drop(engine); + let _ = std::fs::remove_dir_all(&root); + } + + /// Neither live GC nor boot-time GC deletes any layer while either + /// `containers.json` or `images.json` has a `.corrupt-*` copy (#440, #722). + #[test] + fn prune_layers_skips_when_records_or_images_are_damaged() { + let root = std::env::temp_dir().join(format!("kiri-layer-gc-damaged-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("containers.json.corrupt-1-0"), b"[").unwrap(); + let engine = boot_without_vm(&root); + assert!(engine.retained_layers().is_none(), "damaged containers.json must keep every layer"); + let mut called = false; + engine.prune_layers_with(|_| { + called = true; + Ok(()) + }).unwrap(); + assert!(!called); + drop(engine); + let _ = std::fs::remove_dir_all(&root); + + let root2 = std::env::temp_dir().join(format!("kiri-layer-gc-imgdmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root2); + std::fs::create_dir_all(&root2).unwrap(); + std::fs::write(root2.join("images.json.corrupt-1-0"), b"[").unwrap(); + let engine2 = boot_without_vm(&root2); + assert!(engine2.retained_layers().is_none(), "damaged images.json must keep every layer"); + let mut called2 = false; + engine2.prune_layers_with(|_| { + called2 = true; + Ok(()) + }).unwrap(); + assert!(!called2); + drop(engine2); + let _ = std::fs::remove_dir_all(&root2); + } +} + #[cfg(all(test, target_os = "linux"))] mod cpu_tests { /// The CPUs `Cpus_allowed_list` of /proc/self/status lists. diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index 8e24c23ac..c2c00018f 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -344,6 +344,7 @@ fn commit(req: &Request, engine: &Engine) -> Result { }; let image = kiri_image::archive::from_config(name, &config_digest, &cfg, layers); engine.store.put_image(image)?; + engine.prune_layers(); engine.emit_container("commit", &id, &[]); Ok(json!({"Id": config_digest})) } @@ -400,6 +401,7 @@ fn image_prune(req: &Request, engine: &Engine) -> Result { let until = prune_until(&f, "until")?; let used: Vec = engine.each(|c| Some(c.spec.image_id.clone())); let mut deleted = Vec::new(); + let mut any_deleted = false; let mut reclaimed = 0u64; for i in engine.store.images()? { if used.contains(&i.config_digest) || (dangling_only && !i.name.starts_with("sha256:")) { @@ -418,11 +420,15 @@ fn image_prune(req: &Request, engine: &Engine) -> Result { deleted.push(json!({"Untagged": i.name})); engine.emit_image("untag", &i.config_digest, &i.name); if !engine.store.images()?.iter().any(|o| o.config_digest == i.config_digest) { + any_deleted = true; deleted.push(json!({"Deleted": i.config_digest})); engine.emit_image("delete", &i.config_digest, &i.name); } } } + if any_deleted { + engine.prune_layers(); + } Ok(json!({"ImagesDeleted": if deleted.is_empty() { Value::Null } else { Value::Array(deleted) }, "SpaceReclaimed": reclaimed})) } @@ -475,7 +481,7 @@ fn system_df(engine: &Engine) -> Result { } // Every image layer once, as `layer_size` counts it; with the guest's // numbers, plus the rest of the layer store: layers only stopped - // containers still use, and leftovers the next VM start clears. + // containers still use, and any leftovers the next VM start clears. let mut seen = HashSet::new(); let mut layers_size: u64 = images.iter().flat_map(|i| &i.layers).filter(|l| seen.insert(l.digest.trim_start_matches("sha256:"))).map(layer_size).sum(); if let Some(d) = &du { diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index aed1b48c1..d448cad59 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -625,6 +625,15 @@ impl VmLink { self.send(|o| kiri_proto::encode_retain_layers(o, digests)) } + /// Waits for every earlier no-reply frame (such as `retain_layers`) to + /// finish on the guest: the agent processes frames in order. + pub fn ping(&self) -> io::Result<()> { + match self.call(|o| Msg::Ping(0).encode(o), None)? { + Reply::Pong => Ok(()), + other => Err(io::Error::other(format!("expected Pong, got {other:?}"))), + } + } + pub fn kill(&self, id: &str, signal: u32) -> io::Result<()> { self.send(|o| Msg::Kill { id, signal }.encode(o)) } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 3dfc5db7a..076f77487 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 +### #722 Engine: prune unreferenced unpacked layers immediately on image removal, prune, tag overwrite and container removal (unreleased) +- Fixes: #722 Unpacked layers in `/var/lib/kiri/layers` are not removed when images are removed or pruned, or when Kiri is quit and reopened +- Caused: none known +- Caused by: - +- Check: `layer-gc-rmi-df`, `layer-gc-rmi-disk`, `layer-gc-container-keeps-layer` + ### #344 Guest kernel: link the arm64 vDSO with both hash tables for macOS 14's Rosetta (unreleased) - Fixes: #344 macOS 14 (Apple silicon): every linux/amd64 container aborts with Rosetta "Failed to find vdso DT_HASH" - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 8d3d2216a..d9b79861b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2057,6 +2057,9 @@ t system-df-v "VOLUME NAME" $D system df -v # each hold 20 MiB (it once reported every volume as unknown, every # container as 0 and images at their download size). t system-df-sizes "SIZES-OK" bash -c "$D rm -f e2e-dfc >/dev/null 2>&1; $D volume rm e2e-dfv >/dev/null 2>&1; $D run --rm -v e2e-dfv:/d alpine sh -c 'head -c 20971520 /dev/urandom > /d/f' && $D run --name e2e-dfc alpine sh -c 'head -c 20971520 /dev/urandom > /f' && curl -s --unix-socket $(printf %q "$SOCK") http://kiri/system/df | python3 -c 'import json,sys; d=json.load(sys.stdin); v=[x[\"UsageData\"][\"Size\"] for x in d[\"Volumes\"] if x[\"Name\"]==\"e2e-dfv\"]; c=[x[\"SizeRw\"] for x in d[\"Containers\"] if \"/e2e-dfc\" in x[\"Names\"]]; i=[x for x in d[\"Images\"] if x[\"Size\"]<=0]; print(\"SIZES-OK\" if v and v[0]>=20971520 and c and c[0]>=20971520 and not i and d[\"LayersSize\"]>0 else (v, c, len(i)))'; $D rm -f e2e-dfc >/dev/null; $D volume rm e2e-dfv >/dev/null" +# Removing an image frees its unpacked layers on the guest immediately, +# without restarting Kiri (#722). +t layer-gc-rmi-df "FREED-OK" bash -c "$D rm -f e2e-lgc >/dev/null 2>&1; $D rmi kiri-e2e-lgc:1 >/dev/null 2>&1; $D run --name e2e-lgc alpine sh -c 'head -c 20971520 /dev/urandom > /big.bin' && $D commit e2e-lgc kiri-e2e-lgc:1 >/dev/null && $D rm e2e-lgc >/dev/null && $D run --rm kiri-e2e-lgc:1 true && before=\$(curl -s --unix-socket $(printf %q "$SOCK") http://kiri/system/df | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"LayersSize\"])') && $D rmi kiri-e2e-lgc:1 >/dev/null && after=\$(curl -s --unix-socket $(printf %q "$SOCK") http://kiri/system/df | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"LayersSize\"])') && python3 -c \"b,a=int(\$before),int(\$after); print('FREED-OK' if b-a>=16777216 else (b,a,b-a))\"" t search "alpine" $D search alpine --limit 3 t search-official "[OK]" $D search --filter is-official=true alpine --limit 3 diff --git a/tests/linux-host.sh b/tests/linux-host.sh index ea3b0ae3e..fff4389bb 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -920,6 +920,49 @@ t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"1 t limit-memory-swap "def=268435456:ok custom=201326592:ok zero=134217728:ok unlim=-1:ok none=0:ok upd=335544320:ok cpus=335544320:ok uunlim=-1:ok umem=-1:ok bad=ok:ok:ok" "docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 lhswu >/dev/null 2>&1; sw() { docker exec \"\$1\" sh -c \"[ ! -e /sys/fs/cgroup/memory.swap.max ] && echo ok || { v=\\\$(cat /sys/fs/cgroup/memory.swap.max); [ \\\"\\\$v\\\" = \\\"\$2\\\" ] && echo ok || echo bad:\\\$v; }\"; }; docker run -d --name lhsw0 alpine sleep 60 >/dev/null; docker run -d --name lhsw1 --memory 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw2 --memory 128m --memory-swap 192m alpine sleep 60 >/dev/null; docker run -d --name lhsw3 --memory 128m --memory-swap 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw4 --memory 128m --memory-swap -1 alpine sleep 60 >/dev/null; none=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw0):\$(sw lhsw0 max); def=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); custom=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw2):\$(sw lhsw2 67108864); zero=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw3):\$(sw lhsw3 0); unlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw4):\$(sw lhsw4 max); docker update --memory 512m lhsw1 2>&1 | grep -q 'Memory limit should be smaller than already set memoryswap limit' && b1=ok || b1=bad; docker create --memory-swap 64m alpine true 2>&1 | grep -q 'You should always set the Memory limit' && b2=ok || b2=bad; docker create --memory 128m --memory-swap 64m alpine true 2>&1 | grep -q 'Minimum memoryswap limit' && b3=ok || b3=bad; docker update --memory 192m --memory-swap 320m lhsw1 >/dev/null; upd=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --cpus 1 lhsw1 >/dev/null; cpus=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --memory-swap -1 lhsw1 >/dev/null; uunlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker update --memory 256m lhsw1 >/dev/null; umem=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 >/dev/null 2>&1; echo \"def=\$def custom=\$custom zero=\$zero unlim=\$unlim none=\$none upd=\$upd cpus=\$cpus uunlim=\$uunlim umem=\$umem bad=\$b1:\$b2:\$b3\"" # Container stats carry cgroup CPU throttling counters in Docker units (#537). t stats-cpu-throttling "ok" "docker rm -f lhthr >/dev/null 2>&1; id=\$(docker run -d --name lhthr --cpus 0.1 alpine sh -c 'i=0; while [ \$i -lt 200000 ]; do i=\$((i+1)); done; sleep 10'); out=\$(curl -s --unix-socket /root/.kiri/run/docker.sock \"http://d/v1.47/containers/\$id/stats?stream=false\" | python3 -c 'import json, sys; td = json.load(sys.stdin)[\"cpu_stats\"][\"throttling_data\"]; print(\"ok\" if td[\"periods\"] > 0 and td[\"throttled_periods\"] > 0 and td[\"throttled_time\"] > 0 else td)'); docker rm -f lhthr >/dev/null 2>&1; echo \"\$out\"" +# Removing an image or overwriting a tag reclaims unreferenced unpacked layers +# and their .done markers in /var/lib/kiri/layers immediately, while keeping +# layers still referenced by an existing container until it is removed (#722). +t layer-gc-rmi-disk "DISK-FREED" ' + docker rm -f lh-lgc >/dev/null 2>&1; docker rmi kiri-lh-lgc:1 >/dev/null 2>&1 + docker run --rm alpine true >/dev/null && + base=$(ls /var/lib/kiri/layers | wc -l) && + docker run --name lh-lgc alpine sh -c "head -c 10485760 /dev/urandom > /big.bin" >/dev/null && + docker commit lh-lgc kiri-lh-lgc:1 >/dev/null && + docker rm lh-lgc >/dev/null && + docker run --rm kiri-lh-lgc:1 true && + with_img=$(ls /var/lib/kiri/layers | wc -l) && + df_before=$(curl -s --unix-socket /root/.kiri/run/docker.sock http://kiri/system/df | python3 -c "import json,sys; print(json.load(sys.stdin)[\"LayersSize\"])") && + docker rmi kiri-lh-lgc:1 >/dev/null && + after=$(ls /var/lib/kiri/layers | wc -l) && + df_after=$(curl -s --unix-socket /root/.kiri/run/docker.sock http://kiri/system/df | python3 -c "import json,sys; print(json.load(sys.stdin)[\"LayersSize\"])") && + if [ "$with_img" -gt "$base" ] && [ "$after" -eq "$base" ] && [ $((df_before - df_after)) -ge 8388608 ]; then + echo DISK-FREED + else + echo "base=$base with=$with_img after=$after df_before=$df_before df_after=$df_after" + fi +' +t layer-gc-container-keeps-layer "KEPT-THEN-FREED" ' + docker rm -f lh-lgc-hold lh-lgc-tmp >/dev/null 2>&1; docker rmi kiri-lh-lgc:2 >/dev/null 2>&1 + docker run --rm alpine true >/dev/null && + base=$(ls /var/lib/kiri/layers | wc -l) && + docker run --name lh-lgc-tmp alpine sh -c "echo v1 > /ver" >/dev/null && + docker commit lh-lgc-tmp kiri-lh-lgc:2 >/dev/null && + docker rm lh-lgc-tmp >/dev/null && + docker run --name lh-lgc-hold kiri-lh-lgc:2 cat /ver >/dev/null && + docker run --name lh-lgc-tmp alpine sh -c "echo v2 > /ver" >/dev/null && + docker commit lh-lgc-tmp kiri-lh-lgc:2 >/dev/null && + docker rm lh-lgc-tmp >/dev/null && + kept=$(docker start -a lh-lgc-hold) && + docker rm lh-lgc-hold >/dev/null && + docker rmi kiri-lh-lgc:2 >/dev/null && + after=$(ls /var/lib/kiri/layers | wc -l) && + if [ "$kept" = "v1" ] && [ "$after" -eq "$base" ]; then + echo KEPT-THEN-FREED + else + echo "kept=$kept base=$base after=$after" + fi +' $D rm -f "$N" >/dev/null # An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597), # where the kernel refuses mknod of a device and raising nofile past the diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 901656fe8..143458e53 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -269,3 +269,6 @@ cp-ro-volume-refused #245 PUT /containers/{id}/archive into a read-only (:ro) vo cp-ro-rootfs-refused #245 PUT /containers/{id}/archive onto a --read-only container rootfs must fail with 403 Forbidden and "container rootfs is marked read-only" while allowing writes into :rw volumes cp-created-symlink-confined #245 mount target lookup and docker cp path resolution on a non-running container must confine symlinks inside the container rootfs without escaping onto the host or VM filesystem rosetta-vdso-dt-hash #344 the arm64 guest kernel vDSO was linked with DT_GNU_HASH only, so macOS 14's Rosetta aborted every linux/amd64 container with "Failed to find vdso DT_HASH" +layer-gc-rmi-df #722 removing an image left its unpacked layers in /var/lib/kiri/layers and in docker system df until the next VM boot +layer-gc-rmi-disk #722 docker rmi left the removed image's unpacked layer directory and .done marker on disk in /var/lib/kiri/layers +layer-gc-container-keeps-layer #722 layer GC after overwriting a tag must keep layers still used by an existing container and reclaim them once that container is removed From 89464323a7a7f0ec3813b94fd68583e7ee8486e2 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 22:40:07 +0100 Subject: [PATCH 032/157] Guest kernel: drop cached virtiofs dentries when host files are deleted or replaced (#399) Co-authored-by: Shuvro Roy --- docs/fix-registry.md | 6 + .../0006-fsnotify-events-from-the-host.patch | 110 +++++++++++++++--- tests/bind-recreate.sh | 98 ++++++++++++++++ tests/e2e.sh | 1 + tests/regressions.tsv | 1 + 5 files changed, 198 insertions(+), 18 deletions(-) create mode 100755 tests/bind-recreate.sh diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 076f77487..1e1dc56b2 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 +### #402 Guest kernel: drop stale cached bind-mount file dentries on host change (unreleased) +- Fixes: #399 macOS: bind-mounted files deleted or replaced on the Mac return ENOENT or stale cached contents until Apple's cache timeout +- Caused: none known +- Caused by: - +- Check: `bind-recreate` + ### #722 Engine: prune unreferenced unpacked layers immediately on image removal, prune, tag overwrite and container removal (unreleased) - Fixes: #722 Unpacked layers in `/var/lib/kiri/layers` are not removed when images are removed or pruned, or when Kiri is quit and reopened - Caused: none known diff --git a/guest/kernel/patches/0006-fsnotify-events-from-the-host.patch b/guest/kernel/patches/0006-fsnotify-events-from-the-host.patch index 5b2d73777..c168134fc 100644 --- a/guest/kernel/patches/0006-fsnotify-events-from-the-host.patch +++ b/guest/kernel/patches/0006-fsnotify-events-from-the-host.patch @@ -5,8 +5,11 @@ # which hears of those changes from the Mac, raise the fsnotify events Linux # raises for a local change ("M\t/mnt/mac/…" → IN_MODIFY, C/A/D likewise). # Paths are looked up beneath /mnt/mac only (no symlinks, no other mounts), -# nothing is written and no dentry dropped, and only the VM's agent may -# write (root, in the VM's first mount namespace: not a container). +# nothing is written, and cached non-directory, non-mountpoint dentries are +# dropped so guest lookups see deletes and replacements before Apple's cache +# timeout (walking cached dentries only when nobody watches, with no requests +# to the Mac). Only the VM's agent may write (root, in the VM's first mount +# namespace: not a container). --- a/fs/notify/Makefile +++ b/fs/notify/Makefile @@ -5,3 +5,5 @@ @@ -17,7 +20,7 @@ +obj-$(CONFIG_FSNOTIFY) += kiri_inject.o --- /dev/null +++ b/fs/notify/kiri_inject.c -@@ -0,0 +1,191 @@ +@@ -0,0 +1,262 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * /proc/kiri-fsnotify: changes made outside the VM, raised as fsnotify @@ -35,12 +38,15 @@ + * A PATH's attributes changed (IN_ATTRIB) + * D PATH was deleted (IN_DELETE on its directory, IN_DELETE_SELF) + * -+ * Only events are raised: nothing is written, and no dentry is dropped -+ * (the share caches nothing, so lookups already ask the Mac). PATH is -+ * looked up beneath /mnt/mac only, crossing no symlink and no mount, and -+ * /mnt/mac must be the FUSE (virtiofs) share: a name can't lead anywhere -+ * else in the VM. Only the VM's own agent may write: root, in the VM's -+ * first mount namespace, so a container can't, even as root. ++ * Nothing is written. Cached non-directory, non-mountpoint dentries are ++ * dropped before lookups and events so the guest sees host deletes, ++ * replacements, and attribute changes before Apple's cache timeout; when ++ * nobody is watching, only already-cached dentries are walked (no requests ++ * to the Mac). Directories and mount points are left alone. PATH is looked ++ * up beneath /mnt/mac only, crossing no symlink and no mount, and /mnt/mac ++ * must be the FUSE (virtiofs) share: a name can't lead anywhere else in the ++ * VM. Only the VM's own agent may write: root, in the VM's first mount ++ * namespace, so a container can't, even as root. + */ +#include +#include @@ -60,8 +66,53 @@ +#define KIRI_SHARE "/mnt/mac" +#define KIRI_SCOPED (LOOKUP_BENEATH | LOOKUP_NO_SYMLINKS | LOOKUP_NO_XDEV | LOOKUP_NO_MAGICLINKS) + -+/* The file was deleted outside: tell its directory, and the file's own -+ * watchers if the VM still has its inode. */ ++/* 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) ++{ ++ spin_lock(&dentry->d_lock); ++ if (!d_is_dir(dentry) && !d_mountpoint(dentry) && ++ (!negative_only || d_really_is_negative(dentry))) ++ __d_drop(dentry); ++ spin_unlock(&dentry->d_lock); ++} ++ ++/* Walk `rel` below `root` in the guest dcache only (no filesystem lookups or ++ * revalidations to the Mac) and drop the final dentry if cached. */ ++static void kiri_drop_cached(struct dentry *root, const char *rel, ++ bool negative_only) ++{ ++ struct dentry *cur = dget(root); ++ const char *p = rel; ++ ++ while (*p) { ++ const char *slash = strchr(p, '/'); ++ size_t len = slash ? (size_t)(slash - p) : strlen(p); ++ struct qstr name = QSTR_INIT(p, len); ++ struct dentry *next; ++ ++ next = try_lookup_noperm(&name, cur); ++ dput(cur); ++ if (IS_ERR_OR_NULL(next)) ++ return; ++ if (slash) { ++ if (!d_is_dir(next) || d_mountpoint(next)) { ++ dput(next); ++ return; ++ } ++ cur = next; ++ p = slash + 1; ++ } else { ++ kiri_drop_dentry(next, negative_only); ++ dput(next); ++ return; ++ } ++ } ++ dput(cur); ++} ++ ++/* The file was deleted outside: drop its cached name, tell its directory, ++ * and tell the file's own watchers if the VM still has its inode. */ +static int kiri_deleted(struct path *parent, struct qstr *name) +{ + struct inode *dir = d_inode(parent->dentry); @@ -69,6 +120,8 @@ + + if (IS_ERR(child)) + return PTR_ERR(child); ++ if (child) ++ kiri_drop_dentry(child, false); + if (child && d_really_is_positive(child)) { + struct inode *inode = d_inode(child); + __u32 mask = FS_DELETE; @@ -113,6 +166,17 @@ + err = kiri_deleted(&parent, &name); + goto out; + } ++ if (op == 'M' || op == 'A' || op == 'C') { ++ struct dentry *cached = try_lookup_noperm(&name, parent.dentry); ++ ++ if (!IS_ERR_OR_NULL(cached)) { ++ /* 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'); ++ dput(cached); ++ } ++ } + err = vfs_path_lookup(share->dentry, share->mnt, rel, KIRI_SCOPED, &target); + if (err) + goto out; @@ -169,13 +233,6 @@ + path_put(&share); + return -EXDEV; + } -+ /* Without a watcher there is no one to tell, and a batch costs no -+ * lookups (a container writing many files to a bind mount sends its -+ * own changes back). */ -+ if (!fsnotify_sb_has_watchers(share.dentry->d_sb)) { -+ path_put(&share); -+ return count; -+ } + buf = memdup_user_nul(ubuf, count); + if (IS_ERR(buf)) { + path_put(&share); @@ -191,6 +248,23 @@ + err = -EINVAL; + continue; + } ++ /* Without a watcher there is no one to tell: walk cached ++ * dentries only so a batch costs no requests to the Mac. */ ++ 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); ++ break; ++ case 'C': ++ kiri_drop_cached(share.dentry, rel, true); ++ break; ++ default: ++ err = -EINVAL; ++ } ++ continue; ++ } + err = kiri_event(&share, line[0], rel); + } + kfree(buf); diff --git a/tests/bind-recreate.sh b/tests/bind-recreate.sh new file mode 100755 index 000000000..671363fa4 --- /dev/null +++ b/tests/bind-recreate.sh @@ -0,0 +1,98 @@ +#!/bin/bash +# A name cached by virtiofs must be reusable and show its new length and +# contents after the Mac deletes or replaces the file (#399), with and +# without an inotify watcher: +# DOCKER_CONTEXT=kiri tests/bind-recreate.sh +set -eu + +D=${D:-docker} +bind=$(mktemp -d) +bind=$(cd "$bind" && pwd -P) +container="kiri-bind-recreate-$$" +cleanup() { + $D rm -f "$container" >/dev/null 2>&1 || true + rm -rf "$bind" +} +trap cleanup EXIT +trap 'exit 1' INT TERM HUP ALRM +failed=0 +cat > "$bind/onchange.sh" <<'SH' +#!/bin/sh +cat "$2/$3" > "/tmp/seen-$3" 2>&1 +SH +chmod +x "$bind/onchange.sh" + +for watched in no yes; do + if [ "$watched" = yes ]; then + # Watch both modify (c, raised by /proc/kiri-fsnotify on macOS) and + # moved-to (y, raised by mv onto a file on Linux and WSL). + $D run -d --name "$container" -v "$bind:/w" alpine inotifyd /w/onchange.sh /w:cy >/dev/null + else + $D run -d --name "$container" -v "$bind:/w" alpine sleep 60 >/dev/null + fi + # The daemon scans for new bind sources once a second. Let FSEvents + # subscribe before testing changes, so this tests the guest's cache. + sleep 2 + for change in guest-create host-replace host-recreate; do + for i in 1 2 3 4 5; do + file="$watched-$change-$i" + # Alternate shorter->longer and longer->shorter replacements so a + # stale cached file size shows up as a truncated or trailing read, + # not only as ENOENT. + if [ $((i % 2)) -eq 1 ]; then + before="old" + after="three-much-longer" + else + before="three-much-longer" + after="xy" + fi + echo "$before" > "$bind/$file" + $D exec "$container" cat "/w/$file" >/dev/null + if [ "$watched" = yes ]; then + $D exec "$container" sh -c ' + for attempt in 1 2 3 4 5 6 7 8 9 10; do + [ -f "/tmp/seen-$1" ] && break + sleep 0.05 + done + rm -f "/tmp/seen-$1"' sh "$file" + fi + case "$change" in + guest-create) rm "$bind/$file" ;; + host-replace) echo "$after" > "$bind/tmp"; mv "$bind/tmp" "$bind/$file" ;; + host-recreate) rm "$bind/$file"; echo "$after" > "$bind/$file" ;; + esac + # FSEvents batches changes for 50 ms. Allow delivery, but stay well + # inside Apple's roughly one-second positive-entry cache timeout. + sleep 0.2 + if [ "$change" = guest-create ] && + ! $D exec "$container" sh -c 'printf "%s\n" "$2" > "/w/$1"' sh "$file" "$after"; then + echo "FAIL $change (watcher: $watched, file: $file)" >&2 + failed=1 + continue + fi + # The watcher's first read after the event must already see the + # replacement, before the explicit read below can refresh its name. + if [ "$watched" = yes ]; then + if ! content=$($D exec "$container" sh -c ' + for attempt in 1 2 3 4 5 6 7 8 9 10; do + if [ -f "/tmp/seen-$1" ]; then cat "/tmp/seen-$1"; exit; fi + sleep 0.02 + done + exit 1' sh "$file") || [ "$content" != "$after" ]; then + echo "FAIL watcher read after $change (file: $file): got ${content:-no event}, want $after" >&2 + failed=1 + fi + fi + if ! content=$($D exec "$container" cat "/w/$file") || + [ "$content" != "$after" ] || [ "$(cat "$bind/$file" 2>/dev/null)" != "$after" ]; then + echo "FAIL $change (watcher: $watched, file: $file): got ${content:-err}, want $after" >&2 + failed=1 + fi + done + done + $D rm -f "$container" >/dev/null +done +if [ "$failed" = 0 ]; then + echo "PASS bind recreate and replace, with and without a watcher (30 attempts)" +fi +exit "$failed" diff --git a/tests/e2e.sh b/tests/e2e.sh index d9b79861b..1152edd4c 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1042,6 +1042,7 @@ code bind-mount-missing 125 $D run --rm --mount type=bind,source=/kiri/does/not/ # host the daemon's umask (0027) must not shut out the user whose mount it is. t bind-v-creates "made 755 755" bash -c "$D run --rm -v $BIND/new/dir:/n alpine true && [ -d $BIND/new/dir ] && perl -e 'print q(made); printf q( %o), (stat)[2] & 07777 for @ARGV' $BIND/new $BIND/new/dir" t bind-file "from the mac" $D run --rm -v "$BIND/hello.txt:/etc/greeting" alpine cat /etc/greeting +code bind-recreate 0 env D="$D" bash "$(dirname "$0")/bind-recreate.sh" # Docker Desktop's SSH agent mount path (/run/host-services/ssh-auth.sock) works # through -v and --mount for non-root container users too, while inspect shows # the path asked for (#420). diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 143458e53..893be08c1 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -272,3 +272,4 @@ rosetta-vdso-dt-hash #344 the arm64 guest kernel vDSO was linked with DT_GNU_HAS layer-gc-rmi-df #722 removing an image left its unpacked layers in /var/lib/kiri/layers and in docker system df until the next VM boot layer-gc-rmi-disk #722 docker rmi left the removed image's unpacked layer directory and .done marker on disk in /var/lib/kiri/layers layer-gc-container-keeps-layer #722 layer GC after overwriting a tag must keep layers still used by an existing container and reclaim them once that container is removed +bind-recreate #402 deleting or replacing a bind-mounted file on the Mac left a stale guest dentry until Apple's cache timeout, causing ENOENT or truncated reads (#399) From 8bfc1a4e1d12c57561cc0349bd8e6ccbc6490ebf Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Mon, 23 Nov 2026 22:59:18 +0100 Subject: [PATCH 033/157] Mac: reach loopback-published ports and Kiri's resolver from --network host (#732) Co-authored-by: Masih Moloodian --- crates/kiri-init/src/linux/agent.rs | 30 ++++++- crates/kiri-init/src/linux/container.rs | 84 ++++++++++++++++- crates/kiri-init/src/linux/net.rs | 114 ++++++++++++++++++++++-- crates/kiri-init/src/linux/netlink.rs | 67 +++++++++++++- crates/kiri-init/src/linux/relay.rs | 40 +++++++-- crates/kiri/src/daemon/engine.rs | 7 +- crates/kiri/src/daemon/ports.rs | 53 ++++++++++- docs/fix-registry.md | 6 ++ tests/e2e.sh | 17 ++++ tests/regressions.tsv | 3 + 10 files changed, 401 insertions(+), 20 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 5d5d90a1f..7d915a9f9 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -314,7 +314,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap match { // A container that wants the network must not start before the // VM has it: right after boot the DHCP lease can be a few - // hundred milliseconds away. - if spec.flags & (kiri_proto::run_flags::NET_NONE | kiri_proto::run_flags::NET_HOST) == 0 { + // hundred milliseconds away. Only `--network none` skips it; + // `--network host` shares the VM's network and needs the lease + // too (on a Linux host `dhcp` is None so this is a no-op). + if needs_lease(spec.flags) { wait_for_lease(&mut dhcp, std::time::Duration::from_secs(3)); } // Only its network namespace is joined, which exists from @@ -827,6 +829,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap bool { + flags & kiri_proto::run_flags::NET_NONE == 0 +} + /// Runs the DHCP client alone until it has a lease or `max` passes. fn wait_for_lease(dhcp: &mut Option, max: std::time::Duration) { let Some(d) = dhcp.as_mut() else { return }; @@ -1614,6 +1623,21 @@ mod running_tests { assert_ne!(unsafe { libc::kill(pid, 0) }, 0, "killed and reaped once its root was in place"); let _ = child.try_wait(); } + + #[test] + fn wait_for_lease_runs_for_bridged_and_host_but_not_none() { + use kiri_proto::run_flags; + assert!(super::needs_lease(0), "default bridge needs a lease"); + assert!(super::needs_lease(run_flags::NET_HOST), "host network in the VM shares eth0 and needs a lease"); + assert!(super::needs_lease(run_flags::NET_HOST | run_flags::REMOVE)); + assert!(!super::needs_lease(run_flags::NET_NONE), "--network none skips waiting for a lease"); + assert!(!super::needs_lease(run_flags::NET_NONE | run_flags::REMOVE)); + // On a Linux host there is no DHCP client; wait_for_lease is an immediate no-op. + let mut none = None; + let t = std::time::Instant::now(); + super::wait_for_lease(&mut none, std::time::Duration::from_secs(3)); + assert!(t.elapsed() < std::time::Duration::from_secs(1)); + } } #[cfg(test)] diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 46fc88476..329d5d469 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -565,7 +565,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, upstream: &[[u8; 4]], relay: bool) -> bool { embedded_dns_if(spec, || relay || net::local_resolver(upstream)) } +/// In the VM, a `--network host` container's resolver: the agent's on the +/// default bridge's gateway, which is one of the VM's own addresses, so the +/// container reaches it. As the default bridge's containers do, its +/// lookups then go through the Mac when the Mac's resolver for the VM +/// network doesn't answer (dns.rs), where asking that resolver directly +/// would just fail. Not on a Linux host (the container has the host's own +/// resolv.conf), nor with `--dns`. On a fresh VM before any bridged +/// container has started, `kiri0` is brought up on demand with the default +/// bridge's gateway and prefix. None, the VM's upstream as before, when +/// the bridge can't be brought up or the agent can't listen there. +fn host_network_resolver(spec: &RunSpec<'_>, bridges: &mut net::Bridges, dns: &mut super::dns::Dns) -> Option<[u8; 4]> { + if !host_network_uses_agent(spec, dns.relay) { + return None; + } + let gateway = match net::bridge_ipv4(DEFAULT_BRIDGE) { + Some(gw) => gw, + None => { + let (gw, prefix) = host_bridge_addr(spec); + if let Err(e) = bridges.ensure(DEFAULT_BRIDGE, Some(gw), prefix, None) { + eprintln!("kiri-init: dns: cannot bring up {DEFAULT_BRIDGE} for host-network DNS: {e}"); + return None; + } + gw + } + }; + dns.serve_or_warn(DEFAULT_BRIDGE, gateway).then_some(gateway) +} + +/// The default bridge, where the agent's resolver answers on the gateway. +const DEFAULT_BRIDGE: &str = "kiri0"; +const DEFAULT_BRIDGE_GATEWAY: [u8; 4] = [172, 17, 0, 1]; +const DEFAULT_BRIDGE_PREFIX: u8 = 16; + +/// Gateway and prefix for bringing up `DEFAULT_BRIDGE` when a `--network host` +/// container starts before any bridged one: what the daemon sent on `spec.net` +/// when present, falling back to Docker's default 172.17.0.1/16. +fn host_bridge_addr(spec: &RunSpec<'_>) -> ([u8; 4], u8) { + if spec.net.gateway == [0; 4] { + (DEFAULT_BRIDGE_GATEWAY, DEFAULT_BRIDGE_PREFIX) + } else { + let prefix = if spec.net.prefix == 0 { DEFAULT_BRIDGE_PREFIX } else { spec.net.prefix }; + (spec.net.gateway, prefix) + } +} + +/// Whether a container's lookups go to the agent's resolver on the default +/// bridge because it shares the VM's own network (see `host_network_resolver`). +fn host_network_uses_agent(spec: &RunSpec<'_>, relay: bool) -> bool { + relay && spec.flags & run_flags::NET_HOST != 0 && net_opts::values(spec.net.opts, net_opts::NAMESERVER).next().is_none() +} + /// `embedded_dns`, with `through_agent` saying whether the default bridge's /// lookups go through the agent (asked only when it matters). fn embedded_dns_if(spec: &RunSpec<'_>, through_agent: impl FnOnce() -> bool) -> bool { @@ -3655,7 +3706,14 @@ mod tests { let gateway = [[192, 168, 64, 1]]; spec_with(0, &[], &|s| assert!(super::embedded_dns(s, &gateway, true), "so a refused gateway can fall back to the host")); spec_with(0, &["nameserver=8.8.8.8"], &|s| assert!(!super::embedded_dns(s, &gateway, true), "--dns servers are asked directly")); - spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking keeps the VM's resolv.conf")); + spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking has no embedded DNS of its own")); + // In the VM a host-network container asks the agent on the default + // bridge's gateway, so a refused gateway resolver falls back to the + // Mac too (#732); not with --dns, nor on a Linux host (no relay). + spec_with(run_flags::NET_HOST, &[], &|s| assert!(super::host_network_uses_agent(s, true))); + spec_with(run_flags::NET_HOST, &["nameserver=8.8.8.8"], &|s| assert!(!super::host_network_uses_agent(s, true), "--dns servers are asked directly")); + spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::host_network_uses_agent(s, false), "a Linux host keeps its own resolv.conf")); + spec_with(0, &[], &|s| assert!(!super::host_network_uses_agent(s, true), "a bridged container has its own")); // Named by the bridge's gateway, not 127.0.0.11: builders keep it // for their steps rather than swapping in 8.8.8.8. spec_with(0, &[], &|s| assert_eq!(super::embedded_address(s), [172, 17, 0, 1])); @@ -3664,6 +3722,28 @@ mod tests { spec_with(run_flags::DNS_GATEWAY, &[], &|s| assert_eq!(super::embedded_address(s), super::super::dns::EMBEDDED)); } + #[test] + fn host_network_resolver_picks_bridge_gateway_or_default() { + let check = |gateway: [u8; 4], prefix: u8, opts: &[&str], f: &mut dyn FnMut(&kiri_proto::RunSpec<'_>)| { + let mut buf = Vec::new(); + let net = Net { bridge: "", ip: [0; 4], prefix, gateway, extra_hosts: &[], dns_names: &[], opts }; + encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", run_flags::NET_HOST, net, &[], &Limits::default(), 0, &[] as &[&str], &[]); + let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() }; + f(&spec); + }; + check([172, 18, 0, 1], 24, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 24))); + check([0; 4], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 17, 0, 1], 16), "standalone caller falls back to 172.17.0.1/16")); + check([172, 18, 0, 1], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 16), "zero prefix falls back to /16")); + + let mut bridges = super::net::Bridges::default(); + let mut dns = super::super::dns::Dns::default(); + check([172, 17, 0, 1], 16, &[], &mut |s| assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "no relay on a Linux host")); + dns.relay = true; + check([172, 17, 0, 1], 16, &["nameserver=8.8.8.8"], &mut |s| { + assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "--dns bypasses agent resolver"); + }); + } + /// WSL 2: the host's resolver is 10.255.255.254, an address on `lo`. /// The default bridge's lookups go through the agent, which the /// container finds at the bridge's gateway, as in the VM: a loopback diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 16909a694..6cef17f03 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -316,6 +316,34 @@ pub fn local_resolver_among(servers: &[[u8; 4]], local: &[[u8; 4]]) -> bool { servers.iter().any(|s| local.contains(s)) } +/// The IPv4 address of interface `name`, if it has one: a bridge's gateway. +pub fn bridge_ipv4(name: &str) -> Option<[u8; 4]> { + if name.is_empty() || name.len() >= libc::IFNAMSIZ || name.contains('\0') { + return None; + } + let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) }; + if fd < 0 { + return None; + } + // SAFETY: all-zero is a valid `ifreq`; `ifr_name` gets an ASCII name shorter than IFNAMSIZ. + let mut ifr: libc::ifreq = unsafe { std::mem::zeroed() }; + for (dst, &src) in ifr.ifr_name.iter_mut().zip(name.as_bytes()) { + *dst = src as libc::c_char; + } + // SAFETY: `SIOCGIFADDR` fills `ifr_ifru.ifru_addr` with an `AF_INET` `sockaddr` for `ifr_name`. + let rc = unsafe { libc::ioctl(fd, libc::SIOCGIFADDR as _, &mut ifr) }; + unsafe { libc::close(fd) }; + if rc != 0 { + return None; + } + // SAFETY: `SIOCGIFADDR` initialized `ifru_addr`; in `sockaddr_in`, `sa_data[2..6]` is `sin_addr`. + let addr = unsafe { ifr.ifr_ifru.ifru_addr }; + (i32::from(addr.sa_family) == libc::AF_INET).then(|| { + let d = addr.sa_data; + [d[2] as u8, d[3] as u8, d[4] as u8, d[5] as u8] + }) +} + /// This machine's IPv4 addresses but loopback, what `fib daddr type local` /// matches. fn local_addrs() -> Vec<[u8; 4]> { @@ -583,21 +611,50 @@ pub struct Bridges { made: HashMap, u8, Bridge6)>, } +/// What `Bridges::ensure` needs to do for a bridge given its cached state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BridgePlan { + /// Already up with everything asked for. + Reuse(i32), + /// Already up with the same IPv4 gateway/prefix; add IPv6 in place so + /// existing sockets and containers on the bridge are not disrupted. + AddV6(i32), + /// A different subnet took the bridge name: tear down and recreate. + Recreate, + /// Not created yet. + Create, +} + impl Bridges { + fn plan(&self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, want6: Bridge6) -> BridgePlan { + match self.made.get(name) { + Some(&(i, g, p, b6)) if (g, p) == (gateway, prefix) => match (b6, want6) { + (None, None) => BridgePlan::Reuse(i), + (None, Some(_)) => BridgePlan::AddV6(i), + // Already has IPv6 (e.g. a later container with IPv6 disabled, + // or a host-network caller that only needs IPv4): keep it. + (Some(_), None) => BridgePlan::Reuse(i), + (Some(a), Some(b)) if a == b => BridgePlan::Reuse(i), + (Some(_), Some(_)) => BridgePlan::Recreate, + }, + Some(_) => BridgePlan::Recreate, + None => BridgePlan::Create, + } + } + /// Creates the bridge (once) with its gateway address (and IPv6 one) /// and brings it up, with its rules in Kiri's tables. All or nothing: on /// an error the bridge is gone again and not recorded, so the next /// container tries afresh rather than starting with half the rules. pub fn ensure(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option) -> io::Result { let want6 = v6.map(|v| (v.gateway, v.prefix)); - match self.made.get(name) { - Some(&(i, g, p, b6)) if (g, p, b6) == (gateway, prefix, want6) => return Ok(i), + match self.plan(name, gateway, prefix, want6) { + BridgePlan::Reuse(i) => return Ok(i), + BridgePlan::AddV6(i) => return self.add_v6(name, i, gateway, prefix, v6.expect("AddV6 requires v6")), // The network was removed and its bridge name reused for one // with another subnet: start the bridge afresh. - Some(_) => { - self.remove(name); - } - None => {} + BridgePlan::Recreate => self.remove(name), + BridgePlan::Create => {} } let r = self.bring_up(name, gateway, prefix, v6); if r.is_err() { @@ -614,6 +671,17 @@ impl Bridges { r } + fn add_v6(&mut self, name: &str, index: i32, gateway: Option<[u8; 4]>, prefix: u8, v: Ip6) -> io::Result { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + netlink::add_address6(&mut nl, index, v.gateway, v.prefix)?; + self.made.insert(name.to_owned(), (index, gateway, prefix, Some((v.gateway, v.prefix)))); + if let Err(e) = self.update_v6(Some(v)) { + self.made.insert(name.to_owned(), (index, gateway, prefix, None)); + return Err(e); + } + Ok(index) + } + fn bring_up(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option) -> io::Result { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; netlink::create_bridge(&mut nl, name)?; @@ -934,4 +1002,38 @@ fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 000000 hand_over_default_routes(-1, &mut ups, "a").unwrap(); assert!(ups.is_empty()); } + + #[test] + fn bridge_ipv4_reads_an_interfaces_address() { + assert_eq!(bridge_ipv4("lo"), Some([127, 0, 0, 1])); + assert_eq!(bridge_ipv4("kiri-no-such-if"), None); + } + + #[test] + fn bridges_ensure_is_idempotent_and_adds_ipv6_in_place() { + let gw4 = [172, 17, 0, 1]; + let gw6 = [0xfd, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]; + let other6 = [0xfd, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1]; + let v6 = Ip6 { ip: gw6, prefix: 64, gateway: gw6 }; + + let mut bridges = Bridges::default(); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, None), BridgePlan::Create); + + // Once kiri0 is brought up IPv4-only (e.g. by host-network DNS on a fresh VM), + // a repeat ensure reuses it without touching netlink, and a later IPv6 attach + // upgrades it in place rather than tearing it down. + bridges.made.insert("kiri0".into(), (42, Some(gw4), 16, None)); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, None).unwrap(), 42); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, Some((gw6, 64))), BridgePlan::AddV6(42)); + assert_eq!(bridges.plan("kiri0", Some([172, 18, 0, 1]), 16, None), BridgePlan::Recreate); + assert_eq!(bridges.plan("kiri0", Some(gw4), 24, None), BridgePlan::Recreate); + assert_eq!(bridges.plan("kiri0", None, 16, Some((gw6, 64))), BridgePlan::Recreate); + + // Once IPv6 is configured on kiri0, both matching IPv6 callers and IPv4-only + // callers reuse the existing bridge; a different IPv6 subnet recreates it. + bridges.made.insert("kiri0".into(), (42, Some(gw4), 16, Some((gw6, 64)))); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, Some(v6)).unwrap(), 42); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, None).unwrap(), 42); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, Some((other6, 64))), BridgePlan::Recreate); + } } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 1dd81942b..4d812f67f 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -1168,15 +1168,57 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r msgs.extend(localnet_guard()); msgs.push(host_relay_guard(host_port)); for d in dnat.iter().filter(|d| !d.udp) { - msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)))); + if d.host_ip == LOOPBACK { + // A port the Mac has on its loopback, for the VM's own + // connections (`--network host` containers) to 127.0.0.1. + // Skip `host_port` itself: redirecting to the same port does not + // mark `ct status dnat`, so `host_relay_guard` and `redirected_from` + // reject direct connections to the relay listener. + if d.host_port != host_port { + msgs.push(loopback_published_rule(d.host_port, host_port)); + } + } else { + msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)))); + } } - if dnat.iter().any(|d| !d.udp) { + if dnat.iter().any(|d| !d.udp && d.host_ip != LOOPBACK) { msgs.push(published_masq_rule(uplink_index, gateway)); } msgs.push(end); nl.request(&mut msgs) } +/// A published port's `host_ip` in the VM that means "the Mac's loopback": +/// the VM's own connections to 127.0.0.1 on it reach the Mac's 127.0.0.1. +pub const LOOPBACK: [u8; 4] = [127, 0, 0, 1]; + +/// `ip daddr 127.0.0.1 tcp dport redirect to :`, in output: +/// in the VM, a connection the VM itself makes (a `--network host` +/// container) to a port published on the Mac's loopback goes to the host +/// relay, which dials the Mac's 127.0.0.1 on that port, where Kiri's own +/// listener forwards it to the container. As on Docker, where the +/// published port is bound in the host's own network namespace. The +/// redirect stays on the loopback, so `route_localnet` stays off. +fn loopback_published_rule(port: u16, relay: u16) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, "output"); + rule.nest(4); + // meta l4proto => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload daddr => reg 1; cmp eq 127.0.0.1 + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &LOOPBACK).end().end().end(); + // payload transport header + 2 (dport) => reg 1; cmp eq port + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 2).attr_be32(4, 2).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &port.to_be_bytes()).end().end().end(); + // immediate reg 1 = relay; redir to it + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &relay.to_be_bytes()).end().end().end(); + rule.nest(1).attr_str(1, "redir").nest(2).attr_be32(1, 1).end().end(); + rule.end(); + rule +} + #[cfg(test)] mod tests { use super::*; @@ -1372,9 +1414,30 @@ mod tests { assert!(f.iter().all(|m| m.buf[16] == libc::NFPROTO_IPV6 as u8)); } + /// In the VM, a port published on the Mac's loopback: the VM's own TCP + /// connections to 127.0.0.1 on it, in output, go to the host relay. + #[test] + fn a_loopback_published_port_redirects_the_vms_own_connections_to_the_relay() { + let r = loopback_published_rule(5999, 1026); + let top = attrs(&r.buf[20..]); + assert_eq!(get(&top, 2), b"output\0", "the VM's own connections only, not the bridges'"); + assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"]); + let e = exprs(&r); + assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // network header + 16, 4 bytes: daddr, which must be 127.0.0.1 + assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (1, 16, 4)); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &LOOPBACK); + // transport header + 2, 2 bytes: dport + assert_eq!((be32(get(&e[4].1, 2)), be32(get(&e[4].1, 3)), be32(get(&e[4].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e[5].1, 3)), 1), &5999u16.to_be_bytes()); + assert_eq!(get(&attrs(get(&e[6].1, 2)), 1), &1026u16.to_be_bytes(), "redirected to the relay's port"); + } + #[test] fn host_relay_takes_only_redirected_connections() { let r = host_relay_guard(1026); + let top = attrs(&r.buf[20..]); + assert_eq!(get(&top, 2), b"input\0", "guards every incoming interface, loopback included"); assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "ct", "bitwise", "cmp", "immediate"]); let e = exprs(&r); assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index c03271b89..0888ebdc3 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -369,9 +369,12 @@ pub const HOST_VSOCK_PORT: u32 = 1026; /// Accepts one redirected connection, finds the port the container meant, /// dials the Mac and returns a relay between the two. Only connections that -/// were redirected from `host_addr` are relayed: one made to the listener -/// directly (from the LAN, on a Linux host) would reach the host's loopback. -pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4]) -> Option { +/// were redirected from `host_addr`, or from 127.0.0.1 on another port (a +/// port published on the Mac's loopback, which only the VM's own output +/// chain redirects), are relayed: one made to the listener directly (from +/// the LAN, or from a `--network host` container dialling `127.0.0.1:relay_port`) +/// would reach the host's loopback. +pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4], relay_port: u16) -> Option { // SAFETY: accept4 on a listening socket we own; the fd is owned immediately. let fd = unsafe { libc::accept4(listener.as_raw_fd(), std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; if fd < 0 { @@ -387,10 +390,11 @@ pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4]) -> Option Option bool { + dst == host_addr || (dst == super::netlink::LOOPBACK && dst_port != relay_port) +} + fn dial_host(port: u32) -> io::Result { super::transport::dial(port) } @@ -581,6 +594,23 @@ pub fn accept_engine(listener: &OwnedFd) -> Option { mod tests { use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + /// The host relay takes connections redirected from the host's address + /// and from the VM's loopback on another port (published ports), never + /// direct connections to the relay's own port or other addresses. + #[test] + fn the_host_relay_takes_the_host_address_and_loopback() { + let host = [198, 19, 248, 254]; + let relay = 1026; + assert!(super::redirected_from(host, 8080, host, relay)); + assert!(super::redirected_from(host, relay, host, relay)); + assert!(super::redirected_from([127, 0, 0, 1], 5999, host, relay)); + assert!(!super::redirected_from([127, 0, 0, 1], relay, host, relay), "direct loopback connection to the relay"); + for other in [[192, 168, 64, 2], [172, 17, 0, 1], [127, 0, 0, 2], [0, 0, 0, 0]] { + assert!(!super::redirected_from(other, 5999, host, relay), "{other:?}"); + assert!(!super::redirected_from(other, relay, host, relay), "{other:?}"); + } + } + #[test] fn framed_reads_carry_their_length_and_end_with_an_empty_frame() { let mut fds = [0; 2]; diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index b49bbe383..c920acb55 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -3305,7 +3305,12 @@ impl Engine { let (bridge, ip, prefix, gateway) = match net.as_ref().map(|n| n.driver.as_str()) { Some("host") => { flags |= run_flags::NET_HOST; - (String::new(), [0; 4], 0, [0; 4]) + // Pass the default bridge's gateway and prefix so the VM's + // agent can bring up kiri0 on demand for host-network DNS + // before any bridged container starts, while keeping `bridge` + // empty so this container is not treated as bridged. + let (prefix, gateway) = self.lock_networks().find("bridge").map_or((0, [0; 4]), |b| (b.prefix, b.gateway)); + (String::new(), [0; 4], prefix, gateway) } Some("bridge") => { let n = net.as_ref().expect("matched"); diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index dc9c558d1..64212de5f 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -207,6 +207,10 @@ pub struct Forwards { /// In the VM: the guest ports its kernel forwards for these listeners; /// dropping tells the agent to stop, then frees the ports. nat: Option<(Arc, String, Vec)>, + /// In the VM: the ports also published on the VM's own loopback, for + /// `--network host` containers (`loopback_ports`); dropping tells the + /// agent to stop if `nat` didn't already unpublish the container. + loopback: Option<(Arc, String)>, /// What was actually bound: (binding, host address, host port). pub bound: Vec<(Binding, String, u16)>, } @@ -219,11 +223,19 @@ impl std::fmt::Debug for Forwards { impl Drop for Forwards { fn drop(&mut self) { + let mut unpublished = false; if let Some((vm, id, ..)) = self.kernel.take() { let _ = vm.unpublish(&id); + unpublished = true; } if let Some((vm, id, _ports)) = self.nat.take() { let _ = vm.unpublish(&id); + unpublished = true; + } + if let Some((vm, id)) = self.loopback.take() + && !unpublished + { + let _ = vm.unpublish(&id); } // Closing the write ends wakes every listener thread. self.wake.clear(); @@ -436,7 +448,7 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] listeners.push((b.clone(), ip, port, l)); } } - let mut fw = Forwards { wake: Vec::new(), threads: Vec::new(), kernel: None, nat: None, bound: Vec::new() }; + let mut fw = Forwards { wake: Vec::new(), threads: Vec::new(), kernel: None, nat: None, loopback: None, bound: Vec::new() }; // On a Linux host the daemon shares the kernel with the containers, so // the kernel can rewrite the packets (nftables DNAT) instead of two // user-space relays copying every byte; that serves every address but @@ -493,6 +505,26 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] Err(e) => crate::diag::warn!("NAT port forwarding unavailable; relaying over vsock", id = &id[..id.len().min(12)], error = e), } } + // In the VM: a `--network host` container shares the VM's network, not + // the Mac's, so the VM's 127.0.0.1 has none of these ports. Each TCP + // port the Mac has on its loopback is published there too: the agent + // sends the VM's own connections to it through the host relay, to this + // listener. As on Docker, where a published port is bound in the host's + // namespace. A target on loopback is itself a host-network container. + if cfg!(target_os = "macos") && target_ip != [127, 0, 0, 1] { + let ports = loopback_ports(listeners.iter().map(|(b, ip, port, _)| (b.container_port, ip.as_str(), *port))); + let mut published = false; + for (to_port, host_port) in ports { + let p = kiri_proto::Publish { id, udp: false, host_ip: [127, 0, 0, 1], host_port, to_ip: target_ip, to_port }; + match vm.publish(p) { + Ok(()) => published = true, + Err(e) => crate::diag::warn!("published port not reachable from host-network containers", port = host_port, error = e), + } + } + if published { + fw.loopback = Some((vm.clone(), id.to_owned())); + } + } for ((b, ip, port, listener), nat) in listeners.into_iter().zip(nat) { let (wake_r, wake_w) = pipe()?; fw.wake.push(wake_w); @@ -506,6 +538,19 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] Ok(fw) } +/// The TCP ports (container port, port bound on the Mac) that are on the +/// Mac's loopback: bound on 127.0.0.1 or on every IPv4 address, once each. +/// A port on one other address, or on IPv6 only, is not. +fn loopback_ports<'a>(bound: impl Iterator) -> Vec<(u16, u16)> { + let mut out: Vec<(u16, u16)> = Vec::new(); + for (container_port, ip, port) in bound { + if matches!(ip, "" | "0.0.0.0" | "127.0.0.1") && !out.iter().any(|(_, p)| *p == port) { + out.push((container_port, port)); + } + } + out +} + /// Asks the agent to forward a guest port to each container port, from the /// Mac only; returns the address the Mac dials for each. All or nothing. fn publish_nat(vm: &VmLink, id: &str, container_ports: &[u16], target_ip: [u8; 4]) -> io::Result<(Vec, Vec)> { @@ -1321,6 +1366,12 @@ mod tests { assert_eq!(out, b"HTTP/1"); } + #[test] + fn loopback_ports_are_the_ones_on_the_macs_loopback() { + let bound = [(80, "0.0.0.0", 8080), (80, "::", 8080), (81, "", 8081), (5000, "127.0.0.1", 5999), (5000, "127.0.0.1", 5999), (443, "192.168.1.5", 8443), (53, "::1", 5353)]; + assert_eq!(super::loopback_ports(bound.into_iter()), vec![(80, 8080), (81, 8081), (5000, 5999)]); + } + #[test] fn nat_ports_are_the_lowest_free_and_released() { let a = nat_port().expect("free port"); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 1e1dc56b2..05d29e247 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 +### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) +- Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry +- Caused: none known +- Caused by: - +- Check: `hostnet-published-loopback`, `hostnet-published-every-address`, `hostnet-published-gone`, `hostnet-dns-kiri`, `hostnet-dns-names` + ### #402 Guest kernel: drop stale cached bind-mount file dentries on host change (unreleased) - Fixes: #399 macOS: bind-mounted files deleted or replaced on the Mac return ENOENT or stale cached contents until Apple's cache timeout - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 1152edd4c..a5a30eda1 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -917,6 +917,23 @@ sleep 0.7 t host-internal "Directory listing" $D run --rm alpine wget -qO- http://host.docker.internal:18999/ t host-gateway "Directory listing" $D run --rm --add-host mac:host-gateway alpine wget -qO- http://mac:18999/ t host-internal-hostnet "Directory listing" $D run --rm --network host alpine wget -qO- http://host.docker.internal:18999/ +# A port published on 127.0.0.1 or on every address is in the host's own +# network, as Docker binds it: a --network host container reaches it at +# 127.0.0.1 (#732; a host-network BuildKit pushing to a local registry). +$D rm -f hn-lo hn-all >/dev/null 2>&1 +$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-every-address "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://127.0.0.1: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 && echo still-there || echo ok'" +$D rm -f hn-all >/dev/null 2>&1 +# In the VM a host-network container asks Kiri's resolver, as the default +# bridge's do, so a lookup the Mac's resolver for the VM network refuses +# 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/ kill "$HTTP_PID" ${HTTP_LO_PID:+"$HTTP_LO_PID"}; rm -rf "$HTTP_DIR" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 893be08c1..099cc08a3 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -273,3 +273,6 @@ layer-gc-rmi-df #722 removing an image left its unpacked layers in /var/lib/kiri layer-gc-rmi-disk #722 docker rmi left the removed image's unpacked layer directory and .done marker on disk in /var/lib/kiri/layers layer-gc-container-keeps-layer #722 layer GC after overwriting a tag must keep layers still used by an existing container and reclaim them once that container is removed bind-recreate #402 deleting or replacing a bind-mounted file on the Mac left a stale guest dentry until Apple's cache timeout, causing ENOENT or truncated reads (#399) +hostnet-published-loopback #732 a port published on 127.0.0.1 was unreachable from a --network host container at 127.0.0.1 (Mac): connection refused +hostnet-published-every-address #732 the same for a port published on every address +hostnet-dns-kiri #732 a --network host container asked the Mac's resolver for the VM network directly, with no fallback when it refused From 0f662fffeebb601dd357f2d949fb7fd23ee9d6cd Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:42:02 +0100 Subject: [PATCH 034/157] Mac: hand the VM its uplink settings directly when DHCP does not answer (#435) (#815) --- crates/kiri-init/src/linux/agent.rs | 19 +- crates/kiri-init/src/linux/net.rs | 70 +++++++ crates/kiri-proto/src/lib.rs | 20 ++ crates/kiri/src/daemon/api.rs | 1 + crates/kiri/src/daemon/engine.rs | 62 +++++- crates/kiri/src/daemon/mod.rs | 1 + crates/kiri/src/daemon/vmlink.rs | 6 + crates/kiri/src/daemon/vmnet.rs | 312 ++++++++++++++++++++++++++++ crates/kiri/src/diag/report.rs | 114 ++++++++-- docs/fix-registry.md | 6 + 10 files changed, 592 insertions(+), 19 deletions(-) create mode 100644 crates/kiri/src/daemon/vmnet.rs diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 7d915a9f9..f7dac4762 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -750,6 +750,19 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Uplink { ip: l.ip, gateway: l.gateway }.encode(&mut out), None => Msg::Error("no uplink lease").encode(&mut out), }, + Ok(Msg::SetUplink { ip, prefix, gateway, dns: dns_ip }) => match dhcp.as_mut() { + _ if host_process => Msg::Error("set uplink is only for the VM").encode(&mut out), + Some(d) => match d.apply_static(ip, prefix, gateway, dns_ip) { + Ok(applied) => { + if applied { + eprintln!("kiri-init: DHCP did not answer; configured {} statically as {}/{} via {} from host", net::UPLINK, net::ip_str(ip), prefix, net::ip_str(gateway)); + } + Msg::Ack.encode(&mut out); + } + Err(e) => Msg::Error(&format!("set uplink: {e}")).encode(&mut out), + }, + None => Msg::Error("no uplink interface").encode(&mut out), + }, Ok(Msg::Route { dst, prefix, via, add }) => match net::route(dst, prefix, via, add) { Ok(()) => Msg::Ack.encode(&mut out), Err(e) => Msg::Error(&format!("route: {e}")).encode(&mut out), @@ -851,7 +864,11 @@ fn wait_for_lease(dhcp: &mut Option, max: std::time::Duration) { // SAFETY: one valid pollfd. unsafe { libc::poll(&mut pfd, 1, wait.max(1)) }; if pfd.revents != 0 { - let _ = d.on_readable(); + if let Ok(true) = d.on_readable() + && let Some(l) = &d.lease + { + eprintln!("kiri-init: {} is {}/{} via {}", net::UPLINK, net::ip_str(l.ip), l.prefix, net::ip_str(l.gateway)); + } } let _ = d.on_timer(); } diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 6cef17f03..9e75845ea 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -508,6 +508,31 @@ impl Dhcp { Ok(()) } + /// Configures `eth0` from host-supplied settings when DHCP did not answer. + /// No-op (`Ok(false)`) if a lease is already active. + pub fn apply_static(&mut self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4]) -> io::Result { + let index = self.index; + self.apply_static_with(ip, prefix, gateway, dns, |lease| { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + netlink::add_address(&mut nl, index, lease.ip, lease.prefix)?; + netlink::add_default_route(&mut nl, index, lease.gateway) + }) + } + + fn apply_static_with(&mut self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4], configure: impl FnOnce(&Lease) -> io::Result<()>) -> io::Result { + if self.lease.is_some() { + return Ok(false); + } + if !valid_uplink(ip, prefix, gateway) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid uplink settings")); + } + let lease = Lease { ip, prefix, gateway, dns: if dns == [0; 4] { Vec::new() } else { vec![dns] } }; + configure(&lease)?; + self.state = DhcpState::Bound; + self.lease = Some(lease); + Ok(true) + } + /// Handles a reply. Returns true once a lease has been configured. pub fn on_readable(&mut self) -> io::Result { let mut buf = [0u8; 1500]; @@ -568,6 +593,18 @@ impl Dhcp { } } +fn valid_uplink(ip: [u8; 4], prefix: u8, gateway: [u8; 4]) -> bool { + if !(1..=30).contains(&prefix) || ip == [0; 4] || gateway == [0; 4] || ip == gateway { + return false; + } + if ip[0] == 127 || gateway[0] == 127 || ip[0] >= 224 || gateway[0] >= 224 { + return false; + } + let mask = u32::MAX << (32 - u32::from(prefix)); + let (ip_u, gw_u) = (u32::from_be_bytes(ip), u32::from_be_bytes(gateway)); + (ip_u & mask) == (gw_u & mask) && (ip_u & !mask) != 0 && (ip_u & !mask) != !mask && (gw_u & !mask) != 0 && (gw_u & !mask) != !mask +} + fn random_u32() -> u32 { let mut b = [0u8; 4]; let _ = std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut b)); @@ -1036,4 +1073,37 @@ fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 000000 assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, None).unwrap(), 42); assert_eq!(bridges.plan("kiri0", Some(gw4), 16, Some((other6, 64))), BridgePlan::Recreate); } + + fn test_dhcp() -> Dhcp { + let (r, _w) = sys::pipe().unwrap(); + Dhcp { sock: r, index: 2, mac: [2, 0, 0, 0, 0, 1], xid: 1, state: DhcpState::Discovering, next_send: Instant::now() + Duration::from_secs(1), attempt: 1, lease: None } + } + + #[test] + fn set_uplink_applies_skips_when_leased_and_validates() { + let mut dhcp = test_dhcp(); + for (ip, prefix, gw) in [ + ([0; 4], 24, [192, 168, 64, 1]), + ([192, 168, 64, 2], 0, [192, 168, 64, 1]), + ([192, 168, 64, 2], 31, [192, 168, 64, 1]), + ([192, 168, 64, 2], 32, [192, 168, 64, 1]), + ([192, 168, 64, 2], 33, [192, 168, 64, 1]), + ([127, 0, 0, 2], 8, [127, 0, 0, 1]), + ([224, 0, 0, 2], 24, [224, 0, 0, 1]), + ([240, 0, 0, 2], 24, [240, 0, 0, 1]), + ([192, 168, 64, 1], 24, [192, 168, 64, 1]), + ([192, 168, 64, 255], 24, [192, 168, 64, 1]), + ([192, 168, 64, 0], 24, [192, 168, 64, 1]), + ([192, 168, 65, 2], 24, [192, 168, 64, 1]), + ] { + assert!(dhcp.apply_static_with(ip, prefix, gw, [0; 4], |_| panic!("must not configure")).is_err()); + } + assert!(dhcp.apply_static_with([192, 168, 64, 2], 24, [192, 168, 64, 1], [192, 168, 64, 1], |_| Ok(())).unwrap()); + assert_eq!(dhcp.timeout_ms(), -1); + let l = dhcp.lease.as_ref().unwrap(); + assert_eq!((l.ip, l.prefix, l.gateway, l.dns.as_slice()), ([192, 168, 64, 2], 24, [192, 168, 64, 1], &[[192, 168, 64, 1]][..])); + // No-op when a lease (from DHCP or SetUplink) is already active. + assert!(!dhcp.apply_static_with([192, 168, 64, 9], 24, [192, 168, 64, 1], [0; 4], |_| panic!("must not reconfigure")).unwrap()); + assert_eq!(dhcp.lease.as_ref().unwrap().ip, [192, 168, 64, 2]); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index eb3fdfafe..f6aa57557 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -214,6 +214,11 @@ pub enum Msg<'a> { /// or `Error` with no lease yet; an older agent answers `Error`. UplinkQuery, Uplink { ip: [u8; 4], gateway: [u8; 4] }, + /// Host → guest, in the VM: configure the uplink (`eth0`) directly when + /// DHCP did not answer. Ignored (still answered `Ack`) if the guest + /// already obtained a DHCP lease. `dns` of `[0; 4]` leaves DNS unset. + /// Answered by `Ack` or `Error`; an older agent answers `Error`. + SetUplink { ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4] }, /// Host → guest: container `id` on `bridge` was renamed. Its old DNS /// names are dropped and `names` registered to the same address (A /// records only when `v4`: a network without IPv4 addresses keeps the @@ -850,6 +855,7 @@ mod kind { pub const CANCEL_START: u16 = 80; pub const DNS_RENAME: u16 = 81; pub const FS_READ_LINK: u16 = 82; + pub const SET_UPLINK: u16 = 83; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1271,6 +1277,12 @@ impl Msg<'_> { o.extend_from_slice(&ip); o.extend_from_slice(&gateway); }), + Msg::SetUplink { ip, prefix, gateway, dns } => frame(out, kind::SET_UPLINK, |o| { + o.extend_from_slice(&ip); + o.push(prefix); + o.extend_from_slice(&gateway); + o.extend_from_slice(&dns); + }), Msg::Ack => frame(out, kind::ACK, |_| {}), Msg::InputConsumed { id, bytes } => frame(out, kind::INPUT_CONSUMED, |o| { put_str(o, id); @@ -1566,6 +1578,12 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::NET_DETACH => Msg::NetDetach { id: r.str()?, ifname: r.str()?, bridge: r.str()?, ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)? }, kind::UPLINK_QUERY => Msg::UplinkQuery, kind::UPLINK => Msg::Uplink { ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, gateway: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)? }, + kind::SET_UPLINK => Msg::SetUplink { + ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + prefix: r.u8()?, + gateway: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + dns: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + }, kind::ACK => Msg::Ack, kind::INPUT_CONSUMED => Msg::InputConsumed { id: r.str()?, bytes: r.u32()? }, kind::PUBLISH => Msg::Publish(Publish { @@ -1932,6 +1950,8 @@ mod tests { round(Msg::Route { dst: [10, 43, 0, 0], prefix: 16, via: [172, 17, 0, 4], add: true }); round(Msg::UplinkQuery); round(Msg::Uplink { ip: [192, 168, 64, 18], gateway: [192, 168, 64, 1] }); + round(Msg::SetUplink { ip: [192, 168, 64, 2], prefix: 24, gateway: [192, 168, 64, 1], dns: [192, 168, 64, 1] }); + round(Msg::SetUplink { ip: [10, 0, 0, 5], prefix: 16, gateway: [10, 0, 0, 1], dns: [0, 0, 0, 0] }); round(Msg::Ack); let mut buf = Vec::new(); let mounts = ["/var/lib/kiri/volumes/pg/_data\t/var/lib/postgresql/data\tcreate,copyup", "/host/cfg\t/etc/app\tro"]; diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index a155c74fa..d6614592c 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -513,6 +513,7 @@ fn info(engine: &Engine) -> Value { "RegistryConfig": super::daemon_json::info(), "KiriAgentMemory": engine.agent_rss().unwrap_or(0), "KiriVmAwake": engine.is_awake(), + "KiriVmUplink": engine.uplink_info(), "KiriStopped": engine.is_stopped(), "KiriMemoryCeiling": engine.memory().0, "KiriMemoryTarget": engine.memory().1, diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index c920acb55..98867cba6 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1345,6 +1345,8 @@ pub struct Engine { /// Configs are content-addressed, so an entry never goes stale; entries /// of images no longer stored are dropped on the next listing. image_labels: Mutex>, + /// The running VM's uplink status for `/info` and `kiri diag report` (#435). + uplink: Mutex, } /// k3s's pod and service ranges, which `kiri k8s` leaves at their defaults. @@ -1473,6 +1475,7 @@ impl Engine { k8s_routes: Mutex::new(None), k8s_fwd: Mutex::new(HashMap::new()), image_labels: Mutex::new(HashMap::new()), + uplink: Mutex::new(serde_json::Value::Null), }); let _ = engine.me.set(Arc::downgrade(&engine)); engine.start_syncer(); @@ -1493,9 +1496,61 @@ impl Engine { } /// What the agent found wrong with a Linux host, for `docker info` - /// (`VmLink::host_warnings`). + /// (`VmLink::host_warnings`), or a Mac VM uplink fallback failure. pub fn host_warnings(&self) -> Vec { - self.awake().map(|vm| vm.host_warnings()).unwrap_or_default() + let mut out = self.awake().map(|vm| vm.host_warnings()).unwrap_or_default(); + if let Some(w) = self.uplink.lock().unwrap_or_else(|e| e.into_inner())["warning"].as_str() { + out.push(w.to_owned()); + } + out + } + + /// The running VM's uplink status for `/info` and `kiri diag report`. + pub fn uplink_info(&self) -> serde_json::Value { + self.uplink.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// Waits up to 2 s for macOS `bootpd` to lease `eth0` in the VM; if DHCP + /// does not answer (e.g. another app bound UDP port 67), configures the + /// VM's uplink directly from the Mac's `vmnet` bridge (#435). + #[cfg(target_os = "macos")] + fn ensure_uplink(&self, vm: &VmLink) { + let deadline = std::time::Instant::now() + Duration::from_secs(2); + loop { + if let Ok((ip, gw)) = vm.uplink() { + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::json!({ + "mode": "dhcp", + "ip": std::net::Ipv4Addr::from(ip).to_string(), + "gateway": std::net::Ipv4Addr::from(gw).to_string(), + }); + return; + } + if vm.is_disconnected() { + return; + } + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + break; + } + std::thread::sleep(left.min(Duration::from_millis(100))); + } + let udp67 = super::vmnet::udp67_holder(); + let status = match super::vmnet::discover_uplink(self.store.root()) + .and_then(|(b, ip)| vm.set_uplink(ip, b.prefix, b.gateway, b.gateway).map(|()| (b, ip)).map_err(|e| e.to_string())) + { + Ok((b, addr)) => { + let (ip, gw) = (format!("{}/{}", std::net::Ipv4Addr::from(addr), b.prefix), std::net::Ipv4Addr::from(b.gateway).to_string()); + crate::diag::warn!("VM DHCP did not answer; configured VM uplink directly from Mac", bridge = b.name, ip = ip, gateway = gw, dns = gw, udp67 = udp67.as_deref().unwrap_or("none visible")); + serde_json::json!({"mode": "static-fallback", "bridge": b.name, "ip": ip, "gateway": gw, "dns": gw, "udp67": udp67}) + } + Err(reason) => { + crate::diag::warn!("VM DHCP did not answer and static uplink fallback failed", error = reason, udp67 = udp67.as_deref().unwrap_or("none visible")); + let holder = udp67.as_deref().map(|h| format!(" (UDP port 67 held by {h})")).unwrap_or_default(); + let warning = format!("VM has no IPv4 uplink: DHCP did not answer and static fallback failed: {reason}{holder}"); + serde_json::json!({"mode": "fallback-failed", "reason": reason, "udp67": udp67, "warning": warning}) + } + }; + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = status; } /// Why unpacked layers may belong to images the image list lost, for @@ -1622,6 +1677,8 @@ impl Engine { *self.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = ceiling; self.sleeping.store(false, std::sync::atomic::Ordering::SeqCst); self.lock().vm_booted_at = Some(std::time::Instant::now()); + #[cfg(target_os = "macos")] + self.ensure_uplink(&vm); *self.link.lock().unwrap_or_else(|e| e.into_inner()) = Some(vm.clone()); crate::diag::info!("VM booted", ms = t0.elapsed().as_millis(), cpus = cpus, memory_mib = ceiling >> 20); drop(waking); @@ -2618,6 +2675,7 @@ impl Engine { self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take(); + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::Value::Null; self.changed.notify_all(); match end { // sleep_if_idle says why it slept. diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index 497bc2051..c8df7f13d 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -36,6 +36,7 @@ mod top; mod usb; mod vmcpu; mod vmlink; +pub(crate) mod vmnet; mod volumes; #[cfg(target_os = "macos")] mod watch; diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index d448cad59..a063798d7 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -577,6 +577,12 @@ impl VmLink { } } + /// Configures the VM's uplink (`eth0`) directly when macOS DHCP did not + /// answer. Ignored by the guest if it already obtained a DHCP lease. + pub fn set_uplink(&self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4]) -> io::Result<()> { + self.ack(|o| Msg::SetUplink { ip, prefix, gateway, dns }.encode(o)) + } + /// Forwards a published port in the kernel (on a Linux host; in the VM, /// from the NAT network). `Err` means the agent could not; the caller /// falls back to relaying. diff --git a/crates/kiri/src/daemon/vmnet.rs b/crates/kiri/src/daemon/vmnet.rs new file mode 100644 index 000000000..5e3bb3192 --- /dev/null +++ b/crates/kiri/src/daemon/vmnet.rs @@ -0,0 +1,312 @@ +//! macOS `vmnet` (`VZNATNetworkDeviceAttachment`) network discovery and IP +//! selection for the VM uplink fallback (#435). + +#![cfg_attr(not(target_os = "macos"), allow(dead_code))] + +use std::collections::HashSet; +use std::net::Ipv4Addr; +use std::path::Path; + +/// A host bridge interface serving Apple's shared NAT network (`bridge100`, …). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bridge { + pub name: String, + pub gateway: [u8; 4], + pub prefix: u8, +} + +pub fn mask_to_prefix(mask: [u8; 4]) -> Option { + let bits = u32::from_be_bytes(mask); + let ones = bits.leading_ones(); + ((1..=30).contains(&ones) && bits == (u32::MAX << (32 - ones))).then_some(ones as u8) +} + +fn mask_from_prefix(prefix: u8) -> u32 { + if prefix == 0 { 0 } else { u32::MAX << (32 - u32::from(prefix)) } +} + +fn parse_ipv4(s: &str) -> Option<[u8; 4]> { + s.trim().parse::().ok().map(|a| a.octets()) +} + +pub fn parse_mac(s: &str) -> Option<[u8; 6]> { + let mut mac = [0u8; 6]; + let mut parts = s.trim().split(':'); + for b in &mut mac { + let p = parts.next().filter(|p| !p.is_empty() && p.len() <= 2)?; + *b = u8::from_str_radix(p, 16).ok()?; + } + parts.next().is_none().then_some(mac) +} + +fn usable_gateway(ip: [u8; 4]) -> bool { + ip != [0; 4] && ip[0] != 127 && !(ip[0] == 169 && ip[1] == 254) +} + +/// Extracts `Shared_Net_Address` and `Shared_Net_Mask` from `com.apple.vmnet.plist`. +pub fn parse_vmnet_plist(xml: &str) -> Option<([u8; 4], u8)> { + let val = |k: &str| { + let after = xml.split_once(&format!("{k}"))?.1.trim_start(); + after.strip_prefix("")?.split_once("").map(|(v, _)| v.trim()).filter(|v| !v.is_empty()) + }; + let addr = parse_ipv4(val("Shared_Net_Address")?).filter(|&a| usable_gateway(a))?; + let prefix = match val("Shared_Net_Mask") { + Some(m) => mask_to_prefix(parse_ipv4(m)?)?, + None => 24, + }; + let (mask, raw) = (mask_from_prefix(prefix), u32::from_be_bytes(addr)); + Some((if raw & !mask == 0 { (raw | 1).to_be_bytes() } else { addr }, prefix)) +} + +/// Parses macOS `/var/db/dhcpd_leases` blocks into `(ip, mac)` pairs. +pub fn parse_dhcpd_leases(text: &str) -> Vec<([u8; 4], Option<[u8; 6]>)> { + let (mut out, mut in_block, mut ip, mut mac) = (Vec::new(), false, None, None); + for raw in text.lines() { + match raw.trim() { + "{" => (in_block, ip, mac) = (true, None, None), + "}" => { + if in_block && let Some(a) = ip.take() { + out.push((a, mac)); + } + in_block = false; + } + line if in_block => match line.split_once('=') { + Some((k, v)) if k.trim() == "ip_address" => ip = parse_ipv4(v), + Some((k, v)) if k.trim() == "hw_address" => mac = parse_mac(v.trim().split_once(',').map_or(v.trim(), |(_, r)| r)), + _ => {} + }, + _ => {} + } + } + out +} + +/// Parses `netstat -anv -p udp` output for listeners bound to UDP port 67. +pub fn parse_udp67_listeners(netstat: &str) -> Vec<(Option, u32)> { + let (mut out, mut pid_col) = (Vec::new(), None); + for line in netstat.lines().map(str::trim).filter(|l| !l.is_empty()) { + if let Some((_, after)) = line.split_once("(state)") { + pid_col = after.split_whitespace().position(|c| c == "pid" || c == "process:pid"); + continue; + } + let f: Vec<&str> = line.split_whitespace().collect(); + if f.len() < 6 || !matches!(f[0], "udp4" | "udp46" | "udp6") || !f[3].ends_with(".67") { + continue; + } + let named = |t: &str| { + let (n, p) = t.rsplit_once(':')?; + (!n.is_empty() && !n.starts_with("0x") && !n.contains(':')).then(|| p.parse::().ok().filter(|&p| p > 0))?.map(|p| (Some(n.to_owned()), p)) + }; + let tail = &f[5..]; + let entry = pid_col + .and_then(|i| tail.get(i).copied()) + .and_then(|t| named(t).or_else(|| t.parse::().ok().filter(|&p| p > 0).map(|p| (None, p)))) + .or_else(|| tail.iter().copied().find_map(named)); + if let Some(e) = entry && !out.contains(&e) { + out.push(e); + } + } + out +} + +/// Picks the host bridge backing Apple's shared NAT network (`bridge100+`). +pub fn pick_bridge(ifaces: &[Bridge], plist: Option<([u8; 4], u8)>) -> Option { + let num = |n: &str| n.strip_prefix("bridge")?.parse::().ok(); + let valid: Vec<&Bridge> = ifaces.iter().filter(|b| b.name.starts_with("bridge") && (8..=30).contains(&b.prefix) && usable_gateway(b.gateway)).collect(); + if let Some((p_gw, p_prefix)) = plist { + let p_mask = mask_from_prefix(p_prefix); + let p_net = u32::from_be_bytes(p_gw) & p_mask; + if let Some(b) = valid.iter().copied().filter(|b| (u32::from_be_bytes(b.gateway) & p_mask) == p_net).min_by_key(|b| (b.name != "bridge100", num(&b.name).unwrap_or(u32::MAX))) { + return Some(b.clone()); + } + } + valid + .into_iter() + .filter(|b| num(&b.name).is_some_and(|n| n >= 100)) + .min_by_key(|b| (b.name != "bridge100", num(&b.name).unwrap_or(u32::MAX))) + .cloned() + .or_else(|| plist.map(|(gateway, prefix)| Bridge { name: "bridge100".into(), gateway, prefix })) +} + +/// Picks an IPv4 host address inside `gateway/prefix` avoiding the network, +/// gateway, broadcast, and other hosts' leases in `/var/db/dhcpd_leases`. +pub fn pick_ip(gateway: [u8; 4], prefix: u8, our_mac: Option<[u8; 6]>, leases: &[([u8; 4], Option<[u8; 6]>)]) -> Option<[u8; 4]> { + if !(1..=30).contains(&prefix) || !usable_gateway(gateway) { + return None; + } + let (mask, gw) = (mask_from_prefix(prefix), u32::from_be_bytes(gateway)); + let (net, bcast) = (gw & mask, (gw & mask) | !mask); + let in_sub = |ip: [u8; 4]| { + let v = u32::from_be_bytes(ip); + v > net && v < bcast && v != gw + }; + let other: HashSet<[u8; 4]> = leases.iter().filter(|&&(ip, mac)| in_sub(ip) && (our_mac.is_none() || mac != our_mac)).map(|&(ip, _)| ip).collect(); + if let Some(m) = our_mac + && let Some(&(ip, _)) = leases.iter().find(|&&(ip, mac)| mac == Some(m) && in_sub(ip) && !other.contains(&ip)) + { + return Some(ip); + } + ((net + 1)..bcast).filter(|&h| h != gw).map(u32::to_be_bytes).find(|ip| !other.contains(ip)) +} + +pub fn format_udp67_summary(listeners: &[(Option, u32)]) -> Option { + let mut items: Vec<(bool, String)> = Vec::new(); + for (name, pid) in listeners { + let label = name.as_ref().map_or_else(|| format!("pid {pid}"), |n| format!("{n} (pid {pid})")); + let sys = name.as_deref().is_some_and(|n| matches!(n, "bootpd" | "launchd")); + if !items.iter().any(|(_, s)| s == &label) { + items.push((sys, label)); + } + } + items.sort_by_key(|(sys, _)| *sys); + (!items.is_empty()).then(|| items.into_iter().map(|(_, s)| s).collect::>().join(", ")) +} + +/// Extracts the IPv4 octets (`sin_addr`, bytes `4..8` of BSD `sockaddr_in`) +/// from a raw BSD `sockaddr` slice (`raw[0] == sa_len`), zero-padding +/// truncated netmasks (`sa_len` 5..8 on macOS) without reading past `sa_len`. +pub fn parse_bsd_sockaddr_ipv4(raw: &[u8], min_len: usize) -> Option<[u8; 4]> { + let len = usize::from(*raw.first()?).min(raw.len()); + if len < min_len || len <= 4 { + return None; + } + let mut out = [0u8; 4]; + let n = (len - 4).min(4); + out[..n].copy_from_slice(&raw[4..4 + n]); + Some(out) +} + +#[cfg(target_os = "macos")] +unsafe fn sockaddr_ipv4(sa: *const libc::sockaddr, min_len: usize) -> Option<[u8; 4]> { + if sa.is_null() { + return None; + } + let len = usize::from(unsafe { (*sa).sa_len }); + // SAFETY: `getifaddrs` allocates at least `sa_len` bytes at `sa`. + parse_bsd_sockaddr_ipv4(unsafe { std::slice::from_raw_parts(sa as *const u8, len) }, min_len) +} + +#[cfg(target_os = "macos")] +fn live_bridges() -> Vec { + let mut list: *mut libc::ifaddrs = std::ptr::null_mut(); + // SAFETY: getifaddrs fills `list`, freed below; entries are read only while it lives. + if unsafe { libc::getifaddrs(&mut list) } != 0 { + return Vec::new(); + } + let (mut out, mut p) = (Vec::new(), list); + while let Some(ifa) = unsafe { p.as_ref() } { + let up = (ifa.ifa_flags as i32) & libc::IFF_UP != 0; + if up && !ifa.ifa_name.is_null() && !ifa.ifa_addr.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET { + let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned(); + if name.starts_with("bridge") + && let (Some(gateway), Some(mask)) = (unsafe { sockaddr_ipv4(ifa.ifa_addr, 8) }, unsafe { sockaddr_ipv4(ifa.ifa_netmask, 5) }) + && let Some(prefix) = mask_to_prefix(mask) + { + out.push(Bridge { name, gateway, prefix }); + } + } + p = ifa.ifa_next; + } + // SAFETY: freed once for the list returned by getifaddrs. + unsafe { libc::freeifaddrs(list) }; + out +} + +#[cfg(target_os = "macos")] +pub fn current_bridge() -> Option { + let plist = std::fs::read_to_string("/Library/Preferences/SystemConfiguration/com.apple.vmnet.plist").ok().and_then(|s| parse_vmnet_plist(&s)); + pick_bridge(&live_bridges(), plist) +} + +#[cfg(not(target_os = "macos"))] +pub fn current_bridge() -> Option { + None +} + +#[cfg(target_os = "macos")] +pub fn discover_uplink(store_root: &Path) -> Result<(Bridge, [u8; 4]), String> { + let bridge = current_bridge().ok_or_else(|| "no macOS vmnet bridge interface (bridge100) found".to_owned())?; + let vm_mac = std::fs::read_to_string(store_root.join("vm/mac")).ok().and_then(|s| parse_mac(&s)); + let leases = std::fs::read_to_string("/var/db/dhcpd_leases").map(|t| parse_dhcpd_leases(&t)).unwrap_or_default(); + let ip = pick_ip(bridge.gateway, bridge.prefix, vm_mac, &leases) + .ok_or_else(|| format!("no free IPv4 address left on {} ({}/{})", bridge.name, Ipv4Addr::from(bridge.gateway), bridge.prefix))?; + Ok((bridge, ip)) +} + +#[cfg(not(target_os = "macos"))] +pub fn discover_uplink(_store_root: &Path) -> Result<(Bridge, [u8; 4]), String> { + Err("vmnet uplink discovery is only available on macOS".into()) +} + +#[cfg(target_os = "macos")] +pub fn udp67_holder() -> Option { + let out = std::process::Command::new("/usr/sbin/netstat").args(["-anv", "-p", "udp"]).stderr(std::process::Stdio::null()).output().ok()?; + let mut listeners = parse_udp67_listeners(&String::from_utf8_lossy(&out.stdout)); + for (name, pid) in &mut listeners { + if name.is_none() { + *name = std::process::Command::new("/bin/ps") + .args(["-p", &pid.to_string(), "-o", "comm="]) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .and_then(|o| { + let raw = String::from_utf8_lossy(&o.stdout).trim().to_owned(); + (!raw.is_empty()).then(|| Path::new(&raw).file_name().and_then(|f| f.to_str()).unwrap_or(&raw).to_owned()) + }); + } + } + format_udp67_summary(&listeners) +} + +#[cfg(not(target_os = "macos"))] +pub fn udp67_holder() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_vmnet_plist_and_picks_bridge() { + let xml = "Shared_Net_Address192.168.64.1Shared_Net_Mask255.255.255.0"; + assert_eq!(parse_vmnet_plist(xml), Some(([192, 168, 64, 1], 24))); + assert_eq!(parse_vmnet_plist("Shared_Net_Address10.20.30.0"), Some(([10, 20, 30, 1], 24))); + assert_eq!(parse_vmnet_plist("Shared_Net_Address127.0.0.1"), None); + let (tb, b100, b101) = ( + Bridge { name: "bridge0".into(), gateway: [10, 0, 0, 1], prefix: 24 }, + Bridge { name: "bridge100".into(), gateway: [192, 168, 64, 1], prefix: 24 }, + Bridge { name: "bridge101".into(), gateway: [192, 168, 65, 1], prefix: 24 }, + ); + assert_eq!(pick_bridge(&[tb.clone(), b101.clone(), b100.clone()], None), Some(b100.clone())); + assert_eq!(pick_bridge(std::slice::from_ref(&tb), None), None); + assert_eq!(pick_bridge(&[b100, b101.clone()], Some(([192, 168, 65, 1], 24))), Some(b101)); + } + + #[test] + fn parses_leases_and_picks_collision_free_ip() { + let leases = parse_dhcpd_leases("{\n\tip_address=192.168.64.2\n\thw_address=1,2:48:44:4d:d8:13\n}\n{\n\tip_address=192.168.64.28\n\thw_address=1,f6:49:47:3e:68:51\n}\n"); + let our_mac = [0xf6, 0x49, 0x47, 0x3e, 0x68, 0x51]; + assert_eq!(pick_ip([192, 168, 64, 1], 24, Some(our_mac), &leases), Some([192, 168, 64, 28])); + assert_eq!(pick_ip([192, 168, 64, 1], 24, None, &leases[..1]), Some([192, 168, 64, 3])); + assert_eq!(pick_ip([192, 168, 64, 1], 30, None, &leases[..1]), None); + } + + #[test] + fn parses_udp67_listeners_from_netstat() { + let netstat = "Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat process:pid state\n\ + udp4 0 0 *.67 *.* 786896 9216 kavd:412 0x0000\n\ + udp4 0 0 192.168.64.1.67 *.* 786896 9216 bootpd:510 0x0000\n"; + assert_eq!(format_udp67_summary(&parse_udp67_listeners(netstat)).as_deref(), Some("kavd (pid 412), bootpd (pid 510)")); + } + + #[test] + fn decodes_truncated_bsd_netmask_sockaddrs() { + assert_eq!(parse_bsd_sockaddr_ipv4(&[4, 2, 0, 0], 5), None); + assert_eq!(parse_bsd_sockaddr_ipv4(&[7, 2, 0, 0, 255, 255, 255], 8), None); + assert_eq!(parse_bsd_sockaddr_ipv4(&[5, 2, 0, 0, 255], 5).and_then(mask_to_prefix), Some(8)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[7, 2, 0, 0, 255, 255, 255], 5).and_then(mask_to_prefix), Some(24)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[8, 2, 0, 0, 255, 255, 255, 252], 5).and_then(mask_to_prefix), Some(30)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[16, 2, 0, 0, 192, 168, 64, 1, 0, 0, 0, 0, 0, 0, 0, 0], 8), Some([192, 168, 64, 1])); + } +} diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index efc4af7e9..d334a69c8 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -253,23 +253,59 @@ pub struct Facts { pub created: SystemTime, /// The container list, when the person ticked it in the window. pub containers: Option, + /// VM uplink / DHCP status and (on macOS) bridge & UDP port 67 summary. + pub vm_network: Option, } -/// The engine as the report describes it, asked without waking the VM. -fn engine_line() -> String { +/// The engine as the report describes it (plus its `/info` payload), asked +/// without waking the VM. +fn engine_facts() -> (String, Option) { if !crate::client::alive() { - return "not running".into(); + return ("not running".into(), None); } let version = crate::client::get_background("/version").unwrap_or_default(); let info = crate::client::get_background("/info").unwrap_or_default(); - format!( + let line = format!( "running (engine {}, VM {}, {} of {} containers running, {} images)", crate::client::kiri_version(&version).unwrap_or("?"), if info["KiriVmAwake"] == true { "awake" } else { "asleep" }, info["ContainersRunning"].as_u64().unwrap_or(0), info["Containers"].as_u64().unwrap_or(0), info["Images"].as_u64().unwrap_or(0), - ) + ); + (line, Some(info)) +} + +/// Formats the VM uplink / DHCP fallback and host UDP port 67 lines for the +/// report. Returns `None` when there is nothing to report (e.g. Linux host). +pub fn vm_network_summary(info: Option<&Value>, bridge: Option<&crate::daemon::vmnet::Bridge>, udp67: Option<&str>) -> Option { + let (mut lines, mut dhcp_failed, mut recorded_udp67) = (Vec::new(), false, None); + if let Some(u) = info.and_then(|i| i.get("KiriVmUplink")).filter(|v| v.is_object()) { + recorded_udp67 = u["udp67"].as_str(); + let (ip, gw) = (u["ip"].as_str().unwrap_or("?"), u["gateway"].as_str().unwrap_or("?")); + match u["mode"].as_str().unwrap_or("") { + "dhcp" => lines.push(format!("VM uplink: DHCP ({ip} via {gw})")), + "static-fallback" => { + dhcp_failed = true; + let (br, dns) = (u["bridge"].as_str().unwrap_or("bridge100"), u["dns"].as_str().unwrap_or("?")); + lines.push(format!("VM uplink: static fallback on {br} ({ip} via {gw}, dns {dns}) — DHCP did not answer")); + } + "fallback-failed" => { + dhcp_failed = true; + lines.push(format!("VM uplink: no uplink — DHCP did not answer and fallback failed ({})", u["reason"].as_str().unwrap_or("unknown"))); + } + _ => {} + } + } + if let Some(b) = bridge { + lines.push(format!("Host vmnet bridge: {} ({}/{})", b.name, std::net::Ipv4Addr::from(b.gateway), b.prefix)); + } + if let Some(holder) = udp67.or(recorded_udp67) { + lines.push(format!("Host UDP port 67: {holder}")); + } else if dhcp_failed { + lines.push("Host UDP port 67: none visible".into()); + } + (!lines.is_empty()).then(|| lines.join("\n")) } /// The engine's containers, one a line: name, image and status. Nothing @@ -362,6 +398,11 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - let _ = writeln!(s, "System: {}", super::system().line()); let _ = writeln!(s, "Engine: {}", facts.engine); let _ = writeln!(s, "Crash reports: {}", if facts.crash_reports { "sent automatically" } else { "not sent automatically" }); + if let Some(net) = &facts.vm_network { + for line in net.lines() { + let _ = writeln!(s, "{line}"); + } + } for (part, title) in [(Part::Daemon, "engine"), (Part::Ui, "window"), (Part::Cli, "command line")] { let path = log_file(state, part); @@ -374,15 +415,20 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - } } - // The engine's own stderr, as launchd (or the window) keeps it. - let raw = state.join("daemon.log"); - let _ = writeln!(s, "\n==== Engine output ({}) ====", raw.display()); - let text = tail(&raw, LOG_BUDGET as u64); - let lines: Vec<&str> = text.lines().collect(); - if lines.is_empty() { - let _ = writeln!(s, "(empty)"); - } else { - let _ = writeln!(s, "{}", lines[lines.len().saturating_sub(200)..].join("\n")); + // The engine's own stderr, as launchd (or the window) keeps it, and the + // VM's console log (kiri-init messages, kernel boot, DHCP fallback). + for (title, path, always) in [("Engine output", state.join("daemon.log"), true), ("Guest console", state.join("logs/guest-console.log"), false)] { + if !always && !path.is_file() { + continue; + } + let _ = writeln!(s, "\n==== {title} ({}) ====", path.display()); + let text = tail(&path, LOG_BUDGET as u64); + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + let _ = writeln!(s, "(empty)"); + } else { + let _ = writeln!(s, "{}", lines[lines.len().saturating_sub(200)..].join("\n")); + } } if let Some(list) = &facts.containers { @@ -419,7 +465,17 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - pub fn report_text(containers: bool) -> io::Result { let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; let state = home.join(crate::flavor::STATE.get()); - let facts = Facts { engine: engine_line(), crash_reports: crash_reports_on(), created: SystemTime::now(), containers: containers.then(container_lines) }; + let (engine, info) = engine_facts(); + let bridge = crate::daemon::vmnet::current_bridge(); + let udp67 = crate::daemon::vmnet::udp67_holder(); + let vm_network = vm_network_summary(info.as_ref(), bridge.as_ref(), udp67.as_deref()); + let facts = Facts { + engine, + crash_reports: crash_reports_on(), + created: SystemTime::now(), + containers: containers.then(container_lines), + vm_network, + }; Ok(assemble(&home, &state, &facts, &Redactor::for_user())) } @@ -882,7 +938,7 @@ mod tests { std::fs::write(state.join("crashes/1792700000-ui.sent.txt"), "Kiri crash report\nMessage: older\n").unwrap(); std::fs::write(reports.join("kiri-2026-10-28-094107.ips"), format!("{{\"app_name\":\"kiri\",\"crashReporterKey\":\"ABCD-1234\"}}\n{{\"procPath\":\"{h}/Applications/Kiri.app\"}}")).unwrap(); std::fs::write(reports.join("Safari-2026-10-28-094107.ips"), "not ours").unwrap(); - let facts = Facts { engine: "not running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: Some("web nginx:alpine Up 2 hours\n".into()) }; + let facts = Facts { engine: "not running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: Some("web nginx:alpine Up 2 hours\n".into()), vm_network: None }; let text = assemble(&home, &state, &facts, &Redactor::new(Some(h.clone()), Vec::new())); assert!(text.starts_with("Kiri diagnostics report\nCreated: 2026-10-24T00:00:00"), "{text}"); @@ -966,4 +1022,30 @@ mod tests { assert!(pending(&home, 1_792_800_001).is_empty()); let _ = std::fs::remove_dir_all(&home); } + + #[test] + fn report_includes_vm_uplink_dhcp_fallback_udp67_and_guest_console() { + let bridge = crate::daemon::vmnet::Bridge { name: "bridge100".into(), gateway: [192, 168, 64, 1], prefix: 24 }; + let fallback_info = json!({"KiriVmUplink": {"mode": "static-fallback", "bridge": "bridge100", "ip": "192.168.64.2/24", "gateway": "192.168.64.1", "dns": "192.168.64.1", "udp67": "kavd (pid 412)"}}); + let summary = vm_network_summary(Some(&fallback_info), Some(&bridge), Some("kavd (pid 412)")).unwrap(); + assert!(summary.contains("VM uplink: static fallback on bridge100 (192.168.64.2/24 via 192.168.64.1, dns 192.168.64.1) — DHCP did not answer"), "{summary}"); + assert!(summary.contains("Host vmnet bridge: bridge100 (192.168.64.1/24)") && summary.contains("Host UDP port 67: kavd (pid 412)"), "{summary}"); + + let ok = vm_network_summary(Some(&json!({"KiriVmUplink": {"mode": "dhcp", "ip": "192.168.64.28", "gateway": "192.168.64.1"}})), Some(&bridge), None).unwrap(); + assert!(ok.contains("VM uplink: DHCP (192.168.64.28 via 192.168.64.1)") && !ok.contains("UDP port 67"), "{ok}"); + + let fail = vm_network_summary(Some(&json!({"KiriVmUplink": {"mode": "fallback-failed", "reason": "no bridge100"}})), None, None).unwrap(); + assert!(fail.contains("DHCP did not answer and fallback failed (no bridge100)") && fail.contains("Host UDP port 67: none visible"), "{fail}"); + assert_eq!(vm_network_summary(None, None, None), None); + + let home = temp_home("vm-net"); + let state = home.join(".kiri"); + std::fs::create_dir_all(state.join("logs")).unwrap(); + std::fs::write(state.join("logs/guest-console.log"), "kiri-init: DHCP did not answer; configured eth0 statically as 192.168.64.2/24 via 192.168.64.1 from host\n").unwrap(); + let facts = Facts { engine: "running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: None, vm_network: Some(summary) }; + let text = assemble(&home, &state, &facts, &Redactor::new(Some(home.display().to_string()), Vec::new())); + assert!(text.contains("VM uplink: static fallback on bridge100") && text.contains("Host UDP port 67: kavd (pid 412)"), "{text}"); + assert!(text.contains("==== Guest console (~/.kiri/logs/guest-console.log) ====") && text.contains("configured eth0 statically as 192.168.64.2/24"), "{text}"); + let _ = std::fs::remove_dir_all(&home); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 05d29e247..445df8a0e 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 +### #435 Mac: hand the VM its network settings directly when DHCP does not answer (unreleased) +- Fixes: #435 Containers have no internet: VM never gets IPv4/uplink lease when another app binds UDP 67 +- Caused: none known +- Caused by: - +- Check: none + ### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known From eb3867b1e330829381eb227106185a569dd4314d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:37:58 +0100 Subject: [PATCH 035/157] CLI: support kiri update --check on Linux (#749) (#817) --- crates/kiri/src/docker.rs | 2 +- crates/kiri/src/main.rs | 4 +- crates/kiri/src/update.rs | 136 +++++++++++++++++++++++++++++++++----- docs/fix-registry.md | 5 ++ 4 files changed, 128 insertions(+), 19 deletions(-) diff --git a/crates/kiri/src/docker.rs b/crates/kiri/src/docker.rs index 499770929..e2c7ec060 100644 --- a/crates/kiri/src/docker.rs +++ b/crates/kiri/src/docker.rs @@ -21,7 +21,7 @@ pub const COMMANDS: &[&str] = &[ /// `kiri update` is two commands. Alone or with `--check` it updates Kiri; /// with anything else it is Docker's `update`, which always names a /// container (`kiri update --memory 256m web`). -#[cfg(any(target_os = "macos", test))] +#[cfg(any(target_os = "macos", target_os = "linux", test))] pub fn is_container_update(args: &[String]) -> bool { args.iter().any(|a| !matches!(a.as_str(), "--check" | "-h" | "--help")) } diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 69bea5477..c8cd4d247 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -77,7 +77,7 @@ mod ui; #[cfg(unix)] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod tools; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", target_os = "linux"))] mod update; const USAGE: &str = "\ @@ -175,7 +175,7 @@ fn main() -> ExitCode { Some("usb") => usb::run(&args[1..]), #[cfg(target_os = "macos")] Some("import") => import::run(&args[1..]), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "linux"))] Some("update") if !docker::is_container_update(&args[1..]) => update::run(&args[1..]), #[cfg(unix)] Some("diag") => diag::run(&args[1..]), diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 935a17408..2327f83bc 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -16,11 +16,17 @@ //! never happened). `kiri update` does it all at once; `--check` only //! reports. -use std::io::{self, Read, Write}; +use std::io::{self, Write}; +#[cfg(target_os = "macos")] +use std::io::Read; +#[cfg(target_os = "macos")] use std::path::{Path, PathBuf}; +#[cfg(target_os = "macos")] use std::process::Command; +#[cfg(target_os = "macos")] use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(target_os = "macos")] use sha2::{Digest, Sha256}; /// Each Mac reads its own feed, so a release for one never reaches the other @@ -35,6 +41,7 @@ const FEED: &str = "https://download.runkiri.com/latest-mac-x86_64.json"; #[cfg(target_os = "linux")] const FEED: &str = "https://download.runkiri.com/latest.json"; /// The biggest download accepted (the app is about 60 MB packed). +#[cfg(target_os = "macos")] const MAX_DOWNLOAD: u64 = 2 << 30; #[derive(serde::Deserialize, serde::Serialize, Clone, Debug)] @@ -71,8 +78,12 @@ fn agent() -> ureq::Agent { pub fn latest() -> io::Result { let url = std::env::var("KIRI_UPDATE_URL").unwrap_or_else(|_| FEED.to_owned()); + latest_from(&url) +} + +fn latest_from(url: &str) -> io::Result { let release = (|| -> io::Result { - let body = agent().get(&url).call().map_err(io::Error::other)?.body_mut().with_config().limit(64 << 10).read_to_vec().map_err(io::Error::other)?; + let body = agent().get(url).call().map_err(io::Error::other)?.body_mut().with_config().limit(64 << 10).read_to_vec().map_err(io::Error::other)?; serde_json::from_slice(&body).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{url}: {e}"))) })(); match &release { @@ -83,6 +94,7 @@ pub fn latest() -> io::Result { } /// The running Kiri.app. +#[cfg(target_os = "macos")] pub fn app() -> io::Result { let exe = std::env::current_exe()?.canonicalize()?; let app = exe.ancestors().find(|p| p.extension().is_some_and(|e| e == "app")).map(Path::to_path_buf); @@ -91,6 +103,7 @@ pub fn app() -> io::Result { /// `.kiri-update/` beside the app: on the same volume, so installing is a /// rename. +#[cfg(target_os = "macos")] fn stage_dir(app: &Path) -> io::Result { Ok(app.parent().ok_or_else(|| io::Error::other("Kiri.app has no parent directory"))?.join(".kiri-update")) } @@ -98,6 +111,7 @@ fn stage_dir(app: &Path) -> io::Result { /// Downloads `release`, checks it and stages it for `install_staged`. /// `progress` gets the bytes so far and the total when the server says; /// setting `cancel` stops the download. +#[cfg(target_os = "macos")] pub fn download(release: &Release, progress: &mut dyn FnMut(u64, Option), cancel: &AtomicBool) -> io::Result<()> { let app = app()?; if !newer(&release.version, env!("CARGO_PKG_VERSION")) { @@ -119,6 +133,7 @@ pub fn download(release: &Release, progress: &mut dyn FnMut(u64, Option), c result } +#[cfg(target_os = "macos")] fn fetch_and_check(release: &Release, app: &Path, dir: &Path, progress: &mut dyn FnMut(u64, Option), cancel: &AtomicBool) -> io::Result<()> { // Download, hashing as it streams to disk. let tgz = dir.join("Kiri.tar.gz"); @@ -163,6 +178,7 @@ fn fetch_and_check(release: &Release, app: &Path, dir: &Path, progress: &mut dyn } /// The staged update's version, when there is one newer than this build. +#[cfg(target_os = "macos")] pub fn staged() -> Option { let dir = stage_dir(&app().ok()?).ok()?; let version = std::fs::read_to_string(dir.join("version")).ok()?.trim().to_owned(); @@ -171,6 +187,7 @@ pub fn staged() -> Option { /// Swaps the staged app in for the running one, checking it again first: /// the folder sat on disk since the download. Returns its version. +#[cfg(target_os = "macos")] pub fn install_staged() -> io::Result { let app = app()?; let dir = stage_dir(&app)?; @@ -203,6 +220,7 @@ pub fn install_staged() -> io::Result { /// launchd alone (`kickstart -k`) missed the last two: the job it restarted /// found the old engine still on the socket and exited, and the old one kept /// running while the window said it had restarted. +#[cfg(target_os = "macos")] pub fn restart_engine(expect: &str) -> io::Result { crate::diag::info!("restarting the engine", version = expect); stop_engine()?; @@ -221,6 +239,7 @@ pub fn restart_engine(expect: &str) -> io::Result { /// Starts the engine if it is not running: through the LaunchAgent when it /// starts this copy of Kiri, so launchd owns the one engine there is, else /// as a child of its own session. Returns once it answers. +#[cfg(target_os = "macos")] pub fn start_engine() -> io::Result<()> { if crate::client::alive() { return Ok(()); @@ -238,12 +257,14 @@ pub fn start_engine() -> io::Result<()> { Err(io::Error::other(format!("kiri daemon did not start; see {}", log_path().display()))) } +#[cfg(target_os = "macos")] fn log_path() -> PathBuf { crate::client::socket().ok().and_then(|s| Some(s.parent()?.parent()?.join("daemon.log"))).unwrap_or_else(|| PathBuf::from("daemon.log")) } /// `kiri daemon` in its own session, so quitting the window does not take /// it down; its output goes to daemon.log. +#[cfg(target_os = "macos")] fn spawn_daemon() -> io::Result<()> { let log_file = log_path(); if let Some(dir) = log_file.parent() { @@ -266,6 +287,7 @@ fn spawn_daemon() -> io::Result<()> { /// Stops the engine on the socket, if one answers: SIGTERM (it powers the /// VM off and removes the socket), then SIGKILL if it is still there after /// 30 seconds. +#[cfg(target_os = "macos")] fn stop_engine() -> io::Result<()> { let Some(pid) = engine_pid() else { return Ok(()) }; crate::diag::info!("stopping the engine", pid = pid); @@ -286,6 +308,7 @@ fn stop_engine() -> io::Result<()> { /// The process answering on the engine's socket (macOS's LOCAL_PEERPID): /// the engine itself, however it was started. +#[cfg(target_os = "macos")] fn engine_pid() -> Option { use std::os::fd::AsRawFd; let conn = std::os::unix::net::UnixStream::connect(crate::client::socket().ok()?).ok()?; @@ -298,6 +321,7 @@ fn engine_pid() -> Option { /// The engine's version once it answers as `expect`, or the last other /// version it gave when `limit` runs out (None if it never answered). +#[cfg(target_os = "macos")] pub fn wait_for_version(expect: &str, limit: std::time::Duration) -> Option { let began = std::time::Instant::now(); let mut last = None; @@ -314,6 +338,7 @@ pub fn wait_for_version(expect: &str, limit: std::time::Duration) -> Option io::Result<()> { // A valid signature is not enough: `--verify` alone passes for any // self-consistent signature, including an attacker's own Developer ID or @@ -363,6 +388,7 @@ fn check(new_app: &Path, app: &Path, promised: &str) -> io::Result<()> { /// Whether a Mach-O executable (its first bytes) has code for this CPU: /// a thin binary of this architecture, or a universal one with a slice of it. +#[cfg(any(target_os = "macos", test))] fn runs_here(head: &[u8]) -> bool { const ARM64: u32 = 0x0100_000c; const X86_64: u32 = 0x0100_0007; @@ -370,6 +396,7 @@ fn runs_here(head: &[u8]) -> bool { has_cpu(head, want) } +#[cfg(any(target_os = "macos", test))] fn has_cpu(head: &[u8], want: u32) -> bool { let word = |at: usize, be: bool| -> Option { let b: [u8; 4] = head.get(at..at + 4)?.try_into().ok()?; @@ -393,29 +420,39 @@ pub fn run(args: &[String]) -> io::Result<()> { if crate::flavor::dev() { return Err(io::Error::other(format!("{} doesn't update itself: rebuild it with `cargo xtask app-dev`", crate::flavor::APP))); } - let current = env!("CARGO_PKG_VERSION"); let release = latest()?; + run_release(args, &release, env!("CARGO_PKG_VERSION"), &mut io::stdout()) +} + +fn run_release(args: &[String], release: &Release, current: &str, out: &mut dyn Write) -> io::Result<()> { if !newer(&release.version, current) { - println!("Kiri {current} is up to date"); + writeln!(out, "Kiri {current} is up to date")?; return Ok(()); } - println!("Kiri {} is available (this is {current}){}", release.version, if release.notes.is_empty() { String::new() } else { format!(": {}", release.notes) }); - if args.iter().any(|a| a == "--check") { - return Ok(()); + writeln!(out, "Kiri {} is available (this is {current}){}", release.version, if release.notes.is_empty() { String::new() } else { format!(": {}", release.notes) })?; + #[cfg(target_os = "linux")] + { + let _ = args; + writeln!(out, "download the new .deb or .rpm from https://runkiri.com/releases/ and install it as before")?; + Ok(()) } - if cfg!(target_os = "linux") { - return Err(io::Error::other("download the new .deb or .rpm from https://runkiri.com/releases/ and install it as before")); + #[cfg(target_os = "macos")] + { + if args.iter().any(|a| a == "--check") { + return Ok(()); + } + download(release, &mut |_, _| {}, &AtomicBool::new(false))?; + let version = install_staged()?; + // The daemon runs from the app: restart it on the new binary. + restart_engine(&version)?; + writeln!(out, "updated to Kiri {version}, and the engine runs it")?; + Ok(()) } - download(&release, &mut |_, _| {}, &AtomicBool::new(false))?; - let version = install_staged()?; - // The daemon runs from the app: restart it on the new binary. - restart_engine(&version)?; - println!("updated to Kiri {version}, and the engine runs it"); - Ok(()) } /// `CFBundleShortVersionString` from an Info.plist: the key, then the next /// ``. The file is our own (xtask writes it as XML), so a scan does. +#[cfg(any(target_os = "macos", test))] fn bundle_version(plist: &str) -> Option { const KEY: &str = "CFBundleShortVersionString"; let after = &plist[plist.find(KEY)? + KEY.len()..]; @@ -426,7 +463,30 @@ fn bundle_version(plist: &str) -> Option { #[cfg(test)] mod tests { - use super::{Release, bundle_version, has_cpu, newer, runs_here}; + use std::io::{self, Read, Write}; + use std::net::TcpListener; + + use super::{Release, bundle_version, has_cpu, latest_from, newer, run_release, runs_here}; + + fn run_with(args: &[String], url: &str, current: &str, out: &mut dyn Write) -> io::Result<()> { + let release = latest_from(url)?; + run_release(args, &release, current, out) + } + + fn serve_feed(status: &'static str, body: &'static str) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut req = [0u8; 1024]; + let _ = stream.read(&mut req); + let resp = format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + let _ = stream.write_all(resp.as_bytes()); + let _ = stream.flush(); + } + }); + format!("http://{addr}/latest.json") + } #[test] fn compares_versions() { @@ -473,4 +533,48 @@ mod tests { let r: Release = serde_json::from_str(r###"{"version":"0.1.5","url":"u","sha256":"ab","notes":"## New\n- a line"}"###).unwrap(); assert_eq!(r.notes, "## New\n- a line"); } + + #[test] + fn reports_up_to_date_when_feed_is_not_newer() { + let url = serve_feed("200 OK", r#"{"version":"0.0.1","url":"https://runkiri.com/download","sha256":""}"#); + let mut out = Vec::new(); + run_with(&["--check".into()], &url, "0.2.0", &mut out).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "Kiri 0.2.0 is up to date\n"); + + let url = serve_feed("200 OK", r#"{"version":"0.0.0","url":"https://runkiri.com/download","sha256":""}"#); + let mut out = Vec::new(); + run_with(&["--check".into()], &url, env!("CARGO_PKG_VERSION"), &mut out).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), format!("Kiri {} is up to date\n", env!("CARGO_PKG_VERSION"))); + } + + #[test] + fn reports_newer_version_from_feed() { + let url = serve_feed("200 OK", r#"{"version":"99.0.0","url":"https://runkiri.com/download","sha256":""}"#); + let mut out = Vec::new(); + run_with(&["--check".into()], &url, env!("CARGO_PKG_VERSION"), &mut out).unwrap(); + let text = String::from_utf8(out).unwrap(); + assert!(text.starts_with(&format!("Kiri 99.0.0 is available (this is {})\n", env!("CARGO_PKG_VERSION"))), "got {text:?}"); + if cfg!(target_os = "linux") { + assert!(text.contains("download the new .deb or .rpm from https://runkiri.com/releases/ and install it as before\n"), "got {text:?}"); + } + } + + #[test] + fn rejects_malformed_json_and_http_500() { + let bad_json = serve_feed("200 OK", "{not json"); + let err = latest_from(&bad_json).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + + let err_500 = serve_feed("500 Internal Server Error", r#"{"error":"boom"}"#); + assert!(latest_from(&err_500).is_err()); + } + + #[test] + fn routes_container_update_to_docker_and_self_update_to_kiri() { + let a = |v: &[&str]| v.iter().map(|s| (*s).to_owned()).collect::>(); + assert!(crate::docker::is_container_update(&a(&["--memory", "128m", "c1"]))); + assert!(crate::docker::is_container_update(&a(&["--cpus", "2", "my-ctr"]))); + assert!(!crate::docker::is_container_update(&a(&["--check"]))); + assert!(!crate::docker::is_container_update(&a(&[]))); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 445df8a0e..ffcc66daa 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,12 +13,17 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### #749 Linux: `kiri update --check` checks the release feed instead of falling through to `docker update` (unreleased) +- Fixes: #749 Linux: `kiri update --check` falls through to `docker update` + ### #435 Mac: hand the VM its network settings directly when DHCP does not answer (unreleased) - Fixes: #435 Containers have no internet: VM never gets IPv4/uplink lease when another app binds UDP 67 - Caused: none known - Caused by: - - Check: none + + ### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known From 6d8928bc99061df950928b2ce123a15ea1e35d5d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:46:34 +0100 Subject: [PATCH 036/157] CLI: add kiri scan vulnerability scanner subcommand (#472) (#818) Co-authored-by: Chukwuebuka (Gaus Octavio) <56232734+Chukwuebuka-2003@users.noreply.github.com> --- crates/kiri/src/client.rs | 15 +- crates/kiri/src/main.rs | 17 ++ crates/kiri/src/scan.rs | 263 ++++++++++++++++--- crates/kiri/src/scan_cli.rs | 490 ++++++++++++++++++++++++++++++++++++ crates/kiri/src/wsl.rs | 17 +- docs/features.md | 8 + 6 files changed, 770 insertions(+), 40 deletions(-) create mode 100644 crates/kiri/src/scan_cli.rs diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index d0fb0a493..29d5a218c 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -167,12 +167,23 @@ pub fn alive() -> bool { /// `auth` is a registry sign-in for a pull (`X-Registry-Auth`, base64url). /// `opened` gets the connection once it is made, so another thread can /// shut it down to stop the request (Cancel on a pull). -pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { +pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), on_line: impl FnMut(Value)) -> io::Result { + post_lines_inner(path, auth, Some(Duration::from_secs(120)), opened, on_line) +} + +/// Like `post_lines_closable` without a read timeout, for long-running +/// streamed operations such as `/kiri/images/scan` (first-time DB download). +#[cfg(target_os = "linux")] +pub fn post_lines_unbounded(path: &str, on_line: impl FnMut(Value)) -> io::Result { + post_lines_inner(path, None, None, |_| {}, on_line) +} + +fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { if auth.is_some_and(|a| a.contains(['\r', '\n'])) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); } let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); - let mut s = connect(Some(Duration::from_secs(120)))?; + let mut s = connect(timeout)?; opened(&s); write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", crate::diag::op_header())?; let mut r = BufReader::new(s); diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index c8cd4d247..182a540dd 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -62,6 +62,9 @@ mod run; #[cfg(unix)] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod scan; +// `kiri scan`: vulnerability scanning from the terminal (Windows: in WSL). +#[cfg(unix)] +mod scan_cli; #[cfg(target_os = "macos")] mod setup; #[cfg(unix)] @@ -91,6 +94,7 @@ usage: kiri COMMAND docker's commands, on Kiri: kiri run, ps, exec, kiri build-with [docker|kiri] which builder docker build uses kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors + kiri scan [--json] [--history] known vulnerabilities in an image, found by Grype kiri update [--check] update Kiri (with a container: docker's update) kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N] kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out) @@ -168,6 +172,8 @@ fn main() -> ExitCode { #[cfg(unix)] Some("registry") => registry_cli::run(&args[1..]), #[cfg(unix)] + Some("scan") => scan_cli::run(&args[1..]), + #[cfg(unix)] Some("k8s") => k8s::run(&args[1..]), #[cfg(unix)] Some("machine") => machine::run(&args[1..]), @@ -275,3 +281,14 @@ fn engine_version_check() { eprintln!("kiri: this kiri ({exe}) is {me}, but the engine runs {engine}. Restart the engine to use one version (Kiri → Restart engine), or remove the older kiri."); } } + +#[cfg(test)] +mod tests { + use super::USAGE; + + #[test] + fn usage_lists_scan_command() { + assert!(USAGE.contains("kiri scan [--json] [--history] ")); + assert!(!USAGE.ends_with('\n')); + } +} diff --git a/crates/kiri/src/scan.rs b/crates/kiri/src/scan.rs index 3c90150c3..dc3cdd11b 100644 --- a/crates/kiri/src/scan.rs +++ b/crates/kiri/src/scan.rs @@ -42,16 +42,37 @@ fn root() -> io::Result { kiri_image::Store::default_root() } -fn grype() -> io::Result { - Ok(root()?.join("scanner/grype")) +fn grype_in(root: &Path) -> PathBuf { + root.join("scanner/grype") } /// Scans kept per image. const KEEP: usize = 20; /// An image's scans, one folder each: Grype's JSON report, the SBOM and a summary. -fn scan_dir(config_digest: &str) -> io::Result { - Ok(root()?.join("scans").join(kiri_image::store::digest_hex(config_digest)?)) +fn scan_dir_in(root: &Path, config_digest: &str) -> io::Result { + Ok(root.join("scans").join(kiri_image::store::digest_hex(config_digest)?)) +} + +/// Strips ANSI CSI escape sequences (`\x1b[...`) from a line. +pub(crate) fn strip_ansi(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + if chars.peek() == Some(&'[') { + chars.next(); + for n in chars.by_ref() { + if ('@'..='~').contains(&n) { + break; + } + } + } + } else { + out.push(c); + } + } + out } /// The image's scans, newest first, by their time. A scan kept before there @@ -74,10 +95,10 @@ fn scan_times(dir: &Path) -> Vec { } /// Grype's environment: its own database folder, no update nag, Kiri's proxy. -fn command(args: &[&str]) -> io::Result { - let mut c = Command::new(grype()?); +fn command_in(root: &Path, args: &[&str]) -> Command { + let mut c = Command::new(grype_in(root)); c.args(args) - .env("GRYPE_DB_CACHE_DIR", root()?.join("scanner/db")) + .env("GRYPE_DB_CACHE_DIR", root.join("scanner/db")) .env("GRYPE_CHECK_FOR_APP_UPDATE", "false"); let p = crate::daemon::proxy::effective(); if let Some(u) = &p.https { @@ -89,7 +110,7 @@ fn command(args: &[&str]) -> io::Result { if !p.no_proxy.is_empty() { c.env("NO_PROXY", p.no_proxy.join(",")); } - Ok(c) + c } fn run(mut c: Command, what: &str) -> io::Result<()> { @@ -98,14 +119,19 @@ fn run(mut c: Command, what: &str) -> io::Result<()> { return Ok(()); } let err = String::from_utf8_lossy(&out.stderr); - // Grype's log lines carry colour codes; keep the last plain line. - let line = err.lines().rev().map(|l| l.replace('\u{1b}', "")).map(|l| l.trim_start_matches(|c: char| c == '[' || c.is_ascii_digit() || c == ';' || c == 'm').to_string()).find(|l| !l.trim().is_empty()).unwrap_or_default(); - Err(io::Error::other(format!("{what}: {}", line.trim()))) + // Grype's log lines carry colour codes; keep the last plain line, redacted. + let line = err.lines().rev().map(strip_ansi).find(|l| !l.trim().is_empty()).unwrap_or_default(); + let msg = crate::diag::redact::Redactor::home_only().apply(line.trim()); + if msg.is_empty() { + Err(io::Error::other(what.to_owned())) + } else { + Err(io::Error::other(format!("{what}: {msg}"))) + } } /// Downloads Grype if it isn't there yet, checked against its pinned SHA-256. -fn ensure_grype(progress: &mut dyn FnMut(u8)) -> io::Result<()> { - let dest = grype()?; +fn ensure_grype_in(root: &Path, progress: &mut dyn FnMut(u8)) -> io::Result<()> { + let dest = grype_in(root); if dest.is_file() { return Ok(()); } @@ -168,7 +194,11 @@ fn layout(store: &kiri_image::Store, i: &kiri_image::Image, to: &Path) -> io::Re /// Scans the image (a name or an ID). `progress(phase, percent)`, with phase /// "scanner" (downloading Grype), "database" or "scanning". pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { - let store = kiri_image::Store::open(root()?)?; + scan_in(&root()?, name, progress) +} + +fn scan_in(root: &Path, name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + let store = kiri_image::Store::open(root)?; let (i, ..) = crate::builds::stored(&store, name)?; { let mut r = RUNNING.lock().unwrap(); @@ -177,19 +207,19 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result } } let result = (|| { - ensure_grype(&mut |pct| progress("scanner", pct))?; + ensure_grype_in(root, &mut |pct| progress("scanner", pct))?; progress("database", 0); - let has_db = root()?.join("scanner/db").read_dir().is_ok_and(|mut d| d.next().is_some()); + let has_db = root.join("scanner/db").read_dir().is_ok_and(|mut d| d.next().is_some()); // Offline with a database already here: scan with what's here, and // Grype says so itself if it's too old. - if let Err(e) = run(command(&["db", "update", "-q"])?, "Could not update the vulnerability database") { - if !has_db { - return Err(e); - } + if let Err(e) = run(command_in(root, &["db", "update", "-q"]), "Could not update the vulnerability database") + && !has_db + { + return Err(e); } progress("scanning", 0); let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let dir = scan_dir(&i.config_digest)?.join(at.to_string()); + let dir = scan_dir_in(root, &i.config_digest)?.join(at.to_string()); std::fs::create_dir_all(&dir)?; let tmp = store.root().join("tmp").join(format!("scan-{}-{}", std::process::id(), kiri_image::store::digest_hex(&i.config_digest)?)); let _ = std::fs::remove_dir_all(&tmp); @@ -197,11 +227,9 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result let report = dir.join("grype.json.part"); let sbom = dir.join("sbom.cdx.json.part"); let target = format!("oci-dir:{}", tmp.display()); - let out = (|| { - let mut c = command(&["-q", &target, "-o", &format!("json={}", report.display()), "-o", &format!("cyclonedx-json={}", sbom.display())])?; - c.env("GRYPE_DB_AUTO_UPDATE", "false"); - run(c, "The scan failed") - })(); + let mut c = command_in(root, &["-q", &target, "-o", &format!("json={}", report.display()), "-o", &format!("cyclonedx-json={}", sbom.display())]); + c.env("GRYPE_DB_AUTO_UPDATE", "false"); + let out = run(c, "The scan failed"); let _ = std::fs::remove_dir_all(&tmp); if let Err(e) = out { let _ = std::fs::remove_dir_all(&dir); @@ -209,12 +237,14 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result } std::fs::rename(&report, dir.join("grype.json"))?; std::fs::rename(&sbom, dir.join("sbom.cdx.json"))?; + // Invalidate any cached summary if a second scan ran in the same second. + let _ = std::fs::remove_file(dir.join("summary.json")); // Only the newest KEEP. - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; for old in scan_times(&all).into_iter().skip(KEEP) { let _ = std::fs::remove_dir_all(all.join(old.to_string())); } - open(name, Some(at))?.ok_or_else(|| io::Error::other("the scan wrote no report")) + open_in(root, name, Some(at))?.ok_or_else(|| io::Error::other("the scan wrote no report")) })(); RUNNING.lock().unwrap().as_mut().map(|r| r.remove(&i.config_digest)); result @@ -223,16 +253,20 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result /// The image's scans for the history list, newest first: when, the count /// per severity, how many have a fix. Each summary is worked out once and kept. pub fn history(name: &str) -> io::Result { - let store = kiri_image::Store::open(root()?)?; + history_in(&root()?, name) +} + +fn history_in(root: &Path, name: &str) -> io::Result { + let store = kiri_image::Store::open(root)?; let (i, ..) = crate::builds::stored(&store, name)?; - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; let mut list = Vec::new(); for at in scan_times(&all) { let path = all.join(at.to_string()).join("summary.json"); let summary = match std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::(&b).ok()) { Some(v) => v, None => { - let Some(full) = open(name, Some(at))? else { continue }; + let Some(full) = open_in(root, name, Some(at))? else { continue }; let mut counts = serde_json::Map::new(); for v in full["vulns"].as_array().into_iter().flatten() { let k = v["severity"].as_str().unwrap_or("Unknown").to_owned(); @@ -254,9 +288,13 @@ pub fn history(name: &str) -> io::Result { /// One of the image's scans in full (the newest when `at` is None), or None /// if it has none. pub fn open(name: &str, at: Option) -> io::Result> { - let store = kiri_image::Store::open(root()?)?; + open_in(&root()?, name, at) +} + +fn open_in(root: &Path, name: &str, at: Option) -> io::Result> { + let store = kiri_image::Store::open(root)?; let (i, manifest, config) = crate::builds::stored(&store, name)?; - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; let Some(when) = at.or_else(|| scan_times(&all).first().copied()) else { return Ok(None) }; let dir = all.join(when.to_string()); let Ok(raw) = std::fs::read(dir.join("grype.json")) else { return Ok(None) }; @@ -313,9 +351,10 @@ fn summarize(report: &Value, lines: &[Value], config: &Value) -> Value { /// One scan's SBOM, where it's kept. pub fn sbom(name: &str, at: u64) -> io::Result { - let store = kiri_image::Store::open(root()?)?; + let root = root()?; + let store = kiri_image::Store::open(&root)?; let (i, ..) = crate::builds::stored(&store, name)?; - let from = scan_dir(&i.config_digest)?.join(at.to_string()).join("sbom.cdx.json"); + let from = scan_dir_in(&root, &i.config_digest)?.join(at.to_string()).join("sbom.cdx.json"); if !from.is_file() { return Err(io::Error::other("scan the image first")); } @@ -368,6 +407,160 @@ mod tests { assert_eq!((v[1]["layer"].as_u64(), v[1]["base"].as_bool(), v[1]["fixed"].as_array().map(Vec::len)), (Some(0), Some(true), Some(0))); } + #[test] + fn grype_pins_and_urls_cover_macos_and_linux() { + for (v, sum) in [GRYPE, cli_pins::LINUX_GRYPE, cli_pins::LINUX_ARM64_GRYPE] { + assert!(!v.is_empty()); + assert_eq!(sum.len(), 64); + assert!(sum.bytes().all(|b| b.is_ascii_hexdigit())); + } + assert!(grype_url(GRYPE.0).starts_with("https://github.com/anchore/grype/releases/download/v")); + assert_eq!( + cli_pins::linux_grype_url("0.120.1", "amd64"), + "https://github.com/anchore/grype/releases/download/v0.120.1/grype_0.120.1_linux_amd64.tar.gz" + ); + assert_eq!( + cli_pins::linux_grype_url("0.120.1", "arm64"), + "https://github.com/anchore/grype/releases/download/v0.120.1/grype_0.120.1_linux_arm64.tar.gz" + ); + } + + #[test] + fn strips_ansi_and_redacts_failed_grype_output() { + assert_eq!(strip_ansi("\x1b[31merror:\x1b[0m failed to fetch \x1b[1mdb\x1b[0m"), "error: failed to fetch db"); + let mut c = Command::new("/bin/sh"); + c.args(["-c", "printf '\\033[31mproxy failed: http://bob:hunter2@proxy.example:3128\\033[0m\\n' >&2; exit 1"]); + let err = run(c, "The scan failed").unwrap_err().to_string(); + assert!(err.starts_with("The scan failed: "), "{err}"); + assert!(!err.contains("hunter2"), "secret leaked: {err}"); + assert!(!err.contains('\x1b'), "ANSI leaked: {err}"); + assert!(err.contains("http://[redacted]@proxy.example:3128"), "{err}"); + } + + #[test] + fn scan_open_and_history_end_to_end_with_mock_grype() { + use std::os::unix::fs::PermissionsExt; + + let dir = std::env::temp_dir().join(format!("kiri-scan-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + + let layer_bytes = b"fake-layer-tar-bytes"; + let layer_digest = kiri_image::store::sha256_digest(layer_bytes); + std::fs::write(store.blob_path(&layer_digest).unwrap(), layer_bytes).unwrap(); + + let config_bytes = serde_json::to_vec(&json!({ + "architecture": "arm64", + "os": "linux", + "created": "2026-11-16T20:00:00Z", + "rootfs": {"type": "layers", "diff_ids": ["sha256:diff0"]}, + "history": [{"created": "2026-11-16T20:00:00Z", "created_by": "ADD rootfs /"}] + })) + .unwrap(); + let config_digest = kiri_image::store::sha256_digest(&config_bytes); + std::fs::write(store.blob_path(&config_digest).unwrap(), &config_bytes).unwrap(); + + store + .put_image(kiri_image::Image { + name: "demo:1".to_owned(), + digest: config_digest.clone(), + index_digest: None, + config_digest: config_digest.clone(), + layers: vec![kiri_image::Layer { + digest: layer_digest, + size: layer_bytes.len() as u64, + media_type: "application/vnd.oci.image.layer.v1.tar+gzip".to_owned(), + }], + size: layer_bytes.len() as u64, + platform: "linux/arm64".to_owned(), + created: "2026-11-16T20:00:00Z".to_owned(), + pulled_at: 1_794_859_620, + config: kiri_image::RunConfig::default(), + mirror: None, + }) + .unwrap(); + + let scanner = dir.join("scanner"); + std::fs::create_dir_all(scanner.join("db")).unwrap(); + let mock = scanner.join("grype"); + let script = r#"#!/bin/sh +set -eu +if [ "${1:-}" = "db" ] && [ "${2:-}" = "update" ]; then + exit 0 +fi +oci="" +json_out="" +sbom_out="" +while [ $# -gt 0 ]; do + case "$1" in + oci-dir:*) oci="${1#oci-dir:}" ;; + -o) + shift + case "$1" in + json=*) json_out="${1#json=}" ;; + cyclonedx-json=*) sbom_out="${1#cyclonedx-json=}" ;; + esac + ;; + esac + shift +done +[ -f "$oci/oci-layout" ] && [ -f "$oci/index.json" ] +cat > "$json_out" <<'EOF' +{ + "descriptor": {"db": {"status": {"built": "2026-11-16T00:00:00Z"}}}, + "matches": [ + { + "vulnerability": {"id": "CVE-2026-1001", "severity": "Critical", "fix": {"state": "fixed", "versions": ["3.1.1"]}, "dataSource": "https://nvd.nist.gov/vuln/detail/CVE-2026-1001", "description": "critical bug"}, + "artifact": {"name": "openssl", "version": "3.1.0", "type": "apk", "locations": [{"layerID": "sha256:diff0"}]} + }, + { + "vulnerability": {"id": "CVE-2026-1002", "severity": "Negligible", "fix": {"state": "not-fixed"}, "dataSource": "https://nvd.nist.gov/vuln/detail/CVE-2026-1002", "description": "minor"}, + "artifact": {"name": "musl", "version": "1.2.4", "type": "apk", "locations": [{"layerID": "sha256:diff0"}]} + } + ] +} +EOF +cat > "$sbom_out" <<'EOF' +{"components": [{"name": "openssl"}, {"name": "musl"}, {"name": "busybox"}]} +EOF +"#; + std::fs::write(&mock, script).unwrap(); + std::fs::set_permissions(&mock, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let mut phases = Vec::new(); + let report = scan_in(&dir, "demo:1", &mut |phase, pct| phases.push((phase.to_owned(), pct))).unwrap(); + assert!(phases.iter().any(|(p, _)| p == "database"), "{phases:?}"); + assert!(phases.iter().any(|(p, _)| p == "scanning"), "{phases:?}"); + + // `--json` output from `scan` must match `GET /kiri/images/scan` (`open`). + let opened = open_in(&dir, "demo:1", None).unwrap().unwrap(); + assert_eq!(report, opened); + assert_eq!(report["id"], config_digest); + assert_eq!(report["packages"], 3); + assert_eq!(report["db"], "2026-11-16T00:00:00Z"); + assert_eq!(report["grype"], GRYPE.0); + assert_eq!(report["vulns"].as_array().unwrap().len(), 2); + + let table = crate::scan_cli::format_report("demo:1", &report).unwrap(); + assert!(table.contains("demo:1: 3 packages, 2 findings, 1 with a fix available, database built 2026-11-16T00:00:00Z"), "{table}"); + assert!(table.contains("1 Critical, 1 Negligible"), "{table}"); + assert!(table.contains("fixed in 3.1.1"), "{table}"); + + let hist = history_in(&dir, "demo:1").unwrap(); + assert_eq!(hist["id"], config_digest); + assert_eq!(hist["scans"].as_array().unwrap().len(), 1); + let hist_table = crate::scan_cli::format_history(&hist).unwrap(); + assert!(hist_table.contains("1 Critical, 1 Negligible"), "{hist_table}"); + + // Missing image gives a clear error. + let missing = scan_in(&dir, "no-such-image:latest", &mut |_, _| {}).unwrap_err().to_string(); + assert_eq!(missing, "no image no-such-image:latest in Kiri"); + let missing_hist = history_in(&dir, "no-such-image:latest").unwrap_err().to_string(); + assert_eq!(missing_hist, "no image no-such-image:latest in Kiri"); + + let _ = std::fs::remove_dir_all(&dir); + } + /// A real scan of an image in a real store, Grype and its database downloaded on first use: /// `KIRI_LIVE_IMAGE=alpine:latest KIRI_DATA_DIR=... cargo test -p kiri scan_live -- --ignored --nocapture`. #[test] diff --git a/crates/kiri/src/scan_cli.rs b/crates/kiri/src/scan_cli.rs new file mode 100644 index 000000000..fff4f1d82 --- /dev/null +++ b/crates/kiri/src/scan_cli.rs @@ -0,0 +1,490 @@ +//! `kiri scan `: scan an image in Kiri's store for known +//! vulnerabilities from the terminal. The same scan the window's Security +//! tab runs (`crate::scan`): Grype reads the image through an OCI layout of +//! the store's own blobs, so the VM isn't woken and nothing is uploaded. +//! The first scan downloads Grype and its database (about 230 MB, 3 GB +//! unpacked), kept for every scan after. +//! +//! On Windows this runs inside WSL by the engine's own `kiri` (`wsl.rs`). +//! On a Linux host running the `kiri` system service (`/run/kiri/docker.sock`), +//! a user without direct access to `/var/lib/kiri-daemon` scans through the +//! daemon's `/kiri/images/scan` and `/kiri/images/scans` endpoints. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::io; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Map, Value}; + +const USAGE: &str = "usage: kiri scan [--json] [--history] "; + +const SEVERITIES: [&str; 6] = ["Critical", "High", "Medium", "Low", "Negligible", "Unknown"]; + +#[derive(Debug, PartialEq, Eq)] +enum Action { + Help, + Scan { image: String, json: bool }, + History { image: String, json: bool }, +} + +fn invalid(msg: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidInput, msg.into()) +} + +fn parse(args: &[String]) -> Result { + let mut json = false; + let mut history = false; + let mut names: Vec = Vec::new(); + for a in args { + match a.as_str() { + "--json" => json = true, + "--history" => history = true, + "-h" | "--help" => return Ok(Action::Help), + s if s.starts_with('-') => return Err(format!("unknown flag {s}; {USAGE}")), + s if s.trim().is_empty() => return Err(USAGE.to_owned()), + s => names.push(s.to_owned()), + } + } + let Some(image) = names.first().cloned() else { + return Err(USAGE.to_owned()); + }; + if names.len() > 1 { + return Err(format!("one image at a time; {USAGE}")); + } + if history { + Ok(Action::History { image, json }) + } else { + Ok(Action::Scan { image, json }) + } +} + +/// Strips ANSI CSI escape sequences and control characters from untrusted +/// image metadata before printing to a terminal. +fn sanitize(s: &str) -> String { + let stripped = crate::scan::strip_ansi(s); + let mut out = String::with_capacity(stripped.len()); + for c in stripped.chars() { + if c == '\r' || c == '\n' || c == '\t' { + out.push(' '); + } else if !c.is_control() { + out.push(c); + } + } + out +} + +/// When a scan was run, in UTC for the history table: `2026-11-16 20:07 UTC`. +fn stamp(at: u64) -> String { + let Some(t) = UNIX_EPOCH.checked_add(Duration::from_secs(at)) else { + return at.to_string(); + }; + let r = crate::daemon::time::rfc3339(t); + match r.get(..16) { + Some(prefix) => format!("{} UTC", prefix.replace('T', " ")), + None => r, + } +} + +/// Formats severity counts worst-first (`1 Critical, 3 Medium`) or +/// `no vulnerabilities found` when none are present. +fn format_counts(mut counts: BTreeMap) -> String { + let mut parts = Vec::new(); + for s in SEVERITIES { + if let Some(n) = counts.remove(s).filter(|&n| n > 0) { + parts.push(format!("{n} {s}")); + } + } + // Any severity Grype may add later, sorted after the known list. + for (s, n) in counts { + if n > 0 { + parts.push(format!("{n} {}", sanitize(&s))); + } + } + if parts.is_empty() { + "no vulnerabilities found".to_owned() + } else { + parts.join(", ") + } +} + +/// The severity counts from a report's `vulns` list, worst first. +fn count_line(vulns: &[Value]) -> String { + let mut counts = BTreeMap::new(); + for v in vulns { + let s = v["severity"].as_str().unwrap_or("Unknown").to_owned(); + *counts.entry(s).or_insert(0u64) += 1; + } + format_counts(counts) +} + +/// The severity counts from a saved history summary's `counts` object, worst first. +fn count_line_from_map(map: Option<&Map>) -> String { + let mut counts = BTreeMap::new(); + if let Some(obj) = map { + for (k, v) in obj { + if let Some(n) = v.as_u64() + && n > 0 + { + *counts.entry(k.clone()).or_insert(0u64) += n; + } + } + } + format_counts(counts) +} + +/// Formats `scan::history`'s output as a table, newest scan first. +pub(crate) fn format_history(h: &Value) -> io::Result { + let scans = h["scans"].as_array().ok_or_else(|| io::Error::other("no scans"))?; + if scans.is_empty() { + return Ok("no scans yet\n".to_owned()); + } + let rows: Vec<(String, String, u64, u64, u64)> = scans + .iter() + .map(|s| { + ( + stamp(s["scanned"].as_u64().unwrap_or(0)), + count_line_from_map(s["counts"].as_object()), + s["vulns"].as_u64().unwrap_or(0), + s["fixable"].as_u64().unwrap_or(0), + s["packages"].as_u64().unwrap_or(0), + ) + }) + .collect(); + let w_scanned = rows.iter().map(|r| r.0.len()).max().unwrap_or(0).max("scanned".len()); + let w_found = rows.iter().map(|r| r.1.len()).max().unwrap_or(0).max("found".len()); + let mut out = String::new(); + let _ = writeln!(out, "{:6} {:>7} {:>8}", "scanned", "found", "vulns", "fixable", "packages"); + for (when, counts, vulns, fixable, packages) in rows { + let _ = writeln!(out, "{when:6} {fixable:>7} {packages:>8}"); + } + Ok(out) +} + +/// Formats `scan::scan`'s report: summary counts first, then one aligned row +/// per finding, worst severity first as `crate::scan` ordered them. +pub(crate) fn format_report(name: &str, report: &Value) -> io::Result { + let vulns = report["vulns"].as_array().ok_or_else(|| io::Error::other("the scan wrote no report"))?; + let packages = report["packages"].as_u64().unwrap_or(0); + let fixable = vulns.iter().filter(|v| v["fixed"].as_array().is_some_and(|f| !f.is_empty())).count(); + let db = sanitize(report["db"].as_str().unwrap_or("")); + let display_name = sanitize(name); + let mut out = String::new(); + let _ = write!( + out, + "{display_name}: {packages} package{}, {} finding{}, {fixable} with a fix available", + if packages == 1 { "" } else { "s" }, + vulns.len(), + if vulns.len() == 1 { "" } else { "s" }, + ); + if !db.is_empty() { + let _ = write!(out, ", database built {db}"); + } + out.push('\n'); + let _ = writeln!(out, "{}", count_line(vulns)); + if vulns.is_empty() { + return Ok(out); + } + let rows: Vec<[String; 5]> = vulns + .iter() + .map(|v| { + let sev = sanitize(v["severity"].as_str().unwrap_or("Unknown")); + let id = sanitize(v["id"].as_str().unwrap_or("")); + let pkg = sanitize(v["package"].as_str().unwrap_or("")); + let kind = sanitize(v["kind"].as_str().unwrap_or("")); + let package = if kind.is_empty() { pkg } else { format!("{pkg} ({kind})") }; + let version = sanitize(v["version"].as_str().unwrap_or("")); + let fixed: Vec = v["fixed"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(sanitize) + .filter(|s| !s.is_empty()) + .collect(); + let fix = if fixed.is_empty() { "-".to_owned() } else { format!("fixed in {}", fixed.join(", ")) }; + [sev, id, package, version, fix] + }) + .collect(); + let w0 = rows.iter().map(|r| r[0].len()).max().unwrap_or(0).max("severity".len()); + let w1 = rows.iter().map(|r| r[1].len()).max().unwrap_or(0).max("vulnerability".len()); + let w2 = rows.iter().map(|r| r[2].len()).max().unwrap_or(0).max("package".len()); + let w3 = rows.iter().map(|r| r[3].len()).max().unwrap_or(0).max("version".len()); + out.push('\n'); + let _ = writeln!(out, "{: bool { + std::env::var_os("KIRI_DATA_DIR").is_none() + && std::env::var_os("KIRI_SOCKET").is_none() + && std::env::var_os("HOME").as_deref() != Some(std::ffi::OsStr::new("/var/lib/kiri-daemon")) + && std::path::Path::new(crate::client::SERVICE_SOCKET).exists() + && crate::client::alive() +} + +#[cfg(target_os = "linux")] +fn query_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + let _ = write!(out, "%{b:02X}"); + } + } + out +} + +#[cfg(target_os = "linux")] +fn daemon_history(name: &str) -> io::Result { + crate::client::get(&format!("/kiri/images/scans?name={}", query_escape(name))) +} + +#[cfg(target_os = "linux")] +fn daemon_scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + let mut end = None; + let status = crate::client::post_lines_unbounded(&format!("/kiri/images/scan?name={}", query_escape(name)), |v| { + if let Some(phase) = v["phase"].as_str() { + progress(phase, v["pct"].as_u64().unwrap_or(0).min(100) as u8); + } else if let Some(e) = v["error"].as_str() { + end = Some(Err(io::Error::other(e.to_owned()))); + } else if let Some(m) = v["message"].as_str() { + end = Some(Err(io::Error::other(m.to_owned()))); + } else if v.get("result").is_some() { + end = Some(Ok(v["result"].clone())); + } + })?; + if !(200..300).contains(&status) { + return Err(io::Error::other(format!("scan failed (HTTP {status})"))); + } + end.unwrap_or_else(|| Err(io::Error::other("the scan stopped before it finished"))) +} + +fn run_history(name: &str) -> io::Result { + #[cfg(target_os = "linux")] + if use_service_daemon() { + return daemon_history(name); + } + crate::scan::history(name) +} + +fn run_scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + #[cfg(target_os = "linux")] + if use_service_daemon() { + return daemon_scan(name, progress); + } + crate::scan::scan(name, progress) +} + +/// Runs `kiri scan [--json] [--history] `. +pub fn run(args: &[String]) -> io::Result<()> { + match parse(args).map_err(invalid)? { + Action::Help => { + println!( + "{USAGE}\n --json the full report, as JSON\n --history the image's kept scans, newest first, without scanning again" + ); + Ok(()) + } + Action::History { image, json } => { + let h = run_history(&image)?; + if json { + println!("{}", serde_json::to_string_pretty(&h).map_err(io::Error::other)?); + return Ok(()); + } + print!("{}", format_history(&h)?); + Ok(()) + } + Action::Scan { image, json } => { + let mut last = (String::new(), 255u8); + let report = run_scan(&image, &mut |phase, pct| { + if (pct == 0 || pct == 100) && (phase, pct) != (last.0.as_str(), last.1) { + last = (phase.to_owned(), pct); + eprintln!("{phase} {pct}%"); + } + })?; + if json { + println!("{}", serde_json::to_string_pretty(&report).map_err(io::Error::other)?); + return Ok(()); + } + print!("{}", format_report(&image, &report)?); + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn argv(s: &str) -> Vec { + s.split_whitespace().map(String::from).collect() + } + + #[test] + fn parses_scan_flags_and_image() { + assert_eq!(parse(&argv("alpine:latest")), Ok(Action::Scan { image: "alpine:latest".into(), json: false })); + assert_eq!(parse(&argv("--json alpine:latest")), Ok(Action::Scan { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("alpine:latest --json")), Ok(Action::Scan { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("--history alpine:latest")), Ok(Action::History { image: "alpine:latest".into(), json: false })); + assert_eq!(parse(&argv("--history --json alpine:latest")), Ok(Action::History { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("alpine --json --history")), Ok(Action::History { image: "alpine".into(), json: true })); + assert_eq!(parse(&argv("-h")), Ok(Action::Help)); + assert_eq!(parse(&argv("--help")), Ok(Action::Help)); + } + + #[test] + fn rejects_invalid_flags_and_missing_or_extra_images() { + assert_eq!(parse(&[]).unwrap_err(), USAGE); + assert_eq!(parse(&argv("--json")).unwrap_err(), USAGE); + assert_eq!(parse(&argv("--history")).unwrap_err(), USAGE); + assert_eq!(parse(&["".to_owned()]).unwrap_err(), USAGE); + assert_eq!(parse(&[" ".to_owned()]).unwrap_err(), USAGE); + + let bad_flag = parse(&argv("--bogus alpine")).unwrap_err(); + assert!(bad_flag.starts_with("unknown flag --bogus;"), "{bad_flag}"); + assert!(bad_flag.contains(USAGE), "{bad_flag}"); + + let short_flag = parse(&argv("-q alpine")).unwrap_err(); + assert!(short_flag.starts_with("unknown flag -q;"), "{short_flag}"); + + let extra = parse(&argv("alpine nginx")).unwrap_err(); + assert!(extra.starts_with("one image at a time;"), "{extra}"); + } + + #[test] + fn not_a_docker_command() { + assert!(!crate::docker::handles("scan")); + } + + #[test] + fn counts_worst_first_and_empty() { + let vulns = json!([ + {"severity": "Negligible"}, + {"severity": "Medium"}, + {"severity": "Critical"}, + {"severity": "Low"}, + {"severity": "Medium"}, + {"severity": "High"}, + {"severity": "Unknown"}, + ]); + assert_eq!( + count_line(vulns.as_array().unwrap()), + "1 Critical, 1 High, 2 Medium, 1 Low, 1 Negligible, 1 Unknown" + ); + assert_eq!(count_line(&[]), "no vulnerabilities found"); + } + + #[test] + fn formats_report_table_all_severities_with_and_without_fixes() { + let report = json!({ + "id": "sha256:0000000000000000000000000000000000000000000000000000000000000001", + "scanned": 1_794_859_620u64, + "packages": 14, + "db": "2026-11-16T00:00:00Z", + "grype": "0.120.1", + "vulns": [ + {"id": "CVE-2026-0001", "severity": "Critical", "package": "openssl", "kind": "apk", "version": "3.1.0-r0", "fixed": ["3.1.1-r0"]}, + {"id": "CVE-2026-0002", "severity": "High", "package": "zlib", "kind": "apk", "version": "1.3.0", "fixed": ["1.3.1", "1.3.2"]}, + {"id": "CVE-2026-0003", "severity": "Medium", "package": "busybox", "kind": "apk", "version": "1.36.1", "fixed": []}, + {"id": "CVE-2026-0004", "severity": "Low", "package": "curl", "kind": "", "version": "8.4.0", "fixed": ["8.5.0"]}, + {"id": "CVE-2026-0005", "severity": "Negligible", "package": "musl", "kind": "apk", "version": "1.2.4", "fixed": []}, + ] + }); + let out = format_report("alpine:3.21", &report).unwrap(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!( + lines[0], + "alpine:3.21: 14 packages, 5 findings, 3 with a fix available, database built 2026-11-16T00:00:00Z" + ); + assert_eq!(lines[1], "1 Critical, 1 High, 1 Medium, 1 Low, 1 Negligible"); + assert_eq!(lines[2], ""); + assert!(lines[3].starts_with("severity"), "{}", lines[3]); + assert!(lines[4].contains("Critical") && lines[4].contains("CVE-2026-0001") && lines[4].contains("openssl (apk)") && lines[4].ends_with("fixed in 3.1.1-r0")); + assert!(lines[5].contains("High") && lines[5].ends_with("fixed in 1.3.1, 1.3.2")); + assert!(lines[6].contains("Medium") && lines[6].ends_with(" -")); + assert!(lines[7].contains("Low") && lines[7].contains("curl") && !lines[7].contains("curl ()") && lines[7].ends_with("fixed in 8.5.0")); + assert!(lines[8].contains("Negligible") && lines[8].ends_with(" -")); + } + + #[test] + fn formats_clean_report_and_singular_counts() { + let report = json!({ + "packages": 1, + "db": "", + "vulns": [] + }); + let out = format_report("scratch:latest", &report).unwrap(); + assert_eq!(out, "scratch:latest: 1 package, 0 findings, 0 with a fix available\nno vulnerabilities found\n"); + } + + #[test] + fn sanitizes_control_and_ansi_sequences_in_table() { + let report = json!({ + "packages": 1, + "db": "2026-11-16\x1b[31m", + "vulns": [{ + "id": "CVE-1\nFAKE", + "severity": "High", + "package": "\x1b[31mevil\x1b[0m", + "kind": "apk", + "version": "1.0\r", + "fixed": ["1.1\x07"] + }] + }); + let out = format_report("img\x1b[2J:1", &report).unwrap(); + assert!(!out.contains('\x1b'), "escape sequence leaked: {out:?}"); + assert!(!out.contains('\r'), "CR leaked: {out:?}"); + assert!(!out.contains('\x07'), "BEL leaked: {out:?}"); + assert!(out.contains("CVE-1 FAKE"), "newline not flattened: {out}"); + assert!(out.contains("evil (apk)"), "ANSI not stripped: {out}"); + } + + #[test] + fn formats_history_worst_first_and_empty() { + let empty = json!({"id": "sha256:0", "scans": []}); + assert_eq!(format_history(&empty).unwrap(), "no scans yet\n"); + + let history = json!({ + "id": "sha256:0", + "scans": [ + { + "scanned": 1_794_859_620u64, + "counts": {"Low": 1, "Critical": 2, "Medium": 3, "High": 1}, + "vulns": 7, + "fixable": 4, + "packages": 20 + }, + { + "scanned": 1_794_773_220u64, + "counts": {}, + "vulns": 0, + "fixable": 0, + "packages": 20 + } + ] + }); + let out = format_history(&history).unwrap(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!(lines.len(), 3, "{out}"); + assert!(lines[0].contains("scanned") && lines[0].contains("found") && lines[0].contains("packages")); + // Worst-first order: Critical before High before Medium before Low (not alphabetical!). + assert!(lines[1].contains("2026-11-16 20:07 UTC"), "{}", lines[1]); + assert!(lines[1].contains("2 Critical, 1 High, 3 Medium, 1 Low"), "{}", lines[1]); + assert!(lines[2].contains("no vulnerabilities found"), "{}", lines[2]); + } + + #[test] + fn stamp_never_panics_on_extreme_values() { + assert_eq!(stamp(0), "1970-01-01 00:00 UTC"); + assert_eq!(stamp(u64::MAX), u64::MAX.to_string()); + } +} diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 86768fe27..5f44253d0 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -1,7 +1,8 @@ -//! `kiri k8s`, `kiri machine`, `kiri diag`, `kiri usb` and `kiri domains` on Windows: the engine's own +//! `kiri k8s`, `kiri machine`, `kiri diag`, `kiri usb`, `kiri domains`, +//! `kiri registry` and `kiri scan` on Windows: the engine's own //! commands, run by the Linux `kiri` in the WSL distro Kiri's engine lives //! in, as the engine runs (root, with its HOME), so it finds the daemon's -//! socket. Arguments go through as they are: Windows paths are not +//! socket and store. Arguments go through as they are: Windows paths are not //! translated. `kiri machine shell` is the exception: it needs a terminal //! and a docker CLI, so it runs on Windows (machine_shell below). @@ -10,7 +11,7 @@ use std::path::PathBuf; use std::process::Command; /// The commands passed to the engine in WSL. -pub const COMMANDS: &[&str] = &["k8s", "machine", "diag", "usb", "domains", "registry"]; +pub const COMMANDS: &[&str] = &["k8s", "machine", "diag", "usb", "domains", "registry", "scan"]; /// 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. @@ -59,3 +60,13 @@ fn machine_shell(name: &str, rest: &[String]) -> io::Result<()> { } crate::docker::run(&args) } + +#[cfg(test)] +mod tests { + use super::COMMANDS; + + #[test] + fn forwards_scan_to_wsl() { + assert!(COMMANDS.contains(&"scan")); + } +} diff --git a/docs/features.md b/docs/features.md index 523f519fd..c20d09977 100644 --- a/docs/features.md +++ b/docs/features.md @@ -96,6 +96,14 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr Kiri container (buildx's docker-container driver), stopped when idle; `--platform` for one platform at a time; on Apple silicon, amd64 build steps run through Rosetta too +- **Vulnerability scanning**: `kiri scan ` (or an image's Security + tab in the window) finds known CVEs in an image with Grype, on Mac, + Windows and Linux — also what every build's page shows. Nothing leaves + your machine: Grype reads the image through an OCI layout of Kiri's own + store, and the first scan downloads Grype and its database (about + 230 MB, 3 GB unpacked), kept for every scan after. The last 20 scans of + an image are kept, with `--history` and `--json`, and finding + descriptions link their advisories - **Compose**: `up` (with `--build` and `--wait`), `down`, `ps`, `logs`, `exec`, `build:`, healthchecks, `depends_on` conditions (`service_healthy`, `service_completed_successfully`), `platform:`, From 603191fd95d1793591f252433b5ac5e949ad7d0b Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:10:43 +0100 Subject: [PATCH 037/157] Linux: allow containerized SDK clients to reach the daemon socket via group (#127) (#820) Co-authored-by: Andre Kurait --- crates/kiri/src/daemon/access.rs | 11 + crates/kiri/src/daemon/binds.rs | 25 +- crates/kiri/src/daemon/mod.rs | 405 ++++++++++++++++++++++++++++--- docs/fix-registry.md | 6 + tests/linux-host.sh | 6 + tests/regressions.tsv | 1 + 6 files changed, 411 insertions(+), 43 deletions(-) diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index 8236377c0..32f6ae4f2 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -1137,6 +1137,17 @@ impl Gate { }) } + #[cfg(test)] + pub(crate) fn allowed_for_test(&self, uid: u32) -> io::Result { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + state.recent.remove(&uid); + drop(state); + self.allowed_with(uid, |u| { + let group = self.cached_group()?; + Ok(member_of_detailed(u, &group)? == Membership::Allowed) + }) + } + fn allowed_with(&self, uid: u32, check: impl Fn(u32) -> io::Result) -> io::Result { if uid == 0 || uid == self.owner { return Ok(true); diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index e77fb0b78..a0edecdd8 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -232,27 +232,41 @@ pub fn real(p: &str) -> Option { pub fn engine_socket(src: &str) -> Option { let own = super::socket_path().ok()?; let own = own.to_string_lossy(); - engine_socket_for(src, &own, real) + let alias = if std::env::var_os("KIRI_SOCKET").is_none() { + super::home_socket_path().ok().filter(|p| p.as_os_str() != own.as_ref()) + } else { + None + }; + let alias = alias.as_deref().and_then(|p| p.to_str()); + engine_socket_with_alias(src, &own, alias, real) } /// [`engine_socket`], with `resolve` giving where a path that exists /// really is. The path as given is followed first, as the kernel will /// follow it; only a path that is not there is compared as text. +#[cfg(test)] fn engine_socket_for(src: &str, own: &str, resolve: impl Fn(&str) -> Option) -> Option { + engine_socket_with_alias(src, own, None, resolve) +} + +fn engine_socket_with_alias(src: &str, own: &str, alias: Option<&str>, resolve: impl Fn(&str) -> Option) -> Option { let found = resolve(src); - let is_own = found.as_ref().zip(resolve(own)).is_some_and(|(a, b)| a.same(&b)); + let is_own = found.as_ref().is_some_and(|a| { + resolve(own).is_some_and(|b| a.same(&b)) || alias.and_then(&resolve).is_some_and(|b| a.same(&b)) + }); let text = clean(src); + let matches_text = |p: &str| text == clean(p); #[cfg(target_os = "macos")] { let named = ENGINE_SOCKS.contains(&text.as_str()) || found.as_ref().is_some_and(|r| ENGINE_SOCKS.contains(&r.path.as_str())); - (is_own || named || text == clean(own)).then(|| VM_ENGINE_SOCK.to_owned()) + (is_own || named || matches_text(own) || alias.is_some_and(matches_text)).then(|| VM_ENGINE_SOCK.to_owned()) } #[cfg(not(target_os = "macos"))] { let given = || super::caller::container_socket(Path::new(own)).to_string_lossy().into_owned(); match found { Some(_) => is_own.then(given), - None => (text == clean(own) || ENGINE_SOCKS.contains(&text.as_str())).then(given), + None => (matches_text(own) || alias.is_some_and(matches_text) || ENGINE_SOCKS.contains(&text.as_str())).then(given), } } } @@ -514,6 +528,9 @@ mod tests { let raw = fake(&spelled, &[]); let raw = |p: &str| if p == "/tmp/l//../kiri/docker.sock" || p == own { raw(p) } else { None }; assert_eq!(engine_socket_for("/tmp/l//../kiri/docker.sock", own, raw).as_deref(), given); + // Compatibility home socket alias alongside /run/kiri/docker.sock also maps to the container socket. + let home_alias = "/root/.kiri/run/docker.sock"; + assert_eq!(engine_socket_with_alias(home_alias, own, Some(home_alias), &itself).as_deref(), given); } assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", none), None); assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", &itself), None); diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index c8df7f13d..ca5f50dad 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -57,15 +57,38 @@ pub fn state_dir() -> io::Result { Ok(home.join(crate::flavor::STATE.get())) } -/// `~/.kiri/run/docker.sock`, beside OrbStack's `~/.orbstack/run/docker.sock`. +static BOUND_SOCKET: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Root on Linux uses `/run/kiri/docker.sock`; other users use `~/.kiri/run/docker.sock`, +/// beside OrbStack's `~/.orbstack/run/docker.sock`. pub fn socket_path() -> io::Result { - if let Some(s) = std::env::var_os("KIRI_SOCKET") { - return Ok(PathBuf::from(s)); + if let Some(s) = BOUND_SOCKET.get() { + return Ok(s.clone()); } - let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; + // SAFETY: geteuid cannot fail. + let linux_root = cfg!(target_os = "linux") && unsafe { libc::geteuid() } == 0; + socket_path_for(std::env::var_os("KIRI_SOCKET").as_deref(), linux_root, std::env::var_os("HOME").as_deref()) +} + +pub(crate) fn home_socket_path() -> io::Result { + home_socket_path_for(std::env::var_os("HOME").as_deref()) +} + +fn home_socket_path_for(home: Option<&std::ffi::OsStr>) -> io::Result { + let home = home.map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; Ok(home.join(crate::flavor::STATE.get()).join("run/docker.sock")) } +fn socket_path_for(override_path: Option<&std::ffi::OsStr>, linux_root: bool, home: Option<&std::ffi::OsStr>) -> io::Result { + if let Some(s) = override_path { + return Ok(PathBuf::from(s)); + } + if linux_root { + return Ok(PathBuf::from("/run/kiri/docker.sock")); + } + home_socket_path_for(home) +} + /// Raises the soft open-file limit to the hard one, as Go does for dockerd. /// launchd starts the daemon with 256, and each relayed connection holds /// four or five descriptors: a LAN client opening ~60 connections to a @@ -104,24 +127,40 @@ pub fn run(_args: &[String]) -> io::Result<()> { libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut()); set }; - let socket = socket_path()?; + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut socket = socket_path()?; + #[cfg(target_os = "linux")] + let mut extra_home_socket = if std::env::var_os("KIRI_SOCKET").is_none() { + home_socket_path().ok().filter(|p| p != &socket) + } else { + None + }; if UnixStream::connect(&socket).is_ok() { - // Not an error: launchd (KeepAlive on failure) must not retry it. - diag::info!("engine already running", socket = socket.display()); - return Ok(()); - } - if let Some(dir) = socket.parent() { - std::fs::create_dir_all(dir)?; + #[cfg(target_os = "linux")] + if let Some(home_sock) = extra_home_socket.take() + && UnixStream::connect(&home_sock).is_err() + { + socket = home_sock; + } else { + // Not an error: launchd (KeepAlive on failure) must not retry it. + diag::info!("engine already running", socket = socket.display()); + return Ok(()); + } + #[cfg(not(target_os = "linux"))] + { + // Not an error: launchd (KeepAlive on failure) must not retry it. + diag::info!("engine already running", socket = socket.display()); + return Ok(()); + } } - let _ = std::fs::remove_file(&socket); // stale, from a daemon that died - let listener = UnixListener::bind(&socket)?; - std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?; + let _ = BOUND_SOCKET.set(socket.clone()); // On a Linux host the daemon runs as root; `KIRI_SOCKET_GROUP=kiri` // lets that group's users in, as the docker group does for dockerd. + // Without an explicit group, root on Linux uses ordinary 0660 Unix + // group access (`docker` when present), so containerized SDK clients + // whose numeric uid has no host account can connect via socket gid. let access_group = std::env::var_os("KIRI_SOCKET_GROUP"); - if let Some(group) = &access_group { - socket_group(&socket, group)?; - } + let listener = bind_daemon_socket(&socket, access_group.as_deref())?; // On a Linux host (and WSL) containers that mount the engine's socket // are given this one instead (binds.rs), so the API knows their // connections by where they arrive (caller.rs). Made as the daemon's @@ -130,21 +169,27 @@ pub fn run(_args: &[String]) -> io::Result<()> { #[cfg(target_os = "linux")] let for_containers = { let path = caller::container_socket(&socket); - let _ = std::fs::remove_file(&path); - let listener = UnixListener::bind(&path)?; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; - if let Some(group) = &access_group { - socket_group(&path, group)?; - } + let listener = bind_daemon_socket(&path, access_group.as_deref())?; (listener, path) }; + #[cfg(target_os = "linux")] + let extra_home = extra_home_socket.and_then(|path| { + if UnixStream::connect(&path).is_ok() { + return None; + } + bind_daemon_socket(&path, access_group.as_deref()).ok().map(|l| (l, path)) + }); // Each member by name too, so one just added needn't sign in again; and // connections are checked against the group when made and while open, so // a member removed is let go at once, whatever the list still says. #[cfg(target_os = "linux")] let gate = match &access_group { Some(group) => { - let gate = access::Gate::new(&[socket.as_path(), for_containers.1.as_path()], group)?; + let mut gated = vec![socket.as_path(), for_containers.1.as_path()]; + if let Some((_, ref home_path)) = extra_home { + gated.push(home_path.as_path()); + } + let gate = access::Gate::new(&gated, group)?; match gate.grant() { Ok(n) => diag::info!("socket access list written", members = n), Err(e) => diag::warn!("socket access list not written: new members sign in again first", error = e), @@ -200,7 +245,11 @@ pub fn run(_args: &[String]) -> io::Result<()> { } } - watch_own_app(engine.clone(), socket.clone()); + #[cfg(target_os = "linux")] + let extra_sock = extra_home.as_ref().map(|(_, p)| p.clone()); + #[cfg(not(target_os = "linux"))] + let extra_sock: Option = None; + watch_own_app(engine.clone(), socket.clone(), extra_sock.clone()); let on_signal = engine.clone(); let sock = socket.clone(); @@ -213,6 +262,9 @@ pub fn run(_args: &[String]) -> io::Result<()> { nfs::unmount(); let _ = std::fs::remove_file(&sock); let _ = std::fs::remove_file(caller::container_socket(&sock)); + if let Some(ref extra) = extra_sock { + let _ = std::fs::remove_file(extra); + } on_signal.shutdown(); // Give the guest a moment to power off before the VM is released. std::thread::sleep(std::time::Duration::from_millis(50)); @@ -221,6 +273,10 @@ pub fn run(_args: &[String]) -> io::Result<()> { #[cfg(target_os = "linux")] { + if let Some((extra_listener, _)) = extra_home { + let (engine_extra, gate_extra) = (engine.clone(), gate.clone()); + std::thread::Builder::new().name("kiri-api-home".into()).spawn(move || accept(&extra_listener, &engine_extra, &gate_extra, caller::Caller::Host))?; + } let (engine2, gate2) = (engine.clone(), gate.clone()); std::thread::Builder::new().name("kiri-api-containers".into()).spawn(move || accept(&for_containers.0, &engine2, &gate2, caller::Caller::Container))?; accept(&listener, &engine, &gate, caller::Caller::Host); @@ -230,6 +286,14 @@ pub fn run(_args: &[String]) -> io::Result<()> { Ok(()) } +#[cfg(target_os = "linux")] +fn admit_connection(gate: &Option>, conn: &UnixStream) -> Result, ()> { + match gate { + Some(gate) => gate.admit(conn).map(Some).ok_or(()), + None => Ok(None), + } +} + /// Serves each connection `listener` takes, as `who`'s, on a thread of its own. fn accept( listener: &UnixListener, @@ -246,12 +310,8 @@ fn accept( // Checked here, not in the accept loop: a slow user lookup holds up // this connection only. #[cfg(target_os = "linux")] - let _seat = match &gate { - Some(gate) => match gate.admit(&conn) { - Some(seat) => Some(seat), - None => return, - }, - None => None, + let Ok(_seat) = admit_connection(&gate, &conn) else { + return; }; let _ = api::serve(conn, engine, who); }); @@ -264,7 +324,7 @@ fn accept( /// When the app this daemon runs from is deleted (appwatch.rs): docker /// build handed back (buildwith.rs: what was there before; the choice /// stays, so the app taken up again takes it again), and the engine stops. -fn watch_own_app(engine: std::sync::Arc, socket: std::path::PathBuf) { +fn watch_own_app(engine: std::sync::Arc, socket: std::path::PathBuf, extra_socket: Option) { crate::appwatch::watch(move |exe| { diag::error!("the app this engine runs from was deleted; stopping and handing docker build back", path = exe.display()); if let Err(e) = crate::buildwith::places().and_then(|p| p.give_back()) { @@ -274,6 +334,9 @@ fn watch_own_app(engine: std::sync::Arc, socket: std::path::Path nfs::unmount(); let _ = std::fs::remove_file(&socket); let _ = std::fs::remove_file(caller::container_socket(&socket)); + if let Some(ref extra) = extra_socket { + let _ = std::fs::remove_file(extra); + } engine.shutdown(); std::thread::sleep(Duration::from_millis(50)); // 0: launchd restarts the engine on failure only, and there is @@ -296,12 +359,67 @@ fn finder(engine: &std::sync::Arc) { } } -/// Gives `group` read-write access to the socket. -fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result<()> { +fn bind_daemon_socket(socket: &std::path::Path, access_group: Option<&std::ffi::OsStr>) -> io::Result { + if let Some(dir) = socket.parent() { + std::fs::create_dir_all(dir)?; + if dir == std::path::Path::new("/run/kiri") { + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?; + } + } + let _ = std::fs::remove_file(socket); // stale, from a daemon that died + let _ = std::fs::remove_dir(socket); // empty directory left by a pre-0.2.3 bind mount + let listener = UnixListener::bind(socket)?; + std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))?; + if let Some(group) = access_group { + socket_group(socket, group)?; + } else { + default_socket_access(socket)?; + } + Ok(listener) +} + +/// Docker-compatible permissions for a root-run Linux daemon when no explicit +/// `KIRI_SOCKET_GROUP` is configured: mode 0660 (never world-writable), with +/// the `docker` group when present on the host. +fn default_socket_access(socket: &std::path::Path) -> io::Result<()> { + // SAFETY: geteuid cannot fail. + let linux_root = cfg!(target_os = "linux") && unsafe { libc::geteuid() } == 0; + default_socket_access_with(socket, linux_root, lookup_group_gid, apply_socket_gid) +} + +fn default_socket_access_with( + socket: &std::path::Path, + linux_root: bool, + lookup_gid: impl FnOnce(&std::ffi::OsStr) -> io::Result, + apply_gid: impl FnMut(&std::path::Path, Option) -> io::Result<()>, +) -> io::Result<()> { + let mut apply_gid = apply_gid; + if !linux_root { + return Ok(()); + } + match lookup_gid(std::ffi::OsStr::new("docker")) { + Ok(gid) => match apply_gid(socket, Some(gid)) { + Ok(()) => Ok(()), + // In a single-user namespace where the host's `docker` gid is not + // mapped, chown returns EINVAL: keep the socket's group at 0660. + Err(e) if e.raw_os_error() == Some(libc::EINVAL) => apply_gid(socket, None), + Err(e) => Err(e), + }, + // When `KIRI_SOCKET_GROUP` is unset, `docker` is optional: Alpine / + // BusyBox `getent group docker` exits 1 (`ErrorKind::Other`) when + // absent, while glibc exits 2 (`ErrorKind::NotFound`). Keep root's + // group at 0660 rather than refusing to start the daemon. + Err(_) => apply_gid(socket, None), + } +} + +fn lookup_group_gid(group: &std::ffi::OsStr) -> io::Result { #[cfg(target_os = "linux")] - let gid = access::group_gid(group)?; + { + access::group_gid(group) + } #[cfg(not(target_os = "linux"))] - let gid = { + { let name = std::ffi::CString::new(std::os::unix::ffi::OsStrExt::as_bytes(group)).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; // SAFETY: getgrnam with a valid C string; the result is read at once. unsafe { @@ -309,9 +427,218 @@ fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result if g.is_null() { return Err(io::Error::new(io::ErrorKind::NotFound, format!("no group {}", group.to_string_lossy()))); } - (*g).gr_gid + Ok((*g).gr_gid) } - }; - std::os::unix::fs::chown(socket, None, Some(gid))?; + } +} + +fn apply_socket_gid(socket: &std::path::Path, gid: Option) -> io::Result<()> { + if let Some(gid) = gid { + std::os::unix::fs::chown(socket, None, Some(gid))?; + } std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o660)) } + +/// Gives `group` read-write access to the socket. +fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result<()> { + let gid = lookup_group_gid(group)?; + apply_socket_gid(socket, Some(gid)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsStr; + use std::os::unix::fs::MetadataExt; + + #[test] + fn root_linux_default_socket_and_overrides() { + assert_eq!(socket_path_for(None, true, Some(OsStr::new("/root"))).unwrap(), PathBuf::from("/run/kiri/docker.sock")); + assert_eq!(socket_path_for(None, true, None).unwrap(), PathBuf::from("/run/kiri/docker.sock")); + assert_eq!( + socket_path_for(Some(OsStr::new("/custom/kiri.sock")), true, Some(OsStr::new("/root"))).unwrap(), + PathBuf::from("/custom/kiri.sock") + ); + assert_eq!( + socket_path_for(None, false, Some(OsStr::new("/home/alice"))).unwrap(), + PathBuf::from("/home/alice").join(crate::flavor::STATE.get()).join("run/docker.sock") + ); + } + + #[test] + fn default_socket_access_uses_0660_never_world_writable_and_selects_docker_group() { + let dir = std::env::temp_dir().join(format!("kiri-daemon-sock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("docker.sock"); + let _listener = UnixListener::bind(&sock).unwrap(); + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o7777; + + // Non-root / macOS default keeps 0600 and is never world-writable. + default_socket_access_with(&sock, false, |_| unreachable!(), apply_socket_gid).unwrap(); + assert_eq!(mode(&sock), 0o600); + assert_eq!(mode(&sock) & 0o002, 0, "socket must never be world-writable"); + + // Root on Linux with `docker` group present selects `docker` group and 0660 (never 0666). + // SAFETY: getegid cannot fail. + let my_gid = unsafe { libc::getegid() }; + let mut applied_gid = None; + default_socket_access_with( + &sock, + true, + |g| { + assert_eq!(g, OsStr::new("docker")); + Ok(my_gid) + }, + |p, gid| { + applied_gid = gid; + apply_socket_gid(p, gid) + }, + ) + .unwrap(); + assert_eq!(applied_gid, Some(my_gid)); + assert_eq!(mode(&sock), 0o660); + assert_eq!(mode(&sock) & 0o007, 0, "socket must forbid world access (never 0666)"); + assert_eq!(std::fs::metadata(&sock).unwrap().gid(), my_gid); + + // Root on Linux without a `docker` group keeps existing group and sets 0660 (never 0666). + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut fallback_gid = Some(99999); + default_socket_access_with( + &sock, + true, + |_| Err(io::Error::new(io::ErrorKind::NotFound, "no group docker")), + |p, gid| { + fallback_gid = gid; + apply_socket_gid(p, gid) + }, + ) + .unwrap(); + assert_eq!(fallback_gid, None); + assert_eq!(mode(&sock), 0o660); + assert_eq!(mode(&sock) & 0o007, 0, "socket must forbid world access (never 0666)"); + + // Unmapped gid in a user namespace (EINVAL) also falls back cleanly to 0660. + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut attempts = Vec::new(); + default_socket_access_with( + &sock, + true, + |_| Ok(999), + |p, gid| { + attempts.push(gid); + if gid.is_some() { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + } + apply_socket_gid(p, None) + }, + ) + .unwrap(); + assert_eq!(attempts, vec![Some(999), None]); + assert_eq!(mode(&sock), 0o660); + + // BusyBox `getent group docker` exits 1 (`ErrorKind::Other`) when absent: must still start at 0660. + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + default_socket_access_with( + &sock, + true, + |_| Err(io::Error::other("getent group docker: exit status: 1")), + apply_socket_gid, + ) + .unwrap(); + assert_eq!(mode(&sock), 0o660); + + // Explicit KIRI_SOCKET_GROUP fails closed when the group does not exist. + assert_eq!(socket_group(&sock, OsStr::new("kiri-no-such-group-127")).unwrap_err().kind(), io::ErrorKind::NotFound); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn peer_authorization_allows_container_uid_when_unmanaged_and_denies_without_gid_or_when_managed() { + // Container-only numeric UID 54321 must not exist in the host's /etc/passwd. + #[cfg(target_os = "linux")] + const PROBE_ID: u32 = 54321; + let has_host_entry = std::fs::read_to_string("/etc/passwd") + .unwrap_or_default() + .lines() + .any(|l| l.split(':').nth(2) == Some("54321")); + assert!(!has_host_entry, "54321 must not be a host account"); + + let dir = std::env::temp_dir().join(format!("kiri-peer-auth-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + // SAFETY: getegid cannot fail. + let sock_gid = unsafe { libc::getegid() }; + default_socket_access_with(&sock, true, |_| Ok(sock_gid), apply_socket_gid).unwrap(); + + let m = std::fs::metadata(&sock).unwrap(); + let mode = m.permissions().mode() & 0o7777; + assert_eq!(mode, 0o660); + // Group rw (0o060) lets a container UID with supplementary `sock_gid` connect; + // other is 0 (0o007 == 0) so the kernel denies any UID/GID lacking `sock_gid` with EACCES. + assert_eq!(mode & 0o070, 0o060); + assert_eq!(mode & 0o007, 0); + + #[cfg(target_os = "linux")] + { + let (_client, server) = UnixStream::pair().unwrap(); + // 1. When KIRI_SOCKET_GROUP is unset (`gate` is `None`), a connected peer that + // passed the kernel's 0660 group check is admitted without requiring an `/etc/passwd` entry. + assert!(admit_connection(&None, &server).is_ok()); + + // 2. When KIRI_SOCKET_GROUP IS explicitly set, managed account-membership check is + // enforced: container-only numeric `uid=54321` is not a member of that managed group and is DENIED. + let gate = access::Gate::new(&[sock.as_path()], OsStr::new("root")).unwrap(); + assert!(!gate.allowed_for_test(PROBE_ID).unwrap(), "non-NSS peer must be denied by managed KIRI_SOCKET_GROUP gate"); + + // SAFETY: geteuid cannot fail. + if unsafe { libc::geteuid() } == 0 { + let try_connect = |with_sock_gid: bool| -> io::ErrorKind { + // SAFETY: fork in a test; the child only drops privileges, connects and exits with raw errno. + unsafe { + let pid = libc::fork(); + if pid == 0 { + let rc = if with_sock_gid { + let gids = [sock_gid as libc::gid_t]; + libc::setgroups(1, gids.as_ptr()) + } else { + libc::setgroups(0, std::ptr::null()) + }; + if rc != 0 || libc::setgid(PROBE_ID) != 0 || libc::setuid(PROBE_ID) != 0 { + libc::_exit(126); + } + match UnixStream::connect(&sock) { + Ok(_) => libc::_exit(0), + Err(e) => libc::_exit(e.raw_os_error().unwrap_or(1).clamp(1, 125)), + } + } + let mut status = 0; + libc::waitpid(pid, &mut status, 0); + let code = libc::WEXITSTATUS(status); + if code == 0 { + io::ErrorKind::Other + } else { + io::Error::from_raw_os_error(code).kind() + } + } + }; + // Denied by kernel 0660 when lacking `sock_gid`. + assert_eq!(try_connect(false), io::ErrorKind::PermissionDenied); + // Allowed by kernel 0660 when carrying supplementary `sock_gid`, and admitted when KIRI_SOCKET_GROUP is unset. + assert_eq!(try_connect(true), io::ErrorKind::Other); + let (accepted, _) = listener.accept().unwrap(); + assert!(admit_connection(&None, &accepted).is_ok()); + // Denied by managed `KIRI_SOCKET_GROUP` gate even after kernel 0660 connect. + assert!(admit_connection(&Some(gate), &accepted).is_err()); + } + } + let _ = listener; + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index ffcc66daa..12eaf5eaa 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 +### #127 Linux: standalone root daemon serves 0660 `/run/kiri/docker.sock` for containerized SDK clients (unreleased) +- Fixes: #127 Linux daemon: Docker-compatible socket access for containerized SDK clients +- Caused: none known +- Caused by: - +- Check: `socket-container-uid-group` + ### #749 Linux: `kiri update --check` checks the release feed instead of falling through to `docker update` (unreleased) - Fixes: #749 Linux: `kiri update --check` falls through to `docker update` diff --git a/tests/linux-host.sh b/tests/linux-host.sh index fff4389bb..269d7f1bd 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -130,6 +130,12 @@ t socket-mount-reaches-kiri "Kiri" "docker run --rm -v /root/.kiri/run/docker.so # A container given the engine's socket uses Docker's API, not Kiri's own # settings: the same CLI that changes them here is refused from inside one. t socket-mount-settings-refused "not from a container" "docker run --rm -v /opt/kiri/kiri:/kiri:ro -v /root/.kiri/run/docker.sock:/var/run/docker.sock -e KIRI_SOCKET=/var/run/docker.sock alpine /kiri registry insecure add 10.9.9.9:5000 2>&1" +# A standalone root-run Linux daemon listens at /run/kiri/docker.sock (0660, +# never world-writable) and lets a containerized client whose numeric uid +# (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 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" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 099cc08a3..c7b63c401 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -276,3 +276,4 @@ bind-recreate #402 deleting or replacing a bind-mounted file on the Mac left a s hostnet-published-loopback #732 a port published on 127.0.0.1 was unreachable from a --network host container at 127.0.0.1 (Mac): connection refused hostnet-published-every-address #732 the same for a port published on every address hostnet-dns-kiri #732 a --network host container asked the Mac's resolver for the VM network directly, with no fallback when it refused +socket-container-uid-group #127 a standalone root-run Linux daemon put its 0600 socket under /root/.kiri/run/docker.sock instead of a 0660 /run/kiri/docker.sock, locking out containerized SDK clients whose numeric uid has no host account From 7fdd3fc86c452d50fadc21595ecda652938b6cc4 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:17:38 +0100 Subject: [PATCH 038/157] Mac: redirect IPv6 loopback (::1) published ports on --network host (#732) (#821) --- crates/kiri-init/src/linux/net.rs | 25 +++++- crates/kiri-init/src/linux/netlink.rs | 112 ++++++++++++++++++++------ crates/kiri-init/src/linux/relay.rs | 92 ++++++++++++++++----- docs/fix-registry.md | 2 +- tests/e2e.sh | 8 +- 5 files changed, 185 insertions(+), 54 deletions(-) diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 9e75845ea..778d8deca 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -234,7 +234,7 @@ fn through_firewall(why: firewall::Why) { let nat6 = NAT6.lock().unwrap_or_else(|e| e.into_inner()).clone(); if v6 && !nat6.0.is_empty() - && let Err(e) = netlink::install_nat6(&nat6.0, &nat6.1) + && let Err(e) = refresh_nat6(&nat6.0, &nat6.1) { eprintln!("kiri-init: IPv6 NAT: {e}"); } @@ -246,6 +246,17 @@ fn through_firewall(why: firewall::Why) { #[allow(clippy::type_complexity)] static NAT6: std::sync::Mutex<(Vec<([u8; 16], u8)>, Vec)> = std::sync::Mutex::new((Vec::new(), Vec::new())); +/// Rebuilds Kiri's IPv6 table from `subnets`/`bridges` and, in the VM, the +/// loopback redirect and input guard for `HOST_RELAY_PORT`. +fn refresh_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Result<()> { + let (redirect, dnat) = NAT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or((false, Vec::new()), |n| (n.redirect, n.dnat.clone())); + netlink::install_nat6(subnets, bridges, HOST_RELAY_PORT, redirect, &dnat) +} + /// What Kiri's IPv4 table was last built from, so it can be rebuilt when a /// bridge comes or goes (the forward filter has a rule per bridge). struct Nat { @@ -261,7 +272,8 @@ static NAT: std::sync::Mutex> = std::sync::Mutex::new(None); static NO_FIB4: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Builds Kiri's IPv4 table from `nat` and the bridges made so far, and -/// keeps `nat` for `refresh_nat`. +/// keeps `nat` for `refresh_nat`. In the VM (`nat.redirect`), also installs +/// the IPv6 `::1` loopback redirect and input guard on a best-effort basis. fn install_nat(nat: Nat) -> io::Result<()> { use std::sync::atomic::Ordering; let bridges = MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).clone(); @@ -280,7 +292,12 @@ fn install_nat(nat: Nat) -> io::Result<()> { } }; if r.is_ok() { + let redirect = nat.redirect; *NAT.lock().unwrap_or_else(|e| e.into_inner()) = Some(nat); + if redirect { + let nat6 = NAT6.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let _ = refresh_nat6(&nat6.0, &nat6.1); + } } r } @@ -785,7 +802,7 @@ impl Bridges { if added.is_some() { ipv6_forwarding(true)?; } - let r = netlink::install_nat6(&subnets, &names); + let r = refresh_nat6(&subnets, &names); if r.is_ok() { *NAT6.lock().unwrap_or_else(|e| e.into_inner()) = (subnets.clone(), names.clone()); } @@ -856,7 +873,7 @@ pub fn remove_host_network() { if let Err(e) = netlink::remove_nat() { eprintln!("kiri-init: removing the nftables table: {e}"); } - let _ = netlink::install_nat6(&[], &[]); + let _ = netlink::install_nat6(&[], &[], HOST_RELAY_PORT, false, &[]); let _ = ipv6_forwarding(false); through_firewall(firewall::Why::Stop); } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 4d812f67f..e058e1081 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -830,7 +830,15 @@ fn localnet_guard() -> Vec { /// VM's address, a container dialling its gateway) never reached the Mac; /// now it is not even accepted. Redirected connections are DNATed and pass. fn host_relay_guard(port: u16) -> Msg { - let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + host_relay_guard_in(libc::NFPROTO_IPV4 as u8, port) +} + +fn host_relay_guard6(port: u16) -> Msg { + host_relay_guard_in(libc::NFPROTO_IPV6 as u8, port) +} + +fn host_relay_guard_in(family: u8, port: u16) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, "input"); rule.nest(4); // meta l4proto => reg 1; cmp eq tcp @@ -885,8 +893,9 @@ fn masq6_rule(subnet: [u8; 16], prefix: u8) -> Msg { rule } -/// Kiri's IPv6 table, for the IPv6 networks `subnets`, rebuilt whole (and -/// removed with the last one, so an engine with none has no IPv6 rules): +/// Kiri's IPv6 table, for the IPv6 networks `subnets` and (in the VM, when +/// `redirect` is true) the `::1` loopback redirect for published ports and +/// the input guard on `host_port`, rebuilt whole: /// /// ```text /// table ip6 kiri { @@ -894,9 +903,15 @@ fn masq6_rule(subnet: [u8; 16], prefix: u8) -> Msg { /// ip6 saddr oifname != "kiri*" masquerade # one per network /// } /// chain forward { … } (the IPv4 table's `forward_filter`) +/// chain input { type filter hook input priority 0; +/// tcp dport ct status & dnat == 0 drop +/// } +/// chain output { type nat hook output priority -100; +/// ip6 daddr ::1 tcp dport redirect to : +/// } /// } /// ``` -pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Result<()> { +pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String], host_port: u16, redirect: bool, dnat: &[Dnat]) -> io::Result<()> { let v6 = libc::NFPROTO_IPV6 as u8; let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); @@ -905,18 +920,34 @@ pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Resul let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); let mut msgs = vec![begin, add, delete]; - if !subnets.is_empty() { + if !subnets.is_empty() || redirect { let mut table = nft_in(v6, NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); table.attr_str(1, "kiri"); + msgs.push(table); + } + if !subnets.is_empty() { let mut chain = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); chain.attr_str(1, "kiri").attr_str(3, "postrouting"); chain.nest(4).attr_be32(1, 4).attr_be32(2, 100).end(); chain.attr_be32(5, 1).attr_str(7, "nat"); - msgs.push(table); msgs.push(chain); msgs.extend(subnets.iter().map(|(s, p)| masq6_rule(*s, *p))); msgs.extend(forward_filter_in(v6, bridges, forward_guard(v6).as_deref())); } + if redirect { + let mut input = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + input.attr_str(1, "kiri").attr_str(3, "input"); + input.nest(4).attr_be32(1, 1).attr_be32(2, 0).end(); // NF_INET_LOCAL_IN, priority 0 + input.attr_be32(5, 1).attr_str(7, "filter"); + let mut output = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + output.attr_str(1, "kiri").attr_str(3, "output"); + output.nest(4).attr_be32(1, 3).attr_be32(2, -100i32 as u32).end(); // NF_INET_LOCAL_OUT, priority -100 + output.attr_be32(5, 1).attr_str(7, "nat"); + msgs.extend([input, host_relay_guard6(host_port), output]); + for d in dnat.iter().filter(|d| !d.udp && d.host_ip == LOOPBACK && d.host_port != host_port) { + msgs.push(loopback_published_rule6(d.host_port, host_port)); + } + } msgs.push(end); nl.request(&mut msgs) } @@ -1189,8 +1220,9 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r } /// A published port's `host_ip` in the VM that means "the Mac's loopback": -/// the VM's own connections to 127.0.0.1 on it reach the Mac's 127.0.0.1. +/// the VM's own connections to 127.0.0.1 or ::1 on it reach the Mac's 127.0.0.1. pub const LOOPBACK: [u8; 4] = [127, 0, 0, 1]; +pub const LOOPBACK6: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; /// `ip daddr 127.0.0.1 tcp dport redirect to :`, in output: /// in the VM, a connection the VM itself makes (a `--network host` @@ -1200,15 +1232,28 @@ pub const LOOPBACK: [u8; 4] = [127, 0, 0, 1]; /// published port is bound in the host's own network namespace. The /// redirect stays on the loopback, so `route_localnet` stays off. fn loopback_published_rule(port: u16, relay: u16) -> Msg { - let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + loopback_published_rule_in(libc::NFPROTO_IPV4 as u8, 16, &LOOPBACK, port, relay) +} + +/// `ip6 daddr ::1 tcp dport redirect to :`, in output of +/// `table ip6 kiri`: the IPv6 counterpart of `loopback_published_rule`, so +/// clients in a `--network host` container that resolve `localhost` to `::1` +/// first (musl's `getaddrinfo`) and do not fall back to `127.0.0.1` reach +/// the Mac's loopback-published port too. +fn loopback_published_rule6(port: u16, relay: u16) -> Msg { + loopback_published_rule_in(libc::NFPROTO_IPV6 as u8, 24, &LOOPBACK6, port, relay) +} + +fn loopback_published_rule_in(family: u8, daddr_offset: u32, loopback: &[u8], port: u16, relay: u16) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, "output"); rule.nest(4); // meta l4proto => reg 1; cmp eq tcp rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); - // payload daddr => reg 1; cmp eq 127.0.0.1 - rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); - rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &LOOPBACK).end().end().end(); + // payload daddr => reg 1; cmp eq loopback (127.0.0.1 or ::1) + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, daddr_offset).attr_be32(4, loopback.len() as u32).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, loopback).end().end().end(); // payload transport header + 2 (dport) => reg 1; cmp eq port rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 2).attr_be32(4, 2).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &port.to_be_bytes()).end().end().end(); @@ -1415,10 +1460,11 @@ mod tests { } /// In the VM, a port published on the Mac's loopback: the VM's own TCP - /// connections to 127.0.0.1 on it, in output, go to the host relay. + /// connections to 127.0.0.1 or ::1 on it, in output, go to the host relay. #[test] fn a_loopback_published_port_redirects_the_vms_own_connections_to_the_relay() { let r = loopback_published_rule(5999, 1026); + assert_eq!(r.buf[16], libc::NFPROTO_IPV4 as u8); let top = attrs(&r.buf[20..]); assert_eq!(get(&top, 2), b"output\0", "the VM's own connections only, not the bridges'"); assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"]); @@ -1431,22 +1477,38 @@ mod tests { assert_eq!((be32(get(&e[4].1, 2)), be32(get(&e[4].1, 3)), be32(get(&e[4].1, 4))), (2, 2, 2)); assert_eq!(get(&attrs(get(&e[5].1, 3)), 1), &5999u16.to_be_bytes()); assert_eq!(get(&attrs(get(&e[6].1, 2)), 1), &1026u16.to_be_bytes(), "redirected to the relay's port"); + + let r6 = loopback_published_rule6(5999, 1026); + assert_eq!(r6.buf[16], libc::NFPROTO_IPV6 as u8); + let top6 = attrs(&r6.buf[20..]); + assert_eq!(get(&top6, 2), b"output\0"); + assert_eq!(names(&r6), ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"]); + let e6 = exprs(&r6); + assert_eq!(get(&attrs(get(&e6[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // network header + 24, 16 bytes: ip6 daddr, which must be ::1 + assert_eq!((be32(get(&e6[2].1, 2)), be32(get(&e6[2].1, 3)), be32(get(&e6[2].1, 4))), (1, 24, 16)); + assert_eq!(get(&attrs(get(&e6[3].1, 3)), 1), &LOOPBACK6); + assert_eq!((be32(get(&e6[4].1, 2)), be32(get(&e6[4].1, 3)), be32(get(&e6[4].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e6[5].1, 3)), 1), &5999u16.to_be_bytes()); + assert_eq!(get(&attrs(get(&e6[6].1, 2)), 1), &1026u16.to_be_bytes()); } #[test] fn host_relay_takes_only_redirected_connections() { - let r = host_relay_guard(1026); - let top = attrs(&r.buf[20..]); - assert_eq!(get(&top, 2), b"input\0", "guards every incoming interface, loopback included"); - assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "ct", "bitwise", "cmp", "immediate"]); - let e = exprs(&r); - assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); - // transport header + 2, 2 bytes: dport - assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (2, 2, 2)); - assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &1026u16.to_be_bytes()); - assert_eq!(be32(get(&e[4].1, 2)), 2, "ct status"); - assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &CT_STATUS_DNAT.to_ne_bytes()); - assert_eq!(be32(get(&e[6].1, 2)), 0, "== 0"); - assert_eq!(verdict(&r), libc::NF_DROP as u32); + for (r, family) in [(host_relay_guard(1026), libc::NFPROTO_IPV4 as u8), (host_relay_guard6(1026), libc::NFPROTO_IPV6 as u8)] { + assert_eq!(r.buf[16], family); + let top = attrs(&r.buf[20..]); + assert_eq!(get(&top, 2), b"input\0", "guards every incoming interface, loopback included"); + assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "ct", "bitwise", "cmp", "immediate"]); + let e = exprs(&r); + assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // transport header + 2, 2 bytes: dport + assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &1026u16.to_be_bytes()); + assert_eq!(be32(get(&e[4].1, 2)), 2, "ct status"); + assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &CT_STATUS_DNAT.to_ne_bytes()); + assert_eq!(be32(get(&e[6].1, 2)), 0, "== 0"); + assert_eq!(verdict(&r), libc::NF_DROP as u32); + } } } diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index 0888ebdc3..e7c455725 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -346,11 +346,28 @@ fn connect(ip: [u8; 4], port: u16) -> io::Result { } } -/// The reverse direction, for `host.docker.internal`: TCP connections a -/// container makes to the reserved host address are redirected here. +/// The reverse direction, for `host.docker.internal` and loopback-published +/// ports: TCP connections a container makes to the reserved host address or +/// (from the VM itself) to a port published on the Mac's loopback (`127.0.0.1` +/// or `::1`) are redirected here. Dual-stack (`[::]` with `IPV6_V6ONLY = 0`), +/// falling back to `AF_INET` only if the kernel has no IPv6. pub fn listen_host_bound(port: u16) -> io::Result { // SAFETY: plain socket setup; the fd is owned immediately. unsafe { + let fd = libc::socket(libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0); + if fd >= 0 { + let sock = OwnedFd::from_raw_fd(fd as RawFd); + let zero: libc::c_int = 0; + sys::check(libc::setsockopt(sock.as_raw_fd(), libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, (&zero as *const libc::c_int).cast(), 4) as _, "v6only")?; + let one: libc::c_int = 1; + libc::setsockopt(sock.as_raw_fd(), libc::SOL_SOCKET, libc::SO_REUSEADDR, (&one as *const libc::c_int).cast(), 4); + let mut a: libc::sockaddr_in6 = std::mem::zeroed(); + a.sin6_family = libc::AF_INET6 as libc::sa_family_t; + a.sin6_port = port.to_be(); + sys::check(libc::bind(sock.as_raw_fd(), (&a as *const libc::sockaddr_in6).cast(), std::mem::size_of::() as u32) as _, "bind")?; + sys::check(libc::listen(sock.as_raw_fd(), 128) as _, "listen")?; + return Ok(sock); + } let fd = sys::check(libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; let sock = OwnedFd::from_raw_fd(fd as RawFd); let one: libc::c_int = 1; @@ -369,11 +386,11 @@ pub const HOST_VSOCK_PORT: u32 = 1026; /// Accepts one redirected connection, finds the port the container meant, /// dials the Mac and returns a relay between the two. Only connections that -/// were redirected from `host_addr`, or from 127.0.0.1 on another port (a -/// port published on the Mac's loopback, which only the VM's own output +/// were redirected from `host_addr`, or from 127.0.0.1 / ::1 on another port +/// (a port published on the Mac's loopback, which only the VM's own output /// chain redirects), are relayed: one made to the listener directly (from -/// the LAN, or from a `--network host` container dialling `127.0.0.1:relay_port`) -/// would reach the host's loopback. +/// the LAN, or from a `--network host` container dialling `127.0.0.1:relay_port` +/// or `[::1]:relay_port`) would reach the host's loopback. pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4], relay_port: u16) -> Option { // SAFETY: accept4 on a listening socket we own; the fd is owned immediately. let fd = unsafe { libc::accept4(listener.as_raw_fd(), std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; @@ -382,19 +399,8 @@ pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4], relay_port: u16 } // SAFETY: `fd` is a fresh descriptor that nothing else owns. let client = unsafe { OwnedFd::from_raw_fd(fd) }; - // SAFETY: SO_ORIGINAL_DST fills a sockaddr_in with the pre-redirect destination. - let port = unsafe { - let mut dst: libc::sockaddr_in = std::mem::zeroed(); - let mut len = std::mem::size_of::() as u32; - const SO_ORIGINAL_DST: libc::c_int = 80; - if libc::getsockopt(client.as_raw_fd(), libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) != 0 { - return Some(Relay::dead_one(client)); - } - let dst_port = u16::from_be(dst.sin_port); - if !redirected_from(dst.sin_addr.s_addr.to_ne_bytes(), dst_port, host_addr, relay_port) { - return Some(Relay::dead_one(client)); - } - dst_port + let Some(port) = original_dst_port(client.as_raw_fd(), host_addr, relay_port) else { + return Some(Relay::dead_one(client)); }; let Ok(host) = dial_host(HOST_VSOCK_PORT) else { return Some(Relay::dead_one(client)) }; // The Mac connects to its own loopback: services bound to 127.0.0.1 work. @@ -420,6 +426,29 @@ pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4], relay_port: u16 }) } +/// Pre-redirect destination port of an accepted `host_bound` connection, if +/// it came from one of Kiri's IPv4 (`SOL_IP` / `SO_ORIGINAL_DST`) or IPv6 +/// (`SOL_IPV6` / `IP6T_SO_ORIGINAL_DST`) redirect rules. +fn original_dst_port(fd: RawFd, host_addr: [u8; 4], relay_port: u16) -> Option { + const SO_ORIGINAL_DST: libc::c_int = 80; // also IP6T_SO_ORIGINAL_DST on SOL_IPV6 + // SAFETY: SO_ORIGINAL_DST / IP6T_SO_ORIGINAL_DST fill sockaddr_in / sockaddr_in6. + unsafe { + let mut dst: libc::sockaddr_in = std::mem::zeroed(); + let mut len = std::mem::size_of::() as u32; + if libc::getsockopt(fd, libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) == 0 { + let dst_port = u16::from_be(dst.sin_port); + return redirected_from(dst.sin_addr.s_addr.to_ne_bytes(), dst_port, host_addr, relay_port).then_some(dst_port); + } + let mut dst6: libc::sockaddr_in6 = std::mem::zeroed(); + let mut len6 = std::mem::size_of::() as u32; + if libc::getsockopt(fd, libc::SOL_IPV6, SO_ORIGINAL_DST, (&mut dst6 as *mut libc::sockaddr_in6).cast(), &mut len6) == 0 { + let dst_port = u16::from_be(dst6.sin6_port); + return redirected_from6(dst6.sin6_addr.s6_addr, dst_port, relay_port).then_some(dst_port); + } + None + } +} + /// Whether a host-bound connection's original destination is one the /// redirect rules send to the relay: the host's reserved address, or the /// VM's loopback on another port (published ports only, see @@ -429,6 +458,13 @@ fn redirected_from(dst: [u8; 4], dst_port: u16, host_addr: [u8; 4], relay_port: dst == host_addr || (dst == super::netlink::LOOPBACK && dst_port != relay_port) } +/// The IPv6 counterpart of `redirected_from`: the VM's `::1` loopback on a +/// published port (`loopback_published_rule6`), never `relay_port` itself or +/// any other IPv6 address. +fn redirected_from6(dst: [u8; 16], dst_port: u16, relay_port: u16) -> bool { + dst == super::netlink::LOOPBACK6 && dst_port != relay_port +} + fn dial_host(port: u32) -> io::Result { super::transport::dial(port) } @@ -595,8 +631,9 @@ mod tests { use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; /// The host relay takes connections redirected from the host's address - /// and from the VM's loopback on another port (published ports), never - /// direct connections to the relay's own port or other addresses. + /// and from the VM's loopback (`127.0.0.1` and `::1`) on another port + /// (published ports), never direct connections to the relay's own port or + /// other addresses. #[test] fn the_host_relay_takes_the_host_address_and_loopback() { let host = [198, 19, 248, 254]; @@ -609,6 +646,19 @@ mod tests { assert!(!super::redirected_from(other, 5999, host, relay), "{other:?}"); assert!(!super::redirected_from(other, relay, host, relay), "{other:?}"); } + let lo6 = super::super::netlink::LOOPBACK6; + assert!(super::redirected_from6(lo6, 5999, relay)); + assert!(!super::redirected_from6(lo6, relay, relay), "direct ::1 connection to the relay"); + for other6 in [ + [0; 16], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1], + [0xfd, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + ] { + assert!(!super::redirected_from6(other6, 5999, relay), "{other6:?}"); + assert!(!super::redirected_from6(other6, relay, relay), "{other6:?}"); + } } #[test] diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 12eaf5eaa..840529dc3 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -34,7 +34,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known - Caused by: - -- Check: `hostnet-published-loopback`, `hostnet-published-every-address`, `hostnet-published-gone`, `hostnet-dns-kiri`, `hostnet-dns-names` +- Check: `hostnet-published-loopback`, `hostnet-published-localhost`, `hostnet-published-every-address`, `hostnet-published-gone`, `hostnet-dns-kiri`, `hostnet-dns-names` ### #402 Guest kernel: drop stale cached bind-mount file dentries on host change (unreleased) - Fixes: #399 macOS: bind-mounted files deleted or replaced on the Mac return ENOENT or stale cached contents until Apple's cache timeout diff --git a/tests/e2e.sh b/tests/e2e.sh index a5a30eda1..88c977273 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -919,15 +919,17 @@ t host-gateway "Directory listing" $D run --rm --add-host mac:host-gateway alpin t host-internal-hostnet "Directory listing" $D run --rm --network host alpine wget -qO- http://host.docker.internal:18999/ # A port published on 127.0.0.1 or on every address is in the host's own # network, as Docker binds it: a --network host container reaches it at -# 127.0.0.1 (#732; a host-network BuildKit pushing to a local registry). +# 127.0.0.1 and localhost (::1 first in musl) (#732; a host-network +# BuildKit pushing to a local registry). $D rm -f hn-lo hn-all >/dev/null 2>&1 $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-every-address "Welcome to nginx" $D run --rm --network host alpine wget -qO- -T 5 http://127.0.0.1:18094/ +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 && echo still-there || echo ok'" +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'" $D rm -f hn-all >/dev/null 2>&1 # In the VM a host-network container asks Kiri's resolver, as the default # bridge's do, so a lookup the Mac's resolver for the VM network refuses From 8b461a3eb965ba4862b0b98a75a2127df4a5862d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:28:40 +0100 Subject: [PATCH 039/157] Mac: relay VPN and security-extension egress through the host (#319) (#822) --- crates/kiri-init/src/linux/agent.rs | 21 + crates/kiri-init/src/linux/dns.rs | 75 +- crates/kiri-init/src/linux/net.rs | 91 ++- crates/kiri-init/src/linux/netlink.rs | 156 ++++- crates/kiri-init/src/linux/relay.rs | 334 +++++++++ crates/kiri-proto/src/lib.rs | 51 +- crates/kiri/src/daemon/engine.rs | 12 + crates/kiri/src/daemon/ports.rs | 954 +++++++++++++++++++++++++- crates/kiri/src/daemon/vmlink.rs | 6 + docs/fix-registry.md | 4 + 10 files changed, 1684 insertions(+), 20 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index f7dac4762..60e4728b6 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -107,6 +107,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { + let parsed = net::parse_egress_routes(routes); + if !host_process && !parsed.is_empty() && egress.is_none() { + egress = super::relay::listen_host_bound(net::EGRESS_RELAY_PORT) + .inspect_err(|e| eprintln!("kiri-init: no egress relay listener: {e}")) + .ok(); + } + dns.prefer_relay = !host_process && net::egress_prefers_dns_relay(&parsed); + if let Err(e) = net::set_egress_routes(parsed) { + eprintln!("kiri-init: egress routes: {e}"); + } + continue; + } Ok(Msg::Retain(keep)) => { let running: Vec<&str> = procs.values().map(|p| p.run.id.as_str()).collect(); container::retain(paths, keep, &running); diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index fa76c9bc7..19baf817d 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -144,6 +144,11 @@ pub struct Dns { /// Lookups the VM's resolver fails go through the host (in the VM; a /// Linux host's agent asks the host's resolvers itself). pub relay: bool, + /// Send upstream lookups straight through the host relay instead of + /// asking the VM's gateway resolver first (when a macOS network + /// extension or host egress mode is active, or once the gateway resolver + /// has answered with a `198.18.0.0/15` Fake-IP address). + pub prefer_relay: bool, /// The host didn't take a relayed lookup: none are tried until then. relay_down_until: Option, /// Bridges whose gateway wouldn't take the listener (`serve_or_warn`): @@ -407,6 +412,16 @@ impl Dns { if matches!(msg[3] & 0x0f, 2 | 5) && self.pending[at].own.is_some() && self.ask_next_own(at) { break; } + // A macOS security network extension intercepting the VM + // bridge's DNS answers with a Fake-IP in 198.18.0.0/15 + // (#367): ask the Mac's own resolvers over vsock instead, + // and prefer the host relay from then on. + if self.pending[at].own.is_none() && self.pending[at].may_relay && answer_has_fake_ip(msg) { + self.prefer_relay = true; + if self.relay(at) { + break; + } + } self.answered(at, msg); break; } @@ -544,13 +559,21 @@ impl Dns { at = Some(i); Some(sock) }), + None if self.prefer_relay && may_relay => None, None => upstream.first().and_then(|d| ask(*d, &msg)), }; - // No resolver yet, or it can't be reached: the host, if allowed. + // No resolver yet, or it can't be reached (or `prefer_relay` chose the host): the host, if allowed. let (sock, relayed) = match sock { Some(s) => (s, false), None => match may_relay.then(|| self.relay_stream(&msg)).flatten() { Some(s) => (s, true), + None if self.prefer_relay && own.is_none() => match upstream.first().and_then(|d| ask(*d, &msg)) { + Some(s) => (s, false), + None => { + send_to(self.servers[server].sock.as_raw_fd(), &servfail(id, rd(q), &q[12..end]), &client); + return; + } + }, // No upstream that can be sent to and no host relay (none on // a Linux host, not used for `--dns`, or backing off): // answer at once rather than leave Go's resolver to time @@ -886,6 +909,38 @@ fn response_matches(msg: &[u8], pending: &Pending) -> bool { msg.get(2).is_some_and(|flags| flags & 0x80 != 0) && msg.get(12..12 + pending.question.len()).is_some_and(|question| question == pending.question) } +/// Whether a DNS reply carries an A record in `198.18.0.0/15` (RFC 2544 +/// benchmarking space, used by macOS security network extensions as a +/// synthetic Fake-IP range, #367), excluding `host.docker.internal`. +fn answer_has_fake_ip(msg: &[u8]) -> bool { + let Some((_, _, mut pos)) = parse_question(msg) else { return false }; + let ancount = u16::from_be_bytes([msg[6], msg[7]]) as usize; + for _ in 0..ancount { + loop { + let Some(&b) = msg.get(pos) else { return false }; + if b == 0 { + pos += 1; + break; + } + if b & 0xc0 == 0xc0 { + pos += 2; + break; + } + pos += 1 + (b as usize); + } + let Some(hdr) = msg.get(pos..pos + 10) else { return false }; + let rtype = u16::from_be_bytes([hdr[0], hdr[1]]); + let rdlen = u16::from_be_bytes([hdr[8], hdr[9]]) as usize; + pos += 10; + let Some(rdata) = msg.get(pos..pos + rdlen) else { return false }; + if rtype == 1 && rdlen == 4 && rdata[0] == 198 && (rdata[1] & 0xfe) == 18 && rdata != super::net::HOST_ADDR { + return true; + } + pos += rdlen; + } + false +} + fn random_id() -> Option { let mut bytes = [0u8; 2]; std::fs::File::open("/dev/urandom").ok()?.read_exact(&mut bytes).ok()?; @@ -2004,4 +2059,22 @@ mod tests { response[2] = 0x01; assert!(!response_matches(&response, &p)); } + + #[test] + fn detects_fake_ip_answers_in_198_18_range_and_ignores_real_or_host_ips() { + let mut msg = query("registry.npmjs.org", 1); + msg[2] = 0x81; + msg[3] = 0x80; + msg[6..8].copy_from_slice(&1u16.to_be_bytes()); + // Name pointer 0xc00c, type A (1), class IN (1), TTL 60, rdlen 4, rdata + msg.extend_from_slice(&[0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 198, 18, 2, 3]); + let rdata_off = msg.len() - 4; + assert!(super::answer_has_fake_ip(&msg), "198.18.2.3 is a Fake-IP answer (#367)"); + msg[rdata_off..].copy_from_slice(&[198, 19, 0, 42]); + assert!(super::answer_has_fake_ip(&msg), "198.19.0.42 is in 198.18.0.0/15"); + msg[rdata_off..].copy_from_slice(&super::super::net::HOST_ADDR); + assert!(!super::answer_has_fake_ip(&msg), "host.docker.internal is not a Fake-IP"); + msg[rdata_off..].copy_from_slice(&[104, 16, 25, 34]); + assert!(!super::answer_has_fake_ip(&msg), "real public IP is not a Fake-IP"); + } } diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 778d8deca..3edc41713 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -16,6 +16,9 @@ pub const UPLINK: &str = "eth0"; pub const HOST_ADDR: [u8; 4] = [198, 19, 248, 254]; /// Where the redirect lands: the agent's listener for host-bound connections. pub const HOST_RELAY_PORT: u16 = 1026; +/// Where outbound container TCP connections to VPN tunnel prefixes or under +/// host egress land, to be relayed over vsock to the host dialer. +pub const EGRESS_RELAY_PORT: u16 = 1038; /// Container interfaces stay below this, so any uplink MTU fits. const CONTAINER_MTU: u32 = 1500; @@ -267,18 +270,91 @@ struct Nat { } static NAT: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Egress IPv4 CIDR prefixes redirected to `EGRESS_RELAY_PORT`. +static EGRESS_ROUTES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// Active bridge IPv4 subnets `(name, network, prefix)`, exempt from egress redirect. +static BRIDGE_SUBNETS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// The VM uplink's IPv4 subnet `(network, prefix)`, exempt from egress redirect. +static UPLINK_SUBNET: std::sync::Mutex> = std::sync::Mutex::new(None); /// The kernel has no nft_fib_ipv4 (`fib daddr type local`): ports /// published on every address are matched per address of this machine. static NO_FIB4: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +pub fn parse_cidr(s: &str) -> Option<([u8; 4], u8)> { + let (ip, prefix) = s.trim().split_once('/')?; + let ip = parse_ip(ip)?; + let prefix: u8 = prefix.parse().ok().filter(|&p| p <= 32)?; + Some((netlink::mask_ipv4(ip, prefix), prefix)) +} + +pub fn parse_egress_routes(list: kiri_proto::StrList<'_>) -> Vec<([u8; 4], u8)> { + let mut out = Vec::new(); + for s in list.iter() { + if let Some(c) = parse_cidr(s) + && !out.contains(&c) + { + out.push(c); + } + } + out +} + +/// Whether `routes` includes full host egress (`0.0.0.0/0`), in which case +/// guest upstream DNS lookups should go straight through the host DNS relay. +pub fn egress_prefers_dns_relay(routes: &[([u8; 4], u8)]) -> bool { + routes.iter().any(|&(_, prefix)| prefix == 0) +} + +/// Updates the IPv4 CIDR prefixes redirected to the host egress dialer and +/// rebuilds Kiri's IPv4 nftables table. +pub fn set_egress_routes(routes: Vec<([u8; 4], u8)>) -> io::Result<()> { + *EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()) = routes; + refresh_nat() +} + +fn egress_skip_subnets() -> Vec<([u8; 4], u8)> { + let mut skip = vec![ + ([127, 0, 0, 0], 8), + ([169, 254, 0, 0], 16), + ([224, 0, 0, 0], 3), + ]; + if let Some(up) = *UPLINK_SUBNET.lock().unwrap_or_else(|e| e.into_inner()) + && !skip.contains(&up) + { + skip.push(up); + } + for &(_, net, prefix) in BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).iter() { + if !skip.contains(&(net, prefix)) { + skip.push((net, prefix)); + } + } + skip +} + /// Builds Kiri's IPv4 table from `nat` and the bridges made so far, and /// keeps `nat` for `refresh_nat`. In the VM (`nat.redirect`), also installs /// the IPv6 `::1` loopback redirect and input guard on a best-effort basis. fn install_nat(nat: Nat) -> io::Result<()> { use std::sync::atomic::Ordering; let bridges = MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let egress = EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let skip = if egress.is_empty() { Vec::new() } else { egress_skip_subnets() }; let any_addr = nat.dnat.iter().any(|d| d.host_ip == [0; 4]); - let install = |local: Option<&[[u8; 4]]>| netlink::install_nat_from(nat.uplink, HOST_ADDR, HOST_RELAY_PORT, nat.redirect, &nat.dnat, nat.gateway, &bridges, local); + let install = |local: Option<&[[u8; 4]]>| { + netlink::install_nat_with_egress( + nat.uplink, + HOST_ADDR, + HOST_RELAY_PORT, + nat.redirect, + &nat.dnat, + nat.gateway, + &bridges, + local, + EGRESS_RELAY_PORT, + &egress, + &skip, + ) + }; let r = if any_addr && NO_FIB4.load(Ordering::Relaxed) { install(Some(&local_addrs())) } else { @@ -594,6 +670,8 @@ impl Dhcp { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; netlink::add_address(&mut nl, self.index, lease.ip, lease.prefix)?; netlink::add_default_route(&mut nl, self.index, lease.gateway)?; + *UPLINK_SUBNET.lock().unwrap_or_else(|e| e.into_inner()) = Some((netlink::mask_ipv4(lease.ip, lease.prefix), lease.prefix)); + let _ = refresh_nat(); self.state = DhcpState::Bound; self.lease = Some(lease); return Ok(true); @@ -716,6 +794,7 @@ impl Bridges { let _ = netlink::delete_link(&mut nl, name); } MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|m| m != name); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(m, ..)| m != name); let had6 = matches!(self.made.remove(name), Some((.., Some(_)))); let _ = refresh_nat(); if had6 { @@ -744,6 +823,13 @@ impl Bridges { made.push(name.to_owned()); } drop(made); + { + let mut subs = BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()); + subs.retain(|(m, ..)| m != name); + if let Some(g) = gateway { + subs.push((name.to_owned(), netlink::mask_ipv4(g, prefix), prefix)); + } + } let index = netlink::index_of(name)?; if let Some(g) = gateway { netlink::add_address(&mut nl, index, g, prefix)?; @@ -777,6 +863,7 @@ impl Bridges { let _ = netlink::delete_link(&mut nl, name); } MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|m| m != name); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(m, ..)| m != name); if let Err(e) = refresh_nat() { eprintln!("kiri-init: NAT: {e}"); } @@ -865,6 +952,8 @@ static MADE_BRIDGES: std::sync::Mutex> = std::sync::Mutex::new(Vec:: /// nftables table, so nothing of the engine is left in the host's network. pub fn remove_host_network() { let names = std::mem::take(&mut *MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner())); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).clear(); + EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clear(); if let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { for name in names { let _ = netlink::delete_link(&mut nl, &name); diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index e058e1081..2af717914 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -485,12 +485,40 @@ fn nat_chain(name: &str, hook: u32, priority: i32) -> Msg { /// Kiri's container bridges are kiri0, kiri1, … (the daemon names them). const BRIDGE_PREFIX: &[u8] = b"kiri"; -/// `ip daddr tcp redirect to :`: connections to `addr` (any -/// port) go to a local listener, which can read the original port back. -/// With `from_bridges`, only packets arriving on a Kiri bridge match -/// (`iifname "kiri*"`): the redirect leads to the host's loopback, which -/// nothing on the uplink (the LAN, on a Linux host) may reach. -fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { +/// Netmask bytes for an IPv4 CIDR prefix length (`0..=32`). +pub fn ipv4_mask(prefix: u8) -> [u8; 4] { + let p = prefix.min(32); + if p == 0 { [0; 4] } else { (u32::MAX << (32 - p)).to_be_bytes() } +} + +/// Masks `ip` to its `prefix`-bit network address. +pub fn mask_ipv4(ip: [u8; 4], prefix: u8) -> [u8; 4] { + let m = ipv4_mask(prefix); + [ip[0] & m[0], ip[1] & m[1], ip[2] & m[2], ip[3] & m[3]] +} + +fn match_daddr_prefix(rule: &mut Msg, addr: [u8; 4], prefix: u8) { + let p = prefix.min(32); + if p == 0 { + return; + } + // payload network header + 16 (daddr), 4 bytes => reg 1 + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + if p < 32 { + let mask = ipv4_mask(p); + let net = mask_ipv4(addr, p); + rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); + rule.nest(4).attr(1, &mask).end().nest(5).attr(1, &[0; 4]).end().end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &net).end().end().end(); + } else { + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + } +} + +/// `ip daddr / tcp redirect to :`: connections to +/// `addr/prefix` (any port) go to a local listener, which can read the +/// original destination and port back via `SO_ORIGINAL_DST`. +fn redirect_prefix_rule(chain: &str, addr: [u8; 4], prefix: u8, port: u16, from_bridges: bool) -> Msg { let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, chain); rule.nest(4); @@ -503,9 +531,7 @@ fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> M // meta l4proto => reg 1; cmp eq tcp rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); - // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr - rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); - rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + match_daddr_prefix(&mut rule, addr, prefix); // immediate reg 1 = port; redir to it rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &port.to_be_bytes()).end().end().end(); rule.nest(1).attr_str(1, "redir").nest(2).attr_be32(1, 1).end().end(); @@ -513,6 +539,33 @@ fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> M rule } +/// `ip daddr / tcp accept`: exempts local, bridge and uplink +/// subnets from subsequent broader egress redirect rules (such as `0.0.0.0/0`). +fn accept_prefix_rule(chain: &str, addr: [u8; 4], prefix: u8, from_bridges: bool) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, chain); + rule.nest(4); + if from_bridges { + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + } + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + match_daddr_prefix(&mut rule, addr, prefix); + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_ACCEPT as u32).end().end().end().end(); + rule.end(); + rule +} + +/// `ip daddr tcp redirect to :`: connections to `addr` (any +/// port) go to a local listener, which can read the original port back. +/// With `from_bridges`, only packets arriving on a Kiri bridge match +/// (`iifname "kiri*"`): the redirect leads to the host's loopback, which +/// nothing on the uplink (the LAN, on a Linux host) may reach. +fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { + redirect_prefix_rule(chain, addr, 32, port, from_bridges) +} + /// `iifname "kiri*" ip daddr udp dport 53 redirect to :53`: DNS /// sent to the host's address goes to the embedded DNS on the receiving /// bridge's gateway. A kind node rewrites its resolv.conf from 127.0.0.11 to @@ -688,6 +741,30 @@ fn forward_guard(family: u8) -> Option { FORWARD_GUARD.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(up4, up6)| if family == libc::NFPROTO_IPV6 as u8 { up6.clone() } else { up4.clone() }) } +/// `tcp flags syn tcp option maxseg size set rt mtu`: clamps the TCP MSS on +/// forwarded SYN packets to the route's path MTU. +fn tcp_mss_clamp_rule(family: u8) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, "forward"); + rule.nest(4); + // meta l4proto => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload transport header + 13 (tcp flags), 1 byte => reg 1; (reg 1 & 0x02) != 0 (SYN) + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 13).attr_be32(4, 1).end().end(); + rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 1); + rule.nest(4).attr(1, &[0x02]).end().nest(5).attr(1, &[0x00]).end().end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &[0x00]).end().end().end(); + // rt load tcpmss (NFT_RT_TCPMSS = 3) => reg 1 + rule.nest(1).attr_str(1, "rt").nest(2).attr_be32(1, 1).attr_be32(2, 3).end().end(); + // byteorder reg 1 = hton(reg 1, 2, 2) (NFT_BYTEORDER_HTON = 1) + rule.nest(1).attr_str(1, "byteorder").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 1).attr_be32(4, 2).attr_be32(5, 2).end().end(); + // exthdr write tcpopt reg 1 => 2b @ 2 + 2 (type 2 = TCPOPT_MAXSEG, op 1 = NFT_EXTHDR_OP_TCPOPT) + rule.nest(1).attr_str(1, "exthdr").nest(2).attr_be32(7, 1).attr(2, &[2]).attr_be32(3, 2).attr_be32(4, 2).attr_be32(6, 1).end().end(); + rule.end(); + rule +} + /// `forward_filter` for a table of `family`: the same rules hold for IPv6. /// `guard`: the uplink, while `FORWARD_GUARD` holds one. fn forward_filter_in(family: u8, bridges: &[String], guard: Option<&str>) -> Vec { @@ -759,6 +836,7 @@ fn forward_filter_in(family: u8, bridges: &[String], guard: Option<&str>) -> Vec drop, )); } + msgs.push(tcp_mss_clamp_rule(family)); msgs.extend([ rule(&ifname(7, 1), accept), // NFT_CMP_NEQ rule(&ct_any(0, CT_ESTABLISHED | CT_RELATED), accept), // NFT_CT_STATE @@ -1141,7 +1219,19 @@ pub fn remove_nat() -> io::Result<()> { /// the uplink's gateway `gateway` (the Mac itself): other VMs on the NAT /// network, or the LAN routed through the Mac, never reach a container. #[allow(clippy::too_many_arguments)] -pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, redirect: bool, dnat: &[Dnat], gateway: [u8; 4], bridges: &[String], local: Option<&[[u8; 4]]>) -> io::Result<()> { +pub fn install_nat_with_egress( + uplink_index: i32, + host_addr: [u8; 4], + host_port: u16, + redirect: bool, + dnat: &[Dnat], + gateway: [u8; 4], + bridges: &[String], + local: Option<&[[u8; 4]]>, + egress_port: u16, + egress_routes: &[([u8; 4], u8)], + egress_skip: &[([u8; 4], u8)], +) -> io::Result<()> { let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; // The table is replaced, not appended to (on a Linux host it outlives // the agent and changes with every published port), in one batch: @@ -1172,6 +1262,7 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let have_egress = egress_port != 0 && !egress_routes.is_empty(); if !redirect { // A Linux host: no host.docker.internal redirect, but its published // ports are DNATed here (prerouting for the LAN, output for the host @@ -1179,12 +1270,23 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r let mut msgs = vec![begin, add, delete, table, chain, rule]; msgs.extend(forward_filter(bridges, forward_guard(libc::NFPROTO_IPV4 as u8).as_deref())); msgs.extend(localnet_guard()); + if have_egress { + msgs.push(host_relay_guard(egress_port)); + } msgs.push(nat_chain("prerouting", 0, -100)); msgs.push(nat_chain("output", 3, -100)); for d in dnat { msgs.extend(dnat_rules("prerouting", d, local)); msgs.extend(dnat_rules("output", d, local)); } + if have_egress { + for &(subnet, prefix) in egress_skip { + msgs.push(accept_prefix_rule("prerouting", subnet, prefix, true)); + } + for &(dst, prefix) in egress_routes { + msgs.push(redirect_prefix_rule("prerouting", dst, prefix, egress_port, true)); + } + } msgs.push(end); return nl.request(&mut msgs); } @@ -1198,6 +1300,9 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r msgs.extend(forward_filter(bridges, forward_guard(libc::NFPROTO_IPV4 as u8).as_deref())); msgs.extend(localnet_guard()); msgs.push(host_relay_guard(host_port)); + if have_egress { + msgs.push(host_relay_guard(egress_port)); + } for d in dnat.iter().filter(|d| !d.udp) { if d.host_ip == LOOPBACK { // A port the Mac has on its loopback, for the VM's own @@ -1212,6 +1317,16 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)))); } } + if have_egress { + for &(subnet, prefix) in egress_skip { + msgs.push(accept_prefix_rule("prerouting", subnet, prefix, true)); + msgs.push(accept_prefix_rule("output", subnet, prefix, false)); + } + for &(dst, prefix) in egress_routes { + msgs.push(redirect_prefix_rule("prerouting", dst, prefix, egress_port, true)); + msgs.push(redirect_prefix_rule("output", dst, prefix, egress_port, false)); + } + } if dnat.iter().any(|d| !d.udp && d.host_ip != LOOPBACK) { msgs.push(published_masq_rule(uplink_index, gateway)); } @@ -1374,8 +1489,9 @@ mod tests { #[test] fn forward_keeps_networks_apart() { let msgs = forward_filter(&["kiri1".to_owned(), "kiri22".to_owned()], None); - assert_eq!(msgs.len(), 7); - let rules = &msgs[1..]; + assert_eq!(msgs.len(), 8); + assert_eq!(names(&msgs[1]), ["meta", "cmp", "payload", "bitwise", "cmp", "rt", "byteorder", "exthdr"], "SYN MSS clamping to route MTU"); + let rules = &msgs[2..]; // Nothing from a bridge is accepted on the interface name alone: that // let any network reach any other. for r in rules { @@ -1408,6 +1524,22 @@ mod tests { assert_eq!(be32(get(&exprs(&rules[2])[0].1, 2)), 2, "ct status"); } + #[test] + fn egress_prefix_redirect_and_accept_rules_match_cidr() { + let r24 = redirect_prefix_rule("prerouting", [10, 0, 5, 10], 24, 1038, true); + assert_eq!(names(&r24), ["meta", "cmp", "meta", "cmp", "payload", "bitwise", "cmp", "immediate", "redir"]); + let e = exprs(&r24); + assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &[255, 255, 255, 0]); + assert_eq!(get(&attrs(get(&e[6].1, 3)), 1), &[10, 0, 5, 0]); + + let r0 = redirect_prefix_rule("output", [0, 0, 0, 0], 0, 1038, false); + assert_eq!(names(&r0), ["meta", "cmp", "immediate", "redir"], "0.0.0.0/0 needs no payload daddr match"); + + let skip = accept_prefix_rule("prerouting", [172, 17, 0, 1], 16, true); + assert_eq!(names(&skip), ["meta", "cmp", "meta", "cmp", "payload", "bitwise", "cmp", "immediate"]); + assert_eq!(verdict(&skip), libc::NF_ACCEPT as u32); + } + #[test] fn with_firewalld_new_connections_leave_only_through_the_uplink() { let bridges = ["kiri0".to_owned()]; diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index e7c455725..ca2ea2fbf 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -383,6 +383,132 @@ pub fn listen_host_bound(port: u16) -> io::Result { /// The host side listens on this vsock port for host-bound connections. pub const HOST_VSOCK_PORT: u32 = 1026; +/// The host side listens on this vsock port for outbound TCP connections +/// redirected from containers (split-tunnel VPN routes, network extensions). +pub const EGRESS_VSOCK_PORT: u32 = kiri_proto::EGRESS_TCP_PORT; + +/// Whether a redirected container connection's original destination may be +/// sent to the host egress dialer: never loopback, unspecified, link-local, +/// multicast/reserved, port 0, or `host.docker.internal` (which has its own +/// listener). +pub fn egress_dst_allowed(ip: [u8; 4], port: u16, host_addr: [u8; 4]) -> bool { + port != 0 + && ip[0] != 0 + && ip[0] != 127 + && !(ip[0] == 169 && ip[1] == 254) + && ip[0] < 224 + && ip != host_addr +} + +/// Accepts one connection redirected by an egress route rule, reads the +/// original IPv4 destination and port via `SO_ORIGINAL_DST`, dials the host on +/// `EGRESS_VSOCK_PORT` with `ip[4] port[2]`, and returns a relay between the +/// two. Direct connections not redirected by netfilter are dropped by +/// `host_relay_guard` in the input chain and rejected here if their +/// destination is local or forbidden. +pub fn accept_egress(listener: &OwnedFd, host_addr: [u8; 4]) -> Option { + accept_egress_with(listener, host_addr, || dial_host(EGRESS_VSOCK_PORT)) +} + +pub fn accept_egress_with( + listener: &OwnedFd, + host_addr: [u8; 4], + dial: impl FnOnce() -> io::Result, +) -> Option { + // SAFETY: accept4 on a listening socket we own; the fd is owned immediately. + let fd = unsafe { + libc::accept4( + listener.as_raw_fd(), + std::ptr::null_mut(), + std::ptr::null_mut(), + libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, + ) + }; + if fd < 0 { + return None; + } + // SAFETY: `fd` is a fresh descriptor that nothing else owns. + let client = unsafe { OwnedFd::from_raw_fd(fd) }; + let one: libc::c_int = 1; + // SAFETY: setting TCP_NODELAY on a stream socket we own. + unsafe { + libc::setsockopt( + client.as_raw_fd(), + libc::IPPROTO_TCP, + libc::TCP_NODELAY, + (&one as *const libc::c_int).cast(), + 4, + ); + } + // SAFETY: SO_ORIGINAL_DST fills a sockaddr_in with the pre-redirect destination. + let (ip, port) = unsafe { + let mut dst: libc::sockaddr_in = std::mem::zeroed(); + let mut len = std::mem::size_of::() as u32; + const SO_ORIGINAL_DST: libc::c_int = 80; + if libc::getsockopt( + client.as_raw_fd(), + libc::SOL_IP, + SO_ORIGINAL_DST, + (&mut dst as *mut libc::sockaddr_in).cast(), + &mut len, + ) != 0 + { + return Some(Relay::dead_one(client)); + } + let mut local: libc::sockaddr_in = std::mem::zeroed(); + let mut local_len = std::mem::size_of::() as u32; + if libc::getsockname( + listener.as_raw_fd(), + (&mut local as *mut libc::sockaddr_in).cast(), + &mut local_len, + ) == 0 + && dst.sin_port == local.sin_port + && (dst.sin_addr.s_addr == local.sin_addr.s_addr || local.sin_addr.s_addr == 0) + { + // A direct non-redirected connection to the listener's own port has + // SO_ORIGINAL_DST equal to the socket's local endpoint; reject it + // if the port matches and the IP is one of this machine's own. + let mut own: libc::sockaddr_in = std::mem::zeroed(); + let mut own_len = std::mem::size_of::() as u32; + if libc::getsockname( + client.as_raw_fd(), + (&mut own as *mut libc::sockaddr_in).cast(), + &mut own_len, + ) == 0 + && dst.sin_addr.s_addr == own.sin_addr.s_addr + { + return Some(Relay::dead_one(client)); + } + } + (dst.sin_addr.s_addr.to_ne_bytes(), u16::from_be(dst.sin_port)) + }; + if !egress_dst_allowed(ip, port, host_addr) { + return Some(Relay::dead_one(client)); + } + let Ok(host) = dial() else { + return Some(Relay::dead_one(client)); + }; + let mut header = [ip[0], ip[1], ip[2], ip[3], 0, 0]; + header[4..].copy_from_slice(&port.to_be_bytes()); + // SAFETY: a 6-byte write to a just-connected stream; the socket buffer is empty. + if unsafe { libc::write(host.as_raw_fd(), header.as_ptr().cast(), 6) } != 6 { + return Some(Relay::dead_one(client)); + } + if sys::set_nonblocking(host.as_raw_fd()).is_err() { + return Some(Relay::dead_one(client)); + } + Some(Relay { + host, + target: Some(client), + connected: true, + header: Vec::new(), + up: Pipe::new(), + down: Pipe::new(), + dead: false, + udp: false, + framed: false, + }) +} /// Accepts one redirected connection, finds the port the container meant, /// dials the Mac and returns a relay between the two. Only connections that @@ -726,4 +852,212 @@ mod tests { assert_eq!(super::listen_ssh_agent_at(&long).unwrap_err().kind(), std::io::ErrorKind::InvalidInput); let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn egress_dst_guard_rejects_local_and_allows_vpn_and_public_destinations() { + let host = super::super::net::HOST_ADDR; + assert!(!super::egress_dst_allowed([127, 0, 0, 1], 443, host)); + assert!(!super::egress_dst_allowed([0, 0, 0, 0], 443, host)); + assert!(!super::egress_dst_allowed([169, 254, 169, 254], 80, host)); + assert!(!super::egress_dst_allowed([224, 0, 0, 1], 80, host)); + assert!(!super::egress_dst_allowed([255, 255, 255, 255], 80, host)); + assert!(!super::egress_dst_allowed(host, 80, host)); + assert!(!super::egress_dst_allowed([10, 0, 5, 10], 0, host)); + assert!(super::egress_dst_allowed([10, 0, 5, 10], 443, host)); + assert!(super::egress_dst_allowed([10, 254, 99, 10], 8443, host)); + assert!(super::egress_dst_allowed([198, 18, 2, 3], 443, host)); + } + + #[test] + fn egress_redirect_relays_vpn_tcp_with_original_dst_and_exempts_bridge_peers() { + use std::io::{Read, Write}; + use super::super::{net, netlink, sys}; + + // Requires root (CAP_NET_ADMIN / CLONE_NEWNET) on Linux. + if unsafe { libc::geteuid() } != 0 { + return; + } + + let spawn_netns_holder = || -> (libc::pid_t, std::fs::File) { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0); + let pid = unsafe { libc::fork() }; + assert!(pid >= 0); + if pid == 0 { + unsafe { + libc::close(pipe[0]); + if libc::unshare(libc::CLONE_NEWNET) != 0 { + libc::_exit(1); + } + let _ = libc::write(pipe[1], b"1".as_ptr().cast(), 1); + libc::close(pipe[1]); + loop { + libc::pause(); + } + } + } + unsafe { libc::close(pipe[1]) }; + let mut b = [0u8; 1]; + assert_eq!(unsafe { libc::read(pipe[0], b.as_mut_ptr().cast(), 1) }, 1); + unsafe { libc::close(pipe[0]) }; + let ns = std::fs::File::open(format!("/proc/{pid}/ns/net")).expect("open child netns"); + (pid, ns) + }; + + // Run inside a forked child with its own root network namespace so the + // host machine's interfaces and nftables rules are never touched. + let child = unsafe { libc::fork() }; + assert!(child >= 0); + if child == 0 { + unsafe { + if libc::unshare(libc::CLONE_NEWNET) != 0 { + libc::_exit(2); + } + } + let mut nl = netlink::Netlink::open(libc::NETLINK_ROUTE).unwrap(); + netlink::set_up(&mut nl, 1).unwrap(); + netlink::create_bridge(&mut nl, "eth0").unwrap(); + let eth0 = netlink::index_of("eth0").unwrap(); + netlink::add_address(&mut nl, eth0, [192, 168, 64, 2], 24).unwrap(); + netlink::set_up(&mut nl, eth0).unwrap(); + netlink::add_default_route(&mut nl, eth0, [192, 168, 64, 1]).unwrap(); + sys::write_file("/proc/sys/net/ipv4/ip_forward", "1").unwrap(); + + let (c1_pid, c1_ns) = spawn_netns_holder(); + let (c2_pid, c2_ns) = spawn_netns_holder(); + + let mut bridges = net::Bridges::default(); + net::attach_container( + &mut bridges, + "kiri0", + "kv_eg1", + c1_pid, + [172, 18, 0, 2], + 16, + [172, 18, 0, 1], + None, + None, + net::Plug::default(), + ) + .unwrap(); + net::attach_container( + &mut bridges, + "kiri0", + "kv_eg2", + c2_pid, + [172, 18, 0, 3], + 16, + [172, 18, 0, 1], + None, + None, + net::Plug::default(), + ) + .unwrap(); + + let skip = [([127, 0, 0, 0], 8), ([172, 18, 0, 0], 16), ([192, 168, 64, 0], 24)]; + netlink::install_nat_with_egress( + eth0, + net::HOST_ADDR, + net::HOST_RELAY_PORT, + true, + &[], + [192, 168, 64, 1], + &["kiri0".to_owned()], + None, + net::EGRESS_RELAY_PORT, + &[([10, 254, 99, 0], 24)], + &skip, + ) + .unwrap(); + + let listener = super::listen_host_bound(net::EGRESS_RELAY_PORT).unwrap(); + + // 1) Container 1 dials mock VPN destination 10.254.99.10:8443. + let c1_sock = netlink::in_netns(&c1_ns, || super::connect([10, 254, 99, 10], 8443)).unwrap(); + let mut pfd = libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut pfd, 1, 2000) }, 1, "egress listener must receive redirected SYN"); + + let mut pair = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0, pair.as_mut_ptr()) }, 0); + let mut mock_host = unsafe { std::fs::File::from_raw_fd(pair[0]) }; + let relay_host = unsafe { OwnedFd::from_raw_fd(pair[1]) }; + + let mut relay = super::accept_egress_with(&listener, net::HOST_ADDR, || Ok(relay_host)).expect("accept_egress"); + assert!(!relay.dead, "redirected VPN connection must be accepted"); + + let mut hdr = [0u8; 6]; + mock_host.read_exact(&mut hdr).unwrap(); + assert_eq!(hdr, [10, 254, 99, 10, 0x20, 0xfb], "SO_ORIGINAL_DST must report 10.254.99.10:8443"); + + let mut c1_pfd = libc::pollfd { fd: c1_sock.as_raw_fd(), events: libc::POLLOUT, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut c1_pfd, 1, 2000) }, 1); + let req = b"GET /vpn HTTP/1.1\r\n\r\n"; + assert_eq!(unsafe { libc::write(c1_sock.as_raw_fd(), req.as_ptr().cast(), req.len()) }, req.len() as isize); + + relay.step(); + let mut got_req = vec![0u8; req.len()]; + mock_host.read_exact(&mut got_req).unwrap(); + assert_eq!(got_req, req); + + let resp = b"HTTP/1.1 200 OK\r\n\r\nvpn-ok"; + mock_host.write_all(resp).unwrap(); + drop(mock_host); + + for _ in 0..20 { + relay.step(); + if relay.dead { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + unsafe { + let flags = libc::fcntl(c1_sock.as_raw_fd(), libc::F_GETFL); + libc::fcntl(c1_sock.as_raw_fd(), libc::F_SETFL, flags & !libc::O_NONBLOCK); + } + let mut c1_file = unsafe { std::fs::File::from_raw_fd(c1_sock.as_raw_fd()) }; + std::mem::forget(c1_sock); + let mut got_resp = vec![0u8; resp.len()]; + c1_file.read_exact(&mut got_resp).unwrap(); + assert_eq!(got_resp, resp); + let mut eof = [0u8; 1]; + assert_eq!(c1_file.read(&mut eof).unwrap(), 0, "relay must pass clean EOF to container"); + + // 2) Even under full host egress (0.0.0.0/0), container-to-container + // TCP on the bridge (172.18.0.2 -> 172.18.0.3:9090) is exempt and + // connects directly without hitting the egress relay listener. + netlink::install_nat_with_egress( + eth0, + net::HOST_ADDR, + net::HOST_RELAY_PORT, + true, + &[], + [192, 168, 64, 1], + &["kiri0".to_owned()], + None, + net::EGRESS_RELAY_PORT, + &[([0, 0, 0, 0], 0)], + &skip, + ) + .unwrap(); + + let peer_listener = netlink::in_netns(&c2_ns, || std::net::TcpListener::bind("172.18.0.3:9090")).unwrap(); + let mut peer_client = netlink::in_netns(&c1_ns, || std::net::TcpStream::connect("172.18.0.3:9090")).unwrap(); + let mut check_egress = libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut check_egress, 1, 50) }, 0, "bridge peer traffic must not hit egress listener"); + let (mut peer_accepted, _) = peer_listener.accept().unwrap(); + peer_client.write_all(b"peer-ping").unwrap(); + let mut peer_buf = [0u8; 9]; + peer_accepted.read_exact(&mut peer_buf).unwrap(); + assert_eq!(&peer_buf, b"peer-ping"); + + unsafe { + libc::kill(c1_pid, libc::SIGKILL); + libc::kill(c2_pid, libc::SIGKILL); + libc::_exit(0); + } + } + let mut status: libc::c_int = 0; + assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, "child failed with status {status}"); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index f6aa57557..292ce064c 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -54,8 +54,11 @@ pub const INPUT_WINDOW: usize = 4 << 20; /// the same reason. 9 added `Limits::swap_max`: an older agent would read /// the limits one field short. 10 added a payload on `MemoryPressure` /// (MemAvailable and PSI full avg10): an older agent's bare `MemoryPressure` -/// has neither field, so decode rejects it as truncated. -pub const PROTOCOL: u16 = 10; +/// has neither field, so decode rejects it as truncated. 11 added +/// `SetEgressRoutes`, another no-reply message (sent on every VM boot): an +/// older agent's "unexpected" error would be taken as the reply to the next +/// request. +pub const PROTOCOL: u16 = 11; /// Most names a `DnsRename` may carry: a name, its aliases and a hostname. pub const MAX_DNS_NAMES: usize = 256; @@ -240,6 +243,12 @@ pub enum Msg<'a> { /// request; the VM runs inside the daemon process today, so the two /// versions cannot differ. FsEvents(StrList<'a>), + /// Host → guest: IPv4 CIDR prefixes (`a.b.c.d/prefix`) whose outbound + /// container TCP connections are redirected to the agent and relayed over + /// [`EGRESS_TCP_PORT`] for the host to dial (split-tunnel VPN routes, + /// security network extensions, or `0.0.0.0/0` under host egress). Empty + /// clears the redirect rules. No reply. + SetEgressRoutes(StrList<'a>), /// Success, for requests with nothing else to say. Ack, } @@ -252,6 +261,11 @@ pub const COPY_PORT: u32 = 1028; /// TCP frames it, and gets `u16 len | reply` back: one lookup per connection. pub const DNS_RELAY_PORT: u32 = 1037; +/// vsock port of the host's outbound TCP relay. The agent sends `ip[4] port[2]` +/// for a connection redirected from a container, and the host dials it and +/// relays bytes both ways. +pub const EGRESS_TCP_PORT: u32 = 1038; + /// vsock port of the guest's USB passthrough: one connection per device, /// `speed u32 | devid u32` then USB/IP (crates/kiri-init/src/linux/usb.rs). pub const USB_PORT: u32 = 1040; @@ -856,6 +870,7 @@ mod kind { pub const DNS_RENAME: u16 = 81; pub const FS_READ_LINK: u16 = 82; pub const SET_UPLINK: u16 = 83; + pub const SET_EGRESS_ROUTES: u16 = 84; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -925,10 +940,15 @@ pub fn encode_net_attach>(out: &mut Vec, id: &str, ifname: &st } /// Whether `frame` is of a kind the guest answers with no reply -/// (`DnsRename`): one that doesn't decode is then dropped, not answered -/// with an `Error` the host would read as the next request's reply. +/// (`DnsRename`, `SetEgressRoutes`): one that doesn't decode is then dropped, +/// not answered with an `Error` the host would read as the next request's reply. pub fn takes_no_reply(frame: &[u8]) -> bool { - frame.len() >= HEADER && u16::from_le_bytes([frame[4], frame[5]]) == kind::DNS_RENAME + frame.len() >= HEADER && matches!(u16::from_le_bytes([frame[4], frame[5]]), kind::DNS_RENAME | kind::SET_EGRESS_ROUTES) +} + +/// Encodes a `SetEgressRoutes` frame from the sender's CIDR strings. +pub fn encode_set_egress_routes>(out: &mut Vec, routes: &[S]) { + frame(out, kind::SET_EGRESS_ROUTES, |out| StrList::put_capped(out, routes, MAX_BODY)); } /// Encodes a `DnsRename` frame from the sender's slices. @@ -1246,6 +1266,10 @@ impl Msg<'_> { put_u32(o, lines.count); o.extend_from_slice(lines.raw); }), + Msg::SetEgressRoutes(routes) => frame(out, kind::SET_EGRESS_ROUTES, |o| { + put_u32(o, routes.count); + o.extend_from_slice(routes.raw); + }), Msg::Listening(lines) => frame(out, kind::LISTENING, |o| { put_u32(o, lines.count); o.extend_from_slice(lines.raw); @@ -1556,6 +1580,7 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::USB_NODES_QUERY => Msg::UsbNodesQuery, kind::USB_NODES => Msg::UsbNodes(r.list()?), kind::FS_EVENTS => Msg::FsEvents(r.list()?), + kind::SET_EGRESS_ROUTES => Msg::SetEgressRoutes(r.list()?), kind::NET_ATTACH => Msg::NetAttach { id: r.str()?, ifname: r.str()?, @@ -1873,6 +1898,16 @@ mod tests { const { assert!(PROTOCOL >= 8) }; } + #[test] + fn the_protocol_version_covers_set_egress_routes() { + // An agent from before `SetEgressRoutes` answers it with an error + // that the host would take as the reply to its next request. + const { assert!(PROTOCOL >= 11) }; + let mut buf = Vec::new(); + encode_set_egress_routes(&mut buf, &["10.0.5.0/24"]); + assert!(takes_no_reply(&buf)); + } + #[test] fn the_protocol_version_covers_swap_max() { // An agent from before `Limits::swap_max` reads the limits one field short. @@ -1928,6 +1963,11 @@ mod tests { let Msg::FsEvents(lines) = decode(&buf).unwrap() else { panic!() }; assert_eq!(lines.iter().collect::>(), ["M\t/mnt/mac/Users/a/app/main.js", "D\t/mnt/mac/Users/a/app/old.js"]); let mut buf = Vec::new(); + encode_set_egress_routes(&mut buf, &["10.0.5.0/24", "198.18.0.0/15"]); + let Msg::SetEgressRoutes(routes) = decode(&buf).unwrap() else { panic!() }; + assert_eq!(routes.iter().collect::>(), ["10.0.5.0/24", "198.18.0.0/15"]); + assert!(takes_no_reply(&buf)); + let mut buf = Vec::new(); encode_listening(&mut buf, &[" 0: 00000000:11D7 00000000:0000 0A"]); let Msg::Listening(lines) = decode(&buf).unwrap() else { panic!() }; assert_eq!(lines.iter().collect::>(), [" 0: 00000000:11D7 00000000:0000 0A"]); @@ -2040,6 +2080,7 @@ mod tests { ("usage", encode_usage::), ("usb_nodes", encode_usb_nodes::), ("fs_events", encode_fs_events::), + ("set_egress_routes", encode_set_egress_routes::), ("listening", encode_listening::), ]; // Exact single-item fit (MAX_BODY - 8 bytes) and 1 byte over. diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 98867cba6..27b780944 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1645,6 +1645,8 @@ impl Engine { })?); // host.docker.internal: the guest dials back for each connection. vm.listen(super::ports::HOST_BOUND_PORT, Box::new(super::ports::serve_host_bound))?; + // Outbound container TCP to VPN tunnel routes or under host egress. + vm.listen(kiri_proto::EGRESS_TCP_PORT, Box::new(super::ports::serve_egress))?; // SSH agent forwarding, for containers that mount /run/host-services/ssh-auth.sock. vm.listen(super::ports::SSH_AGENT_PORT, Box::new(super::ports::serve_ssh_agent))?; // The engine's API, for containers that mount /var/run/docker.sock @@ -1658,6 +1660,16 @@ impl Engine { if cfg!(target_os = "macos") { vm.listen(kiri_proto::DNS_RELAY_PORT, Box::new(super::dns::serve_relay))?; } + // The VM's own NAT subnet, which the host egress dialer must refuse + // (VM only). Without a lease yet the default subnet still covers it, + // and publishing a port learns it again. + if cfg!(target_os = "macos") { + match vm.uplink() { + Ok((_ip, gateway)) => super::ports::set_vm_subnet(gateway, super::ports::VM_UPLINK_PREFIX), + Err(e) => crate::diag::debug!("VM uplink not known yet", error = e), + } + } + super::ports::sync_egress_routes(&vm); // Everything else on the guest's disk belongs to containers that are // gone, unless the container list was damaged: then a container // missing from it may still be someone's, and so may the layers only diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index 64212de5f..756c9568b 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -554,7 +554,8 @@ fn loopback_ports<'a>(bound: impl Iterator) -> Vec<( /// Asks the agent to forward a guest port to each container port, from the /// Mac only; returns the address the Mac dials for each. All or nothing. fn publish_nat(vm: &VmLink, id: &str, container_ports: &[u16], target_ip: [u8; 4]) -> io::Result<(Vec, Vec)> { - let (guest_ip, _gateway) = vm.uplink()?; + let (guest_ip, gateway) = vm.uplink()?; + set_vm_subnet(gateway, VM_UPLINK_PREFIX); let mut addrs = Vec::with_capacity(container_ports.len()); let mut ports = Vec::with_capacity(container_ports.len()); for &to_port in container_ports { @@ -1052,6 +1053,707 @@ fn host_bound_allowed(ip: std::net::Ipv4Addr, port: u16, router: impl Fn(u16) -> ip == std::net::Ipv4Addr::LOCALHOST && !router(port) } +/// How long an outbound host-dialed TCP connection waits to connect. +const EGRESS_CONNECT: Duration = Duration::from_secs(10); +/// Default macOS `VZNATNetworkDeviceAttachment` (`bridge100`) subnet. +pub const DEFAULT_VM_SUBNET: ([u8; 4], u8) = ([192, 168, 64, 0], 24); +/// RFC 2544 benchmarking range used as a synthetic Fake-IP pool by macOS +/// security network extensions (#367). +pub const FAKE_IP_CIDR: ([u8; 4], u8) = ([198, 18, 0, 0], 15); +/// Prefix of the VM's NAT uplink: `VZNATNetworkDeviceAttachment` leases a /24. +pub const VM_UPLINK_PREFIX: u8 = 24; +/// Additional VM NAT bridge subnets learned at runtime (`bridge100`, guest +/// uplink), via `set_vm_subnet`. +static VM_SUBNETS: Mutex> = Mutex::new(Vec::new()); + +pub fn ipv4_mask(prefix: u8) -> u32 { + let p = prefix.min(32); + if p == 0 { 0 } else { u32::MAX << (32 - p) } +} + +pub fn mask_ipv4(ip: [u8; 4], prefix: u8) -> [u8; 4] { + (u32::from_be_bytes(ip) & ipv4_mask(prefix)).to_be_bytes() +} + +pub fn cidr_contains(net: [u8; 4], prefix: u8, ip: [u8; 4]) -> bool { + let mask = ipv4_mask(prefix); + (u32::from_be_bytes(ip) & mask) == (u32::from_be_bytes(net) & mask) +} + +/// Whether the host egress dialer may connect to `ip:port` on behalf of a +/// container. Rejects loopback (`127.0.0.0/8`), unspecified (`0.0.0.0/8`), +/// link-local (`169.254.0.0/16`), multicast and reserved (`224.0.0.0/4`, +/// `240.0.0.0/4`, broadcast), `host.docker.internal` (`198.19.248.254`), +/// port 0, and the VM's own NAT bridge subnet (`192.168.64.0/24` and any +/// subnet in `vm_subnets`). +pub fn egress_allowed(ip: std::net::Ipv4Addr, port: u16, vm_subnets: &[([u8; 4], u8)]) -> bool { + let o = ip.octets(); + if port == 0 + || o[0] == 0 + || o[0] == 127 + || (o[0] == 169 && o[1] == 254) + || o[0] >= 224 + || o == [198, 19, 248, 254] + || cidr_contains(DEFAULT_VM_SUBNET.0, DEFAULT_VM_SUBNET.1, o) + || vm_subnets.iter().any(|&(net, prefix)| cidr_contains(net, prefix, o)) + { + return false; + } + true +} + +/// Records the VM's NAT uplink subnet, learned from the agent's `Uplink` +/// (its gateway is the Mac's side of the NAT network), so the host egress +/// dialer refuses it as it does `DEFAULT_VM_SUBNET` even when macOS picked +/// another bridge subnet. +pub fn set_vm_subnet(gateway: [u8; 4], prefix: u8) { + let prefix = prefix.min(32); + let net = (mask_ipv4(gateway, prefix), prefix); + let mut subnets = VM_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()); + if !subnets.contains(&net) { + subnets.push(net); + } +} + +fn current_vm_subnets() -> Vec<([u8; 4], u8)> { + VM_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// Whether the host egress dialer may connect to `ip:port` now, given the VM +/// NAT subnets learned so far. +fn egress_target_allowed(ip: std::net::Ipv4Addr, port: u16) -> bool { + egress_allowed(ip, port, ¤t_vm_subnets()) +} + +/// One outbound TCP connection redirected from a container to the host +/// dialer (`kiri_proto::EGRESS_TCP_PORT`): the guest sends `ip[4] port[2]`, +/// and the daemon dials it from the host process so macOS split-tunnel VPN +/// routes (`utun*`, `ipsec*`, `ppp*`, #319) and NetworkExtension socket +/// filters (#367, #616) carry the connection. +pub fn serve_egress(stream: kiri_vmm::VsockStream) { + let Some(permit) = tcp_permit(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)) else { + return; + }; + let _ = std::thread::Builder::new().name("kiri-egress".into()).spawn(move || { + let _permit = permit; + let _ = egress(stream); + }); +} + +fn egress(stream: kiri_vmm::VsockStream) -> io::Result<()> { + vsock_stall(stream.fd.as_raw_fd())?; + let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); + let mut header = [0u8; 6]; + from_guest.read_exact(&mut header)?; + let ip = std::net::Ipv4Addr::new(header[0], header[1], header[2], header[3]); + let port = u16::from_be_bytes([header[4], header[5]]); + if !egress_target_allowed(ip, port) { + crate::diag::warn!("refused an outbound egress connection to a restricted address", to = format!("{ip}:{port}")); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "egress target not allowed")); + } + let target = TcpStream::connect_timeout(&SocketAddr::from((ip, port)), EGRESS_CONNECT)?; + relayed_tcp(&target)?; + let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); + let mut target_read = target.try_clone()?; + let mut target_write = target; + let down = std::thread::Builder::new().name("kiri-egress-down".into()).spawn(move || { + let how = match pass_on(copy(&mut target_read, &mut to_guest)) { + Shutdown::Write => libc::SHUT_WR, + _ => libc::SHUT_RDWR, + }; + // SAFETY: shutting down a socket we own. + unsafe { libc::shutdown(to_guest.as_raw_fd(), how) }; + })?; + let up = copy(&mut from_guest, &mut target_write); + let _ = target_write.shutdown(pass_on(up)); + let _ = down.join(); + drop(stream); + Ok(()) +} + +/// Whether `name` is a tunnel interface that macOS `InternetSharing` does not +/// NAT `bridge100` out of (`utun*`, `ipsec*`, `ppp*`, `gpd*`, `feth*`). +pub fn is_tunnel_iface(name: &str) -> bool { + ["utun", "ipsec", "ppp", "gpd", "feth"] + .iter() + .any(|prefix| name.strip_prefix(prefix).is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))) +} + +/// Collapses a set of IPv4 CIDRs, removing duplicates and any sub-prefix +/// already covered by a broader prefix in the set. +pub fn collapse_cidrs(cidrs: impl IntoIterator) -> Vec<([u8; 4], u8)> { + let mut list: Vec<([u8; 4], u8)> = cidrs + .into_iter() + .map(|(ip, prefix)| { + let p = prefix.min(32); + (mask_ipv4(ip, p), p) + }) + .collect(); + list.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + list.dedup(); + let mut out: Vec<([u8; 4], u8)> = Vec::with_capacity(list.len()); + for (net, prefix) in list { + if !out.iter().any(|&(broader_net, broader_prefix)| broader_prefix <= prefix && cidr_contains(broader_net, broader_prefix, net)) { + out.push((net, prefix)); + } + } + out +} + +/// Parses a macOS `sysctl([CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0])` +/// binary routing table buffer and returns the collapsed IPv4 CIDR prefixes +/// whose outgoing interface is a tunnel (`is_tunnel_iface`), skipping +/// loopback, link-local and multicast/reserved destinations. +pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) -> Vec<([u8; 4], u8)> { + const RTM_HDR_LEN: usize = 92; + const RTM_VERSION: u8 = 5; + const RTF_UP: i32 = 0x1; + const RTF_HOST: i32 = 0x4; + const RTF_LLINFO: i32 = 0x400; + const RTF_WASCLONED: i32 = 0x20000; + const RTF_IFSCOPE: i32 = 0x1000000; + const AF_INET_U8: u8 = libc::AF_INET as u8; + + #[cfg(target_os = "macos")] + const _: () = assert!(std::mem::size_of::() == RTM_HDR_LEN); + + let mut entries: Vec<([u8; 4], u8, String)> = Vec::new(); + let mut off = 0; + while off + RTM_HDR_LEN <= buf.len() { + let msglen = u16::from_ne_bytes([buf[off], buf[off + 1]]) as usize; + if msglen < RTM_HDR_LEN || off + msglen > buf.len() { + break; + } + let msg = &buf[off..off + msglen]; + off += msglen; + + let version = msg[2]; + if version != RTM_VERSION { + continue; + } + let ifindex = u16::from_ne_bytes([msg[4], msg[5]]); + let flags = i32::from_ne_bytes([msg[8], msg[9], msg[10], msg[11]]); + let addrs = i32::from_ne_bytes([msg[12], msg[13], msg[14], msg[15]]); + if flags & RTF_UP == 0 || flags & (RTF_WASCLONED | RTF_LLINFO | RTF_IFSCOPE) != 0 || addrs & 0x1 == 0 { + continue; + } + let mut pos = RTM_HDR_LEN; + let mut dst: Option<[u8; 4]> = None; + let mut mask_prefix: Option = None; + let mut ok = true; + for bit in 0..8 { + if addrs & (1 << bit) == 0 { + continue; + } + if pos + 2 > msg.len() { + ok = false; + break; + } + let sa_len = msg[pos]; + let sa_family = msg[pos + 1]; + let step = if sa_len == 0 { 4 } else { ((sa_len as usize) + 3) & !3 }; + if bit == 0 { + if sa_family != AF_INET_U8 || sa_len < 8 || pos + 8 > msg.len() { + ok = false; + break; + } + dst = Some([msg[pos + 4], msg[pos + 5], msg[pos + 6], msg[pos + 7]]); + } else if bit == 2 { + let mut mask = [0u8; 4]; + let avail = (sa_len as usize).min(msg.len().saturating_sub(pos)).saturating_sub(4).min(4); + if avail > 0 { + mask[..avail].copy_from_slice(&msg[pos + 4..pos + 4 + avail]); + } + mask_prefix = Some(u32::from_be_bytes(mask).leading_ones() as u8); + } + if pos + step > msg.len() { + break; + } + pos += step; + } + if !ok { + continue; + } + let Some(dst_ip) = dst else { continue }; + let prefix = if flags & RTF_HOST != 0 { + 32 + } else { + mask_prefix.unwrap_or(0) + }; + let Some(ifname) = ifname_of(ifindex).filter(|s| !s.is_empty()) else { continue }; + entries.push((mask_ipv4(dst_ip, prefix), prefix, ifname)); + } + + let mut routes = Vec::new(); + for (dst, prefix, ifname) in entries { + if !is_tunnel_iface(&ifname) { + continue; + } + // Every tunnel route is kept, the default route too when a full + // tunnel VPN replaced the primary interface. Skip loopback, link-local, multicast/reserved and 0.0.0.0/32. + if dst[0] == 127 + || (dst[0] == 169 && dst[1] == 254) + || dst[0] >= 224 + || (dst == [0, 0, 0, 0] && prefix == 32) + { + continue; + } + routes.push((dst, prefix)); + } + collapse_cidrs(routes) +} + +/// Whether `identifier` (and optional extension points blob/text) is a pure +/// packet-tunnel VPN extension whose routes live in the kernel routing table +/// on `utun*`, rather than a transparent proxy, content filter or DNS proxy. +fn is_pure_packet_tunnel_ext(identifier: &str, ext_points_haystack: &[u8]) -> bool { + if identifier.starts_with("io.tailscale.") || identifier.starts_with("com.wireguard.") { + return true; + } + let has_bytes = |needle: &[u8]| ext_points_haystack.windows(needle.len()).any(|w| w == needle); + let has_packet_tunnel = has_bytes(b"com.apple.networkextension.packet-tunnel"); + let has_filter_or_proxy = has_bytes(b"com.apple.networkextension.filter-data") + || has_bytes(b"com.apple.networkextension.filter-packet") + || has_bytes(b"com.apple.networkextension.app-proxy") + || has_bytes(b"com.apple.networkextension.dns-proxy") + || has_bytes(b"com.apple.networkextension.transparent-proxy"); + has_packet_tunnel && !has_filter_or_proxy +} + +fn is_network_ext_category(cat: &str) -> bool { + matches!( + cat, + "com.apple.system_extension.network_extension" | "com.apple.developer.networking.networkextension" + ) +} + +/// Parses `/Library/SystemExtensions/db.plist` (either XML plist or `bplist00` +/// binary plist) and returns true when an active (`activated_enabled`) +/// third-party macOS NetworkExtension content filter, transparent proxy or +/// DNS proxy is enabled (#367, #616). +pub fn has_active_network_extension(plist: &[u8]) -> bool { + if plist.starts_with(b"bplist00") { + has_active_network_extension_bplist(plist) + } else if let Ok(xml) = std::str::from_utf8(plist) { + has_active_network_extension_xml(xml) + } else { + false + } +} + +fn has_active_network_extension_xml(xml: &str) -> bool { + // Walk top-level entries inside extensions... + // (or any if the snippet is not wrapped in extensions). + let scope = match xml.find("extensions") { + Some(idx) => &xml[idx..], + None => xml, + }; + for dict in xml_extension_dicts(scope) { + let Some(id) = xml_key_string(dict, "identifier") else { continue }; + let Some(state) = xml_key_string(dict, "state") else { continue }; + if state != "activated_enabled" || id.is_empty() || id.starts_with("com.apple.") { + continue; + } + let has_net_cat = dict.contains("com.apple.system_extension.network_extension") + || dict.contains("com.apple.developer.networking.networkextension"); + if !has_net_cat { + continue; + } + if is_pure_packet_tunnel_ext(id, dict.as_bytes()) { + continue; + } + return true; + } + false +} + +/// Extracts each extension `...` block from `xml`, tracking +/// nested `` depth so sub-dictionaries (`bundleVersion`, `container`, +/// `stagedBundleURL`) stay inside their parent extension block. +fn xml_extension_dicts(xml: &str) -> Vec<&str> { + let mut out = Vec::new(); + let base_depth = if xml.trim_start().starts_with("extensions") { 1 } else { 2 }; + let mut depth = 0usize; + let mut start: Option = None; + let mut i = 0; + let bytes = xml.as_bytes(); + while i < bytes.len() { + if bytes[i] == b'<' { + if xml[i..].starts_with("") || xml[i..].starts_with("") { + if depth == base_depth + && let Some(s) = start.take() + { + out.push(&xml[s..i + 7]); + } + depth = depth.saturating_sub(1); + i += 7; + continue; + } + } + i += 1; + } + if out.is_empty() && base_depth == 2 { + // Fallback for a bare `...` fixture at depth 1. + return xml_extension_dicts_at(xml, 1); + } + out +} + +fn xml_extension_dicts_at(xml: &str, target_depth: usize) -> Vec<&str> { + let mut out = Vec::new(); + let mut depth = 0usize; + let mut start: Option = None; + let mut i = 0; + let bytes = xml.as_bytes(); + while i < bytes.len() { + if bytes[i] == b'<' { + if xml[i..].starts_with("") || xml[i..].starts_with("") { + if depth == target_depth + && let Some(s) = start.take() + { + out.push(&xml[s..i + 7]); + } + depth = depth.saturating_sub(1); + i += 7; + continue; + } + } + i += 1; + } + out +} + +fn xml_key_string<'a>(dict: &'a str, key: &str) -> Option<&'a str> { + let pattern = format!("{key}"); + let idx = dict.find(&pattern)?; + let rest = dict[idx + pattern.len()..].trim_start(); + let rest = rest.strip_prefix("")?; + let end = rest.find("")?; + Some(rest[..end].trim()) +} + +#[derive(Debug)] +enum BplistObj<'a> { + Str(&'a str), + Data(&'a [u8]), + Array(Vec), + Dict(Vec<(usize, usize)>), + Other, +} + +fn read_be_uint(b: &[u8]) -> Option { + if b.is_empty() || b.len() > 8 { + return None; + } + let mut v = 0usize; + for &byte in b { + v = (v << 8) | (byte as usize); + } + Some(v) +} + +fn bplist_len(buf: &[u8], pos: usize, low: u8) -> Option<(usize, usize)> { + if low != 0x0f { + return Some((low as usize, pos)); + } + let marker = *buf.get(pos)?; + if (marker >> 4) != 0x1 { + return None; + } + let nbytes = 1usize << (marker & 0x0f); + let end = pos.checked_add(1)?.checked_add(nbytes)?; + let len = read_be_uint(buf.get(pos + 1..end)?)?; + Some((len, end)) +} + +fn parse_bplist(buf: &[u8]) -> Option<(usize, Vec>)> { + if buf.len() < 40 || !buf.starts_with(b"bplist00") { + return None; + } + let trailer = &buf[buf.len() - 32..]; + let offset_size = trailer[6] as usize; + let ref_size = trailer[7] as usize; + if !(1..=8).contains(&offset_size) || !(1..=8).contains(&ref_size) { + return None; + } + let num_objects = read_be_uint(&trailer[8..16])?; + let top_object = read_be_uint(&trailer[16..24])?; + let offset_table = read_be_uint(&trailer[24..32])?; + if num_objects == 0 || num_objects > 65_536 || top_object >= num_objects { + return None; + } + let table_end = offset_table.checked_add(num_objects.checked_mul(offset_size)?)?; + if table_end > buf.len() - 32 { + return None; + } + let mut objs = Vec::with_capacity(num_objects); + for i in 0..num_objects { + let off_pos = offset_table + i * offset_size; + let obj_off = read_be_uint(buf.get(off_pos..off_pos + offset_size)?)?; + let marker = *buf.get(obj_off)?; + let kind = marker >> 4; + let low = marker & 0x0f; + let obj = match kind { + 0x4 => { + let (len, start) = bplist_len(buf, obj_off + 1, low)?; + BplistObj::Data(buf.get(start..start.checked_add(len)?)?) + } + 0x5 => { + let (len, start) = bplist_len(buf, obj_off + 1, low)?; + let s = std::str::from_utf8(buf.get(start..start.checked_add(len)?)?).ok()?; + BplistObj::Str(s) + } + 0xa => { + let (count, start) = bplist_len(buf, obj_off + 1, low)?; + if count > 65_536 { + return None; + } + let mut items = Vec::with_capacity(count); + for j in 0..count { + let p = start.checked_add(j.checked_mul(ref_size)?)?; + items.push(read_be_uint(buf.get(p..p.checked_add(ref_size)?)?)?); + } + BplistObj::Array(items) + } + 0xd => { + let (count, start) = bplist_len(buf, obj_off + 1, low)?; + if count > 65_536 { + return None; + } + let vals_start = start.checked_add(count.checked_mul(ref_size)?)?; + let mut pairs = Vec::with_capacity(count); + for j in 0..count { + let kp = start + j * ref_size; + let vp = vals_start + j * ref_size; + let k = read_be_uint(buf.get(kp..kp.checked_add(ref_size)?)?)?; + let v = read_be_uint(buf.get(vp..vp.checked_add(ref_size)?)?)?; + pairs.push((k, v)); + } + BplistObj::Dict(pairs) + } + _ => BplistObj::Other, + }; + objs.push(obj); + } + Some((top_object, objs)) +} + +fn has_active_network_extension_bplist(buf: &[u8]) -> bool { + let Some((top, objs)) = parse_bplist(buf) else { return false }; + let get_dict_field = |pairs: &[(usize, usize)], key: &str| -> Option { + pairs.iter().find_map(|&(k, v)| match objs.get(k) { + Some(BplistObj::Str(s)) if *s == key => Some(v), + _ => None, + }) + }; + let get_str = |idx: usize| -> Option<&str> { + match objs.get(idx) { + Some(BplistObj::Str(s)) => Some(*s), + _ => None, + } + }; + let Some(BplistObj::Dict(root)) = objs.get(top) else { return false }; + let Some(ext_idx) = get_dict_field(root, "extensions") else { return false }; + let Some(BplistObj::Array(items)) = objs.get(ext_idx) else { return false }; + for &item in items { + let Some(BplistObj::Dict(pairs)) = objs.get(item) else { continue }; + let Some(id) = get_dict_field(pairs, "identifier").and_then(get_str) else { continue }; + let Some(state) = get_dict_field(pairs, "state").and_then(get_str) else { continue }; + if state != "activated_enabled" || id.is_empty() || id.starts_with("com.apple.") { + continue; + } + let has_net_cat = get_dict_field(pairs, "categories").is_some_and(|cidx| match objs.get(cidx) { + Some(BplistObj::Array(cats)) => cats.iter().any(|&c| get_str(c).is_some_and(is_network_ext_category)), + _ => false, + }); + if !has_net_cat { + continue; + } + let launchd_data = get_dict_field(pairs, "additionalLaunchdPlistEntries") + .and_then(|didx| match objs.get(didx) { + Some(BplistObj::Data(d)) => Some(*d), + _ => None, + }) + .unwrap_or(&[]); + if is_pure_packet_tunnel_ext(id, launchd_data) { + continue; + } + return true; + } + false +} + +fn parse_cidr_str(s: &str) -> Option<([u8; 4], u8)> { + let (ip, prefix) = s.trim().split_once('/')?; + let ip = ip.parse::().ok()?.octets(); + let prefix: u8 = prefix.parse().ok().filter(|&p| p <= 32)?; + Some((mask_ipv4(ip, prefix), prefix)) +} + +/// Computes the egress CIDR strings to send to the guest given: +/// - `env_mode`: `KIRI_HOST_EGRESS` (`auto`, `always`, `off`, or comma-separated CIDRs) +/// - `has_net_ext`: whether an active third-party macOS NetworkExtension filter/proxy is enabled +/// - `tunnel_routes`: IPv4 prefixes routed over tunnel interfaces (`utun*`, `ipsec*`, `ppp*`, `gpd*`, `feth*`) +/// - `is_macos`: whether the host is macOS +pub fn host_egress_routes_for( + env_mode: Option<&str>, + has_net_ext: bool, + tunnel_routes: &[([u8; 4], u8)], + is_macos: bool, +) -> Vec { + let mode = env_mode.map(str::trim).unwrap_or("auto"); + if mode.eq_ignore_ascii_case("off") || mode.eq_ignore_ascii_case("0") || mode.eq_ignore_ascii_case("false") || mode.eq_ignore_ascii_case("no") { + return Vec::new(); + } + if mode.eq_ignore_ascii_case("always") || mode.eq_ignore_ascii_case("1") || mode.eq_ignore_ascii_case("true") || mode.eq_ignore_ascii_case("all") { + return vec!["0.0.0.0/0".into()]; + } + if mode.contains('/') { + let parsed: Vec<([u8; 4], u8)> = mode.split(',').filter_map(parse_cidr_str).collect(); + return collapse_cidrs(parsed) + .into_iter() + .map(|(ip, p)| format!("{}.{}.{}.{}/{p}", ip[0], ip[1], ip[2], ip[3])) + .collect(); + } + if !is_macos { + return Vec::new(); + } + if has_net_ext { + return vec!["0.0.0.0/0".into()]; + } + let mut all = tunnel_routes.to_vec(); + all.push(FAKE_IP_CIDR); + collapse_cidrs(all) + .into_iter() + .map(|(ip, p)| format!("{}.{}.{}.{}/{p}", ip[0], ip[1], ip[2], ip[3])) + .collect() +} + +#[cfg(target_os = "macos")] +fn dump_macos_route_table() -> Option> { + let mut mib = [libc::CTL_NET, libc::PF_ROUTE, 0, libc::AF_INET, libc::NET_RT_DUMP, 0]; + let mut len: libc::size_t = 0; + // SAFETY: sysctl with null oldp queries the required buffer size. + if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, std::ptr::null_mut(), &mut len, std::ptr::null_mut(), 0) } != 0 || len == 0 { + return None; + } + // Add headroom in case a route is added between the two calls. + len = len.saturating_add(4096); + let mut buf = vec![0u8; len]; + // SAFETY: sysctl writes at most `len` bytes into `buf`. + if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, buf.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) } != 0 { + return None; + } + buf.truncate(len); + Some(buf) +} + +#[cfg(target_os = "macos")] +fn macos_ifname(index: u16) -> Option { + let mut buf = [0 as libc::c_char; libc::IFNAMSIZ]; + // SAFETY: `buf` is IFNAMSIZ bytes, as if_indextoname requires. + let ptr = unsafe { libc::if_indextoname(index as libc::c_uint, buf.as_mut_ptr()) }; + if ptr.is_null() { + return None; + } + // SAFETY: if_indextoname NUL-terminates `buf` on success. + Some(unsafe { std::ffi::CStr::from_ptr(ptr) }.to_string_lossy().into_owned()) +} + +pub fn current_egress_routes() -> Vec { + let env_mode = std::env::var("KIRI_HOST_EGRESS").ok(); + #[cfg(target_os = "macos")] + let (has_ext, tunnel_routes) = { + let ext = std::fs::read("/Library/SystemExtensions/db.plist") + .ok() + .is_some_and(|b| has_active_network_extension(&b)); + let routes = dump_macos_route_table() + .map(|b| parse_macos_routes(&b, macos_ifname)) + .unwrap_or_default(); + (ext, routes) + }; + #[cfg(not(target_os = "macos"))] + let (has_ext, tunnel_routes) = (false, Vec::new()); + host_egress_routes_for(env_mode.as_deref(), has_ext, &tunnel_routes, cfg!(target_os = "macos")) +} + +/// Sends the initial egress routes to `vm` and, on macOS, watches `PF_ROUTE` +/// for routing table changes (a VPN connecting or disconnecting while Kiri +/// runs) so `Msg::SetEgressRoutes` stays current without restarting the VM. +pub fn sync_egress_routes(vm: &Arc) { + let initial = current_egress_routes(); + if !initial.is_empty() { + let _ = vm.set_egress_routes(&initial); + } + #[cfg(target_os = "macos")] + { + let weak = Arc::downgrade(vm); + let _ = std::thread::Builder::new().name("kiri-route-watch".into()).spawn(move || { + watch_macos_routes(weak, initial); + }); + } +} + +#[cfg(target_os = "macos")] +fn watch_macos_routes(weak: std::sync::Weak, mut last: Vec) { + // SAFETY: opening a raw PF_ROUTE socket to hear kernel routing changes. + let fd = unsafe { libc::socket(libc::PF_ROUTE, libc::SOCK_RAW, libc::AF_UNSPEC) }; + let sock = if fd >= 0 { + // SAFETY: `fd` is a fresh descriptor owned only here. + unsafe { + libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC); + let tv = libc::timeval { tv_sec: 2, tv_usec: 0 }; + libc::setsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + (&tv as *const libc::timeval).cast(), + std::mem::size_of::() as libc::socklen_t, + ); + Some(OwnedFd::from_raw_fd(fd)) + } + } else { + None + }; + let mut buf = [0u8; 4096]; + loop { + match &sock { + Some(s) => { + // SAFETY: reading into a local buffer with SO_RCVTIMEO set. + let n = unsafe { libc::read(s.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + // Drain any burst of route messages before dumping once. + // SAFETY: non-blocking recv into a local buffer. + while unsafe { libc::recv(s.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), libc::MSG_DONTWAIT) } > 0 {} + } + } + None => std::thread::sleep(Duration::from_secs(2)), + } + let Some(vm) = weak.upgrade().filter(|v| !v.is_disconnected()) else { + return; + }; + let next = current_egress_routes(); + if next != last { + last = next; + let _ = vm.set_egress_routes(&last); + } + } +} + /// vsock port the guest dials for SSH agent connections. pub const SSH_AGENT_PORT: u32 = 1027; @@ -1385,4 +2087,254 @@ mod tests { let c = nat_port().expect("free port"); assert_eq!(c.0, freed); } + + #[test] + fn host_egress_dialer_rejects_ssrf_and_allows_vpn_and_public_targets() { + use super::egress_allowed; + use std::net::Ipv4Addr; + let extra = [([192, 168, 105, 0], 24)]; + // Loopback, unspecified, link-local (cloud metadata), multicast, broadcast, + // host.docker.internal, port 0, and the VM NAT bridge subnets are rejected. + for bad in [ + Ipv4Addr::new(127, 0, 0, 1), + Ipv4Addr::new(127, 0, 0, 53), + Ipv4Addr::new(127, 255, 255, 254), + Ipv4Addr::new(0, 0, 0, 0), + Ipv4Addr::new(0, 1, 2, 3), + Ipv4Addr::new(169, 254, 169, 254), + Ipv4Addr::new(169, 254, 0, 1), + Ipv4Addr::new(224, 0, 0, 1), + Ipv4Addr::new(239, 255, 255, 250), + Ipv4Addr::new(240, 0, 0, 1), + Ipv4Addr::new(255, 255, 255, 255), + Ipv4Addr::new(198, 19, 248, 254), + Ipv4Addr::new(192, 168, 64, 1), + Ipv4Addr::new(192, 168, 64, 18), + Ipv4Addr::new(192, 168, 105, 1), + ] { + assert!(!egress_allowed(bad, 443, &extra), "{bad} must be rejected"); + } + assert!(!egress_allowed(Ipv4Addr::new(10, 0, 5, 10), 0, &extra), "port 0 must be rejected"); + + // Split-tunnel VPN RFC1918 targets, Tailscale CGNAT, NetworkExtension + // Fake-IP (198.18.0.0/15), and public internet targets are allowed. + for ok in [ + Ipv4Addr::new(10, 0, 5, 10), + Ipv4Addr::new(172, 16, 4, 20), + Ipv4Addr::new(192, 168, 1, 50), + Ipv4Addr::new(100, 64, 1, 2), + Ipv4Addr::new(198, 18, 2, 3), + Ipv4Addr::new(35, 190, 46, 17), + Ipv4Addr::new(1, 1, 1, 1), + ] { + assert!(egress_allowed(ok, 443, &extra), "{ok} must be allowed"); + } + } + + #[test] + fn host_egress_dialer_rejects_the_learned_vm_subnet() { + use std::net::Ipv4Addr; + // macOS picked another NAT bridge subnet than the default one. + let inside = Ipv4Addr::new(192, 168, 205, 7); + let gateway = Ipv4Addr::new(192, 168, 205, 1); + let outside = Ipv4Addr::new(192, 168, 206, 7); + assert!(super::egress_target_allowed(inside, 443), "not learned yet"); + super::set_vm_subnet(gateway.octets(), super::VM_UPLINK_PREFIX); + super::set_vm_subnet(gateway.octets(), super::VM_UPLINK_PREFIX); + assert_eq!(super::current_vm_subnets().iter().filter(|&&s| s == ([192, 168, 205, 0], 24)).count(), 1); + assert!(!super::egress_target_allowed(inside, 443), "{inside} is in the VM's NAT subnet"); + assert!(!super::egress_target_allowed(gateway, 443), "{gateway} is the Mac's side of the NAT"); + assert!(super::egress_target_allowed(outside, 443), "{outside} is outside it"); + } + + /// Builds a BSD `rt_msghdr` (92 bytes) followed by `RTA_DST`, optional + /// `RTA_GATEWAY`, and optional truncated `RTA_NETMASK` sockaddrs, matching + /// macOS `sysctl([CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0])`. + fn bsd_rtm(ifindex: u16, flags: i32, dst: [u8; 4], mask: Option<&[u8]>) -> Vec { + let mut msg = vec![0u8; 92]; + msg[2] = 5; // RTM_VERSION + msg[3] = 4; // RTM_GET + msg[4..6].copy_from_slice(&ifindex.to_ne_bytes()); + msg[8..12].copy_from_slice(&flags.to_ne_bytes()); + let mut addrs: i32 = 0x1 | 0x2; // RTA_DST | RTA_GATEWAY + if mask.is_some() { + addrs |= 0x4; // RTA_NETMASK + } + msg[12..16].copy_from_slice(&addrs.to_ne_bytes()); + // RTA_DST: sockaddr_in (16 bytes) + let mut sa_dst = [0u8; 16]; + sa_dst[0] = 16; + sa_dst[1] = libc::AF_INET as u8; + sa_dst[4..8].copy_from_slice(&dst); + msg.extend_from_slice(&sa_dst); + // RTA_GATEWAY: sockaddr_in (16 bytes) + let mut sa_gw = [0u8; 16]; + sa_gw[0] = 16; + sa_gw[1] = libc::AF_INET as u8; + sa_gw[4..8].copy_from_slice(&[192, 168, 1, 1]); + msg.extend_from_slice(&sa_gw); + // RTA_NETMASK: BSD radix-tree variable-length sockaddr + if let Some(m) = mask { + if m.is_empty() { + // sa_len = 0 (/0 default route mask) occupies 4 rounded bytes. + msg.extend_from_slice(&[0, 0, 0, 0]); + } else { + let sa_len = (4 + m.len()) as u8; + let padded = ((sa_len as usize) + 3) & !3; + let mut sa_mask = vec![0u8; padded]; + sa_mask[0] = sa_len; + sa_mask[1] = libc::AF_INET as u8; + sa_mask[4..4 + m.len()].copy_from_slice(m); + msg.extend_from_slice(&sa_mask); + } + } + let msglen = msg.len() as u16; + msg[0..2].copy_from_slice(&msglen.to_ne_bytes()); + msg + } + + #[test] + fn macos_net_rt_dump_extracts_vpn_tunnel_prefixes_and_skips_ifscope_and_cloned() { + const RTF_UP: i32 = 0x1; + const RTF_GATEWAY: i32 = 0x2; + const RTF_HOST: i32 = 0x4; + const RTF_LLINFO: i32 = 0x400; + const RTF_STATIC: i32 = 0x800; + const RTF_WASCLONED: i32 = 0x20000; + const RTF_IFSCOPE: i32 = 0x1000000; + + let mut dump = Vec::new(); + // Primary default route on en0 (index 1): 0.0.0.0/0 + dump.extend_from_slice(&bsd_rtm(1, RTF_UP | RTF_GATEWAY | RTF_STATIC, [0, 0, 0, 0], Some(&[]))); + // Interface-scoped default route on utun4 (index 2): must be ignored! + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_IFSCOPE, [0, 0, 0, 0], Some(&[]))); + // OpenVPN split-tunnel route 10.0.5.0/24 on utun4 (index 2), truncated 3-byte radix mask + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_STATIC, [10, 0, 5, 0], Some(&[255, 255, 255]))); + // Redundant /32 host route inside 10.0.5.0/24 on utun4: collapsed into 10.0.5.0/24 + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_HOST, [10, 0, 5, 10], None)); + // Corporate /16 route on ipsec0 (index 3), truncated 2-byte radix mask + dump.extend_from_slice(&bsd_rtm(3, RTF_UP | RTF_STATIC, [172, 20, 0, 0], Some(&[255, 255]))); + // Tailscale CGNAT 100.64.0.0/10 on utun5 (index 4), truncated 2-byte radix mask + dump.extend_from_slice(&bsd_rtm(4, RTF_UP | RTF_STATIC, [100, 64, 0, 0], Some(&[255, 192]))); + // Multicast 224.0.0.0/4 and loopback on utun4: must be ignored + dump.extend_from_slice(&bsd_rtm(2, RTF_UP, [224, 0, 0, 0], Some(&[240]))); + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_HOST, [127, 0, 0, 1], None)); + // Cloned ARP entry on utun4 and regular LAN route on en0: must be ignored + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_WASCLONED | RTF_LLINFO, [10, 99, 0, 1], None)); + dump.extend_from_slice(&bsd_rtm(1, RTF_UP, [192, 168, 1, 0], Some(&[255, 255, 255]))); + + let ifname = |idx: u16| match idx { + 1 => Some("en0".into()), + 2 => Some("utun4".into()), + 3 => Some("ipsec0".into()), + 4 => Some("utun5".into()), + _ => None, + }; + let routes = super::parse_macos_routes(&dump, ifname); + assert_eq!( + routes, + vec![ + ([100, 64, 0, 0], 10), + ([172, 20, 0, 0], 16), + ([10, 0, 5, 0], 24), + ] + ); + } + + #[test] + fn system_extensions_plist_detects_active_security_extensions_and_ignores_inactive_or_tailscale() { + let active_kaspersky_and_forticlient = br#" + + + + extensions + + + bundleVersion + + CFBundleShortVersionString + 26.0.0 + + categories + + com.apple.system_extension.network_extension + + identifier + com.kaspersky.kav.sysext + state + activated_enabled + + + categories + + com.apple.developer.networking.networkextension + + identifier + com.fortinet.forticlient.macos.vpn.nwextension + state + terminated_waiting_to_uninstall_on_reboot + + + +"#; + assert!(super::has_active_network_extension(active_kaspersky_and_forticlient)); + + let deactivated_or_tailscale = br#" + + + extensions + + + categories + + com.apple.developer.networking.networkextension + + identifier + com.fortinet.forticlient.macos.vpn.nwextension + state + terminated_waiting_to_uninstall_on_reboot + + + categories + + com.apple.system_extension.network_extension + + identifier + io.tailscale.ipn.macsys.network-extension + state + activated_enabled + + + categories + + com.apple.system_extension.endpoint_security + + identifier + com.example.edr.esext + state + activated_enabled + + + +"#; + assert!(!super::has_active_network_extension(deactivated_or_tailscale)); + + assert_eq!( + super::host_egress_routes_for(Some("auto"), false, &[([10, 0, 5, 0], 24)], true), + vec!["198.18.0.0/15", "10.0.5.0/24"] + ); + assert_eq!( + super::host_egress_routes_for(Some("auto"), true, &[([10, 0, 5, 0], 24)], true), + vec!["0.0.0.0/0"] + ); + assert_eq!( + super::host_egress_routes_for(Some("always"), false, &[], false), + vec!["0.0.0.0/0"] + ); + assert!(super::host_egress_routes_for(Some("off"), true, &[([10, 0, 5, 0], 24)], true).is_empty()); + assert_eq!( + super::host_egress_routes_for(Some("10.254.99.0/24"), false, &[], false), + vec!["10.254.99.0/24"] + ); + } } diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index a063798d7..811c336a8 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -614,6 +614,12 @@ impl VmLink { self.send(|o| kiri_proto::encode_fs_events(o, lines)) } + /// Sets the IPv4 CIDR prefixes (`a.b.c.d/prefix`) whose outbound container + /// TCP connections the guest redirects to the host egress dialer. No reply. + pub fn set_egress_routes>(&self, routes: &[S]) -> io::Result<()> { + self.send(|o| kiri_proto::encode_set_egress_routes(o, routes)) + } + /// The Mac's wall clock, for the guest. Sent at boot, and again while it /// runs: the VM's clock stops while the Mac sleeps. pub fn set_time(&self) -> io::Result<()> { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 840529dc3..aed17e265 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,9 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### #319 Mac: relay outbound container TCP for split-tunnel VPN routes and security network extensions (unreleased) +- Fixes: #319 Mac: containers can't reach hosts behind a split-tunnel VPN; #367 Mac: containers have no working HTTP/HTTPS when a security network extension is active (DNS answers 198.18.x, TCP reset); #616 macOS: large HTTPS downloads from Google-fronted hosts stall in containers (~10 KB/s) while the Mac gets 17 MB/s; Cloudflare is fine + ### #127 Linux: standalone root daemon serves 0660 `/run/kiri/docker.sock` for containerized SDK clients (unreleased) - Fixes: #127 Linux daemon: Docker-compatible socket access for containerized SDK clients - Caused: none known @@ -30,6 +33,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug + ### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known From d14d20c5081878b7eba51f15088a3bdf2b59d891 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:35:34 +0100 Subject: [PATCH 040/157] Windows: opt-in file-change events for C:\ bind mounts (#487) (#823) --- crates/kiri-init/src/linux/fsnotify.rs | 558 ++++++++++++++++-- crates/kiri-win/src/engine.rs | 16 +- crates/kiri-win/src/main.rs | 5 + crates/kiri-win/src/watch.rs | 782 +++++++++++++++++++++++++ crates/kiri/src/daemon/api.rs | 95 ++- crates/kiri/src/daemon/binds.rs | 47 ++ crates/kiri/src/daemon/engine.rs | 32 + docs/fix-registry.md | 4 + 8 files changed, 1500 insertions(+), 39 deletions(-) create mode 100644 crates/kiri-win/src/watch.rs diff --git a/crates/kiri-init/src/linux/fsnotify.rs b/crates/kiri-init/src/linux/fsnotify.rs index cab9698c4..79d2544dd 100644 --- a/crates/kiri-init/src/linux/fsnotify.rs +++ b/crates/kiri-init/src/linux/fsnotify.rs @@ -1,14 +1,30 @@ -//! Files the Mac changed under bind mounts, raised as inotify events in the -//! VM. Apple's virtiofs server tells the guest nothing when a file changes -//! on the Mac, so file watchers in containers (Vite, webpack, nodemon, -//! `cargo watch`) never heard of a save. The daemon watches the bind sources -//! with FSEvents and sends `OP\tPATH` lines (`Msg::FsEvents`); the guest -//! kernel's /proc/kiri-fsnotify (guest/kernel/patches/0006) raises the -//! event for each, as a change made in the VM would. Nothing is written to +//! Files changed on the host under bind mounts, raised as inotify events in +//! the guest or WSL 2 userland. +//! +//! On macOS, Apple's virtiofs server tells the guest nothing when a file +//! changes on the Mac, so the daemon watches bind sources with FSEvents and +//! sends `OP\tPATH` lines (`Msg::FsEvents`) to the guest kernel's +//! `/proc/kiri-fsnotify` (guest/kernel/patches/0006). Nothing is written to //! the files, so nothing goes back to the Mac. +//! +//! On Windows (WSL 2), `C:\` is mounted over 9P (`drvfs` at `/mnt/c/...`) and +//! Microsoft's WSL 2 kernel neither forwards Windows file-change events over +//! 9P nor provides `/proc/kiri-fsnotify`. When `/proc/kiri-fsnotify` is +//! absent and a path is under WSL's automount root (`/mnt//...`), the +//! agent raises real Linux VFS inotify events itself, never following a +//! symlink and never writing to a file: +//! - `M`, `C` and `A`: sets the mode the file or directory already has, which +//! raises `IN_ATTRIB` on it and its watched parent (`raise_vfs_under`). +//! - `D`: the same on the parent directory, whose watchers read it again. +//! - `P` and `U` (from `kiri-win` as it starts and stops watching a root): +//! hold and release `O_PATH` fds on the root's directories, without which +//! no inotify watch on `drvfs` hears of anything (`Pins`). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; +use std::ffi::{CStr, CString}; use std::io::Write; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::sync::OnceLock; /// Where the Mac's filesystem is mounted in the VM (mod.rs). const MAC: &str = "/mnt/mac/"; @@ -17,63 +33,366 @@ const PROC: &str = "/proc/kiri-fsnotify"; /// that missed a change in a storm hears of the next one). const MAX_PENDING: usize = 8192; /// Lines raised per turn of the agent's loop, so a storm of changes on the -/// Mac doesn't hold up its other messages. +/// host doesn't hold up its other messages. const PER_TURN: usize = 64; +/// Most directories held open under watched WSL roots (see `Pins`). +const MAX_PINS: usize = 16384; +/// Directories opened per turn of the agent's loop while pinning a root. +const PINS_PER_TURN: usize = 64; +/// Skipped when pinning a root: dependency and git trees, which dev servers' +/// watchers ignore by default and which can hold most of a project's folders. +const SKIP_DIRS: [&str; 2] = ["node_modules", ".git"]; /// Changes waiting to be raised. Raised from the agent's own loop, a few at /// a time, not a thread: the agent must stay single-threaded (it starts /// containers with clone3, and a thread breaks setuid in the child). #[derive(Default)] -pub struct Pending(VecDeque); +pub struct Pending { + lines: VecDeque, + pins: Pins, +} impl Pending { - /// Queues the lines that name a file under the Mac's mount, in order. - /// Each is kept, repeats too: dropping one that is already queued would - /// lose a delete in `D a, C a, M a, D a`. The daemon merges each batch. + /// Queues the lines that name a file under the Mac's mount or WSL's + /// automount root, in order. Each is kept, repeats too: dropping one that + /// is already queued would lose a delete in `D a, C a, M a, D a`. The + /// sender merges each batch. pub fn add<'a>(&mut self, lines: impl Iterator) { for line in valid(lines) { - if self.0.len() < MAX_PENDING { - self.0.push_back(line); + if self.lines.len() < MAX_PENDING { + self.lines.push_back(line); } } } pub fn is_empty(&self) -> bool { - self.0.is_empty() + self.lines.is_empty() && self.pins.walk.is_empty() } - /// Raises up to PER_TURN lines. A kernel without the interface (or a - /// host-process engine) drops them all. + /// Raises up to PER_TURN lines. Uses `/proc/kiri-fsnotify` when present + /// (macOS guest VM); otherwise raises Linux VFS inotify events for valid + /// WSL automount paths (`/mnt//...`) and pins up to PINS_PER_TURN + /// directories of watched roots. pub fn raise_some(&mut self) { - let Ok(mut f) = std::fs::OpenOptions::new().write(true).open(PROC) else { - self.0.clear(); + let count = PER_TURN.min(self.lines.len()); + if let Ok(mut f) = std::fs::OpenOptions::new().write(true).open(PROC) { + // One write per line: the kernel answers each with its own result, + // and a file gone again by now (ENOENT) must not drop the rest. + for line in self.lines.drain(..count) { + let _ = f.write_all(line.as_bytes()); + } return; - }; - // One write per line: the kernel answers each with its own result, - // and a file gone again by now (ENOENT) must not drop the rest. - for line in self.0.drain(..PER_TURN.min(self.0.len())) { - let _ = f.write_all(line.as_bytes()); } + let root = wsl_automount_root(); + for line in self.lines.drain(..count) { + raise_vfs_line(&line, root, &mut self.pins); + } + self.pins.walk_some(root); + } +} + +/// `[automount] root` from `/etc/wsl.conf`, defaulting to `/mnt/`. +fn automount_root(conf: &str) -> String { + let mut section = String::new(); + let mut root = None; + for line in conf.lines() { + let line = line.split('#').next().unwrap_or("").trim(); + if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + section = s.trim().to_ascii_lowercase(); + continue; + } + let Some((key, value)) = line.split_once('=') else { continue }; + if section == "automount" && key.trim().eq_ignore_ascii_case("root") { + let value = value.trim().trim_matches('"').trim(); + if value.starts_with('/') { + root = Some(value.to_owned()); + } + } + } + let mut root = root.unwrap_or_else(|| "/mnt/".to_owned()); + if !root.ends_with('/') { + root.push('/'); + } + root +} + +fn wsl_automount_root() -> &'static str { + static ROOT: OnceLock = OnceLock::new(); + ROOT.get_or_init(|| automount_root(&std::fs::read_to_string("/etc/wsl.conf").unwrap_or_default())) +} + +/// Splits a validated WSL automount path (`/mnt/c/Users/a/app.js`) into +/// `(drive_root, rel_path)` (`("/mnt/c", "Users/a/app.js")`). +/// Rejects paths outside `/...`, empty relative paths, +/// control characters (`\n`, `\r`, `\0`), and `.` or `..` traversal components. +fn split_wsl_drive_path<'a>(path: &'a str, automount_root: &str) -> Option<(&'a str, &'a str)> { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if path.contains(['\n', '\r', '\0']) { + return None; + } + let rest = path.strip_prefix(automount_root)?; + let bytes = rest.as_bytes(); + if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b'/' { + return None; + } + let rel = &rest[2..]; + let mut has_component = false; + for part in rel.split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return None; + } + has_component = true; } + if !has_component { + return None; + } + Some((&path[..automount_root.len() + 1], rel)) } -/// The lines the kernel takes, each ending in a newline: `C`, `M`, `A` or -/// `D`, a tab, and a path under /mnt/mac with no `..` and no newline. +/// The lines the raiser accepts, each ending in a newline: `C`, `M`, `A` or +/// `D`, a tab, and a path under `/mnt/mac/` or WSL's automount root with no +/// `..`, no NUL and no newline; or `P` or `U` and a path under WSL's +/// automount root. fn valid<'a>(lines: impl Iterator) -> impl Iterator { - lines.filter_map(|line| { + valid_for(lines, wsl_automount_root()) +} + +fn valid_for<'a>(lines: impl Iterator, automount_root: &'a str) -> impl Iterator { + lines.filter_map(move |line| { let (op, path) = line.split_once('\t')?; - let ok = matches!(op, "C" | "M" | "A" | "D") - && path.starts_with(MAC) - && path.len() > MAC.len() - && !path.contains('\n') - && !path.split('/').any(|part| part == ".."); + let no_bad_chars = !path.contains(['\n', '\r', '\0']) && !path.split('/').any(|part| part == ".."); + let is_mac = path.starts_with(MAC) && path.len() > MAC.len(); + let is_wsl = split_wsl_drive_path(path, automount_root).is_some(); + let ok = no_bad_chars && match op { + "C" | "M" | "A" | "D" => is_mac || is_wsl, + "P" | "U" => is_wsl, + _ => false, + }; ok.then(|| format!("{op}\t{path}\n")) }) } +/// Raises a single `OP\tPATH` line via Linux VFS syscalls, strictly restricted +/// to paths under `/...`. `P` and `U` pin and unpin a +/// watched root's directories (see `Pins`). +fn raise_vfs_line(line: &str, automount_root: &str, pins: &mut Pins) -> bool { + let line = line.trim_end_matches('\n'); + let Some((op, path)) = line.split_once('\t') else { return false }; + let Some((base, rel)) = split_wsl_drive_path(path, automount_root) else { return false }; + match op { + "P" => pins.pin_tree(path), + "U" => pins.unpin_tree(path), + "D" => pins.unpin_tree(path), + // A new directory is pinned before its parent hears of it, so a + // watcher that adds a watch on it in answer gets the pinned inode. + "C" if path.rsplit_once('/').is_some_and(|(parent, _)| pins.held.contains_key(parent)) => { + if let Some(fd) = open_dir_nofollow(base, rel) { + pins.hold(path, fd); + pins.walk.push_back(path.to_owned()); + } + } + _ => {} + } + matches!(op, "P" | "U") || raise_vfs_under(base, rel, op) +} + +/// Directories held open under watched WSL roots. +/// +/// `drvfs` (9P without metadata caching, `cache=5`) drops a dentry as soon as +/// nothing holds it and makes a new inode on every lookup. An inotify watch +/// sits on the inode it was added to, so once that directory's dentry is +/// gone, no change made later (in WSL or raised here) ever reaches the watch. +/// Holding an `O_PATH` fd on each directory keeps its dentry, and so its +/// inode, for every later lookup. `O_PATH` opens nothing on the Windows side +/// and raises no inotify event. +#[derive(Default)] +struct Pins { + held: HashMap, + /// Directories still to open and list, a few per turn of the agent's loop. + walk: VecDeque, +} + +impl Pins { + fn pin_tree(&mut self, path: &str) { + if !self.walk.iter().any(|p| p == path) { + self.walk.push_back(path.to_owned()); + } + } + + fn unpin_tree(&mut self, path: &str) { + let under = |p: &str| p == path || p.strip_prefix(path).is_some_and(|rest| rest.starts_with('/')); + self.held.retain(|p, _| !under(p)); + self.walk.retain(|p| !under(p)); + } + + fn hold(&mut self, path: &str, fd: OwnedFd) { + if self.held.len() < MAX_PINS || self.held.contains_key(path) { + self.held.insert(path.to_owned(), fd); + } + } + + /// Opens and lists up to PINS_PER_TURN queued directories, queueing their + /// subdirectories. Never follows a symlink; skips `SKIP_DIRS`. + fn walk_some(&mut self, automount_root: &str) { + for _ in 0..PINS_PER_TURN { + let Some(dir) = self.walk.pop_front() else { return }; + if self.held.len() >= MAX_PINS { + self.walk.clear(); + return; + } + let Some((base, rel)) = split_wsl_drive_path(&dir, automount_root) else { continue }; + let Some(fd) = open_dir_nofollow(base, rel) else { continue }; + let list = std::fs::read_dir(format!("/proc/self/fd/{}", fd.as_raw_fd())); + self.hold(&dir, fd); + for entry in list.into_iter().flatten().flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue }; + if SKIP_DIRS.contains(&name.as_str()) || name.contains(['\n', '\r']) || !entry.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + if self.held.len() + self.walk.len() >= MAX_PINS { + break; + } + self.walk.push_back(format!("{dir}/{name}")); + } + } + } +} + +/// Opens `base_dir`, then each directory of `rel_path` but the last, with +/// `O_PATH | O_DIRECTORY | O_NOFOLLOW`: a symlink anywhere on the way fails. +/// Returns the parent directory and the last component. +fn open_parent_nofollow(base_dir: &str, rel_path: &str) -> Option<(OwnedFd, CString)> { + let comps: Vec<&str> = rel_path.split('/').filter(|s| !s.is_empty()).collect(); + if comps.is_empty() || comps.iter().any(|c| *c == "." || *c == ".." || c.contains('\0')) { + return None; + } + let c_base = CString::new(base_dir).ok()?; + // SAFETY: `c_base` is a valid NUL-terminated path; the returned fd is + // immediately wrapped in `OwnedFd` when non-negative. + let raw = unsafe { libc::open(c_base.as_ptr(), DIR_FLAGS) }; + if raw < 0 { + return None; + } + // SAFETY: `raw` is a newly opened valid file descriptor. + let mut parent = unsafe { OwnedFd::from_raw_fd(raw) }; + for comp in &comps[..comps.len() - 1] { + parent = open_at(&parent, &CString::new(*comp).ok()?, DIR_FLAGS)?; + } + Some((parent, CString::new(comps[comps.len() - 1]).ok()?)) +} + +/// The directory at `rel_path` under `base_dir`, opened `O_PATH` without +/// following any symlink. +fn open_dir_nofollow(base_dir: &str, rel_path: &str) -> Option { + let (parent, leaf) = open_parent_nofollow(base_dir, rel_path)?; + open_at(&parent, &leaf, DIR_FLAGS) +} + +const DIR_FLAGS: libc::c_int = libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC; + +fn open_at(dir: &OwnedFd, name: &CStr, flags: libc::c_int) -> Option { + // SAFETY: `dir` is a valid directory fd and `name` is NUL-terminated. + let raw = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags) }; + // SAFETY: `raw` is a newly opened valid file descriptor when non-negative. + (raw >= 0).then(|| unsafe { OwnedFd::from_raw_fd(raw) }) +} + +/// Raises a real Linux VFS inotify event for `op` on `rel_path` under +/// `base_dir` without following symlinks and without writing to the file. +/// +/// The event is `IN_ATTRIB`, from setting the mode the file already has: +/// Node's `fs.watch` (libuv), Chokidar, Vite, webpack, nodemon, watchdog and +/// `notify` all listen for it. Nothing reaches Windows: `drvfs` changes no +/// timestamp or attribute and raises no `ReadDirectoryChangesW` event. Writing +/// a timestamp instead loses its sub-second part on `drvfs` and comes back +/// from Windows as a new change; changing the size to raise `IN_MODIFY` could +/// cut off a write Windows makes at the same moment. +fn raise_vfs_under(base_dir: &str, rel_path: &str, op: &str) -> bool { + let Some((parent, leaf)) = open_parent_nofollow(base_dir, rel_path) else { return false }; + match op { + "M" | "C" | "A" => { + let Some(fd) = open_at(&parent, &leaf, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) else { return false }; + // Never a symlink (`O_PATH | O_NOFOLLOW` opens the link itself), + // FIFO, socket or device node. + fstat(&fd).is_some_and(|st| matches!(st.st_mode & libc::S_IFMT, libc::S_IFREG | libc::S_IFDIR) && chmod_same(&fd, &st)) + } + // The entry is gone: its parent directory raises the event, and a + // watcher on it reads the directory again. + "D" => fstat(&parent).is_some_and(|st| chmod_same(&parent, &st)), + _ => false, + } +} + +fn fstat(fd: &OwnedFd) -> Option { + // SAFETY: zeroed `libc::stat` filled by `fstat` on a valid fd. + unsafe { + let mut st: libc::stat = std::mem::zeroed(); + (libc::fstat(fd.as_raw_fd(), &mut st) == 0).then_some(st) + } +} + +/// Sets the mode `fd` already has, through `/proc/self/fd` (an `O_PATH` fd +/// can't be `fchmod`ed): the inode is the one `fd` was opened on, never a +/// symlink swapped in since. Raises `IN_ATTRIB` on it and its watched parent. +fn chmod_same(fd: &OwnedFd, st: &libc::stat) -> bool { + let Ok(path) = CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())) else { return false }; + // SAFETY: valid NUL-terminated path. + unsafe { libc::chmod(path.as_ptr(), st.st_mode & 0o7777) == 0 } +} + #[cfg(test)] mod tests { - use super::{Pending, valid}; + use super::{Pending, Pins, automount_root, raise_vfs_line, raise_vfs_under, split_wsl_drive_path, valid, valid_for}; + use std::ffi::CString; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::fs::MetadataExt; + use std::path::PathBuf; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("kiri-fsnotify-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn watch_dir(dir: &std::path::Path, mask: u32) -> OwnedFd { + // SAFETY: standard Linux inotify syscalls on a valid NUL-terminated path. + unsafe { + let fd = libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC); + assert!(fd >= 0, "inotify_init1 failed"); + let c = CString::new(dir.to_str().unwrap()).unwrap(); + let wd = libc::inotify_add_watch(fd, c.as_ptr(), mask); + assert!(wd >= 0, "inotify_add_watch failed"); + OwnedFd::from_raw_fd(fd) + } + } + + fn read_inotify_masks(fd: &OwnedFd) -> Vec { + let mut buf = [0u8; 4096]; + let mut masks = Vec::new(); + loop { + // SAFETY: `fd` is a valid non-blocking inotify fd and `buf` is writable. + let n = unsafe { libc::read(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + if n <= 0 { + break; + } + let n = n as usize; + let mut off = 0; + let hdr = std::mem::size_of::(); + while off + hdr <= n { + // SAFETY: reading an unaligned `inotify_event` header within bounds. + let ev: libc::inotify_event = unsafe { std::ptr::read_unaligned(buf.as_ptr().add(off).cast()) }; + masks.push(ev.mask); + off += hdr + ev.len as usize; + } + } + masks + } #[test] fn only_paths_under_the_macs_mount() { @@ -86,7 +405,174 @@ mod tests { let mut p = Pending::default(); p.add(["D\t/mnt/mac/a", "C\t/mnt/mac/a", "M\t/mnt/mac/a"].into_iter()); p.add(["D\t/mnt/mac/a"].into_iter()); - assert_eq!(p.0.len(), 4); - assert_eq!(p.0.back().unwrap(), "D\t/mnt/mac/a\n"); + assert_eq!(p.lines.len(), 4); + assert_eq!(p.lines.back().unwrap(), "D\t/mnt/mac/a\n"); + } + + #[test] + fn wsl_drive_paths_are_validated_and_traversal_rejected() { + assert_eq!(split_wsl_drive_path("/mnt/c/Users/me/app.js", "/mnt/"), Some(("/mnt/c", "Users/me/app.js"))); + assert_eq!(split_wsl_drive_path("/windows/d/proj/x", "/windows/"), Some(("/windows/d", "proj/x"))); + assert_eq!(split_wsl_drive_path("/mnt/mac/Users/a", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/../etc/shadow", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/./app.js", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/etc/passwd", "/mnt/"), None); + assert_eq!(automount_root("[automount]\nroot = /win\n"), "/win/"); + assert_eq!(automount_root(""), "/mnt/"); + + let lines = [ + "M\t/mnt/c/Users/me/app.js", + "D\t/mnt/d/old.txt", + "M\t/mnt/c/../etc/passwd", + "M\t/etc/shadow", + "M\t/mnt/c/", + ]; + assert_eq!( + valid_for(lines.into_iter(), "/mnt/").collect::>(), + ["M\t/mnt/c/Users/me/app.js\n", "D\t/mnt/d/old.txt\n"] + ); + let mut pins = Pins::default(); + assert!(!raise_vfs_line("M\t/etc/passwd\n", "/mnt/", &mut pins)); + assert!(!raise_vfs_line("M\t/mnt/c/../etc/passwd\n", "/mnt/", &mut pins)); + assert!(!raise_vfs_line("P\t/etc\n", "/mnt/", &mut pins)); + assert!(pins.walk.is_empty()); + } + + /// Pins a known mtime with nanoseconds, so a raiser that rewrites it shows. + fn pin_mtime(path: &std::path::Path, sec: i64, nsec: i64) { + let c = CString::new(path.to_str().unwrap()).unwrap(); + let times = [libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }, libc::timespec { tv_sec: sec, tv_nsec: nsec }]; + // SAFETY: valid path and timespec array. + assert_eq!(unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0) }, 0); + } + + /// Holds `dir` open as `Pins` does: on `drvfs` a watch added to a directory + /// nothing holds hears of nothing (run with TMPDIR on `/mnt/c` to see). + fn pin(dir: &std::path::Path) -> OwnedFd { + let c = CString::new(dir.to_str().unwrap()).unwrap(); + // SAFETY: valid path; the fd is wrapped at once. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: just opened. + unsafe { OwnedFd::from_raw_fd(fd) } + } + + fn mtime_and_mode(path: &std::path::Path) -> (i64, i64, u32) { + let m = std::fs::symlink_metadata(path).unwrap(); + (m.mtime(), m.mtime_nsec(), m.mode()) + } + + #[test] + fn vfs_fallback_raises_in_attrib_keeping_bytes_mtime_and_mode() { + let base = temp_dir("attrib"); + let sub = base.join("app"); + std::fs::create_dir_all(&sub).unwrap(); + let file = sub.join("main.js"); + std::fs::write(&file, b"console.log('hi');\n").unwrap(); + pin_mtime(&file, 1_700_000_123, 456_789_123); + let before = mtime_and_mode(&file); + + let _pin = pin(&sub); + let inotify = watch_dir(&sub, libc::IN_ALL_EVENTS); + for op in ["M", "C", "A"] { + assert!(raise_vfs_under(base.to_str().unwrap(), "app/main.js", op)); + let masks = read_inotify_masks(&inotify); + assert!(masks.iter().any(|m| m & libc::IN_ATTRIB != 0), "{op}: expected IN_ATTRIB, got {masks:?}"); + // O_PATH opens raise no IN_OPEN, and nothing is written. + assert!(masks.iter().all(|m| m & (libc::IN_OPEN | libc::IN_MODIFY | libc::IN_CLOSE_WRITE) == 0), "{op}: got {masks:?}"); + } + assert_eq!(std::fs::read(&file).unwrap(), b"console.log('hi');\n"); + assert_eq!(mtime_and_mode(&file), before); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn vfs_fallback_refuses_symlinks_leaf_and_intermediate() { + let base = temp_dir("symlink"); + let outside = temp_dir("symlink-outside"); + let secret = outside.join("shadow"); + std::fs::write(&secret, b"top-secret").unwrap(); + std::fs::set_permissions(&secret, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap(); + // drvfs keeps no Unix mode bits: compare with what it reports. + let mode = std::fs::symlink_metadata(&secret).unwrap().mode(); + + std::os::unix::fs::symlink(&secret, base.join("evil")).unwrap(); + std::os::unix::fs::symlink(&outside, base.join("sub")).unwrap(); + + let _pin = pin(&outside); + let inotify = watch_dir(&outside, libc::IN_ALL_EVENTS); + for op in ["M", "C", "A", "D"] { + assert!(!raise_vfs_under(base.to_str().unwrap(), "evil", op) || op == "D", "leaf symlink must be refused for {op}"); + assert!(!raise_vfs_under(base.to_str().unwrap(), "sub/shadow", op), "intermediate symlink must be refused for {op}"); + } + assert!(read_inotify_masks(&inotify).is_empty(), "target outside root must receive zero events"); + assert_eq!(std::fs::symlink_metadata(&secret).unwrap().mode(), mode); + let _ = std::fs::remove_dir_all(&base); + let _ = std::fs::remove_dir_all(&outside); + } + + #[test] + fn vfs_fallback_delete_raises_in_attrib_on_parent_keeping_mtime() { + let base = temp_dir("delete"); + let sub = base.join("proj"); + std::fs::create_dir_all(&sub).unwrap(); + pin_mtime(&sub, 1_720_000_000, 222_333_444); + let before = mtime_and_mode(&sub); + + let _pin = pin(&sub); + let inotify = watch_dir(&sub, libc::IN_ALL_EVENTS); + assert!(raise_vfs_under(base.to_str().unwrap(), "proj/gone.js", "D")); + let masks = read_inotify_masks(&inotify); + assert!(masks.iter().any(|m| m & libc::IN_ATTRIB != 0), "expected IN_ATTRIB on parent dir, got {masks:?}"); + assert_eq!(mtime_and_mode(&sub), before); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn pins_hold_a_roots_directories_but_not_symlinks_or_skipped_trees() { + // An automount root of our own: `/` with drive `c`. + let base = temp_dir("pins"); + let root = format!("{}/", base.to_str().unwrap()); + let proj = base.join("c/proj"); + for d in ["src/a", "src/b", "node_modules/x", ".git/objects"] { + std::fs::create_dir_all(proj.join(d)).unwrap(); + } + std::fs::write(proj.join("src/file.js"), b"x").unwrap(); + let outside = temp_dir("pins-outside"); + std::os::unix::fs::symlink(&outside, proj.join("link")).unwrap(); + let p = |rel: &str| format!("{root}c/proj{rel}"); + + let mut pins = Pins::default(); + assert!(raise_vfs_line(&format!("P\t{}\n", p("")), &root, &mut pins)); + while !pins.walk.is_empty() { + pins.walk_some(&root); + } + let mut held: Vec<&str> = pins.held.keys().map(String::as_str).collect(); + held.sort(); + assert_eq!(held, [p(""), p("/src"), p("/src/a"), p("/src/b")]); + + // A watch added once the tree is pinned hears a change raised later. + let inotify = watch_dir(&proj.join("src"), libc::IN_ALL_EVENTS); + assert!(raise_vfs_line(&format!("M\t{}\n", p("/src/file.js")), &root, &mut pins)); + assert!(read_inotify_masks(&inotify).iter().any(|m| m & libc::IN_ATTRIB != 0)); + + // A new directory under a pinned one is pinned as it is raised. + std::fs::create_dir(proj.join("src/new")).unwrap(); + assert!(raise_vfs_line(&format!("C\t{}\n", p("/src/new")), &root, &mut pins)); + assert!(pins.held.contains_key(&p("/src/new"))); + + // A deleted directory lets go of its subtree; U lets go of the root. + std::fs::remove_dir_all(proj.join("src")).unwrap(); + raise_vfs_line(&format!("D\t{}\n", p("/src")), &root, &mut pins); + assert_eq!(pins.held.keys().collect::>(), [&p("")]); + assert!(raise_vfs_line(&format!("U\t{}\n", p("")), &root, &mut pins)); + assert!(pins.held.is_empty()); + + let lines = [format!("P\t{}", p("")), "P\t/mnt/mac/Users/a".to_owned(), format!("U\t{}", p(""))]; + assert_eq!(valid_for(lines.iter().map(String::as_str), &root).count(), 2); + let _ = std::fs::remove_dir_all(&base); + let _ = std::fs::remove_dir_all(&outside); } } diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 5848b91cd..4b75e670f 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -243,7 +243,11 @@ fn watch(tx: Sender) { } // A Kubernetes node already running gets its kubectl context. crate::k8s::sync_soon(); - let _ = client::events(|_| tx.send(Cmd::Refresh).is_ok()); + crate::watch::notify_containers_changed(); + let _ = client::events(|_| { + crate::watch::notify_containers_changed(); + tx.send(Cmd::Refresh).is_ok() + }); } std::thread::sleep(Duration::from_secs(1)); }); @@ -899,6 +903,7 @@ pub fn prefs() -> Value { if p.get("theme").is_none() { p["theme"] = "dark".into(); } + p["watchBindMounts"] = json!(crate::watch::is_enabled()); p } @@ -914,6 +919,15 @@ pub fn trf(en: &str, vars: &[(&str, &dyn std::fmt::Display)]) -> String { } fn set_pref(name: &str, value: Value) { + if name == "watchBindMounts" { + let on = value.as_bool().unwrap_or(false); + if crate::watch::save_enabled(on).is_err() { + emit(notice("error", &trf("Could not save the setting to {path}", &[("path", &"%LOCALAPPDATA%\\Kiri\\settings.json")]))); + return; + } + crate::watch::set_enabled(crate::watch::is_enabled()); + return; + } if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked") { return; } diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index f4d8028c9..72681027e 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -110,6 +110,10 @@ mod update; mod wslsync; #[cfg(any(windows, test))] mod refuse; +// Opt-in Windows bind-mount watcher (ReadDirectoryChangesW -> /kiri/fs-events): +// path mapping, buffer decoding and coalescing tested on any host. +#[cfg(any(windows, test))] +mod watch; // Settings → Import from Docker Desktop: the Mac's and Linux's own // crates/kiri/src/import.rs, through the docker CLI's contexts. #[cfg(windows)] @@ -182,6 +186,7 @@ fn main() -> std::process::ExitCode { serve::log(&format!("dns on 127.0.0.1:53: {e}")); } engine::start(engine::Env { distro: cfg.distro.clone(), pipe: cfg.pipe.clone() }); + watch::start_if_enabled(); // Its folder renamed, moved or deleted around it (Windows won't delete // a running program itself): docker build handed back as it was before // Kiri took it, the choice kept for when Kiri runs again, and Kiri quits. diff --git a/crates/kiri-win/src/watch.rs b/crates/kiri-win/src/watch.rs new file mode 100644 index 000000000..6850c9331 --- /dev/null +++ b/crates/kiri-win/src/watch.rs @@ -0,0 +1,782 @@ +//! Opt-in Windows bind-mount watcher for WSL 2 (`C:\...` -> `/mnt/c/...`). +//! +//! WSL 2 mounts Windows drives over 9P (`drvfs`), and Microsoft's kernel does +//! not forward Windows file-change notifications into Linux inotify. When the +//! user opts in (`%LOCALAPPDATA%\Kiri\settings.json` with +//! `{"watchBindMounts": true}`, or `KIRI_WIN_WATCH_BINDS=1`), this watches +//! active `/mnt//...` bind sources of running containers using +//! kernel-blocking `ReadDirectoryChangesW` (0% CPU when idle), debounces +//! changes over 50 ms in batches of at most 512, and posts `OP\t/mnt/...` +//! lines to `POST /kiri/fs-events` so `kiri-init` raises real Linux VFS +//! inotify events. As it starts and stops watching a root it posts +//! `P\t/mnt/...` and `U\t/mnt/...`: `kiri-init` holds the root's directories +//! open meanwhile, without which no inotify watch on `drvfs` hears of +//! anything (a watcher started before that misses changes until it restarts). +//! +//! When opt-in is OFF (the default): zero threads, zero directory handles, +//! and zero polling. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::collections::{HashMap, HashSet}; +use std::io; +use std::path::PathBuf; + +use serde_json::{Value, json}; + +/// At most this many coalesced lines per `POST /kiri/fs-events` request. +pub const BATCH: usize = 512; +/// Debounce window before flushing a burst of Windows file-change events. +#[cfg(windows)] +const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(50); +/// Maximum raw events buffered during one debounce window. +#[cfg(windows)] +const MAX_BURST: usize = 4096; +/// Fallback rescan interval when the watcher is active (container events also +/// wake it immediately). +#[cfg(windows)] +const RESCAN_FALLBACK: std::time::Duration = std::time::Duration::from_secs(5); + +/// `%LOCALAPPDATA%\Kiri\settings.json`. +fn settings_path() -> Option { + std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri").join("settings.json")) +} + +/// Parses an environment flag (`KIRI_WIN_WATCH_BINDS`). +fn parse_env_bool(val: &str) -> Option { + match val.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + } +} + +/// Resolves whether bind-mount watching is enabled from `settings.json` text +/// and the optional `KIRI_WIN_WATCH_BINDS` override. Off by default. +pub fn parse_settings_enabled(settings_json: Option<&str>, env_override: Option<&str>) -> bool { + if let Some(b) = env_override.and_then(parse_env_bool) { + return b; + } + settings_json + .and_then(|s| serde_json::from_str::(s).ok()) + .and_then(|v| v.get("watchBindMounts")?.as_bool()) + .unwrap_or(false) +} + +/// Whether bind-mount watching is currently enabled (env override or +/// `%LOCALAPPDATA%\Kiri\settings.json`). Off by default. +pub fn is_enabled() -> bool { + let env = std::env::var("KIRI_WIN_WATCH_BINDS").ok(); + let text = settings_path().and_then(|p| std::fs::read_to_string(p).ok()); + parse_settings_enabled(text.as_deref(), env.as_deref()) +} + +/// Persists `watchBindMounts` into `%LOCALAPPDATA%\Kiri\settings.json` while +/// preserving any other keys in that file. +pub fn save_enabled(enabled: bool) -> io::Result<()> { + let Some(path) = settings_path() else { + return Err(io::Error::other("LOCALAPPDATA is not set")); + }; + let mut obj: Value = std::fs::read_to_string(&path) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + obj["watchBindMounts"] = json!(enabled); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, obj.to_string())?; + std::fs::rename(&tmp, &path) +} + +/// Translates a WSL automount path (`/mnt/c/Users/me/app`) to a Windows path +/// (`C:\Users\me\app`). Rejects paths outside `automount_root`, non-drive +/// entries (like `/mnt/mac/...`), control characters, and `..` traversal. +pub fn wsl_to_windows(wsl_path: &str, automount_root: &str) -> Option { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if wsl_path.contains(['\n', '\r', '\0']) { + return None; + } + let rest = wsl_path.strip_prefix(automount_root)?; + let bytes = rest.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() { + return None; + } + let drive = (bytes[0] as char).to_ascii_uppercase(); + if bytes.len() == 1 { + return Some(format!("{drive}:\\")); + } + if bytes[1] != b'/' { + return None; + } + let mut parts = Vec::new(); + for part in rest[2..].split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." || part.contains('\\') { + return None; + } + parts.push(part); + } + if parts.is_empty() { + Some(format!("{drive}:\\")) + } else { + Some(format!("{drive}:\\{}", parts.join("\\"))) + } +} + +/// Translates a watched Windows root (`C:\Users\me\app`) plus a relative path +/// from `ReadDirectoryChangesW` (`src\main.js`) back to a WSL automount path +/// (`/mnt/c/Users/me/app/src/main.js`). Rejects `..`, `.`, control characters, +/// or malformed roots. +pub fn windows_to_wsl(win_root: &str, rel_win: &str, automount_root: &str) -> Option { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if win_root.contains(['\n', '\r', '\0']) || rel_win.contains(['\n', '\r', '\0']) { + return None; + } + let b = win_root.as_bytes(); + if b.len() < 3 || !b[0].is_ascii_alphabetic() || b[1] != b':' || (b[2] != b'\\' && b[2] != b'/') { + return None; + } + let drive = (b[0] as char).to_ascii_lowercase(); + let mut comps: Vec<&str> = Vec::new(); + for part in win_root[3..].split(['\\', '/']) { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return None; + } + comps.push(part); + } + let mut rel_count = 0usize; + for part in rel_win.split(['\\', '/']) { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return None; + } + comps.push(part); + rel_count += 1; + } + if rel_count == 0 { + return None; + } + Some(format!("{automount_root}{drive}/{}", comps.join("/"))) +} + +/// Whether a relative path belongs to high-volume `.git` internals (object +/// store, reflogs, lockfiles) that cause event storms during git operations. +pub fn is_git_storm_path(rel: &str) -> bool { + let parts: Vec<&str> = rel.split(['\\', '/']).filter(|p| !p.is_empty()).collect(); + for i in 0..parts.len() { + if parts[i].eq_ignore_ascii_case(".git") + && let Some(next) = parts.get(i + 1) + && (next.eq_ignore_ascii_case("objects") || next.eq_ignore_ascii_case("logs") || next.to_ascii_lowercase().ends_with(".lock")) + { + return true; + } + } + false +} + +/// Decodes a Win32 `FILE_NOTIFY_INFORMATION` buffer (UTF-16LE filenames) into +/// `(op, relative_path)` pairs: +/// - `FILE_ACTION_ADDED (1)` -> `'C'` +/// - `FILE_ACTION_REMOVED (2)` / `FILE_ACTION_RENAMED_OLD_NAME (4)` -> `'D'` +/// - `FILE_ACTION_MODIFIED (3)` / `FILE_ACTION_RENAMED_NEW_NAME (5)` -> `'M'` +pub fn decode_notify_buffer(buf: &[u8]) -> Vec<(char, String)> { + const ACTION_ADDED: u32 = 1; + const ACTION_REMOVED: u32 = 2; + const ACTION_MODIFIED: u32 = 3; + const ACTION_RENAMED_OLD: u32 = 4; + const ACTION_RENAMED_NEW: u32 = 5; + + let mut out = Vec::new(); + let mut offset = 0usize; + while offset + 12 <= buf.len() { + let next_offset = u32::from_le_bytes([buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]]) as usize; + let action = u32::from_le_bytes([buf[offset + 4], buf[offset + 5], buf[offset + 6], buf[offset + 7]]); + let name_bytes = u32::from_le_bytes([buf[offset + 8], buf[offset + 9], buf[offset + 10], buf[offset + 11]]) as usize; + let name_start = offset + 12; + let Some(name_end) = name_start.checked_add(name_bytes) else { break }; + if name_end > buf.len() || !name_bytes.is_multiple_of(2) { + break; + } + let op = match action { + ACTION_ADDED => Some('C'), + ACTION_REMOVED | ACTION_RENAMED_OLD => Some('D'), + ACTION_MODIFIED | ACTION_RENAMED_NEW => Some('M'), + _ => None, + }; + if let Some(op) = op && name_bytes > 0 { + let units: Vec = buf[name_start..name_end].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let name = String::from_utf16_lossy(&units); + if !name.is_empty() && !name.contains('\0') { + out.push((op, name)); + } + } + if next_offset == 0 { + break; + } + let Some(next) = offset.checked_add(next_offset) else { break }; + if next <= offset || next > buf.len() { + break; + } + offset = next; + } + out +} + +/// Merges two ops for the same path arriving within one 50 ms debounce window. +fn merge_op(prev: char, next: char) -> char { + match (prev, next) { + (_, 'D') => 'D', + ('C', 'M') | ('M', 'C') | ('C', 'C') => 'C', + ('D', 'C') | ('D', 'M') | ('M', 'M') => 'M', + _ => next, + } +} + +/// Coalesces duplicate/burst events within a batch, preserving arrival order +/// and emitting at most one change line per distinct path. A root's pin +/// (`P`) or unpin (`U`) is kept apart from changes to the same path; the +/// later of the two wins. +pub fn coalesce_events(events: &[(char, String)]) -> Vec { + let mut order: Vec<(bool, String)> = Vec::new(); + let mut ops: HashMap<(bool, String), char> = HashMap::new(); + for (op, path) in events { + if !matches!(op, 'C' | 'M' | 'A' | 'D' | 'P' | 'U') || path.is_empty() { + continue; + } + let key = (matches!(op, 'P' | 'U'), path.clone()); + if let Some(existing) = ops.get_mut(&key) { + *existing = if key.0 { *op } else { merge_op(*existing, *op) }; + } else { + ops.insert(key.clone(), *op); + order.push(key); + } + } + order.into_iter().filter_map(|k| ops.get(&k).map(|op| format!("{op}\t{}", k.1))).collect() +} + +/// The WSL path of a watched Windows directory (`C:\Users\me\app` -> +/// `/mnt/c/Users/me/app`), for its `P` and `U` lines. None for a drive root. +fn wsl_dir(win_dir: &str, automount_root: &str) -> Option { + let (parent, name) = win_dir.trim_end_matches('\\').rsplit_once('\\')?; + let parent = if parent.len() == 2 { format!("{parent}\\") } else { parent.to_owned() }; + windows_to_wsl(&parent, name, automount_root) +} + +/// A Windows directory watch specification: either a recursive directory tree +/// or a single-file mount watched non-recursively via its parent directory. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct WatchSpec { + /// Directory opened with `CreateFileW` (`C:\Users\me\app`). + dir: String, + /// `true` for a directory bind mount, `false` for a single-file mount. + recursive: bool, + /// When `recursive == false`, only match this exact filename (case-insensitive). + only_file: Option, +} + +/// Removes directory specs already covered by a parent recursive directory watch. +fn collapse_specs(specs: Vec) -> Vec { + let mut dirs: Vec = specs.iter().filter(|s| s.recursive).map(|s| s.dir.clone()).collect(); + dirs.sort_by_key(|d| d.len()); + dirs.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + + let covered_by_dir = |path: &str, exclude_self: bool| -> bool { + dirs.iter().any(|parent| { + if exclude_self && parent.eq_ignore_ascii_case(path) { + return false; + } + if path.len() < parent.len() { + return false; + } + let head = &path[..parent.len()]; + if !head.eq_ignore_ascii_case(parent) { + return false; + } + let rest = &path[parent.len()..]; + parent.ends_with('\\') || rest.is_empty() || rest.starts_with('\\') + }) + }; + + let mut seen: HashSet = HashSet::new(); + let mut out = Vec::new(); + for s in specs { + if s.recursive { + if covered_by_dir(&s.dir, true) { + continue; + } + let key = format!("d:{}", s.dir.to_ascii_lowercase()); + if seen.insert(key) { + out.push(s); + } + } else { + let full = match &s.only_file { + Some(f) if s.dir.ends_with('\\') => format!("{}{f}", s.dir), + Some(f) => format!("{}\\{f}", s.dir), + None => s.dir.clone(), + }; + if covered_by_dir(&full, false) { + continue; + } + let key = format!("f:{}", full.to_ascii_lowercase()); + if seen.insert(key) { + out.push(s); + } + } + } + out +} + +#[cfg(windows)] +mod runtime { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Condvar, Mutex, PoisonError, mpsc}; + use std::thread::JoinHandle; + use std::time::{Duration, Instant}; + + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0}; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SIZE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadDirectoryChangesW, + }; + use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}; + use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects}; + + const NOTIFY_FILTER: u32 = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE; + + struct Coordinator { + stop: Arc, + wake: Arc<(Mutex, Condvar)>, + thread: Option>, + } + + static STATE: Mutex> = Mutex::new(None); + + /// Starts the watcher ONLY if opt-in is enabled. When disabled (the + /// default), spawns zero threads and opens zero handles. + pub fn start_if_enabled() { + if is_enabled() { + set_enabled(true); + } + } + + /// Starts or stops the watcher dynamically. Turning it off cancels all + /// `ReadDirectoryChangesW` calls, closes every handle, and stops all + /// watcher threads. + pub fn set_enabled(enabled: bool) { + let mut guard = STATE.lock().unwrap_or_else(PoisonError::into_inner); + if enabled { + if guard.is_some() { + return; + } + let stop = Arc::new(AtomicBool::new(false)); + let wake = Arc::new((Mutex::new(false), Condvar::new())); + let stop_c = stop.clone(); + let wake_c = wake.clone(); + let thread = std::thread::Builder::new().name("kiri-win-watch".into()).spawn(move || coordinate(stop_c, wake_c)).ok(); + if thread.is_some() { + *guard = Some(Coordinator { stop, wake, thread }); + } + } else if let Some(mut coord) = guard.take() { + coord.stop.store(true, Ordering::SeqCst); + { + let (m, cv) = &*coord.wake; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + drop(guard); + if let Some(t) = coord.thread.take() { + let _ = t.join(); + } + } + } + + /// Wakes the coordinator when running containers change. No-op when off. + pub fn notify_containers_changed() { + let guard = STATE.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(coord) = guard.as_ref() { + let (m, cv) = &*coord.wake; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + } + + struct DirWatcher { + /// Manual-reset event: once set, the worker's wait returns at once, + /// whether it is waiting already or not yet. + stop: HANDLE, + thread: Option>, + /// The root's WSL path and the channel its `U` line goes out on. + unpin: Option<(String, mpsc::Sender<(char, String)>)>, + } + + impl DirWatcher { + fn start(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>) -> Option { + // SAFETY: an unnamed manual-reset event, initially not set. + let stop = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + if stop == 0 { + return None; + } + let pin = if spec.recursive { wsl_dir(&spec.dir, &automount_root) } else { None }; + let tx_c = tx.clone(); + let thread = std::thread::Builder::new().name("kiri-win-dirwatch".into()).spawn(move || watch_dir_loop(spec, automount_root, tx_c, stop)); + let Ok(thread) = thread else { + // SAFETY: our own event, never shared. + unsafe { CloseHandle(stop) }; + return None; + }; + if let Some(root) = &pin { + let _ = tx.send(('P', root.clone())); + } + Some(DirWatcher { stop, thread: Some(thread), unpin: pin.map(|root| (root, tx)) }) + } + + fn stop(mut self) { + // SAFETY: `self.stop` stays open until after the join below. + unsafe { SetEvent(self.stop) }; + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + // SAFETY: the worker has exited; nothing else uses the event. + unsafe { CloseHandle(self.stop) }; + if let Some((root, tx)) = self.unpin.take() { + let _ = tx.send(('U', root)); + } + } + } + + /// Reads changes with overlapped `ReadDirectoryChangesW`, waiting on the + /// read and `stop` together, so a stop ends the wait at once. + fn watch_dir_loop(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>, stop: HANDLE) { + let wide: Vec = OsStr::new(&spec.dir).encode_wide().chain(std::iter::once(0)).collect(); + // SAFETY: valid NUL-terminated UTF-16 path with standard directory flags. + let h = unsafe { + CreateFileW( + wide.as_ptr(), + FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, + 0, + ) + }; + if h == INVALID_HANDLE_VALUE || h == 0 { + return; + } + // SAFETY: an unnamed manual-reset event, initially not set. + let io = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + if io == 0 { + // SAFETY: our own handle. + unsafe { CloseHandle(h) }; + return; + } + + // 64 KiB DWORD-aligned buffer as required by ReadDirectoryChangesW. + let mut buf = vec![0u32; 16384]; + let buf_len = (buf.len() * std::mem::size_of::()) as u32; + let subtree = i32::from(spec.recursive); + + loop { + // SAFETY: zeroed OVERLAPPED is valid; its event is ours. + let mut ov: OVERLAPPED = unsafe { std::mem::zeroed() }; + ov.hEvent = io; + // SAFETY: `h`, `buf` and `ov` outlive the read: every path out of + // this iteration waits for it to complete or be cancelled. + let ok = unsafe { ReadDirectoryChangesW(h, buf.as_mut_ptr().cast(), buf_len, subtree, NOTIFY_FILTER, std::ptr::null_mut(), &mut ov, None) }; + if ok == 0 { + break; + } + let waits = [io, stop]; + // SAFETY: two valid event handles. + let woke = unsafe { WaitForMultipleObjects(2, waits.as_ptr(), 0, INFINITE) }; + let mut returned: u32 = 0; + if woke != WAIT_OBJECT_0 { + // Stopped (or the wait failed): cancel the read and wait for it + // to finish before `buf` and `ov` go away. + // SAFETY: `h` and `ov` are the pending read's. + unsafe { + CancelIoEx(h, &ov); + GetOverlappedResult(h, &ov, &mut returned, 1); + } + break; + } + // SAFETY: the read completed; `ov` is its OVERLAPPED. + if unsafe { GetOverlappedResult(h, &ov, &mut returned, 0) } == 0 { + break; + } + let n = (returned as usize).min(buf_len as usize); + // SAFETY: `buf` holds `n` initialized bytes written by Windows. + let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), n) }; + for (op, rel) in decode_notify_buffer(bytes) { + if let Some(only) = &spec.only_file + && !rel.eq_ignore_ascii_case(only) + { + continue; + } + if is_git_storm_path(&rel) { + continue; + } + let Some(wsl_path) = windows_to_wsl(&spec.dir, &rel, &automount_root) else { continue }; + if tx.send((op, wsl_path)).is_err() { + break; + } + } + } + + // SAFETY: closing our own handles; no read is pending. + unsafe { + CloseHandle(io); + CloseHandle(h); + } + } + + fn flush_loop(rx: mpsc::Receiver<(char, String)>) { + while let Ok(first) = rx.recv() { + let mut batch = vec![first]; + let deadline = Instant::now() + DEBOUNCE; + while batch.len() < MAX_BURST { + let Some(rem) = deadline.checked_duration_since(Instant::now()) else { break }; + match rx.recv_timeout(rem) { + Ok(ev) => batch.push(ev), + Err(mpsc::RecvTimeoutError::Timeout) => break, + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + let lines = coalesce_events(&batch); + for chunk in lines.chunks(BATCH) { + let body = json!({"events": chunk}); + let _ = crate::client::request_within("POST", "/kiri/fs-events", Some(&body), true, Some(Duration::from_secs(3))); + } + } + } + + fn desired_watches() -> Option<(String, Vec)> { + let resp = crate::client::get_quick("/kiri/watch-roots").ok()?; + let root = resp["automount_root"].as_str().unwrap_or("/mnt/").to_owned(); + let mut specs = Vec::new(); + for wsl in resp["roots"].as_array().into_iter().flatten().filter_map(Value::as_str) { + let Some(win) = wsl_to_windows(wsl, &root) else { continue }; + let p = std::path::Path::new(&win); + if p.is_dir() { + specs.push(WatchSpec { dir: win, recursive: true, only_file: None }); + } else if p.is_file() + && let (Some(parent), Some(name)) = (p.parent(), p.file_name()) + { + specs.push(WatchSpec { + dir: parent.to_string_lossy().into_owned(), + recursive: false, + only_file: Some(name.to_string_lossy().into_owned()), + }); + } + } + Some((root, collapse_specs(specs))) + } + + fn coordinate(stop: Arc, wake: Arc<(Mutex, Condvar)>) { + let (tx, rx) = mpsc::channel::<(char, String)>(); + let sender = std::thread::Builder::new().name("kiri-win-watch-tx".into()).spawn(move || flush_loop(rx)).ok(); + let mut active: HashMap = HashMap::new(); + let mut last_root = String::from("/mnt/"); + + while !stop.load(Ordering::SeqCst) { + if let Some((root, want)) = desired_watches() { + let root_changed = root != last_root; + last_root = root.clone(); + let want_set: HashSet = want.iter().cloned().collect(); + let remove: Vec = active.keys().filter(|k| root_changed || !want_set.contains(*k)).cloned().collect(); + for k in remove { + if let Some(w) = active.remove(&k) { + w.stop(); + } + } + for spec in want { + if !active.contains_key(&spec) + && let Some(w) = DirWatcher::start(spec.clone(), root.clone(), tx.clone()) + { + active.insert(spec, w); + } + } + } + if stop.load(Ordering::SeqCst) { + break; + } + let (m, cv) = &*wake; + let mut signaled = m.lock().unwrap_or_else(PoisonError::into_inner); + if !*signaled { + let (g, _) = cv.wait_timeout(signaled, RESCAN_FALLBACK).unwrap_or_else(PoisonError::into_inner); + signaled = g; + } + *signaled = false; + } + + for (_, w) in active.drain() { + w.stop(); + } + drop(tx); + if let Some(t) = sender { + let _ = t.join(); + } + } +} + +#[cfg(windows)] +pub use runtime::{notify_containers_changed, set_enabled, start_if_enabled}; + +#[cfg(test)] +mod tests { + use super::*; + + fn encode_notify_entries(entries: &[(u32, &str)]) -> Vec { + let mut buf = Vec::new(); + for (idx, (action, name)) in entries.iter().enumerate() { + let utf16: Vec = name.encode_utf16().collect(); + let name_bytes = utf16.len() * 2; + let raw_len = 12 + name_bytes; + let padded_len = (raw_len + 3) & !3; + let next_offset = if idx + 1 < entries.len() { padded_len as u32 } else { 0u32 }; + buf.extend_from_slice(&next_offset.to_le_bytes()); + buf.extend_from_slice(&action.to_le_bytes()); + buf.extend_from_slice(&(name_bytes as u32).to_le_bytes()); + for u in utf16 { + buf.extend_from_slice(&u.to_le_bytes()); + } + buf.resize(buf.len() + (padded_len - raw_len), 0); + } + buf + } + + #[test] + fn opt_in_is_off_by_default_and_honors_settings_and_env() { + assert!(!parse_settings_enabled(None, None)); + assert!(!parse_settings_enabled(Some("{}"), None)); + assert!(!parse_settings_enabled(Some(r#"{"watchBindMounts": false}"#), None)); + assert!(parse_settings_enabled(Some(r#"{"watchBindMounts": true}"#), None)); + assert!(parse_settings_enabled(None, Some("1"))); + assert!(parse_settings_enabled(Some(r#"{"watchBindMounts": false}"#), Some("true"))); + assert!(!parse_settings_enabled(Some(r#"{"watchBindMounts": true}"#), Some("0"))); + assert!(!parse_settings_enabled(Some("not json"), None)); + } + + #[test] + fn wsl_and_windows_path_mapping_and_traversal_rejection() { + assert_eq!(wsl_to_windows("/mnt/c/Users/me/app", "/mnt/").as_deref(), Some(r"C:\Users\me\app")); + assert_eq!(wsl_to_windows("/mnt/d/My Project/src", "/mnt/").as_deref(), Some(r"D:\My Project\src")); + assert_eq!(wsl_to_windows("/mnt/c", "/mnt/").as_deref(), Some(r"C:\")); + assert_eq!(wsl_to_windows("/windows/e/code", "/windows/").as_deref(), Some(r"E:\code")); + // Reject non-/mnt/, multi-letter mount names, and .. traversal. + assert_eq!(wsl_to_windows("/home/me/app", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/mac/Users/a", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/../etc/passwd", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/../../etc/shadow", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/a\nb", "/mnt/"), None); + + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"src\main.js", "/mnt/").as_deref(), Some("/mnt/c/Users/me/app/src/main.js")); + assert_eq!(windows_to_wsl(r"C:\", r"test\app.js", "/mnt/").as_deref(), Some("/mnt/c/test/app.js")); + assert_eq!(windows_to_wsl(r"D:\proj", r"sub\file.ts", "/windows/").as_deref(), Some("/windows/d/proj/sub/file.ts")); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"..\secret.txt", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", "", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"\\server\share", r"a.txt", "/mnt/"), None); + } + + #[test] + fn decodes_utf16le_file_notify_information_buffer() { + let buf = encode_notify_entries(&[ + (1, r"src\new.ts"), + (2, r"src\old.ts"), + (3, r"src\app.ts"), + (4, r"src\before.ts"), + (5, r"src\after.ts"), + (3, "src\\caf\u{00e9}.js"), + ]); + assert_eq!( + decode_notify_buffer(&buf), + vec![ + ('C', r"src\new.ts".into()), + ('D', r"src\old.ts".into()), + ('M', r"src\app.ts".into()), + ('D', r"src\before.ts".into()), + ('M', r"src\after.ts".into()), + ('M', "src\\caf\u{00e9}.js".into()), + ] + ); + // Truncated buffer does not panic. + assert!(decode_notify_buffer(&buf[..5]).is_empty()); + assert!(decode_notify_buffer(&[]).is_empty()); + } + + #[test] + fn coalesces_bursts_and_filters_git_object_storms() { + assert!(is_git_storm_path(r".git\objects\ab\123456")); + assert!(is_git_storm_path(r"sub\.git\objects\pack\pack-1.idx")); + assert!(is_git_storm_path(r".git\logs\HEAD")); + assert!(is_git_storm_path(r".git\index.lock")); + assert!(!is_git_storm_path(r".gitignore")); + assert!(!is_git_storm_path(r"src\app.js")); + assert!(!is_git_storm_path(r".git\HEAD")); + + let events = vec![ + ('M', "/mnt/c/app/a.js".into()), + ('M', "/mnt/c/app/a.js".into()), + ('C', "/mnt/c/app/b.js".into()), + ('M', "/mnt/c/app/b.js".into()), + ('D', "/mnt/c/app/c.js".into()), + ('M', "/mnt/c/app/c.js".into()), + ('C', "/mnt/c/app/tmp.js".into()), + ('D', "/mnt/c/app/tmp.js".into()), + ('P', "/mnt/c/app".into()), + ('M', "/mnt/c/app".into()), + ('U', "/mnt/c/app".into()), + ]; + assert_eq!( + coalesce_events(&events), + vec![ + "M\t/mnt/c/app/a.js", + "C\t/mnt/c/app/b.js", + "M\t/mnt/c/app/c.js", + "D\t/mnt/c/app/tmp.js", + "U\t/mnt/c/app", + "M\t/mnt/c/app", + ] + ); + assert_eq!(wsl_dir(r"C:\Users\me\app", "/mnt/").as_deref(), Some("/mnt/c/Users/me/app")); + assert_eq!(wsl_dir(r"D:\proj\", "/mnt/").as_deref(), Some("/mnt/d/proj")); + assert_eq!(wsl_dir(r"C:\", "/mnt/"), None); + } + + #[test] + fn collapses_nested_watch_specs() { + let specs = vec![ + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\app\src".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: false, only_file: Some(".env".into()) }, + WatchSpec { dir: r"C:\Users\me\application".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me".into(), recursive: false, only_file: Some(".env".into()) }, + ]; + let collapsed = collapse_specs(specs); + assert_eq!( + collapsed, + vec![ + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\application".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me".into(), recursive: false, only_file: Some(".env".into()) }, + ] + ); + } +} diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index d6614592c..a0ab8c918 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -244,6 +244,8 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream ("POST", "/build/prune") => return reply(w, super::builder::prune(req, engine), 200), ("GET", "/kiri/builder") => return reply(w, Ok(super::builder::settings_report(engine)), 200), ("POST", "/kiri/builder") => return reply(w, super::builder::set_settings(req).map(|()| super::builder::settings_report(engine)), 200), + ("GET", "/kiri/watch-roots") => return reply(w, Ok(watch_roots(engine)), 200), + ("POST", "/kiri/fs-events") => return reply(w, fs_events(req, engine), 204), ("GET", "/images/json") => return reply(w, images(req, engine), 200), ("POST", "/images/create") if req.query("fromSrc").is_some_and(|s| !s.is_empty()) => return image_import(req, engine, w, r), ("POST", "/images/create") => return pull(req, engine, w), @@ -1067,6 +1069,48 @@ fn set_env(req: &Request, engine: &Engine, id: &str) -> Result { Ok(Value::Null) } +/// Active WSL drive bind sources of running containers, for `kiri-win`'s +/// opt-in bind-mount watcher. +fn watch_roots(engine: &Engine) -> Value { + let root = super::binds::wsl().map_or("/mnt/", |w| w.root.as_str()); + json!({ + "automount_root": root, + "roots": engine.wsl_bind_sources(root), + }) +} + +/// Parses `POST /kiri/fs-events` (`{"events": ["OP\tPATH", ...]}` or newline- +/// separated `OP\tPATH` text), filters to valid WSL automount paths under +/// `automount_root` with no `..` traversal, and caps per-request volume. OP is +/// a change (`C`, `M`, `A`, `D`) or a watched root's pin (`P`) or unpin (`U`). +fn parse_fs_events(body: &[u8], automount_root: &str) -> Result, Error> { + const MAX_EVENTS: usize = 4096; + let raw: Vec = if body.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{') { + let v: Value = serde_json::from_slice(body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + strings(&v["events"]).ok_or_else(|| Error::BadRequest("events must be a list of OP\\tPATH lines".into()))? + } else { + let text = std::str::from_utf8(body).map_err(|_| Error::BadRequest("invalid UTF-8 body".into()))?; + text.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect() + }; + if raw.len() > MAX_EVENTS { + return Err(Error::BadRequest(format!("too many events ({}, limit is {MAX_EVENTS})", raw.len()))); + } + Ok(raw + .into_iter() + .filter(|line| { + let Some((op, path)) = line.split_once('\t') else { return false }; + matches!(op, "C" | "M" | "A" | "D" | "P" | "U") && super::binds::is_wsl_drive_path(path, automount_root, false) + }) + .collect()) +} + +fn fs_events(req: &Request, engine: &Engine) -> Result { + let root = super::binds::wsl().map_or("/mnt/", |w| w.root.as_str()); + let lines = parse_fs_events(&req.body, root)?; + engine.send_fs_events(&lines); + Ok(Value::Null) +} + /// A registry client with the credentials the CLI sent, if any. fn client_for(req: &Request) -> Client { Client::new().with_credentials(req.header("x-registry-auth").and_then(kiri_image::Credentials::from_header)) @@ -4465,7 +4509,7 @@ mod tests { }; let mut routes = kiri_routes(body_of(include_str!("api.rs"), "\nfn route(")); routes.extend(kiri_routes(body_of(include_str!("ops.rs"), "\npub fn route("))); - for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("DELETE", "/kiri/k8s/forward/1")] { + for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] { assert!(routes.iter().any(|(m, p)| (m.as_str(), p.as_str()) == known), "{known:?} not found in route(): {routes:?}"); } for (m, p) in &routes { @@ -4484,13 +4528,60 @@ mod tests { } } + #[test] + fn fs_events_parsing_validates_paths_and_rejects_traversal() { + let json_body = br#"{"events":["M\t/mnt/c/Users/me/app.js","D\t/etc/passwd","C\t/mnt/c/../etc/shadow","X\t/mnt/c/a","C\t/mnt/d/new.ts"]}"#; + assert_eq!(parse_fs_events(json_body, "/mnt/").unwrap(), vec!["M\t/mnt/c/Users/me/app.js", "C\t/mnt/d/new.ts"]); + let text_body = b"M\t/mnt/c/test/app.js\nD\t/mnt/mac/Users/a\nP\t/mnt/c/test\nU\t/etc\n"; + assert_eq!(parse_fs_events(text_body, "/mnt/").unwrap(), vec!["M\t/mnt/c/test/app.js", "P\t/mnt/c/test"]); + assert!(parse_fs_events(b"{not json", "/mnt/").is_err()); + let too_many = vec!["M\t/mnt/c/a"; 4097].join("\n"); + assert!(parse_fs_events(too_many.as_bytes(), "/mnt/").is_err()); + } + + #[test] + fn watch_roots_and_fs_events_endpoints_work_without_waking_vm() { + use std::io::{Read, Write}; + let (root, engine) = engine_in("watch-roots", false); + // GET /kiri/watch-roots + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.write_all(b"GET /kiri/watch-roots HTTP/1.1\r\nHost: d\r\nX-Kiri-Background: 1\r\nConnection: close\r\n\r\n").unwrap(); + let mut got = String::new(); + client.read_to_string(&mut got).unwrap(); + served.join().unwrap().unwrap(); + assert!(got.starts_with("HTTP/1.1 200 "), "{got}"); + assert!(got.contains("\"automount_root\":\"/mnt/\""), "{got}"); + assert!(got.contains("\"roots\":[]"), "{got}"); + + // POST /kiri/fs-events from Host returns 204 and does not wake VM + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + let body = r#"{"events":["M\t/mnt/c/test/app.js"]}"#; + client.write_all(format!("POST /kiri/fs-events HTTP/1.1\r\nHost: d\r\nX-Kiri-Background: 1\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).unwrap(); + let mut got = String::new(); + client.read_to_string(&mut got).unwrap(); + served.join().unwrap().unwrap(); + assert!(got.starts_with("HTTP/1.1 204 "), "{got}"); + assert!(!engine.is_awake()); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// Through the API itself: a container's Stop and settings are refused, /// and the engine stays as it was. #[test] fn a_containers_stop_and_settings_are_refused() { use std::io::{Read, Write}; let (root, engine) = engine_in("container-gate", false); - for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains"] { + for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains", "POST /kiri/fs-events"] { let (mut client, server) = UnixStream::pair().unwrap(); let served = std::thread::spawn({ let engine = engine.clone(); diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index a0edecdd8..5e1862a2c 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -171,6 +171,40 @@ fn drive(wsl: &Wsl, letter: u8, rest: &str) -> String { clean(&format!("{}{}/{}", wsl.root, letter.to_ascii_lowercase() as char, rest.replace('\\', "/"))) } +/// Whether `path` is under WSL's automount root (`/...`, +/// or `` when `allow_drive_root` is true), with no +/// control characters and no `.` or `..` traversal components. +pub fn is_wsl_drive_path(path: &str, automount_root: &str, allow_drive_root: bool) -> bool { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return false; + } + if path.contains(['\n', '\r', '\0']) { + return false; + } + let Some(rest) = path.strip_prefix(automount_root) else { return false }; + let bytes = rest.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() { + return false; + } + if bytes.len() == 1 { + return allow_drive_root; + } + if bytes[1] != b'/' { + return false; + } + let mut has_component = false; + for part in rest[2..].split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return false; + } + has_component = true; + } + has_component || allow_drive_root +} + /// Single slashes, none at the end. fn clean(p: &str) -> String { let mut out = String::with_capacity(p.len()); @@ -535,4 +569,17 @@ mod tests { assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", none), None); assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", &itself), None); } + + #[test] + fn wsl_drive_path_validation() { + assert!(is_wsl_drive_path("/mnt/c/Users/me/app", "/mnt/", false)); + assert!(is_wsl_drive_path("/mnt/c", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c", "/mnt/", false)); + assert!(!is_wsl_drive_path("/mnt/c/", "/mnt/", false)); + assert!(!is_wsl_drive_path("/mnt/mac/Users/a", "/mnt/", true)); + assert!(!is_wsl_drive_path("/etc/passwd", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c/../etc/passwd", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c/a\nb", "/mnt/", true)); + assert!(is_wsl_drive_path("/windows/d/proj", "/windows/", false)); + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 27b780944..782e6b2a7 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -2190,6 +2190,38 @@ impl Engine { out } + /// The WSL drive bind sources (`/mnt/` or `/mnt//...`) of + /// running containers, under `automount_root` (e.g. `/mnt/`). + pub fn wsl_bind_sources(&self, automount_root: &str) -> Vec { + let mut out: Vec = self + .lock() + .containers + .values() + .filter(|c| c.status == Status::Running) + .flat_map(|c| c.spec.mounts.iter()) + .filter_map(|m| { + let src = m.split('\t').next()?; + super::binds::is_wsl_drive_path(src, automount_root, true).then(|| src.to_owned()) + }) + .collect(); + out.sort(); + out.dedup(); + out + } + + /// Forwards host file-change lines (`OP\tPATH`) to the running agent + /// without waking a sleeping or stopped VM/agent. + pub fn send_fs_events(&self, lines: &[String]) { + if lines.is_empty() { + return; + } + if let Some(vm) = self.awake() { + for chunk in lines.chunks(512) { + let _ = vm.fs_events(chunk); + } + } + } + /// The VM's link while it runs, without waking it. #[cfg(target_os = "macos")] pub fn awake_link(&self) -> Option> { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index aed17e265..866ce9632 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,9 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### #487 Windows: opt-in file-change events for `C:\` bind mounts (unreleased) +- Fixes: #487 Windows: file watchers in containers never hear of changes made on Windows to files in `C:\` bind mounts + ### #319 Mac: relay outbound container TCP for split-tunnel VPN routes and security network extensions (unreleased) - Fixes: #319 Mac: containers can't reach hosts behind a split-tunnel VPN; #367 Mac: containers have no working HTTP/HTTPS when a security network extension is active (DNS answers 198.18.x, TCP reset); #616 macOS: large HTTPS downloads from Google-fronted hosts stall in containers (~10 KB/s) while the Mac gets 17 MB/s; Cloudflare is fine @@ -34,6 +37,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug + ### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known From afd53c026bc760f955e99939542358a6d6fc7e73 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:50:23 +0100 Subject: [PATCH 041/157] Mac: support configuring and growing the VM data disk online (#384) (#824) Co-authored-by: Shuvro Roy --- crates/kiri-init/src/linux/disk.rs | 126 +++++++++++++ crates/kiri-init/src/linux/mod.rs | 3 + crates/kiri/src/daemon/api.rs | 162 ++++++++++++++-- crates/kiri/src/daemon/engine.rs | 30 ++- crates/kiri/src/guest.rs | 11 +- crates/kiri/src/guest/disk.rs | 271 +++++++++++++++++++++++++++ crates/kiri/src/ui/index.html | 27 ++- crates/kiri/src/ui/lang/am.json | 6 +- crates/kiri/src/ui/lang/ar.json | 6 +- crates/kiri/src/ui/lang/bg.json | 6 +- crates/kiri/src/ui/lang/bn.json | 6 +- crates/kiri/src/ui/lang/ca.json | 6 +- crates/kiri/src/ui/lang/ckb.json | 6 +- crates/kiri/src/ui/lang/cs.json | 6 +- crates/kiri/src/ui/lang/de.json | 6 +- crates/kiri/src/ui/lang/el.json | 6 +- crates/kiri/src/ui/lang/es.json | 6 +- crates/kiri/src/ui/lang/fa.json | 6 +- crates/kiri/src/ui/lang/fi.json | 6 +- crates/kiri/src/ui/lang/fr.json | 6 +- crates/kiri/src/ui/lang/hi.json | 6 +- crates/kiri/src/ui/lang/hu.json | 6 +- crates/kiri/src/ui/lang/id.json | 6 +- crates/kiri/src/ui/lang/it.json | 6 +- crates/kiri/src/ui/lang/ja.json | 6 +- crates/kiri/src/ui/lang/kk.json | 6 +- crates/kiri/src/ui/lang/ko.json | 6 +- crates/kiri/src/ui/lang/lo.json | 6 +- crates/kiri/src/ui/lang/lt.json | 6 +- crates/kiri/src/ui/lang/nb.json | 6 +- crates/kiri/src/ui/lang/pl.json | 6 +- crates/kiri/src/ui/lang/pt-BR.json | 6 +- crates/kiri/src/ui/lang/ro.json | 6 +- crates/kiri/src/ui/lang/ru.json | 6 +- crates/kiri/src/ui/lang/sl.json | 6 +- crates/kiri/src/ui/lang/sq.json | 6 +- crates/kiri/src/ui/lang/ta.json | 6 +- crates/kiri/src/ui/lang/te.json | 6 +- crates/kiri/src/ui/lang/th.json | 6 +- crates/kiri/src/ui/lang/tr.json | 6 +- crates/kiri/src/ui/lang/uk.json | 6 +- crates/kiri/src/ui/lang/vi.json | 6 +- crates/kiri/src/ui/lang/zh-Hans.json | 6 +- crates/kiri/src/ui/lang/zh-Hant.json | 6 +- docs/development.md | 14 ++ docs/features.md | 5 +- docs/fix-registry.md | 6 + tests/disk-grow.py | 130 +++++++++++++ tests/regressions.tsv | 2 + tests/ui/resources-disk.js | 96 ++++++++++ 50 files changed, 1038 insertions(+), 67 deletions(-) create mode 100644 crates/kiri-init/src/linux/disk.rs create mode 100644 crates/kiri/src/guest/disk.rs create mode 100644 tests/disk-grow.py create mode 100644 tests/ui/resources-disk.js diff --git a/crates/kiri-init/src/linux/disk.rs b/crates/kiri-init/src/linux/disk.rs new file mode 100644 index 000000000..cca7d15d1 --- /dev/null +++ b/crates/kiri-init/src/linux/disk.rs @@ -0,0 +1,126 @@ +//! Expand the mounted ext4 filesystem to the backing device's capacity. + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +use std::os::fd::AsRawFd; +use std::path::Path; + +const EXT4_SUPER_OFFSET: u64 = 1024; +const EXT4_SUPER_LEN: usize = 1024; +const EXT4_SUPER_MAGIC: u16 = 0xEF53; +const EXT4_FEATURE_INCOMPAT_64BIT: u32 = 0x80; + +// EXT4_IOC_RESIZE_FS = _IOW('f', 16, __u64), on both guest architectures. +const EXT4_IOC_RESIZE_FS: libc::Ioctl = 0x4008_6610_u32 as libc::Ioctl; + +/// Parses the ext4 superblock's total block count (including metadata). +/// Returns `InvalidData` if the superblock magic does not match ext4. +fn superblock_blocks(sb: &[u8; EXT4_SUPER_LEN]) -> io::Result { + let magic = u16::from_le_bytes([sb[0x38], sb[0x39]]); + if magic != EXT4_SUPER_MAGIC { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unexpected ext4 superblock magic 0x{magic:04x}"), + )); + } + let word = |offset: usize| u32::from_le_bytes(sb[offset..offset + 4].try_into().unwrap()); + let mut blocks = u64::from(word(0x04)); + if word(0x60) & EXT4_FEATURE_INCOMPAT_64BIT != 0 { + blocks |= u64::from(word(0x150)) << 32; + } + Ok(blocks) +} + +pub fn grow() -> io::Result<()> { + grow_device(Path::new("/dev/vda"), Path::new(super::DATA)) +} + +pub(crate) fn grow_device(device: &Path, mountpoint: &Path) -> io::Result<()> { + let mut disk = File::open(device)?; + let bytes = disk.seek(SeekFrom::End(0))?; + // The data disk has already mounted as ext4. Read its total block + // count, including metadata (statfs excludes metadata from f_blocks). + disk.seek(SeekFrom::Start(EXT4_SUPER_OFFSET))?; + let mut sb = [0u8; EXT4_SUPER_LEN]; + disk.read_exact(&mut sb)?; + let current = superblock_blocks(&sb)?; + let fs = File::open(mountpoint)?; + // SAFETY: statfs is plain data; fstatfs writes it before it is read. + let mut stat: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: fs is open and stat is valid writable storage. + super::sys::check( + unsafe { libc::fstatfs(fs.as_raw_fd(), &mut stat) } as _, + "data disk statfs", + )?; + let block_size = stat.f_bsize as u64; + if block_size == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid ext4 block size", + )); + } + let blocks = bytes / block_size; + if blocks <= current { + return Ok(()); + } + // SAFETY: fs is the mounted ext4 directory and blocks is a valid u64. + super::sys::check( + unsafe { libc::ioctl(fs.as_raw_fd(), EXT4_IOC_RESIZE_FS, &blocks) } as _, + "grow ext4 data disk", + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake_superblock(lo: u32, hi: u32, is_64bit: bool) -> [u8; EXT4_SUPER_LEN] { + let mut sb = [0u8; EXT4_SUPER_LEN]; + sb[0x38..0x3a].copy_from_slice(&EXT4_SUPER_MAGIC.to_le_bytes()); + sb[0x04..0x08].copy_from_slice(&lo.to_le_bytes()); + let incompat: u32 = if is_64bit { + EXT4_FEATURE_INCOMPAT_64BIT + } else { + 0 + }; + sb[0x60..0x64].copy_from_slice(&incompat.to_le_bytes()); + sb[0x150..0x154].copy_from_slice(&hi.to_le_bytes()); + sb + } + + #[test] + fn superblock_reads_32bit_and_64bit_block_counts() { + let sb32 = fake_superblock(16_777_216, 99, false); + assert_eq!(superblock_blocks(&sb32).unwrap(), 16_777_216); + + let sb64 = fake_superblock(0x0000_0001, 0x0000_0002, true); + assert_eq!(superblock_blocks(&sb64).unwrap(), (2u64 << 32) | 1); + } + + #[test] + fn superblock_rejects_bad_magic() { + let sb = [0u8; EXT4_SUPER_LEN]; + assert_eq!( + superblock_blocks(&sb).unwrap_err().kind(), + io::ErrorKind::InvalidData + ); + } + + /// Real online ext4 resize check when driven on a Linux host with a + /// mounted loop device (`KIRI_TEST_EXT4_DEV` + `KIRI_TEST_EXT4_MOUNT`). + #[test] + fn grows_mounted_ext4_online_when_configured() { + let (Ok(dev), Ok(mnt)) = ( + std::env::var("KIRI_TEST_EXT4_DEV"), + std::env::var("KIRI_TEST_EXT4_MOUNT"), + ) else { + return; + }; + let dev = Path::new(&dev); + let mnt = Path::new(&mnt); + grow_device(dev, mnt).expect("first online ext4 resize must succeed"); + // Calling grow again when already at full capacity must be a no-op. + grow_device(dev, mnt).expect("second online ext4 resize must be idempotent"); + } +} diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index 17c28566d..b23cb3333 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -2,6 +2,7 @@ mod agent; mod cgroup; mod container; mod devices; +mod disk; mod copy; mod dns; mod fsnotify; @@ -542,6 +543,8 @@ fn data_dirs() -> io::Result { if let Err(ref e) = disk { eprintln!("kiri-init: no data disk ({e}); keeping images in memory"); mount(c"kiri", c"/var/lib/kiri", c"tmpfs", libc::MS_NOATIME, Some(c"mode=0755"))?; + } else if let Err(e) = disk::grow() { + eprintln!("kiri-init: growing data disk: {e}"); } // The Mac's filesystem over virtiofs, for bind mounts. sys::mkdir(c"/mnt", 0o755); diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index a0ab8c918..de901291a 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -949,16 +949,56 @@ fn image_scan(req: &Request, w: &mut UnixStream) -> io::Result { /// the limits of this Mac. fn resources(engine: &Engine) -> Value { use super::engine as e; - json!({ - "cpus": e::vm_cpus(), - "memory_mib": e::memory_ceiling() >> 20, - "running_cpus": engine.cpus(), - "running_memory_mib": engine.memory().0 >> 20, - "awake": engine.is_awake(), - "max_cpus": e::max_cpus(), - "max_memory_mib": e::physical_memory_bytes() >> 20, - "overridden": std::env::var_os("KIRI_CPUS").is_some() || std::env::var_os("KIRI_MEMORY_MIB").is_some(), - }) + #[cfg(target_os = "macos")] + let disk = Some((crate::guest::disk::current_gb(), e::vm_disk_gb(), engine.disk_gb())); + #[cfg(not(target_os = "macos"))] + let disk: Option<(u64, u64, u64)> = None; + let overridden = std::env::var_os("KIRI_CPUS").is_some() + || std::env::var_os("KIRI_MEMORY_MIB").is_some() + || (cfg!(target_os = "macos") && std::env::var_os("KIRI_DISK_GB").is_some()); + resources_payload( + e::vm_cpus(), + e::memory_ceiling() >> 20, + engine.cpus(), + engine.memory().0 >> 20, + engine.is_awake(), + e::max_cpus(), + e::physical_memory_bytes() >> 20, + overridden, + disk, + ) +} + +#[allow(clippy::too_many_arguments)] +fn resources_payload( + cpus: usize, + memory_mib: u64, + running_cpus: usize, + running_memory_mib: u64, + awake: bool, + max_cpus: usize, + max_memory_mib: u64, + overridden: bool, + disk: Option<(u64, u64, u64)>, +) -> Value { + let mut v = json!({ + "cpus": cpus, + "memory_mib": memory_mib, + "running_cpus": running_cpus, + "running_memory_mib": running_memory_mib, + "awake": awake, + "max_cpus": max_cpus, + "max_memory_mib": max_memory_mib, + "overridden": overridden, + }); + if let Some((current_disk_gb, disk_gb, running_disk_gb)) = disk { + let (min_disk_gb, max_disk_gb) = crate::guest::disk::ui_bounds(current_disk_gb, disk_gb); + v["disk_gb"] = json!(disk_gb); + v["running_disk_gb"] = json!(running_disk_gb); + v["min_disk_gb"] = json!(min_disk_gb); + v["max_disk_gb"] = json!(max_disk_gb); + } + v } /// The host's system proxy, from kiri-win on Windows: `{http, https, @@ -1021,13 +1061,46 @@ fn set_domain_ports(req: &Request, engine: &Arc) -> Result fn set_resources(req: &Request) -> Result<(), Error> { use super::engine as e; - let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; - let max_mem = e::physical_memory_bytes() >> 20; - let cpus = body["cpus"].as_u64().filter(|c| (1..=e::max_cpus() as u64).contains(c)).ok_or_else(|| Error::BadRequest(format!("cpus must be 1 to {}", e::max_cpus())))?; - let mem = body["memory_mib"].as_u64().filter(|m| (1024..=max_mem).contains(m)).ok_or_else(|| Error::BadRequest(format!("memory_mib must be 1024 to {max_mem}")))?; let path = e::resources_path().ok_or_else(|| Error::Io(io::Error::other("HOME is not set")))?; + let current_disk = cfg!(target_os = "macos").then(crate::guest::disk::current_gb); + save_resources( + &req.body, + &path, + e::max_cpus() as u64, + e::physical_memory_bytes() >> 20, + current_disk, + e::vm_disk_gb_config(), + ) +} + +fn save_resources( + raw_body: &[u8], + path: &std::path::Path, + max_cpus: u64, + max_mem: u64, + current_disk_gb: Option, + existing_disk_gb: Option, +) -> Result<(), Error> { + let body: Value = serde_json::from_slice(raw_body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + let cpus = body["cpus"].as_u64().filter(|c| (1..=max_cpus).contains(c)).ok_or_else(|| Error::BadRequest(format!("cpus must be 1 to {max_cpus}")))?; + let mem = body["memory_mib"].as_u64().filter(|m| (1024..=max_mem).contains(m)).ok_or_else(|| Error::BadRequest(format!("memory_mib must be 1024 to {max_mem}")))?; + let mut out = json!({"cpus": cpus, "memory_mib": mem}); + if let Some(val) = body.get("disk_gb").filter(|v| !v.is_null()) { + let current = current_disk_gb.unwrap_or(crate::guest::disk::DEFAULT_GB); + let (min_disk, max_disk) = crate::guest::disk::ui_bounds(current, existing_disk_gb.unwrap_or(current)); + let disk_gb = val + .as_u64() + .filter(|d| (min_disk..=max_disk).contains(d)) + .ok_or_else(|| Error::BadRequest(format!("disk_gb must be {min_disk} to {max_disk}")))?; + out["disk_gb"] = json!(disk_gb); + } else if let Some(prev) = existing_disk_gb { + out["disk_gb"] = json!(prev); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(Error::Io)?; + } let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, json!({"cpus": cpus, "memory_mib": mem}).to_string()).and_then(|()| std::fs::rename(&tmp, &path)).map_err(Error::Io) + std::fs::write(&tmp, out.to_string()).and_then(|()| std::fs::rename(&tmp, path)).map_err(Error::Io) } fn set_ports(req: &Request, engine: &Engine, id: &str) -> Result { @@ -6157,3 +6230,62 @@ mod leave_first_network_tests { let _ = std::fs::remove_dir_all(root); } } + +#[cfg(test)] +mod resources_disk_tests { + use super::*; + + #[test] + fn resources_payload_round_trip_and_disk_bounds() { + let dir = std::env::temp_dir().join(format!( + "kiri-res-disk-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + let path = dir.join("vm.json"); + + // Save CPUs, memory and disk_gb; verify vm.json contents. + let body = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 128}).to_string(); + save_resources(body.as_bytes(), &path, 12, 32768, Some(64), None).unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved, json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 128})); + + // Omitting disk_gb preserves the existing disk_gb in vm.json. + let body2 = json!({"cpus": 6, "memory_mib": 4096}).to_string(); + save_resources(body2.as_bytes(), &path, 12, 32768, Some(64), saved["disk_gb"].as_u64()).unwrap(); + let saved2: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved2, json!({"cpus": 6, "memory_mib": 4096, "disk_gb": 128})); + + // Shrinking below current data.img size (128 GiB) is rejected with 400. + let shrink = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 96}).to_string(); + match save_resources(shrink.as_bytes(), &path, 12, 32768, Some(128), Some(128)) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("disk_gb must be 128 to 1024"), "{msg}"), + other => panic!("expected BadRequest for shrink, got {other:?}"), + } + + // Below 64 GiB template floor, zero, negative, and oversized values are rejected. + for bad in [json!(0), json!(32), json!(-1), json!(2048), json!("128")] { + let raw = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": bad}).to_string(); + match save_resources(raw.as_bytes(), &path, 12, 32768, Some(64), None) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("disk_gb must be"), "{msg}"), + other => panic!("expected BadRequest for {bad}, got {other:?}"), + } + } + + // Payload includes disk fields on macOS and omits them when None (Linux). + let mac = resources_payload(4, 8192, 4, 8192, true, 12, 32768, false, Some((128, 256, 128))); + assert_eq!(mac["disk_gb"], 256); + assert_eq!(mac["running_disk_gb"], 128); + assert_eq!(mac["min_disk_gb"], 128); + assert_eq!(mac["max_disk_gb"], 1024); + + let linux = resources_payload(4, 8192, 4, 8192, true, 12, 32768, false, None); + assert!(linux.get("disk_gb").is_none()); + assert!(linux.get("min_disk_gb").is_none()); + + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 782e6b2a7..7d408cb3a 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -243,7 +243,7 @@ pub fn max_cpus() -> usize { std::thread::available_parallelism().map_or(2, std::num::NonZero::get) } -/// What Settings → Resources saved, read at each boot: `{"cpus", "memory_mib"}`. +/// What Settings → Resources saved, read at each boot: `{"cpus", "memory_mib", "disk_gb"}`. pub fn resources_path() -> Option { super::state_dir().ok().map(|d| d.join("vm.json")) } @@ -252,6 +252,22 @@ pub fn resources() -> serde_json::Value { resources_path().and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(serde_json::Value::Null) } +/// The VM's persistent data disk size from `vm.json`, if valid. +pub fn vm_disk_gb_config() -> Option { + resources()["disk_gb"] + .as_u64() + .filter(|&gb| crate::guest::disk::size_bytes(gb).is_ok()) +} + +/// The VM's effective data disk size in GiB: `KIRI_DISK_GB`, else +/// Settings → Resources (`vm.json`), else 64 GiB; never below the current +/// `data.img` size. +pub fn vm_disk_gb() -> u64 { + let env_os = std::env::var_os("KIRI_DISK_GB"); + let env_str = env_os.as_ref().and_then(|v| v.to_str()); + crate::guest::disk::effective_gb(env_str, vm_disk_gb_config(), crate::guest::disk::current_gb()) +} + pub fn physical_memory_bytes() -> u64 { physical_memory() } @@ -1310,6 +1326,8 @@ pub struct Engine { ceiling: std::sync::atomic::AtomicU64, /// CPUs the running VM has. cpus: std::sync::atomic::AtomicUsize, + /// Data disk capacity in GiB the running VM booted with (macOS). + disk_gb: std::sync::atomic::AtomicU64, memory_target: Mutex, /// What the guest last used, in bytes (0 while asleep): the balloon's /// measure, without the pages the balloon itself holds. @@ -1463,6 +1481,7 @@ impl Engine { parking: std::sync::atomic::AtomicBool::new(false), ceiling: std::sync::atomic::AtomicU64::new(ceiling), cpus: std::sync::atomic::AtomicUsize::new(vm_cpus()), + disk_gb: std::sync::atomic::AtomicU64::new(vm_disk_gb()), memory_target: Mutex::new(ceiling), memory_used: std::sync::atomic::AtomicU64::new(0), mem_available_kib: std::sync::atomic::AtomicU64::new(0), @@ -1622,7 +1641,7 @@ impl Engine { if recovery && !self.lock().containers.values().any(recover_after_vm_loss) { return Err(io::Error::new(io::ErrorKind::WouldBlock, "VM recovery was canceled")); } - let (ceiling, cpus) = (memory_ceiling(), vm_cpus()); + let (ceiling, cpus, disk_cfg) = (memory_ceiling(), vm_cpus(), vm_disk_gb_config()); self.ceiling.store(ceiling, std::sync::atomic::Ordering::Relaxed); self.cpus.store(cpus, std::sync::atomic::Ordering::Relaxed); let t0 = std::time::Instant::now(); @@ -1633,9 +1652,11 @@ impl Engine { console_log: crate::diag::console::path().ok(), memory_mib: Some(ceiling >> 20), cpus: Some(cpus), + disk_gb: disk_cfg, ..Default::default() }) .inspect_err(|e| crate::diag::error!("VM did not boot", error = e))?; + self.disk_gb.store(crate::guest::disk::current_gb(), std::sync::atomic::Ordering::Relaxed); let (vm, conn) = guest.into_parts(); let me = self.me.get().cloned().unwrap_or_default(); let vm = Arc::new(VmLink::new(vm, conn, move |ev| { @@ -2173,6 +2194,11 @@ impl Engine { self.cpus.load(std::sync::atomic::Ordering::Relaxed) } + /// Data disk capacity in GiB the VM has (or will boot with). + pub fn disk_gb(&self) -> u64 { + self.disk_gb.load(std::sync::atomic::Ordering::Relaxed) + } + /// The Mac folders and files that running containers bind-mount, as /// the Mac keeps them (the guest sees them under /mnt/mac). #[cfg(target_os = "macos")] diff --git a/crates/kiri/src/guest.rs b/crates/kiri/src/guest.rs index d83bfbaf2..240466869 100644 --- a/crates/kiri/src/guest.rs +++ b/crates/kiri/src/guest.rs @@ -12,6 +12,8 @@ use std::time::{Duration, Instant}; use kiri_proto::{HEADER, Hello, LayerBegin, Msg, Stream}; use kiri_vmm::{Config, Event, Vm}; +pub mod disk; + /// The virtiofs tag the guest mounts the Mac's folders under: `/mnt/mac`. pub const MAC_TAG: &str = "kiri-mac"; @@ -68,6 +70,9 @@ pub struct BootOptions { pub memory_mib: Option, /// The VM's CPUs; 2 if not set. pub cpus: Option, + /// The VM's persistent data disk size in GiB (`vm.json`'s `disk_gb`); + /// `KIRI_DISK_GB` overrides this when set. + pub disk_gb: Option, } fn console_output(opts: &BootOptions) -> io::Result> { @@ -181,7 +186,7 @@ impl Guest { cmdline, console: console_output(opts)?, agent_port: kiri_proto::HOST_PORT, - disk: if opts.data_disk { Some(data_disk(&dir)?) } else { None }, + disk: if opts.data_disk { Some(data_disk(&dir, opts.disk_gb)?) } else { None }, nat_mac: if opts.data_disk { Some(mac_address()?) } else { None }, // The Mac's folders a bind mount may name: /mnt/mac in the guest. share: opts.data_disk.then(mac_share), @@ -388,7 +393,8 @@ fn agent_binary() -> PathBuf { #[cfg(target_os = "macos")] /// The guest's data disk, copied from the empty template on first use. On /// APFS the copy is a clone: instant, and it takes no space until written. -fn data_disk(guest_dir: &std::path::Path) -> io::Result { +fn data_disk(guest_dir: &std::path::Path, configured_gb: Option) -> io::Result { + let requested = disk::requested_size(configured_gb)?; let vm = kiri_image::Store::default_root()?.join("vm"); std::fs::create_dir_all(&vm)?; let disk = vm.join("data.img"); @@ -416,6 +422,7 @@ fn data_disk(guest_dir: &std::path::Path) -> io::Result { } std::fs::rename(tmp, &disk)?; } + disk::grow(&disk, requested)?; Ok(disk) } diff --git a/crates/kiri/src/guest/disk.rs b/crates/kiri/src/guest/disk.rs new file mode 100644 index 000000000..5f9c77977 --- /dev/null +++ b/crates/kiri/src/guest/disk.rs @@ -0,0 +1,271 @@ +//! Grow the Mac's sparse backing file before attaching it to the VM. + +use std::fs::OpenOptions; +use std::io; +use std::path::{Path, PathBuf}; + +/// Default template data disk size in GiB (`cargo xtask disk` makes a 64 GiB +/// sparse ext4 template). +pub const DEFAULT_GB: u64 = 64; +/// Default upper bound for the Settings → Resources disk slider in GiB. +pub const MAX_UI_GB: u64 = 1024; +const GIB: u64 = 1 << 30; + +fn invalid_size() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + "KIRI_DISK_GB must be a positive whole number of GiB that fits the disk image", + ) +} + +/// Converts a positive GiB count to bytes, rejecting zero and values that +/// overflow `u64` or exceed `i64::MAX`. +pub fn size_bytes(gb: u64) -> io::Result { + if gb == 0 { + return Err(invalid_size()); + } + gb.checked_mul(GIB) + .filter(|&bytes| bytes <= i64::MAX as u64) + .ok_or_else(invalid_size) +} + +pub fn parse_size_gb(value: &str) -> io::Result { + let gb = value.parse::().map_err(|_| invalid_size())?; + size_bytes(gb)?; + Ok(gb) +} + +pub fn parse_size(value: &str) -> io::Result { + size_bytes(parse_size_gb(value)?) +} + +/// Resolves the requested disk size in bytes: `KIRI_DISK_GB` takes precedence +/// over a persistent `vm.json` `"disk_gb"` value. An invalid `KIRI_DISK_GB` +/// returns `InvalidInput` rather than silently falling back. +pub fn resolve_requested_size( + env_val: Option<&str>, + configured_gb: Option, +) -> io::Result> { + if let Some(value) = env_val { + return parse_size(value).map(Some); + } + configured_gb.map(size_bytes).transpose() +} + +/// Resolves the requested disk size from `KIRI_DISK_GB` in the process +/// environment, falling back to `configured_gb` from `vm.json`. +pub fn requested_size(configured_gb: Option) -> io::Result> { + let env_os = std::env::var_os("KIRI_DISK_GB"); + let env_str = env_os.as_ref().map(|v| v.to_str().unwrap_or_default()); + resolve_requested_size(env_str, configured_gb) +} + +/// Resolves the effective disk size in GiB for Settings and status reporting: +/// `KIRI_DISK_GB` (if valid), else `vm.json`'s `disk_gb` (if valid), else +/// `DEFAULT_GB`, and never smaller than the existing `data.img` (`current_gb`). +pub fn effective_gb(env_val: Option<&str>, configured_gb: Option, current_gb: u64) -> u64 { + let min_gb = current_gb.max(DEFAULT_GB); + let wanted = env_val + .and_then(|v| parse_size_gb(v).ok()) + .or_else(|| configured_gb.filter(|&gb| size_bytes(gb).is_ok())) + .unwrap_or(DEFAULT_GB); + wanted.max(min_gb) +} + +/// The path to the VM's data disk backing file (`/vm/data.img`). +pub fn data_disk_path() -> Option { + kiri_image::Store::default_root() + .ok() + .map(|root| root.join("vm/data.img")) +} + +/// Current size in GiB of an existing backing file, or `DEFAULT_GB` when the +/// file does not exist yet or is smaller than the template size. +pub fn current_gb_at(path: &Path) -> u64 { + std::fs::metadata(path) + .ok() + .map(|m| m.len().div_ceil(GIB)) + .unwrap_or(DEFAULT_GB) + .max(DEFAULT_GB) +} + +/// Current size in GiB of the default data disk file. +pub fn current_gb() -> u64 { + data_disk_path() + .map(|p| current_gb_at(&p)) + .unwrap_or(DEFAULT_GB) +} + +/// Allowed `(min_gb, max_gb)` range for Settings → Resources: never shrinks +/// below the current disk image size (or 64 GiB), and expands up to at least +/// `MAX_UI_GB` (1024 GiB). +pub fn ui_bounds(current_gb: u64, effective_gb: u64) -> (u64, u64) { + let min_gb = current_gb.max(DEFAULT_GB); + let max_gb = MAX_UI_GB.max(min_gb).max(effective_gb); + (min_gb, max_gb) +} + +/// Grows the sparse backing file to `requested` bytes if it is currently +/// smaller. Never shrinks an existing file. +pub fn grow(path: &Path, requested: Option) -> io::Result<()> { + let Some(bytes) = requested else { + return Ok(()); + }; + let file = OpenOptions::new().read(true).write(true).open(path)?; + if file.metadata()?.len() < bytes { + // Extending creates holes, rather than allocating the requested + // capacity. The agent grows ext4 after mounting it at the next boot. + file.set_len(bytes).map_err(|e| { + io::Error::new(e.kind(), format!("grow data disk {}: {e}", path.display())) + })?; + file.sync_all()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Read; + use std::os::unix::fs::MetadataExt; + + #[test] + fn sizes_are_gib_and_invalid_or_overflowing_values_are_rejected() { + assert_eq!(parse_size("64").unwrap(), 64 << 30); + assert_eq!(parse_size("128").unwrap(), 128 << 30); + assert_eq!(size_bytes(1024).unwrap(), 1024 << 30); + assert_eq!( + size_bytes(0).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + size_bytes(8_589_934_592).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + size_bytes(u64::MAX).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + for value in [ + "", + "0", + "-1", + "1.5", + "128GB", + "18446744073709551615", + "8589934592", + ] { + assert_eq!( + parse_size(value).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + "expected InvalidInput for {value:?}" + ); + } + } + + #[test] + fn env_precedence_over_vm_json_and_invalid_env_is_rejected() { + // KIRI_DISK_GB wins over vm.json. + assert_eq!( + resolve_requested_size(Some("256"), Some(128)).unwrap(), + Some(256 << 30) + ); + // Even a smaller KIRI_DISK_GB wins in resolution (grow() then refuses to shrink). + assert_eq!( + resolve_requested_size(Some("96"), Some(256)).unwrap(), + Some(96 << 30) + ); + // Without KIRI_DISK_GB, vm.json's disk_gb is used. + assert_eq!( + resolve_requested_size(None, Some(128)).unwrap(), + Some(128 << 30) + ); + // Neither set means keep template/current size. + assert_eq!(resolve_requested_size(None, None).unwrap(), None); + // Invalid KIRI_DISK_GB fails loudly rather than silently falling back to vm.json. + assert_eq!( + resolve_requested_size(Some("0"), Some(128)) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + resolve_requested_size(Some("128GB"), Some(128)) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + } + + #[test] + fn effective_size_and_ui_bounds_never_shrink() { + // Default 64 GiB when neither env nor vm.json is set. + assert_eq!(effective_gb(None, None, 64), 64); + assert_eq!(effective_gb(None, None, 32), 64); + // vm.json applies when larger than current. + assert_eq!(effective_gb(None, Some(128), 64), 128); + // Env overrides vm.json. + assert_eq!(effective_gb(Some("256"), Some(128), 64), 256); + // Lowering vm.json or env below current disk size never reports a smaller disk. + assert_eq!(effective_gb(None, Some(96), 128), 128); + assert_eq!(effective_gb(Some("64"), Some(96), 128), 128); + assert_eq!(effective_gb(Some("32"), None, 64), 64); + // Bounds never allow shrinking below current disk size or 64 GiB. + assert_eq!(ui_bounds(64, 64), (64, 1024)); + assert_eq!(ui_bounds(128, 256), (128, 1024)); + assert_eq!(ui_bounds(64, 2048), (64, 2048)); + assert_eq!(ui_bounds(1536, 1536), (1536, 1536)); + } + + #[test] + fn growth_preserves_data_and_holes_and_never_shrinks() { + let path = std::env::temp_dir().join(format!( + "kiri-disk-grow-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .unwrap(); + drop(file); + std::fs::write(&path, b"keep").unwrap(); + grow(&path, None).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 4); + // Below 64 GiB template floor still reports 64 GiB for UI. + assert_eq!(current_gb_at(&path), 64); + + grow(&path, Some(128 << 20)).unwrap(); + grow(&path, Some(64 << 20)).unwrap(); + grow(&path, None).unwrap(); + let metadata = std::fs::metadata(&path).unwrap(); + assert_eq!(metadata.len(), 128 << 20); + assert!(metadata.blocks() * 512 < 1 << 20); + let mut contents = [0; 8]; + std::fs::File::open(&path) + .unwrap() + .read_exact(&mut contents) + .unwrap(); + assert_eq!(&contents, b"keep\0\0\0\0"); + + // Sparse growth to 128 GiB keeps existing bytes, stays sparse, and reports 128 GiB. + grow(&path, Some(128 << 30)).unwrap(); + grow(&path, Some(64 << 30)).unwrap(); + let big = std::fs::metadata(&path).unwrap(); + assert_eq!(big.len(), 128 << 30); + assert!(big.blocks() * 512 < 1 << 20); + assert_eq!(current_gb_at(&path), 128); + let mut head = [0; 4]; + std::fs::File::open(&path) + .unwrap() + .read_exact(&mut head) + .unwrap(); + assert_eq!(&head, b"keep"); + + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index c689677fc..268b83335 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4409,6 +4409,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

/* Settings → Resources: the most the Linux VM may use. */ const gb = (mib) => `${Math.round(mib / 1024)} GB`; +const diskGb = (g) => `${g} GB`; const cpuText = (n) => trn(n, "{n} CPU", "{n} CPUs"); /* How far along its track a slider's blue fill reaches, as CSS: to the middle of the thumb, which travels the track less its own 26 px. */ @@ -4416,7 +4417,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const f = max > min ? (v - min) / (max - min) : 0; return `calc(13px + (100% - 26px) * ${f.toFixed(4)})`; }; -const resChanged = () => ui.res && (ui.resDraft.cpus !== ui.res.cpus || ui.resDraft.memory_mib !== ui.res.memory_mib); +const resChanged = () => ui.res && (ui.resDraft.cpus !== ui.res.cpus || ui.resDraft.memory_mib !== ui.res.memory_mib || (ui.res.disk_gb != null && ui.resDraft.disk_gb !== ui.res.disk_gb)); /* Settings › Resources: the engine's on/off, the same switch as the card. */ function enginePane() { const { shown } = engineShown(), off = shown === "stopped"; @@ -4436,14 +4437,21 @@

${tr("Use {app} for docker?", { app: esc(app) })}

if (r.error) return `

${tr("Resources")}

${tr("Start Kiri to change its resources. ({error})", { error: esc(r.error) })}

`; const d = ui.resDraft; const maxGb = Math.max(1, Math.floor(r.max_memory_mib / 1024)); - const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64); + const hasDisk = r.disk_gb != null; + const minDisk = r.min_disk_gb ?? 64; + const maxDisk = Math.max(minDisk, r.max_disk_gb ?? 1024); + const diskVal = hasDisk ? Math.min(Math.max(d.disk_gb ?? r.disk_gb, minDisk), maxDisk) : minDisk; + const diskStep = minDisk % 8 === 0 && diskVal % 8 === 0 && maxDisk % 8 === 0 ? 8 : 1; + const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64 || (hasDisk && r.running_disk_gb != null && r.running_disk_gb !== r.disk_gb)); return `

${tr("Resources")}

${tr("CPUs")}${tr("Shared with {os}: the VM only uses them while containers are busy.", { os: OS })}
${cpuText(d.cpus)}
${tr("Memory")}${tr("The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.", { os: OS })}
${gb(d.memory_mib)}
- ${r.overridden ? `

${tr("KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.")}

` : ""} -
${r.awake ? tr("Running now with {cpus} and up to {mem}.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib) }) : tr("The VM is asleep; it starts with these next time.")} + ${hasDisk ? `
${tr("Disk image size")}${tr("The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.", { os: OS })} +
${diskGb(diskVal)}
` : ""} + ${r.overridden ? `

${hasDisk ? tr("KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.") : tr("KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.")}

` : ""} +
${r.awake ? (hasDisk ? tr("Running now with {cpus}, up to {mem}, and a {disk} disk.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib), disk: diskGb(r.running_disk_gb ?? r.disk_gb) }) : tr("Running now with {cpus} and up to {mem}.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib) })) : tr("The VM is asleep; it starts with these next time.")} ${pending ? `` : ""}
@@ -4564,10 +4572,11 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const go = document.querySelector("#content [data-impgo]"), n = importCount(); if (go) { go.disabled = !n; go.textContent = n ? trn(n, "Import {n} item", "Import {n} items") : tr("Import"); } })); - for (const id of ["res-cpus", "res-mem"]) $(id)?.addEventListener("input", (ev) => { - ui.resDraft[id === "res-cpus" ? "cpus" : "memory_mib"] = +ev.target.value; - ev.target.style.setProperty("--fill", rangeFill(+ev.target.value, +ev.target.min, +ev.target.max)); - $(`${id}-v`).textContent = id === "res-cpus" ? cpuText(+ev.target.value) : gb(+ev.target.value); + for (const id of ["res-cpus", "res-mem", "res-disk"]) $(id)?.addEventListener("input", (ev) => { + const v = +ev.target.value; + ui.resDraft[id === "res-cpus" ? "cpus" : id === "res-mem" ? "memory_mib" : "disk_gb"] = v; + ev.target.style.setProperty("--fill", rangeFill(v, +ev.target.min, +ev.target.max)); + $(`${id}-v`).textContent = id === "res-cpus" ? cpuText(v) : id === "res-mem" ? gb(v) : diskGb(v); $("res-save").disabled = !resChanged(); }); $("pref-font")?.addEventListener("change", (ev) => setPref("font", ev.target.value)); @@ -8211,7 +8220,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (ui.view === "settings") render(); break; } - case "resources": ui.res = e; ui.resDraft = { cpus: e.cpus, memory_mib: e.memory_mib }; if (ui.view === "settings") render(); break; + case "resources": ui.res = e; ui.resDraft = { cpus: e.cpus, memory_mib: e.memory_mib, ...(e.disk_gb != null ? { disk_gb: e.disk_gb } : {}) }; if (ui.view === "settings") render(); break; case "detail": openDetail(e.id); break; case "inspect": if (ui.detail?.id === e.id) { diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index 9612a0a4b..8c755365d 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1850,5 +1850,9 @@ "Continue anyway": "ቢሆንም ቀጥል", "One step didn't work. Everything else is ready.": "አንድ ደረጃ አልሠራም። ሌላው ሁሉ ዝግጁ ነው።", "Some steps didn't work. Everything else is ready.": "አንዳንድ ደረጃዎች አልሠሩም። ሌላው ሁሉ ዝግጁ ነው።", - "No matches": "ምንም የሚዛመድ የለም" + "No matches": "ምንም የሚዛመድ የለም", + "Disk image size": "የዲስክ ምስል መጠን", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS፣ KIRI_MEMORY_MIB ወይም KIRI_DISK_GB ለዴሞኑ ተቀናብሯል፣ ከእነዚህም ቅድሚያ ይወስዳል።", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "አሁን በ{cpus}፣ እስከ {mem} እና በ{disk} ዲስክ እየሠራ ነው።", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፤ በፍጹም አይቀንስም። ዳግም ሲጀመር ተግባራዊ ይሆናል።" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index 9153eabc6..daf85bb92 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1850,5 +1850,9 @@ "Continue anyway": "المتابعة على أي حال", "One step didn't work. Everything else is ready.": "لم تنجح خطوة واحدة. كل شيء آخر جاهز.", "Some steps didn't work. Everything else is ready.": "لم تنجح بعض الخطوات. كل شيء آخر جاهز.", - "No matches": "لا توجد نتائج مطابقة" + "No matches": "لا توجد نتائج مطابقة", + "Disk image size": "حجم صورة القرص", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "المتغير KIRI_CPUS أو KIRI_MEMORY_MIB أو KIRI_DISK_GB معيّن للخدمة الخلفية، وله الأولوية على هذه الإعدادات.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "يعمل الآن بـ {cpus} وبحد أقصى {mem} وقرص بحجم {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ولا يتقلص الحجم أبداً. يُطبّق عند إعادة التشغيل." } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 99df96c46..5489196e5 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Продължи въпреки това", "One step didn't work. Everything else is ready.": "Една стъпка не се получи. Всичко останало е готово.", "Some steps didn't work. Everything else is ready.": "Някои стъпки не се получиха. Всичко останало е готово.", - "No matches": "Няма съвпадения" + "No matches": "Няма съвпадения", + "Disk image size": "Размер на дисковия образ", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "За демона е зададена KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB и тя има предимство пред тези настройки.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Работи в момента с {cpus}, до {mem} и диск {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни; размерът никога не се свива. Прилага се при рестартиране." } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index d4e29e031..4b39fca4f 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1850,5 +1850,9 @@ "Continue anyway": "তবুও চালিয়ে যান", "One step didn't work. Everything else is ready.": "একটি ধাপ কাজ করেনি। বাকি সব প্রস্তুত।", "Some steps didn't work. Everything else is ready.": "কিছু ধাপ কাজ করেনি। বাকি সব প্রস্তুত।", - "No matches": "কোনো মিল নেই" + "No matches": "কোনো মিল নেই", + "Disk image size": "ডিস্ক ইমেজের আকার", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "ডেমনের জন্য KIRI_CPUS, KIRI_MEMORY_MIB বা KIRI_DISK_GB সেট করা আছে, এবং সেগুলো এগুলোর চেয়ে অগ্রাধিকার পায়।", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "এখন {cpus}, সর্বোচ্চ {mem} ও {disk} ডিস্ক নিয়ে চলছে।", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়; এটি কখনো ছোট হয় না। রিস্টার্ট করলে প্রয়োগ হয়।" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 28b5ac537..161819362 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continua igualment", "One step didn't work. Everything else is ready.": "Un pas no ha funcionat. Tota la resta està a punt.", "Some steps didn't work. Everything else is ready.": "Alguns passos no han funcionat. Tota la resta està a punt.", - "No matches": "Cap coincidència" + "No matches": "Cap coincidència", + "Disk image size": "Mida de la imatge de disc", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB estan definits per al dimoni i tenen prioritat sobre aquests valors.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ara s'executa amb {cpus}, fins a {mem} i un disc de {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades; no s'encongeix mai. S'aplica en reiniciar." } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index ce51e2b24..2678ad1e9 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1850,5 +1850,9 @@ "Continue anyway": "هەر بەردەوام بە", "One step didn't work. Everything else is ready.": "یەک هەنگاو سەرکەوتوو نەبوو. هەموو شتێکی تر ئامادەیە.", "Some steps didn't work. Everything else is ready.": "هەندێک هەنگاو سەرکەوتوو نەبوون. هەموو شتێکی تر ئامادەیە.", - "No matches": "هیچ شتێکی هاوتا نییە" + "No matches": "هیچ شتێکی هاوتا نییە", + "Disk image size": "قەبارەی وێنەی دیسک", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یان KIRI_DISK_GB بۆ daemon دانراوە، و لەسەر ئەمانە پێشەنگی هەیە.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ئێستا بە {cpus}، تا {mem} و دیسکی {disk} کاردەکات.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت؛ هەرگیز بچووک نابێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت." } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index a7d9ec6b4..8ba15be48 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Přesto pokračovat", "One step didn't work. Everything else is ready.": "Jeden krok se nezdařil. Vše ostatní je připraveno.", "Some steps didn't work. Everything else is ready.": "Některé kroky se nezdařily. Vše ostatní je připraveno.", - "No matches": "Žádné shody" + "No matches": "Žádné shody", + "Disk image size": "Velikost obrazu disku", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Pro démona je nastaveno KIRI_CPUS, KIRI_MEMORY_MIB nebo KIRI_DISK_GB a to má přednost před těmito hodnotami.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Teď běží s {cpus}, až {mem} a diskem {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat; nikdy se nezmenšuje. Použije se po restartu." } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index 4342400d1..3f776c0e6 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Trotzdem fortfahren", "One step didn't work. Everything else is ready.": "Ein Schritt hat nicht geklappt. Alles andere ist bereit.", "Some steps didn't work. Everything else is ready.": "Einige Schritte haben nicht geklappt. Alles andere ist bereit.", - "No matches": "Keine Treffer" + "No matches": "Keine Treffer", + "Disk image size": "Größe des Festplattenimages", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB oder KIRI_DISK_GB ist für den Daemon gesetzt und hat Vorrang vor diesen Werten.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Läuft jetzt mit {cpus}, bis zu {mem} und einer {disk}-Festplatte.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt; die Größe schrumpft nie. Gilt nach einem Neustart." } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 0c09dc37d..76444feab 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Συνέχεια παρ' όλα αυτά", "One step didn't work. Everything else is ready.": "Ένα βήμα δεν πέτυχε. Όλα τα υπόλοιπα είναι έτοιμα.", "Some steps didn't work. Everything else is ready.": "Ορισμένα βήματα δεν πέτυχαν. Όλα τα υπόλοιπα είναι έτοιμα.", - "No matches": "Δεν βρέθηκαν αντιστοιχίες" + "No matches": "Δεν βρέθηκαν αντιστοιχίες", + "Disk image size": "Μέγεθος εικόνας δίσκου", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Το KIRI_CPUS, το KIRI_MEMORY_MIB ή το KIRI_DISK_GB έχει οριστεί για τον daemon και υπερισχύει αυτών.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Εκτελείται τώρα με {cpus}, έως {mem} και δίσκο {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα και δεν μικραίνει ποτέ. Εφαρμόζεται κατά την επανεκκίνηση." } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index 238e86c82..e14b30c9f 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continuar de todos modos", "One step didn't work. Everything else is ready.": "Un paso no funcionó. Todo lo demás está listo.", "Some steps didn't work. Everything else is ready.": "Algunos pasos no funcionaron. Todo lo demás está listo.", - "No matches": "Sin coincidencias" + "No matches": "Sin coincidencias", + "Disk image size": "Tamaño de la imagen de disco", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB está definida para el daemon y tiene prioridad sobre estos valores.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marcha ahora con {cpus}, hasta {mem} y un disco de {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos; nunca se reduce. Se aplica al reiniciar." } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index a612d5baf..b6fb2721a 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1850,5 +1850,9 @@ "Continue anyway": "به هر حال ادامه بده", "One step didn't work. Everything else is ready.": "یک مرحله انجام نشد. بقیه چیزها آماده است.", "Some steps didn't work. Everything else is ready.": "چند مرحله انجام نشد. بقیه چیزها آماده است.", - "No matches": "موردی پیدا نشد" + "No matches": "موردی پیدا نشد", + "Disk image size": "اندازهٔ تصویر دیسک", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یا KIRI_DISK_GB برای سرویس پس‌زمینه تنظیم شده و بر این تنظیمات اولویت دارد.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "اکنون با {cpus}، حداکثر {mem} و دیسک {disk} در حال اجراست.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و هرگز کوچک نمی‌شود. پس از راه‌اندازی مجدد اعمال می‌شود." } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index 5c7d2506d..971ee5bc6 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Jatka silti", "One step didn't work. Everything else is ready.": "Yksi vaihe ei onnistunut. Kaikki muu on valmista.", "Some steps didn't work. Everything else is ready.": "Jotkin vaiheet eivät onnistuneet. Kaikki muu on valmista.", - "No matches": "Ei osumia" + "No matches": "Ei osumia", + "Disk image size": "Levykuvan koko", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemonille on asetettu KIRI_CPUS, KIRI_MEMORY_MIB tai KIRI_DISK_GB, ja ne menevät näiden edelle.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Käynnissä nyt: {cpus}, muistia enintään {mem}, levy {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, eikä levy koskaan pienene. Tulee voimaan uudelleenkäynnistyksessä." } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 4869d8e2e..00e68ae37 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continuer quand même", "One step didn't work. Everything else is ready.": "Une étape a échoué. Tout le reste est prêt.", "Some steps didn't work. Everything else is ready.": "Certaines étapes ont échoué. Tout le reste est prêt.", - "No matches": "Aucun résultat" + "No matches": "Aucun résultat", + "Disk image size": "Taille de l’image disque", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB est défini pour le démon et prime sur ces réglages.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marche avec {cpus}, jusqu’à {mem} et un disque de {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites ; il ne rétrécit jamais. Appliqué au redémarrage." } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index ee7182fbc..895c98f7f 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1850,5 +1850,9 @@ "Continue anyway": "फिर भी जारी रखें", "One step didn't work. Everything else is ready.": "एक चरण काम नहीं किया। बाकी सब तैयार है।", "Some steps didn't work. Everything else is ready.": "कुछ चरण काम नहीं किए। बाकी सब तैयार है।", - "No matches": "कोई मेल नहीं" + "No matches": "कोई मेल नहीं", + "Disk image size": "डिस्क इमेज का आकार", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "डेमन के लिए KIRI_CPUS, KIRI_MEMORY_MIB या KIRI_DISK_GB सेट है, और वह इनसे ऊपर लागू होता है।", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "अभी {cpus}, अधिकतम {mem} और {disk} डिस्क के साथ चल रहा है।", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है; यह कभी छोटा नहीं होता। रीस्टार्ट पर लागू होता है।" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 3f03d21e7..89aa37ac9 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Folytatás mindenképp", "One step didn't work. Everything else is ready.": "Egy lépés nem sikerült. Minden más készen áll.", "Some steps didn't work. Everything else is ready.": "Néhány lépés nem sikerült. Minden más készen áll.", - "No matches": "Nincs találat" + "No matches": "Nincs találat", + "Disk image size": "Lemezkép mérete", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "A démonnál be van állítva a KIRI_CPUS, a KIRI_MEMORY_MIB vagy a KIRI_DISK_GB, és ez felülírja ezeket.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Most így fut: {cpus}, legfeljebb {mem} memória és {disk} lemez.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), és soha nem zsugorodik. Újraindításkor lép életbe." } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 036490383..19bc9a27d 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Tetap lanjutkan", "One step didn't work. Everything else is ready.": "Satu langkah tidak berhasil. Yang lainnya sudah siap.", "Some steps didn't work. Everything else is ready.": "Beberapa langkah tidak berhasil. Yang lainnya sudah siap.", - "No matches": "Tidak ada yang cocok" + "No matches": "Tidak ada yang cocok", + "Disk image size": "Ukuran image disk", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB, atau KIRI_DISK_GB diatur untuk daemon, dan lebih diutamakan daripada pengaturan ini.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Berjalan sekarang dengan {cpus}, hingga {mem}, dan disk {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis; ukurannya tidak pernah menyusut. Berlaku setelah mulai ulang." } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 7592c2404..a5309eca9 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continua comunque", "One step didn't work. Everything else is ready.": "Un passaggio non ha funzionato. Tutto il resto è pronto.", "Some steps didn't work. Everything else is ready.": "Alcuni passaggi non hanno funzionato. Tutto il resto è pronto.", - "No matches": "Nessuna corrispondenza" + "No matches": "Nessuna corrispondenza", + "Disk image size": "Dimensione immagine disco", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB è impostata per il daemon e ha la precedenza su questi valori.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ora in esecuzione con {cpus}, fino a {mem} e un disco da {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati; non si riduce mai. Si applica al riavvio." } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index 018621ca4..2aac13bda 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1850,5 +1850,9 @@ "Continue anyway": "このまま続ける", "One step didn't work. Everything else is ready.": "1 つの手順がうまくいきませんでした。ほかはすべて準備できています。", "Some steps didn't work. Everything else is ready.": "いくつかの手順がうまくいきませんでした。ほかはすべて準備できています。", - "No matches": "一致するものはありません" + "No matches": "一致するものはありません", + "Disk image size": "ディスクイメージのサイズ", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "デーモンに KIRI_CPUS、KIRI_MEMORY_MIB、または KIRI_DISK_GB が設定されており、こちらの設定より優先されます。", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "現在 {cpus}、最大 {mem}、{disk} ディスクで実行中です。", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、縮小することはありません。再起動時に適用されます。" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 01bb377a1..e6f0e0aea 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Бәрібір жалғастыру", "One step didn't work. Everything else is ready.": "Бір қадам орындалмады. Қалғанының бәрі дайын.", "Some steps didn't work. Everything else is ready.": "Кейбір қадамдар орындалмады. Қалғанының бәрі дайын.", - "No matches": "Сәйкестік жоқ" + "No matches": "Сәйкестік жоқ", + "Disk image size": "Диск кескінінің өлшемі", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Демон үшін KIRI_CPUS, KIRI_MEMORY_MIB немесе KIRI_DISK_GB орнатылған және ол осы баптаулардан басым.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Қазір {cpus}, {mem} дейінгі жад және {disk} дискімен жұмыс істеп тұр.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады; ол ешқашан кішіреймейді. Қайта іске қосқанда қолданылады." } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index dfef26d9c..5b28b139c 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1850,5 +1850,9 @@ "Continue anyway": "그래도 계속", "One step didn't work. Everything else is ready.": "한 단계가 실패했습니다. 나머지는 모두 준비되었습니다.", "Some steps didn't work. Everything else is ready.": "일부 단계가 실패했습니다. 나머지는 모두 준비되었습니다.", - "No matches": "일치하는 항목 없음" + "No matches": "일치하는 항목 없음", + "Disk image size": "디스크 이미지 크기", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "데몬에 KIRI_CPUS, KIRI_MEMORY_MIB 또는 KIRI_DISK_GB가 설정되어 있어 이 값보다 우선합니다.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "지금 {cpus}, 최대 {mem}, {disk} 디스크로 실행 중입니다.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며 줄어들지 않습니다. 재시작 시 적용됩니다." } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 8d934cbeb..965b6e55c 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1850,5 +1850,9 @@ "Continue anyway": "ສືບຕໍ່ຕໍ່ໄປ", "One step didn't work. Everything else is ready.": "ມີ 1 ຂັ້ນຕອນບໍ່ສຳເລັດ. ສ່ວນອື່ນພ້ອມທັງໝົດ.", "Some steps didn't work. Everything else is ready.": "ບາງຂັ້ນຕອນບໍ່ສຳເລັດ. ສ່ວນອື່ນພ້ອມທັງໝົດ.", - "No matches": "ບໍ່ມີລາຍການທີ່ກົງກັນ" + "No matches": "ບໍ່ມີລາຍການທີ່ກົງກັນ", + "Disk image size": "ຂະໜາດອິມເມຈດິສກ໌", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ຫຼື KIRI_DISK_GB ຖືກຕັ້ງໄວ້ສຳລັບ daemon, ແລະ ມັນມີຜົນເໜືອກວ່າຄ່າເຫຼົ່ານີ້.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ຕອນນີ້ແລ່ນດ້ວຍ {cpus}, ສູງສຸດ {mem} ແລະ ດິສກ໌ {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ບໍ່ເຄີຍຫົດລົງ. ມີຜົນເມື່ອເລີ່ມໃໝ່." } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 57d13b362..8a5628a7e 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Vis tiek tęsti", "One step didn't work. Everything else is ready.": "Vienas veiksmas nepavyko. Visa kita paruošta.", "Some steps didn't work. Everything else is ready.": "Keli veiksmai nepavyko. Visa kita paruošta.", - "No matches": "Atitikmenų nėra" + "No matches": "Atitikmenų nėra", + "Disk image size": "Disko atvaizdo dydis", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Tarnybai nustatytas KIRI_CPUS, KIRI_MEMORY_MIB arba KIRI_DISK_GB, ir jie turi pirmenybę prieš šiuos nustatymus.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Dabar veikia su {cpus}, iki {mem} ir {disk} disku.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis; diskas niekada nesumažėja. Pritaikoma paleidus iš naujo." } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 317f30819..b97f466d0 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Fortsett likevel", "One step didn't work. Everything else is ready.": "Ett trinn fungerte ikke. Alt annet er klart.", "Some steps didn't work. Everything else is ready.": "Noen trinn fungerte ikke. Alt annet er klart.", - "No matches": "Ingen treff" + "No matches": "Ingen treff", + "Disk image size": "Størrelse på diskbilde", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB eller KIRI_DISK_GB er satt for daemonen og har forrang foran disse.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Kjører nå med {cpus}, opptil {mem} og en disk på {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives; den krymper aldri. Gjelder ved omstart." } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index ec8d6e43c..12f7f02f9 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Mimo to kontynuuj", "One step didn't work. Everything else is ready.": "Jeden krok się nie powiódł. Wszystko inne jest gotowe.", "Some steps didn't work. Everything else is ready.": "Niektóre kroki się nie powiodły. Wszystko inne jest gotowe.", - "No matches": "Brak wyników" + "No matches": "Brak wyników", + "Disk image size": "Rozmiar obrazu dysku", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Dla demona ustawiono KIRI_CPUS, KIRI_MEMORY_MIB lub KIRI_DISK_GB i to one mają pierwszeństwo przed tymi ustawieniami.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Działa teraz z {cpus}, maks. {mem} i dyskiem {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych; dysk nigdy się nie zmniejsza. Działa po restarcie." } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 4572d032a..36d4438e2 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continuar mesmo assim", "One step didn't work. Everything else is ready.": "Uma etapa não funcionou. Todo o resto está pronto.", "Some steps didn't work. Everything else is ready.": "Algumas etapas não funcionaram. Todo o resto está pronto.", - "No matches": "Nenhum resultado" + "No matches": "Nenhum resultado", + "Disk image size": "Tamanho da imagem de disco", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB está definido para o daemon e tem prioridade sobre estes.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rodando agora com {cpus}, até {mem} e disco de {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados; ele nunca encolhe. Aplica ao reiniciar." } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index 88df324c6..679d9774a 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Continuă oricum", "One step didn't work. Everything else is ready.": "Un pas nu a funcționat. Restul este gata.", "Some steps didn't work. Everything else is ready.": "Unii pași nu au funcționat. Restul este gata.", - "No matches": "Nicio potrivire" + "No matches": "Nicio potrivire", + "Disk image size": "Dimensiunea imaginii de disc", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB sau KIRI_DISK_GB este setat pentru daemon și are prioritate față de acestea.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rulează acum cu {cpus}, până la {mem} și un disc de {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date; nu se micșorează niciodată. Se aplică la repornire." } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index fd4bf3a22..a9573154b 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Всё равно продолжить", "One step didn't work. Everything else is ready.": "Один шаг не удался. Всё остальное готово.", "Some steps didn't work. Everything else is ready.": "Некоторые шаги не удались. Всё остальное готово.", - "No matches": "Совпадений нет" + "No matches": "Совпадений нет", + "Disk image size": "Размер образа диска", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задана переменная KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB, и она имеет приоритет над этими настройками.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Сейчас работает с {cpus}, до {mem} памяти и диском {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных; размер никогда не уменьшается. Применяется после перезапуска." } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index 79c947b88..b6157329d 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Vseeno nadaljuj", "One step didn't work. Everything else is ready.": "En korak ni uspel. Vse drugo je pripravljeno.", "Some steps didn't work. Everything else is ready.": "Nekateri koraki niso uspeli. Vse drugo je pripravljeno.", - "No matches": "Ni zadetkov" + "No matches": "Ni zadetkov", + "Disk image size": "Velikost slike diska", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Za demon je nastavljen KIRI_CPUS, KIRI_MEMORY_MIB ali KIRI_DISK_GB, ki ima prednost pred temi nastavitvami.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Zdaj teče s {cpus}, največ {mem} in diskom {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov; disk se nikoli ne skrči. Uveljavi se ob ponovnem zagonu." } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 2ebf5b493..c92d55777 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Vazhdo prapë", "One step didn't work. Everything else is ready.": "Një hap nuk funksionoi. Gjithçka tjetër është gati.", "Some steps didn't work. Everything else is ready.": "Disa hapa nuk funksionuan. Gjithçka tjetër është gati.", - "No matches": "Asnjë përputhje" + "No matches": "Asnjë përputhje", + "Disk image size": "Madhësia e imazhit të diskut", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ose KIRI_DISK_GB është vendosur për daemon-in dhe ka përparësi ndaj këtyre.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Tani në punë me {cpus}, deri në {mem} dhe disk {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna; nuk tkurret kurrë. Zbatohet pas rinisjes." } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index 1c5a3614d..d97b4e57c 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1850,5 +1850,9 @@ "Continue anyway": "இருந்தாலும் தொடர்", "One step didn't work. Everything else is ready.": "ஒரு படி வேலை செய்யவில்லை. மற்ற அனைத்தும் தயார்.", "Some steps didn't work. Everything else is ready.": "சில படிகள் வேலை செய்யவில்லை. மற்ற அனைத்தும் தயார்.", - "No matches": "பொருத்தம் இல்லை" + "No matches": "பொருத்தம் இல்லை", + "Disk image size": "வட்டுப் பட அளவு", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "டீமனுக்கு KIRI_CPUS, KIRI_MEMORY_MIB அல்லது KIRI_DISK_GB அமைக்கப்பட்டுள்ளது, அது இவற்றை விட முன்னுரிமை பெறும்.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "இப்போது {cpus}, அதிகபட்சம் {mem} மற்றும் {disk} வட்டுடன் இயங்குகிறது.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; இது ஒருபோதும் சுருங்காது. மறுதொடக்கத்தில் நடைமுறைக்கு வரும்." } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 013f61bf5..8a39cafe0 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1850,5 +1850,9 @@ "Continue anyway": "ఏదేమైనా కొనసాగించు", "One step didn't work. Everything else is ready.": "ఒక దశ పని చేయలేదు. మిగతావన్నీ సిద్ధంగా ఉన్నాయి.", "Some steps didn't work. Everything else is ready.": "కొన్ని దశలు పని చేయలేదు. మిగతావన్నీ సిద్ధంగా ఉన్నాయి.", - "No matches": "సరిపోలికలు లేవు" + "No matches": "సరిపోలికలు లేవు", + "Disk image size": "డిస్క్ ఇమేజ్ పరిమాణం", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "డెమన్‌కు KIRI_CPUS, KIRI_MEMORY_MIB లేదా KIRI_DISK_GB సెట్ చేయబడింది, అది వీటి కంటే ప్రాధాన్యం పొందుతుంది.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ఇప్పుడు {cpus}, గరిష్టంగా {mem}, {disk} డిస్క్‌తో రన్ అవుతోంది.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది; ఇది ఎప్పుడూ తగ్గదు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది." } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index 933ea6907..4bd17630a 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1850,5 +1850,9 @@ "Continue anyway": "ดำเนินการต่อ", "One step didn't work. Everything else is ready.": "ขั้นตอนหนึ่งไม่สำเร็จ ส่วนอื่นพร้อมทั้งหมด", "Some steps didn't work. Everything else is ready.": "บางขั้นตอนไม่สำเร็จ ส่วนอื่นพร้อมทั้งหมด", - "No matches": "ไม่พบรายการที่ตรงกัน" + "No matches": "ไม่พบรายการที่ตรงกัน", + "Disk image size": "ขนาดอิมเมจดิสก์", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "มีการตั้งค่า KIRI_CPUS, KIRI_MEMORY_MIB หรือ KIRI_DISK_GB ให้ daemon ซึ่งมีลำดับความสำคัญเหนือค่าเหล่านี้", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ขณะนี้ทำงานด้วย {cpus} สูงสุด {mem} และดิสก์ {disk}", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และจะไม่หดเล็กลง มีผลเมื่อรีสตาร์ท" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index 9ac0a2679..cc57defb3 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Yine de devam et", "One step didn't work. Everything else is ready.": "Bir adım çalışmadı. Geri kalan her şey hazır.", "Some steps didn't work. Everything else is ready.": "Bazı adımlar çalışmadı. Geri kalan her şey hazır.", - "No matches": "Eşleşme yok" + "No matches": "Eşleşme yok", + "Disk image size": "Disk görüntüsü boyutu", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_CPUS, KIRI_MEMORY_MIB veya KIRI_DISK_GB ayarlı ve bunlar buradakilerden önceliklidir.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Şu anda {cpus}, en fazla {mem} ve {disk} disk ile çalışıyor.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; asla küçülmez. Yeniden başlatmada uygulanır." } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index ce04078b4..69ac6806c 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Усе одно продовжити", "One step didn't work. Everything else is ready.": "Один крок не вдався. Усе інше готове.", "Some steps didn't work. Everything else is ready.": "Деякі кроки не вдалися. Усе інше готове.", - "No matches": "Збігів немає" + "No matches": "Збігів немає", + "Disk image size": "Розмір образу диска", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задано змінну KIRI_CPUS, KIRI_MEMORY_MIB або KIRI_DISK_GB, і вона має пріоритет над цими налаштуваннями.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Зараз працює з {cpus}, до {mem} пам’яті та диском {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних; розмір ніколи не зменшується. Застосовується після перезапуску." } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index a948012c9..98baabfee 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1850,5 +1850,9 @@ "Continue anyway": "Vẫn tiếp tục", "One step didn't work. Everything else is ready.": "Một bước không thành công. Mọi thứ khác đã sẵn sàng.", "Some steps didn't work. Everything else is ready.": "Một số bước không thành công. Mọi thứ khác đã sẵn sàng.", - "No matches": "Không có kết quả phù hợp" + "No matches": "Không có kết quả phù hợp", + "Disk image size": "Kích thước ảnh đĩa", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB hoặc KIRI_DISK_GB đã được đặt cho daemon và được ưu tiên hơn các thiết lập này.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Đang chạy với {cpus}, tối đa {mem} và đĩa {disk}.", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu; đĩa không bao giờ thu nhỏ. Áp dụng khi khởi động lại." } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 58e9dc6dc..221e0981f 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1850,5 +1850,9 @@ "Continue anyway": "仍然继续", "One step didn't work. Everything else is ready.": "有一个步骤未成功,其余均已就绪。", "Some steps didn't work. Everything else is ready.": "有些步骤未成功,其余均已就绪。", - "No matches": "没有匹配项" + "No matches": "没有匹配项", + "Disk image size": "磁盘镜像大小", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "守护进程设置了 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其优先级高于这里的设置。", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "当前运行使用 {cpus}、内存最多 {mem}、{disk} 磁盘。", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,且永不缩小。重启后生效。" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 1d388493d..fc3514a00 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1850,5 +1850,9 @@ "Continue anyway": "仍然繼續", "One step didn't work. Everything else is ready.": "有一個步驟未成功,其餘均已就緒。", "Some steps didn't work. Everything else is ready.": "有些步驟未成功,其餘均已就緒。", - "No matches": "沒有相符的項目" + "No matches": "沒有相符的項目", + "Disk image size": "磁碟映像大小", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "常駐程式已設定 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其優先順序高於這裡的設定。", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "目前以 {cpus}、記憶體最多 {mem} 與 {disk} 磁碟執行。", + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,且永不縮小。重新啟動後生效。" } diff --git a/docs/development.md b/docs/development.md index af10d0516..1a163e0ff 100644 --- a/docs/development.md +++ b/docs/development.md @@ -68,6 +68,20 @@ that boot their own guest are `kiri raw run|pull|images|rmi`. `kiri` keeps its data in `~/Library/Application Support/Kiri` (override with `KIRI_DATA_DIR`). It does not touch `/usr/local/bin/docker`. + +On macOS the VM starts with a sparse 64 GiB data disk. Change its size in +Settings → Resources (saved as `"disk_gb"` in `~/.kiri/vm.json`), or set +`KIRI_DISK_GB` for the daemon to override it on the next VM start, for example +`KIRI_DISK_GB=128 ./target/release/kiri daemon`. The backing file grows before +the VM opens it, and the guest grows ext4 online before starting containers. No +Homebrew tools are needed. Existing images and volumes are kept; lowering or +removing the setting never shrinks an existing disk. The extra capacity uses +space on the Mac only as it is written. Linux and WSL use their host's storage +instead of this disk image. + +`python3 tests/disk-grow.py` checks growth and data preservation across +restarts in a disposable VM, after building the host and guest above. + `/var/run/docker.sock` changes only when you ask: `kiri setup --docker-socket` (or the password prompt for `*.kiri.local` names) links it to Kiri's socket when no other engine has it, after macOS asks for an administrator password, diff --git a/docs/features.md b/docs/features.md index c20d09977..9fd93d1e7 100644 --- a/docs/features.md +++ b/docs/features.md @@ -123,8 +123,9 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr container has its own page with details, live logs (find, level filter), a command line (and "Open in Terminal" for a full shell) and its files (preview, Save to Downloads, Show in Finder); Settings for fonts, text - size, the VM's CPUs and memory (`~/.kiri/vm.json`, used from the VM's - next start; `KIRI_CPUS` and `KIRI_MEMORY_MIB` override it) and local names + size, the VM's CPUs, memory and disk image size (`~/.kiri/vm.json`, used from + the VM's next start; `KIRI_CPUS`, `KIRI_MEMORY_MIB` and `KIRI_DISK_GB` + override it; the disk grows online on boot and never shrinks) and local names - **Menu bar**: Kiri stays in the menu bar when its window closes, with the VM's state, running containers (click one to open it) and Start/Stop - **Kubernetes**: `kiri k8s start` — a single-node k3s cluster in one diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 866ce9632..0df082cf4 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 +### #384 macOS: configurable VM disk size with online ext4 growth (unreleased) +- Fixes: #384 macOS: VM data.img is fixed at 64 GiB with no disk size setting +- Caused: none known +- Caused by: - +- Check: `tests/disk-grow.py`, `tests/ui/resources-disk.js` + ### #487 Windows: opt-in file-change events for `C:\` bind mounts (unreleased) - Fixes: #487 Windows: file watchers in containers never hear of changes made on Windows to files in `C:\` bind mounts diff --git a/tests/disk-grow.py b/tests/disk-grow.py new file mode 100644 index 000000000..150b5e95e --- /dev/null +++ b/tests/disk-grow.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""VM disk growth on macOS, in a disposable daemon with its own data and state. + +cargo xtask host && cargo xtask guest +python3 tests/disk-grow.py [target/release/kiri] [--guest-dir guest/out] +""" +import argparse +import os +from pathlib import Path +import platform +import plistlib +import secrets +import shutil +import subprocess +import tempfile +import time + + +def main(): + if platform.system() != "Darwin": + print("SKIP VM disk growth: macOS only") + return + repo = Path(__file__).resolve().parent.parent + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", nargs="?", default=repo / "target/release/kiri", type=Path) + parser.add_argument("--guest-dir", default=repo / "guest/out", type=Path) + args = parser.parse_args() + feature = "disk" + secrets.token_hex(4) + state = Path.home() / (".kiri-" + feature) + assert not state.exists() + env = os.environ.copy() + for key in ["DOCKER_CONTEXT", "DOCKER_HOST", "KIRI_DISK_GB"]: + env.pop(key, None) + with tempfile.TemporaryDirectory(prefix="kiri-disk-", dir="/tmp") as directory: + work = Path(directory).resolve() + contents = work / "Kiri Disk.app/Contents" + (contents / "MacOS").mkdir(parents=True) + binary = contents / "MacOS/kiri" + shutil.copy2(args.binary.resolve(), binary) + (contents / "Info.plist").write_bytes(plistlib.dumps({ + "CFBundleIdentifier": "dev.kiri.app." + feature, + "CFBundleExecutable": "kiri", + })) + socket = work / "docker.sock" + env.update(KIRI_SOCKET=str(socket), KIRI_DATA_DIR=str(work / "data"), + KIRI_GUEST_DIR=str(args.guest_dir.resolve()), KIRI_NO_FINDER="1", + KIRI_IDLE_SECS="0", KIRI_MEMORY_MIB="1024") + proc = None + log = (work / "daemon.log").open("w+") + + def docker(*command): + return subprocess.run(["docker", "--host", "unix://" + str(socket), *command], + env=env, capture_output=True, text=True, check=True, + timeout=90).stdout.strip() + + def stop(): + nonlocal proc + if proc is not None: + proc.terminate() + try: + proc.wait(timeout=20) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + raise AssertionError("daemon did not stop cleanly") + proc = None + + def start(size): + nonlocal proc + settings = dict(env) + if size is not None: + settings["KIRI_DISK_GB"] = str(size) + proc = subprocess.Popen([str(binary), "daemon"], env=settings, stdout=log, stderr=log) + for _ in range(100): + assert proc.poll() is None, "daemon exited before becoming ready" + if socket.exists(): + try: + docker("info") + return + except subprocess.CalledProcessError: + pass + time.sleep(0.1) + raise AssertionError("daemon did not become ready") + + def volume(command): + return docker("run", "--rm", "-v", "disk-grow:/data", "alpine", "sh", "-c", command) + + def check_capacity(size, checksum): + assert volume("sha256sum /data/keep").split()[0] == checksum, "volume data changed" + blocks, block_size = map(int, volume("stat -f -c '%b %S' /data").split()) + actual = blocks * block_size + assert size * 0.9 * (1 << 30) < actual <= size * (1 << 30), actual + image = work / "data/vm/data.img" + info = image.stat() + assert info.st_size == size * (1 << 30), info.st_size + assert info.st_blocks * 512 < info.st_size // 8, "image is no longer sparse" + print(f"PASS {size} GiB image and filesystem; volume data preserved", flush=True) + + try: + start(None) + checksum = volume("dd if=/dev/urandom of=/data/keep bs=1048576 count=1 2>/dev/null; sha256sum /data/keep").split()[0] + check_capacity(64, checksum) + stop() + for setting in [128, 96, None]: + start(setting) + check_capacity(128, checksum) + stop() + print("PASS growth, smaller setting, and removed setting across VM restarts", flush=True) + # A fresh install must grow its copy of the template as well. + env["KIRI_DATA_DIR"] = str(work / "fresh") + start(128) + volume("echo fresh > /data/keep") + fresh = (work / "fresh/vm/data.img").stat() + blocks, block_size = map(int, volume("stat -f -c '%b %S' /data").split()) + assert fresh.st_size == 128 << 30 + assert blocks * block_size > 115 << 30 + print("PASS new disk starts at configured capacity", flush=True) + except Exception: + log.flush() + print((work / "daemon.log").read_text()) + raise + finally: + stop() + log.close() + if state.exists(): + shutil.rmtree(state) + + +if __name__ == "__main__": + main() diff --git a/tests/regressions.tsv b/tests/regressions.tsv index c7b63c401..348744553 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -277,3 +277,5 @@ hostnet-published-loopback #732 a port published on 127.0.0.1 was unreachable fr hostnet-published-every-address #732 the same for a port published on every address hostnet-dns-kiri #732 a --network host container asked the Mac's resolver for the VM network directly, with no fallback when it refused socket-container-uid-group #127 a standalone root-run Linux daemon put its 0600 socket under /root/.kiri/run/docker.sock instead of a 0660 /run/kiri/docker.sock, locking out containerized SDK clients whose numeric uid has no host account +tests/disk-grow.py #384 the macOS VM data disk stayed fixed at 64 GiB instead of growing via KIRI_DISK_GB / vm.json and online ext4 resize +tests/ui/resources-disk.js #384 Settings -> Resources had no Disk image size control for macOS VM disk growth without shrinking diff --git a/tests/ui/resources-disk.js b/tests/ui/resources-disk.js new file mode 100644 index 000000000..bf36b5fc6 --- /dev/null +++ b/tests/ui/resources-disk.js @@ -0,0 +1,96 @@ +// Settings -> Resources: Disk image size slider on macOS (bounds, save +// round-trip, pending restart notice) and clean omission when absent. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, what) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(`${what}: got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`); }; + +kiri.on({ + type: "resources", + cpus: 4, + memory_mib: 8192, + disk_gb: 128, + running_cpus: 4, + running_memory_mib: 8192, + running_disk_gb: 128, + awake: true, + max_cpus: 12, + max_memory_mib: 32768, + min_disk_gb: 128, + max_disk_gb: 1024, + overridden: false, +}); +prefs.tab = "resources"; +show("settings"); + +t("Disk slider renders beside tabs with current size as min (no shrink)", () => { + const tabs = document.querySelector(".settings .tabs").getBoundingClientRect(); + const slider = document.getElementById("res-disk"); + if (!slider) throw new Error("missing #res-disk"); + const r = slider.getBoundingClientRect(); + if (r.left < tabs.right) throw new Error(`res-disk starts at ${Math.round(r.left)}, under the tabs`); + eq(slider.min, "128", "min"); + eq(slider.max, "1024", "max"); + eq(slider.value, "128", "value"); + eq(document.getElementById("res-disk-v").textContent, "128 GB", "label"); + eq(document.getElementById("res-save").disabled, true, "save initially disabled"); + if (document.getElementById("res-restart")) throw new Error("no restart button when running matches saved"); +}); + +t("Raising disk slider enables Save and posts disk_gb in setresources", () => { + const slider = document.getElementById("res-disk"); + slider.value = "256"; + slider.dispatchEvent(new Event("input", { bubbles: true })); + eq(document.getElementById("res-disk-v").textContent, "256 GB", "updated label"); + eq(document.getElementById("res-save").disabled, false, "save enabled"); + const before = sent.length; + document.getElementById("res-save").click(); + const msg = sent.slice(before).find((m) => m.cmd === "setresources"); + if (!msg) throw new Error("setresources not sent"); + eq(msg.value, { cpus: 4, memory_mib: 8192, disk_gb: 256 }, "setresources payload"); +}); + +t("Pending disk growth while awake offers Restart VM to apply", () => { + kiri.on({ + type: "resources", + cpus: 4, + memory_mib: 8192, + disk_gb: 256, + running_cpus: 4, + running_memory_mib: 8192, + running_disk_gb: 128, + awake: true, + max_cpus: 12, + max_memory_mib: 32768, + min_disk_gb: 128, + max_disk_gb: 1024, + overridden: true, + }); + if (!document.getElementById("res-restart")) throw new Error("missing Restart VM button"); + const text = document.querySelector(".settings").textContent; + if (!text.includes("KIRI_DISK_GB")) throw new Error("overridden notice should mention KIRI_DISK_GB"); + if (!text.includes("128 GB")) throw new Error("running footer should show current running disk size"); +}); + +t("When disk_gb is absent (Linux/Windows), disk slider is hidden and Save omits disk_gb", () => { + kiri.on({ + type: "resources", + cpus: 4, + memory_mib: 8192, + running_cpus: 4, + running_memory_mib: 8192, + awake: false, + max_cpus: 12, + max_memory_mib: 32768, + overridden: false, + }); + if (document.getElementById("res-disk")) throw new Error("res-disk should not render without disk_gb"); + const cpuSlider = document.getElementById("res-cpus"); + cpuSlider.value = "6"; + cpuSlider.dispatchEvent(new Event("input", { bubbles: true })); + const before = sent.length; + document.getElementById("res-save").click(); + const msg = sent.slice(before).find((m) => m.cmd === "setresources"); + eq(msg.value, { cpus: 6, memory_mib: 8192 }, "payload without disk_gb"); +}); + +report(R); From 96829c7079a99cab3fc07829558ec60ecf4bdac2 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:11:09 +0100 Subject: [PATCH 042/157] Windows: add opt-in WSL 2 distro socket and bind-mount integration (#269) (#825) --- crates/kiri-win/src/engine.rs | 2 + crates/kiri-win/src/wslconfig.rs | 163 ++++++++++++++- crates/kiri-win/src/wslsync.rs | 280 +++++++++++++++++++++++++ crates/kiri/src/daemon/api.rs | 55 ++++- crates/kiri/src/daemon/binds.rs | 300 ++++++++++++++++++++++++++- crates/kiri/src/daemon/caller.rs | 13 +- crates/kiri/src/daemon/mod.rs | 251 ++++++++++++++++++++++ crates/kiri/src/ui/index.html | 17 +- crates/kiri/src/ui/lang/am.json | 4 +- crates/kiri/src/ui/lang/ar.json | 4 +- crates/kiri/src/ui/lang/bg.json | 4 +- crates/kiri/src/ui/lang/bn.json | 4 +- crates/kiri/src/ui/lang/ca.json | 4 +- crates/kiri/src/ui/lang/ckb.json | 4 +- crates/kiri/src/ui/lang/cs.json | 4 +- crates/kiri/src/ui/lang/de.json | 4 +- crates/kiri/src/ui/lang/el.json | 4 +- crates/kiri/src/ui/lang/es.json | 4 +- crates/kiri/src/ui/lang/fa.json | 4 +- crates/kiri/src/ui/lang/fi.json | 4 +- crates/kiri/src/ui/lang/fr.json | 4 +- crates/kiri/src/ui/lang/hi.json | 4 +- crates/kiri/src/ui/lang/hu.json | 4 +- crates/kiri/src/ui/lang/id.json | 4 +- crates/kiri/src/ui/lang/it.json | 4 +- crates/kiri/src/ui/lang/ja.json | 4 +- crates/kiri/src/ui/lang/kk.json | 4 +- crates/kiri/src/ui/lang/ko.json | 4 +- crates/kiri/src/ui/lang/lo.json | 4 +- crates/kiri/src/ui/lang/lt.json | 4 +- crates/kiri/src/ui/lang/nb.json | 4 +- crates/kiri/src/ui/lang/pl.json | 4 +- crates/kiri/src/ui/lang/pt-BR.json | 4 +- crates/kiri/src/ui/lang/ro.json | 4 +- crates/kiri/src/ui/lang/ru.json | 4 +- crates/kiri/src/ui/lang/sl.json | 4 +- crates/kiri/src/ui/lang/sq.json | 4 +- crates/kiri/src/ui/lang/ta.json | 4 +- crates/kiri/src/ui/lang/te.json | 4 +- crates/kiri/src/ui/lang/th.json | 4 +- crates/kiri/src/ui/lang/tr.json | 4 +- crates/kiri/src/ui/lang/uk.json | 4 +- crates/kiri/src/ui/lang/vi.json | 4 +- crates/kiri/src/ui/lang/zh-Hans.json | 4 +- crates/kiri/src/ui/lang/zh-Hant.json | 4 +- docs/features.md | 7 +- tests/ui/settingscolumn.js | 18 ++ tests/ui/wsl-integration.js | 89 ++++++++ 48 files changed, 1282 insertions(+), 61 deletions(-) create mode 100644 tests/ui/wsl-integration.js diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 4b75e670f..485a6b5fd 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -244,6 +244,7 @@ fn watch(tx: Sender) { // A Kubernetes node already running gets its kubectl context. crate::k8s::sync_soon(); crate::watch::notify_containers_changed(); + crate::wslconfig::sync_wsl_integration_soon(); let _ = client::events(|_| { crate::watch::notify_containers_changed(); tx.send(Cmd::Refresh).is_ok() @@ -333,6 +334,7 @@ pub(crate) fn ensure_daemon() -> io::Result<()> { start_daemon()?; } std::thread::spawn(crate::update::catch_up_engine); + crate::wslconfig::sync_wsl_integration_soon(); Ok(()) } diff --git a/crates/kiri-win/src/wslconfig.rs b/crates/kiri-win/src/wslconfig.rs index 2adfed17b..54facd37c 100644 --- a/crates/kiri-win/src/wslconfig.rs +++ b/crates/kiri-win/src/wslconfig.rs @@ -15,6 +15,145 @@ fn path() -> Option { std::env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join(".wslconfig")) } +fn integration_path() -> Option { + std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri").join("wsl-integration.json")) +} + +/// Enabled WSL integration distros from `%LOCALAPPDATA%\Kiri\wsl-integration.json` +/// (off by default). +pub fn enabled_distros() -> Vec { + integration_path() + .and_then(|p| std::fs::read(p).ok()) + .map(|b| crate::wslsync::parse_enabled_distros(&b)) + .unwrap_or_default() +} + +fn save_enabled_distros(distros: &[String]) -> io::Result<()> { + let p = integration_path().ok_or_else(|| io::Error::other("LOCALAPPDATA is not set"))?; + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent)?; + } + let tmp = p.with_extension("json.tmp"); + std::fs::write(&tmp, crate::wslsync::encode_enabled_distros(distros))?; + std::fs::rename(&tmp, &p) +} + +/// User WSL distros discovered by `wsl.exe --list --quiet` (excluding `kiri` +/// and `docker-desktop*`). +fn user_distros() -> Vec { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let Ok(out) = crate::update::output_within(cmd.args(["-l", "-q"]), std::time::Duration::from_secs(15)) else { + return Vec::new(); + }; + if !out.status.success() { + return Vec::new(); + } + crate::wslsync::parse_wsl_distros(&out.stdout, crate::engine::distro().as_deref()) +} + +fn run_distro_script(distro: &str, script: &str) -> io::Result { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let out = crate::update::output_within( + cmd.args(crate::wslsync::wsl_sh(distro, script)), + crate::update::WSL_LIMIT, + )?; + if !out.status.success() { + let err = crate::wslsync::wsl_text(&out.stderr); + let msg = err.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("WSL command failed"); + return Err(io::Error::other(format!("{distro}: {msg}"))); + } + Ok(crate::wslsync::wsl_text(&out.stdout).trim().to_owned()) +} + +static WSL_SYNC_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Applies the current WSL integration settings to all enabled distros and updates +/// the daemon's per-distro sockets in `/mnt/wsl/kiri/sockets//docker.sock`. +pub fn apply_wsl_integration(disabled: Option<&str>, background: bool) -> io::Result<()> { + let _guard = WSL_SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let enabled = enabled_distros(); + if enabled.is_empty() && disabled.is_none() { + if background && crate::client::alive_quick() { + if let Ok(v) = crate::client::get_background("/kiri/wsl") + && v["distros"].as_array().is_some_and(|a| !a.is_empty()) + { + let _ = crate::client::request_with("POST", "/kiri/wsl", Some(&json!({"distros": []})), true); + } + } + return Ok(()); + } + if !background { + crate::engine::ensure_daemon()?; + } else if !crate::client::alive_quick() { + return Ok(()); + } + let available = user_distros(); + let mut active = Vec::new(); + let mut first_err: Option = None; + for want in &enabled { + let Some(name) = available.iter().find(|a| a.eq_ignore_ascii_case(want)) else { + continue; + }; + let script = crate::wslsync::wsl_enable_script(name, ""); + match run_distro_script(name, &script) { + Ok(out) => { + let gid = out.lines().next_back().and_then(|l| l.trim().parse::().ok()).unwrap_or(0); + active.push(json!({"name": name, "gid": gid})); + } + Err(e) => { + crate::serve::log(&format!("wsl integration ({name}): {e}")); + if first_err.is_none() { + first_err = Some(e); + } + } + } + } + let res = crate::client::request_with("POST", "/kiri/wsl", Some(&json!({"distros": active})), background); + if let Err(e) = crate::engine::expect_ok(res) + && first_err.is_none() + { + first_err = Some(e); + } + if let Some(off) = disabled { + let script = crate::wslsync::wsl_disable_script(off, ""); + if let Err(e) = run_distro_script(off, &script) { + crate::serve::log(&format!("wsl integration disable ({off}): {e}")); + if first_err.is_none() { + first_err = Some(e); + } + } + } + match first_err { + Some(e) => Err(e), + None => Ok(()), + } +} + +/// Re-applies enabled WSL distros in the background when Kiri starts or +/// reconnects to the engine (handling `wsl --shutdown`). +pub fn sync_wsl_integration_soon() { + std::thread::spawn(|| { + if let Err(e) = apply_wsl_integration(None, true) { + crate::serve::log(&format!("wsl integration sync: {e}")); + } + }); +} + +fn toggle_distro(distro: &str, on: bool) -> io::Result<()> { + if !crate::wslsync::valid_distro_name(distro) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid WSL distro name")); + } + let mut list = enabled_distros(); + list.retain(|d| !d.eq_ignore_ascii_case(distro)); + if on { + list.push(distro.to_owned()); + } + save_enabled_distros(&list)?; + apply_wsl_integration((!on).then_some(distro), false) +} + /// `32GB`, `8192MB`, `512m` → MiB. fn mib(v: &str) -> Option { let v = v.trim().to_ascii_uppercase(); @@ -129,6 +268,14 @@ fn event() -> Value { let cpus = get(&text, "processors").and_then(|v| v.parse().ok()).unwrap_or(max_cpus).clamp(1, max_cpus); let memory = get(&text, "memory").and_then(|v| mib(&v)).unwrap_or(max_mib / 2); let now = running(); + let enabled = enabled_distros(); + let wsl_distros: Vec = user_distros() + .into_iter() + .map(|name| { + let on = enabled.iter().any(|e| e.eq_ignore_ascii_case(&name)); + json!({ "name": name, "on": on }) + }) + .collect(); json!({ "type": "resources", "cpus": cpus, @@ -140,6 +287,7 @@ fn event() -> Value { "max_memory_mib": max_mib, "overridden": false, "restart_note": "Restarting restarts WSL: every WSL distro stops, not only Kiri's, and Kiri's containers start again as they're set to.", + "wsl_distros": wsl_distros, }) } @@ -155,9 +303,19 @@ fn save(body: &Value) -> io::Result<()> { std::fs::write(&p, text) } -/// Reads (or saves, then reads) the CPUs and memory for Settings. +/// Reads (or saves, then reads) the CPUs, memory and WSL integration for Settings. pub fn resources(body: Option) { std::thread::spawn(move || { + if let Some(b) = &body + && let Some(distro) = b["wsl_distro"].as_str() + { + let on = b["on"].as_bool().unwrap_or(false); + if let Err(e) = toggle_distro(distro, on) { + emit(notice("error", &e.to_string())); + } + emit(event().to_string()); + return; + } let saved = body.map(|b| save(&b)); let ev = event(); match saved { @@ -176,6 +334,9 @@ pub fn restart() { let mut cmd = crate::win::tool("wsl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| crate::engine::ensure_daemon()); + if r.is_ok() { + let _ = apply_wsl_integration(None, true); + } emit(match r { Ok(()) => notice("ok", &tr("WSL restarted with the new resources")), Err(e) => notice("error", &trf("Could not restart WSL: {error}", &[("error", &e)])), diff --git a/crates/kiri-win/src/wslsync.rs b/crates/kiri-win/src/wslsync.rs index 673ba9605..8047e474f 100644 --- a/crates/kiri-win/src/wslsync.rs +++ b/crates/kiri-win/src/wslsync.rs @@ -129,6 +129,182 @@ pub fn wsl_sh<'a>(distro: &'a str, script: &'a str) -> [&'a str; 8] { ["-d", distro, "-u", "root", "-e", "sh", "-c", script] } +/// Whether `name` is a valid single-component WSL distro name. +pub fn valid_distro_name(name: &str) -> bool { + !name.is_empty() + && name != "." + && name != ".." + && !name.contains(['/', '\\', '\0']) + && !name.bytes().any(|b| b.is_ascii_control()) +} + +/// Decodes `wsl.exe` output (UTF-16LE with or without BOM, or UTF-8), +/// dropping any leading BOM and NUL bytes. +pub fn wsl_text(bytes: &[u8]) -> String { + let (bytes, bom) = bytes.strip_prefix(&[0xFF, 0xFE]).map_or((bytes, false), |rest| (rest, true)); + let units = bytes.len() / 2; + let ascii = bytes.as_chunks::<2>().0.iter().filter(|&&[lo, hi]| lo != 0 && hi == 0).count(); + let looks_utf16 = ascii >= 2 && ascii * 4 >= units; + let text = if bom || looks_utf16 { + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|&p| u16::from_le_bytes(p)).collect(); + String::from_utf16_lossy(&units) + } else { + String::from_utf8_lossy(bytes).into_owned() + }; + text.trim_start_matches('\u{feff}').replace('\0', "") +} + +/// Parses `wsl.exe --list --quiet` output into user distros eligible for WSL +/// integration, filtering out `kiri`, `engine_distro`, `docker-desktop`, +/// `docker-desktop-data` (`docker-desktop*`), empty lines and BOMs. +pub fn parse_wsl_distros(bytes: &[u8], engine_distro: Option<&str>) -> Vec { + let mut out = Vec::new(); + for line in wsl_text(bytes).lines() { + let d = line.trim().trim_matches('\u{feff}').trim(); + if !valid_distro_name(d) { + continue; + } + let lower = d.to_ascii_lowercase(); + if lower == "kiri" || lower.starts_with("docker-desktop") { + continue; + } + if engine_distro.is_some_and(|e| d.eq_ignore_ascii_case(e)) { + continue; + } + if !out.iter().any(|x: &String| x.eq_ignore_ascii_case(d)) { + out.push(d.to_owned()); + } + } + out +} + +/// Parses `%LOCALAPPDATA%\Kiri\wsl-integration.json`; off (empty) by default. +pub fn parse_enabled_distros(bytes: &[u8]) -> Vec { + let v: serde_json::Value = serde_json::from_slice(bytes).unwrap_or(serde_json::Value::Null); + let arr = v["distros"].as_array().or_else(|| v.as_array()); + let mut out = Vec::new(); + for item in arr.into_iter().flatten() { + let Some(d) = item.as_str().map(str::trim) else { continue }; + if valid_distro_name(d) + && !d.eq_ignore_ascii_case("kiri") + && !d.to_ascii_lowercase().starts_with("docker-desktop") + && !out.iter().any(|x: &String| x.eq_ignore_ascii_case(d)) + { + out.push(d.to_owned()); + } + } + out +} + +/// Encodes the enabled distros for `%LOCALAPPDATA%\Kiri\wsl-integration.json`. +pub fn encode_enabled_distros(distros: &[String]) -> Vec { + serde_json::to_vec_pretty(&serde_json::json!({ "distros": distros })).unwrap_or_default() +} + +/// SHA-256 of `"kiri"`, used by the Docker CLI for `~/.docker/contexts/meta//meta.json`. +const KIRI_CONTEXT_HASH: &str = "c288b06224b0bc4af8a3d80f683a27a8fc72e45f901a7e6766109e2fc1d5c2b9"; + +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 } \ + u && index(tolower(k($0)), \"default=\") == 1 { s = k($0); sub(/^[dD][eE][fF][aA][uU][lL][tT]=/, \"\", s); print s; exit }"; + +const PASSWD_AWK: &str = "def != \"\" && $1 == def && $3 != 0 && $4 ~ /^[0-9]+$/ { print $1 \":\" $3 \":\" $4 \":\" $6; found = 1; exit } \ + $3 == 1000 && $4 ~ /^[0-9]+$/ && !u1000 { u1000 = $1 \":\" $3 \":\" $4 \":\" $6 } \ + $3 >= 1000 && $3 < 65534 && $4 ~ /^[0-9]+$/ && !ufirst { ufirst = $1 \":\" $3 \":\" $4 \":\" $6 } \ + END { if (!found) { if (u1000) print u1000; else if (ufirst) print ufirst } }"; + +/// The script, run as root inside `distro`, that enables Kiri's WSL integration: +/// 1. Mounts `distro`'s `/` onto `/mnt/wsl/kiri/roots/`. +/// 2. Determines the socket GID (`docker` group GID if `docker` exists in +/// `/etc/group`, otherwise the default non-root user's primary GID in +/// `/etc/passwd`, so NixOS without `groupadd` works cleanly). +/// 3. Links `/var/run/docker.sock -> /mnt/wsl/kiri/sockets//docker.sock` +/// unless `/var/run/docker.sock` belongs to a running `dockerd` inside `distro`, +/// and writes the `kiri` Docker context for the default user. +/// 4. Prints the numeric GID on stdout. +/// `root` is `""` in production and a stand-in directory in unit tests. +pub fn wsl_enable_script(distro: &str, root: &str) -> String { + let bind_root = sh_quote(&format!("{root}/mnt/wsl/kiri/roots/{distro}")); + let sock_target = sh_quote(&format!("{root}/mnt/wsl/kiri/sockets/{distro}/docker.sock")); + let src_root = sh_quote(if root.is_empty() { "/" } else { root }); + let etc_group = sh_quote(&format!("{root}/etc/group")); + let etc_passwd = sh_quote(&format!("{root}/etc/passwd")); + let etc_wsl = sh_quote(&format!("{root}/etc/wsl.conf")); + let var_run = sh_quote(&format!("{root}/var/run")); + let host_prefix = sh_quote(root); + let ctx_meta = serde_json::json!({ + "Name": "kiri", + "Metadata": { "Description": "Kiri" }, + "Endpoints": { + "docker": { + "Host": format!("unix://{root}/mnt/wsl/kiri/sockets/{distro}/docker.sock"), + "SkipTLSVerify": false + } + } + }) + .to_string(); + format!( + "export PATH=\"$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/run/current-system/sw/bin:/nix/var/nix/profiles/default/bin\"; \ + r={bind_root}; mkdir -p \"$r\" || exit 1; \ + if ! mountpoint -q \"$r\" 2>/dev/null && ! grep -Fqs \" $r \" /proc/mounts 2>/dev/null; then mount --bind {src_root} \"$r\" || exit 1; fi; \ + defuser=\"\"; [ -f {etc_wsl} ] && defuser=$(awk {} {etc_wsl} 2>/dev/null); \ + uinfo=\"\"; [ -f {etc_passwd} ] && uinfo=$(awk -F: -v def=\"$defuser\" {} {etc_passwd} 2>/dev/null); \ + uname=$(printf %s \"$uinfo\" | cut -d: -f1); \ + uuid=$(printf %s \"$uinfo\" | cut -d: -f2); \ + ugid=$(printf %s \"$uinfo\" | cut -d: -f3); \ + uhome=$(printf %s \"$uinfo\" | cut -d: -f4); \ + dgid=\"\"; [ -f {etc_group} ] && dgid=$(awk -F: '$1 == \"docker\" && $3 ~ /^[0-9]+$/ {{ print $3; exit }}' {etc_group} 2>/dev/null); \ + if [ -n \"$dgid\" ]; then \ + gid=\"$dgid\"; \ + if [ -n \"$uname\" ] && command -v usermod >/dev/null 2>&1; then usermod -aG docker \"$uname\" 2>/dev/null || true; fi; \ + elif [ -n \"$ugid\" ]; then \ + gid=\"$ugid\"; \ + else \ + gid=0; \ + fi; \ + vr={var_run}; mkdir -p \"$vr\" || exit 1; \ + busy=0; \ + if [ -S \"$vr/docker.sock\" ] && [ ! -L \"$vr/docker.sock\" ]; then \ + if [ -f \"$vr/docker.pid\" ] && kill -0 \"$(cat \"$vr/docker.pid\" 2>/dev/null)\" 2>/dev/null; then busy=1; \ + elif pgrep -x dockerd >/dev/null 2>&1 || pidof dockerd >/dev/null 2>&1; then busy=1; fi; \ + fi; \ + [ \"$busy\" = 0 ] && ln -sfn {sock_target} \"$vr/docker.sock\"; \ + if [ -n \"$uhome\" ] && [ -d {host_prefix}\"$uhome\" ]; then \ + cdir={host_prefix}\"$uhome/.docker/contexts/meta/{KIRI_CONTEXT_HASH}\"; \ + mkdir -p \"$cdir\" 2>/dev/null && printf %s {} | base64 -d >\"$cdir/meta.json\" 2>/dev/null; \ + [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -R \"$uuid:$ugid\" {host_prefix}\"$uhome/.docker\" 2>/dev/null || true; \ + fi; \ + echo \"$gid\"", + sh_quote(DEFAULT_USER_AWK), + sh_quote(PASSWD_AWK), + base64(ctx_meta.as_bytes()), + ) +} + +/// The script, run as root inside `distro`, that tears down Kiri's WSL +/// integration when `distro` is disabled: removes `/var/run/docker.sock` if it +/// points into `/mnt/wsl/kiri/`, unmounts `/mnt/wsl/kiri/roots/`, and +/// removes `/mnt/wsl/kiri/sockets//docker.sock`. +pub fn wsl_disable_script(distro: &str, root: &str) -> String { + let bind_root = sh_quote(&format!("{root}/mnt/wsl/kiri/roots/{distro}")); + let sock_dir = sh_quote(&format!("{root}/mnt/wsl/kiri/sockets/{distro}")); + let var_run = sh_quote(&format!("{root}/var/run")); + format!( + "export PATH=\"$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/run/current-system/sw/bin:/nix/var/nix/profiles/default/bin\"; \ + vr={var_run}; \ + if [ -L \"$vr/docker.sock\" ]; then \ + t=$(readlink \"$vr/docker.sock\" 2>/dev/null || true); \ + case \"$t\" in */mnt/wsl/kiri/*) rm -f \"$vr/docker.sock\" ;; esac; \ + fi; \ + r={bind_root}; \ + if mountpoint -q \"$r\" 2>/dev/null || grep -Fqs \" $r \" /proc/mounts 2>/dev/null; then \ + umount -l \"$r\" 2>/dev/null || umount \"$r\" 2>/dev/null || true; \ + fi; \ + rmdir \"$r\" 2>/dev/null || true; \ + sd={sock_dir}; rm -f \"$sd/docker.sock\" 2>/dev/null || true; rmdir \"$sd\" 2>/dev/null || true; true" + ) +} + #[cfg(all(test, unix))] mod tests { use super::*; @@ -321,4 +497,108 @@ mod tests { fn quotes_one_word() { assert_eq!(sh_quote("C:/Users/O'Neil/x"), r"'C:/Users/O'\''Neil/x'"); } + + #[test] + fn parses_utf16le_wsl_list_and_filters_system_distros() { + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_le_bytes).collect::>(); + let raw = "\u{feff}kiri\r\nUbuntu\r\ndocker-desktop\r\ndocker-desktop-data\r\n\r\nNixOS\r\nDebian\r\nUbuntu\r\n"; + assert_eq!( + parse_wsl_distros(&utf16(raw), Some("kiri")), + vec!["Ubuntu".to_owned(), "NixOS".to_owned(), "Debian".to_owned()] + ); + // With explicit UTF-16LE BOM prefix and custom engine distro. + let mut with_bom = vec![0xFF, 0xFE]; + with_bom.extend_from_slice(&utf16("Ubuntu-26.04\nNixOS\ndocker-desktop\nkiri\n")); + assert_eq!( + parse_wsl_distros(&with_bom, Some("Ubuntu-26.04")), + vec!["NixOS".to_owned()] + ); + // Enabled distros file defaults to off (empty) and filters system distros. + assert!(parse_enabled_distros(b"").is_empty()); + let saved = encode_enabled_distros(&["Ubuntu".into(), "NixOS".into()]); + assert_eq!(parse_enabled_distros(&saved), vec!["Ubuntu".to_owned(), "NixOS".to_owned()]); + } + + #[test] + fn wsl_integration_scripts_have_no_backslash() { + assert!(!wsl_enable_script("Ubuntu", "").contains('\\')); + assert!(!wsl_disable_script("Ubuntu", "").contains('\\')); + } + + #[test] + fn wsl_enable_and_disable_scripts_setup_gid_symlink_and_teardown() { + use std::os::unix::net::UnixListener; + let dir = std::env::temp_dir().join(format!("kiri-wsl-integ-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (root, tools) = (dir.join("root"), dir.join("tools")); + for d in [&root.join("etc"), &root.join("var/run"), &root.join("home/alice"), &tools] { + std::fs::create_dir_all(d).unwrap(); + } + // Mock mountpoint, mount and umount in PATH so the test runs unprivileged. + let mounted_flag = dir.join("mounted"); + std::fs::write( + tools.join("mountpoint"), + format!("#!/bin/sh\n[ -f '{}' ]\n", mounted_flag.display()), + ) + .unwrap(); + std::fs::write( + tools.join("mount"), + format!("#!/bin/sh\n[ \"$1\" = --bind ] && [ -d \"$3\" ] && touch '{}'\n", mounted_flag.display()), + ) + .unwrap(); + std::fs::write( + tools.join("umount"), + format!("#!/bin/sh\nrm -f '{}'\n", mounted_flag.display()), + ) + .unwrap(); + for tool in ["mountpoint", "mount", "umount"] { + std::fs::set_permissions(tools.join(tool), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let path = format!("{}:{}", tools.display(), std::env::var("PATH").unwrap_or_default()); + let root_str = root.to_string_lossy(); + + // 1. NixOS-like distro without `docker` group: uses default user's primary GID (100). + std::fs::write(root.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\nalice:x:1000:100:Alice:/home/alice:/bin/sh\n").unwrap(); + std::fs::write(root.join("etc/group"), "root:x:0:\nusers:x:100:\n").unwrap(); + let enable = wsl_enable_script("NixOS", &root_str); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "100"); + assert!(mounted_flag.exists(), "root bind mount must be performed"); + assert!(root.join("mnt/wsl/kiri/roots/NixOS").is_dir()); + let link = std::fs::read_link(root.join("var/run/docker.sock")).unwrap(); + assert_eq!(link, root.join("mnt/wsl/kiri/sockets/NixOS/docker.sock")); + assert!(root.join("home/alice/.docker/contexts/meta").join(KIRI_CONTEXT_HASH).join("meta.json").is_file()); + + // 2. Distro with `docker` group in /etc/group: uses `docker` group GID (131). + std::fs::write(root.join("etc/group"), "root:x:0:\nusers:x:100:\ndocker:x:131:alice\n").unwrap(); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "131"); + + // 3. Disable script unmounts root, removes /var/run/docker.sock symlink and socket dir. + let sock_dir = root.join("mnt/wsl/kiri/sockets/NixOS"); + std::fs::create_dir_all(&sock_dir).unwrap(); + std::fs::write(sock_dir.join("docker.sock"), "").unwrap(); + let disable = wsl_disable_script("NixOS", &root_str); + let out = Command::new("sh").args(["-c", &disable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(!mounted_flag.exists(), "root bind mount must be unmounted"); + assert!(std::fs::symlink_metadata(root.join("var/run/docker.sock")).is_err(), "symlink must be removed"); + assert!(!sock_dir.exists(), "socket dir must be removed"); + + // 4. When a live dockerd owns /var/run/docker.sock, enable leaves it untouched. + let own_sock = root.join("var/run/docker.sock"); + let _listener = UnixListener::bind(&own_sock).unwrap(); + std::fs::write(root.join("var/run/docker.pid"), std::process::id().to_string()).unwrap(); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert!(!std::fs::symlink_metadata(&own_sock).unwrap().file_type().is_symlink(), "running dockerd socket must not be overwritten"); + // And disable leaves a real dockerd socket untouched too. + let out = Command::new("sh").args(["-c", &disable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert!(own_sock.exists(), "running dockerd socket must not be removed on disable"); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index de901291a..d2830ebf2 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -38,7 +38,7 @@ pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Res if req.header("X-Kiri-Background").is_none() { engine.touch(); } - match route(&req, &engine, caller, &mut w, &mut r) { + match route(&req, &engine, &caller, &mut w, &mut r) { // `Connection: close` or HTTP/1.0: the client reads to the end of // the stream (a 204 has no length to read by), which `close` // gives it cleanly. @@ -134,7 +134,7 @@ fn container_may(method: &str, path: &str) -> bool { !kiri || matches!(method, "GET" | "HEAD") || CONTAINER_MAY.contains(&(method, path)) } -fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream, r: &mut BufReader) -> io::Result { +fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStream, r: &mut BufReader) -> io::Result { if req.api_version.is_some_and(|v| v < http::MIN_API_VERSION) { let (major, minor) = req.api_version.unwrap_or_default(); let (min_major, min_minor) = http::MIN_API_VERSION; @@ -144,7 +144,7 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream let m = req.method.as_str(); // Kiri's own endpoints that change something are for this machine's // programs (caller.rs), not for a container given the socket. - if caller == Caller::Container && !container_may(m, p) { + if *caller == Caller::Container && !container_may(m, p) { // Closed after the answer: a body the request carried is not left // on the connection to be read as the next request. http::error(w, 403, "this is changed in Kiri's window or with the kiri command on this machine, not from a container")?; @@ -185,6 +185,9 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream ("POST", "/kiri/domains") => return reply(w, set_domain_ports(req, engine), 200), // Back to the ports a start gives (a test copy's routers stop). ("DELETE", "/kiri/domains") => return reply(w, super::domains::reset(engine).map_err(Error::Conflict), 200), + // Settings → Resources → WSL integration: per-distro sockets in /mnt/wsl/kiri. + ("GET", "/kiri/wsl") => return reply(w, Ok(super::wsl_report()), 200), + ("POST", "/kiri/wsl") => return reply(w, set_wsl(req, caller), 200), // USB passthrough (macOS: the root helper `kiri usb serve` connects here). #[cfg(target_os = "macos")] ("POST", "/kiri/usb") => return super::usb::attach(req, engine, w, r), @@ -258,7 +261,7 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream if let Some(made) = super::builder::create_for_buildx(engine, req.query("name")) { return reply(w, made, 201); } - return reply(w, create(req, engine), 201); + return reply(w, create_for(req, engine, caller.wsl_distro()), 201); } ("GET", "/containers/json") => return reply(w, list(req, engine), 200), ("GET", "/networks") => return reply(w, networks(req, engine), 200), @@ -1059,6 +1062,27 @@ fn set_domain_ports(req: &Request, engine: &Arc) -> Result super::domains::set_ports(engine, port("http")?, port("https")?).map_err(Error::Conflict) } +fn set_wsl(req: &Request, caller: &Caller) -> Result { + if caller.wsl_distro().is_some() { + return Err(Error::Forbidden("WSL integration settings can only be changed from Kiri on Windows".into())); + } + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + let mut distros = Vec::new(); + for item in body["distros"].as_array().ok_or_else(|| Error::BadRequest("distros must be an array".into()))? { + let name = item["name"].as_str().unwrap_or_default(); + if !super::binds::valid_distro_name(name) { + return Err(Error::BadRequest(format!("invalid WSL distro name: {name}"))); + } + let gid = item["gid"] + .as_u64() + .and_then(|g| u32::try_from(g).ok()) + .ok_or_else(|| Error::BadRequest(format!("invalid gid for WSL distro {name}")))?; + distros.push(super::WslDistroConfig { name: name.to_owned(), gid }); + } + super::sync_wsl_sockets(&distros).map_err(Error::Io)?; + Ok(super::wsl_report()) +} + fn set_resources(req: &Request) -> Result<(), Error> { use super::engine as e; let path = e::resources_path().ok_or_else(|| Error::Io(io::Error::other("HOME is not set")))?; @@ -1755,7 +1779,12 @@ fn volumes_from_mounts(guest: &[String], info: &[Value], ro: bool) -> Vec<(Strin /// `-v`, `--mount`, `--tmpfs`, `--volumes-from`, `-v /path` and the image's /// VOLUME lines. +#[cfg(test)] fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result { + mounts_for(body, engine, image, None) +} + +fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, wsl_distro: Option<&str>) -> Result { let host = &body["HostConfig"]; let mut out = Mounts { guest: Vec::new(), info: Vec::new(), volumes: Vec::new(), anon: Vec::new() }; let check_target = |t: &str| -> Result<(), Error> { @@ -1789,7 +1818,7 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result { out.guest.push(format!("{}\t{dst}\t{}", engine_sock.as_deref().unwrap_or_default(), flag(""))); @@ -1858,10 +1887,11 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result Result super::binds::source(src, w)?, + let src = match (wsl, wsl_distro) { + (_, Some(d)) if kind == "bind" => super::binds::distro_source(src, d, wsl)?, + (Some(w), None) if kind == "bind" => super::binds::source(src, w)?, _ => src.to_owned(), }; let src = src.as_str(); @@ -2403,6 +2434,10 @@ const SECCOMP_UNCONFINED_WARNING: &str = "seccomp=unconfined lifts the default syscall filter, but Kiri keeps its host boundary: io_uring and vsock sockets stay blocked"; pub(super) fn create(req: &Request, engine: &Engine) -> Result { + create_for(req, engine, None) +} + +pub(super) fn create_for(req: &Request, engine: &Engine, wsl_distro: Option<&str>) -> Result { let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; let image_name = body["Image"].as_str().unwrap_or_default(); if image_name.is_empty() { @@ -2539,7 +2574,7 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { // Checked before mounts, which may create volumes. let healthcheck = healthcheck_from(&body, &image_cfg)?; let (entrypoint, cmd) = command(strings(&body["Entrypoint"]), strings(&body["Cmd"]), &image.config.entrypoint, &image.config.cmd)?; - let mounts = mounts(&body, engine, &image)?; + let mounts = mounts_for(&body, engine, &image, wsl_distro)?; let exposed = exposed_ports(&body, &image_cfg); let ports = port_bindings(&body, &exposed)?; if !ports.is_empty() && network_mode == "none" { diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index 5e1862a2c..754d19e6a 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -8,6 +8,125 @@ use std::sync::OnceLock; use super::engine::Error; +/// Shared `/mnt/wsl/kiri` directory across all WSL 2 distros. +pub const WSL_KIRI_DIR: &str = "/mnt/wsl/kiri"; + +/// Active WSL integration base directory (`KIRI_WSL_DIR` override or `/mnt/wsl/kiri`). +pub fn wsl_kiri_dir() -> String { + std::env::var("KIRI_WSL_DIR") + .ok() + .map(|s| s.trim_end_matches('/').to_owned()) + .filter(|s| s.starts_with('/')) + .unwrap_or_else(|| WSL_KIRI_DIR.to_owned()) +} + +fn wsl_roots_dir() -> String { + format!("{}/roots", wsl_kiri_dir()) +} + +fn wsl_sockets_dir() -> String { + format!("{}/sockets", wsl_kiri_dir()) +} + +/// Whether `name` is a safe single-component WSL distro name. +pub fn valid_distro_name(name: &str) -> bool { + !name.is_empty() + && name != "." + && name != ".." + && !name.contains(['/', '\\', '\0']) + && !name.bytes().any(|b| b.is_ascii_control()) +} + +/// Normalizes a path into `/a/b/c`, clamping `..` at `/` so traversal can never +/// climb above the root. +fn lexical_clean(p: &str) -> String { + let mut out: Vec<&str> = Vec::new(); + for c in p.split('/') { + match c { + "" | "." => {} + ".." => { + out.pop(); + } + c => out.push(c), + } + } + format!("/{}", out.join("/")) +} + +/// Joins `inner` under `root` (`/mnt/wsl/kiri/roots/`), clamping any +/// `..` traversal so the result cannot escape `root`. +pub fn confine_to_root(root: &str, inner: &str) -> String { + let root = root.trim_end_matches('/'); + let rel = lexical_clean(inner); + if rel == "/" { + root.to_owned() + } else { + format!("{root}{rel}") + } +} + +/// When `distro_root` exists on disk, verifies that no existing symlink along +/// `target` escapes `distro_root`. +fn verify_on_disk_confinement(src: &str, distro: &str, distro_root: &Path, target: &Path) -> Result<(), Error> { + if !distro_root.exists() { + return Ok(()); + } + let Ok(canon_root) = std::fs::canonicalize(distro_root) else { + return Ok(()); + }; + let Ok(rel) = target.strip_prefix(distro_root) else { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + }; + let mut cur = distro_root.to_path_buf(); + for comp in rel.components() { + cur.push(comp); + if let Ok(link) = std::fs::read_link(&cur) { + let link_str = link.to_string_lossy(); + if !cur.exists() && (link.is_absolute() || link_str.split('/').any(|c| c == "..")) { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + } + } + if cur.exists() { + let canon = std::fs::canonicalize(&cur).map_err(Error::Io)?; + if !canon.starts_with(&canon_root) { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + } + } + } + Ok(()) +} + +/// Finds `/roots/` on disk if `` is integrated and mounted. +fn mounted_distro_root(distro: &str) -> Option { + if !valid_distro_name(distro) { + return None; + } + let roots_dir = wsl_roots_dir(); + let exact = format!("{roots_dir}/{distro}"); + if Path::new(&exact).is_dir() { + return Some(exact); + } + let entries = std::fs::read_dir(&roots_dir).ok()?; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + if name.eq_ignore_ascii_case(distro) && entry.path().is_dir() { + return Some(entry.path().to_string_lossy().into_owned()); + } + } + None +} + +fn is_wsl_engine_socket(p: &str) -> bool { + let sockets_dir = wsl_sockets_dir(); + let matches_prefix = |prefix: &str| { + p.strip_prefix(prefix) + .and_then(|rest| rest.strip_suffix("/docker.sock")) + .is_some_and(valid_distro_name) + }; + matches_prefix(&format!("{sockets_dir}/")) || matches_prefix(&format!("{WSL_KIRI_DIR}/sockets/")) +} + /// Where WSL mounts the Windows drives, and which distro the daemon runs in. #[derive(Debug, Clone, PartialEq)] pub struct Wsl { @@ -83,14 +202,20 @@ fn distro_of(unc: &str) -> Option { /// One `-v` spec (HostConfig.Binds) as source, target and options. In WSL a /// drive letter's colon belongs to the source (`C:\src:/app:ro`), and the /// source is made a path in this Linux. +#[cfg(test)] pub fn split(spec: &str, wsl: Option<&Wsl>) -> Result<(String, String, String), Error> { + split_for(spec, wsl, None) +} + +/// [`split`], translating Linux paths from an integrated WSL distro +/// (`wsl_distro = Some("")`) into `/mnt/wsl/kiri/roots//…`. +pub fn split_for(spec: &str, wsl: Option<&Wsl>, wsl_distro: Option<&str>) -> Result<(String, String, String), Error> { let bad = || Error::BadRequest(format!("invalid volume specification: {spec}")); // `c:/app` is the volume `c` at /app, as in moby's Windows parser: a // drive is the source only when an absolute target follows it. - let skip = match wsl { - Some(_) if spec[drive_prefix(spec)..].split(':').nth(1).is_some_and(|d| d.starts_with('/')) => drive_prefix(spec), - _ => 0, - }; + let has_drive = (wsl.is_some() || wsl_distro.is_some()) + && spec[drive_prefix(spec)..].split(':').nth(1).is_some_and(|d| d.starts_with('/')); + let skip = if has_drive { drive_prefix(spec) } else { 0 }; let Some(i) = spec[skip..].find(':').map(|i| skip + i) else { return Err(bad()) }; let (src, rest) = (&spec[..i], &spec[i + 1..]); let (dst, opts) = match rest.split(':').collect::>().as_slice() { @@ -98,14 +223,79 @@ pub fn split(spec: &str, wsl: Option<&Wsl>) -> Result<(String, String, String), [d, o] => (*d, *o), _ => return Err(bad()), }; - let src = match wsl { + let src = match (wsl, wsl_distro) { + (_, Some(d)) if src.starts_with('/') || looks_windows(src) => distro_source(src, d, wsl)?, // A volume name stays a name; only paths are translated. - Some(w) if looks_windows(src) => source(src, w)?, + (Some(w), None) if looks_windows(src) => source(src, w)?, _ => src.to_owned(), }; Ok((src, dst.to_owned(), opts.to_owned())) } +/// Translates a bind mount source from an integrated WSL distro ``: +/// - `/var/run/docker.sock` (and engine socket aliases) stays the engine socket +/// - `/mnt/c/proj` (under the Windows automount root) stays `/mnt/c/proj` +/// - `/home/alice/app` becomes `/mnt/wsl/kiri/roots//home/alice/app` +/// - `..` traversal is confined so it can never escape ``'s root +pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result { + if !valid_distro_name(distro) { + return Err(Error::BadRequest(format!("invalid WSL distro: {distro}"))); + } + let kiri_dir = wsl_kiri_dir(); + let roots_dir = format!("{kiri_dir}/roots"); + if looks_windows(src) { + let default_wsl = Wsl { root: "/mnt/".into(), distro: None }; + let w = wsl.unwrap_or(&default_wsl); + return source_with_roots(src, w, |d| { + if d.eq_ignore_ascii_case(distro) { + Some(format!("{roots_dir}/{distro}")) + } else { + mounted_distro_root(d) + } + }); + } + if !src.starts_with('/') { + return Ok(src.to_owned()); + } + let distro_root = format!("{roots_dir}/{distro}"); + let cleaned = clean(src); + if ENGINE_SOCKS.contains(&cleaned.as_str()) || is_wsl_engine_socket(&cleaned) { + return Ok(cleaned); + } + if cleaned == distro_root || cleaned.strip_prefix(&distro_root).is_some_and(|r| r.starts_with('/')) { + let rest = cleaned.strip_prefix(&distro_root).unwrap_or(""); + let target = confine_to_root(&distro_root, rest); + verify_on_disk_confinement(src, distro, Path::new(&distro_root), Path::new(&target))?; + return Ok(target); + } + let lex = lexical_clean(src); + if ENGINE_SOCKS.contains(&lex.as_str()) || is_wsl_engine_socket(&lex) { + return Ok(lex); + } + let is_internal_wsl = |p: &str| { + p == kiri_dir + || p.starts_with(&format!("{kiri_dir}/")) + || p == WSL_KIRI_DIR + || p.starts_with(&format!("{WSL_KIRI_DIR}/")) + }; + if is_internal_wsl(&lex) { + return Err(Error::BadRequest(format!( + "invalid mount source {src}: cannot mount Kiri's internal WSL directory" + ))); + } + let mnt = wsl.map_or("/mnt/", |w| w.root.as_str()); + let mnt_trimmed = mnt.trim_end_matches('/'); + if (!mnt_trimmed.is_empty() && (lex == mnt_trimmed || lex.starts_with(mnt))) + && lex != "/mnt/wsl" + && !is_internal_wsl(&lex) + { + return Ok(lex); + } + let target = confine_to_root(&distro_root, &lex); + verify_on_disk_confinement(src, distro, Path::new(&distro_root), Path::new(&target))?; + Ok(target) +} + /// How many leading bytes hold a colon that is not a separator: `C:` and /// `\\?\C:` (moby's Windows parser allows both). fn drive_prefix(spec: &str) -> usize { @@ -130,6 +320,10 @@ fn looks_windows(src: &str) -> bool { /// Anything else (a network share, another distro's files, a relative /// path) is refused: WSL can't reach it as a path here. pub fn source(src: &str, wsl: &Wsl) -> Result { + source_with_roots(src, wsl, mounted_distro_root) +} + +pub fn source_with_roots(src: &str, wsl: &Wsl, distro_root: impl Fn(&str) -> Option) -> Result { let bad = |why: &str| Error::BadRequest(format!("invalid mount source {src}: {why}")); if !looks_windows(src) { return Ok(src.to_owned()); @@ -152,6 +346,11 @@ pub fn source(src: &str, wsl: &Wsl) -> Result { return Err(bad("no WSL distro named")); } if let Some(ours) = wsl.distro.as_deref().filter(|d| !d.eq_ignore_ascii_case(distro)) { + if let Some(root) = distro_root(distro) { + let target = confine_to_root(&root, inner); + verify_on_disk_confinement(src, distro, Path::new(&root), Path::new(&target))?; + return Ok(target); + } return Err(bad(&format!("it is in the WSL distro {distro}, and Kiri runs in {ours}; use a path on a Windows drive or in {ours}"))); } return Ok(clean(&format!("/{inner}"))); @@ -275,6 +474,27 @@ pub fn engine_socket(src: &str) -> Option { engine_socket_with_alias(src, &own, alias, real) } +/// [`engine_socket`] for a create request that arrived from `wsl_distro`: +/// inside an integrated WSL distro, `/var/run/docker.sock` (and `/run/docker.sock`) +/// refers to Kiri's engine socket regardless of whether the host or engine +/// distro has another socket at `/var/run/docker.sock`. +pub fn engine_socket_for_distro(src: &str, wsl_distro: Option<&str>) -> Option { + if wsl_distro.is_some() { + let text = clean(src); + if ENGINE_SOCKS.contains(&text.as_str()) || is_wsl_engine_socket(&text) { + let own = super::socket_path().ok()?; + #[cfg(target_os = "macos")] + { + let _ = own; + return Some(VM_ENGINE_SOCK.to_owned()); + } + #[cfg(not(target_os = "macos"))] + return Some(super::caller::container_socket(&own).to_string_lossy().into_owned()); + } + } + engine_socket(src) +} + /// [`engine_socket`], with `resolve` giving where a path that exists /// really is. The path as given is followed first, as the kernel will /// follow it; only a path that is not there is compared as text. @@ -285,11 +505,12 @@ fn engine_socket_for(src: &str, own: &str, resolve: impl Fn(&str) -> Option, resolve: impl Fn(&str) -> Option) -> Option { let found = resolve(src); - let is_own = found.as_ref().is_some_and(|a| { - resolve(own).is_some_and(|b| a.same(&b)) || alias.and_then(&resolve).is_some_and(|b| a.same(&b)) - }); let text = clean(src); let matches_text = |p: &str| text == clean(p); + let is_own = found.as_ref().is_some_and(|a| { + resolve(own).is_some_and(|b| a.same(&b)) || alias.and_then(&resolve).is_some_and(|b| a.same(&b)) + }) || is_wsl_engine_socket(&text) + || found.as_ref().is_some_and(|r| is_wsl_engine_socket(&r.path)); #[cfg(target_os = "macos")] { let named = ENGINE_SOCKS.contains(&text.as_str()) || found.as_ref().is_some_and(|r| ENGINE_SOCKS.contains(&r.path.as_str())); @@ -300,7 +521,7 @@ fn engine_socket_with_alias(src: &str, own: &str, alias: Option<&str>, resolve: let given = || super::caller::container_socket(Path::new(own)).to_string_lossy().into_owned(); match found { Some(_) => is_own.then(given), - None => (matches_text(own) || alias.is_some_and(matches_text) || ENGINE_SOCKS.contains(&text.as_str())).then(given), + None => (is_own || matches_text(own) || alias.is_some_and(matches_text) || ENGINE_SOCKS.contains(&text.as_str())).then(given), } } } @@ -582,4 +803,63 @@ mod tests { assert!(!is_wsl_drive_path("/mnt/c/a\nb", "/mnt/", true)); assert!(is_wsl_drive_path("/windows/d/proj", "/windows/", false)); } + + #[test] + fn wsl_distro_path_translation_and_confinement() { + let w = wsl(); + assert_eq!( + split_for("/home/me/app:/app", Some(&w), Some("Ubuntu")).unwrap(), + t("/mnt/wsl/kiri/roots/Ubuntu/home/me/app", "/app", "") + ); + assert_eq!( + split_for("/home/me/app:/app:ro", None, Some("Ubuntu")).unwrap(), + t("/mnt/wsl/kiri/roots/Ubuntu/home/me/app", "/app", "ro") + ); + assert_eq!( + split_for("/mnt/c/proj:/app", Some(&w), Some("Ubuntu")).unwrap(), + t("/mnt/c/proj", "/app", "") + ); + assert_eq!( + split_for("/var/run/docker.sock:/var/run/docker.sock", Some(&w), Some("Ubuntu")).unwrap(), + t("/var/run/docker.sock", "/var/run/docker.sock", "") + ); + assert_eq!( + split_for("/run/docker.sock:/var/run/docker.sock", Some(&w), Some("Ubuntu")).unwrap(), + t("/run/docker.sock", "/var/run/docker.sock", "") + ); + assert_eq!( + split_for("myvol:/data", Some(&w), Some("Ubuntu")).unwrap(), + t("myvol", "/data", "") + ); + // `..` traversal confinement: cannot escape ``'s root. + for traversal in [ + "/mnt/wsl/kiri/roots/Ubuntu/../../etc", + "/mnt/wsl/kiri/roots/Ubuntu/../../../../etc", + "/../../etc", + "/home/me/../../../etc", + "/mnt/c/../../etc", + ] { + assert_eq!( + distro_source(traversal, "Ubuntu", Some(&w)).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/etc", + "{traversal}" + ); + } + // Mounting another distro's root or Kiri's internal WSL dir is refused. + assert!(distro_source("/mnt/wsl/kiri/roots/Debian/etc", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source("/mnt/wsl/kiri/sockets/Ubuntu", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source("/home/me", "../evil", Some(&w)).is_err()); + + // From Windows: `\\wsl.localhost\\...` is allowed when ``'s root is mounted. + let with_ubuntu = |d: &str| d.eq_ignore_ascii_case("Ubuntu").then(|| "/mnt/wsl/kiri/roots/Ubuntu".to_owned()); + assert_eq!( + source_with_roots(r"\\wsl.localhost\Ubuntu\home\alice\app", &w, with_ubuntu).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/home/alice/app" + ); + assert_eq!( + source_with_roots(r"\\wsl$\ubuntu\home\alice\..\..\etc", &w, with_ubuntu).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/etc" + ); + assert!(source_with_roots(r"\\wsl.localhost\Debian\home\alice", &w, with_ubuntu).is_err()); + } } diff --git a/crates/kiri/src/daemon/caller.rs b/crates/kiri/src/daemon/caller.rs index 795f879d7..6506f0382 100644 --- a/crates/kiri/src/daemon/caller.rs +++ b/crates/kiri/src/daemon/caller.rs @@ -26,12 +26,23 @@ use std::path::{Path, PathBuf}; /// Who is at the other end of an API connection. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum Caller { /// This machine's programs, on the daemon's own socket. Host, /// A container, through the VM's relay or its own socket. Container, + /// Another WSL 2 distro, on `/mnt/wsl/kiri/sockets//docker.sock`. + Wsl(String), +} + +impl Caller { + pub fn wsl_distro(&self) -> Option<&str> { + match self { + Caller::Wsl(distro) => Some(distro), + Caller::Host | Caller::Container => None, + } + } } /// The socket containers that mount the engine's are given, beside the diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index ca5f50dad..4d46d215f 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -251,6 +251,8 @@ pub fn run(_args: &[String]) -> io::Result<()> { let extra_sock: Option = None; watch_own_app(engine.clone(), socket.clone(), extra_sock.clone()); + init_wsl_sockets(engine.clone()); + let on_signal = engine.clone(); let sock = socket.clone(); std::thread::Builder::new().name("kiri-signals".into()).spawn(move || { @@ -265,6 +267,9 @@ pub fn run(_args: &[String]) -> io::Result<()> { if let Some(ref extra) = extra_sock { let _ = std::fs::remove_file(extra); } + if let Some(ws) = WSL_SOCKETS.get() { + ws.remove_socket_files(); + } on_signal.shutdown(); // Give the guest a moment to power off before the VM is released. std::thread::sleep(std::time::Duration::from_millis(50)); @@ -304,6 +309,7 @@ fn accept( for conn in listener.incoming() { let Ok(conn) = conn else { continue }; let engine = engine.clone(); + let who = who.clone(); #[cfg(target_os = "linux")] let gate = gate.clone(); let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { @@ -445,10 +451,219 @@ fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result apply_socket_gid(socket, Some(gid)) } +/// One WSL 2 distro enabled for WSL integration: its name and socket group GID. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct WslDistroConfig { + pub name: String, + pub gid: u32, +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct WslConfigFile { + #[serde(default)] + distros: Vec, +} + +struct ActiveWslSocket { + gid: u32, + dir: PathBuf, + socket: PathBuf, + stop: std::sync::Arc, +} + +/// Manages per-distro Unix sockets under `/mnt/wsl/kiri/sockets//docker.sock`. +/// Each socket has a `0750` parent directory and a `0660` socket file owned by +/// `0:`, tagging accepted HTTP requests with `Caller::Wsl("")`. +pub struct WslSockets { + base: PathBuf, + active: std::sync::Mutex>, + serve: std::sync::Arc, +} + +static WSL_SOCKETS: std::sync::OnceLock = std::sync::OnceLock::new(); + +fn wsl_base_dir() -> PathBuf { + PathBuf::from(binds::wsl_kiri_dir()) +} + +fn init_wsl_sockets(engine: std::sync::Arc) { + let ws = WSL_SOCKETS.get_or_init(|| { + WslSockets::new(wsl_base_dir(), move |conn, distro| { + let _ = api::serve(conn, engine.clone(), caller::Caller::Wsl(distro)); + }) + }); + if let Err(e) = ws.load_config() { + diag::warn!("WSL integration sockets not loaded", error = e); + } +} + +pub fn wsl_report() -> serde_json::Value { + let distros = WSL_SOCKETS.get().map_or_else(Vec::new, WslSockets::list); + serde_json::json!({ "distros": distros }) +} + +pub fn sync_wsl_sockets(distros: &[WslDistroConfig]) -> io::Result<()> { + let Some(ws) = WSL_SOCKETS.get() else { + return Err(io::Error::other("WSL socket manager is not initialized")); + }; + ws.sync(distros) +} + +fn chown_gid(path: &std::path::Path, gid: u32) -> io::Result<()> { + // SAFETY: geteuid only reads this process's effective user ID. + let uid = if unsafe { libc::geteuid() } == 0 { Some(0) } else { None }; + std::os::unix::fs::chown(path, uid, Some(gid)) +} + +impl WslSockets { + pub fn new(base: PathBuf, serve: impl Fn(UnixStream, String) + Send + Sync + 'static) -> Self { + WslSockets { + base, + active: std::sync::Mutex::new(std::collections::HashMap::new()), + serve: std::sync::Arc::new(serve), + } + } + + pub fn load_config(&self) -> io::Result<()> { + let cfg_path = self.base.join("config.json"); + if !cfg_path.is_file() { + return Ok(()); + } + let bytes = std::fs::read(&cfg_path)?; + let cfg: WslConfigFile = serde_json::from_slice(&bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("invalid {}: {e}", cfg_path.display())))?; + self.sync(&cfg.distros) + } + + pub fn list(&self) -> Vec { + let active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + let mut out: Vec = active + .iter() + .map(|(name, a)| WslDistroConfig { name: name.clone(), gid: a.gid }) + .collect(); + out.sort_by(|a, b| a.name.cmp(&b.name)); + out + } + + pub fn remove_socket_files(&self) { + let active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + for a in active.values() { + a.stop.store(true, std::sync::atomic::Ordering::SeqCst); + let _ = std::fs::remove_file(&a.socket); + let _ = std::fs::remove_dir(&a.dir); + } + } + + pub fn sync(&self, distros: &[WslDistroConfig]) -> io::Result<()> { + for d in distros { + if !binds::valid_distro_name(&d.name) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid WSL distro name: {}", d.name), + )); + } + } + let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + let wanted: std::collections::HashMap<&str, u32> = distros.iter().map(|d| (d.name.as_str(), d.gid)).collect(); + let remove_names: Vec = active + .iter() + .filter(|(name, a)| wanted.get(name.as_str()) != Some(&a.gid) || !a.socket.exists()) + .map(|(name, _)| name.clone()) + .collect(); + for name in remove_names { + if let Some(old) = active.remove(&name) { + old.stop.store(true, std::sync::atomic::Ordering::SeqCst); + let _ = UnixStream::connect(&old.socket); + let _ = std::fs::remove_file(&old.socket); + let _ = std::fs::remove_dir(&old.dir); + } + } + let sockets_dir = self.base.join("sockets"); + if let Ok(entries) = std::fs::read_dir(&sockets_dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name_str) = name.to_str() else { continue }; + if !wanted.contains_key(name_str) { + let p = entry.path(); + let _ = std::fs::remove_file(p.join("docker.sock")); + let _ = std::fs::remove_dir(&p); + } + } + } + if !distros.is_empty() { + let roots_dir = self.base.join("roots"); + for d in [&self.base, &sockets_dir, &roots_dir] { + std::fs::create_dir_all(d)?; + std::fs::set_permissions(d, std::fs::Permissions::from_mode(0o755))?; + } + } + for d in distros { + let dir = sockets_dir.join(&d.name); + let sock = dir.join("docker.sock"); + if active.contains_key(&d.name) { + chown_gid(&sock, d.gid)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660))?; + chown_gid(&dir, d.gid)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o750))?; + continue; + } + std::fs::create_dir_all(&dir)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?; + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600))?; + chown_gid(&sock, d.gid)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660))?; + chown_gid(&dir, d.gid)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o750))?; + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop_loop = stop.clone(); + let serve = self.serve.clone(); + let distro_name = d.name.clone(); + std::thread::Builder::new().name("kiri-api-wsl".into()).spawn(move || { + for conn in listener.incoming() { + if stop_loop.load(std::sync::atomic::Ordering::SeqCst) { + break; + } + let Ok(conn) = conn else { continue }; + if stop_loop.load(std::sync::atomic::Ordering::SeqCst) { + break; + } + let serve = serve.clone(); + let distro_name = distro_name.clone(); + let _ = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { + serve(conn, distro_name); + }); + } + })?; + active.insert( + d.name.clone(), + ActiveWslSocket { + gid: d.gid, + dir, + socket: sock, + stop, + }, + ); + } + if self.base.exists() { + let cfg_path = self.base.join("config.json"); + let tmp_path = self.base.join("config.json.tmp"); + let data = serde_json::to_vec(&WslConfigFile { distros: distros.to_vec() }).unwrap_or_default(); + if std::fs::write(&tmp_path, data).is_ok() { + let _ = std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600)); + let _ = std::fs::rename(&tmp_path, &cfg_path); + } + } + Ok(()) + } +} + #[cfg(test)] mod tests { use super::*; use std::ffi::OsStr; + use std::io::{Read, Write}; use std::os::unix::fs::MetadataExt; #[test] @@ -641,4 +856,40 @@ mod tests { let _ = listener; let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn per_distro_wsl_sockets_have_0660_permissions_and_clean_teardown_on_disable() { + let base = std::env::temp_dir().join(format!("kiri-wsl-sockets-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + // SAFETY: getegid only reads this process's effective group ID. + let gid = unsafe { libc::getegid() }; + let ws = WslSockets::new(base.clone(), |mut conn, distro| { + let _ = conn.write_all(distro.as_bytes()); + }); + ws.sync(&[WslDistroConfig { name: "Ubuntu".into(), gid }]).unwrap(); + + let dir = base.join("sockets/Ubuntu"); + let sock = dir.join("docker.sock"); + assert!(sock.exists()); + let dir_mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777; + let sock_mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o750, "parent directory must be 0750, got {dir_mode:o}"); + assert_eq!(sock_mode, 0o660, "socket must be 0660, got {sock_mode:o}"); + assert_ne!(sock_mode, 0o666, "socket must never be 0666"); + + let mut client = UnixStream::connect(&sock).unwrap(); + let mut tagged = String::new(); + client.read_to_string(&mut tagged).unwrap(); + assert_eq!(tagged, "Ubuntu"); + + // Disabling removes the socket and its parent directory cleanly. + ws.sync(&[]).unwrap(); + assert!(!sock.exists(), "socket must be removed when disabled"); + assert!(!dir.exists(), "parent dir must be removed when disabled"); + + // Path-traversal distro names are rejected. + assert!(ws.sync(&[WslDistroConfig { name: "../evil".into(), gid }]).is_err()); + + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 268b83335..e0593196c 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4459,6 +4459,16 @@

${tr("Use {app} for docker?", { app: esc(app) })}

`; } +function wslPane() { + const list = ui.res?.wsl_distros; + if (!WIN && !Array.isArray(list)) return ""; + if (!Array.isArray(list)) return `

${tr("WSL integration")}

${tr("Loading…")}

`; + if (!list.length) return `

${tr("WSL integration")}

${tr("No other WSL distros installed.")}

`; + const rows = list.map((w) => `
${esc(w.name)}${tr("docker, Compose and Docker-socket tools reach Kiri")} +
`).join(""); + return `

${tr("WSL integration")}

${rows}
`; +} + function renderSettings() { const tab = (id, icon, label) => ``; const opts = (list, current, system) => { @@ -4544,7 +4554,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

${tr("The name comes from the Igbo word ntakịrị, “small”.")}

`; const html = `
${tab("appearance", "textaa", tr("Appearance"))}${tab("resources", "stack", tr("Resources"))}${tab("network", "globe", tr("Network"))}${tab("builds", "hammer", tr("Builds"))}${tab("registries", "lock", tr("Registries"))}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", tr("Import"))}${tab("domains", "network", tr("Domains"))}${tab("diagnostics", "bug", tr("Diagnostics"))}${tab("about", "info", tr("About"))}
- ${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}
` : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}
`; + ${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}`; // The container lists arrive every few seconds; rebuilding an unchanged page // closes an open menu. The font menus list names in the interface font: an // option in its own font made WebKit load every installed font (438 here) @@ -8344,6 +8354,11 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-regsave]"))) { ui.regSaving = el.dataset.regsave; send("setregistryconfig", { value: { [REG_KEY[el.dataset.regsave]]: ui.regDraft[el.dataset.regsave] } }); } else if ((el = t("[data-saverp]")) && ui.rports && !ui.rports.error) send("setrouterports", { value: { http: +(ui.rpDraft.http ?? ui.rports.http.port), https: +(ui.rpDraft.https ?? ui.rports.https.port) } }); else if ((el = t("[data-saveres]"))) send("setresources", { value: ui.resDraft }); + else if ((el = t("[data-wsldistro]"))) { + const name = el.dataset.wsldistro, on = el.dataset.wslon === "1"; + const cur = ui.res?.wsl_distros?.find((d) => d.name === name); + if (cur && !!cur.on !== on) { cur.on = on; send("setresources", { value: { wsl_distro: name, on } }); render(); } + } else if ((el = t("[data-vmpower]"))) { el.disabled = true; powerEngine(el.dataset.vmpower); } else if ((el = t("[data-restartvm]"))) { el.disabled = true; el.textContent = tr("Restarting…"); send("restartvm"); } else if ((el = t("[data-detail]"))) openDetail(el.dataset.detail); diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index 8c755365d..44a46e068 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1854,5 +1854,7 @@ "Disk image size": "የዲስክ ምስል መጠን", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS፣ KIRI_MEMORY_MIB ወይም KIRI_DISK_GB ለዴሞኑ ተቀናብሯል፣ ከእነዚህም ቅድሚያ ይወስዳል።", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "አሁን በ{cpus}፣ እስከ {mem} እና በ{disk} ዲስክ እየሠራ ነው።", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፤ በፍጹም አይቀንስም። ዳግም ሲጀመር ተግባራዊ ይሆናል።" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፤ በፍጹም አይቀንስም። ዳግም ሲጀመር ተግባራዊ ይሆናል።", + "No other WSL distros installed.": "ሌሎች የWSL ስርጭቶች አልተጫኑም።", + "WSL integration": "የWSL ውህደት" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index daf85bb92..5f8b0475a 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1854,5 +1854,7 @@ "Disk image size": "حجم صورة القرص", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "المتغير KIRI_CPUS أو KIRI_MEMORY_MIB أو KIRI_DISK_GB معيّن للخدمة الخلفية، وله الأولوية على هذه الإعدادات.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "يعمل الآن بـ {cpus} وبحد أقصى {mem} وقرص بحجم {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ولا يتقلص الحجم أبداً. يُطبّق عند إعادة التشغيل." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ولا يتقلص الحجم أبداً. يُطبّق عند إعادة التشغيل.", + "No other WSL distros installed.": "لا توجد توزيعات WSL أخرى مثبّتة.", + "WSL integration": "تكامل WSL" } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 5489196e5..a7b285b06 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1854,5 +1854,7 @@ "Disk image size": "Размер на дисковия образ", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "За демона е зададена KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB и тя има предимство пред тези настройки.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Работи в момента с {cpus}, до {mem} и диск {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни; размерът никога не се свива. Прилага се при рестартиране." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни; размерът никога не се свива. Прилага се при рестартиране.", + "No other WSL distros installed.": "Няма други инсталирани WSL дистрибуции.", + "WSL integration": "Интеграция с WSL" } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 4b39fca4f..ecc22fa83 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1854,5 +1854,7 @@ "Disk image size": "ডিস্ক ইমেজের আকার", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "ডেমনের জন্য KIRI_CPUS, KIRI_MEMORY_MIB বা KIRI_DISK_GB সেট করা আছে, এবং সেগুলো এগুলোর চেয়ে অগ্রাধিকার পায়।", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "এখন {cpus}, সর্বোচ্চ {mem} ও {disk} ডিস্ক নিয়ে চলছে।", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়; এটি কখনো ছোট হয় না। রিস্টার্ট করলে প্রয়োগ হয়।" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়; এটি কখনো ছোট হয় না। রিস্টার্ট করলে প্রয়োগ হয়।", + "No other WSL distros installed.": "অন্য কোনো WSL ডিস্ট্রো ইনস্টল করা নেই।", + "WSL integration": "WSL ইন্টিগ্রেশন" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 161819362..a51e42831 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1854,5 +1854,7 @@ "Disk image size": "Mida de la imatge de disc", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB estan definits per al dimoni i tenen prioritat sobre aquests valors.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ara s'executa amb {cpus}, fins a {mem} i un disc de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades; no s'encongeix mai. S'aplica en reiniciar." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades; no s'encongeix mai. S'aplica en reiniciar.", + "No other WSL distros installed.": "No hi ha cap altra distribució de WSL instal·lada.", + "WSL integration": "Integració amb WSL" } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index 2678ad1e9..47b1b6b1b 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1854,5 +1854,7 @@ "Disk image size": "قەبارەی وێنەی دیسک", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یان KIRI_DISK_GB بۆ daemon دانراوە، و لەسەر ئەمانە پێشەنگی هەیە.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ئێستا بە {cpus}، تا {mem} و دیسکی {disk} کاردەکات.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت؛ هەرگیز بچووک نابێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت؛ هەرگیز بچووک نابێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت.", + "No other WSL distros installed.": "هیچ دابەشکراوێکی دیکەی WSL دانەمەزراوە.", + "WSL integration": "ئاوێتەکردنی WSL" } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index 8ba15be48..2ef87ca14 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1854,5 +1854,7 @@ "Disk image size": "Velikost obrazu disku", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Pro démona je nastaveno KIRI_CPUS, KIRI_MEMORY_MIB nebo KIRI_DISK_GB a to má přednost před těmito hodnotami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Teď běží s {cpus}, až {mem} a diskem {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat; nikdy se nezmenšuje. Použije se po restartu." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat; nikdy se nezmenšuje. Použije se po restartu.", + "No other WSL distros installed.": "Nejsou nainstalovány žádné další distribuce WSL.", + "WSL integration": "Integrace s WSL" } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index 3f776c0e6..e64f86e2e 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1854,5 +1854,7 @@ "Disk image size": "Größe des Festplattenimages", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB oder KIRI_DISK_GB ist für den Daemon gesetzt und hat Vorrang vor diesen Werten.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Läuft jetzt mit {cpus}, bis zu {mem} und einer {disk}-Festplatte.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt; die Größe schrumpft nie. Gilt nach einem Neustart." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt; die Größe schrumpft nie. Gilt nach einem Neustart.", + "No other WSL distros installed.": "Keine weiteren WSL-Distributionen installiert.", + "WSL integration": "WSL-Integration" } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 76444feab..f453cd233 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1854,5 +1854,7 @@ "Disk image size": "Μέγεθος εικόνας δίσκου", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Το KIRI_CPUS, το KIRI_MEMORY_MIB ή το KIRI_DISK_GB έχει οριστεί για τον daemon και υπερισχύει αυτών.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Εκτελείται τώρα με {cpus}, έως {mem} και δίσκο {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα και δεν μικραίνει ποτέ. Εφαρμόζεται κατά την επανεκκίνηση." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα και δεν μικραίνει ποτέ. Εφαρμόζεται κατά την επανεκκίνηση.", + "No other WSL distros installed.": "Δεν υπάρχουν άλλες εγκατεστημένες διανομές WSL.", + "WSL integration": "Ενσωμάτωση WSL" } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index e14b30c9f..e9efefe45 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1854,5 +1854,7 @@ "Disk image size": "Tamaño de la imagen de disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB está definida para el daemon y tiene prioridad sobre estos valores.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marcha ahora con {cpus}, hasta {mem} y un disco de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos; nunca se reduce. Se aplica al reiniciar." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos; nunca se reduce. Se aplica al reiniciar.", + "No other WSL distros installed.": "No hay otras distribuciones de WSL instaladas.", + "WSL integration": "Integración con WSL" } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index b6fb2721a..de6b34481 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1854,5 +1854,7 @@ "Disk image size": "اندازهٔ تصویر دیسک", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یا KIRI_DISK_GB برای سرویس پس‌زمینه تنظیم شده و بر این تنظیمات اولویت دارد.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "اکنون با {cpus}، حداکثر {mem} و دیسک {disk} در حال اجراست.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و هرگز کوچک نمی‌شود. پس از راه‌اندازی مجدد اعمال می‌شود." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و هرگز کوچک نمی‌شود. پس از راه‌اندازی مجدد اعمال می‌شود.", + "No other WSL distros installed.": "توزیع WSL دیگری نصب نشده است.", + "WSL integration": "یکپارچه‌سازی WSL" } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index 971ee5bc6..db14956c1 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1854,5 +1854,7 @@ "Disk image size": "Levykuvan koko", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemonille on asetettu KIRI_CPUS, KIRI_MEMORY_MIB tai KIRI_DISK_GB, ja ne menevät näiden edelle.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Käynnissä nyt: {cpus}, muistia enintään {mem}, levy {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, eikä levy koskaan pienene. Tulee voimaan uudelleenkäynnistyksessä." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, eikä levy koskaan pienene. Tulee voimaan uudelleenkäynnistyksessä.", + "No other WSL distros installed.": "Muita WSL-jakeluita ei ole asennettu.", + "WSL integration": "WSL-integraatio" } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 00e68ae37..1833708ed 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1854,5 +1854,7 @@ "Disk image size": "Taille de l’image disque", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB est défini pour le démon et prime sur ces réglages.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marche avec {cpus}, jusqu’à {mem} et un disque de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites ; il ne rétrécit jamais. Appliqué au redémarrage." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites ; il ne rétrécit jamais. Appliqué au redémarrage.", + "No other WSL distros installed.": "Aucune autre distribution WSL installée.", + "WSL integration": "Intégration WSL" } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 895c98f7f..ec3f07a90 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1854,5 +1854,7 @@ "Disk image size": "डिस्क इमेज का आकार", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "डेमन के लिए KIRI_CPUS, KIRI_MEMORY_MIB या KIRI_DISK_GB सेट है, और वह इनसे ऊपर लागू होता है।", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "अभी {cpus}, अधिकतम {mem} और {disk} डिस्क के साथ चल रहा है।", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है; यह कभी छोटा नहीं होता। रीस्टार्ट पर लागू होता है।" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है; यह कभी छोटा नहीं होता। रीस्टार्ट पर लागू होता है।", + "No other WSL distros installed.": "कोई अन्य WSL डिस्ट्रो इंस्टॉल नहीं है।", + "WSL integration": "WSL एकीकरण" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 89aa37ac9..0f461b815 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1854,5 +1854,7 @@ "Disk image size": "Lemezkép mérete", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "A démonnál be van állítva a KIRI_CPUS, a KIRI_MEMORY_MIB vagy a KIRI_DISK_GB, és ez felülírja ezeket.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Most így fut: {cpus}, legfeljebb {mem} memória és {disk} lemez.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), és soha nem zsugorodik. Újraindításkor lép életbe." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), és soha nem zsugorodik. Újraindításkor lép életbe.", + "No other WSL distros installed.": "Nincs más WSL-disztribúció telepítve.", + "WSL integration": "WSL-integráció" } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 19bc9a27d..6d85b62d7 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1854,5 +1854,7 @@ "Disk image size": "Ukuran image disk", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB, atau KIRI_DISK_GB diatur untuk daemon, dan lebih diutamakan daripada pengaturan ini.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Berjalan sekarang dengan {cpus}, hingga {mem}, dan disk {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis; ukurannya tidak pernah menyusut. Berlaku setelah mulai ulang." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis; ukurannya tidak pernah menyusut. Berlaku setelah mulai ulang.", + "No other WSL distros installed.": "Tidak ada distro WSL lain yang terinstal.", + "WSL integration": "Integrasi WSL" } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index a5309eca9..81d002cc6 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1854,5 +1854,7 @@ "Disk image size": "Dimensione immagine disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB è impostata per il daemon e ha la precedenza su questi valori.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ora in esecuzione con {cpus}, fino a {mem} e un disco da {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati; non si riduce mai. Si applica al riavvio." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati; non si riduce mai. Si applica al riavvio.", + "No other WSL distros installed.": "Nessun’altra distribuzione WSL installata.", + "WSL integration": "Integrazione WSL" } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index 2aac13bda..b76c9182e 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1854,5 +1854,7 @@ "Disk image size": "ディスクイメージのサイズ", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "デーモンに KIRI_CPUS、KIRI_MEMORY_MIB、または KIRI_DISK_GB が設定されており、こちらの設定より優先されます。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "現在 {cpus}、最大 {mem}、{disk} ディスクで実行中です。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、縮小することはありません。再起動時に適用されます。" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、縮小することはありません。再起動時に適用されます。", + "No other WSL distros installed.": "他の WSL ディストリビューションはインストールされていません。", + "WSL integration": "WSL 統合" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index e6f0e0aea..0097ae6e5 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1854,5 +1854,7 @@ "Disk image size": "Диск кескінінің өлшемі", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Демон үшін KIRI_CPUS, KIRI_MEMORY_MIB немесе KIRI_DISK_GB орнатылған және ол осы баптаулардан басым.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Қазір {cpus}, {mem} дейінгі жад және {disk} дискімен жұмыс істеп тұр.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады; ол ешқашан кішіреймейді. Қайта іске қосқанда қолданылады." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады; ол ешқашан кішіреймейді. Қайта іске қосқанда қолданылады.", + "No other WSL distros installed.": "Басқа WSL дистрибутивтері орнатылмаған.", + "WSL integration": "WSL интеграциясы" } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 5b28b139c..6b2bde392 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1854,5 +1854,7 @@ "Disk image size": "디스크 이미지 크기", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "데몬에 KIRI_CPUS, KIRI_MEMORY_MIB 또는 KIRI_DISK_GB가 설정되어 있어 이 값보다 우선합니다.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "지금 {cpus}, 최대 {mem}, {disk} 디스크로 실행 중입니다.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며 줄어들지 않습니다. 재시작 시 적용됩니다." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며 줄어들지 않습니다. 재시작 시 적용됩니다.", + "No other WSL distros installed.": "설치된 다른 WSL 배포판이 없습니다.", + "WSL integration": "WSL 통합" } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 965b6e55c..22dc6e92c 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1854,5 +1854,7 @@ "Disk image size": "ຂະໜາດອິມເມຈດິສກ໌", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ຫຼື KIRI_DISK_GB ຖືກຕັ້ງໄວ້ສຳລັບ daemon, ແລະ ມັນມີຜົນເໜືອກວ່າຄ່າເຫຼົ່ານີ້.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ຕອນນີ້ແລ່ນດ້ວຍ {cpus}, ສູງສຸດ {mem} ແລະ ດິສກ໌ {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ບໍ່ເຄີຍຫົດລົງ. ມີຜົນເມື່ອເລີ່ມໃໝ່." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ບໍ່ເຄີຍຫົດລົງ. ມີຜົນເມື່ອເລີ່ມໃໝ່.", + "No other WSL distros installed.": "ບໍ່ມີ WSL distro ອື່ນຕິດຕັ້ງຢู่.", + "WSL integration": "ການເຊື່ອມໂຍງ WSL" } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 8a5628a7e..438324a6c 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1854,5 +1854,7 @@ "Disk image size": "Disko atvaizdo dydis", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Tarnybai nustatytas KIRI_CPUS, KIRI_MEMORY_MIB arba KIRI_DISK_GB, ir jie turi pirmenybę prieš šiuos nustatymus.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Dabar veikia su {cpus}, iki {mem} ir {disk} disku.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis; diskas niekada nesumažėja. Pritaikoma paleidus iš naujo." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis; diskas niekada nesumažėja. Pritaikoma paleidus iš naujo.", + "No other WSL distros installed.": "Kitų WSL distribucijų neįdiegta.", + "WSL integration": "WSL integracija" } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index b97f466d0..b94292a2e 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1854,5 +1854,7 @@ "Disk image size": "Størrelse på diskbilde", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB eller KIRI_DISK_GB er satt for daemonen og har forrang foran disse.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Kjører nå med {cpus}, opptil {mem} og en disk på {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives; den krymper aldri. Gjelder ved omstart." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives; den krymper aldri. Gjelder ved omstart.", + "No other WSL distros installed.": "Ingen andre WSL-distribusjoner er installert.", + "WSL integration": "WSL-integrering" } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index 12f7f02f9..5475e49a8 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1854,5 +1854,7 @@ "Disk image size": "Rozmiar obrazu dysku", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Dla demona ustawiono KIRI_CPUS, KIRI_MEMORY_MIB lub KIRI_DISK_GB i to one mają pierwszeństwo przed tymi ustawieniami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Działa teraz z {cpus}, maks. {mem} i dyskiem {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych; dysk nigdy się nie zmniejsza. Działa po restarcie." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych; dysk nigdy się nie zmniejsza. Działa po restarcie.", + "No other WSL distros installed.": "Brak innych zainstalowanych dystrybucji WSL.", + "WSL integration": "Integracja z WSL" } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 36d4438e2..6a5d2020c 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1854,5 +1854,7 @@ "Disk image size": "Tamanho da imagem de disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB está definido para o daemon e tem prioridade sobre estes.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rodando agora com {cpus}, até {mem} e disco de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados; ele nunca encolhe. Aplica ao reiniciar." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados; ele nunca encolhe. Aplica ao reiniciar.", + "No other WSL distros installed.": "Nenhuma outra distribuição do WSL instalada.", + "WSL integration": "Integração com o WSL" } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index 679d9774a..bf5b2be88 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1854,5 +1854,7 @@ "Disk image size": "Dimensiunea imaginii de disc", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB sau KIRI_DISK_GB este setat pentru daemon și are prioritate față de acestea.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rulează acum cu {cpus}, până la {mem} și un disc de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date; nu se micșorează niciodată. Se aplică la repornire." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date; nu se micșorează niciodată. Se aplică la repornire.", + "No other WSL distros installed.": "Nu sunt instalate alte distribuții WSL.", + "WSL integration": "Integrare WSL" } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index a9573154b..c20951b31 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1854,5 +1854,7 @@ "Disk image size": "Размер образа диска", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задана переменная KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB, и она имеет приоритет над этими настройками.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Сейчас работает с {cpus}, до {mem} памяти и диском {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных; размер никогда не уменьшается. Применяется после перезапуска." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных; размер никогда не уменьшается. Применяется после перезапуска.", + "No other WSL distros installed.": "Другие дистрибутивы WSL не установлены.", + "WSL integration": "Интеграция с WSL" } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index b6157329d..4a2219ed7 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1854,5 +1854,7 @@ "Disk image size": "Velikost slike diska", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Za demon je nastavljen KIRI_CPUS, KIRI_MEMORY_MIB ali KIRI_DISK_GB, ki ima prednost pred temi nastavitvami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Zdaj teče s {cpus}, največ {mem} in diskom {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov; disk se nikoli ne skrči. Uveljavi se ob ponovnem zagonu." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov; disk se nikoli ne skrči. Uveljavi se ob ponovnem zagonu.", + "No other WSL distros installed.": "Nameščene ni nobene druge distribucije WSL.", + "WSL integration": "Integracija z WSL" } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index c92d55777..925448f1c 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1854,5 +1854,7 @@ "Disk image size": "Madhësia e imazhit të diskut", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ose KIRI_DISK_GB është vendosur për daemon-in dhe ka përparësi ndaj këtyre.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Tani në punë me {cpus}, deri në {mem} dhe disk {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna; nuk tkurret kurrë. Zbatohet pas rinisjes." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna; nuk tkurret kurrë. Zbatohet pas rinisjes.", + "No other WSL distros installed.": "Nuk ka shpërndarje të tjera WSL të instaluara.", + "WSL integration": "Integrimi me WSL" } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index d97b4e57c..1a4ac48e7 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1854,5 +1854,7 @@ "Disk image size": "வட்டுப் பட அளவு", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "டீமனுக்கு KIRI_CPUS, KIRI_MEMORY_MIB அல்லது KIRI_DISK_GB அமைக்கப்பட்டுள்ளது, அது இவற்றை விட முன்னுரிமை பெறும்.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "இப்போது {cpus}, அதிகபட்சம் {mem} மற்றும் {disk} வட்டுடன் இயங்குகிறது.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; இது ஒருபோதும் சுருங்காது. மறுதொடக்கத்தில் நடைமுறைக்கு வரும்." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; இது ஒருபோதும் சுருங்காது. மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", + "No other WSL distros installed.": "வேறு எந்த WSL விநியோகங்களும் நிறுவப்படவில்லை.", + "WSL integration": "WSL ஒருங்கிணைப்பு" } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 8a39cafe0..115ffd84d 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1854,5 +1854,7 @@ "Disk image size": "డిస్క్ ఇమేజ్ పరిమాణం", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "డెమన్‌కు KIRI_CPUS, KIRI_MEMORY_MIB లేదా KIRI_DISK_GB సెట్ చేయబడింది, అది వీటి కంటే ప్రాధాన్యం పొందుతుంది.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ఇప్పుడు {cpus}, గరిష్టంగా {mem}, {disk} డిస్క్‌తో రన్ అవుతోంది.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది; ఇది ఎప్పుడూ తగ్గదు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది; ఇది ఎప్పుడూ తగ్గదు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది.", + "No other WSL distros installed.": "ఇతర WSL డిస్ట్రోలు ఏవీ ఇన్‌స్టాల్ చేయబడలేదు.", + "WSL integration": "WSL ఇంటిగ్రేషన్" } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index 4bd17630a..a24283f93 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1854,5 +1854,7 @@ "Disk image size": "ขนาดอิมเมจดิสก์", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "มีการตั้งค่า KIRI_CPUS, KIRI_MEMORY_MIB หรือ KIRI_DISK_GB ให้ daemon ซึ่งมีลำดับความสำคัญเหนือค่าเหล่านี้", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ขณะนี้ทำงานด้วย {cpus} สูงสุด {mem} และดิสก์ {disk}", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และจะไม่หดเล็กลง มีผลเมื่อรีสตาร์ท" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และจะไม่หดเล็กลง มีผลเมื่อรีสตาร์ท", + "No other WSL distros installed.": "ไม่มีดิสโทร WSL อื่นติดตั้งอยู่", + "WSL integration": "การผสานรวม WSL" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index cc57defb3..a020b80dc 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1854,5 +1854,7 @@ "Disk image size": "Disk görüntüsü boyutu", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_CPUS, KIRI_MEMORY_MIB veya KIRI_DISK_GB ayarlı ve bunlar buradakilerden önceliklidir.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Şu anda {cpus}, en fazla {mem} ve {disk} disk ile çalışıyor.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; asla küçülmez. Yeniden başlatmada uygulanır." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; asla küçülmez. Yeniden başlatmada uygulanır.", + "No other WSL distros installed.": "Başka WSL dağıtımı kurulu değil.", + "WSL integration": "WSL entegrasyonu" } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 69ac6806c..738ea6aef 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1854,5 +1854,7 @@ "Disk image size": "Розмір образу диска", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задано змінну KIRI_CPUS, KIRI_MEMORY_MIB або KIRI_DISK_GB, і вона має пріоритет над цими налаштуваннями.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Зараз працює з {cpus}, до {mem} пам’яті та диском {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних; розмір ніколи не зменшується. Застосовується після перезапуску." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних; розмір ніколи не зменшується. Застосовується після перезапуску.", + "No other WSL distros installed.": "Інших дистрибутивів WSL не встановлено.", + "WSL integration": "Інтеграція з WSL" } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index 98baabfee..edc973ef2 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1854,5 +1854,7 @@ "Disk image size": "Kích thước ảnh đĩa", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB hoặc KIRI_DISK_GB đã được đặt cho daemon và được ưu tiên hơn các thiết lập này.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Đang chạy với {cpus}, tối đa {mem} và đĩa {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu; đĩa không bao giờ thu nhỏ. Áp dụng khi khởi động lại." + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu; đĩa không bao giờ thu nhỏ. Áp dụng khi khởi động lại.", + "No other WSL distros installed.": "Chưa cài đặt bản phân phối WSL nào khác.", + "WSL integration": "Tích hợp WSL" } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 221e0981f..1903e09c6 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1854,5 +1854,7 @@ "Disk image size": "磁盘镜像大小", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "守护进程设置了 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其优先级高于这里的设置。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "当前运行使用 {cpus}、内存最多 {mem}、{disk} 磁盘。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,且永不缩小。重启后生效。" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,且永不缩小。重启后生效。", + "No other WSL distros installed.": "未安装其他 WSL 发行版。", + "WSL integration": "WSL 集成" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index fc3514a00..222dc40eb 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1854,5 +1854,7 @@ "Disk image size": "磁碟映像大小", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "常駐程式已設定 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其優先順序高於這裡的設定。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "目前以 {cpus}、記憶體最多 {mem} 與 {disk} 磁碟執行。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,且永不縮小。重新啟動後生效。" + "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,且永不縮小。重新啟動後生效。", + "No other WSL distros installed.": "未安裝其他 WSL 發行版。", + "WSL integration": "WSL 整合" } diff --git a/docs/features.md b/docs/features.md index 9fd93d1e7..53591f880 100644 --- a/docs/features.md +++ b/docs/features.md @@ -150,7 +150,12 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr around `target/kiri-windows-x86_64`; `kiri.ps1` in that folder installs the same without an MSI). Not TCP: WSL's localhost relay drops half-closes, and `docker run` loses its - output + output. Settings → Resources → WSL integration exposes per-distro engine + sockets under `/mnt/wsl/kiri/sockets//docker.sock` (linked from + `/var/run/docker.sock` and a `kiri` Docker context when no `dockerd` is + running in that distro) and translates bind mounts from each enabled WSL 2 + distro's Linux filesystem through `/mnt/wsl/kiri/roots/` (off by + default; Windows paths like `\\wsl.localhost\\…` work too) Kubernetes LoadBalancer services are published on `localhost`, and `kiri machine create NAME --systemd` boots systemd as the machine's init. diff --git a/tests/ui/settingscolumn.js b/tests/ui/settingscolumn.js index b7556fbbb..678d9ea76 100644 --- a/tests/ui/settingscolumn.js +++ b/tests/ui/settingscolumn.js @@ -27,4 +27,22 @@ t("Resources: both sliders beside the tabs, not under them", () => { if (r.left < tabs.right) throw new Error(`${id} starts at ${Math.round(r.left)}, under the tabs`); } }); +t("Resources: WSL integration toggles distros and sits beside the tabs", () => { + kiri.on({ + type: "resources", cpus: 24, memory_mib: 65536, running_cpus: 24, running_memory_mib: 65536, + awake: true, max_cpus: 32, max_memory_mib: 130048, overridden: false, + wsl_distros: [{ name: "Ubuntu", on: false }, { name: "NixOS", on: true }], + }); + document.querySelector('[data-stab="resources"]').click(); + const tabs = document.querySelector(".settings .tabs").getBoundingClientRect(); + const btn = document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="1"]'); + if (!btn || btn.getAttribute("aria-pressed") !== "false") throw new Error("Ubuntu On button missing or already pressed"); + if (btn.getBoundingClientRect().left < tabs.right) throw new Error("WSL integration pane is under the tabs"); + btn.click(); + const after = document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="1"]'); + if (after?.getAttribute("aria-pressed") !== "true") throw new Error("Ubuntu toggle did not flip to On"); + if (!sent.some((m) => m.type === "setresources" && m.value?.wsl_distro === "Ubuntu" && m.value?.on === true)) { + throw new Error("did not send setresources for Ubuntu"); + } +}); report(R); diff --git a/tests/ui/wsl-integration.js b/tests/ui/wsl-integration.js new file mode 100644 index 000000000..f304666a6 --- /dev/null +++ b/tests/ui/wsl-integration.js @@ -0,0 +1,89 @@ +// Settings → Resources → WSL integration: empty state, distro list, +// toggling On/Off, no duplicate sends, and server round-trip updates. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; + +const baseRes = { + type: "resources", cpus: 8, memory_mib: 16384, running_cpus: 8, running_memory_mib: 16384, + awake: true, max_cpus: 16, max_memory_mib: 32768, overridden: false, +}; + +show("settings"); +document.querySelector('[data-stab="resources"]').click(); + +t("WSL pane hidden when wsl_distros is absent on non-Windows", () => { + kiri.on({ ...baseRes }); + if (document.querySelector("[data-wsldistro]")) throw new Error("unexpected distro toggle"); + const titles = [...document.querySelectorAll(".settings .pane h3")].map((h) => h.textContent.trim()); + if (titles.includes("WSL integration")) throw new Error("WSL integration pane shown without wsl_distros"); +}); + +t("WSL pane shows empty message when no other distros are installed", () => { + kiri.on({ ...baseRes, wsl_distros: [] }); + const panes = [...document.querySelectorAll(".settings .pane")]; + const wsl = panes.find((p) => p.querySelector("h3")?.textContent.trim() === "WSL integration"); + if (!wsl) throw new Error("WSL integration pane missing"); + if (!wsl.textContent.includes("No other WSL distros installed.")) { + throw new Error("missing empty-state text: " + wsl.textContent); + } +}); + +t("WSL pane renders distros, toggles On/Off, ignores no-op clicks, and reflects round-trip", () => { + sent.length = 0; + kiri.on({ + ...baseRes, + wsl_distros: [ + { name: "Ubuntu", on: false }, + { name: "NixOS", on: true }, + ], + }); + const tabs = document.querySelector(".settings .tabs").getBoundingClientRect(); + const ubuntuOff = document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="0"]'); + const ubuntuOn = document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="1"]'); + const nixosOn = document.querySelector('[data-wsldistro="NixOS"][data-wslon="1"]'); + const nixosOff = document.querySelector('[data-wsldistro="NixOS"][data-wslon="0"]'); + if (!ubuntuOff || !ubuntuOn || !nixosOn || !nixosOff) throw new Error("missing distro toggle buttons"); + if (ubuntuOn.getBoundingClientRect().left < tabs.right) throw new Error("WSL pane sits under tabs"); + if (ubuntuOff.getAttribute("aria-pressed") !== "true" || ubuntuOn.getAttribute("aria-pressed") !== "false") { + throw new Error("Ubuntu initial toggle state wrong"); + } + if (nixosOn.getAttribute("aria-pressed") !== "true" || nixosOff.getAttribute("aria-pressed") !== "false") { + throw new Error("NixOS initial toggle state wrong"); + } + + // Clicking already-active Off button does not send a message. + ubuntuOff.click(); + if (sent.length !== 0) throw new Error("clicking active Off button sent a message"); + + // Toggle Ubuntu On. + ubuntuOn.click(); + if (sent.length !== 1 || sent[0].type !== "setresources" || sent[0].value?.wsl_distro !== "Ubuntu" || sent[0].value?.on !== true) { + throw new Error("expected setresources { wsl_distro: 'Ubuntu', on: true }, got " + JSON.stringify(sent)); + } + if (document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="1"]')?.getAttribute("aria-pressed") !== "true") { + throw new Error("Ubuntu did not update optimistically to On"); + } + + // Toggle NixOS Off. + document.querySelector('[data-wsldistro="NixOS"][data-wslon="0"]').click(); + if (sent.length !== 2 || sent[1].type !== "setresources" || sent[1].value?.wsl_distro !== "NixOS" || sent[1].value?.on !== false) { + throw new Error("expected setresources { wsl_distro: 'NixOS', on: false }, got " + JSON.stringify(sent[1])); + } + + // Round-trip reply from host reconciles authoritative state (e.g., if Ubuntu stayed on and NixOS turned off). + kiri.on({ + ...baseRes, + wsl_distros: [ + { name: "Ubuntu", on: true }, + { name: "NixOS", on: false }, + ], + }); + if (document.querySelector('[data-wsldistro="Ubuntu"][data-wslon="1"]')?.getAttribute("aria-pressed") !== "true") { + throw new Error("Ubuntu not On after round-trip"); + } + if (document.querySelector('[data-wsldistro="NixOS"][data-wslon="0"]')?.getAttribute("aria-pressed") !== "true") { + throw new Error("NixOS not Off after round-trip"); + } +}); + +report(R); From 9ac386f4ff745c8d7ac43d8dc14c2a7045713385 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:28:11 +0100 Subject: [PATCH 043/157] UI: add Linux StatusNotifierItem tray and option to free WebView memory on close (#405, #168) (#826) Co-authored-by: Kotenkuu Co-authored-by: Urdemonlord --- crates/kiri-win/src/app.rs | 69 +- crates/kiri-win/src/engine.rs | 11 +- crates/kiri/src/ui/gtk.rs | 143 +++- crates/kiri/src/ui/index.html | 5 + crates/kiri/src/ui/lang/am.json | 5 +- crates/kiri/src/ui/lang/ar.json | 5 +- crates/kiri/src/ui/lang/bg.json | 5 +- crates/kiri/src/ui/lang/bn.json | 5 +- crates/kiri/src/ui/lang/ca.json | 5 +- crates/kiri/src/ui/lang/ckb.json | 5 +- crates/kiri/src/ui/lang/cs.json | 5 +- crates/kiri/src/ui/lang/de.json | 5 +- crates/kiri/src/ui/lang/el.json | 5 +- crates/kiri/src/ui/lang/es.json | 5 +- crates/kiri/src/ui/lang/fa.json | 5 +- crates/kiri/src/ui/lang/fi.json | 5 +- crates/kiri/src/ui/lang/fr.json | 5 +- crates/kiri/src/ui/lang/hi.json | 5 +- crates/kiri/src/ui/lang/hu.json | 5 +- crates/kiri/src/ui/lang/id.json | 5 +- crates/kiri/src/ui/lang/it.json | 5 +- crates/kiri/src/ui/lang/ja.json | 5 +- crates/kiri/src/ui/lang/kk.json | 5 +- crates/kiri/src/ui/lang/ko.json | 5 +- crates/kiri/src/ui/lang/lo.json | 5 +- crates/kiri/src/ui/lang/lt.json | 5 +- crates/kiri/src/ui/lang/nb.json | 5 +- crates/kiri/src/ui/lang/pl.json | 5 +- crates/kiri/src/ui/lang/pt-BR.json | 5 +- crates/kiri/src/ui/lang/ro.json | 5 +- crates/kiri/src/ui/lang/ru.json | 5 +- crates/kiri/src/ui/lang/sl.json | 5 +- crates/kiri/src/ui/lang/sq.json | 5 +- crates/kiri/src/ui/lang/ta.json | 5 +- crates/kiri/src/ui/lang/te.json | 5 +- crates/kiri/src/ui/lang/th.json | 5 +- crates/kiri/src/ui/lang/tr.json | 5 +- crates/kiri/src/ui/lang/uk.json | 5 +- crates/kiri/src/ui/lang/vi.json | 5 +- crates/kiri/src/ui/lang/zh-Hans.json | 5 +- crates/kiri/src/ui/lang/zh-Hant.json | 5 +- crates/kiri/src/ui/mac.rs | 98 ++- crates/kiri/src/ui/mod.rs | 14 +- crates/kiri/src/ui/sni.rs | 1135 ++++++++++++++++++++++++++ docs/features.md | 6 +- docs/fix-registry.md | 6 + tests/ui/closebutton.js | 23 + tests/ui/parity.js | 3 +- 48 files changed, 1610 insertions(+), 88 deletions(-) create mode 100644 crates/kiri/src/ui/sni.rs create mode 100644 tests/ui/closebutton.js diff --git a/crates/kiri-win/src/app.rs b/crates/kiri-win/src/app.rs index 9959a00d7..59b250a88 100644 --- a/crates/kiri-win/src/app.rs +++ b/crates/kiri-win/src/app.rs @@ -142,6 +142,13 @@ pub struct Ui { loaded: bool, /// The webview has been asked for. started: bool, + /// Counts the webviews asked for: one that arrives after the window + /// let go of it (closed while WebView2 was still making it) is dropped. + generation: u64, + /// The window let go of its webview (Settings → Closing the window → + /// Close): what the engine sends meanwhile is dropped, not queued, as + /// the page asks for everything again when it next loads. + released: bool, menu: Menu, /// Every message the page sends; called outside the borrow of UI. on_message: Rc, @@ -262,8 +269,8 @@ unsafe fn foreground(hwnd: HWND) { /// Shows the window, making its webview the first time. The webview is /// made outside the borrow of UI: its callbacks borrow it too. fn show() { - if let Some(Some(hwnd)) = with_ui(Ui::show) { - if let Err(e) = start_webview(hwnd) { + if let Some(Some((hwnd, generation))) = with_ui(Ui::show) { + if let Err(e) = start_webview(hwnd, generation) { crate::serve::log(&format!("webview: {e}")); } } @@ -278,12 +285,14 @@ impl Ui { // SAFETY: a live webview, on its own thread. let _ = unsafe { w.ExecuteScript(*js.as_ref().as_pcwstr(), &done) }; } + _ if self.released => {} _ => self.pending.push(js), } } - /// Shows the window; the window to make a webview for, the first time. - fn show(&mut self) -> Option { + /// Shows the window; the window to make a webview for (and which one + /// it is) when it has none. + fn show(&mut self) -> Option<(HWND, u64)> { // SAFETY: our window, on its thread. unsafe { let _ = ShowWindow(self.hwnd, SW_RESTORE); @@ -294,7 +303,12 @@ impl Ui { // whatever was behind it: once more, shortly. SetTimer(Some(self.hwnd), TIMER_FOREGROUND, 400, None); } - (!std::mem::replace(&mut self.started, true)).then_some(self.hwnd) + if std::mem::replace(&mut self.started, true) { + return None; + } + self.released = false; + self.generation += 1; + Some((self.hwnd, self.generation)) } pub fn hide(&mut self) { @@ -304,6 +318,35 @@ impl Ui { } } + /// The window's close button: hidden, as it always was, or (Settings → + /// Closing the window → Close) hidden and its webview let go, which ends + /// WebView2's processes. The tray icon and the pipe stay; the window + /// makes a new webview when it opens again. Setup's page keeps its + /// progress in the page, so the window only hides during setup. + fn close(&mut self) { + self.hide(); + if in_setup() || crate::engine::prefs()["closeButton"] != "close" { + return; + } + let controller = self.controller.take(); + self.webview = None; + self.started = false; + self.released = true; + self.loaded = false; + self.pending.clear(); + STRING_LOAD.set(false); + if let Some(c) = controller { + // SAFETY: our window's controller, on its thread. Its handlers + // find the window busy (with_ui gives None) and do nothing. + unsafe { + let _ = c.Close(); + } + } + // What the page followed (terminals, a log, live figures) goes + // with it, as when Linux's window closes. + crate::engine::page_gone(); + } + pub fn visible(&self) -> bool { // SAFETY: our window. unsafe { IsWindowVisible(self.hwnd).as_bool() } @@ -411,7 +454,7 @@ pub fn run(show: bool, setup: bool, on_message: impl Fn(String) + 'static, on_tr SendMessageW(hwnd, WM_SETICON, Some(WPARAM(ICON_SMALL as usize)), Some(LPARAM(i.0 as isize))); } } - UI.with(|u| *u.borrow_mut() = Some(Ui { hwnd, webview: None, controller: None, pending: Vec::new(), loaded: false, started: false, menu: Menu::default(), on_message: Rc::new(on_message) })); + UI.with(|u| *u.borrow_mut() = Some(Ui { hwnd, webview: None, controller: None, pending: Vec::new(), loaded: false, started: false, generation: 0, released: false, menu: Menu::default(), on_message: Rc::new(on_message) })); tray(hwnd, small, NIM_ADD); if show { self::show(); @@ -567,7 +610,7 @@ extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPA } } WM_SIZE => with_ui_soon(|ui| ui.resize()), - WM_CLOSE => with_ui_soon(Ui::hide), + WM_CLOSE => with_ui_soon(Ui::close), WM_TRAY => match (lparam.0 & 0xffff) as u32 { WM_LBUTTONUP => { if with_ui(|ui| ui.visible()) == Some(true) { @@ -598,7 +641,7 @@ fn data_dir() -> HSTRING { HSTRING::from(dir.as_os_str()) } -fn start_webview(hwnd: HWND) -> windows::core::Result<()> { +fn start_webview(hwnd: HWND, generation: u64) -> windows::core::Result<()> { let env_done = CreateCoreWebView2EnvironmentCompletedHandler::create(Box::new(move |result, env: Option| { result?; let Some(env) = env else { return Ok(()) }; @@ -606,7 +649,7 @@ fn start_webview(hwnd: HWND) -> windows::core::Result<()> { let ctl_done = CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |result, ctl: Option| { result?; if let Some(ctl) = ctl - && let Err(e) = webview_ready(hwnd, &env_for_page, ctl) + && let Err(e) = webview_ready(hwnd, generation, &env_for_page, ctl) { crate::serve::log(&format!("webview: {e}")); } @@ -619,7 +662,13 @@ fn start_webview(hwnd: HWND) -> windows::core::Result<()> { unsafe { CreateCoreWebView2EnvironmentWithOptions(PCWSTR::null(), &data_dir(), None, &env_done) } } -fn webview_ready(hwnd: HWND, env: &ICoreWebView2Environment, ctl: ICoreWebView2Controller) -> windows::core::Result<()> { +fn webview_ready(hwnd: HWND, generation: u64, env: &ICoreWebView2Environment, ctl: ICoreWebView2Controller) -> windows::core::Result<()> { + // Closed while WebView2 was making it: not wanted any more. A busy + // window (None) is one still showing, so it keeps the webview. + if with_ui(|ui| ui.started && ui.generation == generation) == Some(false) { + // SAFETY: the new controller, on the window's thread. + return unsafe { ctl.Close() }; + } // SAFETY: the new controller and its webview, on the window's thread. unsafe { let mut r = RECT::default(); diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 485a6b5fd..703e2ffa0 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -129,6 +129,15 @@ pub fn emit(json: String) { Handle.eval(format!("window.kiri && kiri.on({json})")); } +/// The window let go of its page (app.rs, Ui::close): the terminals, the +/// log and the live figures it followed end with it, as when Linux's window +/// closes. The page asks for what it needs again when it next loads. +pub fn page_gone() { + crate::term::handle("closeall", "", &Value::Null, emit); + crate::detail::stop_logs(); + crate::detail::stop_stats(); +} + pub fn notice(kind: &str, text: &str) -> String { json!({"type": "notice", "kind": kind, "text": text}).to_string() } @@ -930,7 +939,7 @@ fn set_pref(name: &str, value: Value) { crate::watch::set_enabled(crate::watch::is_enabled()); return; } - if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked") { + if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton") { return; } let Some(path) = prefs_path() else { return }; diff --git a/crates/kiri/src/ui/gtk.rs b/crates/kiri/src/ui/gtk.rs index 93dfe46c2..6af6a9cb5 100644 --- a/crates/kiri/src/ui/gtk.rs +++ b/crates/kiri/src/ui/gtk.rs @@ -3,8 +3,13 @@ //! `webkit.messageHandlers.kiri`, which WebKitGTK has too, and gets events //! through `kiri.on(...)`. //! -//! The window keeps the desktop's own title bar, as on Windows. Closing it -//! quits the window only: the engine is a system service and keeps running. +//! The window keeps the desktop's own title bar, as on Windows. While a +//! `StatusNotifierWatcher` is on the session bus (`sni.rs`), closing the +//! window hides it behind the tray icon (or, with Settings → Appearance → +//! Closing the window → Close, lets go of its WebKit view too so WebKit's +//! helper processes end). With no tray host on the desktop, closing the +//! window quits `kiri ui` as before. Either way the engine is a system +//! service and keeps running. use std::cell::RefCell; use std::ffi::{CStr, c_char, c_int, c_void}; @@ -23,12 +28,18 @@ thread_local! { /// The page and its window. Only ever touched on GTK's main thread. static WEBVIEW: RefCell> = const { RefCell::new(None) }; static WINDOW: RefCell> = const { RefCell::new(None) }; + /// Where a page made again (after the window let go of its own) sends + /// its messages. + static PAGE_TX: RefCell>> = const { RefCell::new(None) }; + /// Scripts for a page made again, kept until it says `ready`: the tray + /// menu's container items show the window and send at once. + static QUEUED: RefCell>> = const { RefCell::new(None) }; } /// Before the page's own scripts: which system this is. const SHIM: &str = r#"window.KIRI_OS = "linux";"#; -const ICON_PNG: &[u8] = include_bytes!("../../../../brand/icon/png/kiri-app-icon-512.png"); +pub(super) const ICON_PNG: &[u8] = include_bytes!("../../../../brand/icon/png/kiri-app-icon-512.png"); /// `autostart` starts the engine as soon as the page has loaded; `view` picks /// the sidebar section to open on. @@ -40,6 +51,8 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { let (tx, rx) = mpsc::channel(); let engine_tx = tx.clone(); let engine = std::thread::Builder::new().name("kiri-engine".into()).spawn(move || engine(rx, engine_tx))?; + PAGE_TX.with(|t| *t.borrow_mut() = Some(tx.clone())); + super::sni::start(tx.clone(), ICON_PNG); let window = gtk::Window::new(gtk::WindowType::Toplevel); window.set_title(crate::flavor::APP.get()); @@ -56,13 +69,45 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { window.set_size_request(760, 480); window.set_position(gtk::WindowPosition::Center); + let webview = make_webview(tx.clone(), autostart, view); + window.add(&webview); + // Before set_appearance, which gives it its background. + WEBVIEW.with(|v| *v.borrow_mut() = Some(webview)); + + set_appearance(prefs()["theme"].as_str().unwrap_or("system")); + let quit_tx = tx; + window.connect_delete_event(move |window, _| { + if super::sni::tray_available() { + window.hide(); + release_page(window); + return glib::Propagation::Stop; + } + let _ = quit_tx.send(Cmd::Quit); + gtk::main_quit(); + glib::Propagation::Proceed + }); + window.show_all(); + WINDOW.with(|v| *v.borrow_mut() = Some(window)); + gtk::main(); + let _ = engine.join(); + Ok(()) +} + +/// The page, in a new WebKitGTK view. +fn make_webview(tx: mpsc::Sender, autostart: bool, view: Option) -> WebView { let content = UserContentManager::new(); content.add_script(&UserScript::new(SHIM, UserContentInjectedFrames::TopFrame, UserScriptInjectionTime::Start, &[], &[])); content.register_script_message_handler("kiri"); - let page_tx = tx.clone(); content.connect_script_message_received(Some("kiri"), move |_, message| { if let Some(text) = message.js_value().map(|v| v.to_str()) { - super::handle(&text, &page_tx, autostart, view.as_deref()); + let text = text.to_string(); + // A page made again has loaded: what was sent meanwhile goes in now. + if serde_json::from_str::(&text).is_ok_and(|m| m["cmd"] == "ready") { + for js in QUEUED.with(|q| q.borrow_mut().take()).unwrap_or_default() { + eval(js); + } + } + super::handle(&text, &tx, autostart, view.as_deref()); } }); let webview = WebView::with_user_content_manager(&content); @@ -76,23 +121,32 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { whole_frames(&settings); settings.set_enable_write_console_messages_to_stdout(cfg!(debug_assertions)); } + let dark = match prefs()["theme"].as_str().unwrap_or("system") { + "dark" => true, + "light" => false, + _ => desktop_dark(), + }; + webview.set_background_color(&page_background(dark)); webview.load_html(&super::assemble::page(PAGE, super::prefs()["lang"].as_str()), None); - window.add(&webview); - // Before set_appearance, which gives it its background. - WEBVIEW.with(|v| *v.borrow_mut() = Some(webview)); + webview +} - set_appearance(prefs()["theme"].as_str().unwrap_or("system")); - let quit_tx = tx; - window.connect_delete_event(move |_, _| { - let _ = quit_tx.send(Cmd::Quit); - gtk::main_quit(); - glib::Propagation::Proceed - }); - window.show_all(); - WINDOW.with(|v| *v.borrow_mut() = Some(window)); - gtk::main(); - let _ = engine.join(); - Ok(()) +/// The window closed with Settings → Closing the window → Close while the tray +/// is up: it lets go of its WebKitGTK view, freeing `WebKitWebProcess` and +/// `WebKitNetworkProcess`. The tray and the engine thread stay; [`show`] makes +/// the page again. +fn release_page(window: >k::Window) { + if prefs()["closeButton"] != "close" { + return; + } + let Some(webview) = WEBVIEW.with(|v| v.borrow_mut().take()) else { return }; + QUEUED.with(|q| *q.borrow_mut() = None); + window.remove(&webview); + // SAFETY: `webview` was just removed from `window` and taken out of + // `WEBVIEW`, so nothing queries it after `gtk_widget_destroy`. + unsafe { webview.destroy() }; + drop(webview); + super::page_gone(); } /// Turns off WebKit's `PropagateDamagingInformation`. With it on and no GPU @@ -194,6 +248,14 @@ pub(super) fn relang() {} pub(super) fn eval(js: String) { glib::MainContext::default().invoke(move || { + let js = QUEUED.with(|q| match q.borrow_mut().as_mut() { + Some(queued) => { + queued.push(js); + None + } + None => Some(js), + }); + let Some(js) = js else { return }; WEBVIEW.with(|v| { if let Some(webview) = v.borrow().as_ref() { webview.evaluate_javascript(&js, None, None, None::<>k::gio::Cancellable>, |_| {}); @@ -202,17 +264,52 @@ pub(super) fn eval(js: String) { }); } -/// Closes the window, from any thread. -pub(super) fn quit() { +/// Shows the window again (from the tray's click or Open Kiri), making the +/// page again if closing the window let go of it. +pub(super) fn show() { glib::MainContext::default().invoke(|| { WINDOW.with(|v| { if let Some(window) = v.borrow().as_ref() { - window.close(); + if WEBVIEW.with(|w| w.borrow().is_none()) + && let Some(tx) = PAGE_TX.with(|t| t.borrow().clone()) + { + let webview = make_webview(tx, false, None); + QUEUED.with(|q| *q.borrow_mut() = Some(Vec::new())); + window.add(&webview); + webview.show(); + WEBVIEW.with(|w| *w.borrow_mut() = Some(webview)); + } + window.show(); + window.present(); } }); }); } +/// The tray host left the session bus or refused the item: a window closed +/// to the tray (hidden, or without its page) comes back, so there is never +/// neither a window nor a tray icon. +pub(super) fn tray_gone() { + glib::MainContext::default().invoke(|| { + let hidden = WINDOW.with(|v| v.borrow().as_ref().is_some_and(|w| !w.is_visible())); + if hidden || WEBVIEW.with(|w| w.borrow().is_none()) { + show(); + } + }); +} + +/// Quits the window and its engine thread, from any thread. +pub(super) fn quit() { + glib::MainContext::default().invoke(|| { + PAGE_TX.with(|t| { + if let Some(tx) = t.borrow().as_ref() { + let _ = tx.send(Cmd::Quit); + } + }); + gtk::main_quit(); + }); +} + /// The desktop's own title bar moves the window; the page's strip is not a handle here. pub(super) fn drag() {} diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index e0593196c..92011869e 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4506,6 +4506,10 @@

${tr("Use {app} for docker?", { app: esc(app) })}

${SIZES.map((z) => ``).join("")}
${tr("Log text")}${tr("Container, Kubernetes and diagnostics logs.")}
${LOG_SIZES.map(([px, l]) => ``).join("")}
+
${tr("Closing the window")}${prefs.closeButton === "close" + ? tr("Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.") + : tr("Hide: the window stays ready and opens again at once.")} +
web · nginx:alpine
Up 3 minutes · 26.3 MB · localhost:8080 → 80
ef9a6e2b45c2 docker run -p 8080:80 nginx
`; const portsPref = routerPortsPref(); @@ -8334,6 +8338,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if (diagClick(t)) {} else if ((el = t("[data-scale]"))) setPref("scale", +el.dataset.scale); else if ((el = t("[data-logsize]"))) setPref("logSize", +el.dataset.logsize); + else if ((el = t("[data-closebtn]"))) setPref("closeButton", el.dataset.closebtn); else if ((el = t("[data-theme-pick]"))) setPref("theme", el.dataset.themePick); else if ((el = t("[data-accent]"))) setPref("accent", el.dataset.accent); else if (t("[data-buildprune]")) { ui.bwPruning = true; send("buildprune"); render(); } diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index 44a46e068..e31755eeb 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "አሁን በ{cpus}፣ እስከ {mem} እና በ{disk} ዲስክ እየሠራ ነው።", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፤ በፍጹም አይቀንስም። ዳግም ሲጀመር ተግባራዊ ይሆናል።", "No other WSL distros installed.": "ሌሎች የWSL ስርጭቶች አልተጫኑም።", - "WSL integration": "የWSL ውህደት" + "WSL integration": "የWSL ውህደት", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ዝጋ፦ መስኮቱ የሚጠቀመው ማህደረ ትውስታ ይለቀቃል። እንደገና ለመክፈት ትንሽ ጊዜ ይወስዳል፣ የተከፈቱ ተርሚናሎችም ይዘጋሉ።", + "Closing the window": "መስኮቱን ሲዘጉ", + "Hide: the window stays ready and opens again at once.": "ደብቅ፦ መስኮቱ ዝግጁ ሆኖ ይቆያል፣ ወዲያውኑም እንደገና ይከፈታል።" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index 5f8b0475a..04701d3a5 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "يعمل الآن بـ {cpus} وبحد أقصى {mem} وقرص بحجم {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ولا يتقلص الحجم أبداً. يُطبّق عند إعادة التشغيل.", "No other WSL distros installed.": "لا توجد توزيعات WSL أخرى مثبّتة.", - "WSL integration": "تكامل WSL" + "WSL integration": "تكامل WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "إغلاق: تُحرَّر الذاكرة التي تستخدمها النافذة. تستغرق لحظة لتُفتح مجددًا، وتُنهى الطرفيات المفتوحة.", + "Closing the window": "عند إغلاق النافذة", + "Hide: the window stays ready and opens again at once.": "إخفاء: تبقى النافذة جاهزة وتُفتح مجددًا على الفور." } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index a7b285b06..646d09c4c 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Работи в момента с {cpus}, до {mem} и диск {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни; размерът никога не се свива. Прилага се при рестартиране.", "No other WSL distros installed.": "Няма други инсталирани WSL дистрибуции.", - "WSL integration": "Интеграция с WSL" + "WSL integration": "Интеграция с WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Затваряне: паметта, която прозорецът използва, се освобождава. Отварянето му отново отнема миг, а отворените терминали се затварят.", + "Closing the window": "Затваряне на прозореца", + "Hide: the window stays ready and opens again at once.": "Скриване: прозорецът остава готов и се отваря отново веднага." } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index ecc22fa83..9f2557414 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "এখন {cpus}, সর্বোচ্চ {mem} ও {disk} ডিস্ক নিয়ে চলছে।", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়; এটি কখনো ছোট হয় না। রিস্টার্ট করলে প্রয়োগ হয়।", "No other WSL distros installed.": "অন্য কোনো WSL ডিস্ট্রো ইনস্টল করা নেই।", - "WSL integration": "WSL ইন্টিগ্রেশন" + "WSL integration": "WSL ইন্টিগ্রেশন", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "বন্ধ করুন: উইন্ডোর ব্যবহৃত মেমরি মুক্ত হয়। আবার খুলতে একটু সময় লাগে, এবং খোলা টার্মিনালগুলো বন্ধ হয়ে যায়।", + "Closing the window": "উইন্ডো বন্ধ করলে", + "Hide: the window stays ready and opens again at once.": "লুকান: উইন্ডো প্রস্তুত থাকে এবং সঙ্গে সঙ্গে আবার খোলে।" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index a51e42831..7d7525e71 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ara s'executa amb {cpus}, fins a {mem} i un disc de {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades; no s'encongeix mai. S'aplica en reiniciar.", "No other WSL distros installed.": "No hi ha cap altra distribució de WSL instal·lada.", - "WSL integration": "Integració amb WSL" + "WSL integration": "Integració amb WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tanca: s’allibera la memòria que fa servir la finestra. Tarda un moment a tornar-se a obrir, i els terminals oberts es tanquen.", + "Closing the window": "En tancar la finestra", + "Hide: the window stays ready and opens again at once.": "Amaga: la finestra es manté a punt i es torna a obrir a l’instant." } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index 47b1b6b1b..c90f21cf4 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ئێستا بە {cpus}، تا {mem} و دیسکی {disk} کاردەکات.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت؛ هەرگیز بچووک نابێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت.", "No other WSL distros installed.": "هیچ دابەشکراوێکی دیکەی WSL دانەمەزراوە.", - "WSL integration": "ئاوێتەکردنی WSL" + "WSL integration": "ئاوێتەکردنی WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "داخستن: ئەو بیرگەیەی پەنجەرەکە بەکاری دەهێنێت ئازاد دەکرێت. کردنەوەی دووبارەی کەمێک کات دەبات، و تێرمیناڵە کراوەکان کۆتاییان دێت.", + "Closing the window": "داخستنی پەنجەرە", + "Hide: the window stays ready and opens again at once.": "شاردنەوە: پەنجەرەکە ئامادە دەمێنێتەوە و دەستبەجێ دەکرێتەوە." } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index 2ef87ca14..211df2b14 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Teď běží s {cpus}, až {mem} a diskem {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat; nikdy se nezmenšuje. Použije se po restartu.", "No other WSL distros installed.": "Nejsou nainstalovány žádné další distribuce WSL.", - "WSL integration": "Integrace s WSL" + "WSL integration": "Integrace s WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zavřít: paměť, kterou okno používá, se uvolní. Znovu se otevře až po chvilce a otevřené terminály se ukončí.", + "Closing the window": "Zavření okna", + "Hide: the window stays ready and opens again at once.": "Skrýt: okno zůstane připravené a znovu se otevře hned." } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index e64f86e2e..dc1d25faf 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Läuft jetzt mit {cpus}, bis zu {mem} und einer {disk}-Festplatte.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt; die Größe schrumpft nie. Gilt nach einem Neustart.", "No other WSL distros installed.": "Keine weiteren WSL-Distributionen installiert.", - "WSL integration": "WSL-Integration" + "WSL integration": "WSL-Integration", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Schließen: Der Speicher des Fensters wird freigegeben. Es braucht einen Moment, um wieder zu öffnen, und offene Terminals werden beendet.", + "Closing the window": "Beim Schließen des Fensters", + "Hide: the window stays ready and opens again at once.": "Ausblenden: Das Fenster bleibt bereit und öffnet sich sofort wieder." } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index f453cd233..627715548 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Εκτελείται τώρα με {cpus}, έως {mem} και δίσκο {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα και δεν μικραίνει ποτέ. Εφαρμόζεται κατά την επανεκκίνηση.", "No other WSL distros installed.": "Δεν υπάρχουν άλλες εγκατεστημένες διανομές WSL.", - "WSL integration": "Ενσωμάτωση WSL" + "WSL integration": "Ενσωμάτωση WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Κλείσιμο: η μνήμη που χρησιμοποιεί το παράθυρο ελευθερώνεται. Χρειάζεται μια στιγμή για να ανοίξει ξανά, και τα ανοιχτά τερματικά τερματίζονται.", + "Closing the window": "Κλείσιμο του παραθύρου", + "Hide: the window stays ready and opens again at once.": "Απόκρυψη: το παράθυρο μένει έτοιμο και ανοίγει ξανά αμέσως." } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index e9efefe45..98d5e95c4 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marcha ahora con {cpus}, hasta {mem} y un disco de {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos; nunca se reduce. Se aplica al reiniciar.", "No other WSL distros installed.": "No hay otras distribuciones de WSL instaladas.", - "WSL integration": "Integración con WSL" + "WSL integration": "Integración con WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Cerrar: se libera la memoria que usa la ventana. Tarda un momento en volver a abrirse y los terminales abiertos se cierran.", + "Closing the window": "Al cerrar la ventana", + "Hide: the window stays ready and opens again at once.": "Ocultar: la ventana sigue lista y se abre de nuevo al instante." } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index de6b34481..911676834 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "اکنون با {cpus}، حداکثر {mem} و دیسک {disk} در حال اجراست.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و هرگز کوچک نمی‌شود. پس از راه‌اندازی مجدد اعمال می‌شود.", "No other WSL distros installed.": "توزیع WSL دیگری نصب نشده است.", - "WSL integration": "یکپارچه‌سازی WSL" + "WSL integration": "یکپارچه‌سازی WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "بستن: حافظه‌ای که پنجره مصرف می‌کند آزاد می‌شود. باز شدن دوباره‌اش کمی طول می‌کشد و ترمینال‌های باز بسته می‌شوند.", + "Closing the window": "بستن پنجره", + "Hide: the window stays ready and opens again at once.": "پنهان کردن: پنجره آماده می‌ماند و بی‌درنگ دوباره باز می‌شود." } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index db14956c1..c6021bf1f 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Käynnissä nyt: {cpus}, muistia enintään {mem}, levy {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, eikä levy koskaan pienene. Tulee voimaan uudelleenkäynnistyksessä.", "No other WSL distros installed.": "Muita WSL-jakeluita ei ole asennettu.", - "WSL integration": "WSL-integraatio" + "WSL integration": "WSL-integraatio", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Sulje: ikkunan käyttämä muisti vapautetaan. Uudelleen avautuminen kestää hetken, ja avoimet päätteet suljetaan.", + "Closing the window": "Ikkunan sulkeminen", + "Hide: the window stays ready and opens again at once.": "Piilota: ikkuna pysyy valmiina ja avautuu heti uudelleen." } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 1833708ed..a1e1d38bd 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marche avec {cpus}, jusqu’à {mem} et un disque de {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites ; il ne rétrécit jamais. Appliqué au redémarrage.", "No other WSL distros installed.": "Aucune autre distribution WSL installée.", - "WSL integration": "Intégration WSL" + "WSL integration": "Intégration WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fermer : la mémoire utilisée par la fenêtre est libérée. Elle met un instant à se rouvrir, et les terminaux ouverts se ferment.", + "Closing the window": "Fermeture de la fenêtre", + "Hide: the window stays ready and opens again at once.": "Masquer : la fenêtre reste prête et se rouvre aussitôt." } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index ec3f07a90..6f476c585 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "अभी {cpus}, अधिकतम {mem} और {disk} डिस्क के साथ चल रहा है।", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है; यह कभी छोटा नहीं होता। रीस्टार्ट पर लागू होता है।", "No other WSL distros installed.": "कोई अन्य WSL डिस्ट्रो इंस्टॉल नहीं है।", - "WSL integration": "WSL एकीकरण" + "WSL integration": "WSL एकीकरण", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "बंद करें: विंडो की इस्तेमाल की गई मेमोरी खाली हो जाती है। फिर से खुलने में थोड़ा समय लगता है, और खुले टर्मिनल बंद हो जाते हैं।", + "Closing the window": "विंडो बंद करने पर", + "Hide: the window stays ready and opens again at once.": "छिपाएँ: विंडो तैयार रहती है और तुरंत फिर से खुलती है।" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 0f461b815..a1e39316b 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Most így fut: {cpus}, legfeljebb {mem} memória és {disk} lemez.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), és soha nem zsugorodik. Újraindításkor lép életbe.", "No other WSL distros installed.": "Nincs más WSL-disztribúció telepítve.", - "WSL integration": "WSL-integráció" + "WSL integration": "WSL-integráció", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Bezárás: az ablak által használt memória felszabadul. Újbóli megnyitása egy pillanatig tart, a nyitott terminálok pedig bezárulnak.", + "Closing the window": "Az ablak bezárásakor", + "Hide: the window stays ready and opens again at once.": "Elrejtés: az ablak készenlétben marad, és azonnal újra megnyílik." } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 6d85b62d7..c93975655 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Berjalan sekarang dengan {cpus}, hingga {mem}, dan disk {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis; ukurannya tidak pernah menyusut. Berlaku setelah mulai ulang.", "No other WSL distros installed.": "Tidak ada distro WSL lain yang terinstal.", - "WSL integration": "Integrasi WSL" + "WSL integration": "Integrasi WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tutup: memori yang dipakai jendela dibebaskan. Perlu sesaat untuk membukanya lagi, dan terminal yang terbuka ditutup.", + "Closing the window": "Saat menutup jendela", + "Hide: the window stays ready and opens again at once.": "Sembunyikan: jendela tetap siap dan langsung terbuka lagi." } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 81d002cc6..16db90d1c 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ora in esecuzione con {cpus}, fino a {mem} e un disco da {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati; non si riduce mai. Si applica al riavvio.", "No other WSL distros installed.": "Nessun’altra distribuzione WSL installata.", - "WSL integration": "Integrazione WSL" + "WSL integration": "Integrazione WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Chiudi: la memoria usata dalla finestra viene liberata. Ci vuole un attimo per riaprirla e i terminali aperti si chiudono.", + "Closing the window": "Chiusura della finestra", + "Hide: the window stays ready and opens again at once.": "Nascondi: la finestra resta pronta e si riapre subito." } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index b76c9182e..479592ed4 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "現在 {cpus}、最大 {mem}、{disk} ディスクで実行中です。", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、縮小することはありません。再起動時に適用されます。", "No other WSL distros installed.": "他の WSL ディストリビューションはインストールされていません。", - "WSL integration": "WSL 統合" + "WSL integration": "WSL 統合", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "閉じる:ウインドウが使うメモリを解放します。再び開くまでに少し時間がかかり、開いているターミナルは終了します。", + "Closing the window": "ウインドウを閉じたとき", + "Hide: the window stays ready and opens again at once.": "隠す:ウインドウは準備されたまま残り、すぐに再び開きます。" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 0097ae6e5..c479594ce 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Қазір {cpus}, {mem} дейінгі жад және {disk} дискімен жұмыс істеп тұр.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады; ол ешқашан кішіреймейді. Қайта іске қосқанда қолданылады.", "No other WSL distros installed.": "Басқа WSL дистрибутивтері орнатылмаған.", - "WSL integration": "WSL интеграциясы" + "WSL integration": "WSL интеграциясы", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Жабу: терезе пайдаланатын жад босатылады. Қайта ашылуына біраз уақыт кетеді, ал ашық терминалдар жабылады.", + "Closing the window": "Терезені жапқанда", + "Hide: the window stays ready and opens again at once.": "Жасыру: терезе дайын күйде қалады және бірден қайта ашылады." } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 6b2bde392..9569db397 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "지금 {cpus}, 최대 {mem}, {disk} 디스크로 실행 중입니다.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며 줄어들지 않습니다. 재시작 시 적용됩니다.", "No other WSL distros installed.": "설치된 다른 WSL 배포판이 없습니다.", - "WSL integration": "WSL 통합" + "WSL integration": "WSL 통합", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "닫기: 창이 쓰는 메모리를 해제합니다. 다시 여는 데 잠시 걸리며, 열려 있는 터미널은 종료됩니다.", + "Closing the window": "창을 닫을 때", + "Hide: the window stays ready and opens again at once.": "숨기기: 창이 준비된 채로 남아 바로 다시 열립니다." } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 22dc6e92c..5b57ebab5 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ຕອນນີ້ແລ່ນດ້ວຍ {cpus}, ສູງສຸດ {mem} ແລະ ດິສກ໌ {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ບໍ່ເຄີຍຫົດລົງ. ມີຜົນເມື່ອເລີ່ມໃໝ່.", "No other WSL distros installed.": "ບໍ່ມີ WSL distro ອື່ນຕິດຕັ້ງຢู่.", - "WSL integration": "ການເຊື່ອມໂຍງ WSL" + "WSL integration": "ການເຊື່ອມໂຍງ WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ປິດ: ໜ່ວຍຄວາມຈຳທີ່ໜ້າຕ່າງໃຊ້ຈະຖືກປ່ອຍຄືນ. ການເປີດຄືນຈະໃຊ້ເວລາໜ້ອຍໜຶ່ງ ແລະ ເທີມິນອນທີ່ເປີດຢູ່ຈະຖືກປິດ.", + "Closing the window": "ເມື່ອປິດໜ້າຕ່າງ", + "Hide: the window stays ready and opens again at once.": "ເຊື່ອງ: ໜ້າຕ່າງຈະກຽມພ້ອມໄວ້ ແລະ ເປີດຄືນໄດ້ທັນທີ." } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 438324a6c..92845dd8b 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Dabar veikia su {cpus}, iki {mem} ir {disk} disku.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis; diskas niekada nesumažėja. Pritaikoma paleidus iš naujo.", "No other WSL distros installed.": "Kitų WSL distribucijų neįdiegta.", - "WSL integration": "WSL integracija" + "WSL integration": "WSL integracija", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Uždaryti: lango naudojama atmintis atlaisvinama. Vėl atsidaryti užtrunka akimirką, o atviri terminalai užbaigiami.", + "Closing the window": "Uždarant langą", + "Hide: the window stays ready and opens again at once.": "Slėpti: langas lieka paruoštas ir iškart atsidaro vėl." } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index b94292a2e..48325a36f 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Kjører nå med {cpus}, opptil {mem} og en disk på {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives; den krymper aldri. Gjelder ved omstart.", "No other WSL distros installed.": "Ingen andre WSL-distribusjoner er installert.", - "WSL integration": "WSL-integrering" + "WSL integration": "WSL-integrering", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Lukk: minnet vinduet bruker, frigjøres. Det tar et øyeblikk å åpne det igjen, og åpne terminaler avsluttes.", + "Closing the window": "Når vinduet lukkes", + "Hide: the window stays ready and opens again at once.": "Skjul: vinduet holdes klart og åpnes igjen med en gang." } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index 5475e49a8..5c8edd1d2 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Działa teraz z {cpus}, maks. {mem} i dyskiem {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych; dysk nigdy się nie zmniejsza. Działa po restarcie.", "No other WSL distros installed.": "Brak innych zainstalowanych dystrybucji WSL.", - "WSL integration": "Integracja z WSL" + "WSL integration": "Integracja z WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zamknij: pamięć używana przez okno zostaje zwolniona. Ponowne otwarcie zajmuje chwilę, a otwarte terminale zostają zakończone.", + "Closing the window": "Zamykanie okna", + "Hide: the window stays ready and opens again at once.": "Ukryj: okno pozostaje gotowe i od razu otwiera się ponownie." } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 6a5d2020c..2a9644458 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rodando agora com {cpus}, até {mem} e disco de {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados; ele nunca encolhe. Aplica ao reiniciar.", "No other WSL distros installed.": "Nenhuma outra distribuição do WSL instalada.", - "WSL integration": "Integração com o WSL" + "WSL integration": "Integração com o WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fechar: a memória usada pela janela é liberada. Leva um momento para abrir de novo, e os terminais abertos são encerrados.", + "Closing the window": "Ao fechar a janela", + "Hide: the window stays ready and opens again at once.": "Ocultar: a janela continua pronta e abre de novo na hora." } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index bf5b2be88..83537c114 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rulează acum cu {cpus}, până la {mem} și un disc de {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date; nu se micșorează niciodată. Se aplică la repornire.", "No other WSL distros installed.": "Nu sunt instalate alte distribuții WSL.", - "WSL integration": "Integrare WSL" + "WSL integration": "Integrare WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Închide: memoria folosită de fereastră este eliberată. Redeschiderea durează o clipă, iar terminalele deschise se închid.", + "Closing the window": "La închiderea ferestrei", + "Hide: the window stays ready and opens again at once.": "Ascunde: fereastra rămâne pregătită și se redeschide imediat." } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index c20951b31..1f6515fb5 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Сейчас работает с {cpus}, до {mem} памяти и диском {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных; размер никогда не уменьшается. Применяется после перезапуска.", "No other WSL distros installed.": "Другие дистрибутивы WSL не установлены.", - "WSL integration": "Интеграция с WSL" + "WSL integration": "Интеграция с WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрыть: память, которую занимает окно, освобождается. Повторное открытие занимает мгновение, а открытые терминалы закрываются.", + "Closing the window": "При закрытии окна", + "Hide: the window stays ready and opens again at once.": "Скрыть: окно остаётся готовым и сразу открывается снова." } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index 4a2219ed7..ac9b3b64f 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Zdaj teče s {cpus}, največ {mem} in diskom {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov; disk se nikoli ne skrči. Uveljavi se ob ponovnem zagonu.", "No other WSL distros installed.": "Nameščene ni nobene druge distribucije WSL.", - "WSL integration": "Integracija z WSL" + "WSL integration": "Integracija z WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zapri: pomnilnik, ki ga uporablja okno, se sprosti. Ponovno odpiranje traja trenutek, odprti terminali pa se končajo.", + "Closing the window": "Ob zapiranju okna", + "Hide: the window stays ready and opens again at once.": "Skrij: okno ostane pripravljeno in se takoj znova odpre." } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 925448f1c..131b4c99d 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Tani në punë me {cpus}, deri në {mem} dhe disk {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna; nuk tkurret kurrë. Zbatohet pas rinisjes.", "No other WSL distros installed.": "Nuk ka shpërndarje të tjera WSL të instaluara.", - "WSL integration": "Integrimi me WSL" + "WSL integration": "Integrimi me WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Mbyll: memoria që përdor dritarja lirohet. Rihapja zgjat një çast dhe terminalet e hapura mbyllen.", + "Closing the window": "Kur mbyllet dritarja", + "Hide: the window stays ready and opens again at once.": "Fshih: dritarja mbetet gati dhe hapet sërish menjëherë." } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index 1a4ac48e7..d8b81bce5 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "இப்போது {cpus}, அதிகபட்சம் {mem} மற்றும் {disk} வட்டுடன் இயங்குகிறது.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; இது ஒருபோதும் சுருங்காது. மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", "No other WSL distros installed.": "வேறு எந்த WSL விநியோகங்களும் நிறுவப்படவில்லை.", - "WSL integration": "WSL ஒருங்கிணைப்பு" + "WSL integration": "WSL ஒருங்கிணைப்பு", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "மூடு: சாளரம் பயன்படுத்தும் நினைவகம் விடுவிக்கப்படும். மீண்டும் திறக்கச் சற்று நேரமாகும், திறந்திருக்கும் டெர்மினல்கள் முடிவடையும்.", + "Closing the window": "சாளரத்தை மூடும்போது", + "Hide: the window stays ready and opens again at once.": "மறை: சாளரம் தயாராக இருந்து உடனே மீண்டும் திறக்கும்." } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 115ffd84d..7cc00c1bd 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ఇప్పుడు {cpus}, గరిష్టంగా {mem}, {disk} డిస్క్‌తో రన్ అవుతోంది.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది; ఇది ఎప్పుడూ తగ్గదు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది.", "No other WSL distros installed.": "ఇతర WSL డిస్ట్రోలు ఏవీ ఇన్‌స్టాల్ చేయబడలేదు.", - "WSL integration": "WSL ఇంటిగ్రేషన్" + "WSL integration": "WSL ఇంటిగ్రేషన్", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "మూసివేయి: విండో వాడే మెమరీ విడుదల అవుతుంది. మళ్లీ తెరవడానికి కొంత సమయం పడుతుంది, తెరిచి ఉన్న టెర్మినల్స్ ముగుస్తాయి.", + "Closing the window": "విండోను మూసినప్పుడు", + "Hide: the window stays ready and opens again at once.": "దాచు: విండో సిద్ధంగా ఉండి వెంటనే మళ్లీ తెరుచుకుంటుంది." } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index a24283f93..da0293186 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ขณะนี้ทำงานด้วย {cpus} สูงสุด {mem} และดิสก์ {disk}", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และจะไม่หดเล็กลง มีผลเมื่อรีสตาร์ท", "No other WSL distros installed.": "ไม่มีดิสโทร WSL อื่นติดตั้งอยู่", - "WSL integration": "การผสานรวม WSL" + "WSL integration": "การผสานรวม WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ปิด: คืนหน่วยความจำที่หน้าต่างใช้ การเปิดอีกครั้งจะใช้เวลาสักครู่ และเทอร์มินัลที่เปิดอยู่จะถูกปิด", + "Closing the window": "เมื่อปิดหน้าต่าง", + "Hide: the window stays ready and opens again at once.": "ซ่อน: หน้าต่างพร้อมอยู่เสมอและเปิดกลับมาได้ทันที" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index a020b80dc..dca339ea9 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Şu anda {cpus}, en fazla {mem} ve {disk} disk ile çalışıyor.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; asla küçülmez. Yeniden başlatmada uygulanır.", "No other WSL distros installed.": "Başka WSL dağıtımı kurulu değil.", - "WSL integration": "WSL entegrasyonu" + "WSL integration": "WSL entegrasyonu", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Kapat: pencerenin kullandığı bellek boşaltılır. Yeniden açılması biraz sürer ve açık terminaller kapanır.", + "Closing the window": "Pencere kapatılınca", + "Hide: the window stays ready and opens again at once.": "Gizle: pencere hazır bekler ve hemen yeniden açılır." } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 738ea6aef..7ee82e07b 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Зараз працює з {cpus}, до {mem} пам’яті та диском {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних; розмір ніколи не зменшується. Застосовується після перезапуску.", "No other WSL distros installed.": "Інших дистрибутивів WSL не встановлено.", - "WSL integration": "Інтеграція з WSL" + "WSL integration": "Інтеграція з WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрити: пам’ять, яку займає вікно, звільняється. Повторне відкриття триває мить, а відкриті термінали закриваються.", + "Closing the window": "Закриття вікна", + "Hide: the window stays ready and opens again at once.": "Приховати: вікно залишається готовим і одразу відкривається знову." } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index edc973ef2..fd82cad0e 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Đang chạy với {cpus}, tối đa {mem} và đĩa {disk}.", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu; đĩa không bao giờ thu nhỏ. Áp dụng khi khởi động lại.", "No other WSL distros installed.": "Chưa cài đặt bản phân phối WSL nào khác.", - "WSL integration": "Tích hợp WSL" + "WSL integration": "Tích hợp WSL", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Đóng: giải phóng bộ nhớ cửa sổ đang dùng. Mở lại sẽ mất một lúc, và các terminal đang mở sẽ bị đóng.", + "Closing the window": "Khi đóng cửa sổ", + "Hide: the window stays ready and opens again at once.": "Ẩn: cửa sổ luôn sẵn sàng và mở lại ngay." } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 1903e09c6..942faa6c3 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "当前运行使用 {cpus}、内存最多 {mem}、{disk} 磁盘。", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,且永不缩小。重启后生效。", "No other WSL distros installed.": "未安装其他 WSL 发行版。", - "WSL integration": "WSL 集成" + "WSL integration": "WSL 集成", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "关闭:释放窗口占用的内存。重新打开需要片刻,已打开的终端会结束。", + "Closing the window": "关闭窗口时", + "Hide: the window stays ready and opens again at once.": "隐藏:窗口保持就绪,可立即重新打开。" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 222dc40eb..fa6463463 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1856,5 +1856,8 @@ "Running now with {cpus}, up to {mem}, and a {disk} disk.": "目前以 {cpus}、記憶體最多 {mem} 與 {disk} 磁碟執行。", "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,且永不縮小。重新啟動後生效。", "No other WSL distros installed.": "未安裝其他 WSL 發行版。", - "WSL integration": "WSL 整合" + "WSL integration": "WSL 整合", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "關閉:釋放視窗占用的記憶體。重新開啟需要片刻,已開啟的終端機會結束。", + "Closing the window": "關閉視窗時", + "Hide: the window stays ready and opens again at once.": "隱藏:視窗保持就緒,可立即重新開啟。" } diff --git a/crates/kiri/src/ui/mac.rs b/crates/kiri/src/ui/mac.rs index 68628e87e..a6c8064da 100644 --- a/crates/kiri/src/ui/mac.rs +++ b/crates/kiri/src/ui/mac.rs @@ -29,6 +29,12 @@ thread_local! { static WINDOW: RefCell>> = const { RefCell::new(None) }; /// The menu bar item; AppKit removes it once it is released. static STATUS_ITEM: RefCell>> = const { RefCell::new(None) }; + /// Where a page made again (after the window let go of its own) sends + /// its messages. + static PAGE_TX: RefCell>> = const { RefCell::new(None) }; + /// Scripts for a page made again, kept until it says `ready`: the menu + /// bar's Settings… or a container shows the window and sends at once. + static QUEUED: RefCell>> = const { RefCell::new(None) }; } /// `autostart` boots the VM as soon as the page has loaded; `view` picks the @@ -66,6 +72,7 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { for name in ["NSWindowDidResizeNotification", "NSWindowDidExitFullScreenNotification", "NSWindowDidBecomeKeyNotification", "NSWindowDidResignKeyNotification"] { let _: () = msg_send![&*centre, addObserver: &*delegate, selector: sel!(windowLaidOut:), name: &*NSString::from_str(name), object: &*window]; } + let _: () = msg_send![&*centre, addObserver: &*delegate, selector: sel!(windowWillClose:), name: &*NSString::from_str("NSWindowWillCloseNotification"), object: &*window]; } window.center(); window.makeKeyAndOrderFront(None); @@ -109,8 +116,20 @@ fn make_window(mtm: MainThreadMarker, tx: Sender, autostart: bool, view: Op window.setTitleVisibility(NSWindowTitleVisibility::Hidden); window.setMinSize(NSSize::new(760.0, 480.0)); + PAGE_TX.with(|t| *t.borrow_mut() = Some(tx.clone())); + let webview = make_webview(mtm, frame, tx, autostart, view); + window.setContentView(Some(&webview)); + read_direction(); + place_lights(&window); + WEBVIEW.with(|w| *w.borrow_mut() = Some(webview)); + WINDOW.with(|w| *w.borrow_mut() = Some(window.clone())); + Ok(window) +} + +/// The page, in a new WebKit view of `frame`'s size. +fn make_webview(mtm: MainThreadMarker, frame: NSRect, tx: Sender, autostart: bool, view: Option) -> Retained { // SAFETY: WebKit objects created and configured on the main thread. - let webview = unsafe { + unsafe { let config = WKWebViewConfiguration::new(mtm); let handler = MessageHandler::new(mtm, tx, autostart, view); config @@ -125,13 +144,28 @@ fn make_window(mtm: MainThreadMarker, tx: Sender, autostart: bool, view: Op let _: () = msg_send![&webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")]; webview.loadHTMLString_baseURL(&NSString::from_str(&super::assemble::page(PAGE, prefs()["lang"].as_str())), None); webview - }; - window.setContentView(Some(&webview)); - read_direction(); - place_lights(&window); - WEBVIEW.with(|w| *w.borrow_mut() = Some(webview)); - WINDOW.with(|w| *w.borrow_mut() = Some(window.clone())); - Ok(window) + } +} + +/// The window closed with Settings → Closing the window → Close: it lets go +/// of its page, which ends WebKit's processes for it. The menu bar item and +/// the engine stay; [`show_window`] makes the page again. +fn release_page() { + if prefs()["closeButton"] != "close" { + return; + } + let Some(webview) = WEBVIEW.with(|w| w.borrow_mut().take()) else { return }; + QUEUED.with(|q| *q.borrow_mut() = None); + // SAFETY: main thread; the content controller holds the message + // handler, which goes with the name it was added under. + unsafe { webview.configuration().userContentController().removeScriptMessageHandlerForName(&NSString::from_str("kiri")) }; + WINDOW.with(|w| { + if let Some(window) = w.borrow().as_ref() { + window.setContentView(None); + } + }); + drop(webview); + super::page_gone(); } /// The page's strip across the top (index.html's `.strip`), in points. @@ -266,6 +300,18 @@ fn show_window(mtm: MainThreadMarker) { NSApplication::sharedApplication(mtm).setActivationPolicy(NSApplicationActivationPolicy::Regular); WINDOW.with(|w| { if let Some(window) = w.borrow().as_ref() { + // The page was let go of when the window closed: a new one, + // which opens on its first section, as at launch. + if WEBVIEW.with(|v| v.borrow().is_none()) + && let Some(tx) = PAGE_TX.with(|t| t.borrow().clone()) + { + let frame = NSRect::new(NSPoint::new(0.0, 0.0), window.frame().size); + let webview = make_webview(mtm, frame, tx, false, None); + QUEUED.with(|q| *q.borrow_mut() = Some(Vec::new())); + window.setContentView(Some(&webview)); + WEBVIEW.with(|v| *v.borrow_mut() = Some(webview)); + place_lights(window); + } window.makeKeyAndOrderFront(None); } }); @@ -351,6 +397,14 @@ pub(super) fn relang() { /// Runs JavaScript in the page. Callable from any thread. pub(super) fn eval(js: String) { DispatchQueue::main().exec_async(move || { + let js = QUEUED.with(|q| match q.borrow_mut().as_mut() { + Some(queued) => { + queued.push(js); + None + } + None => Some(js), + }); + let Some(js) = js else { return }; WEBVIEW.with(|w| { if let Some(webview) = w.borrow().as_ref() { let js = NSString::from_str(&js); @@ -388,11 +442,16 @@ pub(super) fn drag() { } /// Closes the window, as the menu's Close Window did before ⌘W went to the page. +/// The page asks from inside WebKit's message callback, and closing can let +/// go of that same page (`release_page`), so the close waits for the main +/// queue's next turn. pub(super) fn close_window() { - WINDOW.with(|w| { - if let Some(window) = w.borrow().as_ref() { - window.performClose(None); - } + DispatchQueue::main().exec_async(|| { + WINDOW.with(|w| { + if let Some(window) = w.borrow().as_ref() { + window.performClose(None); + } + }); }); } @@ -510,7 +569,14 @@ define_class!( let body = unsafe { message.body() }; let Ok(text) = body.downcast::() else { return }; let ivars = self.ivars(); - super::handle(&text.to_string(), &ivars.tx, ivars.autostart, ivars.view.as_deref()); + let text = text.to_string(); + // A page made again has loaded: what was sent meanwhile goes in now. + if serde_json::from_str::(&text).is_ok_and(|m| m["cmd"] == "ready") { + for js in QUEUED.with(|q| q.borrow_mut().take()).unwrap_or_default() { + eval(js); + } + } + super::handle(&text, &ivars.tx, ivars.autostart, ivars.view.as_deref()); } } ); @@ -599,6 +665,12 @@ define_class!( }); } + /// The window is closing (its button, ⌘W or Close Window). + #[unsafe(method(windowWillClose:))] + fn window_will_close(&self, _note: &NSNotification) { + release_page(); + } + #[unsafe(method(openWindow:))] fn open_window(&self, _sender: Option<&AnyObject>) { show_window(self.mtm()); diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index d37a6bd11..f36533169 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -22,6 +22,8 @@ mod macsetup; use mac as window; #[cfg(target_os = "linux")] mod gtk; +#[cfg(any(target_os = "linux", test))] +mod sni; #[cfg(target_os = "linux")] use gtk as window; pub use window::run; @@ -507,8 +509,18 @@ fn trf(en: &str, vars: &[(&str, &dyn std::fmt::Display)]) -> String { lang::fill(tr(en), vars) } +/// The window let go of its page (mac.rs / gtk.rs, Settings → Closing the +/// window → Close): the terminals, the log and the live figures it followed +/// end with it, as when the window quits. The page asks for what it needs +/// again when it next loads. +fn page_gone() { + term::handle("closeall", "", &serde_json::Value::Null, emit); + detail::stop_logs(); + detail::stop_stats(); +} + fn set_pref(name: &str, value: serde_json::Value) { - if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip" | "lang" | "langAsked") { + if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip" | "lang" | "langAsked" | "closeButton") { return; } let Some(path) = prefs_path() else { return }; diff --git a/crates/kiri/src/ui/sni.rs b/crates/kiri/src/ui/sni.rs new file mode 100644 index 000000000..48c7fb0e9 --- /dev/null +++ b/crates/kiri/src/ui/sni.rs @@ -0,0 +1,1135 @@ +//! The Linux tray (#405): `org.kde.StatusNotifierItem` and +//! `com.canonical.dbusmenu` over the session bus through `gtk::gio`, on +//! GTK's own main loop, with no extra crates. +//! +//! The menu matches the Mac menu bar item and the Windows tray: the engine's +//! state, up to 12 running containers (clicking one opens its page in the +//! window), Open Kiri, Start, Stop and Quit Kiri. +//! +//! `org.kde.StatusNotifierWatcher` is watched on the session bus: +//! [`tray_available`] is true only once the watcher has accepted the item, +//! and false again when the watcher leaves the bus. On a desktop without a +//! tray host (such as stock GNOME with no AppIndicator extension), +//! [`tray_available`] is false and closing the window quits `kiri ui` as +//! before, so the window never hides behind a tray icon that isn't there. +//! When the tray host goes away while the window is closed to it, the window +//! comes back. + +#[cfg(target_os = "linux")] +use std::cell::RefCell; +#[cfg(target_os = "linux")] +use std::sync::Arc; +#[cfg(target_os = "linux")] +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(target_os = "linux")] +use std::sync::atomic::AtomicU32; +#[cfg(target_os = "linux")] +use std::sync::mpsc::Sender; + +#[cfg(target_os = "linux")] +use gtk::gdk_pixbuf::prelude::PixbufLoaderExt; +#[cfg(target_os = "linux")] +use gtk::gdk_pixbuf::{InterpType, PixbufLoader}; +#[cfg(target_os = "linux")] +use gtk::gio; +#[cfg(target_os = "linux")] +use gtk::glib; +#[cfg(target_os = "linux")] +use gtk::prelude::*; + +use super::MenuState; +#[cfg(target_os = "linux")] +use super::{Cmd, emit, json_str, menu_state, prefs}; +#[cfg(target_os = "linux")] +use crate::diag; + +#[cfg(target_os = "linux")] +const WATCHER_BUS: &str = "org.kde.StatusNotifierWatcher"; +#[cfg(target_os = "linux")] +const WATCHER_PATH: &str = "/StatusNotifierWatcher"; +#[cfg(target_os = "linux")] +const WATCHER_IFACE: &str = "org.kde.StatusNotifierWatcher"; + +#[cfg(target_os = "linux")] +const ITEM_PATH: &str = "/StatusNotifierItem"; +#[cfg(target_os = "linux")] +const ITEM_IFACE: &str = "org.kde.StatusNotifierItem"; + +#[cfg(target_os = "linux")] +const MENU_PATH: &str = "/MenuBar"; +#[cfg(target_os = "linux")] +const MENU_IFACE: &str = "com.canonical.dbusmenu"; + +#[cfg(target_os = "linux")] +const ID_ROOT: i32 = 0; +const ID_STATE: i32 = 1; +const ID_SEP_TOP: i32 = 2; +const ID_EMPTY: i32 = 3; +const ID_MORE: i32 = 4; +const ID_SEP_MID: i32 = 5; +const ID_OPEN: i32 = 6; +const ID_START: i32 = 7; +const ID_STOP: i32 = 8; +const ID_SEP_BOT: i32 = 9; +const ID_QUIT: i32 = 10; +const ID_CONTAINER: i32 = 100; +const MAX_CONTAINERS: usize = 12; + +#[cfg(target_os = "linux")] +const INTROSPECTION_XML: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + +static AVAILABLE: AtomicBool = AtomicBool::new(false); +#[cfg(target_os = "linux")] +static REVISION: AtomicU32 = AtomicU32::new(1); + +#[cfg(target_os = "linux")] +struct Registration { + _conn: gio::DBusConnection, + _item: gio::RegistrationId, + _menu: gio::RegistrationId, + /// Stops watching `org.kde.StatusNotifierWatcher`. gio 0.18 keeps the + /// id type `bus_watch_name_on_connection` returns in a private module, + /// so the id is held inside this closure instead of a field. + unwatch: Option>, +} + +#[cfg(target_os = "linux")] +impl Drop for Registration { + fn drop(&mut self) { + if let Some(unwatch) = self.unwatch.take() { + unwatch(); + } + } +} + +#[cfg(target_os = "linux")] +thread_local! { + static REG: RefCell> = const { RefCell::new(None) }; +} + +/// Whether a `StatusNotifierWatcher` currently owns the bus name and accepted +/// Kiri's tray item. Only then does closing the window hide or release its +/// page instead of quitting `kiri ui`. +pub(super) fn tray_available() -> bool { + AVAILABLE.load(Ordering::SeqCst) +} + +fn set_watcher_online(has_owner: bool) -> bool { + AVAILABLE.store(has_owner, Ordering::SeqCst); + has_owner +} + +/// The watcher left the bus or refused the item: the tray is gone, and +/// `on_lost` brings back a window that was closed to it. +#[cfg(target_os = "linux")] +fn tray_lost(on_lost: &dyn Fn()) { + set_watcher_online(false); + on_lost(); +} + +/// Exports `org.kde.StatusNotifierItem` and `com.canonical.dbusmenu` on the +/// session bus and watches `org.kde.StatusNotifierWatcher`. +#[cfg(target_os = "linux")] +pub(super) fn start(tx: Sender, icon_png: &[u8]) { + let conn = match gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>) { + Ok(c) => c, + Err(e) => { + diag::warn!("session bus not reached for tray", error = e.to_string()); + return; + } + }; + match register_on(&conn, tx, icon_png, super::window::show, super::window::tray_gone) { + Ok(reg) => REG.with(|r| *r.borrow_mut() = Some(reg)), + Err(e) => diag::warn!("tray not registered", error = e.to_string()), + } +} + +#[cfg(target_os = "linux")] +fn register_on( + conn: &gio::DBusConnection, + tx: Sender, + icon_png: &[u8], + on_activate: impl Fn() + Send + Sync + 'static, + on_lost: impl Fn() + Send + Sync + 'static, +) -> Result { + let node = gio::DBusNodeInfo::for_xml(INTROSPECTION_XML)?; + let item_info = node + .lookup_interface(ITEM_IFACE) + .ok_or_else(|| glib::Error::new(gio::IOErrorEnum::Failed, "missing StatusNotifierItem interface"))?; + let menu_info = node + .lookup_interface(MENU_IFACE) + .ok_or_else(|| glib::Error::new(gio::IOErrorEnum::Failed, "missing dbusmenu interface"))?; + + let icons = Arc::new(pixmaps_variant(&pixmap(icon_png))); + let item_icons = Arc::clone(&icons); + let activate = Arc::new(on_activate); + let item_activate = Arc::clone(&activate); + + let item = conn.register_object( + ITEM_PATH, + &item_info, + move |_conn, _sender, _path, _iface, method, _params, invocation| match method { + "Activate" | "SecondaryActivate" => { + item_activate(); + invocation.return_value(None); + } + "ContextMenu" | "Scroll" | "ProvideXdgActivationToken" => { + invocation.return_value(None); + } + _ => invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", "Unknown method"), + }, + move |_conn, _sender, _path, _iface, prop| sni_property(prop, &item_icons), + |_conn, _sender, _path, _iface, _prop, _val| false, + )?; + + let shown: Arc>> = Arc::new(Mutex::new(Vec::new())); + let menu_shown = Arc::clone(&shown); + let menu_activate = Arc::clone(&activate); + let menu = conn.register_object( + MENU_PATH, + &menu_info, + move |_conn, _sender, _path, _iface, method, params, invocation| { + handle_menu_method(method, ¶ms, invocation, &tx, &menu_shown, &*menu_activate); + }, + |_conn, _sender, _path, _iface, prop| menu_property(prop), + |_conn, _sender, _path, _iface, _prop, _val| false, + )?; + + let lost: Arc = Arc::new(on_lost); + let appeared_lost = Arc::clone(&lost); + let watch = gio::bus_watch_name_on_connection( + conn, + WATCHER_BUS, + gio::BusNameWatcherFlags::NONE, + move |conn, _name, _owner| register_with_watcher(&conn, Arc::clone(&appeared_lost)), + move |_conn, _name| tray_lost(&*lost), + ); + + Ok(Registration { + _conn: conn.clone(), + _item: item, + _menu: menu, + unwatch: Some(Box::new(move || gio::bus_unwatch_name(watch))), + }) +} + +/// Asks the watcher to show the item; the tray counts as up only once the +/// watcher has said yes. +#[cfg(target_os = "linux")] +fn register_with_watcher(conn: &gio::DBusConnection, on_lost: Arc) { + let service = conn + .unique_name() + .map_or_else(|| ITEM_PATH.to_owned(), |n| n.to_string()); + conn.call( + Some(WATCHER_BUS), + WATCHER_PATH, + WATCHER_IFACE, + "RegisterStatusNotifierItem", + Some(&(service,).to_variant()), + None, + gio::DBusCallFlags::NONE, + 5000, + None::<&gio::Cancellable>, + move |res| match res { + Ok(_) => { + set_watcher_online(true); + } + Err(e) => { + diag::warn!("tray watcher rejected item", error = e.to_string()); + tray_lost(&*on_lost); + } + }, + ); +} + +/// Converts raw `GdkPixbuf` rows (RGBA or RGB, with rowstride padding) into +/// network-byte-order ARGB32 (`[a, r, g, b]` per pixel), as +/// `org.kde.StatusNotifierItem.IconPixmap` expects. +fn rgba_to_argb32(bytes: &[u8], width: usize, height: usize, stride: usize, has_alpha: bool) -> Vec { + let channels = if has_alpha { 4 } else { 3 }; + let mut out = Vec::with_capacity(width * height * 4); + for y in 0..height { + for x in 0..width { + let i = y * stride + x * channels; + let (r, g, b, a) = if has_alpha { + (bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]) + } else { + (bytes[i], bytes[i + 1], bytes[i + 2], 0xFF) + }; + out.extend_from_slice(&[a, r, g, b]); + } + } + out +} + +/// Scales `png` to 22 px and 32 px ARGB32 icon bitmaps for `IconPixmap`. +#[cfg(target_os = "linux")] +fn pixmap(png: &[u8]) -> Vec<(i32, i32, Vec)> { + let loader = PixbufLoader::new(); + if loader.write(png).is_err() || loader.close().is_err() { + return Vec::new(); + } + let Some(full) = loader.pixbuf() else { return Vec::new() }; + [22, 32] + .iter() + .filter_map(|&size| { + let scaled = full.scale_simple(size, size, InterpType::Bilinear)?; + let bytes = scaled.read_pixel_bytes(); + let (w, h) = (scaled.width() as usize, scaled.height() as usize); + let data = rgba_to_argb32(&bytes, w, h, scaled.rowstride() as usize, scaled.has_alpha()); + Some((size, size, data)) + }) + .collect() +} + +#[cfg(target_os = "linux")] +fn pixmaps_variant(icons: &[(i32, i32, Vec)]) -> glib::Variant { + let ty = glib::VariantTy::new("(iiay)").unwrap(); + glib::Variant::array_from_iter_with_type( + ty, + icons.iter().map(|(w, h, data)| { + glib::Variant::tuple_from_iter([ + w.to_variant(), + h.to_variant(), + glib::Variant::array_from_fixed_array::(data), + ]) + }), + ) +} + +#[cfg(target_os = "linux")] +fn empty_pixmaps() -> glib::Variant { + pixmaps_variant(&[]) +} + +#[cfg(target_os = "linux")] +fn sni_property(name: &str, icons: &glib::Variant) -> glib::Variant { + let app = crate::flavor::APP.get(); + match name { + "Category" => "ApplicationStatus".to_variant(), + "Id" => "kiri".to_variant(), + "Title" => app.to_variant(), + "Status" => "Active".to_variant(), + "WindowId" => 0i32.to_variant(), + "IconName" | "OverlayIconName" | "AttentionIconName" => "".to_variant(), + "IconPixmap" => icons.clone(), + "OverlayIconPixmap" | "AttentionIconPixmap" => empty_pixmaps(), + "ToolTip" => glib::Variant::tuple_from_iter([ + "".to_variant(), + empty_pixmaps(), + app.to_variant(), + "".to_variant(), + ]), + "ItemIsMenu" => false.to_variant(), + "Menu" => glib::variant::ObjectPath::try_from(MENU_PATH).unwrap().to_variant(), + _ => "".to_variant(), + } +} + +#[cfg(target_os = "linux")] +fn menu_property(name: &str) -> glib::Variant { + match name { + "Version" => 3u32.to_variant(), + "TextDirection" => { + let rtl = super::lang::rtl(super::lang::resolve(prefs()["lang"].as_str())); + (if rtl { "rtl" } else { "ltr" }).to_variant() + } + "Status" => "normal".to_variant(), + "IconThemePath" => Vec::::new().to_variant(), + _ => "".to_variant(), + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum MenuEntry { + Item { id: i32, label: String, enabled: bool }, + Separator { id: i32 }, +} + +#[cfg(target_os = "linux")] +impl MenuEntry { + fn id(&self) -> i32 { + match self { + MenuEntry::Item { id, .. } | MenuEntry::Separator { id } => *id, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum MenuAction { + OpenWindow, + OpenContainer(String), + Start, + Stop, + Quit, +} + +fn menu_entries(state: &MenuState, lang: &str) -> (Vec, Vec) { + let tr = |en: &str| super::lang::tr(lang, en); + let trf = |en: &str, vars: &[(&str, &dyn std::fmt::Display)]| super::lang::fill(tr(en), vars); + let mut items = vec![ + MenuEntry::Item { + id: ID_STATE, + label: trf("Kiri: {state}", &[("state", &tr(state.vm))]), + enabled: false, + }, + MenuEntry::Separator { id: ID_SEP_TOP }, + ]; + let mut shown = Vec::new(); + if state.running.is_empty() { + items.push(MenuEntry::Item { + id: ID_EMPTY, + label: tr("No containers running"), + enabled: false, + }); + } + for (i, (id, name, url)) in state.running.iter().take(MAX_CONTAINERS).enumerate() { + let title = match url { + Some(u) => format!("{name} · {}", u.trim_start_matches("http://")), + None => name.clone(), + }; + items.push(MenuEntry::Item { + id: ID_CONTAINER + i as i32, + label: title, + enabled: true, + }); + shown.push(id.clone()); + } + if state.running.len() > MAX_CONTAINERS { + items.push(MenuEntry::Item { + id: ID_MORE, + label: trf("and {n} more…", &[("n", &(state.running.len() - MAX_CONTAINERS).to_string())]), + enabled: true, + }); + } + items.extend([ + MenuEntry::Separator { id: ID_SEP_MID }, + MenuEntry::Item { id: ID_OPEN, label: tr("Open Kiri"), enabled: true }, + MenuEntry::Item { id: ID_START, label: tr("Start"), enabled: true }, + MenuEntry::Item { id: ID_STOP, label: tr("Stop"), enabled: true }, + MenuEntry::Separator { id: ID_SEP_BOT }, + MenuEntry::Item { id: ID_QUIT, label: tr("Quit Kiri"), enabled: true }, + ]); + (items, shown) +} + +fn action_for_id(id: i32, shown: &[String]) -> Option { + match id { + ID_OPEN | ID_MORE => Some(MenuAction::OpenWindow), + ID_START => Some(MenuAction::Start), + ID_STOP => Some(MenuAction::Stop), + ID_QUIT => Some(MenuAction::Quit), + n if n >= ID_CONTAINER => { + let idx = usize::try_from(n - ID_CONTAINER).ok()?; + shown.get(idx).cloned().map(MenuAction::OpenContainer) + } + _ => None, + } +} + +#[cfg(target_os = "linux")] +fn vardict(entries: &[(&str, glib::Variant)]) -> glib::Variant { + let ty = glib::VariantTy::new("{sv}").unwrap(); + glib::Variant::array_from_iter_with_type( + ty, + entries.iter().map(|(k, v)| { + glib::Variant::from_dict_entry(&k.to_variant(), &glib::Variant::from_variant(v)) + }), + ) +} + +#[cfg(target_os = "linux")] +fn entry_props(entry: &MenuEntry) -> glib::Variant { + match entry { + MenuEntry::Item { label, enabled, .. } => vardict(&[ + ("label", label.to_variant()), + ("enabled", enabled.to_variant()), + ("visible", true.to_variant()), + ]), + MenuEntry::Separator { .. } => vardict(&[ + ("type", "separator".to_variant()), + ("visible", true.to_variant()), + ]), + } +} + +#[cfg(target_os = "linux")] +fn entry_node(entry: &MenuEntry) -> glib::Variant { + let empty_children = glib::Variant::array_from_iter::(std::iter::empty()); + glib::Variant::tuple_from_iter([entry.id().to_variant(), entry_props(entry), empty_children]) +} + +#[cfg(target_os = "linux")] +fn layout_variant(revision: u32, parent_id: i32, recursion_depth: i32, entries: &[MenuEntry]) -> glib::Variant { + if parent_id == ID_ROOT { + let children = if recursion_depth == 0 { + glib::Variant::array_from_iter::(std::iter::empty()) + } else { + glib::Variant::array_from_iter::( + entries.iter().map(|e| glib::Variant::from_variant(&entry_node(e))), + ) + }; + let root = glib::Variant::tuple_from_iter([ + ID_ROOT.to_variant(), + vardict(&[("children-display", "submenu".to_variant())]), + children, + ]); + return glib::Variant::tuple_from_iter([revision.to_variant(), root]); + } + let node = entries.iter().find(|e| e.id() == parent_id).map_or_else( + || { + let empty_children = glib::Variant::array_from_iter::(std::iter::empty()); + glib::Variant::tuple_from_iter([parent_id.to_variant(), vardict(&[]), empty_children]) + }, + entry_node, + ); + glib::Variant::tuple_from_iter([revision.to_variant(), node]) +} + +#[cfg(target_os = "linux")] +fn handle_menu_method( + method: &str, + params: &glib::Variant, + invocation: gio::DBusMethodInvocation, + tx: &Sender, + shown: &Mutex>, + on_open: &dyn Fn(), +) { + let current_entries = || { + let state = menu_state(); + let lang = super::lang::resolve(prefs()["lang"].as_str()); + let (entries, ids) = menu_entries(&state, lang); + *shown.lock().unwrap_or_else(|e| e.into_inner()) = ids; + entries + }; + let trigger = |id: i32| { + let mut ids = shown.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if ids.is_empty() { + ids = menu_state().running.iter().take(MAX_CONTAINERS).map(|(c, _, _)| c.clone()).collect(); + } + match action_for_id(id, &ids) { + Some(MenuAction::OpenWindow) => on_open(), + Some(MenuAction::OpenContainer(cid)) => { + on_open(); + let mut ev = String::from(r#"{"type":"detail","id":"#); + json_str(&mut ev, &cid); + ev.push('}'); + emit(ev); + } + Some(MenuAction::Start) => { + let _ = tx.send(Cmd::Start); + } + Some(MenuAction::Stop) => { + let _ = tx.send(Cmd::Stop); + } + Some(MenuAction::Quit) => super::window::quit(), + None => {} + } + }; + + match method { + "GetLayout" => { + let parent_id = params.try_child_get::(0).ok().flatten().unwrap_or(ID_ROOT); + let depth = params.try_child_get::(1).ok().flatten().unwrap_or(-1); + let entries = current_entries(); + let rev = REVISION.fetch_add(1, Ordering::Relaxed); + let reply = layout_variant(rev, parent_id, depth, &entries); + invocation.return_value(Some(&reply)); + } + "GetGroupProperties" => { + let ids = params.try_child_get::>(0).ok().flatten().unwrap_or_default(); + let entries = current_entries(); + let item_ty = glib::VariantTy::new("(ia{sv})").unwrap(); + let list = glib::Variant::array_from_iter_with_type( + item_ty, + ids.into_iter().filter_map(|id| { + if id == ID_ROOT { + Some(glib::Variant::tuple_from_iter([ + ID_ROOT.to_variant(), + vardict(&[("children-display", "submenu".to_variant())]), + ])) + } else { + entries.iter().find(|e| e.id() == id).map(|e| { + glib::Variant::tuple_from_iter([id.to_variant(), entry_props(e)]) + }) + } + }), + ); + let reply = glib::Variant::tuple_from_iter([list]); + invocation.return_value(Some(&reply)); + } + "GetProperty" => { + let id = params.try_child_get::(0).ok().flatten().unwrap_or(ID_ROOT); + let name = params.try_child_get::(1).ok().flatten().unwrap_or_default(); + let entries = current_entries(); + let val = match (entries.iter().find(|e| e.id() == id), name.as_str()) { + (Some(MenuEntry::Item { label, .. }), "label") => label.to_variant(), + (Some(MenuEntry::Item { enabled, .. }), "enabled") => enabled.to_variant(), + (Some(MenuEntry::Separator { .. }), "type") => "separator".to_variant(), + (_, "visible") => true.to_variant(), + _ => "".to_variant(), + }; + let reply = glib::Variant::tuple_from_iter([glib::Variant::from_variant(&val)]); + invocation.return_value(Some(&reply)); + } + "Event" => { + let id = params.try_child_get::(0).ok().flatten().unwrap_or(-1); + let event_id = params.try_child_get::(1).ok().flatten().unwrap_or_default(); + if event_id == "clicked" { + trigger(id); + } + invocation.return_value(None); + } + "EventGroup" => { + if let Some(events) = params.try_child_value(0) { + for i in 0..events.n_children() { + let ev = events.child_value(i); + let id = ev.try_child_get::(0).ok().flatten().unwrap_or(-1); + let kind = ev.try_child_get::(1).ok().flatten().unwrap_or_default(); + if kind == "clicked" { + trigger(id); + } + } + } + let reply = glib::Variant::tuple_from_iter([Vec::::new().to_variant()]); + invocation.return_value(Some(&reply)); + } + "AboutToShow" => { + let reply = glib::Variant::tuple_from_iter([true.to_variant()]); + invocation.return_value(Some(&reply)); + } + "AboutToShowGroup" => { + let reply = glib::Variant::tuple_from_iter([ + vec![ID_ROOT].to_variant(), + Vec::::new().to_variant(), + ]); + invocation.return_value(Some(&reply)); + } + _ => invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", "Unknown method"), + } +} + +#[cfg(test)] +mod tests { + #[cfg(target_os = "linux")] + use std::io::BufRead; + #[cfg(target_os = "linux")] + use std::process::{Child, Command, Stdio}; + #[cfg(target_os = "linux")] + use std::sync::Arc; + #[cfg(target_os = "linux")] + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + #[cfg(target_os = "linux")] + use std::sync::mpsc; + #[cfg(target_os = "linux")] + use std::time::{Duration, Instant}; + + use super::*; + + /// `AVAILABLE` is one static shared by every test in the process. + static TRAY_STATE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + #[test] + fn argb32_conversion_handles_rgba_rgb_and_rowstride_padding() { + // 2x2 RGBA with 2 bytes of rowstride padding per row (stride = 10). + let rgba = [ + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xFF, 0xFF, + 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x01, 0x02, 0xFF, 0xFF, + ]; + let out = rgba_to_argb32(&rgba, 2, 2, 10, true); + assert_eq!( + out, + vec![ + 0x44, 0x11, 0x22, 0x33, + 0x88, 0x55, 0x66, 0x77, + 0xCC, 0x99, 0xAA, 0xBB, + 0x02, 0xDD, 0xEE, 0x01, + ] + ); + + // 2x1 RGB without alpha (3 bytes per pixel) gets 0xFF alpha first. + let rgb = [0x10, 0x20, 0x30, 0x40, 0x50, 0x60]; + assert_eq!( + rgba_to_argb32(&rgb, 2, 1, 6, false), + vec![0xFF, 0x10, 0x20, 0x30, 0xFF, 0x40, 0x50, 0x60] + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn icon_png_scales_to_22_and_32_argb32_pixmaps() { + let icons = pixmap(super::super::window::ICON_PNG); + assert_eq!(icons.len(), 2); + assert_eq!((icons[0].0, icons[0].1, icons[0].2.len()), (22, 22, 22 * 22 * 4)); + assert_eq!((icons[1].0, icons[1].1, icons[1].2.len()), (32, 32, 32 * 32 * 4)); + let v = pixmaps_variant(&icons); + assert_eq!(v.type_().as_str(), "a(iiay)"); + assert_eq!(v.n_children(), 2); + } + + #[test] + fn watcher_availability_transitions_online_and_offline() { + let _state = TRAY_STATE.lock().unwrap_or_else(|e| e.into_inner()); + set_watcher_online(false); + assert!(!tray_available()); + assert!(set_watcher_online(true)); + assert!(tray_available()); + assert!(!set_watcher_online(false)); + assert!(!tray_available()); + } + + #[test] + fn dbusmenu_layout_caps_running_containers_at_twelve_and_maps_actions() { + let empty_state = MenuState { vm: "Stopped", running: Vec::new() }; + let (entries, shown) = menu_entries(&empty_state, "en"); + assert!(shown.is_empty()); + assert_eq!( + entries, + vec![ + MenuEntry::Item { id: ID_STATE, label: "Kiri: Stopped".into(), enabled: false }, + MenuEntry::Separator { id: ID_SEP_TOP }, + MenuEntry::Item { id: ID_EMPTY, label: "No containers running".into(), enabled: false }, + MenuEntry::Separator { id: ID_SEP_MID }, + MenuEntry::Item { id: ID_OPEN, label: "Open Kiri".into(), enabled: true }, + MenuEntry::Item { id: ID_START, label: "Start".into(), enabled: true }, + MenuEntry::Item { id: ID_STOP, label: "Stop".into(), enabled: true }, + MenuEntry::Separator { id: ID_SEP_BOT }, + MenuEntry::Item { id: ID_QUIT, label: "Quit Kiri".into(), enabled: true }, + ] + ); + + let running: Vec<(String, String, Option)> = (0..14) + .map(|i| { + let url = (i == 0).then(|| "http://web.kiri.localhost".to_owned()); + (format!("cid-{i}"), format!("app-{i}"), url) + }) + .collect(); + let busy_state = MenuState { vm: "Running", running }; + let (entries, shown) = menu_entries(&busy_state, "en"); + assert_eq!(shown.len(), 12); + assert_eq!(shown[0], "cid-0"); + assert_eq!(shown[11], "cid-11"); + assert!(entries.contains(&MenuEntry::Item { + id: ID_CONTAINER, + label: "app-0 · web.kiri.localhost".into(), + enabled: true, + })); + assert!(entries.contains(&MenuEntry::Item { + id: ID_MORE, + label: "and 2 more…".into(), + enabled: true, + })); + + #[cfg(target_os = "linux")] + { + // Verify GVariant signature and structure of GetLayout reply. + let layout = layout_variant(7, ID_ROOT, -1, &entries); + assert_eq!(layout.type_().as_str(), "(u(ia{sv}av))"); + assert_eq!(layout.child_get::(0), 7); + let root = layout.child_value(1); + assert_eq!(root.child_get::(0), ID_ROOT); + assert_eq!(root.child_value(2).n_children(), entries.len()); + } + + // Action lookup for menu item IDs. + assert_eq!(action_for_id(ID_OPEN, &shown), Some(MenuAction::OpenWindow)); + assert_eq!(action_for_id(ID_MORE, &shown), Some(MenuAction::OpenWindow)); + assert_eq!(action_for_id(ID_START, &shown), Some(MenuAction::Start)); + assert_eq!(action_for_id(ID_STOP, &shown), Some(MenuAction::Stop)); + assert_eq!(action_for_id(ID_QUIT, &shown), Some(MenuAction::Quit)); + assert_eq!(action_for_id(ID_CONTAINER, &shown), Some(MenuAction::OpenContainer("cid-0".into()))); + assert_eq!(action_for_id(ID_CONTAINER + 11, &shown), Some(MenuAction::OpenContainer("cid-11".into()))); + assert_eq!(action_for_id(ID_CONTAINER + 12, &shown), None); + assert_eq!(action_for_id(ID_STATE, &shown), None); + } + + #[cfg(target_os = "linux")] + struct PrivateBus { + child: Child, + address: String, + } + + #[cfg(target_os = "linux")] + impl PrivateBus { + fn spawn() -> Option { + let mut child = Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let stdout = child.stdout.take()?; + let mut reader = std::io::BufReader::new(stdout); + let mut address = String::new(); + reader.read_line(&mut address).ok()?; + let address = address.trim().to_owned(); + if address.is_empty() { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + Some(Self { child, address }) + } + } + + #[cfg(target_os = "linux")] + impl Drop for PrivateBus { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + #[cfg(target_os = "linux")] + fn pump_until(ctx: &glib::MainContext, timeout: Duration, mut pred: impl FnMut() -> bool) -> bool { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + while ctx.iteration(false) {} + if pred() { + return true; + } + std::thread::sleep(Duration::from_millis(5)); + } + while ctx.iteration(false) {} + pred() + } + + #[cfg(target_os = "linux")] + fn call_async( + conn: &gio::DBusConnection, + ctx: &glib::MainContext, + bus_name: &str, + object_path: &str, + interface_name: &str, + method_name: &str, + params: Option<&glib::Variant>, + ) -> glib::Variant { + let result: Arc>>> = Arc::new(Mutex::new(None)); + let slot = Arc::clone(&result); + conn.call( + Some(bus_name), + object_path, + interface_name, + method_name, + params, + None, + gio::DBusCallFlags::NONE, + 5000, + None::<&gio::Cancellable>, + move |res| { + *slot.lock().unwrap() = Some(res); + }, + ); + assert!( + pump_until(ctx, Duration::from_secs(5), || result.lock().unwrap().is_some()), + "D-Bus call {interface_name}.{method_name} timed out" + ); + result.lock().unwrap().take().unwrap().unwrap() + } + + #[cfg(target_os = "linux")] + #[test] + fn live_gdbus_status_notifier_registers_serves_icon_layout_and_activates() { + let bus = PrivateBus::spawn().expect("dbus-daemon must be available"); + let ctx = glib::MainContext::default(); + let _guard = ctx.acquire().expect("acquire main context"); + + let flags = gio::DBusConnectionFlags::AUTHENTICATION_CLIENT + | gio::DBusConnectionFlags::MESSAGE_BUS_CONNECTION; + let watcher_conn = gio::DBusConnection::for_address_sync(&bus.address, flags, None, None::<&gio::Cancellable>).unwrap(); + let item_conn = gio::DBusConnection::for_address_sync(&bus.address, flags, None, None::<&gio::Cancellable>).unwrap(); + + let _state = TRAY_STATE.lock().unwrap_or_else(|e| e.into_inner()); + set_watcher_online(false); + let (tx, rx) = mpsc::channel(); + let activated = Arc::new(AtomicUsize::new(0)); + let act_count = Arc::clone(&activated); + let lost = Arc::new(AtomicUsize::new(0)); + let lost_count = Arc::clone(&lost); + let _reg = register_on( + &item_conn, + tx, + super::super::window::ICON_PNG, + move || { + act_count.fetch_add(1, Ordering::SeqCst); + }, + move || { + lost_count.fetch_add(1, Ordering::SeqCst); + }, + ) + .unwrap(); + + // With no StatusNotifierWatcher on the bus yet, tray_available() stays false. + pump_until(&ctx, Duration::from_millis(50), || false); + assert!(!tray_available(), "tray must be unavailable before watcher appears"); + + // Export a mock org.kde.StatusNotifierWatcher that refuses items + // until `accept` is set. + let watcher_xml = r#" + + + + + + + + "#; + let watcher_node = gio::DBusNodeInfo::for_xml(watcher_xml).unwrap(); + let watcher_iface = watcher_node.lookup_interface(WATCHER_IFACE).unwrap(); + let accept = Arc::new(AtomicBool::new(false)); + let watcher_accept = Arc::clone(&accept); + let refused = Arc::new(AtomicUsize::new(0)); + let refused_count = Arc::clone(&refused); + let registered_service: Arc>> = Arc::new(Mutex::new(None)); + let reg_slot = Arc::clone(®istered_service); + let _watcher_obj = watcher_conn + .register_object( + WATCHER_PATH, + &watcher_iface, + move |_conn, _sender, _path, _iface, method, params, invocation| { + if method != "RegisterStatusNotifierItem" { + return; + } + if !watcher_accept.load(Ordering::SeqCst) { + refused_count.fetch_add(1, Ordering::SeqCst); + invocation.return_dbus_error("org.freedesktop.DBus.Error.Failed", "refused"); + return; + } + let svc = params.child_get::(0); + *reg_slot.lock().unwrap() = Some(svc); + invocation.return_value(None); + }, + |_conn, _sender, _path, _iface, _prop| "".to_variant(), + |_conn, _sender, _path, _iface, _prop, _val| false, + ) + .unwrap(); + + let bus_call = |method: &str, params: glib::Variant| { + watcher_conn + .call_sync( + Some("org.freedesktop.DBus"), + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + method, + Some(¶ms), + None, + gio::DBusCallFlags::NONE, + 5000, + None::<&gio::Cancellable>, + ) + .unwrap() + }; + let request_name = || { + let req = bus_call("RequestName", (WATCHER_BUS, 0u32).to_variant()); + assert_eq!(req.child_get::(0), 1, "mock watcher should own bus name"); + }; + let release_name = || { + bus_call("ReleaseName", (WATCHER_BUS,).to_variant()); + }; + + // A watcher that refuses the item leaves the tray unavailable, and + // the window is called back. + let lost_before = lost.load(Ordering::SeqCst); + request_name(); + assert!( + pump_until(&ctx, Duration::from_secs(5), || { + refused.load(Ordering::SeqCst) == 1 && lost.load(Ordering::SeqCst) > lost_before + }), + "refused registration must report the tray lost" + ); + assert!(!tray_available(), "tray must stay unavailable when the watcher refuses the item"); + + // That watcher leaves the bus: the window is called back again. + let lost_before = lost.load(Ordering::SeqCst); + release_name(); + assert!( + pump_until(&ctx, Duration::from_secs(5), || lost.load(Ordering::SeqCst) > lost_before), + "watcher vanishing must report the tray lost" + ); + + // A watcher that accepts the item makes the tray available. + accept.store(true, Ordering::SeqCst); + request_name(); + assert!( + pump_until(&ctx, Duration::from_secs(5), || { + registered_service.lock().unwrap().is_some() && tray_available() + }), + "StatusNotifierItem did not register with watcher" + ); + let item_bus = registered_service.lock().unwrap().clone().unwrap(); + assert_eq!(Some(item_bus.as_str()), item_conn.unique_name().as_deref()); + + // 1. Get("IconPixmap") over real GDBus Properties interface. + let icon_prop = call_async( + &watcher_conn, + &ctx, + &item_bus, + ITEM_PATH, + "org.freedesktop.DBus.Properties", + "Get", + Some(&(ITEM_IFACE, "IconPixmap").to_variant()), + ); + let pixmaps = icon_prop.child_value(0).as_variant().unwrap(); + assert_eq!(pixmaps.type_().as_str(), "a(iiay)"); + assert_eq!(pixmaps.n_children(), 2); + let first_icon = pixmaps.child_value(0); + assert_eq!((first_icon.child_get::(0), first_icon.child_get::(1)), (22, 22)); + assert_eq!(first_icon.child_value(2).n_children(), 22 * 22 * 4); + + // 2. Activate(x, y) over real GDBus invokes our activate callback. + call_async( + &watcher_conn, + &ctx, + &item_bus, + ITEM_PATH, + ITEM_IFACE, + "Activate", + Some(&(10i32, 20i32).to_variant()), + ); + assert_eq!(activated.load(Ordering::SeqCst), 1); + + // 3. GetLayout(0, -1, []) over real GDBus returns the live menu tree. + *menu_state() = MenuState { + vm: "Running", + running: vec![("abc123def".into(), "nginx".into(), Some("http://nginx.kiri.localhost".into()))], + }; + let layout_reply = call_async( + &watcher_conn, + &ctx, + &item_bus, + MENU_PATH, + MENU_IFACE, + "GetLayout", + Some(&(0i32, -1i32, Vec::::new()).to_variant()), + ); + assert_eq!(layout_reply.type_().as_str(), "(u(ia{sv}av))"); + let root = layout_reply.child_value(1); + let children = root.child_value(2); + assert!(children.n_children() >= 8); + let container_node = children.child_value(2).as_variant().unwrap(); + assert_eq!(container_node.child_get::(0), ID_CONTAINER); + + // 4. Event(ID_START, "clicked", ...) sends Cmd::Start to the engine channel. + let click_data = glib::Variant::from_variant(&0i32.to_variant()); + call_async( + &watcher_conn, + &ctx, + &item_bus, + MENU_PATH, + MENU_IFACE, + "Event", + Some(&(ID_START, "clicked", click_data, 0u32).to_variant()), + ); + assert!(matches!(rx.try_recv(), Ok(Cmd::Start))); + + // 5. Releasing the watcher bus name transitions tray_available() back to false. + let lost_before = lost.load(Ordering::SeqCst); + release_name(); + assert!( + pump_until(&ctx, Duration::from_secs(5), || { + !tray_available() && lost.load(Ordering::SeqCst) > lost_before + }), + "tray_available() must become false and the window come back when watcher vanishes" + ); + } +} diff --git a/docs/features.md b/docs/features.md index 53591f880..d52393352 100644 --- a/docs/features.md +++ b/docs/features.md @@ -126,8 +126,10 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr size, the VM's CPUs, memory and disk image size (`~/.kiri/vm.json`, used from the VM's next start; `KIRI_CPUS`, `KIRI_MEMORY_MIB` and `KIRI_DISK_GB` override it; the disk grows online on boot and never shrinks) and local names -- **Menu bar**: Kiri stays in the menu bar when its window closes, with the - VM's state, running containers (click one to open it) and Start/Stop +- **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 + 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 - **Linux machines**: `kiri machine create dev --distro ubuntu` and diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 0df082cf4..cc52ecd5c 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 +### #706, #539 UI: Linux tray icon and unified window-close setting (Hide vs Close) across macOS, Windows and Linux (unreleased) +- Fixes: #405 Linux: close the window to the tray, as on Windows; #168 Release or suspend WebView2 memory when window is closed to tray (Lightweight background mode) +- Caused: none known +- Caused by: - +- Check: `tests/ui/closebutton.js` + ### #384 macOS: configurable VM disk size with online ext4 growth (unreleased) - Fixes: #384 macOS: VM data.img is fixed at 64 GiB with no disk size setting - Caused: none known diff --git a/tests/ui/closebutton.js b/tests/ui/closebutton.js new file mode 100644 index 000000000..5b85e11fb --- /dev/null +++ b/tests/ui/closebutton.js @@ -0,0 +1,23 @@ +// Settings → Appearance → Closing the window: Hide unless you choose Close. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; +const pressed = () => [...document.querySelectorAll("[data-closebtn]")].filter((b) => b.getAttribute("aria-pressed") === "true").map((b) => b.dataset.closebtn); +const words = () => document.querySelector("[data-closebtn]").closest(".pref").querySelector(".d").textContent; +prefs.tab = "appearance"; show("settings"); +t("hide is the choice until another is made", () => { + eq(pressed(), ["hide"], "pressed"); + eq(words().startsWith("Hide:"), true, "says what Hide does"); +}); +t("choosing Close is saved and says what it costs", () => { + sent.length = 0; document.querySelector('[data-closebtn="close"]').click(); + eq(sent.filter((x) => x.type === "setpref").map((x) => [x.name, x.value]), [["closeButton", "close"]], "saved"); + eq(pressed(), ["close"], "pressed"); + eq(/open terminals end/.test(words()), true, "says terminals end"); +}); +t("and back to Hide", () => { + sent.length = 0; document.querySelector('[data-closebtn="hide"]').click(); + eq(sent.filter((x) => x.type === "setpref").map((x) => [x.name, x.value]), [["closeButton", "hide"]], "saved"); + eq(pressed(), ["hide"], "pressed"); +}); +report(R); diff --git a/tests/ui/parity.js b/tests/ui/parity.js index 2fc4a329e..59c99a8cc 100644 --- a/tests/ui/parity.js +++ b/tests/ui/parity.js @@ -24,6 +24,7 @@ for (const b of document.querySelectorAll("[data-imgtab]")) if (seen(b)) items.p kiri.on({ type: "usb", can: "attach", devices: [{ key: "k", name: "Zigbee", id: "10c4:ea60", speed: "full", state: "host", path: "" }] }); show("usb"); for (const th of document.querySelectorAll("#content thead th")) { const h = th.textContent.trim(); if (h) items.push(`column usb: ${h}`); } -show("settings"); +prefs.tab = "appearance"; show("settings"); for (const b of document.querySelectorAll("[data-stab]")) items.push(`settings ${b.dataset.stab}`); +for (const el of document.querySelectorAll(".settings .pref > .t")) if (seen(el)) items.push(`setting appearance: ${el.textContent.trim()}`); report(items.map((x) => "ITEM " + x)); From a1c4ca54c080c9450ff46fb0c76ecb6414e9c797 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:49:51 +0100 Subject: [PATCH 044/157] Settings: add launch at login and stop engine on quit (#368) (#827) --- crates/kiri-win/src/app.rs | 7 +- crates/kiri-win/src/engine.rs | 61 +++++++- crates/kiri-win/src/setup.rs | 105 +++++++++++++- crates/kiri/src/main.rs | 7 + crates/kiri/src/setup.rs | 149 +++++++++++++++++-- crates/kiri/src/ui/index.html | 8 ++ crates/kiri/src/ui/lang/am.json | 6 +- crates/kiri/src/ui/lang/ar.json | 6 +- crates/kiri/src/ui/lang/bg.json | 6 +- crates/kiri/src/ui/lang/bn.json | 6 +- crates/kiri/src/ui/lang/ca.json | 6 +- crates/kiri/src/ui/lang/ckb.json | 6 +- crates/kiri/src/ui/lang/cs.json | 6 +- crates/kiri/src/ui/lang/de.json | 6 +- crates/kiri/src/ui/lang/el.json | 6 +- crates/kiri/src/ui/lang/es.json | 6 +- crates/kiri/src/ui/lang/fa.json | 6 +- crates/kiri/src/ui/lang/fi.json | 6 +- crates/kiri/src/ui/lang/fr.json | 6 +- crates/kiri/src/ui/lang/hi.json | 6 +- crates/kiri/src/ui/lang/hu.json | 6 +- crates/kiri/src/ui/lang/id.json | 6 +- crates/kiri/src/ui/lang/it.json | 6 +- crates/kiri/src/ui/lang/ja.json | 6 +- crates/kiri/src/ui/lang/kk.json | 6 +- crates/kiri/src/ui/lang/ko.json | 6 +- crates/kiri/src/ui/lang/lo.json | 6 +- crates/kiri/src/ui/lang/lt.json | 6 +- crates/kiri/src/ui/lang/nb.json | 6 +- crates/kiri/src/ui/lang/pl.json | 6 +- crates/kiri/src/ui/lang/pt-BR.json | 6 +- crates/kiri/src/ui/lang/ro.json | 6 +- crates/kiri/src/ui/lang/ru.json | 6 +- crates/kiri/src/ui/lang/sl.json | 6 +- crates/kiri/src/ui/lang/sq.json | 6 +- crates/kiri/src/ui/lang/ta.json | 6 +- crates/kiri/src/ui/lang/te.json | 6 +- crates/kiri/src/ui/lang/th.json | 6 +- crates/kiri/src/ui/lang/tr.json | 6 +- crates/kiri/src/ui/lang/uk.json | 6 +- crates/kiri/src/ui/lang/vi.json | 6 +- crates/kiri/src/ui/lang/zh-Hans.json | 6 +- crates/kiri/src/ui/lang/zh-Hant.json | 6 +- crates/kiri/src/ui/linux.rs | 21 +++ crates/kiri/src/ui/mac.rs | 4 +- crates/kiri/src/ui/mod.rs | 207 ++++++++++++++++++++++++++- crates/kiri/src/update.rs | 2 +- docs/features.md | 7 +- docs/fix-registry.md | 10 +- tests/ui/start-quit.js | 73 ++++++++++ 50 files changed, 813 insertions(+), 70 deletions(-) create mode 100644 tests/ui/start-quit.js diff --git a/crates/kiri-win/src/app.rs b/crates/kiri-win/src/app.rs index 59b250a88..69101d2bf 100644 --- a/crates/kiri-win/src/app.rs +++ b/crates/kiri-win/src/app.rs @@ -584,7 +584,12 @@ fn tray_menu(hwnd: HWND) { ID_START => tray_cmd("start"), ID_STOP => tray_cmd("stop"), ID_UPDATE => tray_cmd("update"), - ID_QUIT => PostQuitMessage(0), + ID_QUIT => { + if crate::engine::prefs()["stopOnQuit"] == true { + crate::engine::stop(); + } + PostQuitMessage(0); + } n if n >= ID_CONTAINER => { if let Some((id, _)) = menu.running.get(n - ID_CONTAINER) { show(); diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 703e2ffa0..4807e180f 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -915,9 +915,30 @@ pub fn prefs() -> Value { p["theme"] = "dark".into(); } p["watchBindMounts"] = json!(crate::watch::is_enabled()); + if p.get("startAtLogin").is_none() { + p["startAtLogin"] = crate::setup::start_at_login().into(); + } + if p.get("stopOnQuit").is_none() { + p["stopOnQuit"] = false.into(); + } p } +/// Stops running containers and terminates Kiri's WSL distro when quitting +/// with "Stop the engine when Kiri quits" on. +pub fn stop() { + sharing::close_all(); + let _ = match expect_ok(client::request("POST", "/kiri/stop", None)) { + Err(e) if e.to_string().contains("404") => expect_ok(client::request("POST", "/kiri/sleep", None)), + r => r, + }; + if let Some(d) = distro() { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let _ = crate::update::output_within(cmd.args(["--terminate", &d]), crate::update::WSL_LIMIT); + } +} + /// `en` in the window's language (lang.rs), for words sent to the page: /// notices, and the setup steps. pub fn tr(en: &str) -> String { @@ -939,7 +960,7 @@ fn set_pref(name: &str, value: Value) { crate::watch::set_enabled(crate::watch::is_enabled()); return; } - if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton") { + if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton" | "startAtLogin" | "stopOnQuit") { return; } let Some(path) = prefs_path() else { return }; @@ -1046,6 +1067,30 @@ mod tests { assert!(get_req.starts_with("GET /kiri/proxy HTTP/1.1\r\n") && get_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{get_req}"); assert!(put_req.starts_with("PUT /kiri/proxy/system HTTP/1.1\r\n") && put_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{put_req}"); } + + #[test] + fn saves_stop_on_quit_and_start_at_login_prefs() { + let dir = std::env::temp_dir().join(format!("kiri-win-prefs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let old = std::env::var_os("LOCALAPPDATA"); + // SAFETY: serialized within this test binary's prefs test. + unsafe { std::env::set_var("LOCALAPPDATA", &dir) }; + assert_eq!(super::prefs()["stopOnQuit"], false); + super::set_pref("stopOnQuit", serde_json::json!(true)); + assert_eq!(super::prefs()["stopOnQuit"], true); + super::set_pref("stopOnQuit", serde_json::json!(false)); + assert_eq!(super::prefs()["stopOnQuit"], false); + super::set_pref("startAtLogin", serde_json::json!(false)); + assert_eq!(super::prefs()["startAtLogin"], false); + super::set_pref("startAtLogin", serde_json::json!(true)); + assert_eq!(super::prefs()["startAtLogin"], true); + match old { + Some(v) => unsafe { std::env::set_var("LOCALAPPDATA", v) }, + None => unsafe { std::env::remove_var("LOCALAPPDATA") }, + } + let _ = std::fs::remove_dir_all(&dir); + } } /// The page's "fonts" event, made once (the window asks each time Settings @@ -1098,8 +1143,9 @@ pub fn on_message(msg: &str) { emit(crate::buildwith::event()); }); send(Cmd::Refresh); - // Opening the window starts Kiri, unless it was stopped: that waits for Start. - send(Cmd::Launch); + // Opening the window starts Kiri, unless it was stopped: that waits + // for Start (except when quitting stopped it with stopOnQuit). + send(if prefs()["stopOnQuit"] == true { Cmd::Start } else { Cmd::Launch }); // Anything newer than this build, and a staged update not yet in. crate::update::check_now(false); // For checking the page by hand in a debug build. @@ -1256,6 +1302,15 @@ pub fn on_message(msg: &str) { let theme = c.value.as_str().unwrap_or("").to_owned(); Handle.run(move |ui| ui.set_theme(&theme)); } + if c.name == "startAtLogin" + && let Some(on) = c.value.as_bool() + && let Err(e) = crate::setup::set_start_at_login(on) + { + crate::serve::log(&format!("start at sign-in: {e}")); + emit(notice("error", &e.to_string())); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); + return; + } set_pref(&c.name, c.value); } // A language the page doesn't carry yet (the main window and setup open diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index a5c42d6d5..f2c72b0f5 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -985,20 +985,83 @@ fn finish() { save(&s); crate::serve::set_setup_pending(false); let exe = dir().join("kiri-win.exe"); - let run_key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; if autostart { if exe.is_file() { - let _ = quiet("reg.exe").args(["add", run_key, "/v", "Kiri", "/t", "REG_SZ", "/d", &format!("\"{}\" --background", exe.display()), "/f"]).status(); + let _ = set_start_at_login_named(RUN_VALUE, true, &exe); } else { crate::serve::log("not set to start at sign-in: kiri-win.exe is not installed"); } } else { - let _ = quiet("reg.exe").args(["delete", run_key, "/v", "Kiri", "/f"]).status(); + let _ = set_start_at_login_named(RUN_VALUE, false, &exe); } let _ = quiet("reg.exe").args(["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce", "/v", "KiriSetup", "/f"]).status(); Handle.run(|ui| ui.navigate_main()); } +pub const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; +pub const RUN_VALUE: &str = "Kiri"; + +pub fn run_reg_value(exe: &Path) -> String { + format!("\"{}\" --background", exe.display()) +} + +pub fn run_reg_args(value_name: &str, on: bool, exe: &Path) -> Vec { + if on { + vec![ + "add".into(), + RUN_KEY.into(), + "/v".into(), + value_name.into(), + "/t".into(), + "REG_SZ".into(), + "/d".into(), + run_reg_value(exe), + "/f".into(), + ] + } else { + vec!["delete".into(), RUN_KEY.into(), "/v".into(), value_name.into(), "/f".into()] + } +} + +pub fn parse_run_reg_query(status_ok: bool, stdout: &str, value_name: &str) -> bool { + status_ok + && stdout.lines().any(|l| { + let mut parts = l.split_whitespace(); + parts.next().is_some_and(|n| n.eq_ignore_ascii_case(value_name)) + && parts.next().is_some_and(|t| t.eq_ignore_ascii_case("REG_SZ")) + }) +} + +pub fn start_at_login_named(value_name: &str) -> bool { + quiet("reg.exe") + .args(["query", RUN_KEY, "/v", value_name]) + .output() + .is_ok_and(|o| parse_run_reg_query(o.status.success(), &String::from_utf8_lossy(&o.stdout), value_name)) +} + +pub fn start_at_login() -> bool { + start_at_login_named(RUN_VALUE) +} + +pub fn set_start_at_login_named(value_name: &str, on: bool, exe: &Path) -> io::Result<()> { + if !on && !start_at_login_named(value_name) { + return Ok(()); + } + let args = run_reg_args(value_name, on, exe); + let out = quiet("reg.exe").args(&args).output()?; + if out.status.success() { + Ok(()) + } else { + Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) + } +} + +pub fn set_start_at_login(on: bool) -> io::Result<()> { + let installed = dir().join("kiri-win.exe"); + let exe = if installed.is_file() { installed } else { std::env::current_exe()? }; + set_start_at_login_named(RUN_VALUE, on, &exe) +} + fn copy_to_clipboard(text: &str) { if let Ok(mut c) = quiet("clip.exe").stdin(Stdio::piped()).spawn() { if let Some(mut i) = c.stdin.take() { @@ -1381,4 +1444,40 @@ mod tests { let silent = listing_by(quiet("cmd.exe").raw_arg("/c echo Error code: Wsl/Service/WSAETIMEDOUT 1>&2 & exit 1"), ten); assert!(!silent.components_off && silent.distros.is_none()); } + + #[test] + fn start_at_login_registry_commands_and_query_parsing() { + let exe = std::path::Path::new(r"C:\Users\me\AppData\Local\Kiri\kiri-win.exe"); + assert_eq!(super::run_reg_value(exe), r#""C:\Users\me\AppData\Local\Kiri\kiri-win.exe" --background"#); + assert_eq!( + super::run_reg_args("Kiri", true, exe), + vec![ + "add", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", + "/v", + "Kiri", + "/t", + "REG_SZ", + "/d", + r#""C:\Users\me\AppData\Local\Kiri\kiri-win.exe" --background"#, + "/f", + ] + ); + assert_eq!( + super::run_reg_args("Kiri", false, exe), + vec!["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "Kiri", "/f"] + ); + let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n Kiri REG_SZ \"C:\\Users\\me\\AppData\\Local\\Kiri\\kiri-win.exe\" --background\r\n\r\n"; + assert!(super::parse_run_reg_query(true, out, "Kiri")); + assert!(!super::parse_run_reg_query(false, out, "Kiri")); + assert!(!super::parse_run_reg_query(true, "", "Kiri")); + + let test_val = format!("KiriTest368_{}", std::process::id()); + let _ = super::set_start_at_login_named(&test_val, false, exe); + assert!(!super::start_at_login_named(&test_val)); + super::set_start_at_login_named(&test_val, true, exe).unwrap(); + assert!(super::start_at_login_named(&test_val)); + super::set_start_at_login_named(&test_val, false, exe).unwrap(); + assert!(!super::start_at_login_named(&test_val)); + } } diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 182a540dd..f1deb1b1b 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -251,6 +251,13 @@ fn window(args: &[String]) -> std::io::Result<()> { /// 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()?; + } if !client::alive() { return Err(std::io::Error::other("Kiri's engine isn't running. Open Kiri, or start it with `kiri daemon`")); } diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index 1cce7122b..ef605d0cd 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -793,13 +793,12 @@ fn uid() -> u32 { unsafe { libc::getuid() } } -/// A LaunchAgent for `kiri daemon`: started at login, restarted if it -/// crashes, never restarted after a clean exit. -fn agent() -> io::Result { - let exe = std::env::current_exe()?.canonicalize()?; - let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); +/// A LaunchAgent for `kiri daemon`: started at login when `run_at_load` is +/// true, restarted if it crashes, never restarted after a clean exit. +pub(crate) fn agent_plist_xml(exe: &Path, log: &Path, run_at_load: bool) -> String { let esc = |p: &Path| p.to_string_lossy().replace('&', "&").replace('<', "<"); - let plist = format!( + let run = if run_at_load { "true" } else { "false" }; + format!( r#" @@ -807,7 +806,7 @@ fn agent() -> io::Result { Label{AGENT} AssociatedBundleIdentifiers{APP_ID} ProgramArguments{}daemon - RunAtLoad + RunAtLoad<{run}/> KeepAliveSuccessfulExit ProcessTypeInteractive StandardOutPath{} @@ -815,10 +814,95 @@ fn agent() -> io::Result { "#, - esc(&exe), - esc(&log), - esc(&log) - ); + esc(exe), + esc(log), + esc(log) + ) +} + +/// Reads `RunAtLoad` from a LaunchAgent plist. +pub(crate) fn plist_run_at_load(xml: &str) -> Option { + let rest = xml.split_once("RunAtLoad")?.1.trim_start(); + if rest.starts_with("") { + Some(true) + } else if rest.starts_with("") { + Some(false) + } else { + None + } +} + +/// Flips `RunAtLoad` in a LaunchAgent plist between `` and ``. +pub(crate) fn set_plist_run_at_load(xml: &str, on: bool) -> Option { + let key = "RunAtLoad"; + let at = xml.find(key)? + key.len(); + let after = &xml[at..]; + let ws = after.len() - after.trim_start().len(); + let tag_at = at + ws; + let old_tag = if xml[tag_at..].starts_with("") { + "" + } else if xml[tag_at..].starts_with("") { + "" + } else { + return None; + }; + let new_tag = if on { "" } else { "" }; + let mut out = String::with_capacity(xml.len() + 1); + out.push_str(&xml[..tag_at]); + out.push_str(new_tag); + out.push_str(&xml[tag_at + old_tag.len()..]); + Some(out) +} + +/// Whether the LaunchAgent is set to start Kiri at sign-in (`RunAtLoad`). +pub fn start_at_login() -> bool { + agent_plist() + .ok() + .and_then(|p| std::fs::read_to_string(p).ok()) + .and_then(|xml| plist_run_at_load(&xml)) + .unwrap_or(true) +} + +/// Updates `RunAtLoad` in `path` (or writes a valid LaunchAgent plist when missing). +pub(crate) fn set_start_at_login_at(path: &Path, exe: &Path, log: &Path, on: bool) -> io::Result<()> { + if let Ok(xml) = std::fs::read_to_string(path) + && let Some(updated) = set_plist_run_at_load(&xml, on) + { + return std::fs::write(path, updated); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + if let Some(dir) = log.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(path, agent_plist_xml(exe, log, on)) +} + +/// Settings → Appearance → Start Kiri at sign-in: updates `RunAtLoad` in the +/// LaunchAgent plist while keeping the plist valid for on-demand launchd. +pub fn set_start_at_login(on: bool) -> io::Result<()> { + let path = agent_plist()?; + let exe = std::env::current_exe()?.canonicalize()?; + let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); + set_start_at_login_at(&path, &exe, &log, on) +} + +/// Unloads the LaunchAgent from launchd, stopping `kiri daemon` if launchd runs it. +pub fn bootout_agent() { + let _ = Command::new("/bin/launchctl") + .args(["bootout", &format!("gui/{}/{AGENT}", uid())]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); +} + +/// A LaunchAgent for `kiri daemon`: started at login, restarted if it +/// crashes, never restarted after a clean exit. +fn agent() -> io::Result { + let exe = std::env::current_exe()?.canonicalize()?; + let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); + let plist = agent_plist_xml(&exe, &log, true); let path = agent_plist()?; if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; @@ -858,12 +942,15 @@ pub fn start_agent() -> io::Result { if kicked { return Ok(true); } - // Not loaded: bootstrap it, and RunAtLoad starts it. + // Not loaded: bootstrap it, then kickstart it (when RunAtLoad is false, + // bootstrap loads the job without starting it). let loaded = Command::new("/bin/launchctl").args(["bootstrap", &format!("gui/{}", uid())]).arg(agent_plist()?).stderr(std::process::Stdio::null()).status()?.success(); if !loaded { crate::diag::info!("the LaunchAgent would not load; starting the engine directly"); + return Ok(false); } - Ok(loaded) + let _ = Command::new("/bin/launchctl").args(["kickstart", &job]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status(); + Ok(true) } /// Whether the LaunchAgent starts this copy of Kiri. One left by another @@ -1122,4 +1209,40 @@ mod tests { .unwrap(); assert_eq!(String::from_utf8_lossy(&out.stdout), "/usr/bin:/bin:/h/.kiri/bin"); } + + #[test] + fn launch_agent_plist_run_at_load_generates_parses_and_toggles() { + let d = scratch("plist"); + let exe = std::path::Path::new("/Applications/Kiri.app/Contents/MacOS/kiri"); + let log = d.join(".kiri/daemon.log"); + let plist_path = d.join("Library/LaunchAgents/dev.kiri.daemon.plist"); + + let xml_on = super::agent_plist_xml(exe, &log, true); + assert_eq!(super::plist_run_at_load(&xml_on), Some(true)); + assert!(xml_on.contains("RunAtLoad")); + + let xml_off = super::agent_plist_xml(exe, &log, false); + assert_eq!(super::plist_run_at_load(&xml_off), Some(false)); + assert!(xml_off.contains("RunAtLoad")); + + let flipped_off = super::set_plist_run_at_load(&xml_on, false).unwrap(); + assert_eq!(flipped_off, xml_off); + assert_eq!(super::plist_run_at_load(&flipped_off), Some(false)); + + let flipped_on = super::set_plist_run_at_load(&flipped_off, true).unwrap(); + assert_eq!(flipped_on, xml_on); + assert_eq!(super::plist_run_at_load(&flipped_on), Some(true)); + + // File creation and in-place toggling keep the rest of the plist valid. + super::set_start_at_login_at(&plist_path, exe, &log, true).unwrap(); + assert_eq!(super::plist_run_at_load(&std::fs::read_to_string(&plist_path).unwrap()), Some(true)); + super::set_start_at_login_at(&plist_path, exe, &log, false).unwrap(); + let saved = std::fs::read_to_string(&plist_path).unwrap(); + assert_eq!(super::plist_run_at_load(&saved), Some(false)); + assert!(saved.contains("/Applications/Kiri.app/Contents/MacOS/kiridaemon")); + super::set_start_at_login_at(&plist_path, exe, &log, true).unwrap(); + assert_eq!(super::plist_run_at_load(&std::fs::read_to_string(&plist_path).unwrap()), Some(true)); + + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 92011869e..1f5b8fe79 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4489,6 +4489,8 @@

${tr("Use {app} for docker?", { app: esc(app) })}

}; const inUse = darkNow(); const sysName = LANGS.find(([id]) => id === resolveLang("system"))?.[1] || "English"; + const startAtLogin = prefs.startAtLogin ?? !LINUX; + const stopOnQuit = prefs.stopOnQuit === true; const appearance = `

${tr("Appearance")}

${tr("Language")}${tr("Follow {os} (now {lang}), or always use one language.", { os: OS, lang: sysName })} ${langButton(sysName)} @@ -4511,6 +4513,10 @@

${tr("Use {app} for docker?", { app: esc(app) })}

: tr("Hide: the window stays ready and opens again at once.")}
web · nginx:alpine
Up 3 minutes · 26.3 MB · localhost:8080 → 80
ef9a6e2b45c2 docker run -p 8080:80 nginx
+
${tr("Start Kiri at sign-in")}${tr("Start Kiri in the background when you sign in.")} +
+
${tr("Stop the engine when Kiri quits")}${tr("Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.")} +
`; const portsPref = routerPortsPref(); // On Linux: kiri.localhost only, for now; nothing to switch. @@ -8339,6 +8345,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-scale]"))) setPref("scale", +el.dataset.scale); else if ((el = t("[data-logsize]"))) setPref("logSize", +el.dataset.logsize); else if ((el = t("[data-closebtn]"))) setPref("closeButton", el.dataset.closebtn); + else if ((el = t("[data-startlogin]"))) setPref("startAtLogin", el.dataset.startlogin === "1"); + else if ((el = t("[data-stopquit]"))) setPref("stopOnQuit", el.dataset.stopquit === "1"); else if ((el = t("[data-theme-pick]"))) setPref("theme", el.dataset.themePick); else if ((el = t("[data-accent]"))) setPref("accent", el.dataset.accent); else if (t("[data-buildprune]")) { ui.bwPruning = true; send("buildprune"); render(); } diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index e31755eeb..9741eaae7 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1859,5 +1859,9 @@ "WSL integration": "የWSL ውህደት", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ዝጋ፦ መስኮቱ የሚጠቀመው ማህደረ ትውስታ ይለቀቃል። እንደገና ለመክፈት ትንሽ ጊዜ ይወስዳል፣ የተከፈቱ ተርሚናሎችም ይዘጋሉ።", "Closing the window": "መስኮቱን ሲዘጉ", - "Hide: the window stays ready and opens again at once.": "ደብቅ፦ መስኮቱ ዝግጁ ሆኖ ይቆያል፣ ወዲያውኑም እንደገና ይከፈታል።" + "Hide: the window stays ready and opens again at once.": "ደብቅ፦ መስኮቱ ዝግጁ ሆኖ ይቆያል፣ ወዲያውኑም እንደገና ይከፈታል።", + "Start Kiri at sign-in": "ሲገቡ Kiriን ጀምር", + "Start Kiri in the background when you sign in.": "ሲገቡ Kiriን ከበስተጀርባ ጀምር።", + "Stop the engine when Kiri quits": "ከKiri ሲወጡ ሞተሩን አቁም", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ከKiri መውጣት የሚሠሩ ኮንቴይነሮችን እና ሞተሩን ያቆማል። Kiriን መክፈት እንደገና ያስጀምረዋል።" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index 04701d3a5..624faeaa9 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1859,5 +1859,9 @@ "WSL integration": "تكامل WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "إغلاق: تُحرَّر الذاكرة التي تستخدمها النافذة. تستغرق لحظة لتُفتح مجددًا، وتُنهى الطرفيات المفتوحة.", "Closing the window": "عند إغلاق النافذة", - "Hide: the window stays ready and opens again at once.": "إخفاء: تبقى النافذة جاهزة وتُفتح مجددًا على الفور." + "Hide: the window stays ready and opens again at once.": "إخفاء: تبقى النافذة جاهزة وتُفتح مجددًا على الفور.", + "Start Kiri at sign-in": "بدء Kiri عند تسجيل الدخول", + "Start Kiri in the background when you sign in.": "بدء Kiri في الخلفية عند تسجيل دخولك.", + "Stop the engine when Kiri quits": "إيقاف المحرّك عند إنهاء Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "إنهاء Kiri يوقف الحاويات التي تعمل والمحرّك. فتح Kiri يبدؤه من جديد." } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 646d09c4c..3c1c8aefe 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1859,5 +1859,9 @@ "WSL integration": "Интеграция с WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Затваряне: паметта, която прозорецът използва, се освобождава. Отварянето му отново отнема миг, а отворените терминали се затварят.", "Closing the window": "Затваряне на прозореца", - "Hide: the window stays ready and opens again at once.": "Скриване: прозорецът остава готов и се отваря отново веднага." + "Hide: the window stays ready and opens again at once.": "Скриване: прозорецът остава готов и се отваря отново веднага.", + "Start Kiri at sign-in": "Стартиране на Kiri при влизане", + "Start Kiri in the background when you sign in.": "Стартиране на Kiri във фонов режим, когато влезете.", + "Stop the engine when Kiri quits": "Спиране на двигателя при излизане от Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Излизането от Kiri спира работещите контейнери и двигателя. Отварянето на Kiri го стартира отново." } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 9f2557414..815b50f98 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL ইন্টিগ্রেশন", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "বন্ধ করুন: উইন্ডোর ব্যবহৃত মেমরি মুক্ত হয়। আবার খুলতে একটু সময় লাগে, এবং খোলা টার্মিনালগুলো বন্ধ হয়ে যায়।", "Closing the window": "উইন্ডো বন্ধ করলে", - "Hide: the window stays ready and opens again at once.": "লুকান: উইন্ডো প্রস্তুত থাকে এবং সঙ্গে সঙ্গে আবার খোলে।" + "Hide: the window stays ready and opens again at once.": "লুকান: উইন্ডো প্রস্তুত থাকে এবং সঙ্গে সঙ্গে আবার খোলে।", + "Start Kiri at sign-in": "সাইন ইন করার সময় Kiri চালু করুন", + "Start Kiri in the background when you sign in.": "আপনি সাইন ইন করলে পটভূমিতে Kiri চালু করুন।", + "Stop the engine when Kiri quits": "Kiri বন্ধ করলে ইঞ্জিন থামান", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri বন্ধ করলে চলমান কন্টেইনার এবং ইঞ্জিন থেমে যায়। Kiri খুললে এটি আবার চালু হয়।" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 7d7525e71..c4776d971 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integració amb WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tanca: s’allibera la memòria que fa servir la finestra. Tarda un moment a tornar-se a obrir, i els terminals oberts es tanquen.", "Closing the window": "En tancar la finestra", - "Hide: the window stays ready and opens again at once.": "Amaga: la finestra es manté a punt i es torna a obrir a l’instant." + "Hide: the window stays ready and opens again at once.": "Amaga: la finestra es manté a punt i es torna a obrir a l’instant.", + "Start Kiri at sign-in": "Inicia Kiri en iniciar la sessió", + "Start Kiri in the background when you sign in.": "Inicia Kiri en segon pla quan inicies la sessió.", + "Stop the engine when Kiri quits": "Atura el motor en sortir de Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "En sortir de Kiri s'aturen els contenidors en execució i el motor. En obrir Kiri es torna a iniciar." } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index c90f21cf4..e0736816a 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1859,5 +1859,9 @@ "WSL integration": "ئاوێتەکردنی WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "داخستن: ئەو بیرگەیەی پەنجەرەکە بەکاری دەهێنێت ئازاد دەکرێت. کردنەوەی دووبارەی کەمێک کات دەبات، و تێرمیناڵە کراوەکان کۆتاییان دێت.", "Closing the window": "داخستنی پەنجەرە", - "Hide: the window stays ready and opens again at once.": "شاردنەوە: پەنجەرەکە ئامادە دەمێنێتەوە و دەستبەجێ دەکرێتەوە." + "Hide: the window stays ready and opens again at once.": "شاردنەوە: پەنجەرەکە ئامادە دەمێنێتەوە و دەستبەجێ دەکرێتەوە.", + "Start Kiri at sign-in": "لە کاتی چوونەژوورەوە Kiri دەست پێبکە", + "Start Kiri in the background when you sign in.": "کاتێک دەچیتە ژوورەوە Kiri لە پاشبنەمادا دەست پێبکە.", + "Stop the engine when Kiri quits": "کاتێک لە Kiri دەردەچیت بزوێنەر ڕابگرە", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "دەرچوون لە Kiri کۆنتەینەرە کاراکان و بزوێنەر ڕادەگرێت. کردنەوەی Kiri دووبارە دەستی پێدەکاتەوە." } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index 211df2b14..b0a060ccc 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integrace s WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zavřít: paměť, kterou okno používá, se uvolní. Znovu se otevře až po chvilce a otevřené terminály se ukončí.", "Closing the window": "Zavření okna", - "Hide: the window stays ready and opens again at once.": "Skrýt: okno zůstane připravené a znovu se otevře hned." + "Hide: the window stays ready and opens again at once.": "Skrýt: okno zůstane připravené a znovu se otevře hned.", + "Start Kiri at sign-in": "Spouštět Kiri při přihlášení", + "Start Kiri in the background when you sign in.": "Spustit Kiri na pozadí, když se přihlásíte.", + "Stop the engine when Kiri quits": "Zastavit engine při ukončení Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ukončení Kiri zastaví běžící kontejnery a engine. Otevření Kiri ho znovu spustí." } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index dc1d25faf..b905b19d5 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL-Integration", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Schließen: Der Speicher des Fensters wird freigegeben. Es braucht einen Moment, um wieder zu öffnen, und offene Terminals werden beendet.", "Closing the window": "Beim Schließen des Fensters", - "Hide: the window stays ready and opens again at once.": "Ausblenden: Das Fenster bleibt bereit und öffnet sich sofort wieder." + "Hide: the window stays ready and opens again at once.": "Ausblenden: Das Fenster bleibt bereit und öffnet sich sofort wieder.", + "Start Kiri at sign-in": "Kiri bei der Anmeldung starten", + "Start Kiri in the background when you sign in.": "Kiri im Hintergrund starten, wenn du dich anmeldest.", + "Stop the engine when Kiri quits": "Engine beim Beenden von Kiri stoppen", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Das Beenden von Kiri stoppt laufende Container und die Engine. Das Öffnen von Kiri startet sie erneut." } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 627715548..dc6eb4d63 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1859,5 +1859,9 @@ "WSL integration": "Ενσωμάτωση WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Κλείσιμο: η μνήμη που χρησιμοποιεί το παράθυρο ελευθερώνεται. Χρειάζεται μια στιγμή για να ανοίξει ξανά, και τα ανοιχτά τερματικά τερματίζονται.", "Closing the window": "Κλείσιμο του παραθύρου", - "Hide: the window stays ready and opens again at once.": "Απόκρυψη: το παράθυρο μένει έτοιμο και ανοίγει ξανά αμέσως." + "Hide: the window stays ready and opens again at once.": "Απόκρυψη: το παράθυρο μένει έτοιμο και ανοίγει ξανά αμέσως.", + "Start Kiri at sign-in": "Εκκίνηση του Kiri κατά τη σύνδεση", + "Start Kiri in the background when you sign in.": "Εκκίνηση του Kiri στο παρασκήνιο όταν συνδέεστε.", + "Stop the engine when Kiri quits": "Διακοπή της μηχανής κατά τον τερματισμό του Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ο τερματισμός του Kiri σταματά τα κοντέινερ που εκτελούνται και τη μηχανή. Το άνοιγμα του Kiri την ξεκινά ξανά." } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index 98d5e95c4..e431b3383 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integración con WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Cerrar: se libera la memoria que usa la ventana. Tarda un momento en volver a abrirse y los terminales abiertos se cierran.", "Closing the window": "Al cerrar la ventana", - "Hide: the window stays ready and opens again at once.": "Ocultar: la ventana sigue lista y se abre de nuevo al instante." + "Hide: the window stays ready and opens again at once.": "Ocultar: la ventana sigue lista y se abre de nuevo al instante.", + "Start Kiri at sign-in": "Iniciar Kiri al iniciar sesión", + "Start Kiri in the background when you sign in.": "Inicia Kiri en segundo plano cuando inicias sesión.", + "Stop the engine when Kiri quits": "Detener el motor al salir de Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Salir de Kiri detiene los contenedores en marcha y el motor. Abrir Kiri lo vuelve a iniciar." } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index 911676834..75fafa34b 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1859,5 +1859,9 @@ "WSL integration": "یکپارچه‌سازی WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "بستن: حافظه‌ای که پنجره مصرف می‌کند آزاد می‌شود. باز شدن دوباره‌اش کمی طول می‌کشد و ترمینال‌های باز بسته می‌شوند.", "Closing the window": "بستن پنجره", - "Hide: the window stays ready and opens again at once.": "پنهان کردن: پنجره آماده می‌ماند و بی‌درنگ دوباره باز می‌شود." + "Hide: the window stays ready and opens again at once.": "پنهان کردن: پنجره آماده می‌ماند و بی‌درنگ دوباره باز می‌شود.", + "Start Kiri at sign-in": "شروع Kiri هنگام ورود", + "Start Kiri in the background when you sign in.": "هنگام ورود شما، Kiri را در پس‌زمینه شروع کند.", + "Stop the engine when Kiri quits": "توقف موتور هنگام خروج از Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "خروج از Kiri کانتینرهای در حال اجرا و موتور را متوقف می‌کند. باز کردن Kiri دوباره آن را شروع می‌کند." } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index c6021bf1f..e0546520a 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL-integraatio", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Sulje: ikkunan käyttämä muisti vapautetaan. Uudelleen avautuminen kestää hetken, ja avoimet päätteet suljetaan.", "Closing the window": "Ikkunan sulkeminen", - "Hide: the window stays ready and opens again at once.": "Piilota: ikkuna pysyy valmiina ja avautuu heti uudelleen." + "Hide: the window stays ready and opens again at once.": "Piilota: ikkuna pysyy valmiina ja avautuu heti uudelleen.", + "Start Kiri at sign-in": "Käynnistä Kiri sisäänkirjautuessa", + "Start Kiri in the background when you sign in.": "Käynnistä Kiri taustalla, kun kirjaudut sisään.", + "Stop the engine when Kiri quits": "Pysäytä moottori, kun Kiri lopetetaan", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kirin lopettaminen pysäyttää käynnissä olevat kontit ja moottorin. Kirin avaaminen käynnistää sen uudelleen." } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index a1e1d38bd..ae76d26f1 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1859,5 +1859,9 @@ "WSL integration": "Intégration WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fermer : la mémoire utilisée par la fenêtre est libérée. Elle met un instant à se rouvrir, et les terminaux ouverts se ferment.", "Closing the window": "Fermeture de la fenêtre", - "Hide: the window stays ready and opens again at once.": "Masquer : la fenêtre reste prête et se rouvre aussitôt." + "Hide: the window stays ready and opens again at once.": "Masquer : la fenêtre reste prête et se rouvre aussitôt.", + "Start Kiri at sign-in": "Démarrer Kiri à l’ouverture de session", + "Start Kiri in the background when you sign in.": "Démarre Kiri en arrière-plan à l’ouverture de votre session.", + "Stop the engine when Kiri quits": "Arrêter le moteur en quittant Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Quitter Kiri arrête les conteneurs en marche et le moteur. Ouvrir Kiri le relance." } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 6f476c585..1b138b0be 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL एकीकरण", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "बंद करें: विंडो की इस्तेमाल की गई मेमोरी खाली हो जाती है। फिर से खुलने में थोड़ा समय लगता है, और खुले टर्मिनल बंद हो जाते हैं।", "Closing the window": "विंडो बंद करने पर", - "Hide: the window stays ready and opens again at once.": "छिपाएँ: विंडो तैयार रहती है और तुरंत फिर से खुलती है।" + "Hide: the window stays ready and opens again at once.": "छिपाएँ: विंडो तैयार रहती है और तुरंत फिर से खुलती है।", + "Start Kiri at sign-in": "साइन इन पर Kiri शुरू करें", + "Start Kiri in the background when you sign in.": "जब आप साइन इन करते हैं तो Kiri को बैकग्राउंड में शुरू करें।", + "Stop the engine when Kiri quits": "Kiri बंद करने पर इंजन रोकें", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri बंद करने से चलते कंटेनर और इंजन रुक जाते हैं। Kiri खोलने पर यह फिर शुरू हो जाता है।" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index a1e39316b..6c68d2a7c 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL-integráció", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Bezárás: az ablak által használt memória felszabadul. Újbóli megnyitása egy pillanatig tart, a nyitott terminálok pedig bezárulnak.", "Closing the window": "Az ablak bezárásakor", - "Hide: the window stays ready and opens again at once.": "Elrejtés: az ablak készenlétben marad, és azonnal újra megnyílik." + "Hide: the window stays ready and opens again at once.": "Elrejtés: az ablak készenlétben marad, és azonnal újra megnyílik.", + "Start Kiri at sign-in": "A Kiri indítása bejelentkezéskor", + "Start Kiri in the background when you sign in.": "A Kiri indítása a háttérben bejelentkezéskor.", + "Stop the engine when Kiri quits": "A motor leállítása a Kiriből való kilépéskor", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "A Kiriből való kilépés leállítja a futó konténereket és a motort. A Kiri megnyitása újra elindítja." } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index c93975655..0f53c1068 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integrasi WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tutup: memori yang dipakai jendela dibebaskan. Perlu sesaat untuk membukanya lagi, dan terminal yang terbuka ditutup.", "Closing the window": "Saat menutup jendela", - "Hide: the window stays ready and opens again at once.": "Sembunyikan: jendela tetap siap dan langsung terbuka lagi." + "Hide: the window stays ready and opens again at once.": "Sembunyikan: jendela tetap siap dan langsung terbuka lagi.", + "Start Kiri at sign-in": "Mulai Kiri saat masuk", + "Start Kiri in the background when you sign in.": "Mulai Kiri di latar belakang saat Anda masuk.", + "Stop the engine when Kiri quits": "Hentikan engine saat keluar dari Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Keluar dari Kiri menghentikan kontainer yang berjalan dan engine. Membuka Kiri akan memulainya lagi." } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 16db90d1c..7c6901fd9 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integrazione WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Chiudi: la memoria usata dalla finestra viene liberata. Ci vuole un attimo per riaprirla e i terminali aperti si chiudono.", "Closing the window": "Chiusura della finestra", - "Hide: the window stays ready and opens again at once.": "Nascondi: la finestra resta pronta e si riapre subito." + "Hide: the window stays ready and opens again at once.": "Nascondi: la finestra resta pronta e si riapre subito.", + "Start Kiri at sign-in": "Avvia Kiri all'accesso", + "Start Kiri in the background when you sign in.": "Avvia Kiri in background quando accedi.", + "Stop the engine when Kiri quits": "Ferma il motore quando esci da Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Uscendo da Kiri si fermano i container in esecuzione e il motore. Aprendo Kiri si avvia di nuovo." } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index 479592ed4..1d6e14530 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL 統合", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "閉じる:ウインドウが使うメモリを解放します。再び開くまでに少し時間がかかり、開いているターミナルは終了します。", "Closing the window": "ウインドウを閉じたとき", - "Hide: the window stays ready and opens again at once.": "隠す:ウインドウは準備されたまま残り、すぐに再び開きます。" + "Hide: the window stays ready and opens again at once.": "隠す:ウインドウは準備されたまま残り、すぐに再び開きます。", + "Start Kiri at sign-in": "サインイン時に Kiri を起動", + "Start Kiri in the background when you sign in.": "サインインしたときにバックグラウンドで Kiri を起動します。", + "Stop the engine when Kiri quits": "Kiri の終了時にエンジンを停止", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri を終了すると、実行中のコンテナとエンジンが停止します。Kiri を開くと再び起動します。" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index c479594ce..11c7510c3 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL интеграциясы", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Жабу: терезе пайдаланатын жад босатылады. Қайта ашылуына біраз уақыт кетеді, ал ашық терминалдар жабылады.", "Closing the window": "Терезені жапқанда", - "Hide: the window stays ready and opens again at once.": "Жасыру: терезе дайын күйде қалады және бірден қайта ашылады." + "Hide: the window stays ready and opens again at once.": "Жасыру: терезе дайын күйде қалады және бірден қайта ашылады.", + "Start Kiri at sign-in": "Жүйеге кіргенде Kiri-ді іске қосу", + "Start Kiri in the background when you sign in.": "Жүйеге кірген кезде Kiri-ді фонда іске қосады.", + "Stop the engine when Kiri quits": "Kiri-ден шыққанда қозғалтқышты тоқтату", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ден шығу жұмыс істеп тұрған контейнерлер мен қозғалтқышты тоқтатады. Kiri-ді ашу оны қайта іске қосады." } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 9569db397..880c6e362 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL 통합", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "닫기: 창이 쓰는 메모리를 해제합니다. 다시 여는 데 잠시 걸리며, 열려 있는 터미널은 종료됩니다.", "Closing the window": "창을 닫을 때", - "Hide: the window stays ready and opens again at once.": "숨기기: 창이 준비된 채로 남아 바로 다시 열립니다." + "Hide: the window stays ready and opens again at once.": "숨기기: 창이 준비된 채로 남아 바로 다시 열립니다.", + "Start Kiri at sign-in": "로그인할 때 Kiri 시작", + "Start Kiri in the background when you sign in.": "로그인할 때 백그라운드에서 Kiri를 시작합니다.", + "Stop the engine when Kiri quits": "Kiri를 종료할 때 엔진 중지", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri를 종료하면 실행 중인 컨테이너와 엔진이 중지됩니다. Kiri를 열면 다시 시작됩니다." } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 5b57ebab5..55671f8d5 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1859,5 +1859,9 @@ "WSL integration": "ການເຊື່ອມໂຍງ WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ປິດ: ໜ່ວຍຄວາມຈຳທີ່ໜ້າຕ່າງໃຊ້ຈະຖືກປ່ອຍຄືນ. ການເປີດຄືນຈະໃຊ້ເວລາໜ້ອຍໜຶ່ງ ແລະ ເທີມິນອນທີ່ເປີດຢູ່ຈະຖືກປິດ.", "Closing the window": "ເມື່ອປິດໜ້າຕ່າງ", - "Hide: the window stays ready and opens again at once.": "ເຊື່ອງ: ໜ້າຕ່າງຈະກຽມພ້ອມໄວ້ ແລະ ເປີດຄືນໄດ້ທັນທີ." + "Hide: the window stays ready and opens again at once.": "ເຊື່ອງ: ໜ້າຕ່າງຈະກຽມພ້ອມໄວ້ ແລະ ເປີດຄືນໄດ້ທັນທີ.", + "Start Kiri at sign-in": "ເລີ່ມ Kiri ເມື່ອເຂົ້າສູ່ລະບົບ", + "Start Kiri in the background when you sign in.": "ເລີ່ມ Kiri ໃນພື້ນຫຼັງເມື່ອທ່ານເຂົ້າສູ່ລະບົບ.", + "Stop the engine when Kiri quits": "ຢຸດເອນຈິນເມື່ອອອກຈາກ Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ການອອກຈາກ Kiri ຈະຢຸດຄອນເທນເນີທີ່ແລ່ນຢູ່ ແລະ ເອນຈິນ. ການເປີດ Kiri ຈະເລີ່ມມັນໃໝ່." } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 92845dd8b..a5ccc677c 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL integracija", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Uždaryti: lango naudojama atmintis atlaisvinama. Vėl atsidaryti užtrunka akimirką, o atviri terminalai užbaigiami.", "Closing the window": "Uždarant langą", - "Hide: the window stays ready and opens again at once.": "Slėpti: langas lieka paruoštas ir iškart atsidaro vėl." + "Hide: the window stays ready and opens again at once.": "Slėpti: langas lieka paruoštas ir iškart atsidaro vėl.", + "Start Kiri at sign-in": "Paleisti Kiri prisijungus", + "Start Kiri in the background when you sign in.": "Paleisti Kiri fone, kai prisijungiate.", + "Stop the engine when Kiri quits": "Sustabdyti variklį išėjus iš Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Išėjus iš Kiri sustabdomi veikiantys konteineriai ir variklis. Atidarius Kiri jis paleidžiamas vėl." } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 48325a36f..686ad92be 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL-integrering", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Lukk: minnet vinduet bruker, frigjøres. Det tar et øyeblikk å åpne det igjen, og åpne terminaler avsluttes.", "Closing the window": "Når vinduet lukkes", - "Hide: the window stays ready and opens again at once.": "Skjul: vinduet holdes klart og åpnes igjen med en gang." + "Hide: the window stays ready and opens again at once.": "Skjul: vinduet holdes klart og åpnes igjen med en gang.", + "Start Kiri at sign-in": "Start Kiri ved pålogging", + "Start Kiri in the background when you sign in.": "Start Kiri i bakgrunnen når du logger inn.", + "Stop the engine when Kiri quits": "Stopp motoren når Kiri avsluttes", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Å avslutte Kiri stopper kjørende containere og motoren. Å åpne Kiri starter den igjen." } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index 5c8edd1d2..f59620f17 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integracja z WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zamknij: pamięć używana przez okno zostaje zwolniona. Ponowne otwarcie zajmuje chwilę, a otwarte terminale zostają zakończone.", "Closing the window": "Zamykanie okna", - "Hide: the window stays ready and opens again at once.": "Ukryj: okno pozostaje gotowe i od razu otwiera się ponownie." + "Hide: the window stays ready and opens again at once.": "Ukryj: okno pozostaje gotowe i od razu otwiera się ponownie.", + "Start Kiri at sign-in": "Uruchamiaj Kiri po zalogowaniu", + "Start Kiri in the background when you sign in.": "Uruchamia Kiri w tle po zalogowaniu.", + "Stop the engine when Kiri quits": "Zatrzymuj silnik po zakończeniu Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Zakończenie Kiri zatrzymuje działające kontenery i silnik. Otwarcie Kiri uruchamia go ponownie." } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 2a9644458..c8a1b5c3d 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integração com o WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fechar: a memória usada pela janela é liberada. Leva um momento para abrir de novo, e os terminais abertos são encerrados.", "Closing the window": "Ao fechar a janela", - "Hide: the window stays ready and opens again at once.": "Ocultar: a janela continua pronta e abre de novo na hora." + "Hide: the window stays ready and opens again at once.": "Ocultar: a janela continua pronta e abre de novo na hora.", + "Start Kiri at sign-in": "Iniciar o Kiri ao entrar", + "Start Kiri in the background when you sign in.": "Inicia o Kiri em segundo plano quando você entra.", + "Stop the engine when Kiri quits": "Parar o engine ao sair do Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Sair do Kiri para os contêineres rodando e o engine. Abrir o Kiri o inicia de novo." } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index 83537c114..5c51cb2af 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integrare WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Închide: memoria folosită de fereastră este eliberată. Redeschiderea durează o clipă, iar terminalele deschise se închid.", "Closing the window": "La închiderea ferestrei", - "Hide: the window stays ready and opens again at once.": "Ascunde: fereastra rămâne pregătită și se redeschide imediat." + "Hide: the window stays ready and opens again at once.": "Ascunde: fereastra rămâne pregătită și se redeschide imediat.", + "Start Kiri at sign-in": "Pornește Kiri la conectare", + "Start Kiri in the background when you sign in.": "Pornește Kiri în fundal când te conectezi.", + "Stop the engine when Kiri quits": "Oprește motorul la ieșirea din Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ieșirea din Kiri oprește containerele care rulează și motorul. Deschiderea Kiri îl pornește din nou." } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index 1f6515fb5..de175d80c 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1859,5 +1859,9 @@ "WSL integration": "Интеграция с WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрыть: память, которую занимает окно, освобождается. Повторное открытие занимает мгновение, а открытые терминалы закрываются.", "Closing the window": "При закрытии окна", - "Hide: the window stays ready and opens again at once.": "Скрыть: окно остаётся готовым и сразу открывается снова." + "Hide: the window stays ready and opens again at once.": "Скрыть: окно остаётся готовым и сразу открывается снова.", + "Start Kiri at sign-in": "Запускать Kiri при входе в систему", + "Start Kiri in the background when you sign in.": "Запускать Kiri в фоновом режиме при входе в систему.", + "Stop the engine when Kiri quits": "Останавливать движок при выходе из Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Выход из Kiri останавливает запущенные контейнеры и движок. Открытие Kiri запускает его снова." } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index ac9b3b64f..ce64946a5 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integracija z WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zapri: pomnilnik, ki ga uporablja okno, se sprosti. Ponovno odpiranje traja trenutek, odprti terminali pa se končajo.", "Closing the window": "Ob zapiranju okna", - "Hide: the window stays ready and opens again at once.": "Skrij: okno ostane pripravljeno in se takoj znova odpre." + "Hide: the window stays ready and opens again at once.": "Skrij: okno ostane pripravljeno in se takoj znova odpre.", + "Start Kiri at sign-in": "Zaženi Kiri ob prijavi", + "Start Kiri in the background when you sign in.": "Zažene Kiri v ozadju, ko se prijavite.", + "Stop the engine when Kiri quits": "Ustavi pogon, ko zaprete Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ko zaprete Kiri, se ustavijo kontejnerji, ki tečejo, in pogon. Ko odprete Kiri, se znova zažene." } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 131b4c99d..73e4c2077 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1859,5 +1859,9 @@ "WSL integration": "Integrimi me WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Mbyll: memoria që përdor dritarja lirohet. Rihapja zgjat një çast dhe terminalet e hapura mbyllen.", "Closing the window": "Kur mbyllet dritarja", - "Hide: the window stays ready and opens again at once.": "Fshih: dritarja mbetet gati dhe hapet sërish menjëherë." + "Hide: the window stays ready and opens again at once.": "Fshih: dritarja mbetet gati dhe hapet sërish menjëherë.", + "Start Kiri at sign-in": "Nis Kiri gjatë identifikimit", + "Start Kiri in the background when you sign in.": "Nis Kiri në sfond kur identifikoheni.", + "Stop the engine when Kiri quits": "Ndal motorin kur dilni nga Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Dalja nga Kiri ndal kontejnerët në punë dhe motorin. Hapja e Kiri e nis sërish." } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index d8b81bce5..e75f7789a 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL ஒருங்கிணைப்பு", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "மூடு: சாளரம் பயன்படுத்தும் நினைவகம் விடுவிக்கப்படும். மீண்டும் திறக்கச் சற்று நேரமாகும், திறந்திருக்கும் டெர்மினல்கள் முடிவடையும்.", "Closing the window": "சாளரத்தை மூடும்போது", - "Hide: the window stays ready and opens again at once.": "மறை: சாளரம் தயாராக இருந்து உடனே மீண்டும் திறக்கும்." + "Hide: the window stays ready and opens again at once.": "மறை: சாளரம் தயாராக இருந்து உடனே மீண்டும் திறக்கும்.", + "Start Kiri at sign-in": "உள்நுழையும்போது Kiri-ஐத் தொடங்கு", + "Start Kiri in the background when you sign in.": "நீங்கள் உள்நுழையும்போது பின்னணியில் Kiri-ஐத் தொடங்கும்.", + "Stop the engine when Kiri quits": "Kiri-ஐ மூடும்போது இன்ஜினை நிறுத்து", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ஐ மூடினால் இயங்கும் கன்டெய்னர்களும் இன்ஜினும் நிற்கும். Kiri-ஐத் திறந்தால் மீண்டும் தொடங்கும்." } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 7cc00c1bd..dbeccdeb1 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL ఇంటిగ్రేషన్", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "మూసివేయి: విండో వాడే మెమరీ విడుదల అవుతుంది. మళ్లీ తెరవడానికి కొంత సమయం పడుతుంది, తెరిచి ఉన్న టెర్మినల్స్ ముగుస్తాయి.", "Closing the window": "విండోను మూసినప్పుడు", - "Hide: the window stays ready and opens again at once.": "దాచు: విండో సిద్ధంగా ఉండి వెంటనే మళ్లీ తెరుచుకుంటుంది." + "Hide: the window stays ready and opens again at once.": "దాచు: విండో సిద్ధంగా ఉండి వెంటనే మళ్లీ తెరుచుకుంటుంది.", + "Start Kiri at sign-in": "సైన్ ఇన్ అయినప్పుడు Kiriని ప్రారంభించు", + "Start Kiri in the background when you sign in.": "మీరు సైన్ ఇన్ అయినప్పుడు నేపథ్యంలో Kiriని ప్రారంభిస్తుంది.", + "Stop the engine when Kiri quits": "Kiri నుండి నిష్క్రమించినప్పుడు ఇంజిన్‌ను ఆపు", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri నుండి నిష్క్రమిస్తే రన్ అవుతున్న కంటైనర్‌లు మరియు ఇంజిన్ ఆగిపోతాయి. Kiriని తెరిస్తే అది మళ్లీ ప్రారంభమవుతుంది." } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index da0293186..a4c8becfe 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1859,5 +1859,9 @@ "WSL integration": "การผสานรวม WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ปิด: คืนหน่วยความจำที่หน้าต่างใช้ การเปิดอีกครั้งจะใช้เวลาสักครู่ และเทอร์มินัลที่เปิดอยู่จะถูกปิด", "Closing the window": "เมื่อปิดหน้าต่าง", - "Hide: the window stays ready and opens again at once.": "ซ่อน: หน้าต่างพร้อมอยู่เสมอและเปิดกลับมาได้ทันที" + "Hide: the window stays ready and opens again at once.": "ซ่อน: หน้าต่างพร้อมอยู่เสมอและเปิดกลับมาได้ทันที", + "Start Kiri at sign-in": "เริ่ม Kiri เมื่อลงชื่อเข้าใช้", + "Start Kiri in the background when you sign in.": "เริ่ม Kiri ในพื้นหลังเมื่อคุณลงชื่อเข้าใช้", + "Stop the engine when Kiri quits": "หยุดเอนจินเมื่อออกจาก Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "การออกจาก Kiri จะหยุดคอนเทนเนอร์ที่ทำงานอยู่และเอนจิน การเปิด Kiri จะเริ่มเอนจินอีกครั้ง" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index dca339ea9..0243e356a 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL entegrasyonu", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Kapat: pencerenin kullandığı bellek boşaltılır. Yeniden açılması biraz sürer ve açık terminaller kapanır.", "Closing the window": "Pencere kapatılınca", - "Hide: the window stays ready and opens again at once.": "Gizle: pencere hazır bekler ve hemen yeniden açılır." + "Hide: the window stays ready and opens again at once.": "Gizle: pencere hazır bekler ve hemen yeniden açılır.", + "Start Kiri at sign-in": "Oturum açıldığında Kiri'yi başlat", + "Start Kiri in the background when you sign in.": "Oturum açtığınızda Kiri'yi arka planda başlatır.", + "Stop the engine when Kiri quits": "Kiri'den çıkıldığında motoru durdur", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri'den çıkmak çalışan kapsayıcıları ve motoru durdurur. Kiri'yi açmak onu yeniden başlatır." } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 7ee82e07b..14446cdb6 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1859,5 +1859,9 @@ "WSL integration": "Інтеграція з WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрити: пам’ять, яку займає вікно, звільняється. Повторне відкриття триває мить, а відкриті термінали закриваються.", "Closing the window": "Закриття вікна", - "Hide: the window stays ready and opens again at once.": "Приховати: вікно залишається готовим і одразу відкривається знову." + "Hide: the window stays ready and opens again at once.": "Приховати: вікно залишається готовим і одразу відкривається знову.", + "Start Kiri at sign-in": "Запускати Kiri під час входу в систему", + "Start Kiri in the background when you sign in.": "Запускати Kiri у фоновому режимі під час входу в систему.", + "Stop the engine when Kiri quits": "Зупиняти рушій під час виходу з Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Вихід із Kiri зупиняє запущені контейнери та рушій. Відкриття Kiri запускає його знову." } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index fd82cad0e..31377822f 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1859,5 +1859,9 @@ "WSL integration": "Tích hợp WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Đóng: giải phóng bộ nhớ cửa sổ đang dùng. Mở lại sẽ mất một lúc, và các terminal đang mở sẽ bị đóng.", "Closing the window": "Khi đóng cửa sổ", - "Hide: the window stays ready and opens again at once.": "Ẩn: cửa sổ luôn sẵn sàng và mở lại ngay." + "Hide: the window stays ready and opens again at once.": "Ẩn: cửa sổ luôn sẵn sàng và mở lại ngay.", + "Start Kiri at sign-in": "Khởi động Kiri khi đăng nhập", + "Start Kiri in the background when you sign in.": "Khởi động Kiri dưới nền khi bạn đăng nhập.", + "Stop the engine when Kiri quits": "Dừng engine khi thoát Kiri", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Thoát Kiri sẽ dừng các container đang chạy và engine. Mở Kiri sẽ khởi động lại nó." } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 942faa6c3..e7e4f6e6e 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL 集成", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "关闭:释放窗口占用的内存。重新打开需要片刻,已打开的终端会结束。", "Closing the window": "关闭窗口时", - "Hide: the window stays ready and opens again at once.": "隐藏:窗口保持就绪,可立即重新打开。" + "Hide: the window stays ready and opens again at once.": "隐藏:窗口保持就绪,可立即重新打开。", + "Start Kiri at sign-in": "登录时启动 Kiri", + "Start Kiri in the background when you sign in.": "登录时在后台启动 Kiri。", + "Stop the engine when Kiri quits": "退出 Kiri 时停止引擎", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "退出 Kiri 会停止正在运行的容器和引擎。打开 Kiri 会再次启动它。" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index fa6463463..60309d22a 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1859,5 +1859,9 @@ "WSL integration": "WSL 整合", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "關閉:釋放視窗占用的記憶體。重新開啟需要片刻,已開啟的終端機會結束。", "Closing the window": "關閉視窗時", - "Hide: the window stays ready and opens again at once.": "隱藏:視窗保持就緒,可立即重新開啟。" + "Hide: the window stays ready and opens again at once.": "隱藏:視窗保持就緒,可立即重新開啟。", + "Start Kiri at sign-in": "登入時啟動 Kiri", + "Start Kiri in the background when you sign in.": "登入時在背景啟動 Kiri。", + "Stop the engine when Kiri quits": "結束 Kiri 時停止引擎", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "結束 Kiri 會停止正在執行的容器與引擎。開啟 Kiri 會再次啟動它。" } diff --git a/crates/kiri/src/ui/linux.rs b/crates/kiri/src/ui/linux.rs index d0958584a..c4e0bfa6d 100644 --- a/crates/kiri/src/ui/linux.rs +++ b/crates/kiri/src/ui/linux.rs @@ -47,6 +47,23 @@ pub mod setup { let out = std::process::Command::new("docker").args(["context", "use", name]).output()?; if out.status.success() { Ok(()) } else { Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) } } + + fn config_dir() -> Option { + let xdg = std::env::var_os("XDG_CONFIG_HOME").map(std::path::PathBuf::from); + let home = std::env::var_os("HOME").map(std::path::PathBuf::from); + crate::ui::xdg_config_dir(xdg.as_deref(), home.as_deref()) + } + + pub fn start_at_login() -> bool { + config_dir().is_some_and(|d| crate::ui::linux_autostart_at(&d)) + } + + pub fn set_start_at_login(on: bool) -> io::Result<()> { + let dir = config_dir().ok_or_else(|| io::Error::other("HOME is not set"))?; + crate::ui::set_linux_autostart_at(&dir, on) + } + + pub fn bootout_agent() {} } pub mod update { @@ -114,6 +131,10 @@ pub mod update { pub fn start_engine() -> io::Result<()> { Err(super::engine_down()) } + + pub fn stop_engine() -> io::Result<()> { + Ok(()) + } } pub mod import { diff --git a/crates/kiri/src/ui/mac.rs b/crates/kiri/src/ui/mac.rs index a6c8064da..4f601b3a0 100644 --- a/crates/kiri/src/ui/mac.rs +++ b/crates/kiri/src/ui/mac.rs @@ -635,7 +635,9 @@ define_class!( if crate::update::staged().is_some() { match crate::update::install_staged() { Ok(version) => { - if let Err(e) = crate::update::restart_engine(&version) { + if !super::stop_on_quit() + && let Err(e) = crate::update::restart_engine(&version) + { diag::error!("the engine did not restart on the update", version = version, error = e); } } diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index f36533169..384cf104a 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -348,7 +348,16 @@ fn engine(rx: Receiver, tx: Sender) { refresh(&mut connected); } Ok(Cmd::RemoveNetwork(id)) => act("rmnet", expect_ok(client::request("DELETE", &format!("/networks/{id}"), None))), - Ok(Cmd::Quit) | Err(RecvTimeoutError::Disconnected) => return, + Ok(Cmd::Quit) | Err(RecvTimeoutError::Disconnected) => { + quit_with( + stop_on_quit(), + sharing::close_all, + stop_engine, + write_stopped_marker, + stop_daemon_on_quit, + ); + return; + } Err(RecvTimeoutError::Timeout) => { vm_panel(&mut connected); if connected && LISTED.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= LIST_EVERY { @@ -471,9 +480,100 @@ pub(crate) fn prefs() -> serde_json::Value { if p.get("theme").is_none() { p["theme"] = "dark".into(); } + if p.get("startAtLogin").is_none() { + p["startAtLogin"] = setup::start_at_login().into(); + } + if p.get("stopOnQuit").is_none() { + p["stopOnQuit"] = false.into(); + } p } +pub(crate) fn stop_on_quit() -> bool { + prefs()["stopOnQuit"] == true +} + +/// The XDG configuration directory: `$XDG_CONFIG_HOME`, else `$HOME/.config`. +#[cfg_attr(target_os = "macos", allow(dead_code))] +pub(crate) fn xdg_config_dir(xdg: Option<&std::path::Path>, home: Option<&std::path::Path>) -> Option { + if let Some(dir) = xdg.filter(|p| !p.as_os_str().is_empty()) { + return Some(dir.to_path_buf()); + } + home.filter(|p| !p.as_os_str().is_empty()).map(|h| h.join(".config")) +} + +#[cfg_attr(target_os = "macos", allow(dead_code))] +pub(crate) const AUTOSTART_DESKTOP: &str = "\ +[Desktop Entry] +Type=Application +Name=Kiri +GenericName=Containers +Comment=Run and share containers +Exec=kiri ui +Icon=kiri +Terminal=false +Categories=Development; +StartupWMClass=kiri +"; + +#[cfg_attr(target_os = "macos", allow(dead_code))] +pub(crate) fn linux_autostart_at(config_dir: &std::path::Path) -> bool { + config_dir.join("autostart/kiri.desktop").is_file() +} + +#[cfg_attr(target_os = "macos", allow(dead_code))] +pub(crate) fn set_linux_autostart_at(config_dir: &std::path::Path, on: bool) -> io::Result<()> { + let path = config_dir.join("autostart/kiri.desktop"); + if on { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(path, AUTOSTART_DESKTOP) + } else { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } + } +} + +fn quit_with( + stop_on_quit: bool, + close_shares: impl FnOnce(), + stop_containers: impl FnOnce() -> io::Result<()>, + mark_stopped: impl FnOnce(), + stop_daemon: impl FnOnce(), +) { + if !stop_on_quit { + return; + } + close_shares(); + let _ = stop_containers(); + mark_stopped(); + stop_daemon(); +} + +fn write_stopped_marker() { + if let Some(dir) = state_dir() { + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(dir.join("stopped"), b""); + } +} + +fn clear_stopped_marker() { + if let Some(dir) = state_dir() { + let _ = std::fs::remove_file(dir.join("stopped")); + } +} + +fn stop_daemon_on_quit() { + if let Err(e) = update::stop_engine() { + diag::warn!("engine did not stop on quit", error = e); + } + setup::bootout_agent(); +} + /// The USB view's note under the list, in the window's language /// (crate::usb words it in English; these are its notes). fn usb_words(mut v: serde_json::Value) -> serde_json::Value { @@ -520,7 +620,7 @@ fn page_gone() { } fn set_pref(name: &str, value: serde_json::Value) { - if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip" | "lang" | "langAsked" | "closeButton") { + if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip" | "lang" | "langAsked" | "closeButton" | "startAtLogin" | "stopOnQuit") { return; } let Some(path) = prefs_path() else { return }; @@ -1040,11 +1140,16 @@ fn free_on_mac(port: u16, proto: &str) -> bool { #[cfg_attr(target_os = "linux", allow(unreachable_code))] fn ensure_daemon() -> io::Result<()> { if client::alive() { + if stop_on_quit() && engine_stopped() { + clear_stopped_marker(); + let _ = client::request("POST", "/kiri/wake", None); + } return Ok(()); } // Linux: the engine is a system service, started by systemd, not by the window. #[cfg(target_os = "linux")] return Err(linux::engine_down()); + clear_stopped_marker(); update::start_engine() } @@ -1470,6 +1575,18 @@ mod tests { // Check for updates automatically stays off across launches. super::set_pref("updateAuto", false.into()); assert_eq!(super::prefs()["updateAuto"], false); + // Start at sign-in and Stop engine on quit persist in ui.json. + assert_eq!(super::prefs()["stopOnQuit"], false); + super::set_pref("stopOnQuit", true.into()); + assert_eq!(super::prefs()["stopOnQuit"], true); + assert!(super::stop_on_quit()); + super::set_pref("stopOnQuit", false.into()); + assert_eq!(super::prefs()["stopOnQuit"], false); + assert!(!super::stop_on_quit()); + super::set_pref("startAtLogin", false.into()); + assert_eq!(super::prefs()["startAtLogin"], false); + super::set_pref("startAtLogin", true.into()); + assert_eq!(super::prefs()["startAtLogin"], true); // Crash reports remember when they were turned on, and only the // setting itself can say so. super::set_pref("crashReportsSince", 1.into()); @@ -1485,6 +1602,79 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn stop_on_quit_handler_runs_steps_in_order_only_when_enabled() { + let steps = std::cell::RefCell::new(Vec::new()); + super::quit_with( + false, + || steps.borrow_mut().push("shares"), + || { + steps.borrow_mut().push("stop_containers"); + Ok(()) + }, + || steps.borrow_mut().push("mark_stopped"), + || steps.borrow_mut().push("stop_daemon"), + ); + assert!(steps.borrow().is_empty(), "off by default: quit leaves the engine running"); + + super::quit_with( + true, + || steps.borrow_mut().push("shares"), + || { + steps.borrow_mut().push("stop_containers"); + Ok(()) + }, + || steps.borrow_mut().push("mark_stopped"), + || steps.borrow_mut().push("stop_daemon"), + ); + assert_eq!(*steps.borrow(), ["shares", "stop_containers", "mark_stopped", "stop_daemon"]); + } + + #[test] + fn linux_xdg_autostart_creates_and_removes_desktop_file() { + let dir = std::env::temp_dir().join(format!("kiri-xdg-autostart-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let xdg = dir.join("xdg"); + let home = dir.join("home"); + assert_eq!(super::xdg_config_dir(Some(&xdg), Some(&home)), Some(xdg.clone())); + assert_eq!(super::xdg_config_dir(None, Some(&home)), Some(home.join(".config"))); + assert_eq!(super::xdg_config_dir(Some(std::path::Path::new("")), Some(&home)), Some(home.join(".config"))); + + assert!(!super::linux_autostart_at(&xdg)); + super::set_linux_autostart_at(&xdg, true).unwrap(); + assert!(super::linux_autostart_at(&xdg)); + let desktop = std::fs::read_to_string(xdg.join("autostart/kiri.desktop")).unwrap(); + assert!(desktop.contains("[Desktop Entry]") && desktop.contains("Exec=kiri ui\n"), "{desktop}"); + + super::set_linux_autostart_at(&xdg, false).unwrap(); + assert!(!super::linux_autostart_at(&xdg)); + assert!(!xdg.join("autostart/kiri.desktop").exists()); + // Removing again when already absent succeeds. + super::set_linux_autostart_at(&xdg, false).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn windows_registry_run_args_and_query_parsing() { + let run_key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; + let exe = r"C:\Users\me\AppData\Local\Kiri\kiri-win.exe"; + let val = format!("\"{exe}\" --background"); + let add = ["add", run_key, "/v", "Kiri", "/t", "REG_SZ", "/d", &val, "/f"]; + assert_eq!(add[5], "REG_SZ"); + assert_eq!(add[7], r#""C:\Users\me\AppData\Local\Kiri\kiri-win.exe" --background"#); + let parse = |ok: bool, stdout: &str, name: &str| { + ok && stdout.lines().any(|l| { + let mut parts = l.split_whitespace(); + parts.next().is_some_and(|n| n.eq_ignore_ascii_case(name)) + && parts.next().is_some_and(|t| t.eq_ignore_ascii_case("REG_SZ")) + }) + }; + let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n Kiri REG_SZ \"C:\\Users\\me\\AppData\\Local\\Kiri\\kiri-win.exe\" --background\r\n\r\n"; + assert!(parse(true, out, "Kiri")); + assert!(!parse(false, out, "Kiri")); + assert!(!parse(true, "", "Kiri")); + } + #[test] fn lists_installed_fonts() { let all = super::window::font_families(false); @@ -1627,6 +1817,15 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { if msg.name == "theme" { window::set_appearance(msg.value.as_str().unwrap_or("system")); } + if msg.name == "startAtLogin" + && let Some(on) = msg.value.as_bool() + && let Err(e) = setup::set_start_at_login(on) + { + diag::warn!("could not change start at sign-in", on = on, error = e); + emit(notice("error", &e.to_string())); + emit(serde_json::json!({"type": "prefs", "prefs": prefs()}).to_string()); + return; + } set_pref(&msg.name, msg.value); Ok(()) } @@ -2290,8 +2489,8 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { // Opening the window reaches the engine (starting its service if it // isn't running) but doesn't wake it: asleep, it reads Ready, and the // next docker command or action wakes it. One someone stopped waits - // for Start. - if autostart && !engine_stopped() { tx.send(Cmd::Connect) } else { Ok(()) } + // for Start, unless quitting stopped it (stopOnQuit). + if (autostart || cfg!(target_os = "macos") || stop_on_quit()) && (!engine_stopped() || stop_on_quit()) { tx.send(Cmd::Connect) } else { Ok(()) } } // The Linux setup checklist: check again, fix one or "all", open the // window once it's ready, or sign in again for the group to apply. diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 2327f83bc..38eda56ba 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -288,7 +288,7 @@ fn spawn_daemon() -> io::Result<()> { /// VM off and removes the socket), then SIGKILL if it is still there after /// 30 seconds. #[cfg(target_os = "macos")] -fn stop_engine() -> io::Result<()> { +pub fn stop_engine() -> io::Result<()> { let Some(pid) = engine_pid() else { return Ok(()) }; crate::diag::info!("stopping the engine", pid = pid); for (sig, wait) in [(libc::SIGTERM, 30_000u64), (libc::SIGKILL, 5_000)] { diff --git a/docs/features.md b/docs/features.md index d52393352..75c611f39 100644 --- a/docs/features.md +++ b/docs/features.md @@ -123,9 +123,10 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr container has its own page with details, live logs (find, level filter), a command line (and "Open in Terminal" for a full shell) and its files (preview, Save to Downloads, Show in Finder); Settings for fonts, text - size, the VM's CPUs, memory and disk image size (`~/.kiri/vm.json`, used from - the VM's next start; `KIRI_CPUS`, `KIRI_MEMORY_MIB` and `KIRI_DISK_GB` - override it; the disk grows online on boot and never shrinks) and local names + size, starting at sign-in, stopping the engine when Kiri quits, the VM's + CPUs, memory and disk image size (`~/.kiri/vm.json`, used from the VM's next + start; `KIRI_CPUS`, `KIRI_MEMORY_MIB` and `KIRI_DISK_GB` 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 diff --git a/docs/fix-registry.md b/docs/fix-registry.md index cc52ecd5c..665743705 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 +### #368 Settings: add Start Kiri at sign-in and Stop the engine when Kiri quits (unreleased) +- Fixes: #368 macOS: setting to stop the engine when Kiri quits; #703 Add "Launch at startup" toggle in app settings +- Caused: none known +- Caused by: - +- Check: none + ### #706, #539 UI: Linux tray icon and unified window-close setting (Hide vs Close) across macOS, Windows and Linux (unreleased) - Fixes: #405 Linux: close the window to the tray, as on Windows; #168 Release or suspend WebView2 memory when window is closed to tray (Lightweight background mode) - Caused: none known @@ -46,10 +52,6 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug - Caused by: - - Check: none - - - - ### #735 macOS: reach loopback-published ports and Kiri's resolver from `--network host` containers (unreleased) - Fixes: #732 macOS: `--network host` containers have no DNS and can't reach ports published on 127.0.0.1, so a host-network BuildKit can't push to a local registry - Caused: none known diff --git a/tests/ui/start-quit.js b/tests/ui/start-quit.js new file mode 100644 index 000000000..e36cd08dc --- /dev/null +++ b/tests/ui/start-quit.js @@ -0,0 +1,73 @@ +// parity: macos windows linux +// #368, #703: Settings → Appearance offers "Start Kiri at sign-in" and "Stop +// the engine when Kiri quits" on macOS, Windows and Linux, with per-system +// defaults before prefs arrive, setpref messages on click, and host updates. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; +const seen = (el) => !!el && !el.closest("[hidden]") && getComputedStyle(el).display !== "none"; +const pressed = (attr, v) => document.querySelector(`#content [${attr}="${v}"]`)?.getAttribute("aria-pressed"); +const state = () => ({ + loginOff: pressed("data-startlogin", "0"), + loginOn: pressed("data-startlogin", "1"), + quitOff: pressed("data-stopquit", "0"), + quitOn: pressed("data-stopquit", "1"), +}); + +prefs.tab = "appearance"; +delete prefs.startAtLogin; +delete prefs.stopOnQuit; +show("settings"); + +const items = []; +for (const [attr, name] of [["data-startlogin", "startAtLogin"], ["data-stopquit", "stopOnQuit"]]) { + for (const v of ["0", "1"]) { + if (seen(document.querySelector(`#content [${attr}="${v}"]`))) items.push(`appearance ${name} ${v}`); + } +} + +t("defaults match the system before prefs arrive", () => { + const defaultLogin = window.KIRI_OS !== "linux"; + eq(state(), { + loginOff: String(!defaultLogin), + loginOn: String(defaultLogin), + quitOff: "true", + quitOn: "false", + }, "defaults"); + const text = document.querySelector("#content .settings")?.textContent || ""; + if (!text.includes("Start Kiri at sign-in")) throw new Error("missing Start Kiri at sign-in label"); + if (!text.includes("Stop the engine when Kiri quits")) throw new Error("missing Stop the engine when Kiri quits label"); +}); + +t("toggling Start Kiri at sign-in updates aria-pressed and sends setpref", () => { + sent.length = 0; + document.querySelector('#content [data-startlogin="0"]').click(); + eq([state().loginOff, state().loginOn], ["true", "false"], "startAtLogin off"); + document.querySelector('#content [data-startlogin="1"]').click(); + eq([state().loginOff, state().loginOn], ["false", "true"], "startAtLogin on"); + eq( + sent.filter((x) => x.type === "setpref" && x.name === "startAtLogin").map((x) => x.value), + [false, true], + "startAtLogin setpref", + ); +}); + +t("host prefs event updates or reverts both toggles", () => { + kiri.on({ type: "prefs", prefs: { tab: "appearance", startAtLogin: false, stopOnQuit: true } }); + eq(state(), { loginOff: "true", loginOn: "false", quitOff: "false", quitOn: "true" }, "host prefs applied"); +}); + +t("toggling Stop the engine when Kiri quits updates aria-pressed and sends setpref", () => { + sent.length = 0; + document.querySelector('#content [data-stopquit="0"]').click(); + eq([state().quitOff, state().quitOn], ["true", "false"], "stopOnQuit off"); + document.querySelector('#content [data-stopquit="1"]').click(); + eq([state().quitOff, state().quitOn], ["false", "true"], "stopOnQuit on"); + eq( + sent.filter((x) => x.type === "setpref" && x.name === "stopOnQuit").map((x) => x.value), + [false, true], + "stopOnQuit setpref", + ); +}); + +report([...R, ...items.map((x) => "ITEM " + x)]); From ac8812b65a83cdccb35d88423765e25cf973c10e Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:10:29 +0100 Subject: [PATCH 045/157] Settings: show Docker socket owner, claim when free, and switch docker CLI context (#577, #369) (#828) --- crates/kiri-win/src/engine.rs | 93 +++-- crates/kiri-win/src/main.rs | 3 + crates/kiri-win/src/serve.rs | 31 +- crates/kiri-win/src/setup.rs | 24 ++ crates/kiri/src/dockerctx.rs | 487 +++++++++++++++++++++++++++ crates/kiri/src/main.rs | 3 + crates/kiri/src/setup.rs | 118 ++----- crates/kiri/src/ui/index.html | 105 +++++- crates/kiri/src/ui/lang/am.json | 26 +- crates/kiri/src/ui/lang/ar.json | 26 +- crates/kiri/src/ui/lang/bg.json | 26 +- crates/kiri/src/ui/lang/bn.json | 26 +- crates/kiri/src/ui/lang/ca.json | 26 +- crates/kiri/src/ui/lang/ckb.json | 26 +- crates/kiri/src/ui/lang/cs.json | 26 +- crates/kiri/src/ui/lang/de.json | 26 +- crates/kiri/src/ui/lang/el.json | 26 +- crates/kiri/src/ui/lang/es.json | 26 +- crates/kiri/src/ui/lang/fa.json | 26 +- crates/kiri/src/ui/lang/fi.json | 26 +- crates/kiri/src/ui/lang/fr.json | 26 +- crates/kiri/src/ui/lang/hi.json | 26 +- crates/kiri/src/ui/lang/hu.json | 26 +- crates/kiri/src/ui/lang/id.json | 26 +- crates/kiri/src/ui/lang/it.json | 26 +- crates/kiri/src/ui/lang/ja.json | 26 +- crates/kiri/src/ui/lang/kk.json | 26 +- crates/kiri/src/ui/lang/ko.json | 26 +- crates/kiri/src/ui/lang/lo.json | 26 +- crates/kiri/src/ui/lang/lt.json | 26 +- crates/kiri/src/ui/lang/nb.json | 26 +- crates/kiri/src/ui/lang/pl.json | 26 +- crates/kiri/src/ui/lang/pt-BR.json | 26 +- crates/kiri/src/ui/lang/ro.json | 26 +- crates/kiri/src/ui/lang/ru.json | 26 +- crates/kiri/src/ui/lang/sl.json | 26 +- crates/kiri/src/ui/lang/sq.json | 26 +- crates/kiri/src/ui/lang/ta.json | 26 +- crates/kiri/src/ui/lang/te.json | 26 +- crates/kiri/src/ui/lang/th.json | 26 +- crates/kiri/src/ui/lang/tr.json | 26 +- crates/kiri/src/ui/lang/uk.json | 26 +- crates/kiri/src/ui/lang/vi.json | 26 +- crates/kiri/src/ui/lang/zh-Hans.json | 26 +- crates/kiri/src/ui/lang/zh-Hant.json | 26 +- crates/kiri/src/ui/linux.rs | 96 ++++-- crates/kiri/src/ui/mod.rs | 80 ++++- docs/fix-registry.md | 6 + tests/ui/docker-socket.js | 129 +++++++ tests/ui/parity.js | 5 + 50 files changed, 1951 insertions(+), 191 deletions(-) create mode 100644 crates/kiri/src/dockerctx.rs create mode 100644 tests/ui/docker-socket.js diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 4807e180f..435621e5a 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -234,6 +234,7 @@ fn engine(rx: &Receiver, tx: Sender) { Err(RecvTimeoutError::Disconnected) => return, Err(RecvTimeoutError::Timeout) => { vm_panel(); + emit_docker_state_if_changed(); if LISTED.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= LIST_EVERY { refresh(); } @@ -763,12 +764,59 @@ fn about() { ); } -/// The status bar's left side: this build, and which engine `docker` talks -/// to by default, as `docker context show` says (it knows DOCKER_CONTEXT, -/// DOCKER_HOST and wherever Docker Desktop keeps the CLI config). -fn status_event() -> String { - let context = docker(&["context", "show"]).ok().map(|s| s.trim().to_owned()).filter(|c| !c.is_empty()); - json!({"type": "status", "version": env!("CARGO_PKG_VERSION"), "share": true, "app": "Kiri", "ours": "kiri", "context": context.unwrap_or_else(|| "default".into())}).to_string() +fn npipe_host(pipe: &str) -> String { + format!("npipe:{}", pipe.replace('\\', "/")) +} + +fn context_meta(dir: &std::path::Path, name: &str) -> std::path::PathBuf { + use sha2::Digest as _; + let sum = sha2::Sha256::digest(name.as_bytes()); + let hex: String = sum.iter().map(|b| format!("{b:02x}")).collect(); + dir.join("contexts/meta").join(hex) +} + +fn docker_state() -> (String, String) { + let endpoint = crate::serve::docker_engine_endpoint(); + let pipe = crate::client::pipe(); + let ours = npipe_host(&pipe); + let ctx = crate::flavor::CONTEXT.get(); + let cli = crate::dockerctx::current_cli(ctx, &[&ours], &endpoint); + let status = crate::dockerctx::status_event(env!("CARGO_PKG_VERSION"), false, crate::flavor::APP.get(), ctx, &cli).to_string(); + let sock = crate::dockerctx::sock_event(crate::serve::DOCKER_ENGINE, &endpoint, &ours, false).to_string(); + (status, sock) +} + +static LAST_DOCKER_STATE: Mutex<(String, String)> = Mutex::new((String::new(), String::new())); + +fn emit_docker_state() { + let (status, sock) = docker_state(); + *LAST_DOCKER_STATE.lock().unwrap_or_else(PoisonError::into_inner) = (status.clone(), sock.clone()); + emit(status); + emit(sock); +} + +fn emit_docker_state_if_changed() { + let (status, sock) = docker_state(); + let (send_status, send_sock) = { + let mut last = LAST_DOCKER_STATE.lock().unwrap_or_else(PoisonError::into_inner); + let ss = if last.0 != status { last.0 = status.clone(); true } else { false }; + let sd = if last.1 != sock { last.1 = sock.clone(); true } else { false }; + (ss, sd) + }; + if send_status { + emit(status); + } + if send_sock { + emit(sock); + } +} + +/// Ensures the `kiri` context exists and is plain `docker`'s current context, +/// keeping logins, credential helpers and plugin folders untouched (#369). +pub fn use_kiri_context() -> io::Result<()> { + let dir = crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let ours = crate::flavor::CONTEXT.get(); + crate::dockerctx::use_ours(&dir, &context_meta(&dir, ours), ours, "Kiri (WSL2)", &npipe_host(&crate::client::pipe())) } /// The docker CLI on Kiri's context, without a console window, for Compose @@ -785,18 +833,6 @@ fn compose_store() -> Option { prefs_path().map(|p| p.with_file_name("compose.json")) } -/// Runs the docker CLI without a console window: its output, or why it failed. -fn docker(args: &[&str]) -> io::Result { - let mut cmd = crate::win::tool(&crate::detail::docker_cli()); - std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let out = cmd.args(args).output()?; - if out.status.success() { - Ok(String::from_utf8_lossy(&out.stdout).into_owned()) - } else { - Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) - } -} - fn builds_event() -> String { match crate::builds::list() { Ok(b) => json!({"type": "builds", "builds": b}), @@ -833,10 +869,15 @@ fn build_with() { } } -/// Which engine plain `docker` uses: Kiri, or back to the one before. +/// Which engine plain `docker` uses: Kiri (made first if missing), "default", +/// or another context that exists, keeping logins and plugin folders. fn use_context(name: &str) { - let result = if name.is_empty() { Err(io::Error::other("no context named")) } else { docker(&["context", "use", name]).map(drop) }; - emit(status_event()); + let result = (|| -> io::Result<()> { + let dir = crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let ours = crate::flavor::CONTEXT.get(); + crate::dockerctx::switch(&dir, &context_meta(&dir, name), name, ours, "Kiri (WSL2)", &npipe_host(&crate::client::pipe())) + })(); + emit_docker_state(); emit(json!({"type": "usedcontext", "name": name, "error": result.as_ref().err().map(|e| e.to_string())}).to_string()); } @@ -1091,6 +1132,11 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn npipe_host_formats_pipe_url() { + assert_eq!(super::npipe_host(r"\\.\pipe\kiri"), "npipe:////./pipe/kiri"); + } } /// The page's "fonts" event, made once (the window asks each time Settings @@ -1126,7 +1172,7 @@ pub fn on_message(msg: &str) { emit(r#"{"type":"starprompt"}"#.to_owned()); } emit(domains_event()); - emit(status_event()); + emit_docker_state(); ask_language(); // The first time, offer .kiri.local, as the Mac does. if !crate::dns::installed() && crate::dns::serving() && prefs()["domainsAsked"] != true { @@ -1195,10 +1241,11 @@ pub fn on_message(msg: &str) { emit(crate::buildwith::event()); }); } - // The docker CLI can take a moment: off the window's thread. + // Config update can be done synchronously or off-thread. "usecontext" => { std::thread::spawn(move || use_context(&c.name)); } + "dockersock" => emit_docker_state(), // The Kubernetes section: Pods, Services, a pod's logs, Start. "k8s" => crate::k8s::handle(&c.action, &c.value), // Share: public links for a port or container, and the Share account. diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index 72681027e..eb9a4af57 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -45,6 +45,9 @@ mod relay; #[path = "../../kiri/src/hostrelay.rs"] mod hostrelay; #[cfg(windows)] +#[path = "../../kiri/src/dockerctx.rs"] +mod dockerctx; +#[cfg(windows)] mod win; // The window's USB view, through usbipd-win. #[cfg(windows)] diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 96e16dade..93625efb4 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -146,6 +146,21 @@ pub const DOCKER_ENGINE: &str = r"\\.\pipe\docker_engine"; /// while any instance of Kiri's is open). const OTHER_ENGINES: &[&str] = &["Docker Desktop.exe", "com.docker.backend.exe", "dockerd.exe", "Rancher Desktop.exe"]; +static DOCKER_ENGINE_OWNER: std::sync::LazyLock>> = std::sync::LazyLock::new(|| Mutex::new(None)); + +fn set_docker_engine_owner(owner: crate::dockerctx::Endpoint) { + *DOCKER_ENGINE_OWNER.lock().unwrap_or_else(PoisonError::into_inner) = Some(owner); +} + +/// Who currently serves `\\.\pipe\docker_engine`, for `docker` CLI detection +/// (#369) and Settings → Network (#577). +pub fn docker_engine_endpoint() -> crate::dockerctx::Endpoint { + if let Some(ep) = DOCKER_ENGINE_OWNER.lock().unwrap_or_else(PoisonError::into_inner).clone() { + return ep; + } + other_engine().map(|o| crate::dockerctx::Endpoint::Taken(o.to_owned())).unwrap_or(crate::dockerctx::Endpoint::Free) +} + /// Carries connections to `distro` from now on (setup has just made it); /// the bridge to the old one is left to end. pub fn set_distro(distro: &str) { @@ -227,6 +242,7 @@ fn docker_engine(hub: &Arc) { }; loop { if let Some(other) = other_engine() { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other.to_owned())); say(format!("{DOCKER_ENGINE} left to {other}")); thread::sleep(std::time::Duration::from_secs(5)); continue; @@ -234,14 +250,27 @@ fn docker_engine(hub: &Arc) { let first = match Pipe::create(DOCKER_ENGINE, true) { Ok(p) => p, Err(e) => { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other_engine().unwrap_or("").to_owned())); say(format!("{DOCKER_ENGINE} left to whatever serves it: {e}")); thread::sleep(std::time::Duration::from_secs(5)); continue; } }; + set_docker_engine_owner(crate::dockerctx::Endpoint::Kiri); say(format!("serving {DOCKER_ENGINE} as well (no other engine has it)")); let (h, mut new) = (hub.clone(), NewEngines::default()); - serve_while_free(DOCKER_ENGINE, first, move || new.find(), move |p| serve_shared(&h, p)); + serve_while_free( + DOCKER_ENGINE, + first, + move || { + let found = new.find(); + if let Some(other) = found { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other.to_owned())); + } + found + }, + move |p| serve_shared(&h, p), + ); } } diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index f2c72b0f5..e66b57e7d 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -907,6 +907,10 @@ fn tools() -> io::Result<()> { verified(f)?; } let make_default = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default); + let before_ctx = crate::dockerctx::docker_dir().and_then(|d| { + let cfg: Value = crate::dockerctx::read_json(&d.join("config.json")).ok()?; + cfg["currentContext"].as_str().map(str::to_owned) + }); // setup-tools.ps1 (contrib/windows), checked like the bundle's other // files and run from its file with its parameters as arguments. Not a // copy in this binary run through [scriptblock]::Create from Base64: @@ -951,6 +955,20 @@ fn tools() -> io::Result<()> { .unwrap_or_else(|| "installing the Docker tools failed".to_owned()); return Err(io::Error::other(why)); } + // The user may have toggled "Make Kiri the default for docker" while + // setup-tools.ps1 ran, after `make_default` above was already read (#369). + let want_default = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default); + if want_default { + crate::engine::use_kiri_context()?; + if !make_default { + task(4, "done", ""); + } + } else if make_default + && let Some(dir) = crate::dockerctx::docker_dir() + { + let _ = crate::dockerctx::set_current(&dir.join("config.json"), before_ctx.as_deref().unwrap_or("default")); + task(4, "done", &tr("skipped")); + } // From here on Kiri runs from %LOCALAPPDATA%\Kiri, not the download folder. if let Ok(exe) = std::env::current_exe() { let installed = dir().join("kiri-win.exe"); @@ -968,6 +986,12 @@ fn tools() -> io::Result<()> { /// Ready → Open Kiri: remember setup is done, start at sign-in if asked. fn finish() { let autostart = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_none_or(|s| s.autostart); + // Apply "Make Kiri the default for docker" on finish too (e.g. if checked after tools finished). + if STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default) + && let Err(e) = crate::engine::use_kiri_context() + { + crate::serve::log(&format!("docker context: could not make kiri default ({e})")); + } // Which builder docker build uses: asked with another engine here, Kiri's without. let asked = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().filter(|s| s.other_docker).map(|s| s.build_kiri); let built = match asked { diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs new file mode 100644 index 000000000..da2a2251b --- /dev/null +++ b/crates/kiri/src/dockerctx.rs @@ -0,0 +1,487 @@ +//! Which engine plain `docker` reaches, and who has docker's default +//! endpoint, for the window's status bar and Settings → Network on every +//! system (#369, #577). +//! +//! Plain `docker` uses Kiri only through Kiri's context, or through the +//! default endpoint (`/var/run/docker.sock`, `\\.\pipe\docker_engine` on +//! Windows) while Kiri serves it. Another engine's context +//! (`desktop-linux`, `orbstack`, `colima`) is that engine, whatever Kiri +//! serves. Shared with kiri-win by path, so std and serde_json only. + +use std::ffi::OsString; +use std::io; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +/// Who serves docker's default endpoint. +#[derive(Debug, Clone, PartialEq)] +pub enum Endpoint { + Kiri, + /// Another engine: its name, or the path the endpoint leads to (empty + /// when nothing says which program it is). + Taken(String), + Free, +} + +/// What plain `docker` uses, picked as the docker CLI picks it. +#[derive(Debug, PartialEq)] +pub struct Cli { + /// Its context: "default" for the default endpoint, and for DOCKER_HOST. + pub context: String, + /// The environment variable that decides it, when one does: switching + /// docker's context changes nothing then. + pub pinned: Option<&'static str>, + /// Whether that reaches Kiri. + pub kiri: bool, +} + +impl Cli { + /// The context for the status bar: Kiri's own when docker reaches Kiri + /// another way (the default endpoint Kiri serves), as the page compares + /// it with Kiri's. + pub fn shown<'a>(&'a self, ours: &'a str) -> &'a str { + if self.kiri { ours } else { &self.context } + } + + /// The variable to name in the window: only while docker misses Kiri. + pub fn pinned_shown(&self) -> Option<&'static str> { + self.pinned.filter(|_| !self.kiri) + } +} + +/// What the docker CLI reads to pick its endpoint. +#[derive(Debug, Default)] +pub struct Env<'a> { + /// DOCKER_HOST. + pub host: Option<&'a str>, + /// DOCKER_CONTEXT. + pub context: Option<&'a str>, + /// config.json as read; None when there is none. + pub config: Option<&'a [u8]>, +} + +/// docker's default endpoints, as DOCKER_HOST may name them. +const DEFAULT_HOSTS: [&str; 3] = ["unix:///var/run/docker.sock", "unix:///run/docker.sock", "npipe:////./pipe/docker_engine"]; + +/// The context `docker` uses, in the docker CLI's order: DOCKER_HOST, then +/// DOCKER_CONTEXT, then config.json's `currentContext`, else "default". A +/// config.json that isn't JSON counts as empty, as the CLI warns and goes +/// on without it. `ours` is Kiri's context and `our_hosts` its endpoints. +pub fn cli(env: &Env, ours: &str, our_hosts: &[&str], endpoint: &Endpoint) -> Cli { + let set = |v: Option<&str>| v.map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned); + if let Some(host) = set(env.host) { + let served = *endpoint == Endpoint::Kiri && DEFAULT_HOSTS.iter().any(|h| same_host(h, &host)); + let kiri = served || our_hosts.iter().any(|h| same_host(h, &host)); + return Cli { context: "default".into(), pinned: Some("DOCKER_HOST"), kiri }; + } + let (context, pinned) = match set(env.context) { + Some(c) => (c, Some("DOCKER_CONTEXT")), + None => (current(env.config).unwrap_or_else(|| "default".into()), None), + }; + let kiri = if context == "default" { *endpoint == Endpoint::Kiri } else { context == ours }; + Cli { context, pinned, kiri } +} + +/// config.json's `currentContext`, when it names one. +fn current(config: Option<&[u8]>) -> Option { + let cfg: Value = serde_json::from_slice(config?).ok()?; + cfg["currentContext"].as_str().map(str::trim).filter(|c| !c.is_empty()).map(str::to_owned) +} + +/// Two docker hosts that are the same endpoint: `npipe:////./pipe/x` and +/// `npipe://./pipe/x`, any case, are one pipe. +fn same_host(a: &str, b: &str) -> bool { + let norm = |h: &str| match h.get(..6) { + Some(s) if s.eq_ignore_ascii_case("npipe:") => format!("npipe:{}", h[6..].replace('\\', "/").trim_start_matches('/').to_ascii_lowercase()), + _ => h.trim_end_matches('/').to_owned(), + }; + norm(a) == norm(b) +} + +/// `cli` for this process: its environment and docker's config.json. +pub fn current_cli(ours: &str, our_hosts: &[&str], endpoint: &Endpoint) -> Cli { + let host = std::env::var("DOCKER_HOST").ok(); + let context = std::env::var("DOCKER_CONTEXT").ok(); + let config = docker_dir().and_then(|d| std::fs::read(d.join("config.json")).ok()); + cli(&Env { host: host.as_deref(), context: context.as_deref(), config: config.as_deref() }, ours, our_hosts, endpoint) +} + +/// The engine a socket's path, or a Windows process, belongs to, when it +/// is one Kiri knows. +pub fn engine_name(target: &str) -> Option<&'static str> { + let t = target.replace('\\', "/").to_ascii_lowercase(); + const KNOWN: [(&str, &str); 9] = [ + ("/.orbstack/", "OrbStack"), + ("/.docker/", "Docker Desktop"), + ("docker desktop", "Docker Desktop"), + ("com.docker.", "Docker Desktop"), + ("/.rd/", "Rancher Desktop"), + ("rancher desktop", "Rancher Desktop"), + ("colima", "Colima"), + ("podman", "Podman"), + ("dockerd", "dockerd"), + ]; + KNOWN.iter().find(|(k, _)| t.contains(k)).map(|(_, name)| *name) +} + +/// Settings → Network's Docker socket row: who has `path`, the DOCKER_HOST +/// that points a tool at Kiri instead (`ours`), and whether the window can +/// take it now (`take`: the Mac, while it is free). +pub fn sock_event(path: &str, endpoint: &Endpoint, ours: &str, take: bool) -> Value { + let (owner, engine, target) = match endpoint { + Endpoint::Kiri => ("kiri", None, None), + Endpoint::Free => ("free", None, None), + Endpoint::Taken(t) => ("other", engine_name(t), Some(t.as_str()).filter(|t| !t.is_empty())), + }; + json!({"type": "dockersock", "path": path, "owner": owner, "engine": engine, "target": target, "hint": format!("DOCKER_HOST={ours}"), "take": take && *endpoint == Endpoint::Free}) +} + +/// The window's "status" event: build version, app flavor, and what plain +/// `docker` uses (including `pinned` when DOCKER_HOST or DOCKER_CONTEXT +/// overrides config.json and misses Kiri). +pub fn status_event(version: &str, dev: bool, app: &str, ours: &str, cli: &Cli) -> Value { + json!({"type": "status", "version": version, "dev": dev, "share": true, "app": app, "ours": ours, "context": cli.shown(ours), "pinned": cli.pinned_shown()}) +} + +/// Who owns a Unix docker socket path (`path`): Kiri (`ours`), another +/// engine (a socket, plain file, or link to an installed engine in +/// `engines`), or nobody (`Free`, including a dangling link left behind by +/// an engine that was removed). +#[cfg(unix)] +pub fn sock_at(path: &Path, ours: &Path, engines: &[PathBuf]) -> Endpoint { + let Ok(meta) = std::fs::symlink_metadata(path) else { return Endpoint::Free }; + if meta.file_type().is_symlink() { + let Ok(target) = std::fs::read_link(path) else { return Endpoint::Taken(path.display().to_string()) }; + let resolved = if target.is_relative() { path.parent().map_or_else(|| target.clone(), |p| p.join(&target)) } else { target.clone() }; + if target == ours || resolved == ours { + return Endpoint::Kiri; + } + if resolved.exists() { + if let (Ok(a), Ok(b)) = (std::fs::canonicalize(&resolved), std::fs::canonicalize(ours)) + && a == b + { + return Endpoint::Kiri; + } + return Endpoint::Taken(target.display().to_string()); + } + if engines.iter().any(|e| target.starts_with(e) || resolved.starts_with(e)) { + return Endpoint::Taken(target.display().to_string()); + } + // Left behind by an engine that has been removed. + return Endpoint::Free; + } + // A socket (or anything else) of its own: an engine's, serving or not. + Endpoint::Taken(path.display().to_string()) +} + +/// docker's config folder: DOCKER_CONFIG, else `.docker` in the home +/// folder (HOME, or USERPROFILE on Windows). +pub fn docker_dir() -> Option { + dir_in(std::env::var_os("DOCKER_CONFIG"), std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })) +} + +fn dir_in(config: Option, home: Option) -> Option { + config.filter(|c| !c.is_empty()).map(PathBuf::from).or_else(|| home.filter(|h| !h.is_empty()).map(|h| Path::new(&h).join(".docker"))) +} + +pub fn read_json(path: &Path) -> io::Result { + match std::fs::read(path) { + Ok(b) => serde_json::from_slice(&b).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(json!({})), + Err(e) => Err(e), + } +} + +/// Writes JSON through a temporary file, so a crash never leaves half a config. +pub fn write_json(path: &Path, v: &Value) -> io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("kiri-tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(v).map_err(io::Error::other)?)?; + std::fs::rename(tmp, path) +} + +/// A context's meta.json, as `docker context create NAME --docker +/// host=HOST` writes it, in `meta`: contexts/meta/ and the SHA-256 of its +/// name, which the caller works out. +pub fn write_context(meta: &Path, name: &str, description: &str, host: &str) -> io::Result<()> { + let v = json!({ + "Name": name, + "Metadata": {"Description": description}, + "Endpoints": {"docker": {"Host": host, "SkipTLSVerify": false}}, + }); + write_json(&meta.join("meta.json"), &v) +} + +/// Makes `name` the context in `config` (config.json); "default" takes +/// `currentContext` out. Every other key (registry logins, credential +/// helpers, plugin folders) stays as it was, and a file that isn't a JSON +/// object is left alone, with an error that says so. +pub fn set_current(config: &Path, name: &str) -> io::Result<()> { + let mut cfg = read_json(config)?; + let Some(o) = cfg.as_object_mut() else { return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", config.display()))) }; + if name == "default" { + o.remove("currentContext"); + } else { + o.insert("currentContext".into(), name.into()); + } + write_json(config, &cfg) +} + +/// Kiri's context as docker's current one, made first if it's missing (a +/// context someone removed). `dir` is docker's config folder, `meta` the +/// context's folder in it, `host` Kiri's endpoint. +pub fn use_ours(dir: &Path, meta: &Path, name: &str, description: &str, host: &str) -> io::Result<()> { + if !meta.join("meta.json").is_file() { + write_context(meta, name, description, host)?; + } + set_current(&dir.join("config.json"), name) +} + +/// Validates a docker context name so it cannot escape `contexts/meta/`. +pub fn valid_name(name: &str) -> bool { + !name.is_empty() && name != "." && name != ".." && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) +} + +/// Makes `name` the current context in `dir/config.json`: `ours` (created in +/// `meta` first if missing), `"default"`, or another context whose +/// `meta.json` lives in `meta`. +pub fn switch(dir: &Path, meta: &Path, name: &str, ours: &str, description: &str, host: &str) -> io::Result<()> { + if !valid_name(name) { + return Err(io::Error::other("not a context name")); + } + if name == ours { + return use_ours(dir, meta, name, description, host); + } + if name != "default" && !meta.join("meta.json").is_file() { + return Err(io::Error::other(format!("there is no docker context `{name}`"))); + } + set_current(&dir.join("config.json"), name) +} + +#[cfg(test)] +mod tests { + use super::*; + + const OURS: &str = "kiri"; + const KIRI_HOST: &str = "unix:///Users/me/.kiri/run/docker.sock"; + + fn with_config(config: Option<&str>, endpoint: &Endpoint) -> Cli { + cli(&Env { config: config.map(str::as_bytes), ..Env::default() }, OURS, &[KIRI_HOST], endpoint) + } + + #[test] + fn another_engines_context_is_never_kiri() { + // #369: Docker Desktop's context, while Kiri holds docker_engine or + // /var/run/docker.sock: docker talks to Docker Desktop. + let desktop = Endpoint::Taken("Docker Desktop".into()); + for ctx in ["desktop-linux", "orbstack", "colima"] { + for endpoint in [Endpoint::Kiri, desktop.clone(), Endpoint::Free] { + let c = with_config(Some(&format!(r#"{{"currentContext": "{ctx}", "auths": {{}}}}"#)), &endpoint); + assert_eq!(c, Cli { context: ctx.into(), pinned: None, kiri: false }, "{ctx} with {endpoint:?}"); + assert_eq!(c.shown(OURS), ctx); + } + } + } + + #[test] + fn kiris_context_is_kiri_whoever_has_the_default_endpoint() { + for endpoint in [Endpoint::Kiri, Endpoint::Taken("Docker Desktop".into()), Endpoint::Free] { + let c = with_config(Some(r#"{"currentContext": "kiri"}"#), &endpoint); + assert!(c.kiri, "{endpoint:?}"); + assert_eq!(c.shown(OURS), "kiri"); + } + } + + #[test] + fn the_default_context_is_kiri_only_while_kiri_serves_the_endpoint() { + // Unset, "default", no config.json, or one docker can't read (it + // warns and goes on with none): all the default endpoint. + let configs = [Some(r#"{"currentContext": "default"}"#), Some(r#"{"auths": {}}"#), Some(r#"{"currentContext": ""}"#), None, Some("{not json")]; + for config in configs { + let c = with_config(config, &Endpoint::Kiri); + assert_eq!((c.context.as_str(), c.kiri, c.shown(OURS)), ("default", true, "kiri"), "{config:?}"); + for endpoint in [Endpoint::Taken("Docker Desktop".into()), Endpoint::Free] { + let c = with_config(config, &endpoint); + assert_eq!((c.context.as_str(), c.kiri, c.shown(OURS)), ("default", false, "default"), "{config:?} with {endpoint:?}"); + } + } + } + + #[test] + fn the_environment_comes_before_config_json() { + let config = Some(r#"{"currentContext": "kiri"}"#.as_bytes()); + // DOCKER_CONTEXT over currentContext. + let c = cli(&Env { context: Some("desktop-linux"), config, ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri); + assert_eq!(c, Cli { context: "desktop-linux".into(), pinned: Some("DOCKER_CONTEXT"), kiri: false }); + assert_eq!(c.pinned_shown(), Some("DOCKER_CONTEXT")); + // DOCKER_HOST over both: Kiri only when it leads to Kiri. + let host = |h: &'static str, endpoint: &Endpoint| cli(&Env { host: Some(h), context: Some("kiri"), config }, OURS, &[KIRI_HOST, "npipe:////./pipe/kiri"], endpoint); + let desktop = Endpoint::Taken("Docker Desktop".into()); + assert!(!host("npipe:////./pipe/dockerDesktopLinuxEngine", &Endpoint::Kiri).kiri); + assert_eq!(host("npipe:////./pipe/dockerDesktopLinuxEngine", &Endpoint::Kiri).pinned_shown(), Some("DOCKER_HOST")); + assert!(host(KIRI_HOST, &desktop).kiri); + assert!(host(r"npipe://./pipe/KIRI", &desktop).kiri, "the same pipe, written another way"); + assert_eq!(host(KIRI_HOST, &desktop).pinned_shown(), None, "nothing to say while docker reaches Kiri"); + assert!(host("unix:///var/run/docker.sock", &Endpoint::Kiri).kiri); + assert!(!host("unix:///var/run/docker.sock", &desktop).kiri); + assert!(host("npipe:////./pipe/docker_engine", &Endpoint::Kiri).kiri); + // Empty variables are unset. + let c = cli(&Env { host: Some(""), context: Some(" "), config }, OURS, &[KIRI_HOST], &Endpoint::Free); + assert_eq!(c, Cli { context: "kiri".into(), pinned: None, kiri: true }); + } + + #[test] + fn names_the_engine_behind_an_endpoint() { + assert_eq!(engine_name("/Users/me/.orbstack/run/docker.sock"), Some("OrbStack")); + assert_eq!(engine_name("/Users/me/.docker/run/docker.sock"), Some("Docker Desktop")); + assert_eq!(engine_name("/Users/me/.colima/default/docker.sock"), Some("Colima")); + assert_eq!(engine_name("/Users/me/.rd/docker.sock"), Some("Rancher Desktop")); + assert_eq!(engine_name("Docker Desktop.exe"), Some("Docker Desktop")); + assert_eq!(engine_name("com.docker.backend.exe"), Some("Docker Desktop")); + assert_eq!(engine_name("Rancher Desktop.exe"), Some("Rancher Desktop")); + assert_eq!(engine_name("dockerd.exe"), Some("dockerd")); + assert_eq!(engine_name("/var/run/docker.sock"), None); + } + + #[test] + fn the_socket_rows_event() { + let e = sock_event("/var/run/docker.sock", &Endpoint::Taken("/Users/me/.orbstack/run/docker.sock".into()), KIRI_HOST, true); + assert_eq!(e["owner"], "other"); + assert_eq!(e["engine"], "OrbStack"); + assert_eq!(e["target"], "/Users/me/.orbstack/run/docker.sock"); + assert_eq!(e["hint"], format!("DOCKER_HOST={KIRI_HOST}")); + assert_eq!(e["take"], false, "another engine's socket is never taken"); + let e = sock_event("/var/run/docker.sock", &Endpoint::Free, KIRI_HOST, true); + assert_eq!((e["owner"].as_str(), e["take"].as_bool()), (Some("free"), Some(true))); + let e = sock_event(r"\\.\pipe\docker_engine", &Endpoint::Taken(String::new()), "npipe:////./pipe/kiri", false); + assert_eq!((e["owner"].as_str(), e["engine"].is_null(), e["target"].is_null()), (Some("other"), true, true)); + assert_eq!(sock_event("/var/run/docker.sock", &Endpoint::Kiri, KIRI_HOST, true)["take"], false); + } + + /// A home folder of its own for each test, as HOME or USERPROFILE. + fn scratch_home(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-dockerctx-test-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn docker_dir_is_docker_config_or_the_homes() { + let home = scratch_home("dir"); + assert_eq!(dir_in(None, Some(home.clone().into())), Some(home.join(".docker"))); + assert_eq!(dir_in(Some("".into()), Some(home.clone().into())), Some(home.join(".docker"))); + assert_eq!(dir_in(Some("/elsewhere".into()), Some(home.into())), Some(PathBuf::from("/elsewhere"))); + assert_eq!(dir_in(None, None), None); + let _ = std::fs::remove_dir_all(scratch_home("dir")); + } + + #[test] + fn switching_to_kiri_keeps_logins_helpers_and_plugins() { + let home = scratch_home("switch"); + let dir = dir_in(None, Some(home.clone().into())).unwrap(); + let meta = dir.join("contexts/meta").join("abc123"); + std::fs::create_dir_all(&dir).unwrap(); + let before = json!({ + "auths": {"ghcr.io": {"auth": "c2VjcmV0"}}, + "credHelpers": {"123.dkr.ecr.eu-west-1.amazonaws.com": "ecr-login"}, + "cliPluginsExtraDirs": ["/Applications/Kiri.app/Contents/Resources/bin/cli-plugins"], + "currentContext": "desktop-linux", + }); + write_json(&dir.join("config.json"), &before).unwrap(); + use_ours(&dir, &meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri").unwrap(); + let after = read_json(&dir.join("config.json")).unwrap(); + assert_eq!(after["currentContext"], "kiri"); + for k in ["auths", "credHelpers", "cliPluginsExtraDirs"] { + assert_eq!(after[k], before[k], "{k}"); + } + // The context Kiri made, as `docker context create` does. + let m = read_json(&meta.join("meta.json")).unwrap(); + assert_eq!((m["Name"].as_str(), m["Endpoints"]["docker"]["Host"].as_str()), (Some("kiri"), Some("npipe:////./pipe/kiri"))); + // docker's choice now, from what was written. + let config = std::fs::read(dir.join("config.json")).unwrap(); + assert!(cli(&Env { config: Some(&config), ..Env::default() }, "kiri", &[], &Endpoint::Taken("Docker Desktop".into())).kiri); + // A context already there (setup made it on another pipe) stays. + write_context(&meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri-2").unwrap(); + use_ours(&dir, &meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri").unwrap(); + assert_eq!(read_json(&meta.join("meta.json")).unwrap()["Endpoints"]["docker"]["Host"], "npipe:////./pipe/kiri-2"); + // Back to the default endpoint: currentContext goes, the rest stays. + set_current(&dir.join("config.json"), "default").unwrap(); + let back = read_json(&dir.join("config.json")).unwrap(); + assert!(back.get("currentContext").is_none()); + assert_eq!(back["auths"], before["auths"]); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn switching_without_a_config_makes_one_and_never_overwrites_a_broken_one() { + let home = scratch_home("broken"); + let dir = dir_in(Some(home.join("docker-config").into()), None).unwrap(); + let meta = dir.join("contexts/meta").join("abc123"); + use_ours(&dir, &meta, "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap(), json!({"currentContext": "kiri"})); + for broken in ["{\"auths\": {", "[1, 2]"] { + std::fs::write(dir.join("config.json"), broken).unwrap(); + let e = set_current(&dir.join("config.json"), "kiri").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::InvalidData, "{broken}"); + assert_eq!(std::fs::read_to_string(dir.join("config.json")).unwrap(), broken, "left as it was"); + } + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn switch_validates_names_and_existing_contexts() { + let home = scratch_home("switch-ctx"); + let dir = dir_in(Some(home.join("cfg").into()), None).unwrap(); + let meta = |n: &str| dir.join("contexts/meta").join(n); + assert!(switch(&dir, &meta(""), "", "kiri", "Kiri", KIRI_HOST).is_err()); + assert!(switch(&dir, &meta(".."), "../etc", "kiri", "Kiri", KIRI_HOST).is_err()); + assert!(switch(&dir, &meta("orbstack"), "orbstack", "kiri", "Kiri", KIRI_HOST).is_err()); + write_context(&meta("orbstack"), "orbstack", "OrbStack", "unix:///tmp/orb.sock").unwrap(); + switch(&dir, &meta("orbstack"), "orbstack", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap()["currentContext"], "orbstack"); + switch(&dir, &meta("kiri"), "kiri", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap()["currentContext"], "kiri"); + switch(&dir, &meta("default"), "default", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert!(read_json(&dir.join("config.json")).unwrap().get("currentContext").is_none()); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn status_event_reports_pinned_only_when_not_kiri() { + let c = cli(&Env { host: Some("unix:///tmp/other.sock"), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Free); + let s = status_event("0.1.4", false, "Kiri", OURS, &c); + assert_eq!((s["context"].as_str(), s["pinned"].as_str()), (Some("default"), Some("DOCKER_HOST"))); + let k = cli(&Env { host: Some(KIRI_HOST), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Free); + let sk = status_event("0.1.4", false, "Kiri", OURS, &k); + assert_eq!((sk["context"].as_str(), sk["pinned"].is_null()), (Some("kiri"), true)); + } + + #[cfg(unix)] + #[test] + fn sock_at_detects_kiri_taken_and_free() { + let d = scratch_home("sock-at"); + let ours_dir = d.join("kiri/run"); + std::fs::create_dir_all(&ours_dir).unwrap(); + let ours = ours_dir.join("docker.sock"); + let link = d.join("docker.sock"); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Free); + std::os::unix::fs::symlink(&ours, &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Kiri); + std::fs::remove_file(&link).unwrap(); + // Relative symlink when target exists resolves canonically to Kiri. + std::fs::write(&ours, "").unwrap(); + std::os::unix::fs::symlink("kiri/run/docker.sock", &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Kiri); + std::fs::remove_file(&link).unwrap(); + // Dangling symlink to an installed engine dir stays Taken; without dir, Free. + let orb = d.join(".orbstack/run/docker.sock"); + std::os::unix::fs::symlink(&orb, &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[d.join(".orbstack")]), Endpoint::Taken(orb.display().to_string())); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Free); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index f1deb1b1b..e7602d460 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -37,6 +37,9 @@ mod daemon; mod diag; #[cfg(any(unix, windows))] mod docker; +#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), test))] +#[cfg_attr(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))), allow(dead_code))] +mod dockerctx; // `kiri domains`: the container-domain routers' ports (Windows: in WSL). #[cfg(unix)] mod domains_cli; diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index ef605d0cd..df748f5fe 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -33,7 +33,7 @@ use std::io; use std::path::{Path, PathBuf}; use std::process::Command; -use serde_json::{Value, json}; +use serde_json::Value; // The bundle identifier (`APP_ID`) named in the LaunchAgent makes macOS // say "Kiri" in Login Items, rather than the name on the signing @@ -48,15 +48,14 @@ fn bin_dir() -> io::Result { Ok(home()?.join(crate::flavor::STATE.get()).join("bin")) } +use crate::dockerctx::{Endpoint, read_json, write_json}; + fn home() -> io::Result { std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set")) } fn docker_dir() -> io::Result { - match std::env::var_os("DOCKER_CONFIG") { - Some(d) => Ok(PathBuf::from(d)), - None => Ok(home()?.join(".docker")), - } + crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("HOME is not set")) } /// The docker CLI's directory for a context: named by the SHA-256 of its name. @@ -65,24 +64,6 @@ fn context_dir(name: &str) -> io::Result { Ok(docker_dir()?.join("contexts/meta").join(digest.trim_start_matches("sha256:"))) } -fn read_json(path: &Path) -> io::Result { - match std::fs::read(path) { - Ok(b) => serde_json::from_slice(&b).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(json!({})), - Err(e) => Err(e), - } -} - -/// Writes JSON through a temporary file, so a crash never leaves half a config. -fn write_json(path: &Path, v: &Value) -> io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("kiri-tmp"); - std::fs::write(&tmp, serde_json::to_vec_pretty(v).map_err(io::Error::other)?)?; - std::fs::rename(tmp, path) -} - /// Kiri.app's `Contents`, when this binary runs from the app. fn bundle_contents() -> Option { let exe = std::env::current_exe().ok()?.canonicalize().ok()?; @@ -280,13 +261,23 @@ const DOCKER_SOCK: &str = "/var/run/docker.sock"; const SOCKET_LABEL: &str = "dev.kiri.docker-socket"; const SOCKET_DAEMON: &str = "/Library/LaunchDaemons/dev.kiri.docker-socket.plist"; -/// Who has /var/run/docker.sock. -#[derive(Debug, PartialEq)] -enum DockerSock { - Kiri, - Free, - /// Another engine: what it points at. - Taken(String), +/// Who has `/var/run/docker.sock`. +pub fn docker_sock() -> Endpoint { + let Ok(ours) = crate::daemon::socket_path() else { return Endpoint::Free }; + docker_sock_at_ours(&ours) +} + +fn docker_sock_at_ours(ours: &Path) -> Endpoint { + crate::dockerctx::sock_at(Path::new(DOCKER_SOCK), ours, &other_engine_dirs()) +} + +/// Settings → Network's Docker socket row for the Mac. +pub fn docker_sock_event() -> Value { + let (endpoint, hint) = match crate::daemon::socket_path() { + Ok(ours) => (docker_sock_at_ours(&ours), format!("unix://{}", ours.display())), + Err(_) => (Endpoint::Free, format!("unix://~/{}/run/docker.sock", crate::flavor::STATE.get())), + }; + crate::dockerctx::sock_event(DOCKER_SOCK, &endpoint, &hint, !dev()) } /// The engines whose links stay theirs while the app is installed, running @@ -300,27 +291,6 @@ fn other_engine_dirs() -> Vec { .collect() } -fn docker_sock(ours: &Path) -> DockerSock { - docker_sock_at(Path::new(DOCKER_SOCK), ours, &other_engine_dirs()) -} - -fn docker_sock_at(path: &Path, ours: &Path, engines: &[PathBuf]) -> DockerSock { - let Ok(meta) = std::fs::symlink_metadata(path) else { return DockerSock::Free }; - if meta.file_type().is_symlink() { - let Ok(target) = std::fs::read_link(path) else { return DockerSock::Taken(path.display().to_string()) }; - if target == ours { - return DockerSock::Kiri; - } - if target.exists() || engines.iter().any(|e| target.starts_with(e)) { - return DockerSock::Taken(target.display().to_string()); - } - // Left behind by an engine that has been removed. - return DockerSock::Free; - } - // A socket (or anything else) of its own: an engine's, serving or not. - DockerSock::Taken(path.display().to_string()) -} - /// `'…'` for sh. fn sh_quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) @@ -344,7 +314,7 @@ impl std::fmt::Display for LinkScript { /// Kiri's already or another engine's, or for Kiri Dev. fn docker_socket_script() -> io::Result> { let ours = crate::daemon::socket_path()?; - if dev() || docker_sock(&ours) != DockerSock::Free { + if dev() || docker_sock_at_ours(&ours) != Endpoint::Free { return Ok(None); } let esc = |s: &str| s.replace('&', "&").replace('<', "<"); @@ -389,16 +359,16 @@ pub fn docker_socket() -> io::Result<()> { /// `~/.testcontainers.properties` for when /var/run/docker.sock is not /// Kiri's but could be (a declined password, not yet asked). fn docker_socket_fallback(ours: &Path) -> String { - match docker_sock(ours) { - DockerSock::Kiri => { + match docker_sock_at_ours(ours) { + Endpoint::Kiri => { let _ = testcontainers(ours, false); format!("{DOCKER_SOCK} → Kiri (docker-py, Testcontainers and other tools that ignore docker contexts)") } - DockerSock::Taken(t) => { + Endpoint::Taken(t) => { let _ = testcontainers(ours, false); format!("{DOCKER_SOCK} is another engine's ({t}) and stays so; DOCKER_HOST=unix://{} points a tool at Kiri", ours.display()) } - DockerSock::Free => match testcontainers(ours, true) { + Endpoint::Free => match testcontainers(ours, true) { Ok(true) => format!("{DOCKER_SOCK} is not Kiri's yet (`kiri setup --docker-socket` asks for the password); Testcontainers finds Kiri through ~/.testcontainers.properties"), _ => format!("{DOCKER_SOCK} is not Kiri's yet (`kiri setup --docker-socket` asks for the password); until then DOCKER_HOST=unix://{} points a tool at Kiri", ours.display()), }, @@ -450,8 +420,8 @@ fn testcontainers_at(path: &Path, ours: &Path, on: bool) -> io::Result { /// went, if it is not Kiri's. pub fn docker_socket_note() -> Option { let ours = crate::daemon::socket_path().ok()?; - match docker_sock(&ours) { - DockerSock::Free if !dev() => Some(docker_socket_fallback(&ours)), + match docker_sock_at_ours(&ours) { + Endpoint::Free if !dev() => Some(docker_socket_fallback(&ours)), _ => None, } } @@ -461,7 +431,7 @@ pub fn docker_socket_note() -> Option { fn remove_docker_socket() -> io::Result<()> { let ours = crate::daemon::socket_path()?; let _ = testcontainers(&ours, false); - let linked = docker_sock(&ours) == DockerSock::Kiri; + let linked = docker_sock_at_ours(&ours) == Endpoint::Kiri; if !linked && !Path::new(SOCKET_DAEMON).exists() { return Ok(()); } @@ -533,31 +503,15 @@ pub fn after_tools() -> io::Result<()> { /// The context, as `docker context create kiri --docker host=…` writes it. fn context(socket: &Path) -> io::Result<()> { - let meta = json!({ - "Name": CONTEXT.get(), - "Metadata": {"Description": crate::flavor::APP.get()}, - "Endpoints": {"docker": {"Host": format!("unix://{}", socket.display()), "SkipTLSVerify": false}}, - }); - write_json(&context_dir(CONTEXT.get())?.join("meta.json"), &meta) + crate::dockerctx::write_context(&context_dir(CONTEXT.get())?, CONTEXT.get(), crate::flavor::APP.get(), &format!("unix://{}", socket.display())) } /// Makes `name` the context plain `docker` uses: Kiri's own (made first if /// missing), "default", or another context that exists, to switch back to. pub fn use_context(name: &str) -> io::Result<()> { - if name == CONTEXT.get() { - context(&crate::daemon::socket_path()?)?; - } else if name != "default" && !context_dir(name)?.join("meta.json").is_file() { - return Err(io::Error::other(format!("there is no docker context `{name}`"))); - } - let path = docker_dir()?.join("config.json"); - let mut cfg = read_json(&path)?; - match cfg.as_object_mut() { - Some(o) if name == "default" => { - o.remove("currentContext"); - } - _ => cfg["currentContext"] = name.into(), - } - write_json(&path, &cfg) + let dir = docker_dir()?; + let host = format!("unix://{}", crate::daemon::socket_path()?.display()); + crate::dockerctx::switch(&dir, &context_dir(name)?, name, CONTEXT.get(), crate::flavor::APP.get(), &host) } /// Links `kiri` and the app's `docker` into `~/.kiri/bin`, puts that @@ -768,7 +722,7 @@ fn default_context() -> io::Result<()> { let h = home()?; // Kiri's own /var/run/docker.sock is not another engine. let ours = crate::daemon::socket_path()?; - let system = !matches!(docker_sock(&ours), DockerSock::Kiri) && Path::new(DOCKER_SOCK).exists(); + let system = !matches!(docker_sock_at_ours(&ours), Endpoint::Kiri) && Path::new(DOCKER_SOCK).exists(); let other = system || [h.join(".orbstack/run/docker.sock"), h.join(".docker/run/docker.sock")].iter().any(|p| p.exists()) || Path::new("/Applications/OrbStack.app").exists() @@ -1069,11 +1023,11 @@ mod tests { #[test] fn docker_sock_owner() { - use super::DockerSock::*; + use crate::dockerctx::Endpoint::*; let d = scratch("sock"); let ours = d.join("kiri/run/docker.sock"); let link = d.join("docker.sock"); - let at = |engines: &[std::path::PathBuf]| super::docker_sock_at(&link, &ours, engines); + let at = |engines: &[std::path::PathBuf]| crate::dockerctx::sock_at(&link, &ours, engines); assert_eq!(at(&[]), Free); std::os::unix::fs::symlink(&ours, &link).unwrap(); assert_eq!(at(&[]), Kiri, "Kiri's link, even with the daemon stopped"); diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 1f5b8fe79..fe37d579e 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -1165,6 +1165,8 @@ .rports input:disabled { color: var(--faint); } .rports .btn { height: 32px; } .pref + .rp-notes { margin-top: -6px; } +.pref .sockhint { display: inline-flex; align-items: center; gap: 4px; flex-wrap: wrap; margin-top: 4px; color: var(--text); } +.pref .sockhint code { padding: 1px 6px; border-radius: 5px; background: var(--panel); border: 1px solid var(--line); font: var(--fs-mono) var(--mono-font); user-select: text; -webkit-user-select: text; } /* Chinese and Japanese break between any two characters: a short choice (关闭, 开启) stays on one line, as an English word does; Korean's too. Only in a CJK window, so English lays out as it did. */ @@ -2778,7 +2780,7 @@

Containers

({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); -const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, +const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, imp: { sources: null, source: null, inv: null, picked: { images: new Set(), volumes: new Set(), containers: new Set() }, steps: {}, running: false, summary: "" }, upd: null, engineStale: null, staleHidden: false, // The Builds view: the list, the picked build and its detail, and how its steps show. @@ -4064,6 +4066,7 @@

${tr("How should you reach your containers?")}

const CTX_SNOOZE = 7 * 864e5; const ctx = { card: null }; const ctxOther = () => !!ui.status && ui.status.context !== ui.status.ours; +const ctxPinned = () => ui.status?.pinned || ""; const ctxLabel = (c) => (CTX_NAMES[c] ? tr(CTX_NAMES[c]) : c); const ctxWarn = (cls = "") => ``; // "1.2GB", "187MB", "5.6kB" (docker's image sizes) in bytes. @@ -4072,16 +4075,25 @@

${tr("How should you reach your containers?")}

function ctxStatusItem() { if (!ui.status) return ""; if (!ctxOther()) return `·docker → ${esc(ui.status.app || "Kiri")}`; + const pinned = ctxPinned(); + if (pinned) return `·`; return `·`; } function renderCtxStrip() { const el = $("impstrip"); if (!ctxOther() || !["containers", "images"].includes(ui.view) || Date.now() < (prefs.ctxSnooze || 0) || ctx.card) return false; - el.innerHTML = `${ctxWarn("is-warn")} - ${tr("docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.", { engine: esc(ctxLabel(ui.status.context)) })} - - `; + const pinned = ctxPinned(); + if (pinned) { + el.innerHTML = `${ctxWarn("is-warn")} + ${tr("{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.", { env: `${esc(pinned)}`, docker: "docker", app: esc(ui.status.app || "Kiri") })} + `; + } else { + el.innerHTML = `${ctxWarn("is-warn")} + ${tr("docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.", { engine: esc(ctxLabel(ui.status.context)) })} + + `; + } el.classList.add("ctx"); el.hidden = false; return true; @@ -4096,7 +4108,21 @@

${tr("How should you reach your containers?")}

function ctxDialog() { if (!ctxOther()) return; $("ctx-dlg")?.remove(); - const from = ui.status.context, label = ctxLabel(from), app = ui.status.app || "Kiri"; + const pinned = ctxPinned(), app = ui.status.app || "Kiri"; + if (pinned) { + const cmd = WIN ? `Remove-Item Env:${esc(pinned)}` : `unset ${esc(pinned)}`; + const scrim = document.createElement("div"); + scrim.className = "scrim"; scrim.id = "ctx-dlg"; + scrim.innerHTML = ``; + document.body.append(scrim); + scrim.addEventListener("click", (ev) => { if (ev.target === scrim || ev.target.closest("[data-close]")) scrim.remove(); }); + scrim.querySelector("[data-close]").focus(); + return; + } + const from = ui.status.context, label = ctxLabel(from); const src = ui.imp.sources?.find((s) => s.id === from), imgs = ctxImages(from), inv = ui.imp.inv; if (src?.running && !imgs) send("inventory", { name: from }); const bytes = (imgs || []).reduce((a, v) => a + ctxBytes(v.size), 0); @@ -4367,16 +4393,64 @@

${tr("Use {app} for docker?", { app: esc(app) })}

`; } -/* Settings → Network: the proxy for pulls and, if wanted, for containers. */ +/* Settings → Network: Docker's default socket + CLI binding, and the proxy. */ +function dockerSockRows() { + const app = ui.status?.app || "Kiri"; + const mono = (t) => `${esc(String(t))}`; + const s = ui.dockersock; + let sockRow = ""; + if (s) { + let desc = "", pact = ""; + if (s.owner === "kiri") { + desc = tr("{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.", { path: mono(s.path), app: esc(app) }); + pact = `${esc(app)}`; + } else if (s.owner === "other") { + const who = s.engine ? (s.target?.includes("/") ? `${esc(s.engine)} (${mono(s.target)})` : esc(s.engine)) : s.target ? mono(s.target) : tr("another engine"); + desc = `${tr("{path} belongs to {engine} and stays so.", { path: mono(s.path), engine: who })}
${tr("Tools that ignore docker contexts can use {hint}", { hint: `${esc(s.hint)}` })}${copyBtn(s.hint, tr("command"))}`; + pact = `${s.engine ? esc(s.engine) : tr("In use")}`; + } else { + desc = s.take + ? tr("{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.", { path: mono(s.path), app: esc(app) }) + : WIN + ? tr("{path} is free. {app} serves it whenever it runs and no other Docker engine does.", { path: mono(s.path), app: esc(app) }) + : LINUX + ? tr("{path} is free. {service} links it when Kiri starts while no other Docker engine has it.", { path: mono(s.path), service: mono("kiri.service") }) + : tr("{path} is free. {app} leaves it for the installed Kiri.", { path: mono(s.path), app: esc(app) }); + pact = s.take + ? `` + : `${tr("Free")}`; + } + sockRow = `
${tr("Docker socket")}${desc}${pact}
`; + } + let cliRow = ""; + if (ui.status) { + const pinned = ctxPinned(); + let desc = "", pact = ""; + if (!ctxOther()) { + desc = tr("The {docker} command uses {app}.", { docker: mono("docker"), app: esc(app) }); + pact = `${esc(app)}`; + } else if (pinned) { + desc = tr("{env} is set in this session, so {docker} uses another engine.", { env: mono(pinned), docker: mono("docker") }); + pact = `${esc(pinned)}`; + } else { + desc = tr("The {docker} command uses {engine}.", { docker: mono("docker"), engine: esc(ctxLabel(ui.status.context)) }); + pact = ``; + } + cliRow = `
${tr("{docker} command", { docker: mono("docker") })}${desc}${pact}
`; + } + return sockRow + cliRow; +} + function networkPane() { - const p = ui.proxy; - if (!p) return `

${tr("Network")}

${tr("Loading…")}

`; - if (p.error) return `

${tr("Network")}

${tr("Start Kiri to change its network settings. ({error})", { error: esc(p.error) })}

`; + const p = ui.proxy, sock = dockerSockRows(); + if (!p) return `

${tr("Network")}

${sock}

${tr("Loading…")}

`; + if (p.error) return `

${tr("Network")}

${sock}

${tr("Start Kiri to change its network settings. ({error})", { error: esc(p.error) })}

`; const d = ui.pxDraft, eff = p.effective; const seg = [["system", tr("{os} settings", { os: OS })], ["custom", tr("Custom")], ["none", tr("None")]].map(([v, l]) => ``).join(""); const now = eff.https || eff.http ? (eff.no_proxy.length ? tr("In use: {proxy}, except {hosts}.", { proxy: `${esc(eff.https || eff.http)}`, hosts: `${esc(eff.no_proxy.join(", "))}` }) : tr("In use: {proxy}.", { proxy: `${esc(eff.https || eff.http)}` })) : tr("No proxy is in use."); const field = (k, label, ph) => ``; return `

${tr("Network")}

+ ${sock}
${tr("Proxy")}${tr("For pulling and pushing images.")} ${d.mode === p.settings.mode ? now : ""}
${seg}
${d.mode === "system" && eff.pac ? `

${tr("{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.", { os: OS })}

` : ""} @@ -4619,7 +4693,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

if (view === "compose") { cmp.open = null; cmp.asked = 0; cmpAsk(); } if (view === "usb") usbPoll(); if (view === "share") { send("shares"); send("shareusage"); shPoll(); } - if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("proxy"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } + if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("dockersock"); send("proxy"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } render(); // From the top, as a container's or pod's page opens: leaving a page scrolled // down (a long Terminal or Logs tab) otherwise opened the next view below its rows. @@ -8153,6 +8227,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "onboarding": onboarding(e); break; case "buildask": buildAsk(e.engine); break; case "buildwith": ui.bw = e; if (ui.view === "settings") render(); break; + case "dockersock": ui.dockersock = e; ui.sockTaking = false; if (ui.view === "settings") render(); break; case "status": ui.status = e; document.body.classList.toggle("dev", !!e.dev); @@ -8206,7 +8281,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "imagelayers": if (ui.imgd?.name === e.name) { ui.imgd.layers = e; if (ui.view === "images") render(); } break; case "buildlayers": if (ui.bl.sel?.id === e.id) { ui.bl.layers = e; if (ui.view === "builds") renderBuilds(); } break; case "build": if (ui.bl.sel?.id === e.id) { ui.bl.d = e; if (ui.view === "builds") renderBuilds(); } break; - case "usedcontext": if (e.error) toast("error", tr("Couldn't switch docker: {error}", { error: e.error })); break; + case "usedcontext": ui.ctxSwitching = false; if (e.error) toast("error", tr("Couldn't switch docker: {error}", { error: e.error })); if (ui.view === "settings") render(); break; case "importsources": ui.imp.sources = e.sources; { const s = e.sources.find((x) => x.id === ui.imp.source) || e.sources.find((x) => x.running && x.id === ui.status?.context) || e.sources.find((x) => x.running) || e.sources[0]; if (s) { ui.imp.source = s.id; if (s.running) send("inventory", { name: s.id }); } } if (ui.view === "settings") render(); break; case "inventory": ui.imp.inv = e; if (ui.view === "settings") render(); renderImportStrip(); drawImportModal(); break; case "importstep": ctxStep(e); ui.imp.steps[`${e.kind}/${e.name}`] = e; if (e.state !== "running") ui.imp.picked[e.kind].delete(e.name); if (ui.view === "settings") render(); drawImportModal(); break; @@ -8340,7 +8415,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-g]"))) projectAsk(el.dataset.project, el.dataset.g); else if ((el = t("[data-group]"))) toggleGroup(el); else if (composeClick(t)) {} - else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "builds") send("buildwith"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } + else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "network") { send("proxy"); send("dockersock"); } if (prefs.tab === "builds") send("buildwith"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } else if (diagClick(t)) {} else if ((el = t("[data-scale]"))) setPref("scale", +el.dataset.scale); else if ((el = t("[data-logsize]"))) setPref("logSize", +el.dataset.logsize); @@ -8362,6 +8437,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-pxmode]"))) { ui.pxDraft.mode = el.dataset.pxmode; render(); } else if ((el = t("[data-pxc]"))) { ui.pxDraft.containers = !!+el.dataset.pxc; render(); } else if ((el = t("[data-savepx]"))) send("setproxy", { value: ui.pxDraft }); + else if (t("[data-takesock]")) { ui.sockTaking = true; send("takesocket"); render(); } + else if (t("[data-usekiri]")) { ui.ctxSwitching = true; send("usecontext", { name: ui.status.ours }); render(); } else if ((el = t("[data-regadd]"))) regListAdd(el.dataset.regadd); else if ((el = t("[data-regdel]"))) { const [k, i] = el.dataset.regdel.split(":"); ui.regDraft[k].splice(+i, 1); render(); } else if ((el = t("[data-regsave]"))) { ui.regSaving = el.dataset.regsave; send("setregistryconfig", { value: { [REG_KEY[el.dataset.regsave]]: ui.regDraft[el.dataset.regsave] } }); } @@ -9280,7 +9357,7 @@

${tr("Labels")}

}, 4000); // Animations rest while another window is in front, or this one is hidden. const away = () => document.body.classList.toggle("away", document.hidden || !document.hasFocus()); -addEventListener("focus", away); addEventListener("blur", away); document.addEventListener("visibilitychange", away); +addEventListener("focus", () => { away(); send("dockersock"); }); addEventListener("blur", away); document.addEventListener("visibilitychange", away); // The crane's sway (.is-art), once every 20 s while Kiri is the window in use. setInterval(() => { document.body.classList.remove("sway"); diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index 9741eaae7..da33e5e7a 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "ሲገቡ Kiriን ጀምር", "Start Kiri in the background when you sign in.": "ሲገቡ Kiriን ከበስተጀርባ ጀምር።", "Stop the engine when Kiri quits": "ከKiri ሲወጡ ሞተሩን አቁም", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ከKiri መውጣት የሚሠሩ ኮንቴይነሮችን እና ሞተሩን ያቆማል። Kiriን መክፈት እንደገና ያስጀምረዋል።" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ከKiri መውጣት የሚሠሩ ኮንቴይነሮችን እና ሞተሩን ያቆማል። Kiriን መክፈት እንደገና ያስጀምረዋል።", + "{env} is set, so docker uses another engine instead of {app}": "{env} ተዘጋጅቷል፣ ስለዚህ docker በ{app} ፈንታ ሌላ ሞተር ይጠቀማል", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} ተዘጋጅቷል፣ ስለዚህ {docker} በ{app} ፈንታ ሌላ ሞተር ይጠቀማል። {app}ን ለመጠቀም በሼልዎ ውስጥ ያጥፉት።", + "{env} is set": "{env} ተዘጋጅቷል", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} በዚህ ክፍለ ጊዜ የdockerን አውድ ይሽራል፣ ስለዚህ አውድ መቀየር {docker}ን ወደ {app} አይወስደውም። በ{cmd} ያጥፉት ወይም ከመገለጫዎ ያስወግዱት።", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} ወደ {app} ይመራል። እንደ Testcontainers፣ IDE ተሰኪዎች እና SDK ያሉ መሣሪያዎች በቀጥታ ይጠቀሙበታል።", + "another engine": "ሌላ ሞተር", + "{path} belongs to {engine} and stays so.": "{path} የ{engine} ነው እና እንደዚያው ይቆያል።", + "Tools that ignore docker contexts can use {hint}": "የdocker አውዶችን ችላ የሚሉ መሣሪያዎች {hint}ን መጠቀም ይችላሉ", + "command": "ትዕዛዝ", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ነፃ ነው። የdocker አውዶችን ችላ የሚሉ መሣሪያዎች {app}ን እዚያ እንዲያገኙት ከ{app} ጋር ያገናኙት።", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ነፃ ነው። {app} በሚሠራበት እና ሌላ የDocker ሞተር በማይሠራበት ጊዜ ሁሉ ያገለግለዋል።", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ነፃ ነው። ሌላ የDocker ሞተር ከሌለው Kiri ሲጀምር {service} ያገናኘዋል።", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ነፃ ነው። {app} ለተጫነው Kiri ይተወዋል።", + "Linking…": "በማገናኘት ላይ…", + "Use {app}": "{app}ን ተጠቀም", + "Free": "ነፃ", + "Docker socket": "Docker ሶኬት", + "The {docker} command uses {app}.": "የ{docker} ትዕዛዝ {app}ን ይጠቀማል።", + "{env} is set in this session, so {docker} uses another engine.": "{env} በዚህ ክፍለ ጊዜ ተዘጋጅቷል፣ ስለዚህ {docker} ሌላ ሞተር ይጠቀማል።", + "The {docker} command uses {engine}.": "የ{docker} ትዕዛዝ {engine}ን ይጠቀማል።", + "Switching…": "በመቀየር ላይ…", + "{docker} command": "{docker} ትዕዛዝ", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock አሁን ወደ Kiri ያመለክታል", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sockን ማገናኘት አልተቻለም: {error}" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index 624faeaa9..b1e270953 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "بدء Kiri عند تسجيل الدخول", "Start Kiri in the background when you sign in.": "بدء Kiri في الخلفية عند تسجيل دخولك.", "Stop the engine when Kiri quits": "إيقاف المحرّك عند إنهاء Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "إنهاء Kiri يوقف الحاويات التي تعمل والمحرّك. فتح Kiri يبدؤه من جديد." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "إنهاء Kiri يوقف الحاويات التي تعمل والمحرّك. فتح Kiri يبدؤه من جديد.", + "{env} is set, so docker uses another engine instead of {app}": "{env} مضبوط، لذا يستخدم docker محركاً آخر بدلاً من {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} مضبوط، لذا يستخدم {docker} محركاً آخر بدلاً من {app}. أزله من صدفة الأوامر لاستخدام {app}.", + "{env} is set": "{env} مضبوط", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} يتجاوز سياق docker في هذه الجلسة، لذا لن ينقل تبديل السياق {docker} إلى {app}. امسحه بالأمر {cmd} أو أزله من ملف تعريف الصدفة.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "يشير {path} إلى {app}. تستخدمه أدوات مثل Testcontainers وإضافات بيئات التطوير وحزم SDK مباشرة.", + "another engine": "محرك آخر", + "{path} belongs to {engine} and stays so.": "يتبع {path} للمحرك {engine} ويبقى كذلك.", + "Tools that ignore docker contexts can use {hint}": "يمكن للأدوات التي تتجاهل سياقات docker استخدام {hint}", + "command": "أمر", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} متاح. اربطه بـ {app} لتجد الأدوات التي تتجاهل سياقات docker تطبيق {app} هناك.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} متاح. يخدمه {app} متى كان يعمل ولم يعمل أي محرك Docker آخر.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} متاح. يربطه {service} عند بدء Kiri ما دام لا يشغله أي محرك Docker آخر.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} متاح. يتركه {app} لنسخة Kiri المثبتة.", + "Linking…": "جارٍ الربط…", + "Use {app}": "استخدام {app}", + "Free": "متاح", + "Docker socket": "مقبس Docker", + "The {docker} command uses {app}.": "الأمر {docker} يستخدم {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} مضبوط في هذه الجلسة، لذا يستخدم {docker} محركاً آخر.", + "The {docker} command uses {engine}.": "الأمر {docker} يستخدم {engine}.", + "Switching…": "جارٍ التبديل…", + "{docker} command": "أمر {docker}", + "/var/run/docker.sock now points to Kiri": "يشير /var/run/docker.sock الآن إلى Kiri", + "Could not link /var/run/docker.sock: {error}": "تعذّر ربط /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 3c1c8aefe..ca4f4a324 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Стартиране на Kiri при влизане", "Start Kiri in the background when you sign in.": "Стартиране на Kiri във фонов режим, когато влезете.", "Stop the engine when Kiri quits": "Спиране на двигателя при излизане от Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Излизането от Kiri спира работещите контейнери и двигателя. Отварянето на Kiri го стартира отново." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Излизането от Kiri спира работещите контейнери и двигателя. Отварянето на Kiri го стартира отново.", + "{env} is set, so docker uses another engine instead of {app}": "{env} е зададена, така че docker използва друг двигател вместо {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} е зададена, така че {docker} използва друг двигател вместо {app}. Премахнете я в обвивката си, за да използвате {app}.", + "{env} is set": "{env} е зададена", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} отменя контекста на docker в тази сесия, така че смяната на контекста няма да насочи {docker} към {app}. Изчистете я с {cmd} или я премахнете от профила си.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} води към {app}. Инструменти като Testcontainers, добавки за IDE и SDK го използват директно.", + "another engine": "друг двигател", + "{path} belongs to {engine} and stays so.": "{path} принадлежи на {engine} и остава така.", + "Tools that ignore docker contexts can use {hint}": "Инструментите, които пренебрегват контекстите на docker, могат да използват {hint}", + "command": "команда", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} е свободен. Свържете го с {app}, за да може инструментите, които пренебрегват контекстите на docker, да намират {app} там.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} е свободен. {app} го обслужва винаги щом работи и няма друг Docker двигател.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} е свободен. {service} го свързва при стартиране на Kiri, когато никой друг Docker двигател не го заема.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} е свободен. {app} го оставя за инсталирания Kiri.", + "Linking…": "Свързване…", + "Use {app}": "Използвай {app}", + "Free": "Свободен", + "Docker socket": "Docker сокет", + "The {docker} command uses {app}.": "Командата {docker} използва {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} е зададена в тази сесия, така че {docker} използва друг двигател.", + "The {docker} command uses {engine}.": "Командата {docker} използва {engine}.", + "Switching…": "Превключване…", + "{docker} command": "Команда {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock вече сочи към Kiri", + "Could not link /var/run/docker.sock: {error}": "Неуспешно свързване на /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 815b50f98..0830e3816 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "সাইন ইন করার সময় Kiri চালু করুন", "Start Kiri in the background when you sign in.": "আপনি সাইন ইন করলে পটভূমিতে Kiri চালু করুন।", "Stop the engine when Kiri quits": "Kiri বন্ধ করলে ইঞ্জিন থামান", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri বন্ধ করলে চলমান কন্টেইনার এবং ইঞ্জিন থেমে যায়। Kiri খুললে এটি আবার চালু হয়।" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri বন্ধ করলে চলমান কন্টেইনার এবং ইঞ্জিন থেমে যায়। Kiri খুললে এটি আবার চালু হয়।", + "{env} is set, so docker uses another engine instead of {app}": "{env} সেট করা আছে, তাই docker {app}-এর বদলে অন্য একটি ইঞ্জিন ব্যবহার করে", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} সেট করা আছে, তাই {docker} {app}-এর বদলে অন্য একটি ইঞ্জিন ব্যবহার করে। {app} ব্যবহার করতে শেল থেকে এটি আনসেট করুন।", + "{env} is set": "{env} সেট করা আছে", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} এই সেশনে docker-এর কন্টেক্সট ওভাররাইড করে, তাই কন্টেক্সট বদলালে {docker} {app}-এ যাবে না। {cmd} দিয়ে এটি মুছুন বা আপনার প্রোফাইল থেকে সরান।", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} সরাসরি {app}-এ যায়। Testcontainers, IDE প্লাগইন এবং SDK-এর মতো টুল এটি সরাসরি ব্যবহার করে।", + "another engine": "অন্য ইঞ্জিন", + "{path} belongs to {engine} and stays so.": "{path} বর্তমানে {engine}-এর অধীনে আছে এবং তাই থাকবে।", + "Tools that ignore docker contexts can use {hint}": "যে টুলগুলো docker কন্টেক্সট উপেক্ষা করে তারা {hint} ব্যবহার করতে পারে", + "command": "কমান্ড", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} খালি আছে। {app}-এর সাথে এটি লিঙ্ক করুন যাতে docker কন্টেক্সট উপেক্ষা করা টুলগুলো সেখানে {app}-কে পায়।", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} খালি আছে। যখনই {app} চালু থাকে এবং অন্য কোনো Docker ইঞ্জিন না থাকে, এটি পরিবেশন করে।", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} খালি আছে। অন্য কোনো Docker ইঞ্জিন না থাকলে Kiri শুরু হওয়ার সময় {service} এটি লিঙ্ক করে।", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} খালি আছে। ইনস্টল করা Kiri-এর জন্য {app} এটি ছেড়ে দেয়।", + "Linking…": "লিঙ্ক করা হচ্ছে…", + "Use {app}": "{app} ব্যবহার করুন", + "Free": "খালি", + "Docker socket": "Docker সকেট", + "The {docker} command uses {app}.": "{docker} কমান্ডটি {app} ব্যবহার করে।", + "{env} is set in this session, so {docker} uses another engine.": "এই সেশনে {env} সেট করা আছে, তাই {docker} অন্য ইঞ্জিন ব্যবহার করে।", + "The {docker} command uses {engine}.": "{docker} কমান্ডটি {engine} ব্যবহার করে।", + "Switching…": "পরিবর্তন করা হচ্ছে…", + "{docker} command": "{docker} কমান্ড", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock এখন Kiri-কে নির্দেশ করে", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock লিঙ্ক করা যায়নি: {error}" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index c4776d971..8a54aa171 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Inicia Kiri en iniciar la sessió", "Start Kiri in the background when you sign in.": "Inicia Kiri en segon pla quan inicies la sessió.", "Stop the engine when Kiri quits": "Atura el motor en sortir de Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "En sortir de Kiri s'aturen els contenidors en execució i el motor. En obrir Kiri es torna a iniciar." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "En sortir de Kiri s'aturen els contenidors en execució i el motor. En obrir Kiri es torna a iniciar.", + "{env} is set, so docker uses another engine instead of {app}": "{env} està definit, així que docker utilitza un altre motor en lloc de {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} està definit, així que {docker} utilitza un altre motor en lloc de {app}. Desactiveu-lo al vostre intèrpret d’ordres per fer servir {app}.", + "{env} is set": "{env} està definit", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} anul·la el context de docker en aquesta sessió, així que canviar de context no mourà {docker} a {app}. Esborreu-lo amb {cmd} o traieu-lo del perfil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} apunta a {app}. Eines com Testcontainers, connectors d’IDE i SDK l’utilitzen directament.", + "another engine": "un altre motor", + "{path} belongs to {engine} and stays so.": "{path} pertany a {engine} i es manté així.", + "Tools that ignore docker contexts can use {hint}": "Les eines que ignoren els contextos de docker poden utilitzar {hint}", + "command": "ordre", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} és lliure. Enllaceu-lo amb {app} perquè les eines que ignoren els contextos de docker hi trobin {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} és lliure. {app} el serveix sempre que s’executa i cap altre motor Docker ho fa.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} és lliure. {service} l’enllaça quan s’inicia Kiri mentre cap altre motor Docker el tingui.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} és lliure. {app} el deixa per al Kiri instal·lat.", + "Linking…": "Enllaçant…", + "Use {app}": "Fes servir {app}", + "Free": "Lliure", + "Docker socket": "Sòcol de Docker", + "The {docker} command uses {app}.": "L’ordre {docker} utilitza {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} està definit en aquesta sessió, així que {docker} utilitza un altre motor.", + "The {docker} command uses {engine}.": "L’ordre {docker} utilitza {engine}.", + "Switching…": "Canviant…", + "{docker} command": "Ordre {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ara apunta a Kiri", + "Could not link /var/run/docker.sock: {error}": "No s’ha pogut enllaçar /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index e0736816a..f0d3b9418 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "لە کاتی چوونەژوورەوە Kiri دەست پێبکە", "Start Kiri in the background when you sign in.": "کاتێک دەچیتە ژوورەوە Kiri لە پاشبنەمادا دەست پێبکە.", "Stop the engine when Kiri quits": "کاتێک لە Kiri دەردەچیت بزوێنەر ڕابگرە", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "دەرچوون لە Kiri کۆنتەینەرە کاراکان و بزوێنەر ڕادەگرێت. کردنەوەی Kiri دووبارە دەستی پێدەکاتەوە." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "دەرچوون لە Kiri کۆنتەینەرە کاراکان و بزوێنەر ڕادەگرێت. کردنەوەی Kiri دووبارە دەستی پێدەکاتەوە.", + "{env} is set, so docker uses another engine instead of {app}": "{env} دیاریکراوە، بۆیە docker مۆتۆڕێکی تر بەکاردەهێنێت لەجیاتی {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} دیاریکراوە، بۆیە {docker} مۆتۆڕێکی تر بەکاردەهێنێت لەجیاتی {app}. لە شێڵەکەتدا لایببە بۆ بەکارهێنانی {app}.", + "{env} is set": "{env} دیاریکراوە", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} بەستێنی docker لەم دانیشتنەدا پێشێل دەکات، بۆیە گۆڕینی بەستێن {docker} ناگوازێتەوە بۆ {app}. بە {cmd} پاکی بکەرەوە یان لە پڕۆفایلەکەت لایببە.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} دەچێتە سەر {app}. ئامرازەکانی وەک Testcontainers و پێوەکراوەکانی IDE و SDK ڕاستەوخۆ بەکاری دەهێنن.", + "another engine": "مۆتۆڕێکی تر", + "{path} belongs to {engine} and stays so.": "{path} هی {engine}ـە و وەک خۆی دەمێنێتەوە.", + "Tools that ignore docker contexts can use {hint}": "ئەو ئامرازانەی بەستێنی docker پشتگوێ دەخەن دەتوانن {hint} بەکاربهێنن", + "command": "فەرمان", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} بەتاڵە. بیبەستە بە {app} بۆ ئەوەی ئەو ئامرازانەی بەستێنی docker پشتگوێ دەخەن {app} لەوێ بدۆزنەوە.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} بەتاڵە. هەر کاتێک {app} کاربکات و مۆتۆڕێکی تری Docker نەبێت، ڕاژەی دەکات.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} بەتاڵە. {service} دەیبەستێتەوە کاتێک Kiri دەستپێدەکات ئەگەر مۆتۆڕێکی تری Docker نەیگرتبێت.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} بەتاڵە. {app} بۆ Kiriـی دامەزراو بەجێی دەهێڵێت.", + "Linking…": "دەبەسترێتەوە…", + "Use {app}": "بەکارهێنانی {app}", + "Free": "بەتاڵ", + "Docker socket": "سۆکێتی Docker", + "The {docker} command uses {app}.": "فەرمانی {docker} مۆتۆڕی {app} بەکاردەهێنێت.", + "{env} is set in this session, so {docker} uses another engine.": "{env} لەم دانیشتنەدا دیاریکراوە، بۆیە {docker} مۆتۆڕێکی تر بەکاردەهێنێت.", + "The {docker} command uses {engine}.": "فەرمانی {docker} مۆتۆڕی {engine} بەکاردەهێنێت.", + "Switching…": "دەگۆڕدرێت…", + "{docker} command": "فەرمانی {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ئێستا ئاراستەی Kiri دەکات", + "Could not link /var/run/docker.sock: {error}": "نەتوانرا /var/run/docker.sock ببەسترێتەوە: {error}" } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index b0a060ccc..d6cc906c8 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Spouštět Kiri při přihlášení", "Start Kiri in the background when you sign in.": "Spustit Kiri na pozadí, když se přihlásíte.", "Stop the engine when Kiri quits": "Zastavit engine při ukončení Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ukončení Kiri zastaví běžící kontejnery a engine. Otevření Kiri ho znovu spustí." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ukončení Kiri zastaví běžící kontejnery a engine. Otevření Kiri ho znovu spustí.", + "{env} is set, so docker uses another engine instead of {app}": "Proměnná {env} je nastavena, takže docker používá jiný engine místo {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Proměnná {env} je nastavena, takže {docker} používá jiný engine místo {app}. Zrušte ji v shellu, abyste použili {app}.", + "{env} is set": "Proměnná {env} je nastavena", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "Proměnná {env} v této relaci přebíjí kontext dockeru, takže přepnutí kontextu nepřesměruje {docker} na {app}. Zrušte ji pomocí {cmd} nebo ji odstraňte ze svého profilu.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} vede na {app}. Nástroje jako Testcontainers, doplňky IDE a SDK ho používají přímo.", + "another engine": "jiný engine", + "{path} belongs to {engine} and stays so.": "{path} patří enginu {engine} a zůstává mu.", + "Tools that ignore docker contexts can use {hint}": "Nástroje, které ignorují kontexty dockeru, mohou použít {hint}", + "command": "příkaz", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} je volný. Propojte ho s {app}, aby nástroje ignorující kontexty dockeru našly {app} tam.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} je volný. {app} na něm naslouchá vždy, když běží a žádný jiný Docker engine neběží.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} je volný. {service} ho propojí při spuštění Kiri, pokud ho nedrží jiný Docker engine.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} je volný. {app} ho přenechává nainstalované Kiri.", + "Linking…": "Propojuje se…", + "Use {app}": "Použít {app}", + "Free": "Volný", + "Docker socket": "Docker socket", + "The {docker} command uses {app}.": "Příkaz {docker} používá {app}.", + "{env} is set in this session, so {docker} uses another engine.": "V této relaci je nastavena proměnná {env}, takže {docker} používá jiný engine.", + "The {docker} command uses {engine}.": "Příkaz {docker} používá {engine}.", + "Switching…": "Přepíná se…", + "{docker} command": "Příkaz {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock nyní směřuje na Kiri", + "Could not link /var/run/docker.sock: {error}": "Nepodařilo se propojit /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index b905b19d5..07751130e 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Kiri bei der Anmeldung starten", "Start Kiri in the background when you sign in.": "Kiri im Hintergrund starten, wenn du dich anmeldest.", "Stop the engine when Kiri quits": "Engine beim Beenden von Kiri stoppen", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Das Beenden von Kiri stoppt laufende Container und die Engine. Das Öffnen von Kiri startet sie erneut." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Das Beenden von Kiri stoppt laufende Container und die Engine. Das Öffnen von Kiri startet sie erneut.", + "{env} is set, so docker uses another engine instead of {app}": "{env} ist gesetzt, sodass docker statt {app} eine andere Engine verwendet", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} ist gesetzt, sodass {docker} statt {app} eine andere Engine verwendet. Entfernen Sie die Variable in Ihrer Shell, um {app} zu verwenden.", + "{env} is set": "{env} ist gesetzt", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} überschreibt den Kontext von docker in dieser Sitzung, daher lenkt ein Kontextwechsel {docker} nicht auf {app}. Löschen Sie die Variable mit {cmd} oder entfernen Sie sie aus Ihrem Profil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} führt zu {app}. Werkzeuge wie Testcontainers, IDE-Plugins und SDKs nutzen ihn direkt.", + "another engine": "eine andere Engine", + "{path} belongs to {engine} and stays so.": "{path} gehört zu {engine} und bleibt dort.", + "Tools that ignore docker contexts can use {hint}": "Werkzeuge, die Docker-Kontexte ignorieren, können {hint} verwenden", + "command": "Befehl", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ist frei. Verknüpfen Sie ihn mit {app}, damit Werkzeuge ohne Kontext-Unterstützung {app} dort finden.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ist frei. {app} bedient ihn, sobald er läuft und keine andere Docker-Engine aktiv ist.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ist frei. {service} verknüpft ihn beim Start von Kiri, sofern keine andere Docker-Engine ihn nutzt.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ist frei. {app} überlässt ihn dem installierten Kiri.", + "Linking…": "Verknüpfe…", + "Use {app}": "{app} verwenden", + "Free": "Frei", + "Docker socket": "Docker-Socket", + "The {docker} command uses {app}.": "Der Befehl {docker} verwendet {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} ist in dieser Sitzung gesetzt, sodass {docker} eine andere Engine verwendet.", + "The {docker} command uses {engine}.": "Der Befehl {docker} verwendet {engine}.", + "Switching…": "Wechsle…", + "{docker} command": "Befehl {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock verweist jetzt auf Kiri", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock konnte nicht verknüpft werden: {error}" } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index dc6eb4d63..0f7c155a9 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Εκκίνηση του Kiri κατά τη σύνδεση", "Start Kiri in the background when you sign in.": "Εκκίνηση του Kiri στο παρασκήνιο όταν συνδέεστε.", "Stop the engine when Kiri quits": "Διακοπή της μηχανής κατά τον τερματισμό του Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ο τερματισμός του Kiri σταματά τα κοντέινερ που εκτελούνται και τη μηχανή. Το άνοιγμα του Kiri την ξεκινά ξανά." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ο τερματισμός του Kiri σταματά τα κοντέινερ που εκτελούνται και τη μηχανή. Το άνοιγμα του Kiri την ξεκινά ξανά.", + "{env} is set, so docker uses another engine instead of {app}": "Η {env} είναι ορισμένη, οπότε το docker χρησιμοποιεί άλλη μηχανή αντί για το {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Η {env} είναι ορισμένη, οπότε το {docker} χρησιμοποιεί άλλη μηχανή αντί για το {app}. Καταργήστε την από το κέλυφός σας για να χρησιμοποιήσετε το {app}.", + "{env} is set": "Η {env} είναι ορισμένη", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "Η {env} παρακάμπτει το πλαίσιο του docker σε αυτή τη συνεδρία, οπότε η αλλαγή πλαισίου δεν θα κατευθύνει το {docker} στο {app}. Καθαρίστε την με {cmd} ή αφαιρέστε την από το προφίλ σας.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "Το {path} οδηγεί στο {app}. Εργαλεία όπως Testcontainers, πρόσθετα IDE και SDK το χρησιμοποιούν απευθείας.", + "another engine": "άλλη μηχανή", + "{path} belongs to {engine} and stays so.": "Το {path} ανήκει στο {engine} και παραμένει εκεί.", + "Tools that ignore docker contexts can use {hint}": "Εργαλεία που αγνοούν τα πλαίσια docker μπορούν να χρησιμοποιήσουν {hint}", + "command": "εντολή", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "Το {path} είναι ελεύθερο. Συνδέστε το με το {app} ώστε τα εργαλεία που αγνοούν τα πλαίσια docker να βρίσκουν το {app} εκεί.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "Το {path} είναι ελεύθερο. Το {app} το εξυπηρετεί όποτε εκτελείται χωρίς άλλη μηχανή Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "Το {path} είναι ελεύθερο. Το {service} το συνδέει κατά την εκκίνηση του Kiri όταν δεν το κατέχει άλλη μηχανή Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "Το {path} είναι ελεύθερο. Το {app} το αφήνει για το εγκατεστημένο Kiri.", + "Linking…": "Σύνδεση…", + "Use {app}": "Χρήση {app}", + "Free": "Ελεύθερο", + "Docker socket": "Υποδοχή Docker", + "The {docker} command uses {app}.": "Η εντολή {docker} χρησιμοποιεί το {app}.", + "{env} is set in this session, so {docker} uses another engine.": "Η {env} είναι ορισμένη σε αυτή τη συνεδρία, οπότε το {docker} χρησιμοποιεί άλλη μηχανή.", + "The {docker} command uses {engine}.": "Η εντολή {docker} χρησιμοποιεί το {engine}.", + "Switching…": "Αλλαγή…", + "{docker} command": "Εντολή {docker}", + "/var/run/docker.sock now points to Kiri": "Το /var/run/docker.sock δείχνει πλέον στο Kiri", + "Could not link /var/run/docker.sock: {error}": "Αδυναμία σύνδεσης του /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index e431b3383..0317582c2 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Iniciar Kiri al iniciar sesión", "Start Kiri in the background when you sign in.": "Inicia Kiri en segundo plano cuando inicias sesión.", "Stop the engine when Kiri quits": "Detener el motor al salir de Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Salir de Kiri detiene los contenedores en marcha y el motor. Abrir Kiri lo vuelve a iniciar." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Salir de Kiri detiene los contenedores en marcha y el motor. Abrir Kiri lo vuelve a iniciar.", + "{env} is set, so docker uses another engine instead of {app}": "{env} está definida, por lo que docker usa otro motor en lugar de {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} está definida, por lo que {docker} usa otro motor en lugar de {app}. Quítala en tu shell para usar {app}.", + "{env} is set": "{env} está definida", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} anula el contexto de docker en esta sesión, así que cambiar de contexto no moverá {docker} a {app}. Límpiala con {cmd} o quítala de tu perfil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} lleva a {app}. Herramientas como Testcontainers, complementos de IDE y SDK lo usan directamente.", + "another engine": "otro motor", + "{path} belongs to {engine} and stays so.": "{path} pertenece a {engine} y así se mantiene.", + "Tools that ignore docker contexts can use {hint}": "Las herramientas que ignoran los contextos de docker pueden usar {hint}", + "command": "comando", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} está libre. Enlázalo a {app} para que las herramientas que ignoran los contextos de docker encuentren {app} allí.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} está libre. {app} lo atiende siempre que se ejecuta y ningún otro motor Docker lo hace.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} está libre. {service} lo enlaza al iniciar Kiri mientras no lo use otro motor Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} está libre. {app} lo deja para el Kiri instalado.", + "Linking…": "Enlazando…", + "Use {app}": "Usar {app}", + "Free": "Libre", + "Docker socket": "Socket de Docker", + "The {docker} command uses {app}.": "El comando {docker} usa {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} está definida en esta sesión, por lo que {docker} usa otro motor.", + "The {docker} command uses {engine}.": "El comando {docker} usa {engine}.", + "Switching…": "Cambiando…", + "{docker} command": "Comando {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ahora apunta a Kiri", + "Could not link /var/run/docker.sock: {error}": "No se pudo enlazar /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index 75fafa34b..6e4b66334 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "شروع Kiri هنگام ورود", "Start Kiri in the background when you sign in.": "هنگام ورود شما، Kiri را در پس‌زمینه شروع کند.", "Stop the engine when Kiri quits": "توقف موتور هنگام خروج از Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "خروج از Kiri کانتینرهای در حال اجرا و موتور را متوقف می‌کند. باز کردن Kiri دوباره آن را شروع می‌کند." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "خروج از Kiri کانتینرهای در حال اجرا و موتور را متوقف می‌کند. باز کردن Kiri دوباره آن را شروع می‌کند.", + "{env} is set, so docker uses another engine instead of {app}": "{env} تنظیم شده است، بنابراین docker به‌جای {app} از موتور دیگری استفاده می‌کند", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} تنظیم شده است، بنابراین {docker} به‌جای {app} از موتور دیگری استفاده می‌کند. برای استفاده از {app} آن را در پوسته خود پاک کنید.", + "{env} is set": "{env} تنظیم شده است", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} زمینه docker را در این نشست لغو می‌کند، بنابراین تغییر زمینه {docker} را به {app} منتقل نمی‌کند. با {cmd} پاکش کنید یا از نمایه خود بردارید.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} به {app} متصل است. ابزارهایی مانند Testcontainers، افزونه‌های IDE و SDK مستقیماً از آن استفاده می‌کنند.", + "another engine": "موتور دیگر", + "{path} belongs to {engine} and stays so.": "{path} متعلق به {engine} است و همان‌طور باقی می‌ماند.", + "Tools that ignore docker contexts can use {hint}": "ابزارهایی که زمینه‌های docker را نادیده می‌گیرند می‌توانند از {hint} استفاده کنند", + "command": "فرمان", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} آزاد است. آن را به {app} پیوند دهید تا ابزارهایی که زمینه‌های docker را نادیده می‌گیرند {app} را آنجا بیابند.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} آزاد است. هر زمان {app} اجرا شود و موتور Docker دیگری نباشد، آن را ارائه می‌دهد.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} آزاد است. هنگامی که Kiri آغاز می‌شود و موتور Docker دیگری آن را نگرفته، {service} پیوندش می‌دهد.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} آزاد است. {app} آن را برای Kiri نصب‌شده باقی می‌گذارد.", + "Linking…": "در حال پیوند…", + "Use {app}": "استفاده از {app}", + "Free": "آزاد", + "Docker socket": "سوکت Docker", + "The {docker} command uses {app}.": "فرمان {docker} از {app} استفاده می‌کند.", + "{env} is set in this session, so {docker} uses another engine.": "{env} در این نشست تنظیم شده است، بنابراین {docker} از موتور دیگری استفاده می‌کند.", + "The {docker} command uses {engine}.": "فرمان {docker} از {engine} استفاده می‌کند.", + "Switching…": "در حال تغییر…", + "{docker} command": "فرمان {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock اکنون به Kiri اشاره می‌کند", + "Could not link /var/run/docker.sock: {error}": "پیوند دادن /var/run/docker.sock ممکن نشد: {error}" } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index e0546520a..4a58b9586 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Käynnistä Kiri sisäänkirjautuessa", "Start Kiri in the background when you sign in.": "Käynnistä Kiri taustalla, kun kirjaudut sisään.", "Stop the engine when Kiri quits": "Pysäytä moottori, kun Kiri lopetetaan", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kirin lopettaminen pysäyttää käynnissä olevat kontit ja moottorin. Kirin avaaminen käynnistää sen uudelleen." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kirin lopettaminen pysäyttää käynnissä olevat kontit ja moottorin. Kirin avaaminen käynnistää sen uudelleen.", + "{env} is set, so docker uses another engine instead of {app}": "{env} on asetettu, joten docker käyttää toista moottoria {app}:n sijaan", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} on asetettu, joten {docker} käyttää toista moottoria {app}:n sijaan. Poista se komentotulkista käyttääksesi {app}:ta.", + "{env} is set": "{env} on asetettu", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} ohittaa dockerin kontekstin tässä istunnossa, joten kontekstin vaihto ei siirrä komentoa {docker} kohteeseen {app}. Tyhjennä se komennolla {cmd} tai poista profiilistasi.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} johtaa kohteeseen {app}. Testcontainersin kaltaiset työkalut, IDE-liitännäiset ja SDK:t käyttävät sitä suoraan.", + "another engine": "toinen moottori", + "{path} belongs to {engine} and stays so.": "{path} kuuluu moottorille {engine} ja pysyy sillä.", + "Tools that ignore docker contexts can use {hint}": "Docker-kontekstit ohittavat työkalut voivat käyttää arvoa {hint}", + "command": "komento", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} on vapaa. Linkitä se kohteeseen {app}, jotta docker-kontekstit ohittavat työkalut löytävät sieltä kohteen {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} on vapaa. {app} palvelee sitä aina käynnissä ollessaan, kun mikään muu Docker-moottori ei tee niin.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} on vapaa. {service} linkittää sen Kirin käynnistyessä, jos muuta Docker-moottoria ei ole.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} on vapaa. {app} jättää sen asennetulle Kirille.", + "Linking…": "Linkitetään…", + "Use {app}": "Käytä {app}", + "Free": "Vapaa", + "Docker socket": "Docker-pistoke", + "The {docker} command uses {app}.": "Komento {docker} käyttää kohdetta {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} on asetettu tässä istunnossa, joten {docker} käyttää toista moottoria.", + "The {docker} command uses {engine}.": "Komento {docker} käyttää moottoria {engine}.", + "Switching…": "Vaihdetaan…", + "{docker} command": "Komento {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock osoittaa nyt Kiriin", + "Could not link /var/run/docker.sock: {error}": "Polun /var/run/docker.sock linkittäminen epäonnistui: {error}" } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index ae76d26f1..09162ab1c 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Démarrer Kiri à l’ouverture de session", "Start Kiri in the background when you sign in.": "Démarre Kiri en arrière-plan à l’ouverture de votre session.", "Stop the engine when Kiri quits": "Arrêter le moteur en quittant Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Quitter Kiri arrête les conteneurs en marche et le moteur. Ouvrir Kiri le relance." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Quitter Kiri arrête les conteneurs en marche et le moteur. Ouvrir Kiri le relance.", + "{env} is set, so docker uses another engine instead of {app}": "{env} est défini, donc docker utilise un autre moteur au lieu de {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} est défini, donc {docker} utilise un autre moteur au lieu de {app}. Supprimez-le de votre shell pour utiliser {app}.", + "{env} is set": "{env} est défini", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} remplace le contexte docker dans cette session : changer de contexte ne dirigera pas {docker} vers {app}. Effacez-le avec {cmd} ou retirez-le de votre profil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} mène à {app}. Les outils comme Testcontainers, les extensions d’IDE et les SDK l’utilisent directement.", + "another engine": "un autre moteur", + "{path} belongs to {engine} and stays so.": "{path} appartient à {engine} et reste tel quel.", + "Tools that ignore docker contexts can use {hint}": "Les outils qui ignorent les contextes docker peuvent utiliser {hint}", + "command": "commande", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} est libre. Liez-le à {app} pour que les outils ignorant les contextes docker y trouvent {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} est libre. {app} le sert dès qu’il tourne et qu’aucun autre moteur Docker ne le prend.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} est libre. {service} le lie au démarrage de Kiri tant qu’aucun autre moteur Docker ne l’occupe.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} est libre. {app} le laisse au Kiri installé.", + "Linking…": "Liaison…", + "Use {app}": "Utiliser {app}", + "Free": "Libre", + "Docker socket": "Socket Docker", + "The {docker} command uses {app}.": "La commande {docker} utilise {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} est défini dans cette session, donc {docker} utilise un autre moteur.", + "The {docker} command uses {engine}.": "La commande {docker} utilise {engine}.", + "Switching…": "Changement…", + "{docker} command": "Commande {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock pointe maintenant vers Kiri", + "Could not link /var/run/docker.sock: {error}": "Impossible de lier /var/run/docker.sock : {error}" } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 1b138b0be..cf7983d5e 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "साइन इन पर Kiri शुरू करें", "Start Kiri in the background when you sign in.": "जब आप साइन इन करते हैं तो Kiri को बैकग्राउंड में शुरू करें।", "Stop the engine when Kiri quits": "Kiri बंद करने पर इंजन रोकें", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri बंद करने से चलते कंटेनर और इंजन रुक जाते हैं। Kiri खोलने पर यह फिर शुरू हो जाता है।" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri बंद करने से चलते कंटेनर और इंजन रुक जाते हैं। Kiri खोलने पर यह फिर शुरू हो जाता है।", + "{env} is set, so docker uses another engine instead of {app}": "{env} सेट है, इसलिए docker {app} के बजाय दूसरे इंजन का उपयोग करता है", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} सेट है, इसलिए {docker} {app} के बजाय दूसरे इंजन का उपयोग करता है। {app} का उपयोग करने के लिए इसे अपने शेल से अनसेट करें।", + "{env} is set": "{env} सेट है", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} इस सत्र में docker के कॉन्टेक्स्ट को ओवरराइड करता है, इसलिए कॉन्टेक्स्ट बदलने से {docker} {app} पर नहीं जाएगा। इसे {cmd} से हटाएँ या अपनी प्रोफ़ाइल से निकालें।", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} {app} की ओर जाता है। Testcontainers, IDE प्लगइन और SDK जैसे टूल इसका सीधे उपयोग करते हैं।", + "another engine": "दूसरा इंजन", + "{path} belongs to {engine} and stays so.": "{path} {engine} के पास है और वहीं रहता है।", + "Tools that ignore docker contexts can use {hint}": "docker कॉन्टेक्स्ट को अनदेखा करने वाले टूल {hint} का उपयोग कर सकते हैं", + "command": "कमांड", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} खाली है। इसे {app} से लिंक करें ताकि docker कॉन्टेक्स्ट अनदेखा करने वाले टूल वहाँ {app} पा सकें।", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} खाली है। जब भी {app} चलता है और कोई अन्य Docker इंजन नहीं होता, यह इसे सर्व करता है।", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} खाली है। जब Kiri शुरू होता है और किसी अन्य Docker इंजन के पास यह नहीं होता, तो {service} इसे लिंक करता है।", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} खाली है। {app} इसे इंस्टॉल किए गए Kiri के लिए छोड़ देता है।", + "Linking…": "लिंक हो रहा है…", + "Use {app}": "{app} का उपयोग करें", + "Free": "खाली", + "Docker socket": "Docker सॉकेट", + "The {docker} command uses {app}.": "{docker} कमांड {app} का उपयोग करता है।", + "{env} is set in this session, so {docker} uses another engine.": "इस सत्र में {env} सेट है, इसलिए {docker} दूसरे इंजन का उपयोग करता है।", + "The {docker} command uses {engine}.": "{docker} कमांड {engine} का उपयोग करता है।", + "Switching…": "बदल रहा है…", + "{docker} command": "{docker} कमांड", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock अब Kiri की ओर इंगित करता है", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock लिंक नहीं हो सका: {error}" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 6c68d2a7c..088650b5c 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "A Kiri indítása bejelentkezéskor", "Start Kiri in the background when you sign in.": "A Kiri indítása a háttérben bejelentkezéskor.", "Stop the engine when Kiri quits": "A motor leállítása a Kiriből való kilépéskor", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "A Kiriből való kilépés leállítja a futó konténereket és a motort. A Kiri megnyitása újra elindítja." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "A Kiriből való kilépés leállítja a futó konténereket és a motort. A Kiri megnyitása újra elindítja.", + "{env} is set, so docker uses another engine instead of {app}": "A(z) {env} be van állítva, így a docker a(z) {app} helyett másik motort használ", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "A(z) {env} be van állítva, így a(z) {docker} a(z) {app} helyett másik motort használ. Törölje a parancsértelmezőben a(z) {app} használatához.", + "{env} is set": "A(z) {env} be van állítva", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "A(z) {env} ebben a munkamenetben felülbírálja a docker környezetét, ezért a környezetváltás nem irányítja át a(z) {docker} parancsot a(z) {app} felé. Törölje a(z) {cmd} paranccsal, vagy távolítsa el a profiljából.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "A(z) {path} a(z) {app} felé mutat. Az olyan eszközök, mint a Testcontainers, az IDE-bővítmények és az SDK-k közvetlenül használják.", + "another engine": "egy másik motor", + "{path} belongs to {engine} and stays so.": "A(z) {path} a(z) {engine} tulajdona, és az is marad.", + "Tools that ignore docker contexts can use {hint}": "A docker-környezeteket figyelmen kívül hagyó eszközök használhatják ezt: {hint}", + "command": "parancs", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "A(z) {path} szabad. Csatolja a(z) {app} alkalmazáshoz, hogy a docker-környezeteket figyelmen kívül hagyó eszközök ott megtalálják a(z) {app} motort.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "A(z) {path} szabad. A(z) {app} kiszolgálja, valahányszor fut és más Docker motor nem foglalja.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "A(z) {path} szabad. A(z) {service} csatolja a Kiri indulásakor, amíg más Docker motor nem használja.", + "{path} is free. {app} leaves it for the installed Kiri.": "A(z) {path} szabad. A(z) {app} meghagyja a telepített Kirinek.", + "Linking…": "Csatolás…", + "Use {app}": "{app} használata", + "Free": "Szabad", + "Docker socket": "Docker socket", + "The {docker} command uses {app}.": "A(z) {docker} parancs a(z) {app} motort használja.", + "{env} is set in this session, so {docker} uses another engine.": "A(z) {env} be van állítva ebben a munkamenetben, így a(z) {docker} másik motort használ.", + "The {docker} command uses {engine}.": "A(z) {docker} parancs a(z) {engine} motort használja.", + "Switching…": "Váltás…", + "{docker} command": "{docker} parancs", + "/var/run/docker.sock now points to Kiri": "A /var/run/docker.sock mostantól a Kirire mutat", + "Could not link /var/run/docker.sock: {error}": "Nem sikerült csatolni a /var/run/docker.sock útvonalat: {error}" } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 0f53c1068..e13d345d0 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Mulai Kiri saat masuk", "Start Kiri in the background when you sign in.": "Mulai Kiri di latar belakang saat Anda masuk.", "Stop the engine when Kiri quits": "Hentikan engine saat keluar dari Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Keluar dari Kiri menghentikan kontainer yang berjalan dan engine. Membuka Kiri akan memulainya lagi." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Keluar dari Kiri menghentikan kontainer yang berjalan dan engine. Membuka Kiri akan memulainya lagi.", + "{env} is set, so docker uses another engine instead of {app}": "{env} disetel, sehingga docker memakai mesin lain alih-alih {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} disetel, sehingga {docker} memakai mesin lain alih-alih {app}. Hapus variabel ini di shell Anda untuk memakai {app}.", + "{env} is set": "{env} disetel", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} menimpa konteks docker di sesi ini, jadi mengganti konteks tidak akan mengarahkan {docker} ke {app}. Bersihkan dengan {cmd} atau hapus dari profil Anda.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} mengarah ke {app}. Alat seperti Testcontainers, plugin IDE, dan SDK langsung memakainya.", + "another engine": "mesin lain", + "{path} belongs to {engine} and stays so.": "{path} milik {engine} dan dibiarkan demikian.", + "Tools that ignore docker contexts can use {hint}": "Alat yang mengabaikan konteks docker dapat memakai {hint}", + "command": "perintah", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} kosong. Tautkan ke {app} agar alat yang mengabaikan konteks docker menemukan {app} di sana.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} kosong. {app} melayaninya setiap kali berjalan dan tidak ada mesin Docker lain.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} kosong. {service} menautkannya saat Kiri mulai selama tidak dipakai mesin Docker lain.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} kosong. {app} membiarkannya untuk Kiri yang terpasang.", + "Linking…": "Menautkan…", + "Use {app}": "Pakai {app}", + "Free": "Kosong", + "Docker socket": "Soket Docker", + "The {docker} command uses {app}.": "Perintah {docker} memakai {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} disetel di sesi ini, sehingga {docker} memakai mesin lain.", + "The {docker} command uses {engine}.": "Perintah {docker} memakai {engine}.", + "Switching…": "Mengalihkan…", + "{docker} command": "Perintah {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock kini mengarah ke Kiri", + "Could not link /var/run/docker.sock: {error}": "Tidak dapat menautkan /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 7c6901fd9..857cbc78b 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Avvia Kiri all'accesso", "Start Kiri in the background when you sign in.": "Avvia Kiri in background quando accedi.", "Stop the engine when Kiri quits": "Ferma il motore quando esci da Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Uscendo da Kiri si fermano i container in esecuzione e il motore. Aprendo Kiri si avvia di nuovo." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Uscendo da Kiri si fermano i container in esecuzione e il motore. Aprendo Kiri si avvia di nuovo.", + "{env} is set, so docker uses another engine instead of {app}": "{env} è impostata, quindi docker usa un altro motore anziché {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} è impostata, quindi {docker} usa un altro motore anziché {app}. Rimuovila dalla shell per usare {app}.", + "{env} is set": "{env} è impostata", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} prevale sul contesto di docker in questa sessione, quindi cambiare contesto non sposterà {docker} su {app}. Azzerarla con {cmd} o rimuoverla dal profilo.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} punta a {app}. Strumenti come Testcontainers, plugin IDE e SDK lo usano direttamente.", + "another engine": "un altro motore", + "{path} belongs to {engine} and stays so.": "{path} appartiene a {engine} e rimane tale.", + "Tools that ignore docker contexts can use {hint}": "Gli strumenti che ignorano i contesti docker possono usare {hint}", + "command": "comando", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} è libero. Collegalo a {app} affinché gli strumenti che ignorano i contesti docker trovino {app} lì.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} è libero. {app} lo serve ogni volta che è in esecuzione e nessun altro motore Docker lo usa.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} è libero. {service} lo collega all’avvio di Kiri finché nessun altro motore Docker lo occupa.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} è libero. {app} lo lascia al Kiri installato.", + "Linking…": "Collegamento…", + "Use {app}": "Usa {app}", + "Free": "Libero", + "Docker socket": "Socket Docker", + "The {docker} command uses {app}.": "Il comando {docker} usa {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} è impostata in questa sessione, quindi {docker} usa un altro motore.", + "The {docker} command uses {engine}.": "Il comando {docker} usa {engine}.", + "Switching…": "Cambio…", + "{docker} command": "Comando {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ora punta a Kiri", + "Could not link /var/run/docker.sock: {error}": "Impossibile collegare /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index 1d6e14530..bef9f00cb 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "サインイン時に Kiri を起動", "Start Kiri in the background when you sign in.": "サインインしたときにバックグラウンドで Kiri を起動します。", "Stop the engine when Kiri quits": "Kiri の終了時にエンジンを停止", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri を終了すると、実行中のコンテナとエンジンが停止します。Kiri を開くと再び起動します。" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri を終了すると、実行中のコンテナとエンジンが停止します。Kiri を開くと再び起動します。", + "{env} is set, so docker uses another engine instead of {app}": "{env} が設定されているため、docker は {app} ではなく別のエンジンを使用しています", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} が設定されているため、{docker} は {app} ではなく別のエンジンを使用しています。{app} を使うにはシェルから解除してください。", + "{env} is set": "{env} が設定されています", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "このセッションでは {env} が docker のコンテキストを上書きしているため、コンテキストを切り替えても {docker} は {app} に向きません。{cmd} で解除するかプロファイルから削除してください。", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} は {app} に接続されています。Testcontainers、IDE プラグイン、SDK などのツールが直接使用します。", + "another engine": "別のエンジン", + "{path} belongs to {engine} and stays so.": "{path} は {engine} が使用中のためそのままにされます。", + "Tools that ignore docker contexts can use {hint}": "docker コンテキストを無視するツールでは {hint} を使用できます", + "command": "コマンド", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} は空いています。docker コンテキストを無視するツールが {app} を見つけられるよう {app} にリンクします。", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} は空いています。他の Docker エンジンが動作していない限り、{app} の起動中に提供されます。", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} は空いています。他の Docker エンジンが使用していない間、Kiri 起動時に {service} がリンクします。", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} は空いています。{app} はインストール済みの Kiri のためにそのままにします。", + "Linking…": "リンク中…", + "Use {app}": "{app} を使用", + "Free": "空き", + "Docker socket": "Docker ソケット", + "The {docker} command uses {app}.": "{docker} コマンドは {app} を使用しています。", + "{env} is set in this session, so {docker} uses another engine.": "このセッションでは {env} が設定されているため、{docker} は別のエンジンを使用しています。", + "The {docker} command uses {engine}.": "{docker} コマンドは {engine} を使用しています。", + "Switching…": "切り替え中…", + "{docker} command": "{docker} コマンド", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock が Kiri を指すようになりました", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock をリンクできませんでした: {error}" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 11c7510c3..3416e8519 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Жүйеге кіргенде Kiri-ді іске қосу", "Start Kiri in the background when you sign in.": "Жүйеге кірген кезде Kiri-ді фонда іске қосады.", "Stop the engine when Kiri quits": "Kiri-ден шыққанда қозғалтқышты тоқтату", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ден шығу жұмыс істеп тұрған контейнерлер мен қозғалтқышты тоқтатады. Kiri-ді ашу оны қайта іске қосады." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ден шығу жұмыс істеп тұрған контейнерлер мен қозғалтқышты тоқтатады. Kiri-ді ашу оны қайта іске қосады.", + "{env} is set, so docker uses another engine instead of {app}": "{env} орнатылған, сондықтан docker {app} орнына басқа қозғалтқышты пайдаланады", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} орнатылған, сондықтан {docker} {app} орнына басқа қозғалтқышты пайдаланады. {app} қолдану үшін оны қабықшадан алып тастаңыз.", + "{env} is set": "{env} орнатылған", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} осы сеанста docker контексін қайта анықтайды, сондықтан контекстті ауыстыру {docker} командасын {app}-ға бағыттамайды. Оны {cmd} арқылы тазалаңыз немесе профиліңізден өшіріңіз.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} тікелей {app}-ға апарады. Testcontainers, IDE плагиндері және SDK сияқты құралдар оны тікелей пайдаланады.", + "another engine": "басқа қозғалтқыш", + "{path} belongs to {engine} and stays so.": "{path} {engine} иелігінде және солай қалады.", + "Tools that ignore docker contexts can use {hint}": "docker контексттерін елемейтін құралдар {hint} мәнін қолдана алады", + "command": "команда", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} бос. docker контексттерін елемейтін құралдар {app}-ды сол жерден табуы үшін оны {app}-ға байланыстырыңыз.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} бос. Басқа Docker қозғалтқышы болмаған кезде {app} іске қосылған сайын оған қызмет көрсетеді.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} бос. Басқа Docker қозғалтқышы алмаса, Kiri іске қосылғанда {service} оны байланыстырады.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} бос. {app} оны орнатылған Kiri-ге қалдырады.", + "Linking…": "Байланыстырылуда…", + "Use {app}": "{app} қолдану", + "Free": "Бос", + "Docker socket": "Docker сокеті", + "The {docker} command uses {app}.": "{docker} командасы {app} қолданады.", + "{env} is set in this session, so {docker} uses another engine.": "Бұл сеанста {env} орнатылған, сондықтан {docker} басқа қозғалтқышты пайдаланады.", + "The {docker} command uses {engine}.": "{docker} командасы {engine} қолданады.", + "Switching…": "Ауыстырылуда…", + "{docker} command": "{docker} командасы", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock енді Kiri-ге бағытталған", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock байланыстырылмады: {error}" } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 880c6e362..669f8a477 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "로그인할 때 Kiri 시작", "Start Kiri in the background when you sign in.": "로그인할 때 백그라운드에서 Kiri를 시작합니다.", "Stop the engine when Kiri quits": "Kiri를 종료할 때 엔진 중지", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri를 종료하면 실행 중인 컨테이너와 엔진이 중지됩니다. Kiri를 열면 다시 시작됩니다." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri를 종료하면 실행 중인 컨테이너와 엔진이 중지됩니다. Kiri를 열면 다시 시작됩니다.", + "{env} is set, so docker uses another engine instead of {app}": "{env}이(가) 설정되어 있어 docker가 {app} 대신 다른 엔진을 사용합니다", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env}이(가) 설정되어 있어 {docker}가 {app} 대신 다른 엔진을 사용합니다. {app}을(를) 사용하려면 셸에서 해제하세요.", + "{env} is set": "{env}이(가) 설정되어 있음", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "이 세션에서 {env}이(가) docker 컨텍스트를 재정의하므로 컨텍스트를 전환해도 {docker}가 {app}을(를) 사용하지 않습니다. {cmd}로 지우거나 프로필에서 제거하세요.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path}이(가) {app}에 연결되어 있습니다. Testcontainers, IDE 플러그인, SDK 같은 도구가 직접 사용합니다.", + "another engine": "다른 엔진", + "{path} belongs to {engine} and stays so.": "{path}은(는) {engine} 소유이며 그대로 유지됩니다.", + "Tools that ignore docker contexts can use {hint}": "docker 컨텍스트를 무시하는 도구는 {hint}을(를) 사용할 수 있습니다", + "command": "명령", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path}이(가) 비어 있습니다. docker 컨텍스트를 무시하는 도구가 거기서 {app}을(를) 찾을 수 있도록 {app}에 연결하세요.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path}이(가) 비어 있습니다. 다른 Docker 엔진이 없을 때 {app}이(가) 실행되면 자동으로 제공합니다.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path}이(가) 비어 있습니다. 다른 Docker 엔진이 점유하지 않으면 Kiri 시작 시 {service}가 연결합니다.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path}이(가) 비어 있습니다. {app}은(는) 설치된 Kiri를 위해 비워 둡니다.", + "Linking…": "연결 중…", + "Use {app}": "{app} 사용", + "Free": "사용 가능", + "Docker socket": "Docker 소켓", + "The {docker} command uses {app}.": "{docker} 명령이 {app}을(를) 사용합니다.", + "{env} is set in this session, so {docker} uses another engine.": "이 세션에 {env}이(가) 설정되어 있어 {docker}가 다른 엔진을 사용합니다.", + "The {docker} command uses {engine}.": "{docker} 명령이 {engine}을(를) 사용합니다.", + "Switching…": "전환 중…", + "{docker} command": "{docker} 명령", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock이(가) 이제 Kiri를 가리킵니다", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock을(를) 연결하지 못했습니다: {error}" } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 55671f8d5..7f7f8bd17 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "ເລີ່ມ Kiri ເມື່ອເຂົ້າສູ່ລະບົບ", "Start Kiri in the background when you sign in.": "ເລີ່ມ Kiri ໃນພື້ນຫຼັງເມື່ອທ່ານເຂົ້າສູ່ລະບົບ.", "Stop the engine when Kiri quits": "ຢຸດເອນຈິນເມື່ອອອກຈາກ Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ການອອກຈາກ Kiri ຈະຢຸດຄອນເທນເນີທີ່ແລ່ນຢູ່ ແລະ ເອນຈິນ. ການເປີດ Kiri ຈະເລີ່ມມັນໃໝ່." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "ການອອກຈາກ Kiri ຈະຢຸດຄອນເທນເນີທີ່ແລ່ນຢູ່ ແລະ ເອນຈິນ. ການເປີດ Kiri ຈະເລີ່ມມັນໃໝ່.", + "{env} is set, so docker uses another engine instead of {app}": "ຕັ້ງຄ່າ {env} ໄວ້ແລ້ວ, ດັ່ງນັ້ນ docker ຈຶ່ງໃຊ້ເຄື່ອງຈັກອື່ນແທນ {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "ຕັ້ງຄ່າ {env} ໄວ້ແລ້ວ, ດັ່ງນັ້ນ {docker} ຈຶ່ງໃຊ້ເຄື່ອງຈັກອື່ນແທນ {app}. ຍົກເລີກມັນໃນ shell ຂອງທ່ານເພື່ອໃຊ້ {app}.", + "{env} is set": "ຕັ້ງຄ່າ {env} ໄວ້ແລ້ວ", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} ແທນທີ່ບໍລິບົດຂອງ docker ໃນເຊສຊັນນີ້, ສະນັ້ນການປ່ຽນບໍລິບົດຈະບໍ່ຍ້າຍ {docker} ໄປ {app}. ລ້າງດ້ວຍ {cmd} ຫຼືເອົາອອກຈາກໂປຣໄຟລ໌ຂອງທ່ານ.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} ນຳໄປສູ່ {app}. ເຄື່ອງມືເຊັ່ນ Testcontainers, ປລັກອິນ IDE ແລະ SDK ໃຊ້ມັນໂດຍກົງ.", + "another engine": "ເຄື່ອງຈັກອື່ນ", + "{path} belongs to {engine} and stays so.": "{path} ເປັນຂອງ {engine} ແລະຍັງຄົງເປັນແບບນັ້ນ.", + "Tools that ignore docker contexts can use {hint}": "ເຄື່ອງມືທີ່ບໍ່ສົນໃຈບໍລິບົດ docker ສາມາດໃຊ້ {hint} ໄດ້", + "command": "ຄຳສັ່ງ", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ວ່າງຢູ່. ເຊື່ອມຕໍ່ກັບ {app} ເພື່ອໃຫ້ເຄື່ອງມືທີ່ບໍ່ສົນໃຈບໍລິບົດ docker ພົບ {app} ຢູ່ທີ່ນັ້ນ.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ວ່າງຢູ່. {app} ໃຫ້ບໍລິການມັນເມື່ອເຮັດວຽກ ແລະບໍ່ມີເຄື່ອງຈັກ Docker ອື່ນໃຊ້.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ວ່າງຢູ່. {service} ເຊື່ອມຕໍ່ມັນເມື່ອ Kiri ເລີ່ມຕົ້ນຫາກບໍ່ມີເຄື່ອງຈັກ Docker ອື່ນຄອບຄອງ.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ວ່າງຢູ່. {app} ປະມັນໄວ້ໃຫ້ Kiri ທີ່ຕິດຕັ້ງແລ້ວ.", + "Linking…": "ກຳລັງເຊື່ອມຕໍ່…", + "Use {app}": "ໃຊ້ {app}", + "Free": "ວ່າງ", + "Docker socket": "ຊັອກເກັດ Docker", + "The {docker} command uses {app}.": "ຄຳສັ່ງ {docker} ໃຊ້ {app}.", + "{env} is set in this session, so {docker} uses another engine.": "ຕັ້ງຄ່າ {env} ໃນເຊສຊັນນີ້, ສະນັ້ນ {docker} ໃຊ້ເຄື່ອງຈັກອື່ນ.", + "The {docker} command uses {engine}.": "ຄຳສັ່ງ {docker} ໃຊ້ {engine}.", + "Switching…": "ກຳລັງປ່ຽນ…", + "{docker} command": "ຄຳສັ່ງ {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ຊີ້ໄປທີ່ Kiri ແລ້ວ", + "Could not link /var/run/docker.sock: {error}": "ບໍ່ສາມາດເຊື່ອມຕໍ່ /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index a5ccc677c..580039bf0 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Paleisti Kiri prisijungus", "Start Kiri in the background when you sign in.": "Paleisti Kiri fone, kai prisijungiate.", "Stop the engine when Kiri quits": "Sustabdyti variklį išėjus iš Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Išėjus iš Kiri sustabdomi veikiantys konteineriai ir variklis. Atidarius Kiri jis paleidžiamas vėl." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Išėjus iš Kiri sustabdomi veikiantys konteineriai ir variklis. Atidarius Kiri jis paleidžiamas vėl.", + "{env} is set, so docker uses another engine instead of {app}": "{env} yra nustatytas, todėl docker vietoj {app} naudoja kitą variklį", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} yra nustatytas, todėl {docker} vietoj {app} naudoja kitą variklį. Pašalinkite jį savo apvalkale, kad galėtumėte naudoti {app}.", + "{env} is set": "{env} yra nustatytas", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} šioje sesijoje pakeičia docker kontekstą, todėl konteksto perjungimas nenukreips {docker} į {app}. Išvalykite komanda {cmd} arba pašalinkite iš profilio.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} veda į {app}. Tokie įrankiai kaip Testcontainers, IDE įskiepiai ir SDK jį naudoja tiesiogiai.", + "another engine": "kitas variklis", + "{path} belongs to {engine} and stays so.": "{path} priklauso {engine} ir lieka jam.", + "Tools that ignore docker contexts can use {hint}": "Įrankiai, ignoruojantys docker kontekstus, gali naudoti {hint}", + "command": "komanda", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} yra laisvas. Susiekite jį su {app}, kad docker kontekstų nepaisantys įrankiai rastų {app} ten.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} yra laisvas. {app} jį aptarnauja kaskart veikdamas, kai nėra kito Docker variklio.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} yra laisvas. {service} jį susieja paleidus Kiri, kol jo neužėmė kitas Docker variklis.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} yra laisvas. {app} palieka jį įdiegtam Kiri.", + "Linking…": "Susiejama…", + "Use {app}": "Naudoti {app}", + "Free": "Laisvas", + "Docker socket": "Docker lizdas", + "The {docker} command uses {app}.": "Komanda {docker} naudoja {app}.", + "{env} is set in this session, so {docker} uses another engine.": "Šioje sesijoje nustatytas {env}, todėl {docker} naudoja kitą variklį.", + "The {docker} command uses {engine}.": "Komanda {docker} naudoja {engine}.", + "Switching…": "Perjungiama…", + "{docker} command": "{docker} komanda", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock dabar rodo į Kiri", + "Could not link /var/run/docker.sock: {error}": "Nepavyko susieti /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 686ad92be..5240843af 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Start Kiri ved pålogging", "Start Kiri in the background when you sign in.": "Start Kiri i bakgrunnen når du logger inn.", "Stop the engine when Kiri quits": "Stopp motoren når Kiri avsluttes", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Å avslutte Kiri stopper kjørende containere og motoren. Å åpne Kiri starter den igjen." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Å avslutte Kiri stopper kjørende containere og motoren. Å åpne Kiri starter den igjen.", + "{env} is set, so docker uses another engine instead of {app}": "{env} er satt, så docker bruker en annen motor i stedet for {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} er satt, så {docker} bruker en annen motor i stedet for {app}. Fjern den i skallet ditt for å bruke {app}.", + "{env} is set": "{env} er satt", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} overstyrer dockers kontekst i denne økten, så å bytte kontekst flytter ikke {docker} til {app}. Tøm den med {cmd} eller fjern den fra profilen din.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} peker til {app}. Verktøy som Testcontainers, IDE-utvidelser og SDK-er bruker den direkte.", + "another engine": "en annen motor", + "{path} belongs to {engine} and stays so.": "{path} tilhører {engine} og forblir slik.", + "Tools that ignore docker contexts can use {hint}": "Verktøy som ignorerer docker-kontekster kan bruke {hint}", + "command": "kommando", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} er ledig. Lenk den til {app} så verktøy som ignorerer docker-kontekster finner {app} der.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} er ledig. {app} betjener den når den kjører og ingen annen Docker-motor gjør det.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} er ledig. {service} lenker den når Kiri starter så lenge ingen annen Docker-motor har den.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} er ledig. {app} lar den stå til den installerte Kiri.", + "Linking…": "Lenker…", + "Use {app}": "Bruk {app}", + "Free": "Ledig", + "Docker socket": "Docker-socket", + "The {docker} command uses {app}.": "Kommandoen {docker} bruker {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} er satt i denne økten, så {docker} bruker en annen motor.", + "The {docker} command uses {engine}.": "Kommandoen {docker} bruker {engine}.", + "Switching…": "Bytter…", + "{docker} command": "{docker}-kommando", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock peker nå til Kiri", + "Could not link /var/run/docker.sock: {error}": "Kunne ikke lenke /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index f59620f17..ae0936d44 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Uruchamiaj Kiri po zalogowaniu", "Start Kiri in the background when you sign in.": "Uruchamia Kiri w tle po zalogowaniu.", "Stop the engine when Kiri quits": "Zatrzymuj silnik po zakończeniu Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Zakończenie Kiri zatrzymuje działające kontenery i silnik. Otwarcie Kiri uruchamia go ponownie." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Zakończenie Kiri zatrzymuje działające kontenery i silnik. Otwarcie Kiri uruchamia go ponownie.", + "{env} is set, so docker uses another engine instead of {app}": "Zmienna {env} jest ustawiona, więc docker używa innego silnika zamiast {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Zmienna {env} jest ustawiona, więc {docker} używa innego silnika zamiast {app}. Usuń ją w powłoce, aby używać {app}.", + "{env} is set": "Zmienna {env} jest ustawiona", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "Zmienna {env} przesłania kontekst dockera w tej sesji, więc zmiana kontekstu nie przełączy {docker} na {app}. Wyczyść ją poleceniem {cmd} lub usuń z profilu.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} prowadzi do {app}. Narzędzia takie jak Testcontainers, wtyczki IDE i SDK korzystają z niego bezpośrednio.", + "another engine": "innego silnika", + "{path} belongs to {engine} and stays so.": "{path} należy do {engine} i tak pozostaje.", + "Tools that ignore docker contexts can use {hint}": "Narzędzia ignorujące konteksty dockera mogą użyć {hint}", + "command": "polecenie", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} jest wolne. Dowiąż do {app}, aby narzędzia ignorujące konteksty dockera znalazły tam {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} jest wolne. {app} obsługuje je, gdy działa i nie robi tego żaden inny silnik Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} jest wolne. {service} dowiązuje je przy starcie Kiri, gdy żaden inny silnik Docker go nie zajmuje.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} jest wolne. {app} zostawia je zainstalowanej Kiri.", + "Linking…": "Łączenie…", + "Use {app}": "Użyj {app}", + "Free": "Wolne", + "Docker socket": "Gniazdo Docker", + "The {docker} command uses {app}.": "Polecenie {docker} używa {app}.", + "{env} is set in this session, so {docker} uses another engine.": "W tej sesji ustawiono {env}, więc {docker} używa innego silnika.", + "The {docker} command uses {engine}.": "Polecenie {docker} używa {engine}.", + "Switching…": "Przełączanie…", + "{docker} command": "Polecenie {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock wskazuje teraz na Kiri", + "Could not link /var/run/docker.sock: {error}": "Nie udało się dowiązać /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index c8a1b5c3d..3eca0f4ef 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Iniciar o Kiri ao entrar", "Start Kiri in the background when you sign in.": "Inicia o Kiri em segundo plano quando você entra.", "Stop the engine when Kiri quits": "Parar o engine ao sair do Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Sair do Kiri para os contêineres rodando e o engine. Abrir o Kiri o inicia de novo." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Sair do Kiri para os contêineres rodando e o engine. Abrir o Kiri o inicia de novo.", + "{env} is set, so docker uses another engine instead of {app}": "{env} está definida, então o docker usa outro mecanismo em vez do {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} está definida, então o {docker} usa outro mecanismo em vez do {app}. Remova-a do seu shell para usar o {app}.", + "{env} is set": "{env} está definida", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} sobrescreve o contexto do docker nesta sessão, então trocar o contexto não moverá o {docker} para o {app}. Limpe com {cmd} ou remova do seu perfil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} leva ao {app}. Ferramentas como Testcontainers, plugins de IDE e SDKs usam diretamente.", + "another engine": "outro mecanismo", + "{path} belongs to {engine} and stays so.": "{path} pertence ao {engine} e assim permanece.", + "Tools that ignore docker contexts can use {hint}": "Ferramentas que ignoram contextos do docker podem usar {hint}", + "command": "comando", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} está livre. Vincule-o ao {app} para que ferramentas que ignoram contextos do docker encontrem o {app} lá.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} está livre. O {app} atende sempre que está em execução e nenhum outro mecanismo Docker está.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} está livre. O {service} vincula ao iniciar o Kiri enquanto nenhum outro mecanismo Docker o utiliza.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} está livre. O {app} deixa para o Kiri instalado.", + "Linking…": "Vinculando…", + "Use {app}": "Usar {app}", + "Free": "Livre", + "Docker socket": "Socket do Docker", + "The {docker} command uses {app}.": "O comando {docker} usa o {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} está definida nesta sessão, então o {docker} usa outro mecanismo.", + "The {docker} command uses {engine}.": "O comando {docker} usa o {engine}.", + "Switching…": "Alternando…", + "{docker} command": "Comando {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock agora aponta para o Kiri", + "Could not link /var/run/docker.sock: {error}": "Não foi possível vincular /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index 5c51cb2af..c8edf1707 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Pornește Kiri la conectare", "Start Kiri in the background when you sign in.": "Pornește Kiri în fundal când te conectezi.", "Stop the engine when Kiri quits": "Oprește motorul la ieșirea din Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ieșirea din Kiri oprește containerele care rulează și motorul. Deschiderea Kiri îl pornește din nou." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ieșirea din Kiri oprește containerele care rulează și motorul. Deschiderea Kiri îl pornește din nou.", + "{env} is set, so docker uses another engine instead of {app}": "{env} este setată, astfel că docker folosește alt motor în locul lui {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} este setată, astfel că {docker} folosește alt motor în locul lui {app}. Eliminați-o din shell pentru a folosi {app}.", + "{env} is set": "{env} este setată", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} suprascrie contextul docker în această sesiune, deci schimbarea contextului nu va muta {docker} la {app}. Ștergeți-o cu {cmd} sau eliminați-o din profil.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} duce la {app}. Instrumente precum Testcontainers, extensiile IDE și SDK-urile îl folosesc direct.", + "another engine": "alt motor", + "{path} belongs to {engine} and stays so.": "{path} aparține de {engine} și rămâne așa.", + "Tools that ignore docker contexts can use {hint}": "Instrumentele care ignoră contextele docker pot folosi {hint}", + "command": "comandă", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} este liber. Asociați-l cu {app} ca instrumentele ce ignoră contextele docker să găsească {app} acolo.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} este liber. {app} îl deservește ori de câte ori rulează fără alt motor Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} este liber. {service} îl leagă la pornirea Kiri când niciun alt motor Docker nu îl ocupă.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} este liber. {app} îl lasă pentru Kiri instalat.", + "Linking…": "Se leagă…", + "Use {app}": "Folosește {app}", + "Free": "Liber", + "Docker socket": "Socket Docker", + "The {docker} command uses {app}.": "Comanda {docker} folosește {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} este setată în această sesiune, deci {docker} folosește alt motor.", + "The {docker} command uses {engine}.": "Comanda {docker} folosește {engine}.", + "Switching…": "Se comută…", + "{docker} command": "Comanda {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock indică acum spre Kiri", + "Could not link /var/run/docker.sock: {error}": "Nu s-a putut lega /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index de175d80c..091cb47a3 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Запускать Kiri при входе в систему", "Start Kiri in the background when you sign in.": "Запускать Kiri в фоновом режиме при входе в систему.", "Stop the engine when Kiri quits": "Останавливать движок при выходе из Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Выход из Kiri останавливает запущенные контейнеры и движок. Открытие Kiri запускает его снова." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Выход из Kiri останавливает запущенные контейнеры и движок. Открытие Kiri запускает его снова.", + "{env} is set, so docker uses another engine instead of {app}": "Переменная {env} задана, поэтому docker использует другой движок вместо {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Переменная {env} задана, поэтому {docker} использует другой движок вместо {app}. Сбросьте её в оболочке, чтобы использовать {app}.", + "{env} is set": "Переменная {env} задана", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} переопределяет контекст docker в этом сеансе, поэтому переключение контекста не направит {docker} на {app}. Очистите её командой {cmd} или удалите из профиля.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} ведёт к {app}. Такие инструменты, как Testcontainers, плагины IDE и SDK, используют его напрямую.", + "another engine": "другой движок", + "{path} belongs to {engine} and stays so.": "{path} принадлежит {engine} и остаётся у него.", + "Tools that ignore docker contexts can use {hint}": "Инструменты, игнорирующие контексты docker, могут использовать {hint}", + "command": "команду", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} свободен. Свяжите его с {app}, чтобы инструменты, игнорирующие контексты docker, находили там {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} свободен. {app} обслуживает его всякий раз при работе, если не запущен другой движок Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} свободен. {service} связывает его при запуске Kiri, пока его не занял другой движок Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} свободен. {app} оставляет его для установленного Kiri.", + "Linking…": "Связывание…", + "Use {app}": "Использовать {app}", + "Free": "Свободен", + "Docker socket": "Сокет Docker", + "The {docker} command uses {app}.": "Команда {docker} использует {app}.", + "{env} is set in this session, so {docker} uses another engine.": "В этом сеансе задана {env}, поэтому {docker} использует другой движок.", + "The {docker} command uses {engine}.": "Команда {docker} использует {engine}.", + "Switching…": "Переключение…", + "{docker} command": "Команда {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock теперь указывает на Kiri", + "Could not link /var/run/docker.sock: {error}": "Не удалось связать /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index ce64946a5..a014e9425 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Zaženi Kiri ob prijavi", "Start Kiri in the background when you sign in.": "Zažene Kiri v ozadju, ko se prijavite.", "Stop the engine when Kiri quits": "Ustavi pogon, ko zaprete Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ko zaprete Kiri, se ustavijo kontejnerji, ki tečejo, in pogon. Ko odprete Kiri, se znova zažene." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Ko zaprete Kiri, se ustavijo kontejnerji, ki tečejo, in pogon. Ko odprete Kiri, se znova zažene.", + "{env} is set, so docker uses another engine instead of {app}": "Spremenljivka {env} je nastavljena, zato docker namesto {app} uporablja drug pogon", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Spremenljivka {env} je nastavljena, zato {docker} namesto {app} uporablja drug pogon. Odstranite jo v lupini za uporabo {app}.", + "{env} is set": "Spremenljivka {env} je nastavljena", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} v tej seji preglasi kontekst dockerja, zato preklop konteksta ne bo usmeril {docker} na {app}. Počistite jo z {cmd} ali jo odstranite iz profila.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} vodi do {app}. Orodja, kot so Testcontainers, vtičniki IDE in SDK-ji, ga uporabljajo neposredno.", + "another engine": "drug pogon", + "{path} belongs to {engine} and stays so.": "{path} pripada {engine} in tako ostane.", + "Tools that ignore docker contexts can use {hint}": "Orodja, ki ne upoštevajo kontekstov docker, lahko uporabijo {hint}", + "command": "ukaz", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} je prost. Povežite ga z {app}, da bodo orodja brez podpore kontekstom tam našla {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} je prost. {app} ga streže, kadar koli teče in ni drugega pogona Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} je prost. {service} ga poveže ob zagonu Kiri, kadar ga ne zaseda drug pogon Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} je prost. {app} ga prepusti nameščenemu Kiri.", + "Linking…": "Povezovanje…", + "Use {app}": "Uporabi {app}", + "Free": "Prost", + "Docker socket": "Vtičnica Docker", + "The {docker} command uses {app}.": "Ukaz {docker} uporablja {app}.", + "{env} is set in this session, so {docker} uses another engine.": "V tej seji je nastavljena {env}, zato {docker} uporablja drug pogon.", + "The {docker} command uses {engine}.": "Ukaz {docker} uporablja {engine}.", + "Switching…": "Preklapljanje…", + "{docker} command": "Ukaz {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock zdaj kaže na Kiri", + "Could not link /var/run/docker.sock: {error}": "Povezave /var/run/docker.sock ni bilo mogoče ustvariti: {error}" } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 73e4c2077..268312399 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Nis Kiri gjatë identifikimit", "Start Kiri in the background when you sign in.": "Nis Kiri në sfond kur identifikoheni.", "Stop the engine when Kiri quits": "Ndal motorin kur dilni nga Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Dalja nga Kiri ndal kontejnerët në punë dhe motorin. Hapja e Kiri e nis sërish." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Dalja nga Kiri ndal kontejnerët në punë dhe motorin. Hapja e Kiri e nis sërish.", + "{env} is set, so docker uses another engine instead of {app}": "{env} është caktuar, ndaj docker përdor një motor tjetër në vend të {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} është caktuar, ndaj {docker} përdor një motor tjetër në vend të {app}. Hiqeni në shell për të përdorur {app}.", + "{env} is set": "{env} është caktuar", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} mbishkruan kontekstin e docker-it në këtë sesion, ndaj ndërrimi i kontekstit nuk e kalon {docker} te {app}. Pastrojeni me {cmd} ose hiqeni nga profili juaj.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} çon te {app}. Mjete si Testcontainers, shtojcat IDE dhe SDK-të e përdorin drejtpërdrejt.", + "another engine": "një motor tjetër", + "{path} belongs to {engine} and stays so.": "{path} i përket {engine} dhe mbetet ashtu.", + "Tools that ignore docker contexts can use {hint}": "Mjetet që shpërfillin kontekstet e docker-it mund të përdorin {hint}", + "command": "komandë", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} është i lirë. Lidheni me {app} që mjetet që shpërfillin kontekstet e docker-it ta gjejnë {app} aty.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} është i lirë. {app} e shërben sa herë punon dhe s’ka motor tjetër Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} është i lirë. {service} e lidh kur niset Kiri kur s’e mban ndonjë motor tjetër Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} është i lirë. {app} ia lë Kiri-t të instaluar.", + "Linking…": "Duke lidhur…", + "Use {app}": "Përdor {app}", + "Free": "I lirë", + "Docker socket": "Soketi i Docker-it", + "The {docker} command uses {app}.": "Komanda {docker} përdor {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} është caktuar në këtë sesion, ndaj {docker} përdor një motor tjetër.", + "The {docker} command uses {engine}.": "Komanda {docker} përdor {engine}.", + "Switching…": "Duke ndërruar…", + "{docker} command": "Komanda {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock tani tregon te Kiri", + "Could not link /var/run/docker.sock: {error}": "Nuk u lidh dot /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index e75f7789a..f50e3e8c1 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "உள்நுழையும்போது Kiri-ஐத் தொடங்கு", "Start Kiri in the background when you sign in.": "நீங்கள் உள்நுழையும்போது பின்னணியில் Kiri-ஐத் தொடங்கும்.", "Stop the engine when Kiri quits": "Kiri-ஐ மூடும்போது இன்ஜினை நிறுத்து", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ஐ மூடினால் இயங்கும் கன்டெய்னர்களும் இன்ஜினும் நிற்கும். Kiri-ஐத் திறந்தால் மீண்டும் தொடங்கும்." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ஐ மூடினால் இயங்கும் கன்டெய்னர்களும் இன்ஜினும் நிற்கும். Kiri-ஐத் திறந்தால் மீண்டும் தொடங்கும்.", + "{env} is set, so docker uses another engine instead of {app}": "{env} அமைக்கப்பட்டுள்ளது, எனவே docker {app} க்குப் பதிலாக வேறொரு இயந்திரத்தைப் பயன்படுத்துகிறது", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} அமைக்கப்பட்டுள்ளது, எனவே {docker} {app} க்குப் பதிலாக வேறொரு இயந்திரத்தைப் பயன்படுத்துகிறது. {app} ஐப் பயன்படுத்த உங்கள் ஷெல்லில் அதை நீக்கவும்.", + "{env} is set": "{env} அமைக்கப்பட்டுள்ளது", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "இந்த அமர்வில் {env} docker சூழலை மேலெழுதுகிறது, எனவே சூழலை மாற்றினால் {docker} {app} க்கு மாறாது. {cmd} மூலம் அதை நீக்கவும் அல்லது உங்கள் சுயவிவரத்திலிருந்து அகற்றவும்.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} {app} க்குச் செல்கிறது. Testcontainers, IDE செருகுநிரல்கள் மற்றும் SDK போன்ற கருவிகள் இதை நேரடியாகப் பயன்படுத்துகின்றன.", + "another engine": "வேறொரு இயந்திரம்", + "{path} belongs to {engine} and stays so.": "{path} {engine} க்கு உரியது, அப்படியே இருக்கும்.", + "Tools that ignore docker contexts can use {hint}": "docker சூழல்களைப் புறக்கணிக்கும் கருவிகள் {hint} ஐப் பயன்படுத்தலாம்", + "command": "கட்டளை", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} காலியாக உள்ளது. docker சூழல்களைப் புறக்கணிக்கும் கருவிகள் அங்கே {app} ஐக் கண்டறிய அதை {app} உடன் இணைக்கவும்.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} காலியாக உள்ளது. வேறு எந்த Docker இயந்திரமும் இல்லாதபோது {app} இயங்கும்போதெல்லாம் இதை வழங்கும்.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} காலியாக உள்ளது. வேறு Docker இயந்திரம் வைத்திருக்காதபோது Kiri தொடங்கும்போது {service} இதை இணைக்கும்.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} காலியாக உள்ளது. நிறுவப்பட்ட Kiri க்காக {app} அதை விட்டுவிடுகிறது.", + "Linking…": "இணைக்கிறது…", + "Use {app}": "{app} ஐப் பயன்படுத்து", + "Free": "காலி", + "Docker socket": "Docker சாக்கெட்", + "The {docker} command uses {app}.": "{docker} கட்டளை {app} ஐப் பயன்படுத்துகிறது.", + "{env} is set in this session, so {docker} uses another engine.": "இந்த அமர்வில் {env} அமைக்கப்பட்டுள்ளதால் {docker} வேறொரு இயந்திரத்தைப் பயன்படுத்துகிறது.", + "The {docker} command uses {engine}.": "{docker} கட்டளை {engine} ஐப் பயன்படுத்துகிறது.", + "Switching…": "மாற்றுகிறது…", + "{docker} command": "{docker} கட்டளை", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock இப்போது Kiri ஐக் குறிக்கிறது", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ஐ இணைக்க முடியவில்லை: {error}" } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index dbeccdeb1..822d1f51a 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "సైన్ ఇన్ అయినప్పుడు Kiriని ప్రారంభించు", "Start Kiri in the background when you sign in.": "మీరు సైన్ ఇన్ అయినప్పుడు నేపథ్యంలో Kiriని ప్రారంభిస్తుంది.", "Stop the engine when Kiri quits": "Kiri నుండి నిష్క్రమించినప్పుడు ఇంజిన్‌ను ఆపు", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri నుండి నిష్క్రమిస్తే రన్ అవుతున్న కంటైనర్‌లు మరియు ఇంజిన్ ఆగిపోతాయి. Kiriని తెరిస్తే అది మళ్లీ ప్రారంభమవుతుంది." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri నుండి నిష్క్రమిస్తే రన్ అవుతున్న కంటైనర్‌లు మరియు ఇంజిన్ ఆగిపోతాయి. Kiriని తెరిస్తే అది మళ్లీ ప్రారంభమవుతుంది.", + "{env} is set, so docker uses another engine instead of {app}": "{env} సెట్ చేయబడింది, కాబట్టి docker {app} బదులుగా మరో ఇంజిన్‌ను ఉపయోగిస్తోంది", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} సెట్ చేయబడింది, కాబట్టి {docker} {app} బదులుగా మరో ఇంజిన్‌ను ఉపయోగిస్తోంది. {app} ఉపయోగించడానికి మీ షెల్‌లో దాన్ని తొలగించండి.", + "{env} is set": "{env} సెట్ చేయబడింది", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "ఈ సెషన్‌లో {env} docker కాంటెక్స్ట్‌ను ఓవర్‌రైడ్ చేస్తుంది, కాబట్టి కాంటెక్స్ట్ మార్చినా {docker} {app} కు మారదు. {cmd} తో క్లియర్ చేయండి లేదా మీ ప్రొఫైల్ నుండి తొలగించండి.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} {app} కు దారి తీస్తుంది. Testcontainers, IDE ప్లగ్‌ఇన్‌లు మరియు SDK ల వంటి సాధనాలు దీన్ని నేరుగా ఉపయోగిస్తాయి.", + "another engine": "మరో ఇంజిన్", + "{path} belongs to {engine} and stays so.": "{path} {engine} కు చెందినది మరియు అలాగే ఉంటుంది.", + "Tools that ignore docker contexts can use {hint}": "docker కాంటెక్స్ట్‌లను పట్టించుకోని సాధనాలు {hint} ను ఉపయోగించగలవు", + "command": "ఆదేశం", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ఖాళీగా ఉంది. docker కాంటెక్స్ట్‌లను పట్టించుకోని సాధనాలు అక్కడ {app} ను కనుగొనేలా దీన్ని {app} కు లింక్ చేయండి.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ఖాళీగా ఉంది. మరో Docker ఇంజిన్ లేనప్పుడు {app} నడుస్తున్న ప్రతిసారీ దీన్ని అందిస్తుంది.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ఖాళీగా ఉంది. మరో Docker ఇంజిన్ తీసుకోనప్పుడు Kiri ప్రారంభమైనప్పుడు {service} దీన్ని లింక్ చేస్తుంది.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ఖాళీగా ఉంది. ఇన్‌స్టాల్ చేసిన Kiri కోసం {app} దీన్ని వదిలేస్తుంది.", + "Linking…": "లింక్ అవుతోంది…", + "Use {app}": "{app} ఉపయోగించు", + "Free": "ఖాళీ", + "Docker socket": "Docker సాకెట్", + "The {docker} command uses {app}.": "{docker} ఆదేశం {app} ను ఉపయోగిస్తోంది.", + "{env} is set in this session, so {docker} uses another engine.": "ఈ సెషన్‌లో {env} సెట్ చేయబడింది, కాబట్టి {docker} మరో ఇంజిన్‌ను ఉపయోగిస్తోంది.", + "The {docker} command uses {engine}.": "{docker} ఆదేశం {engine} ను ఉపయోగిస్తోంది.", + "Switching…": "మారుతోంది…", + "{docker} command": "{docker} ఆదేశం", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ఇప్పుడు Kiri కు చూపుతోంది", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ను లింక్ చేయడం సాధ్యం కాలేదు: {error}" } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index a4c8becfe..9dd3e0551 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "เริ่ม Kiri เมื่อลงชื่อเข้าใช้", "Start Kiri in the background when you sign in.": "เริ่ม Kiri ในพื้นหลังเมื่อคุณลงชื่อเข้าใช้", "Stop the engine when Kiri quits": "หยุดเอนจินเมื่อออกจาก Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "การออกจาก Kiri จะหยุดคอนเทนเนอร์ที่ทำงานอยู่และเอนจิน การเปิด Kiri จะเริ่มเอนจินอีกครั้ง" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "การออกจาก Kiri จะหยุดคอนเทนเนอร์ที่ทำงานอยู่และเอนจิน การเปิด Kiri จะเริ่มเอนจินอีกครั้ง", + "{env} is set, so docker uses another engine instead of {app}": "ตั้งค่า {env} ไว้แล้ว ดังนั้น docker จึงใช้เอนจินอื่นแทน {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "ตั้งค่า {env} ไว้แล้ว ดังนั้น {docker} จึงใช้เอนจินอื่นแทน {app} ยกเลิกค่านี้ในเชลล์ของคุณเพื่อใช้ {app}", + "{env} is set": "ตั้งค่า {env} ไว้แล้ว", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} เขียนทับบริบทของ docker ในเซสชันนี้ ดังนั้นการสลับบริบทจะไม่ย้าย {docker} ไปที่ {app} ล้างด้วย {cmd} หรือนำออกจากโปรไฟล์ของคุณ", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} เชื่อมไปยัง {app} เครื่องมืออย่าง Testcontainers ปลั๊กอิน IDE และ SDK ใช้งานได้โดยตรง", + "another engine": "เอนจินอื่น", + "{path} belongs to {engine} and stays so.": "{path} เป็นของ {engine} และจะคงไว้ตามนั้น", + "Tools that ignore docker contexts can use {hint}": "เครื่องมือที่ไม่สนใจบริบท docker สามารถใช้ {hint} ได้", + "command": "คำสั่ง", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ว่างอยู่ ลิงก์ไปยัง {app} เพื่อให้เครื่องมือที่ไม่สนใจบริบท docker พบ {app} ที่นั่น", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ว่างอยู่ {app} จะให้บริการเมื่อทำงานอยู่และไม่มีเอนจิน Docker อื่นใช้งาน", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ว่างอยู่ {service} จะลิงก์ให้เมื่อ Kiri เริ่มทำงานหากไม่มีเอนจิน Docker อื่นใช้อยู่", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ว่างอยู่ {app} เว้นไว้ให้ Kiri ที่ติดตั้งไว้", + "Linking…": "กำลังลิงก์…", + "Use {app}": "ใช้ {app}", + "Free": "ว่าง", + "Docker socket": "ซ็อกเก็ต Docker", + "The {docker} command uses {app}.": "คำสั่ง {docker} ใช้ {app}", + "{env} is set in this session, so {docker} uses another engine.": "ตั้งค่า {env} ในเซสชันนี้ไว้แล้ว ดังนั้น {docker} จึงใช้เอนจินอื่น", + "The {docker} command uses {engine}.": "คำสั่ง {docker} ใช้ {engine}", + "Switching…": "กำลังสลับ…", + "{docker} command": "คำสั่ง {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ชี้ไปที่ Kiri แล้ว", + "Could not link /var/run/docker.sock: {error}": "ไม่สามารถลิงก์ /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index 0243e356a..ed196364e 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Oturum açıldığında Kiri'yi başlat", "Start Kiri in the background when you sign in.": "Oturum açtığınızda Kiri'yi arka planda başlatır.", "Stop the engine when Kiri quits": "Kiri'den çıkıldığında motoru durdur", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri'den çıkmak çalışan kapsayıcıları ve motoru durdurur. Kiri'yi açmak onu yeniden başlatır." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri'den çıkmak çalışan kapsayıcıları ve motoru durdurur. Kiri'yi açmak onu yeniden başlatır.", + "{env} is set, so docker uses another engine instead of {app}": "{env} ayarlı olduğundan docker, {app} yerine başka bir motor kullanıyor", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} ayarlı olduğundan {docker}, {app} yerine başka bir motor kullanıyor. {app} kullanmak için kabuğunuzdan kaldırın.", + "{env} is set": "{env} ayarlı", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} bu oturumda docker bağlamını geçersiz kıldığı için bağlam değiştirmek {docker} komutunu {app} hedefine yönlendirmez. {cmd} ile temizleyin veya profilinizden kaldırın.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path}, {app} uygulamasına gider. Testcontainers, IDE eklentileri ve SDK’ler gibi araçlar doğrudan bunu kullanır.", + "another engine": "başka bir motor", + "{path} belongs to {engine} and stays so.": "{path}, {engine} motoruna aittir ve öyle kalır.", + "Tools that ignore docker contexts can use {hint}": "docker bağlamlarını yok sayan araçlar {hint} kullanabilir", + "command": "komut", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} boş. docker bağlamlarını yok sayan araçların {app} bulabilmesi için bunu {app} ile bağlayın.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} boş. Başka bir Docker motoru çalışmadığında {app} her çalıştığında sunar.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} boş. Başka bir Docker motoru kullanmadığında Kiri başlatılırken {service} bunu bağlar.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} boş. {app} bunu kurulu Kiri için bırakır.", + "Linking…": "Bağlanıyor…", + "Use {app}": "{app} kullan", + "Free": "Boş", + "Docker socket": "Docker soketi", + "The {docker} command uses {app}.": "{docker} komutu {app} kullanıyor.", + "{env} is set in this session, so {docker} uses another engine.": "Bu oturumda {env} ayarlı, bu yüzden {docker} başka bir motor kullanıyor.", + "The {docker} command uses {engine}.": "{docker} komutu {engine} kullanıyor.", + "Switching…": "Geçiliyor…", + "{docker} command": "{docker} komutu", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock artık Kiri’yi gösteriyor", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock bağlanamadı: {error}" } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 14446cdb6..3b9ece504 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Запускати Kiri під час входу в систему", "Start Kiri in the background when you sign in.": "Запускати Kiri у фоновому режимі під час входу в систему.", "Stop the engine when Kiri quits": "Зупиняти рушій під час виходу з Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Вихід із Kiri зупиняє запущені контейнери та рушій. Відкриття Kiri запускає його знову." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Вихід із Kiri зупиняє запущені контейнери та рушій. Відкриття Kiri запускає його знову.", + "{env} is set, so docker uses another engine instead of {app}": "Змінну {env} задано, тому docker використовує інший рушій замість {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Змінну {env} задано, тому {docker} використовує інший рушій замість {app}. Приберіть її в оболонці, щоб використовувати {app}.", + "{env} is set": "Змінну {env} задано", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} перевизначає контекст docker у цьому сеансі, тож зміна контексту не спрямує {docker} на {app}. Очистіть її командою {cmd} або видаліть із профілю.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} веде до {app}. Такі інструменти, як Testcontainers, плагіни IDE та SDK, використовують його напряму.", + "another engine": "інший рушій", + "{path} belongs to {engine} and stays so.": "{path} належить {engine} і залишається таким.", + "Tools that ignore docker contexts can use {hint}": "Інструменти, що ігнорують контексти docker, можуть використовувати {hint}", + "command": "команду", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} вільний. Прив’яжіть його до {app}, щоб інструменти без підтримки контекстів docker знаходили там {app}.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} вільний. {app} обслуговує його щоразу, коли працює і немає іншого рушія Docker.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} вільний. {service} прив’язує його під час запуску Kiri, доки його не зайняв інший рушій Docker.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} вільний. {app} залишає його для встановленого Kiri.", + "Linking…": "Зв’язування…", + "Use {app}": "Використати {app}", + "Free": "Вільний", + "Docker socket": "Сокет Docker", + "The {docker} command uses {app}.": "Команда {docker} використовує {app}.", + "{env} is set in this session, so {docker} uses another engine.": "У цьому сеансі задано {env}, тому {docker} використовує інший рушій.", + "The {docker} command uses {engine}.": "Команда {docker} використовує {engine}.", + "Switching…": "Перемикання…", + "{docker} command": "Команда {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock тепер вказує на Kiri", + "Could not link /var/run/docker.sock: {error}": "Не вдалося зв’язати /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index 31377822f..d7d659dd6 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "Khởi động Kiri khi đăng nhập", "Start Kiri in the background when you sign in.": "Khởi động Kiri dưới nền khi bạn đăng nhập.", "Stop the engine when Kiri quits": "Dừng engine khi thoát Kiri", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Thoát Kiri sẽ dừng các container đang chạy và engine. Mở Kiri sẽ khởi động lại nó." + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Thoát Kiri sẽ dừng các container đang chạy và engine. Mở Kiri sẽ khởi động lại nó.", + "{env} is set, so docker uses another engine instead of {app}": "{env} đang được đặt, nên docker dùng engine khác thay vì {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} đang được đặt, nên {docker} dùng engine khác thay vì {app}. Hãy bỏ đặt trong shell để dùng {app}.", + "{env} is set": "{env} đang được đặt", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} ghi đè ngữ cảnh của docker trong phiên này, nên chuyển ngữ cảnh sẽ không đưa {docker} sang {app}. Hãy xóa bằng {cmd} hoặc gỡ khỏi hồ sơ của bạn.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} trỏ tới {app}. Các công cụ như Testcontainers, plugin IDE và SDK sử dụng trực tiếp.", + "another engine": "một engine khác", + "{path} belongs to {engine} and stays so.": "{path} thuộc về {engine} và vẫn giữ nguyên.", + "Tools that ignore docker contexts can use {hint}": "Các công cụ bỏ qua ngữ cảnh docker có thể dùng {hint}", + "command": "lệnh", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} đang trống. Liên kết tới {app} để các công cụ bỏ qua ngữ cảnh docker tìm thấy {app} tại đó.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} đang trống. {app} phục vụ bất cứ khi nào đang chạy và không có Docker engine nào khác.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} đang trống. {service} liên kết khi Kiri khởi động nếu không có Docker engine khác giữ.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} đang trống. {app} để lại cho bản Kiri đã cài đặt.", + "Linking…": "Đang liên kết…", + "Use {app}": "Dùng {app}", + "Free": "Trống", + "Docker socket": "Socket Docker", + "The {docker} command uses {app}.": "Lệnh {docker} đang dùng {app}.", + "{env} is set in this session, so {docker} uses another engine.": "{env} được đặt trong phiên này, nên {docker} đang dùng engine khác.", + "The {docker} command uses {engine}.": "Lệnh {docker} đang dùng {engine}.", + "Switching…": "Đang chuyển…", + "{docker} command": "Lệnh {docker}", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock hiện trỏ tới Kiri", + "Could not link /var/run/docker.sock: {error}": "Không thể liên kết /var/run/docker.sock: {error}" } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index e7e4f6e6e..ef975a9ca 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "登录时启动 Kiri", "Start Kiri in the background when you sign in.": "登录时在后台启动 Kiri。", "Stop the engine when Kiri quits": "退出 Kiri 时停止引擎", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "退出 Kiri 会停止正在运行的容器和引擎。打开 Kiri 会再次启动它。" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "退出 Kiri 会停止正在运行的容器和引擎。打开 Kiri 会再次启动它。", + "{env} is set, so docker uses another engine instead of {app}": "已设置 {env},因此 docker 使用其他引擎而非 {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "已设置 {env},因此 {docker} 使用其他引擎而非 {app}。请在 shell 中取消设置以使用 {app}。", + "{env} is set": "已设置 {env}", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "在此会话中 {env} 覆盖了 docker 上下文,因此切换上下文不会让 {docker} 指向 {app}。请运行 {cmd} 清除或从配置文件中移除。", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} 指向 {app}。Testcontainers、IDE 插件和 SDK 等工具会直接使用它。", + "another engine": "其他引擎", + "{path} belongs to {engine} and stays so.": "{path} 属于 {engine} 且保持不变。", + "Tools that ignore docker contexts can use {hint}": "忽略 docker 上下文的工具可使用 {hint}", + "command": "命令", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} 空闲。将其链接到 {app},以便忽略 docker 上下文的工具在那里找到 {app}。", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} 空闲。每当 {app} 运行且没有其他 Docker 引擎占用时,它都会提供服务。", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} 空闲。若没有其他 Docker 引擎占用,{service} 会在 Kiri 启动时进行链接。", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} 空闲。{app} 会将其留给已安装的 Kiri。", + "Linking…": "正在链接…", + "Use {app}": "使用 {app}", + "Free": "空闲", + "Docker socket": "Docker 套接字", + "The {docker} command uses {app}.": "{docker} 命令使用 {app}。", + "{env} is set in this session, so {docker} uses another engine.": "当前会话已设置 {env},因此 {docker} 使用其他引擎。", + "The {docker} command uses {engine}.": "{docker} 命令使用 {engine}。", + "Switching…": "正在切换…", + "{docker} command": "{docker} 命令", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock 现已指向 Kiri", + "Could not link /var/run/docker.sock: {error}": "无法链接 /var/run/docker.sock:{error}" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 60309d22a..36635b9f3 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1863,5 +1863,29 @@ "Start Kiri at sign-in": "登入時啟動 Kiri", "Start Kiri in the background when you sign in.": "登入時在背景啟動 Kiri。", "Stop the engine when Kiri quits": "結束 Kiri 時停止引擎", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "結束 Kiri 會停止正在執行的容器與引擎。開啟 Kiri 會再次啟動它。" + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "結束 Kiri 會停止正在執行的容器與引擎。開啟 Kiri 會再次啟動它。", + "{env} is set, so docker uses another engine instead of {app}": "已設定 {env},因此 docker 使用其他引擎而非 {app}", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "已設定 {env},因此 {docker} 使用其他引擎而非 {app}。請在 shell 中取消設定以使用 {app}。", + "{env} is set": "已設定 {env}", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "在此工作階段中 {env} 會覆寫 docker 上下文,因此切換上下文不會讓 {docker} 指向 {app}。請執行 {cmd} 清除或從設定檔移除。", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} 指向 {app}。Testcontainers、IDE 外掛程式與 SDK 等工具會直接使用它。", + "another engine": "其他引擎", + "{path} belongs to {engine} and stays so.": "{path} 屬於 {engine} 並保持原樣。", + "Tools that ignore docker contexts can use {hint}": "忽略 docker 上下文的工具可使用 {hint}", + "command": "指令", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} 目前閒置。將其連結至 {app},讓忽略 docker 上下文的工具在該處找到 {app}。", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} 目前閒置。每當 {app} 執行且沒有其他 Docker 引擎佔用時,它都會提供服務。", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} 目前閒置。若沒有其他 Docker 引擎佔用,{service} 會在 Kiri 啟動時建立連結。", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} 目前閒置。{app} 會將其保留給已安裝的 Kiri。", + "Linking…": "正在連結…", + "Use {app}": "使用 {app}", + "Free": "閒置", + "Docker socket": "Docker Socket", + "The {docker} command uses {app}.": "{docker} 指令使用 {app}。", + "{env} is set in this session, so {docker} uses another engine.": "目前工作階段已設定 {env},因此 {docker} 使用其他引擎。", + "The {docker} command uses {engine}.": "{docker} 指令使用 {engine}。", + "Switching…": "正在切換…", + "{docker} command": "{docker} 指令", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock 現已指向 Kiri", + "Could not link /var/run/docker.sock: {error}": "無法連結 /var/run/docker.sock:{error}" } diff --git a/crates/kiri/src/ui/linux.rs b/crates/kiri/src/ui/linux.rs index c4e0bfa6d..bbebd1007 100644 --- a/crates/kiri/src/ui/linux.rs +++ b/crates/kiri/src/ui/linux.rs @@ -34,18 +34,68 @@ pub mod setup { Ok(()) } + /// Where Kiri's daemon listens on Linux (`KIRI_SOCKET` or `/run/kiri/docker.sock`). + pub fn socket_path() -> std::path::PathBuf { + std::env::var_os("KIRI_SOCKET").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from(crate::client::SERVICE_SOCKET)) + } + + /// Who owns `/var/run/docker.sock` on Linux. + pub fn docker_sock() -> crate::dockerctx::Endpoint { + crate::dockerctx::sock_at(std::path::Path::new("/var/run/docker.sock"), &socket_path(), &[]) + } + + /// Settings → Network's Docker socket row on Linux (status-only: `kiri.service` links it). + pub fn docker_sock_event() -> serde_json::Value { + let ours = format!("unix://{}", socket_path().display()); + crate::dockerctx::sock_event("/var/run/docker.sock", &docker_sock(), &ours, false) + } + + /// Unused on Linux (`take` is false), kept to share `ui::Cmd::TakeSocket`. + pub fn docker_socket() -> io::Result<()> { + Ok(()) + } + /// The package's service provides /var/run/docker.sock (kiri.service). pub fn docker_socket_note() -> Option { None } - /// Which engine plain `docker` uses: the CLI's own switch. - pub fn use_context(name: &str) -> io::Result<()> { - if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) { - return Err(io::Error::other("not a context name")); + /// Whether `docker` resolves to Kiri's packaged wrapper while no context + /// is stored in config.json (`DOCKER_HOST` / `DOCKER_CONTEXT` handled first). + fn wrapper_active() -> bool { + let Some(docker) = crate::client::docker_cli() else { return false }; + let Ok(real) = std::fs::canonicalize(docker) else { return false }; + if real != std::path::Path::new("/usr/libexec/kiri/docker") { + return false; + } + wrapper_uses_default_config(crate::dockerctx::docker_dir().as_deref()) + } + + fn wrapper_uses_default_config(dir: Option<&std::path::Path>) -> bool { + let Some(dir) = dir else { return true }; + let Ok(bytes) = std::fs::read(dir.join("config.json")) else { return true }; + let Ok(cfg) = serde_json::from_slice::(&bytes) else { return true }; + cfg.get("currentContext").and_then(|v| v.as_str()).is_none() + } + + /// What plain `docker` uses on Linux, factoring in Kiri's wrapper script. + pub fn current_cli(endpoint: &crate::dockerctx::Endpoint) -> crate::dockerctx::Cli { + let ours = format!("unix://{}", socket_path().display()); + let mut cli = crate::dockerctx::current_cli(crate::flavor::CONTEXT.get(), &[&ours], endpoint); + if !cli.kiri && cli.context == "default" && cli.pinned.is_none() && wrapper_active() { + cli.kiri = true; } - let out = std::process::Command::new("docker").args(["context", "use", name]).output()?; - if out.status.success() { Ok(()) } else { Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) } + cli + } + + /// Which engine plain `docker` uses: Kiri's context (created if missing), + /// "default", or another existing context, preserving logins and plugins. + pub fn use_context(name: &str) -> io::Result<()> { + let dir = crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("HOME is not set"))?; + let digest = kiri_image::store::sha256_digest(name.as_bytes()); + let meta = dir.join("contexts/meta").join(digest.trim_start_matches("sha256:")); + let host = format!("unix://{}", socket_path().display()); + crate::dockerctx::switch(&dir, &meta, name, crate::flavor::CONTEXT.get(), crate::flavor::APP.get(), &host) } fn config_dir() -> Option { @@ -286,25 +336,16 @@ pub mod onboarding { } } - /// `docker` reaches Kiri: its current endpoint is Kiri's socket, or the - /// standard socket that leads to it. Kiri's own `docker` (the package's - /// wrapper) does unless someone chose another context. + /// `docker` reaches Kiri: DOCKER_HOST, DOCKER_CONTEXT, config.json, + /// /var/run/docker.sock when Kiri serves it, or Kiri's `docker` wrapper. pub fn docker_uses_kiri() -> bool { - let Some(docker) = crate::client::docker_cli() else { return false }; - let Ok(out) = Command::new(docker).args(["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"]).stderr(Stdio::null()).output() else { return false }; - let host = String::from_utf8_lossy(&out.stdout).trim().to_owned(); - match host.strip_prefix("unix://") { - Some(p) if p == SOCKET => true, - Some(p) => std::fs::canonicalize(p).is_ok_and(|real| real == Path::new(SOCKET)), - None => false, - } + crate::client::docker_cli().is_some() && super::setup::current_cli(&super::setup::docker_sock()).kiri } /// The `kiri` docker context, made if missing, as the current one. fn use_kiri() -> io::Result<()> { - let docker = crate::client::docker_cli().ok_or_else(|| io::Error::other("no docker command here: install the kiri package (not kiri-lite) or docker's CLI"))?; - let _ = Command::new(&docker).args(["context", "create", "kiri", "--docker", &format!("host=unix://{SOCKET}")]).stdout(Stdio::null()).stderr(Stdio::null()).status(); - super::setup::use_context("kiri") + let _ = crate::client::docker_cli().ok_or_else(|| io::Error::other("no docker command here: install the kiri package (not kiri-lite) or docker's CLI"))?; + super::setup::use_context(crate::flavor::CONTEXT.get()) } fn builder_made() -> bool { @@ -376,3 +417,18 @@ pub mod onboarding { if Command::new("systemctl").arg("reboot").status()?.success() { Ok(()) } else { Err(io::Error::other("couldn't restart: use the system menu")) } } } + +#[cfg(test)] +mod tests { + use super::setup; + use crate::dockerctx::{Endpoint, sock_event}; + + #[test] + fn linux_sock_event_is_status_only() { + let e = sock_event("/var/run/docker.sock", &Endpoint::Free, "unix:///run/kiri/docker.sock", false); + assert_eq!((e["owner"].as_str(), e["take"].as_bool()), (Some("free"), Some(false))); + let e = sock_event("/var/run/docker.sock", &Endpoint::Taken("/run/podman/podman.sock".into()), "unix:///run/kiri/docker.sock", false); + assert_eq!((e["owner"].as_str(), e["engine"].as_str(), e["take"].as_bool()), (Some("other"), Some("Podman"), Some(false))); + let _ = setup::docker_socket(); + } +} diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 384cf104a..dff5721c4 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -91,6 +91,8 @@ enum Cmd { About, /// Settings → Domains: turn `*.kiri.local` on or off (asks for the password). Domains(bool), + /// Settings → Network: link `/var/run/docker.sock` to Kiri when free (macOS). + TakeSocket, /// New published ports for a container: `[{container_port, host_port, proto, host_ip}]`. Ports { id: String, ports: serde_json::Value }, Env { id: String, env: Vec }, @@ -111,6 +113,7 @@ impl Cmd { Cmd::Ports { id, .. } => ("ports", id.chars().take(12).collect()), Cmd::Env { id, .. } => ("env", id.chars().take(12).collect()), Cmd::Domains(on) => ("domains", on.to_string()), + Cmd::TakeSocket => ("takesocket", String::new()), Cmd::Quit | Cmd::Refresh | Cmd::About | Cmd::Connect => return None, }) } @@ -345,8 +348,25 @@ fn engine(rx: Receiver, tx: Sender) { emit(notice("ok", ¬e)); } emit(domains_event()); + emit_docker_state(); refresh(&mut connected); } + Ok(Cmd::TakeSocket) => { + match setup::docker_socket() { + Ok(()) if setup::docker_sock() == crate::dockerctx::Endpoint::Kiri => { + emit(notice("ok", &tr("/var/run/docker.sock now points to Kiri"))); + } + Ok(()) => { + if let Some(note) = setup::docker_socket_note() { + emit(notice("ok", ¬e)); + } + } + // Cancelling macOS's password prompt is a choice, not an error. + Err(e) if !e.to_string().contains("-128") => emit(notice("error", &trf("Could not link /var/run/docker.sock: {error}", &[("error", &e)]))), + Err(_) => {} + } + emit_docker_state(); + } Ok(Cmd::RemoveNetwork(id)) => act("rmnet", expect_ok(client::request("DELETE", &format!("/networks/{id}"), None))), Ok(Cmd::Quit) | Err(RecvTimeoutError::Disconnected) => { quit_with( @@ -360,6 +380,7 @@ fn engine(rx: Receiver, tx: Sender) { } Err(RecvTimeoutError::Timeout) => { vm_panel(&mut connected); + emit_docker_state_if_changed(); if connected && LISTED.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= LIST_EVERY { refresh(&mut connected); } @@ -937,19 +958,44 @@ fn reopen_after_exit() { let _ = std::process::Command::new("/bin/sh").args(["-c", script, "sh", &std::process::id().to_string()]).arg(&app).spawn(); } -fn status_event() -> String { - let context = std::env::var("DOCKER_CONTEXT").ok().filter(|c| !c.is_empty()).or_else(|| { - let home = std::env::var_os("HOME")?; - let cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(std::path::Path::new(&home).join(".docker/config.json")).ok()?).ok()?; - cfg["currentContext"].as_str().map(str::to_owned) - }); - // Linux: docker's default endpoint is the standard socket, which leads to - // Kiri while no Docker engine has it (the package links it), and the - // package's docker goes to Kiri's socket: that is docker using Kiri, as - // the setup checklist says, not "Docker's default engine". +fn docker_state() -> (String, String) { + #[cfg(target_os = "macos")] + let cli = { + let endpoint = setup::docker_sock(); + let ours = crate::daemon::socket_path().map(|p| format!("unix://{}", p.display())).unwrap_or_default(); + let hosts: Vec<&str> = (!ours.is_empty()).then_some(ours.as_str()).into_iter().collect(); + crate::dockerctx::current_cli(crate::flavor::CONTEXT.get(), &hosts, &endpoint) + }; #[cfg(target_os = "linux")] - let context = if context.as_deref().is_none_or(|c| c == "default") && linux::onboarding::docker_uses_kiri() { Some(crate::flavor::CONTEXT.get().to_owned()) } else { context }; - serde_json::json!({"type": "status", "version": env!("CARGO_PKG_VERSION"), "dev": crate::flavor::dev(), "share": true, "app": crate::flavor::APP.get(), "ours": crate::flavor::CONTEXT.get(), "context": context.unwrap_or_else(|| "default".into())}).to_string() + let cli = setup::current_cli(&setup::docker_sock()); + let status = crate::dockerctx::status_event(env!("CARGO_PKG_VERSION"), crate::flavor::dev(), crate::flavor::APP.get(), crate::flavor::CONTEXT.get(), &cli).to_string(); + let sock = setup::docker_sock_event().to_string(); + (status, sock) +} + +static LAST_DOCKER_STATE: std::sync::Mutex<(String, String)> = std::sync::Mutex::new((String::new(), String::new())); + +fn emit_docker_state() { + let (status, sock) = docker_state(); + *LAST_DOCKER_STATE.lock().unwrap_or_else(|e| e.into_inner()) = (status.clone(), sock.clone()); + emit(status); + emit(sock); +} + +fn emit_docker_state_if_changed() { + let (status, sock) = docker_state(); + let (send_status, send_sock) = { + let mut last = LAST_DOCKER_STATE.lock().unwrap_or_else(|e| e.into_inner()); + let ss = if last.0 != status { last.0 = status.clone(); true } else { false }; + let sd = if last.1 != sock { last.1 = sock.clone(); true } else { false }; + (ss, sd) + }; + if send_status { + emit(status); + } + if send_sock { + emit(sock); + } } /// Which names containers answer at now. @@ -2085,10 +2131,16 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { // Which engine plain `docker` uses: Kiri, or back to the one before. "usecontext" => { let result = setup::use_context(&msg.name); - emit(status_event()); + emit_docker_state(); emit(serde_json::json!({"type": "usedcontext", "name": msg.name, "error": result.as_ref().err().map(|e| e.to_string())}).to_string()); Ok(()) } + // Settings → Network: Docker socket state and taking /var/run/docker.sock when free. + "dockersock" => { + emit_docker_state(); + Ok(()) + } + "takesocket" => tx.send(Cmd::TakeSocket), // Settings → Builds: clear Kiri's builder cache (`docker builder // prune --all`), which Images and Volumes don't list. "buildprune" => { @@ -2437,7 +2489,7 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { setup_tools(); } emit(domains_event()); - emit(status_event()); + emit_docker_state(); // A crash since the window last opened, for the page to // offer a report; crash files go if the person allowed it. std::thread::spawn(|| { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 665743705..4a6a82162 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 +### #577 Network: show default Docker socket owner and accurate CLI binding across macOS, Linux, Windows, and Windows setup (unreleased) +- Fixes: #577 Settings → Network: show who owns the default Docker socket (`/var/run/docker.sock` / `\\.\pipe\docker_engine`), offer to link it when free on macOS, and show `DOCKER_HOST` hint when another engine owns it; #369 report plain `docker` CLI binding accurately when another context or `DOCKER_HOST`/`DOCKER_CONTEXT` overrides Kiri, and apply "Make Kiri the default for docker" in Windows setup +- Caused: none known +- Caused by: - +- Check: none + ### #368 Settings: add Start Kiri at sign-in and Stop the engine when Kiri quits (unreleased) - Fixes: #368 macOS: setting to stop the engine when Kiri quits; #703 Add "Launch at startup" toggle in app settings - Caused: none known diff --git a/tests/ui/docker-socket.js b/tests/ui/docker-socket.js new file mode 100644 index 000000000..12fea25bd --- /dev/null +++ b/tests/ui/docker-socket.js @@ -0,0 +1,129 @@ +// Settings -> Network: Docker socket ownership (#577) and plain `docker` CLI +// binding (#369). Run with scripts/ui-test.py. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; +const click = (sel) => { const el = document.querySelector(sel); if (!el) throw new Error("no " + sel); el.click(); return el; }; + +const reset = () => { + sent.length = 0; + document.querySelectorAll(".scrim").forEach((x) => x.remove()); + kiri.on({ type: "importsources", sources: [] }); + kiri.on({ type: "status", version: "0.1.4", dev: false, share: true, app: "Kiri", ours: "kiri", context: "kiri", pinned: null }); + kiri.on({ type: "dockersock", path: WIN ? "\\\\.\\pipe\\docker_engine" : "/var/run/docker.sock", owner: "kiri", engine: null, target: null, hint: WIN ? "DOCKER_HOST=npipe:////./pipe/kiri" : "DOCKER_HOST=unix:///Users/me/.kiri/run/docker.sock", take: false }); + sent.length = 0; +}; + +prefs.tab = "network"; +show("settings"); + +t("Settings -> Network asks for dockersock on open, tab click and window focus", () => { + reset(); + show("containers"); + sent.length = 0; + show("settings"); + eq(sent.some((x) => x.type === "dockersock"), true, "show settings"); + sent.length = 0; + click('[data-stab="about"]'); + click('[data-stab="network"]'); + eq(sent.some((x) => x.type === "dockersock"), true, "tab click"); + sent.length = 0; + window.dispatchEvent(new Event("focus")); + eq(sent.some((x) => x.type === "dockersock"), true, "window focus"); +}); + +t("Docker socket and CLI rows render above loading or stopped engine error", () => { + reset(); + ui.proxy = null; + render(); + eq(document.querySelectorAll("#content .pref").length >= 2, true, "rows visible while loading"); + ui.proxy = { error: "Kiri is not running" }; + render(); + const txt = document.getElementById("content").textContent; + eq(txt.includes("Docker socket"), true, "socket row while stopped"); + eq(txt.includes("docker command"), true, "cli row while stopped"); + eq(txt.includes("Kiri is not running"), true, "proxy error still shown"); +}); + +t("Another engine owning the socket shows its name, DOCKER_HOST hint and copy button", () => { + reset(); + ui.proxy = { error: "Kiri is not running" }; + const hint = WIN ? "DOCKER_HOST=npipe:////./pipe/kiri" : "DOCKER_HOST=unix:///Users/me/.kiri/run/docker.sock"; + kiri.on({ + type: "dockersock", + path: WIN ? "\\\\.\\pipe\\docker_engine" : "/var/run/docker.sock", + owner: "other", + engine: WIN ? "Docker Desktop" : "OrbStack", + target: WIN ? "Docker Desktop.exe" : "/Users/me/.orbstack/run/docker.sock", + hint, + take: false, + }); + const c = document.getElementById("content"); + const txt = c.textContent; + eq(txt.includes(WIN ? "Docker Desktop" : "OrbStack"), true, "engine shown"); + eq(txt.includes(hint), true, "hint shown"); + eq(!!c.querySelector("[data-takesock]"), false, "never offers to take another engine's socket"); + sent.length = 0; + click("#content [data-copy]"); + eq(sent.find((x) => x.type === "copy")?.name, hint, "copy hint"); + // Unknown owner (no engine name or target) never renders "null" or "undefined". + kiri.on({ type: "dockersock", path: "/var/run/docker.sock", owner: "other", engine: null, target: null, hint, take: false }); + const t2 = document.getElementById("content").textContent; + eq(t2.includes("null") || t2.includes("undefined"), false, "no raw null"); +}); + +t("Free socket shows Use Kiri when take is true and Free badge when take is false", () => { + reset(); + ui.proxy = { error: "stopped" }; + const path = "/var/run/docker.sock"; + const hint = "DOCKER_HOST=unix:///Users/me/.kiri/run/docker.sock"; + kiri.on({ type: "dockersock", path, owner: "free", engine: null, target: null, hint, take: true }); + sent.length = 0; + click("#content [data-takesock]"); + eq(sent.some((x) => x.type === "takesocket"), true, "takesocket sent"); + eq(document.querySelector("#content [data-takesock]").disabled, true, "disabled while taking"); + // Cancel or update re-enables on fresh dockersock event. + kiri.on({ type: "dockersock", path, owner: "free", engine: null, target: null, hint, take: true }); + eq(document.querySelector("#content [data-takesock]").disabled, false, "re-enabled after event"); + kiri.on({ type: "dockersock", path, owner: "free", engine: null, target: null, hint, take: false }); + eq(!!document.querySelector("#content [data-takesock]"), false, "no take button when take is false"); + eq(document.getElementById("content").textContent.includes("Free"), true, "Free badge"); +}); + +t("Another docker context (desktop-linux) reports honestly and switches from Settings", () => { + reset(); + ui.proxy = { error: "stopped" }; + kiri.on({ type: "status", version: "0.1.4", dev: false, share: true, app: "Kiri", ours: "kiri", context: "desktop-linux", pinned: null }); + show("containers"); + eq(document.querySelector("#statusbar").textContent.includes("docker → Docker Desktop"), true, "status bar says Docker Desktop"); + eq(!!document.querySelector("#impstrip [data-ctxswitch]"), true, "strip offers switch"); + prefs.tab = "network"; + show("settings"); + eq(document.getElementById("content").textContent.includes("The docker command uses Docker Desktop."), true, "Settings shows Docker Desktop"); + sent.length = 0; + click("#content [data-usekiri]"); + eq(sent.find((x) => x.type === "usecontext")?.name, "kiri", "switches to kiri"); + kiri.on({ type: "status", version: "0.1.4", dev: false, share: true, app: "Kiri", ours: "kiri", context: "kiri", pinned: null }); + kiri.on({ type: "usedcontext", name: "kiri", error: null }); + eq(!!document.querySelector("#content [data-usekiri]"), false, "switch button gone once on kiri"); + eq(document.querySelector("#statusbar").textContent.includes("docker → Kiri"), true, "status bar updated to Kiri"); +}); + +t("Pinned DOCKER_HOST or DOCKER_CONTEXT never offers a context switch", () => { + reset(); + ui.proxy = { error: "stopped" }; + kiri.on({ type: "status", version: "0.1.4", dev: false, share: true, app: "Kiri", ours: "kiri", context: "default", pinned: "DOCKER_HOST" }); + show("containers"); + eq(document.querySelector("#statusbar").textContent.includes("docker → DOCKER_HOST"), true, "status bar names DOCKER_HOST"); + eq(!!document.querySelector("#impstrip [data-ctxswitch]"), false, "strip does not offer pointless switch"); + click("#statusbar [data-ctxswitch]"); + eq(document.querySelector("#ctx-dlg")?.textContent.includes("DOCKER_HOST"), true, "dialog explains DOCKER_HOST"); + eq(!!document.querySelector("#ctx-dlg [data-ctxgo]"), false, "dialog has no switch button when pinned"); + click("#ctx-dlg [data-close]"); + prefs.tab = "network"; + show("settings"); + eq(!!document.querySelector("#content [data-usekiri]"), false, "Settings hides switch when pinned"); + eq(document.getElementById("content").textContent.includes("DOCKER_HOST"), true, "Settings names DOCKER_HOST"); +}); + +report(R); diff --git a/tests/ui/parity.js b/tests/ui/parity.js index 59c99a8cc..dd6ff8e8a 100644 --- a/tests/ui/parity.js +++ b/tests/ui/parity.js @@ -27,4 +27,9 @@ for (const th of document.querySelectorAll("#content thead th")) { const h = th. prefs.tab = "appearance"; show("settings"); for (const b of document.querySelectorAll("[data-stab]")) items.push(`settings ${b.dataset.stab}`); for (const el of document.querySelectorAll(".settings .pref > .t")) if (seen(el)) items.push(`setting appearance: ${el.textContent.trim()}`); +prefs.tab = "network"; +kiri.on({ type: "status", version: "0.1.4", dev: false, share: true, app: "Kiri", ours: "kiri", context: "kiri", pinned: null }); +kiri.on({ type: "dockersock", path: "/var/run/docker.sock", owner: "kiri", engine: null, target: null, hint: "DOCKER_HOST=unix:///kiri", take: false }); +show("settings"); +for (const t of document.querySelectorAll("#content .pref .t")) items.push(`network ${t.textContent.trim()}`); report(items.map((x) => "ITEM " + x)); From 9e92a80c904663b0e53b9422148d23cb6d786a8b Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:36:34 +0100 Subject: [PATCH 046/157] Settings: allow moving images, containers, and volumes to a custom storage directory (#355) (#829) --- crates/kiri-image/src/lib.rs | 1 + crates/kiri-image/src/storage.rs | 176 +++++ crates/kiri-image/src/store.rs | 15 +- crates/kiri-init/src/linux/mod.rs | 48 ++ crates/kiri-vmm/src/process.rs | 5 + crates/kiri-win/src/app.rs | 36 + crates/kiri-win/src/engine.rs | 30 + crates/kiri-win/src/main.rs | 3 + crates/kiri-win/src/serve.rs | 19 + crates/kiri-win/src/setup.rs | 12 +- crates/kiri-win/src/storage.rs | 767 +++++++++++++++++++++ crates/kiri/src/daemon/api.rs | 13 +- crates/kiri/src/daemon/engine.rs | 51 ++ crates/kiri/src/daemon/mod.rs | 76 +- crates/kiri/src/daemon/storage.rs | 994 +++++++++++++++++++++++++++ crates/kiri/src/daemon/treecopy.rs | 562 +++++++++++++++ crates/kiri/src/guest.rs | 15 +- crates/kiri/src/setup.rs | 48 ++ crates/kiri/src/ui/gtk.rs | 13 + crates/kiri/src/ui/index.html | 177 ++++- crates/kiri/src/ui/lang/am.json | 47 +- crates/kiri/src/ui/lang/ar.json | 47 +- crates/kiri/src/ui/lang/bg.json | 47 +- crates/kiri/src/ui/lang/bn.json | 47 +- crates/kiri/src/ui/lang/ca.json | 47 +- crates/kiri/src/ui/lang/ckb.json | 47 +- crates/kiri/src/ui/lang/cs.json | 47 +- crates/kiri/src/ui/lang/de.json | 47 +- crates/kiri/src/ui/lang/el.json | 47 +- crates/kiri/src/ui/lang/es.json | 47 +- crates/kiri/src/ui/lang/fa.json | 47 +- crates/kiri/src/ui/lang/fi.json | 47 +- crates/kiri/src/ui/lang/fr.json | 47 +- crates/kiri/src/ui/lang/hi.json | 47 +- crates/kiri/src/ui/lang/hu.json | 47 +- crates/kiri/src/ui/lang/id.json | 47 +- crates/kiri/src/ui/lang/it.json | 47 +- crates/kiri/src/ui/lang/ja.json | 47 +- crates/kiri/src/ui/lang/kk.json | 47 +- crates/kiri/src/ui/lang/ko.json | 47 +- crates/kiri/src/ui/lang/lo.json | 47 +- crates/kiri/src/ui/lang/lt.json | 47 +- crates/kiri/src/ui/lang/nb.json | 47 +- crates/kiri/src/ui/lang/pl.json | 47 +- crates/kiri/src/ui/lang/pt-BR.json | 47 +- crates/kiri/src/ui/lang/ro.json | 47 +- crates/kiri/src/ui/lang/ru.json | 47 +- crates/kiri/src/ui/lang/sl.json | 47 +- crates/kiri/src/ui/lang/sq.json | 47 +- crates/kiri/src/ui/lang/ta.json | 47 +- crates/kiri/src/ui/lang/te.json | 47 +- crates/kiri/src/ui/lang/th.json | 47 +- crates/kiri/src/ui/lang/tr.json | 47 +- crates/kiri/src/ui/lang/uk.json | 47 +- crates/kiri/src/ui/lang/vi.json | 47 +- crates/kiri/src/ui/lang/zh-Hans.json | 47 +- crates/kiri/src/ui/lang/zh-Hant.json | 47 +- crates/kiri/src/ui/mac.rs | 28 + crates/kiri/src/ui/mod.rs | 205 ++++++ docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + tests/ui/storage-location.js | 167 +++++ 62 files changed, 5155 insertions(+), 52 deletions(-) create mode 100644 crates/kiri-image/src/storage.rs create mode 100644 crates/kiri-win/src/storage.rs create mode 100644 crates/kiri/src/daemon/storage.rs create mode 100644 crates/kiri/src/daemon/treecopy.rs create mode 100644 tests/ui/storage-location.js diff --git a/crates/kiri-image/src/lib.rs b/crates/kiri-image/src/lib.rs index d34334881..562d17bbf 100644 --- a/crates/kiri-image/src/lib.rs +++ b/crates/kiri-image/src/lib.rs @@ -11,6 +11,7 @@ pub mod jsonfile; pub mod mirror; pub mod reference; pub mod registry; +pub mod storage; pub mod store; pub mod tags; diff --git a/crates/kiri-image/src/storage.rs b/crates/kiri-image/src/storage.rs new file mode 100644 index 000000000..816ee0e43 --- /dev/null +++ b/crates/kiri-image/src/storage.rs @@ -0,0 +1,176 @@ +//! Settings → Storage: the folder a person chose for Kiri's data, kept in +//! `~/.kiri/storage.json` (`{"path": "/Volumes/External/kiri"}`), beside +//! `vm.json` and never inside the data folder itself. +//! +//! Nobody who leaves the setting alone has the file: [`crate::Store::default_root`] +//! then gives the folder it always did. With the file, the chosen folder +//! counts only while it holds the [`MARKER`] a finished move writes there: +//! a drive that isn't connected must not get an empty store made in its +//! place under `/Volumes`, so the folder is reported unavailable instead +//! ([`Unavailable`]). + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// The file, under the state folder (`~/.kiri`). +pub const FILE: &str = "storage.json"; + +/// Written into a data folder once a move into it is complete: what tells +/// a Kiri data folder from an empty mount point or someone else's files. +pub const MARKER: &str = ".kiri-storage"; + +/// What `storage.json` holds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Choice { + /// The data folder. + pub path: PathBuf, + /// The folder the data was moved from and that still holds a copy, + /// until Settings → Storage → Remove old data. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +/// The chosen folder isn't there, or isn't Kiri's (its drive isn't +/// connected): the error [`crate::Store::default_root`] gives for it. +#[derive(Debug)] +pub struct Unavailable(pub PathBuf); + +impl std::fmt::Display for Unavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Kiri's data folder {} isn't available: connect its drive, or choose Settings → Storage → Reset to default", self.0.display()) + } +} + +impl std::error::Error for Unavailable {} + +/// The folder an [`Unavailable`] error names. +pub fn unavailable(e: &io::Error) -> Option<&Path> { + e.get_ref().and_then(|inner| inner.downcast_ref::()).map(|u| u.0.as_path()) +} + +/// `~/.kiri/storage.json`. +pub fn config_path() -> io::Result { + let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; + Ok(home.join(".kiri").join(FILE)) +} + +/// The choice in `file`; None when there is no file. +pub fn read_at(file: &Path) -> io::Result> { + match fs::read(file) { + Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", file.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// The choice in `~/.kiri/storage.json`, if there is one. +pub fn read() -> io::Result> { + read_at(&config_path()?) +} + +/// Writes `choice` to `file` whole: a temporary file renamed over it and +/// synced, so a crash leaves the old choice or the new one. This write is +/// a move's commit point. +pub fn write_at(file: &Path, choice: &Choice) -> io::Result<()> { + if let Some(dir) = file.parent() { + fs::create_dir_all(dir)?; + } + let bytes = serde_json::to_vec_pretty(choice).map_err(io::Error::other)?; + crate::jsonfile::replace(file, &bytes, crate::jsonfile::Durable::Now) +} + +/// Writes `~/.kiri/storage.json`. +pub fn write(choice: &Choice) -> io::Result<()> { + write_at(&config_path()?, choice) +} + +/// Removes `~/.kiri/storage.json`: back to the default folder, as if the +/// setting had never been changed. +pub fn clear() -> io::Result<()> { + match fs::remove_file(config_path()?) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +/// Whether `dir` holds the marker of a finished move. +pub fn has_marker(dir: &Path) -> bool { + dir.join(MARKER).is_file() +} + +/// Writes the marker into `dir`. +pub fn write_marker(dir: &Path) -> io::Result<()> { + crate::jsonfile::replace(&dir.join(MARKER), b"{\"kiri\":1}\n", crate::jsonfile::Durable::Now) +} + +/// The data folder `choice` gives, where `default` is the one without +/// it: the chosen folder if it holds the marker, else [`Unavailable`]. +/// The default folder needs no marker. +pub fn resolve(choice: Option, default: PathBuf) -> io::Result { + match choice { + None => Ok(default), + Some(c) if c.path == default || has_marker(&c.path) => Ok(c.path), + Some(c) => Err(io::Error::new(io::ErrorKind::NotFound, Unavailable(c.path))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-storage-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + /// No file: the default folder, and nothing is written. + #[test] + fn no_file_is_the_default_folder() { + let d = scratch("none"); + let file = d.join(FILE); + assert_eq!(read_at(&file).unwrap(), None); + assert_eq!(resolve(read_at(&file).unwrap(), d.join("default")).unwrap(), d.join("default")); + assert!(!file.exists()); + let _ = fs::remove_dir_all(&d); + } + + /// A chosen folder counts once it holds the marker; without it (the + /// drive isn't connected) it is unavailable, never the default and + /// never made. + #[test] + fn a_chosen_folder_needs_its_marker() { + let d = scratch("marker"); + let file = d.join(FILE); + let chosen = d.join("external/kiri"); + write_at(&file, &Choice { path: chosen.clone(), previous: None }).unwrap(); + let e = resolve(read_at(&file).unwrap(), d.join("default")).unwrap_err(); + assert_eq!(unavailable(&e), Some(chosen.as_path())); + assert!(e.to_string().contains("isn't available"), "{e}"); + assert!(!chosen.exists(), "an unavailable folder is never made"); + fs::create_dir_all(&chosen).unwrap(); + write_marker(&chosen).unwrap(); + assert_eq!(resolve(read_at(&file).unwrap(), d.join("default")).unwrap(), chosen); + let _ = fs::remove_dir_all(&d); + } + + /// The file is replaced whole, and an old copy's `previous` is kept + /// only when written. + #[test] + fn the_choice_round_trips() { + let d = scratch("roundtrip"); + let file = d.join(FILE); + let c = Choice { path: d.join("a"), previous: Some(d.join("b")) }; + write_at(&file, &c).unwrap(); + assert_eq!(read_at(&file).unwrap(), Some(c)); + write_at(&file, &Choice { path: d.join("a"), previous: None }).unwrap(); + assert!(!fs::read_to_string(&file).unwrap().contains("previous")); + fs::write(&file, b"{not json").unwrap(); + assert_eq!(read_at(&file).unwrap_err().kind(), io::ErrorKind::InvalidData); + let _ = fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri-image/src/store.rs b/crates/kiri-image/src/store.rs index 32b201127..969e20d85 100644 --- a/crates/kiri-image/src/store.rs +++ b/crates/kiri-image/src/store.rs @@ -256,13 +256,22 @@ pub fn digest_hex(digest: &str) -> io::Result<&str> { } impl Store { - /// The per-user data directory: `~/Library/Application Support/Kiri` on - /// macOS, `$XDG_DATA_HOME/kiri` (or `~/.local/share/kiri`) elsewhere. - /// `KIRI_DATA_DIR` overrides both. + /// The data directory: `KIRI_DATA_DIR` if set, else the folder chosen + /// in Settings → Storage (`~/.kiri/storage.json`, see + /// [`crate::storage`]), else [`Store::os_default_root`]. A chosen folder + /// without its marker (a drive that isn't connected) is an error that + /// [`crate::storage::unavailable`] recognises, never a fresh folder. pub fn default_root() -> io::Result { if let Some(dir) = std::env::var_os("KIRI_DATA_DIR") { return Ok(PathBuf::from(dir)); } + crate::storage::resolve(crate::storage::read()?, Self::os_default_root()?) + } + + /// The per-user data directory when nothing else is chosen: + /// `~/Library/Application Support/Kiri` on macOS, `$XDG_DATA_HOME/kiri` + /// (or `~/.local/share/kiri`) elsewhere. + pub fn os_default_root() -> io::Result { let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; Ok(if cfg!(target_os = "macos") { home.join("Library/Application Support/Kiri") diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index b23cb3333..e01c69726 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -155,6 +155,9 @@ fn host_dirs() -> io::Result { // SAFETY: umask only changes this process's file-creation mask. unsafe { libc::umask(0o022) }; 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 mkdir = |p: &std::path::Path, mode: u32| -> io::Result<()> { std::fs::create_dir_all(p)?; std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)) @@ -200,6 +203,39 @@ fn host_dirs() -> io::Result { Ok(paths) } +/// Bind-mounts `src` (the chosen folder's `agent` directory, from +/// `KIRI_AGENT_DATA`) onto `/var/lib/kiri` so every agent path stays under +/// `/var/lib/kiri` while living on the chosen disk. No-op when `src` is +/// already mounted there; detaches any other mount on `target` first. +fn mount_agent_data(src: &std::path::Path, target: &std::path::Path) -> io::Result<()> { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::MetadataExt; + std::fs::create_dir_all(src)?; + std::fs::create_dir_all(target)?; + let (sm, tm) = (std::fs::metadata(src)?, std::fs::metadata(target)?); + if (sm.dev(), sm.ino()) == (tm.dev(), tm.ino()) { + return Ok(()); + } + let c_target = CString::new(target.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + if std::fs::read_to_string("/proc/self/mountinfo").is_ok_and(|m| is_mounted_at(&m, target)) { + // SAFETY: valid NUL-terminated path; detaches a stale mount at `target`. + unsafe { libc::umount2(c_target.as_ptr(), libc::MNT_DETACH) }; + } + let c_src = CString::new(src.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: valid NUL-terminated paths for a bind mount (fstype and data unused). + check(unsafe { libc::mount(c_src.as_ptr(), c_target.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null()) } as _, "bind-mount KIRI_AGENT_DATA").map(drop) +} + +/// Whether `/proc/self/mountinfo` lists a mount whose target is `target`. +fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool { + let want = target.to_string_lossy(); + mountinfo.lines().any(|line| { + let Some((before, _)) = line.split_once(" - ") else { return false }; + before.split_whitespace().nth(4).is_some_and(|mp| unescape_mount_path(mp) == want) + }) +} + /// The lock on a Linux host's data directory, held while the agent runs. static AGENT_LOCK: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -831,4 +867,16 @@ mod cgroup_discovery_tests { assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/system.slice/kiri.service"), &[])); assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/custom"), &[std::process::id().to_string()])); } + + #[test] + fn is_mounted_at_finds_exact_mountpoint() { + let mountinfo = "\ +28 1 8:1 / / rw,relatime - ext4 /dev/sda1 rw +55 28 8:2 /kiri/agent /var/lib/kiri rw,relatime - ext4 /dev/sdb1 rw +56 28 8:2 /sub /var/lib/kiri/volumes/x rw,relatime - ext4 /dev/sdb1 rw +"; + assert!(super::is_mounted_at(mountinfo, Path::new("/var/lib/kiri"))); + assert!(!super::is_mounted_at(mountinfo, Path::new("/var/lib"))); + assert!(!super::is_mounted_at(mountinfo, Path::new("/media/ssd"))); + } } diff --git a/crates/kiri-vmm/src/process.rs b/crates/kiri-vmm/src/process.rs index fda1cf6ed..96e778446 100644 --- a/crates/kiri-vmm/src/process.rs +++ b/crates/kiri-vmm/src/process.rs @@ -132,6 +132,11 @@ impl Vm { })?; let mut cmd = Command::new(&cfg.initrd); cmd.env("KIRI_AGENT_DIR", &dir).env_remove("KIRI_SOCKET"); + if let Some(data) = &cfg.disk { + cmd.env("KIRI_AGENT_DATA", data); + } else { + cmd.env_remove("KIRI_AGENT_DATA"); + } if let Some(fd) = cfg.console { cmd.stderr(std::process::Stdio::from(fd.try_clone()?)).stdout(std::process::Stdio::from(fd)); } else { diff --git a/crates/kiri-win/src/app.rs b/crates/kiri-win/src/app.rs index 69101d2bf..e88d5cf42 100644 --- a/crates/kiri-win/src/app.rs +++ b/crates/kiri-win/src/app.rs @@ -193,6 +193,42 @@ pub fn pick_file(title: &str, filters: &[(String, String)], done: impl FnOnce(Op } } +/// Settings → Storage → Change…: Windows' own folder picker (`FOS_PICKFOLDERS`) +/// over the window, on its thread, outside `with_ui`. `done` gets the chosen +/// folder, or None when cancelled, on a thread of its own. +pub fn pick_folder(title: &str, done: impl FnOnce(Option) + Send + 'static) { + let title = HSTRING::from(title); + BARE.lock().unwrap_or_else(PoisonError::into_inner).push(Box::new(move |hwnd| { + // SAFETY: on the window's thread, where COM is initialised (run). + let path = unsafe { folder_dialog(hwnd, &title) }.ok().flatten(); + std::thread::spawn(move || done(path)); + })); + let hwnd = WINDOW.load(Ordering::SeqCst); + if hwnd != 0 { + // SAFETY: posting to our own window; a closed one just drops it. + let _ = unsafe { PostMessageW(Some(HWND(hwnd as _)), WM_RUN, WPARAM(0), LPARAM(0)) }; + } +} + +/// IFileOpenDialog with `FOS_PICKFOLDERS`: one local folder on disk, or None when cancelled. +unsafe fn folder_dialog(owner: HWND, title: &HSTRING) -> windows::core::Result> { + use windows::Win32::System::Com::{CoCreateInstance, CoTaskMemFree, CLSCTX_INPROC_SERVER}; + use windows::Win32::UI::Shell::{FileOpenDialog, IFileOpenDialog, FOS_FORCEFILESYSTEM, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS, SIGDN_FILESYSPATH}; + // SAFETY: COM calls on this thread's apartment. + unsafe { + let d: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER)?; + d.SetTitle(title)?; + d.SetOptions(d.GetOptions()? | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST)?; + if d.Show(Some(owner)).is_err() { + return Ok(None); + } + let name = d.GetResult()?.GetDisplayName(SIGDN_FILESYSPATH)?; + let path = name.to_string().ok(); + CoTaskMemFree(Some(name.0 as *const _)); + Ok(path.map(std::path::PathBuf::from)) + } +} + /// Jobs that need only the window's handle and run outside with_ui (a modal /// dialog), on the window's thread. type BareJob = Box; diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 435621e5a..d6ceb727e 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -350,6 +350,10 @@ pub(crate) fn ensure_daemon() -> io::Result<()> { /// Starts the daemon in WSL, this app's engine copied in first. fn start_daemon() -> io::Result<()> { + if let Some(missing) = crate::storage::unavailable() { + crate::storage::emit_report(); + return Err(io::Error::other(crate::storage::unavailable_message(&missing))); + } crate::serve::log("engine: not answering; starting it in WSL"); // The engine this app installed, not one an update left behind. match crate::update::sync_engine() { @@ -1173,6 +1177,7 @@ pub fn on_message(msg: &str) { } emit(domains_event()); emit_docker_state(); + std::thread::spawn(crate::storage::emit_report); ask_language(); // The first time, offer .kiri.local, as the Mac does. if !crate::dns::installed() && crate::dns::serving() && prefs()["domainsAsked"] != true { @@ -1500,6 +1505,31 @@ pub fn on_message(msg: &str) { emit(builds_event()); }); } + // Settings → Storage: where WSL keeps Kiri's VHDX, and moving it. + "storage" => { + std::thread::spawn(crate::storage::emit_report); + } + "storagepick" => { + crate::app::pick_folder(&tr("Choose a storage folder"), |path| { + if let Some(p) = path { + crate::storage::check_and_emit(Some(p.to_string_lossy().into_owned()), false, false); + } + }); + } + "storagecheck" => { + let path = (!c.path.trim().is_empty()).then(|| c.path.clone()); + let fresh = c.value["fresh"] == true; + let reset = c.value["reset"] == true; + std::thread::spawn(move || crate::storage::check_and_emit(path, fresh, reset)); + } + "storagemove" => { + let path = (!c.path.trim().is_empty()).then(|| c.path.clone()); + let fresh = c.value["fresh"] == true; + crate::storage::start_move(path, fresh); + } + "storagereset" => crate::storage::reset(), + "storageretry" => crate::storage::retry(), + "storageremoveold" => crate::storage::remove_old(), // Settings → Diagnostics and an error's Details: crate::diag. cmd @ ("diaglogs" | "diagreport" | "diagsend" | "diagcrashes" | "diagsendcrash" | "diagfolder") => { crate::diag::handle(cmd, c.name, c.id, &c.value); diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index eb9a4af57..d8f98acd4 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -117,6 +117,9 @@ mod refuse; // path mapping, buffer decoding and coalescing tested on any host. #[cfg(any(windows, test))] mod watch; +// Settings → Storage: custom WSL distro location in %LOCALAPPDATA%\Kiri\storage.json. +#[cfg(any(windows, test))] +mod storage; // Settings → Import from Docker Desktop: the Mac's and Linux's own // crates/kiri/src/import.rs, through the docker CLI's contexts. #[cfg(windows)] diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 93625efb4..cfdc000f7 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -1393,6 +1393,13 @@ impl Hub { if cfg.distro.is_none() { return Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri is not set up yet")); } + // Never boot WSL while storage is moving or its custom drive is offline. + if crate::storage::moving() { + return Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri is moving its data")); + } + if let Some(missing) = crate::storage::unavailable() { + return Err(io::Error::new(io::ErrorKind::NotConnected, crate::storage::unavailable_message(&missing))); + } // The last one has gone (WSL restarted, Windows slept): a docker // client is waiting, so a new one starts now, and the log says why; // once, not again for each try while new ones die as they start. @@ -1699,6 +1706,18 @@ fn serve(hub: &Hub, pipe: Pipe) { fn serve_shared(hub: &Hub, pipe: Arc) { let flush = FlushOnDrop(pipe); let pipe = &flush.0; + if crate::storage::moving() { + if refuse_new(pipe, "Kiri is moving its data to another folder: try again when Settings → Storage says it's done") { + linger(pipe); + } + return; + } + if let Some(missing) = crate::storage::unavailable() { + if refuse_new(pipe, &crate::storage::unavailable_message(&missing)) { + linger(pipe); + } + return; + } // A bridge can die between hub.bridge() and the insert below: while WSL // is still booting, wsl.exe exits at once. `replies` ends every // connection it finds when that happens, but one registered after that diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index e66b57e7d..f67ff70fd 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -121,7 +121,7 @@ static STATE: Mutex> = Mutex::new(None); static BUSY: AtomicBool = AtomicBool::new(false); static CANCEL: AtomicBool = AtomicBool::new(false); -fn dir() -> PathBuf { +pub(crate) fn dir() -> PathBuf { std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri")).unwrap_or_else(|| PathBuf::from(".")) } @@ -202,6 +202,11 @@ fn quiet(program: &str) -> Command { /// as UTF-16LE, and anything else as UTF-8. UTF-16 with no ASCII and no BOM /// at all is the one thing this cannot tell from UTF-8. NULs and a leading /// BOM are dropped either way. +/// Combines wsl.exe's stdout and stderr, decoding UTF-16LE when WSL speaks it. +pub(crate) fn wsl_output(stdout: &[u8], stderr: &[u8]) -> String { + wsl_text(stdout) + &wsl_text(stderr) +} + fn wsl_text(bytes: &[u8]) -> String { let (bytes, bom) = bytes.strip_prefix(&[0xFF, 0xFE]).map_or((bytes, false), |rest| (rest, true)); let text = if bom || looks_utf16(bytes) { @@ -345,7 +350,12 @@ fn restarted_since(at: u64) -> bool { } /// Whether the window should open on setup rather than Kiri. +/// Never opens setup (which could re-create an empty distro) when a custom +/// storage folder in `storage.json` is currently offline. pub fn needed() -> bool { + if crate::storage::unavailable().is_some() { + return false; + } let s = saved(); needs_setup(s.done, s.distro.as_deref(), distros) } diff --git a/crates/kiri-win/src/storage.rs b/crates/kiri-win/src/storage.rs new file mode 100644 index 000000000..fc801bb23 --- /dev/null +++ b/crates/kiri-win/src/storage.rs @@ -0,0 +1,767 @@ +//! Settings → Storage on Windows: where Kiri keeps its WSL 2 distro VHDX +//! (`ext4.vhdx`), recorded in `%LOCALAPPDATA%\Kiri\storage.json` when changed +//! from the default `%LOCALAPPDATA%\Kiri\wsl\`. +//! +//! Users who never change storage have no `storage.json` and zero behavior +//! change. When a custom path is configured, it must hold `.kiri-storage`: +//! if an external drive letter is unplugged or offline, Kiri refuses to +//! wipe or re-create an empty distro, surfaces `state: "unavailable"` in +//! Settings → Storage, and offers Retry, Change…, or Reset to default. +//! +//! Moving the distro tries native `wsl.exe --manage --move ` +//! first (Windows 11 / modern WSL 2), falling back to `wsl.exe --export` +//! (with `--vhd` when supported, else `.tar`) -> `wsl.exe --unregister` -> +//! `wsl.exe --import --version 2`, rolling back to +//! the original folder if `--import` fails. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +/// The settings file, under `%LOCALAPPDATA%\Kiri`. +pub const FILE: &str = "storage.json"; + +/// Written into a custom storage folder once a move completes so an offline +/// drive or an unrelated non-empty folder is never mistaken for Kiri's data. +pub const MARKER: &str = ".kiri-storage"; + +const MOVING: &str = ".kiri-moving"; +const IGNORED: &[&str] = &["desktop.ini", "Thumbs.db", MOVING, MARKER]; + +/// What `storage.json` holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Choice { + pub path: PathBuf, + pub previous: Option, +} + +/// Result of checking a target path before moving. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checked { + pub needed: u64, + pub free: u64, + pub replaces: bool, +} + +/// Whether `dir` holds the marker written by a completed move. +pub fn has_marker(dir: &Path) -> bool { + dir.join(MARKER).is_file() +} + +/// Atomically writes `bytes` to `file` via a sibling temp file + rename. +pub fn write_atomic(file: &Path, bytes: &[u8]) -> io::Result<()> { + if let Some(parent) = file.parent() { + fs::create_dir_all(parent)?; + } + let tmp = file.with_extension(format!("tmp-{}", std::process::id())); + let write_res = (|| -> io::Result<()> { + let mut f = fs::File::create(&tmp)?; + io::Write::write_all(&mut f, bytes)?; + f.sync_all() + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + // On Windows fs::rename fails if the destination exists; remove and rename + // only after the temp file is flushed, keeping the window minimal. + #[cfg(windows)] + if file.exists() { + let _ = fs::remove_file(file); + } + fs::rename(&tmp, file).inspect_err(|_| { + let _ = fs::remove_file(&tmp); + }) +} + +/// Writes the marker into `dir`. +pub fn write_marker(dir: &Path) -> io::Result<()> { + write_atomic(&dir.join(MARKER), b"{\"kiri\":1}\n") +} + +/// Reads `Choice` from `file`; `None` when absent. +pub fn read_at(file: &Path) -> io::Result> { + match fs::read(file) { + Ok(bytes) => { + let v: serde_json::Value = serde_json::from_slice(&bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", file.display())))?; + let path = v["path"] + .as_str() + .map(PathBuf::from) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("{}: missing path", file.display())))?; + let previous = v["previous"].as_str().map(PathBuf::from); + Ok(Some(Choice { path, previous })) + } + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Writes `Choice` atomically to `file`. +pub fn write_at(file: &Path, choice: &Choice) -> io::Result<()> { + let mut map = serde_json::Map::new(); + map.insert("path".into(), serde_json::Value::String(choice.path.to_string_lossy().into_owned())); + if let Some(prev) = &choice.previous { + map.insert("previous".into(), serde_json::Value::String(prev.to_string_lossy().into_owned())); + } + let bytes = serde_json::to_vec_pretty(&serde_json::Value::Object(map)).map_err(io::Error::other)?; + write_atomic(file, &bytes) +} + +/// Removes `file` if present. +pub fn clear_at(file: &Path) -> io::Result<()> { + match fs::remove_file(file) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +/// Resolves whether a configured choice is currently offline / unavailable. +/// Returns `Some(missing_path)` if `choice` points to a non-default folder +/// whose `.kiri-storage` marker is missing (for example an unplugged drive). +pub fn unavailable_for(choice: Option<&Choice>, default: &Path) -> Option { + let c = choice?; + if same_path(&c.path, default) || has_marker(&c.path) { + None + } else { + Some(c.path.clone()) + } +} + +/// Case-insensitive normalized comparison suitable for Windows paths. +pub fn same_path(a: &Path, b: &Path) -> bool { + norm_key(a) == norm_key(b) +} + +/// Whether `child` is inside `parent` (strictly or equal), case-insensitively. +pub fn is_within(child: &Path, parent: &Path) -> bool { + let c = norm_key(child); + let p = norm_key(parent); + if c == p { + return true; + } + let prefix = if p.ends_with('/') { p } else { format!("{p}/") }; + c.starts_with(&prefix) +} + +fn norm_key(p: &Path) -> String { + let s = p.to_string_lossy().replace('\\', "/"); + let s = s.trim_end_matches('/'); + // Preserve root drive like "c:" -> "c:/" + if s.len() == 2 && s.as_bytes()[1] == b':' { + format!("{}/", s.to_ascii_lowercase()) + } else { + s.to_ascii_lowercase() + } +} + +/// Whether `raw` is an absolute local Windows drive path (`C:\...`), +/// rejecting relative paths, parent traversal (`..`), and UNC shares (`\\...`). +pub fn is_local_windows_path(raw: &str) -> bool { + let s = raw.trim(); + if s.starts_with(r"\\") || s.starts_with("//") { + return false; + } + let bytes = s.as_bytes(); + if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' || (bytes[2] != b'\\' && bytes[2] != b'/') { + return false; + } + !s.split(['\\', '/']).any(|seg| seg == "..") +} + +/// Filesystems that cannot reliably hold a WSL 2 `ext4.vhdx`. +pub fn refused_fs(name: &str) -> bool { + let n = name.trim().to_ascii_lowercase(); + matches!(n.as_str(), "fat" | "fat32" | "exfat" | "msdos" | "vfat") +} + +/// Margin kept free beside the data: 10% plus 1 GB. +pub fn headroom(bytes: u64) -> u64 { + bytes / 10 + 1_000_000_000 +} + +fn format_gb(bytes: u64) -> String { + format!("{:.1} GB", bytes as f64 / 1e9) +} + +/// Pure validation helper shared between Windows production code and host tests. +pub fn validate_target( + current: &Path, + target_raw: &str, + used_bytes: u64, + copy: bool, + fs_type: impl FnOnce(&Path) -> io::Result, + free_bytes: impl FnOnce(&Path) -> io::Result, + probe_write: impl FnOnce(&Path) -> io::Result<()>, +) -> Result { + let trimmed = target_raw.trim(); + if !is_local_windows_path(trimmed) { + return Err(format!("{trimmed} isn't a local drive path: choose a folder on a local drive (for example D:\\Kiri)")); + } + let target = PathBuf::from(trimmed); + if same_path(current, &target) { + return Err(format!("Kiri's data is already in {}", target.display())); + } + if is_within(&target, current) { + return Err(format!("{} is inside Kiri's data folder {}: choose a folder outside it", target.display(), current.display())); + } + if is_within(current, &target) { + return Err(format!("Kiri's data folder {} is inside {}: choose another folder", current.display(), target.display())); + } + let mut replaces = false; + if target.symlink_metadata().is_ok() { + if !target.is_dir() { + return Err(format!("{} isn't a folder", target.display())); + } + let others = fs::read_dir(&target) + .map_err(|e| format!("{}: {e}", target.display()))? + .flatten() + .any(|e| { + let name = e.file_name(); + !IGNORED.iter().any(|n| name.eq_ignore_ascii_case(n)) + }); + if has_marker(&target) { + replaces = others; + } else if others { + return Err(format!("{} isn't empty and doesn't hold Kiri's data: choose an empty folder, or make a new one", target.display())); + } + } + let near = target.ancestors().find(|p| p.is_dir()).ok_or_else(|| format!("{} isn't on any connected drive", target.display()))?; + let fs = fs_type(near).map_err(|e| format!("{}: {e}", near.display()))?; + if refused_fs(&fs) { + return Err(format!("{} is on a {fs} drive, which can't hold Kiri's WSL disk: choose a folder on an NTFS drive", target.display())); + } + probe_write(near).map_err(|e| format!("Kiri can't write in {}: {e}", near.display()))?; + let needed = if copy { used_bytes + headroom(used_bytes) } else { headroom(0) }; + let free = free_bytes(near).map_err(|e| format!("{}: {e}", near.display()))?; + if free < needed { + return Err(format!("{} has {} free, and Kiri's data needs {} there", near.display(), format_gb(free), format_gb(needed))); + } + Ok(Checked { needed, free, replaces }) +} + +#[cfg(windows)] +mod imp { + use super::*; + use serde_json::{Value, json}; + use std::os::windows::ffi::OsStrExt; + use std::os::windows::process::CommandExt; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Mutex, PoisonError}; + + use crate::engine::{Cmd, emit, notice, send, tr, trf}; + + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + + #[derive(Default)] + struct Moving { + to: Option, + phase: &'static str, + done: u64, + total: u64, + error: Option, + } + + static MOVE: Mutex = Mutex::new(Moving { to: None, phase: "", done: 0, total: 0, error: None }); + static ACTIVE: AtomicBool = AtomicBool::new(false); + + fn state() -> std::sync::MutexGuard<'static, Moving> { + MOVE.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn moving() -> bool { + ACTIVE.load(Ordering::SeqCst) + } + + fn config_path() -> PathBuf { + crate::setup::dir().join(FILE) + } + + fn distro_name() -> String { + crate::engine::distro().unwrap_or_else(|| crate::setup::KIRI_DISTRO.to_owned()) + } + + pub fn default_root() -> PathBuf { + crate::setup::dir().join("wsl").join(distro_name()) + } + + pub fn read() -> Option { + read_at(&config_path()).ok().flatten() + } + + /// Returns `Some(missing_path)` if `storage.json` configures a custom + /// folder whose drive is currently offline / marker is missing. + pub fn unavailable() -> Option { + let choice = read(); + unavailable_for(choice.as_ref(), &default_root()) + } + + pub fn unavailable_message(missing: &Path) -> String { + format!("Kiri's data folder {} isn't available: connect its drive, or choose Settings → Storage → Reset to default", missing.display()) + } + + fn current_root() -> PathBuf { + read().map(|c| c.path).unwrap_or_else(default_root) + } + + fn dir_size(dir: &Path) -> u64 { + let Ok(entries) = fs::read_dir(dir) else { return 0 }; + let mut total = 0u64; + for e in entries.flatten() { + let Ok(m) = e.metadata() else { continue }; + if m.is_file() { + total = total.saturating_add(m.len()); + } else if m.is_dir() { + total = total.saturating_add(dir_size(&e.path())); + } + } + total + } + + fn wide(p: &Path) -> Vec { + p.as_os_str().encode_wide().chain(std::iter::once(0)).collect() + } + + fn free_space(dir: &Path) -> io::Result { + use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW; + let w = wide(dir); + let mut avail = 0u64; + // SAFETY: `w` is NUL-terminated UTF-16 and `avail` is a valid out pointer. + if unsafe { GetDiskFreeSpaceExW(w.as_ptr(), &mut avail, std::ptr::null_mut(), std::ptr::null_mut()) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(avail) + } + + fn fs_name(dir: &Path) -> io::Result { + use windows_sys::Win32::Storage::FileSystem::{GetVolumeInformationW, GetVolumePathNameW}; + let w = wide(dir); + let mut root = [0u16; 260]; + // SAFETY: valid UTF-16 path and output buffer of length 260. + if unsafe { GetVolumePathNameW(w.as_ptr(), root.as_mut_ptr(), root.len() as u32) } == 0 { + return Err(io::Error::last_os_error()); + } + let mut fs_buf = [0u16; 64]; + // SAFETY: `root` is NUL-terminated; `fs_buf` receives the filesystem name. + if unsafe { + GetVolumeInformationW( + root.as_ptr(), + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + fs_buf.as_mut_ptr(), + fs_buf.len() as u32, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let end = fs_buf.iter().position(|&c| c == 0).unwrap_or(fs_buf.len()); + Ok(String::from_utf16_lossy(&fs_buf[..end])) + } + + fn probe_writable(dir: &Path) -> io::Result<()> { + let probe = dir.join(format!(".kiri-probe-{}", std::process::id())); + let res = (|| { + let mut f = fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + io::Write::write_all(&mut f, b"kiri")?; + f.sync_all() + })(); + let _ = fs::remove_file(&probe); + res + } + + pub fn report() -> Value { + let default = default_root(); + let choice = read(); + let missing = unavailable_for(choice.as_ref(), &default); + let is_missing = missing.is_some(); + let root = missing.unwrap_or_else(|| choice.as_ref().map(|c| c.path.clone()).unwrap_or_else(|| default.clone())); + let custom = !same_path(&root, &default); + let old = choice.and_then(|c| c.previous).filter(|p| !same_path(p, &root) && p.is_dir()); + let active = moving(); + let m = state(); + let near = root.ancestors().find(|p| p.is_dir()); + json!({ + "type": "storage", + "path": root, + "default": default, + "custom": custom, + "env": false, + "state": if is_missing { "unavailable" } else if active { "moving" } else { "ok" }, + "used": (!is_missing && !active).then(|| dir_size(&root)), + "free": if is_missing { None } else { near.and_then(|p| free_space(p).ok()) }, + "fs": if is_missing { None } else { near.and_then(|p| fs_name(p).ok()) }, + "moving": m.to.as_ref().filter(|_| active).map(|to| json!({"to": to, "phase": m.phase, "done": m.done, "total": m.total})), + "error": m.error, + "old": old, + }) + } + + pub fn emit_report() { + emit(report().to_string()); + } + + pub fn check_and_emit(path: Option, fresh: bool, reset: bool) { + let default = default_root(); + let current = current_root(); + let target_str = match path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => p.to_owned(), + None => default.to_string_lossy().into_owned(), + }; + let is_unavail = unavailable().is_some(); + let used = if is_unavail || fresh { 0 } else { dir_size(¤t) }; + match validate_target(¤t, &target_str, used, !is_unavail && !fresh, fs_name, free_space, probe_writable) { + Ok(c) => emit(json!({"type": "storagecheck", "path": target_str, "needed": c.needed, "free": c.free, "replaces": c.replaces, "reset": reset}).to_string()), + Err(e) => emit(json!({"type": "storagecheck", "path": target_str, "error": e, "reset": reset}).to_string()), + } + } + + fn wsl_run(args: &[&std::ffi::OsStr]) -> io::Result { + let mut cmd = crate::win::tool("wsl.exe"); + cmd.creation_flags(CREATE_NO_WINDOW).args(args); + let out = cmd.output()?; + let text = crate::setup::wsl_output(&out.stdout, &out.stderr); + if out.status.success() { + Ok(text) + } else { + let line = text.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("wsl.exe failed"); + Err(io::Error::other(line.to_owned())) + } + } + + fn set_phase(phase: &'static str, done: u64, total: u64) { + { + let mut m = state(); + m.phase = phase; + m.done = done; + m.total = total; + } + emit_report(); + } + + pub fn start_move(path: Option, fresh: bool) { + std::thread::Builder::new() + .name("kiri-storage-move".into()) + .spawn(move || run_move(path, fresh)) + .ok(); + } + + fn run_move(path: Option, fresh: bool) { + let default = default_root(); + let current = current_root(); + let distro = distro_name(); + let target_str = match path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => p.to_owned(), + None => default.to_string_lossy().into_owned(), + }; + let is_unavail = unavailable().is_some(); + let used = if is_unavail || fresh { 0 } else { dir_size(¤t) }; + if let Err(e) = validate_target(¤t, &target_str, used, !is_unavail && !fresh, fs_name, free_space, probe_writable) { + emit(notice("error", &e)); + emit_report(); + return; + } + let target = PathBuf::from(&target_str); + if ACTIVE.swap(true, Ordering::SeqCst) { + emit(notice("error", &tr("Kiri's data is moving already"))); + return; + } + *state() = Moving { to: Some(target.clone()), phase: "stopping", done: 0, total: used, error: None }; + emit_report(); + + let result = (|| -> io::Result> { + let running = if !is_unavail && crate::client::alive_quick() { + let list = crate::client::get_quick("/containers/json").ok(); + let ids: Vec = list + .as_ref() + .and_then(|v| v.as_array()) + .map(|a| a.iter().filter_map(|c| c["Id"].as_str().map(str::to_owned)).collect()) + .unwrap_or_default(); + let _ = crate::client::request("POST", "/kiri/stop", None); + ids + } else { + Vec::new() + }; + crate::serve::renew_bridge(); + let _ = wsl_run(&[std::ffi::OsStr::new("--terminate"), std::ffi::OsStr::new(&distro)]); + fs::create_dir_all(&target)?; + + if is_unavail || fresh { + set_phase("switching", 0, 0); + // Switching to a fresh store on Kiri Linux: verify bundle before touching WSL. + let tar = crate::setup::verified("kiri-linux.tar.gz")?; + let _ = wsl_run(&[std::ffi::OsStr::new("--unregister"), std::ffi::OsStr::new(&distro)]); + wsl_run(&[ + std::ffi::OsStr::new("--import"), + std::ffi::OsStr::new(&distro), + target.as_os_str(), + tar.as_os_str(), + std::ffi::OsStr::new("--version"), + std::ffi::OsStr::new("2"), + ])?; + } else { + set_phase("copying", 0, used); + move_distro(&distro, ¤t, &target)?; + } + + set_phase("switching", 0, 0); + write_marker(&target)?; + if same_path(&target, &default) { + clear_at(&config_path())?; + } else { + write_at(&config_path(), &Choice { path: target.clone(), previous: None })?; + } + + set_phase("restarting", 0, 0); + crate::serve::renew_bridge(); + crate::engine::ensure_daemon()?; + Ok(if fresh || is_unavail { Vec::new() } else { running }) + })(); + + match result { + Ok(running) => { + { + let mut m = state(); + m.to = None; + m.phase = ""; + m.error = None; + } + ACTIVE.store(false, Ordering::SeqCst); + for id in &running { + let _ = crate::client::request("POST", &format!("/containers/{id}/start"), None); + } + emit(notice("ok", &trf("Kiri's data moved to {path}", &[("path", &target.display().to_string())]))); + emit_report(); + send(Cmd::Refresh); + } + Err(e) => { + crate::serve::log(&format!("storage move failed: {e}")); + { + let mut m = state(); + m.to = None; + m.phase = ""; + m.error = Some(e.to_string()); + } + ACTIVE.store(false, Ordering::SeqCst); + let _ = crate::engine::ensure_daemon(); + emit(notice("error", &e.to_string())); + emit_report(); + } + } + } + + /// Moves WSL distro `distro` from `old_dir` to `target`. Tries native + /// `wsl --manage --move ` first, then falls back to + /// `--export` -> `--unregister` -> `--import` with rollback on failure. + fn move_distro(distro: &str, old_dir: &Path, target: &Path) -> io::Result<()> { + let managed = wsl_run(&[ + std::ffi::OsStr::new("--manage"), + std::ffi::OsStr::new(distro), + std::ffi::OsStr::new("--move"), + target.as_os_str(), + ]); + if managed.is_ok() { + return Ok(()); + } + // Fallback: export into staging folder inside target, unregister, import. + let staging = target.join(MOVING); + let _ = fs::remove_dir_all(&staging); + fs::create_dir_all(&staging)?; + let vhd_file = staging.join("distro.vhdx"); + let tar_file = staging.join("distro.tar"); + let (archive, is_vhd) = match wsl_run(&[ + std::ffi::OsStr::new("--export"), + std::ffi::OsStr::new(distro), + vhd_file.as_os_str(), + std::ffi::OsStr::new("--vhd"), + ]) { + Ok(_) if vhd_file.is_file() && fs::metadata(&vhd_file).is_ok_and(|m| m.len() > 0) => (vhd_file, true), + _ => { + let _ = fs::remove_file(&vhd_file); + if let Err(e) = wsl_run(&[std::ffi::OsStr::new("--export"), std::ffi::OsStr::new(distro), tar_file.as_os_str()]) { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + if !tar_file.is_file() || fs::metadata(&tar_file).is_ok_and(|m| m.len() == 0) { + let _ = fs::remove_dir_all(&staging); + return Err(io::Error::other("WSL export produced an empty archive")); + } + (tar_file, false) + } + }; + if let Err(e) = wsl_run(&[std::ffi::OsStr::new("--unregister"), std::ffi::OsStr::new(distro)]) { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + let import_to = |dest: &Path| { + let mut args: Vec<&std::ffi::OsStr> = vec![ + std::ffi::OsStr::new("--import"), + std::ffi::OsStr::new(distro), + dest.as_os_str(), + archive.as_os_str(), + std::ffi::OsStr::new("--version"), + std::ffi::OsStr::new("2"), + ]; + if is_vhd { + args.push(std::ffi::OsStr::new("--vhd")); + } + wsl_run(&args) + }; + if let Err(e) = import_to(target) { + // Roll back: restore the distro at its original folder before deleting staging. + let _ = fs::create_dir_all(old_dir); + let _ = import_to(old_dir); + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + let _ = fs::remove_dir_all(&staging); + Ok(()) + } + + pub fn retry() { + std::thread::spawn(|| { + if let Some(missing) = unavailable() { + emit(notice("error", &unavailable_message(&missing))); + emit_report(); + return; + } + crate::serve::renew_bridge(); + match crate::engine::ensure_daemon() { + Ok(()) => { + emit(notice("ok", &tr("Storage is available again"))); + emit_report(); + send(Cmd::Refresh); + } + Err(e) => { + emit(notice("error", &e.to_string())); + emit_report(); + } + } + }); + } + + pub fn reset() { + if unavailable().is_some() { + start_move(None, true); + } else { + start_move(None, false); + } + } + + pub fn remove_old() { + std::thread::spawn(|| { + if moving() { + emit(notice("error", &tr("Kiri's data is moving already"))); + return; + } + let Some(mut choice) = read() else { return }; + let Some(old) = choice.previous.clone() else { return }; + let current = current_root(); + if same_path(&old, ¤t) || is_within(&old, ¤t) || is_within(¤t, &old) { + emit(notice("error", &format!("{} holds Kiri's data now", old.display()))); + return; + } + if old.exists() { + if !has_marker(&old) { + emit(notice("error", &format!("{} doesn't look like Kiri's old data; remove it yourself if you're sure", old.display()))); + return; + } + if let Err(e) = fs::remove_dir_all(&old) { + emit(notice("error", &format!("{}: {e}", old.display()))); + return; + } + } + choice.previous = None; + let _ = if same_path(&choice.path, &default_root()) { clear_at(&config_path()) } else { write_at(&config_path(), &choice) }; + emit(notice("ok", &tr("Old data removed"))); + emit_report(); + }); + } +} + +#[cfg(windows)] +pub use imp::*; + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-win-storage-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn offline_custom_drive_is_unavailable_and_never_created() { + let d = scratch("unavail"); + let file = d.join(FILE); + let default = d.join("wsl/kiri"); + let offline = d.join("external-drive/kiri"); + write_at(&file, &Choice { path: offline.clone(), previous: None }).unwrap(); + assert_eq!(unavailable_for(read_at(&file).unwrap().as_ref(), &default), Some(offline.clone())); + assert!(!offline.exists(), "offline path must never be created"); + fs::create_dir_all(&offline).unwrap(); + write_marker(&offline).unwrap(); + assert_eq!(unavailable_for(read_at(&file).unwrap().as_ref(), &default), None); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn no_storage_json_uses_default_without_marker() { + let d = scratch("default"); + let file = d.join(FILE); + assert_eq!(read_at(&file).unwrap(), None); + assert_eq!(unavailable_for(None, &d.join("wsl/kiri")), None); + assert!(!file.exists()); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn validates_windows_paths_case_insensitively_and_refuses_fat_exfat_unc() { + assert!(is_local_windows_path(r"D:\Kiri")); + assert!(is_local_windows_path("E:/kiri/data")); + assert!(!is_local_windows_path(r"\\nas\share\kiri")); + assert!(!is_local_windows_path(r"relative\kiri")); + assert!(!is_local_windows_path(r"D:\Kiri\..\Other")); + assert!(same_path(Path::new(r"C:\Users\Me\Kiri"), Path::new(r"c:\users\me\kiri\"))); + assert!(is_within(Path::new(r"D:\Kiri\sub"), Path::new(r"d:\kiri"))); + assert!(!is_within(Path::new(r"D:\Kiri2"), Path::new(r"d:\kiri"))); + assert!(refused_fs("FAT32") && refused_fs("exFAT") && refused_fs("FAT")); + assert!(!refused_fs("NTFS") && !refused_fs("ReFS")); + } + + #[test] + fn choice_round_trips_atomically_and_clears() { + let d = scratch("roundtrip"); + let file = d.join(FILE); + let c = Choice { path: PathBuf::from(r"E:\Kiri"), previous: Some(PathBuf::from(r"C:\Users\u\AppData\Local\Kiri\wsl\kiri")) }; + write_at(&file, &c).unwrap(); + assert_eq!(read_at(&file).unwrap(), Some(c)); + clear_at(&file).unwrap(); + assert_eq!(read_at(&file).unwrap(), None); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn validate_target_checks_path_fs_space_and_contents() { + let ok_fs = |_: &Path| Ok("NTFS".to_owned()); + let plenty = |_: &Path| Ok(100_000_000_000u64); + let writable = |_: &Path| Ok(()); + let cur = Path::new(r"C:\Users\u\AppData\Local\Kiri\wsl\kiri"); + assert!(validate_target(cur, r"relative\path", 0, true, ok_fs, plenty, writable).unwrap_err().contains("local drive path")); + assert!(validate_target(cur, r"\\nas\share\kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("local drive path")); + assert!(validate_target(cur, r"c:\users\u\appdata\local\kiri\wsl\kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("already in")); + assert!(validate_target(cur, r"C:\Users\u\AppData\Local\Kiri\wsl\kiri\sub", 0, true, ok_fs, plenty, writable).unwrap_err().contains("inside Kiri's data folder")); + assert!(validate_target(cur, r"C:\Users\u\AppData\Local\Kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("is inside")); + assert_eq!(headroom(10_000_000_000), 2_000_000_000); + // On non-Windows hosts a Windows drive path like D:\ has no existing ancestor, so check the error cleanly. + let r = validate_target(cur, r"D:\Kiri", 5_000_000_000, true, |_| Ok("exFAT".into()), plenty, writable); + assert!(r.is_err()); + let _ = (Checked { needed: 0, free: 0, replaces: false }, IGNORED, MOVING, format_gb(1_000_000_000)); + } +} diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index d2830ebf2..067b0436e 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -150,6 +150,11 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea http::error(w, 403, "this is changed in Kiri's window or with the kiri command on this machine, not from a container")?; return Ok(Next::Close); } + // While Settings → Storage moves the data, nothing may change it. + if super::storage::moving() && !matches!(m, "GET" | "HEAD") { + super::storage::refuse_while_moving(w)?; + return Ok(Next::Close); + } if let Some(done) = super::ops::route(req, engine, w) { return done; } @@ -245,6 +250,12 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea ("POST", "/build") => return super::builder::build(req, engine, w, r), ("POST", "/build/cancel") => return reply(w, super::builder::cancel(req, engine), 200), ("POST", "/build/prune") => return reply(w, super::builder::prune(req, engine), 200), + // Settings → Storage: where the data is, and moving it (storage.rs). + ("GET", "/kiri/storage") => return reply(w, Ok(super::storage::report(engine)), 200), + ("POST", "/kiri/storage/check") => return reply(w, super::storage::check_request(req, engine), 200), + ("POST", "/kiri/storage") => return reply(w, super::storage::start(req, engine), 202), + ("POST", "/kiri/storage/reset") => return reply(w, super::storage::start_reset(engine), 202), + ("DELETE", "/kiri/storage/old") => return reply(w, super::storage::remove_old(engine), 200), ("GET", "/kiri/builder") => return reply(w, Ok(super::builder::settings_report(engine)), 200), ("POST", "/kiri/builder") => return reply(w, super::builder::set_settings(req).map(|()| super::builder::settings_report(engine)), 200), ("GET", "/kiri/watch-roots") => return reply(w, Ok(watch_roots(engine)), 200), @@ -459,7 +470,7 @@ fn parse_release(raw: &str) -> Option { /// `KiriVersion`, and a component named "Kiri". Moves with `API_VERSION`. pub const ENGINE_VERSION: &str = "27.5.1"; -fn version() -> Value { +pub(super) fn version() -> Value { let kiri = env!("CARGO_PKG_VERSION"); json!({ "Platform": {"Name": "Kiri"}, diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 7d408cb3a..7e4d66a85 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -2070,6 +2070,57 @@ impl Engine { } } + /// Settings → Storage, before the data folder is copied: every container + /// stopped and the VM off, as for a Stop, but without the file that + /// keeps a Stop across restarts; nothing boots the VM again until + /// `resume_after_move`. The container list is written and synced, so + /// the copy has it as it stands. Returns the containers that were + /// running, and whether Kiri was stopped already. + pub fn park_for_move(&self) -> Result<(Vec, bool), Error> { + let running = self.each(|c| (c.status == Status::Running).then(|| c.id.clone())); + let was_stopped = self.stopped.swap(true, std::sync::atomic::Ordering::SeqCst); + if let Err(e) = self.sleep_now() { + self.resume_after_move(was_stopped, running); + return Err(e); + } + self.save(); + self.sync_records(); + Ok((running, was_stopped)) + } + + /// A move that did not finish: Kiri carries on where it was, and the + /// containers that were running start again, held ones first (in the + /// order that starts joined containers after the ones they join). + pub fn resume_after_move(&self, was_stopped: bool, running: Vec) { + if was_stopped { + return; + } + self.stopped.store(false, std::sync::atomic::Ordering::SeqCst); + let mut ids = std::mem::take(&mut *self.held_restarts.lock().unwrap_or_else(|e| e.into_inner())); + for id in running { + if !ids.contains(&id) { + ids.push(id); + } + } + if let Some(me) = self.me.get().and_then(Weak::upgrade) { + std::thread::spawn(move || me.start_again(&ids)); + } + } + + /// Starts `ids` that aren't running: after a move, the containers that + /// ran before it (a restart policy may have started some already). + pub fn start_again(&self, ids: &[String]) { + for id in ids { + let running = self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running); + if running { + continue; + } + if let Err(e) = self.start(id) { + crate::diag::warn!("container did not start again after the move", id = &id[..id.len().min(12)], error = format!("{e:?}")); + } + } + } + /// Starts the held containers (`held_restarts`), one at a time, each /// taken from the list as it starts: Start, or `retry_held` once the VM /// boots. A Stop meanwhile ends it: the rest stay held for the next diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index 4d46d215f..f41ce1887 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -30,8 +30,10 @@ pub(crate) mod ports; mod pulls; mod seccomp; mod seccomp_names; +mod storage; pub mod time; mod top; +mod treecopy; #[cfg(target_os = "macos")] mod usb; mod vmcpu; @@ -201,9 +203,27 @@ pub fn run(_args: &[String]) -> io::Result<()> { }; kiri_image::store::set_error_log(|message| diag::error!("image store", detail = message)); - let store = kiri_image::Store::open(kiri_image::Store::default_root()?)?; + let root = match kiri_image::Store::default_root() { + Ok(root) => root, + Err(e) => match kiri_image::storage::unavailable(&e) { + Some(missing) => { + return unavailable( + &listener, + socket, + set, + missing.to_owned(), + #[cfg(target_os = "linux")] + &gate, + ); + } + None => return Err(e), + }, + }; + let store = kiri_image::Store::open(root)?; let engine = engine::Engine::boot(store).inspect_err(|e| diag::error!("engine did not start", error = e))?; diag::info!("engine ready", version = env!("CARGO_PKG_VERSION"), ms = t0.elapsed().as_millis(), socket = format!("unix://{}", socket.display())); + // Settings → Storage moved the data and started this daemon on it. + storage::after_restart(&engine); // Crash files from earlier runs, if the person said they may go. diag::report::spawn_crash_sender(Duration::from_secs(30), Some(Duration::from_secs(6 * 3600))); // Container files in Finder, at ~/Kiri. A Linux host has them on its @@ -305,11 +325,27 @@ fn accept( engine: &std::sync::Arc, #[cfg(target_os = "linux")] gate: &Option>, who: caller::Caller, +) { + let engine = engine.clone(); + serve_each( + listener, + #[cfg(target_os = "linux")] + gate, + std::sync::Arc::new(move |conn| { + let _ = api::serve(conn, engine.clone(), who.clone()); + }), + ); +} + +/// Hands each connection `listener` takes to `serve`, on a thread of its own. +fn serve_each( + listener: &UnixListener, + #[cfg(target_os = "linux")] gate: &Option>, + serve: std::sync::Arc, ) { for conn in listener.incoming() { let Ok(conn) = conn else { continue }; - let engine = engine.clone(); - let who = who.clone(); + let serve = serve.clone(); #[cfg(target_os = "linux")] let gate = gate.clone(); let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { @@ -319,7 +355,7 @@ fn accept( let Ok(_seat) = admit_connection(&gate, &conn) else { return; }; - let _ = api::serve(conn, engine, who); + serve(conn); }); if let Err(e) = spawned { diag::error!("cannot start a connection thread", error = e); @@ -327,6 +363,38 @@ fn accept( } } +/// The data folder chosen in Settings → Storage isn't there (its drive +/// isn't connected): no empty store is made in its place, and the daemon +/// stays up rather than exiting (launchd and systemd would only start it +/// again and again), answering what Settings → Storage needs to say so +/// and offer Retry or Reset to default (storage::serve_unavailable). +fn unavailable( + listener: &UnixListener, + socket: PathBuf, + set: libc::sigset_t, + missing: PathBuf, + #[cfg(target_os = "linux")] gate: &Option>, +) -> io::Result<()> { + diag::error!("Kiri's data folder isn't available: the engine waits for it, or for Settings → Storage", folder = missing.display()); + std::thread::Builder::new().name("kiri-signals".into()).spawn(move || { + let mut sig = 0; + // SAFETY: waits on the blocked set; writes the signal number to `sig`. + unsafe { libc::sigwait(&set, &mut sig) }; + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(caller::container_socket(&socket)); + std::process::exit(0); + })?; + serve_each( + listener, + #[cfg(target_os = "linux")] + gate, + std::sync::Arc::new(move |conn| { + let _ = storage::serve_unavailable(conn, &missing); + }), + ); + Ok(()) +} + /// When the app this daemon runs from is deleted (appwatch.rs): docker /// build handed back (buildwith.rs: what was there before; the choice /// stays, so the app taken up again takes it again), and the engine stops. diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs new file mode 100644 index 000000000..93418540e --- /dev/null +++ b/crates/kiri/src/daemon/storage.rs @@ -0,0 +1,994 @@ +//! Settings → Storage on a Mac and a Linux host: where Kiri keeps its +//! images, containers and volumes, and moving them to another folder (an +//! external drive, say). Windows moves its WSL distro instead +//! (crates/kiri-win/src/storage.rs). +//! +//! `GET /kiri/storage` says where the data is, what it takes and what is +//! free there, and how a move goes. `POST /kiri/storage/check` checks a +//! folder; `POST /kiri/storage` moves the data there: +//! +//! 1. Every container stops (those that ran are noted) and the VM powers +//! off (`Engine::park_for_move`). +//! 2. The data is copied into `/.kiri-moving`, keeping holes +//! (treecopy.rs), and the copy is checked: blobs by digest, every file +//! by size. +//! 3. The copy is renamed into place and the marker written +//! (kiri_image::storage::MARKER). +//! 4. `~/.kiri/storage.json` is written: the commit point. Up to here any +//! failure removes what was made and Kiri carries on where it was. +//! 5. The daemon starts itself again on the new folder and starts the +//! containers that ran. The old folder is kept until Remove old data. +//! +//! On a Linux host the agent's layers, containers and volumes move too: +//! from /var/lib/kiri to the chosen folder's `agent` folder, which the +//! agent mounts at /var/lib/kiri when it starts (KIRI_AGENT_DATA). +//! +//! A chosen folder without its marker (a drive that isn't connected) gets +//! no empty store made in it: the daemon stays up with nothing but +//! `serve_unavailable`, which offers Retry and Reset to default. + +use std::io::{self, BufReader}; +use std::os::unix::net::UnixStream; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use kiri_image::storage::{self as chosen, Choice, MARKER}; + +use super::engine::{Engine, Error}; +use super::http::{self, Request}; +use super::treecopy; + +/// On a Linux host, where the agent keeps layers, containers and volumes +/// while the data folder is the default one. +#[cfg(target_os = "linux")] +const AGENT_DATA: &str = "/var/lib/kiri"; + +/// The staging folder of a move, inside the folder moved to. +const MOVING: &str = ".kiri-moving"; +/// Kiri data that was in the folder moved to, set aside until the commit. +const REPLACED: &str = ".kiri-replaced"; +/// What a folder may hold besides Kiri's data and still count as empty. +const IGNORED: &[&str] = &[".DS_Store", "lost+found", MOVING, REPLACED, MARKER]; +/// Set on the daemon a move starts again: the containers to start. +const RESTART_ENV: &str = "KIRI_STORAGE_RESTART"; + +/// What other requests get while the data moves. +const MOVING_TEXT: &str = "Kiri is moving its data to another folder: try again when Settings → Storage says it's done"; + +/// The agent's folder on this system, if it has one apart from the data +/// folder. +fn agent_default() -> Option<&'static Path> { + #[cfg(target_os = "linux")] + return Some(Path::new(AGENT_DATA)); + #[cfg(not(target_os = "linux"))] + None +} + +/// The agent's data folder for the data folder `root` on a Linux host: +/// /var/lib/kiri for the default folder, else `/agent`. None +/// elsewhere. `guest.rs` hands a chosen one to the agent. +pub fn agent_dir(root: &Path, default: &Path) -> Option { + agent_default().map(|agent| if root == default { agent.to_owned() } else { root.join("agent") }) +} + +/// One folder a move copies: `from` into `to`, leaving out `skip` (names +/// at its top that another part moves). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Part { + pub from: PathBuf, + pub to: PathBuf, + pub skip: Vec<&'static str>, +} + +/// What moving the data folder `current` to `target` copies, where +/// `default` is the folder without a choice and `agent` the agent's own +/// folder for it (a Linux host's /var/lib/kiri). +pub fn parts(current: &Path, target: &Path, default: &Path, agent: Option<&Path>) -> Vec { + let Some(agent) = agent else { + return vec![Part { from: current.to_owned(), to: target.to_owned(), skip: Vec::new() }]; + }; + let agent_of = |root: &Path| if root == default { agent.to_owned() } else { root.join("agent") }; + vec![ + Part { from: current.to_owned(), to: target.to_owned(), skip: vec!["agent"] }, + Part { from: agent_of(current), to: agent_of(target), skip: Vec::new() }, + ] +} + +/// A folder that passed [`check`]: what the data needs there, what is +/// free, and whether Kiri data already there is replaced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checked { + pub needed: u64, + pub free: u64, + pub replaces: bool, +} + +/// `path` with its links resolved as far as it exists. +fn real(path: &Path) -> PathBuf { + let Some(near) = treecopy::existing_ancestor(path) else { return path.to_owned() }; + let rest = path.strip_prefix(near).unwrap_or(Path::new("")); + near.canonicalize().unwrap_or_else(|_| near.to_owned()).join(rest) +} + +/// "12.3 GB". +fn size(bytes: u64) -> String { + format!("{:.1} GB", bytes as f64 / 1e9) +} + +/// Room left over beside the data: a tenth more, and 1 GB. +fn headroom(bytes: u64) -> u64 { + bytes / 10 + 1_000_000_000 +} + +/// Whether the folders can take the data: full paths, apart from where +/// the data is now, empty (or holding Kiri data from before), writable, +/// not FAT or exFAT, with room for what the data takes plus a margin. +#[cfg(test)] +pub fn check(parts: &[Part]) -> Result { + check_with(parts, true) +} + +/// Like [`check`], but when `copy` is false (`Start fresh`), only checks +/// that the target has baseline headroom (1 GB) rather than the current +/// store's allocated size. +pub fn check_with(parts: &[Part], copy: bool) -> Result { + let mut replaces = false; + // Per filesystem: a folder on it, and the bytes moving there. + let mut needs: Vec<(u64, PathBuf, u64)> = Vec::new(); + for p in parts { + let to = &p.to; + if !to.is_absolute() || to.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{} isn't a full path: choose a folder", to.display())); + } + for q in parts { + let (from, dest) = (real(&q.from), real(to)); + if from == dest { + return Err(format!("Kiri's data is already in {}", to.display())); + } + if dest.starts_with(&from) { + return Err(format!("{} is inside Kiri's data folder {}: choose a folder outside it", to.display(), q.from.display())); + } + if from.starts_with(&dest) { + return Err(format!("Kiri's data folder {} is inside {}: choose another folder", q.from.display(), to.display())); + } + } + if to.symlink_metadata().is_ok() { + if !to.is_dir() { + return Err(format!("{} isn't a folder", to.display())); + } + let others = std::fs::read_dir(to) + .map_err(|e| format!("{}: {e}", to.display()))? + .flatten() + .any(|e| !IGNORED.iter().any(|n| e.file_name() == *n) && !p.skip.iter().any(|n| e.file_name() == *n)); + if chosen::has_marker(to) { + replaces |= others; + } else if others { + return Err(format!("{} isn't empty and doesn't hold Kiri's data: choose an empty folder, or make a new one", to.display())); + } + } + let near = treecopy::existing_ancestor(to).ok_or_else(|| format!("{} isn't on any disk", to.display()))?; + let fs = treecopy::fs_name(near).map_err(|e| format!("{}: {e}", near.display()))?; + if treecopy::refused_fs(&fs) { + let name = if fs == "exfat" { "exFAT" } else { "FAT" }; + return Err(format!("{} is on a {name} drive, which can't hold Kiri's data (no sparse files, owners or links): choose a folder on another drive", to.display())); + } + treecopy::probe_writable(near).map_err(|e| format!("Kiri can't write in {}: {e}", near.display()))?; + let bytes = if copy { treecopy::allocated(&p.from, &p.skip) } else { 0 }; + let dev = treecopy::device(near).map_err(|e| format!("{}: {e}", near.display()))?; + match needs.iter_mut().find(|(d, _, _)| *d == dev) { + Some(n) => n.2 += bytes, + None => needs.push((dev, near.to_owned(), bytes)), + } + } + let (mut needed, mut free) = (0, u64::MAX); + for (_, near, bytes) in &needs { + let want = bytes + headroom(*bytes); + let have = treecopy::free_space(near).map_err(|e| format!("{}: {e}", near.display()))?; + if have < want { + return Err(format!("{} has {} free, and Kiri's data needs {} there", near.display(), size(have), size(want))); + } + needed += want; + free = free.min(have); + } + Ok(Checked { needed, free, replaces }) +} + +/// The steps of [`migrate`] the progress callback is told about. +pub const COPYING: &str = "copying"; +pub const VERIFYING: &str = "verifying"; +pub const SWITCHING: &str = "switching"; + +/// One part put in place: what to undo if a later step fails. +struct Placed { + to: PathBuf, + moved_in: Vec, + set_aside: Vec, + had_marker: bool, +} + +/// Steps 2 to 4 of a move: each part copied into `/.kiri-moving` and +/// checked, put in place with the marker, then `choice` written to +/// `config`, the commit. A failure before the commit undoes everything: +/// what was copied goes, Kiri data that was in the way comes back, and +/// the folders the data is in now are as they were (apart from the marker, +/// which says they hold Kiri data). `step` hears each step's bytes; an +/// error from it stops the move. +pub fn migrate(parts: &[Part], config: &Path, choice: &Choice, step: &mut dyn FnMut(&'static str, u64) -> io::Result<()>) -> io::Result<()> { + let parts: Vec<&Part> = parts.iter().filter(|p| p.from.is_dir()).collect(); + let made: Vec = parts.iter().map(|p| !p.to.exists()).collect(); + let mut placed: Vec = Vec::new(); + let result = (|| -> io::Result<()> { + for p in &parts { + // Recognisable as Kiri's later: the old folder is a valid + // target for a move back. + chosen::write_marker(&p.from)?; + std::fs::create_dir_all(&p.to)?; + let staging = p.to.join(MOVING); + let _ = std::fs::remove_dir_all(&staging); + treecopy::copy_tree(&p.from, &staging, &p.skip, &mut |n| step(COPYING, n))?; + } + for p in &parts { + treecopy::verify_tree(&p.from, &p.to.join(MOVING), &p.skip, &mut |n| step(VERIFYING, n))?; + } + step(SWITCHING, 0)?; + for p in &parts { + placed.push(place(p)?); + } + chosen::write_at(config, choice) + })(); + match result { + Ok(()) => { + for p in &placed { + let _ = std::fs::remove_dir_all(p.to.join(REPLACED)); + } + Ok(()) + } + Err(e) => { + for p in placed.iter().rev() { + undo(p); + } + for (p, made) in parts.iter().zip(made).rev() { + let _ = std::fs::remove_dir_all(p.to.join(MOVING)); + if made { + let _ = std::fs::remove_file(p.to.join(MARKER)); + let _ = std::fs::remove_dir(&p.to); + } + } + Err(e) + } + } +} + +/// Switches `config` to an empty store in `parts` (`Start fresh`): marks +/// the old folders so Remove old data works, prepares empty target folders +/// with the marker (setting aside any prior Kiri data until commit), and +/// commits `choice` atomically. A failure before commit restores everything. +pub fn migrate_fresh(parts: &[Part], config: &Path, choice: &Choice, step: &mut dyn FnMut(&'static str, u64) -> io::Result<()>) -> io::Result<()> { + let made: Vec = parts.iter().map(|p| !p.to.exists()).collect(); + let mut placed: Vec = Vec::new(); + let result = (|| -> io::Result<()> { + step(SWITCHING, 0)?; + for p in parts { + if p.from.is_dir() { + chosen::write_marker(&p.from)?; + } + std::fs::create_dir_all(&p.to)?; + let mut done = Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }; + for e in std::fs::read_dir(&p.to)? { + let name = e?.file_name(); + if IGNORED.iter().any(|n| name == *n) || p.skip.iter().any(|n| name == *n) { + continue; + } + std::fs::create_dir_all(p.to.join(REPLACED))?; + std::fs::rename(p.to.join(&name), p.to.join(REPLACED).join(&name))?; + done.set_aside.push(name); + } + chosen::write_marker(&p.to)?; + placed.push(done); + } + chosen::write_at(config, choice) + })(); + match result { + Ok(()) => { + for p in &placed { + let _ = std::fs::remove_dir_all(p.to.join(REPLACED)); + } + Ok(()) + } + Err(e) => { + for p in placed.iter().rev() { + undo(p); + } + for (p, made) in parts.iter().zip(made).rev() { + if made { + let _ = std::fs::remove_file(p.to.join(MARKER)); + let _ = std::fs::remove_dir(&p.to); + } + } + Err(e) + } + } +} + +/// Renames a part's copy into place: what was there (Kiri data from +/// before) into `.kiri-replaced`, then the copy, then the marker. +fn place(p: &Part) -> io::Result { + let staging = p.to.join(MOVING); + let mut done = Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }; + let mut step = || -> io::Result<()> { + for e in std::fs::read_dir(&p.to)? { + let name = e?.file_name(); + if IGNORED.iter().any(|n| name == *n) || p.skip.iter().any(|n| name == *n) { + continue; + } + std::fs::create_dir_all(p.to.join(REPLACED))?; + std::fs::rename(p.to.join(&name), p.to.join(REPLACED).join(&name))?; + done.set_aside.push(name); + } + for e in std::fs::read_dir(&staging)? { + let name = e?.file_name(); + if name == MARKER { + continue; + } + std::fs::rename(staging.join(&name), p.to.join(&name))?; + done.moved_in.push(name); + } + std::fs::remove_dir_all(&staging)?; + chosen::write_marker(&p.to) + }; + match step() { + Ok(()) => Ok(done), + Err(e) => { + undo(&done); + Err(e) + } + } +} + +/// Takes a placed part back out: the copy removed, what was set aside +/// back where it was. +fn undo(p: &Placed) { + for name in &p.moved_in { + let path = p.to.join(name); + let _ = std::fs::remove_dir_all(&path).or_else(|_| std::fs::remove_file(&path)); + } + for name in &p.set_aside { + let _ = std::fs::rename(p.to.join(REPLACED).join(name), p.to.join(name)); + } + let _ = std::fs::remove_dir(p.to.join(REPLACED)); + if !p.had_marker { + let _ = std::fs::remove_file(p.to.join(MARKER)); + } +} + +/// How a move goes, for `GET /kiri/storage`. +#[derive(Default)] +struct Moving { + to: Option, + phase: &'static str, + done: u64, + total: u64, + /// Why the last move failed; Kiri stayed where it was. + error: Option, +} + +static MOVE: Mutex = Mutex::new(Moving { to: None, phase: "", done: 0, total: 0, error: None }); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn moving_state() -> std::sync::MutexGuard<'static, Moving> { + MOVE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether the data is moving: requests that change anything wait. +pub fn moving() -> bool { + ACTIVE.load(Ordering::SeqCst) +} + +/// The refusal while it moves. +pub fn refuse_while_moving(w: &mut UnixStream) -> io::Result<()> { + http::error(w, 503, MOVING_TEXT) +} + +/// What the data folder takes, kept 30 s: walking a Linux host's layers +/// takes a while. +fn used(root: &Path) -> u64 { + static USED: Mutex> = Mutex::new(None); + let mut cached = USED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((p, at, n)) = cached.as_ref() + && p == root + && at.elapsed() < Duration::from_secs(30) + { + return *n; + } + let default = kiri_image::Store::os_default_root().unwrap_or_default(); + let n = treecopy::allocated(root, &["agent"]) + agent_dir(root, &default).map_or(0, |a| treecopy::allocated(&a, &[])); + *cached = Some((root.to_owned(), Instant::now(), n)); + n +} + +/// `GET /kiri/storage`: for the data folder `root`, or for the chosen +/// folder `missing` that isn't there. +fn status(root: &Path, missing: bool) -> Value { + let default = kiri_image::Store::os_default_root().ok(); + let choice = chosen::read().ok().flatten(); + let custom = choice.as_ref().is_some_and(|c| Some(&c.path) != default.as_ref()); + let old = choice.and_then(|c| c.previous).filter(|p| p != root && p.is_dir()); + let active = moving(); + let m = moving_state(); + let near = treecopy::existing_ancestor(root); + json!({ + "path": root, + "default": default, + "custom": custom, + "env": std::env::var_os("KIRI_DATA_DIR").is_some(), + "state": if missing { "unavailable" } else if active { "moving" } else { "ok" }, + "used": (!missing && !active).then(|| used(root)), + "free": if missing { None } else { near.and_then(|p| treecopy::free_space(p).ok()) }, + "fs": if missing { None } else { near.and_then(|p| treecopy::fs_name(p).ok()) }, + "moving": m.to.as_ref().filter(|_| active).map(|to| json!({"to": to, "phase": m.phase, "done": m.done, "total": m.total})), + "error": m.error, + "old": old, + }) +} + +/// `GET /kiri/storage`. +pub fn report(engine: &Engine) -> Value { + status(engine.store.root(), false) +} + +/// The folder a request names (none or empty: the default one), and the +/// parts moving there would copy. +fn plan(root: &Path, requested: Option<&str>) -> Result<(PathBuf, Vec), Error> { + if let Some(dir) = std::env::var_os("KIRI_DATA_DIR") { + return Err(Error::Conflict(format!("KIRI_DATA_DIR sets Kiri's data folder ({}): change it there", Path::new(&dir).display()))); + } + let default = kiri_image::Store::os_default_root()?; + let target: PathBuf = match requested.map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => Path::new(p).components().collect(), + None => default.clone(), + }; + if target == root { + return Err(Error::BadRequest(format!("Kiri's data is already in {}", root.display()))); + } + let parts = parts(root, &target, &default, agent_default()); + Ok((target, parts)) +} + +fn requested(req: &Request) -> Result<(Option, bool), Error> { + if req.body.is_empty() { + return Ok((None, false)); + } + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + Ok((body["path"].as_str().map(str::to_owned), body["fresh"].as_bool().unwrap_or(false))) +} + +/// `POST /kiri/storage/check {"path": …, "fresh": …}`: whether the data can move there. +pub fn check_request(req: &Request, engine: &Engine) -> Result { + let (path, fresh) = requested(req)?; + let (target, parts) = plan(engine.store.root(), path.as_deref())?; + let c = check_with(&parts, !fresh).map_err(Error::BadRequest)?; + Ok(json!({"path": target, "needed": c.needed, "free": c.free, "replaces": c.replaces})) +} + +/// `POST /kiri/storage {"path": …, "fresh": …}` (none or empty: back to the +/// default folder): checks the folder, then moves the data there on a thread +/// of its own. `GET /kiri/storage` follows it. +pub fn start(req: &Request, engine: &Arc) -> Result { + let (path, fresh) = requested(req)?; + start_to(path.as_deref(), fresh, engine) +} + +/// `POST /kiri/storage/reset`: the data back to the default folder. +pub fn start_reset(engine: &Arc) -> Result { + start_to(None, false, engine) +} + +fn start_to(requested: Option<&str>, fresh: bool, engine: &Arc) -> Result { + let root = engine.store.root().to_owned(); + let (target, parts) = plan(&root, requested)?; + check_with(&parts, !fresh).map_err(Error::BadRequest)?; + if ACTIVE.swap(true, Ordering::SeqCst) { + return Err(Error::Conflict("Kiri's data is moving already".into())); + } + let total = if fresh { 0 } else { parts.iter().map(|p| treecopy::allocated(&p.from, &p.skip)).sum() }; + *moving_state() = Moving { to: Some(target.clone()), phase: "stopping", done: 0, total, error: None }; + let answer = status(&root, false); + let engine = engine.clone(); + std::thread::Builder::new().name("kiri-storage-move".into()).spawn(move || run_move(&engine, &root, &target, &parts, fresh))?; + Ok(answer) +} + +fn run_move(engine: &Engine, root: &Path, target: &Path, parts: &[Part], fresh: bool) { + crate::diag::info!("moving Kiri's data", from = root.display(), to = target.display(), fresh = fresh); + let fail = |e: String, resume: Option<(Vec, bool)>| { + crate::diag::error!("Kiri's data did not move; it stays where it was", to = target.display(), error = &e); + { + let mut m = moving_state(); + m.to = None; + m.error = Some(e); + } + ACTIVE.store(false, Ordering::SeqCst); + if let Some((running, was_stopped)) = resume { + engine.resume_after_move(was_stopped, running); + } + }; + let (running, was_stopped) = match engine.park_for_move() { + Ok(r) => r, + Err(e) => return fail(format!("the containers did not stop: {e:?}"), None), + }; + // The agent has stopped: a chosen folder's mount at /var/lib/kiri + // comes off, so a move back writes to /var/lib/kiri itself. A move that + // fails leaves storage.json as it was, and the agent mounts it again. + #[cfg(target_os = "linux")] + if kiri_image::Store::os_default_root().is_ok_and(|d| d != root) { + unmount_agent_data(); + } + let config = match chosen::config_path() { + Ok(c) => c, + Err(e) => return fail(e.to_string(), Some((running, was_stopped))), + }; + let choice = Choice { path: target.to_owned(), previous: Some(root.to_owned()) }; + let mut on_step = |phase: &'static str, n: u64| { + let mut m = moving_state(); + if m.phase != phase { + m.phase = phase; + m.done = 0; + } + m.done += n; + Ok(()) + }; + let moved = if fresh { + migrate_fresh(parts, &config, &choice, &mut on_step) + } else { + migrate(parts, &config, &choice, &mut on_step) + }; + if let Err(e) = moved { + return fail(e.to_string(), Some((running, was_stopped))); + } + moving_state().phase = "restarting"; + let restart_ids = if fresh { Vec::new() } else { running }; + crate::diag::info!("Kiri's data moved; the engine starts again on it", to = target.display(), containers = restart_ids.len()); + after_commit(root); + let e = restart(&restart_ids); + crate::diag::error!("the engine did not start again after the move; it exits for launchd or systemd to start it", error = e); + std::process::exit(1); +} + +/// After the commit, before the restart: what still points into the old +/// folder. +fn after_commit(old: &Path) { + // Kiri Lite's docker link and plugin folder are in the data folder. + #[cfg(target_os = "macos")] + if let Err(e) = crate::setup::relink_cli(old) { + crate::diag::warn!("docker's links into the data folder were not updated", error = e); + } + // The old agent data comes out from under the new folder's mount, + // into the old folder, so Remove old data finds it there. + #[cfg(target_os = "linux")] + if kiri_image::Store::os_default_root().is_ok_and(|d| d == old) { + stash_agent_data(old); + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + let _ = old; +} + +/// Moves what is in /var/lib/kiri into `/agent`. Only a rename: when +/// they are on different filesystems it stays, under the mount, until a +/// move back. +#[cfg(target_os = "linux")] +fn stash_agent_data(old: &Path) { + let to = old.join("agent"); + let result = (|| -> io::Result<()> { + std::fs::create_dir_all(&to)?; + for e in std::fs::read_dir(AGENT_DATA)? { + let name = e?.file_name(); + if name == MARKER { + continue; + } + std::fs::rename(Path::new(AGENT_DATA).join(&name), to.join(&name))?; + } + let _ = std::fs::remove_file(Path::new(AGENT_DATA).join(MARKER)); + Ok(()) + })(); + if let Err(e) = result { + crate::diag::warn!("the old agent data stays in /var/lib/kiri", error = e); + } +} + +/// Takes a chosen folder's mount off /var/lib/kiri. +#[cfg(target_os = "linux")] +fn unmount_agent_data() { + // SAFETY: a valid NUL-terminated path; MNT_DETACH needs nothing else. + if unsafe { libc::umount2(c"/var/lib/kiri".as_ptr(), libc::MNT_DETACH) } != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EINVAL) { + crate::diag::warn!("/var/lib/kiri did not unmount", error = e); + } + } +} + +/// Starts this daemon again in its place (the same process, so launchd +/// and systemd keep it), on the data folder storage.json now names, with +/// the containers to start again. Returns only if that failed. +fn restart(running: &[String]) -> io::Error { + use std::os::unix::process::CommandExt; + #[cfg(target_os = "macos")] + super::nfs::unmount(); + if let Ok(socket) = super::socket_path() { + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(super::caller::container_socket(&socket)); + } + match std::env::current_exe() { + Ok(exe) => { + let mut cmd = std::process::Command::new(exe); + cmd.arg("daemon"); + if running.is_empty() { + cmd.env_remove(RESTART_ENV); + } else { + cmd.env(RESTART_ENV, running.join(",")); + } + cmd.exec() + } + Err(e) => e, + } +} + +/// On the daemon a move started again: the containers that ran before it +/// start again. +pub fn after_restart(engine: &Arc) { + let Ok(list) = std::env::var(RESTART_ENV) else { return }; + let ids: Vec = list.split(',').filter(|s| !s.is_empty()).map(str::to_owned).collect(); + crate::diag::info!("Kiri's data is in its new folder", folder = engine.store.root().display(), containers = ids.len()); + if !ids.is_empty() { + let engine = engine.clone(); + std::thread::spawn(move || engine.start_again(&ids)); + } +} + +/// `DELETE /kiri/storage/old`: removes the folder the data was moved from. +pub fn remove_old(engine: &Engine) -> Result { + if moving() { + return Err(Error::Conflict(MOVING_TEXT.into())); + } + let root = engine.store.root(); + let mut choice = chosen::read()?.ok_or_else(|| Error::Conflict("there is no old data to remove".into()))?; + let old = choice.previous.clone().ok_or_else(|| Error::Conflict("there is no old data to remove".into()))?; + remove_old_folder(&old, root).map_err(Error::Conflict)?; + choice.previous = None; + if kiri_image::Store::os_default_root().is_ok_and(|d| d == choice.path) { + chosen::clear()?; + } else { + chosen::write(&choice)?; + } + Ok(report(engine)) +} + +/// Removes `old`, the folder data moved away from, if it is safe to: not +/// the data folder `root`, not around or inside it, and holding the marker +/// a move leaves. +fn remove_old_folder(old: &Path, root: &Path) -> Result<(), String> { + let (o, r) = (real(old), real(root)); + if o == r || o.starts_with(&r) || r.starts_with(&o) { + return Err(format!("{} holds Kiri's data now", old.display())); + } + if !old.exists() { + return Ok(()); + } + if !chosen::has_marker(old) { + return Err(format!("{} doesn't look like Kiri's old data; remove it yourself if you're sure", old.display())); + } + std::fs::remove_dir_all(old).map_err(|e| format!("{}: {e}", old.display())) +} + +/// The daemon's API while the chosen data folder `missing` isn't there: +/// `GET /kiri/storage` says so, `POST /kiri/storage/retry` starts again +/// once it is back, `POST /kiri/storage/reset` forgets the choice and +/// starts again on the default folder, and `POST /kiri/storage[/check]` +/// lets the user point to another folder (a drive mounted elsewhere, or +/// a fresh folder). Everything else says why it can't. +pub fn serve_unavailable(stream: UnixStream, missing: &Path) -> io::Result<()> { + use std::io::Write as _; + let mut w = stream.try_clone()?; + let mut r = BufReader::new(stream); + let unavailable = chosen::Unavailable(missing.to_owned()).to_string(); + while let Some(req) = http::read_request(&mut r, |_, _| false)? { + if req.too_large() { + return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); + } + match (req.method.as_str(), req.path.as_str()) { + ("GET" | "HEAD", "/_ping") => http::respond(&mut w, 200, "text/plain; charset=utf-8", if req.method == "HEAD" { b"" } else { b"OK" })?, + ("GET", "/version") => http::json(&mut w, 200, &super::api::version().to_string())?, + ("GET", "/kiri/storage") => http::json(&mut w, 200, &status(missing, true).to_string())?, + ("POST", "/kiri/storage/check") => match check_unavailable(&req, missing) { + Ok(v) => http::json(&mut w, 200, &v.to_string())?, + Err(e) => http::error(&mut w, 400, &e)?, + }, + ("POST", "/kiri/storage") => match switch_unavailable(&req, missing) { + Ok(v) => { + http::json(&mut w, 202, &v.to_string())?; + let _ = w.flush(); + restart_soon(); + } + Err(e) => http::error(&mut w, 400, &e)?, + }, + ("POST", "/kiri/storage/retry") if chosen::has_marker(missing) => { + http::empty(&mut w, 204)?; + let _ = w.flush(); + restart_soon(); + } + ("POST", "/kiri/storage/retry") => http::error(&mut w, 409, &unavailable)?, + ("POST", "/kiri/storage/reset") => { + chosen::clear()?; + crate::diag::info!("storage choice forgotten: the engine starts on the default folder", was = missing.display()); + http::empty(&mut w, 204)?; + let _ = w.flush(); + restart_soon(); + } + _ => http::error(&mut w, 503, &unavailable)?, + } + if req.wants_close() || !http::finish_body(&req, &mut r) { + http::close(&w, &mut r); + return Ok(()); + } + } + Ok(()) +} + +/// Restarts the daemon after a brief pause so the HTTP response finishes +/// writing to the client before `exec()` tears down the listening socket. +fn restart_soon() { + std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(80)); + let _ = restart(&[]); + }); +} + +fn check_unavailable(req: &Request, missing: &Path) -> Result { + let (path, _) = requested(req).map_err(|e| format!("{e:?}"))?; + let (target, parts) = plan(missing, path.as_deref()).map_err(|e| match e { + Error::BadRequest(s) | Error::Conflict(s) => s, + other => format!("{other:?}"), + })?; + let c = check_with(&parts, false)?; + Ok(json!({"path": target, "needed": 0, "free": c.free, "replaces": c.replaces})) +} + +fn switch_unavailable(req: &Request, missing: &Path) -> Result { + let (path, _) = requested(req).map_err(|e| format!("{e:?}"))?; + let (target, parts) = plan(missing, path.as_deref()).map_err(|e| match e { + Error::BadRequest(s) | Error::Conflict(s) => s, + other => format!("{other:?}"), + })?; + check_with(&parts, false)?; + for p in &parts { + std::fs::create_dir_all(&p.to).map_err(|e| format!("{}: {e}", p.to.display()))?; + if !chosen::has_marker(&p.to) { + chosen::write_marker(&p.to).map_err(|e| format!("{}: {e}", p.to.display()))?; + } + } + if kiri_image::Store::os_default_root().is_ok_and(|d| d == target) { + chosen::clear().map_err(|e| e.to_string())?; + } else { + chosen::write(&Choice { path: target.clone(), previous: None }).map_err(|e| e.to_string())?; + } + Ok(status(&target, false)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-storage-move-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.canonicalize().unwrap() + } + + /// A data folder as the daemon leaves it: an image index, a blob, the + /// VM's disk (sparse) and its address. + fn data(root: &Path) { + use sha2::Digest as _; + std::fs::create_dir_all(root.join("blobs/sha256")).unwrap(); + std::fs::create_dir_all(root.join("vm")).unwrap(); + std::fs::write(root.join("images.json"), b"[]").unwrap(); + let hex: String = sha2::Sha256::digest(b"x").iter().map(|b| format!("{b:02x}")).collect(); + std::fs::write(root.join("blobs/sha256").join(hex), b"x").unwrap(); + std::fs::File::create(root.join("vm/data.img")).unwrap().set_len(64 << 20).unwrap(); + std::fs::write(root.join("vm/mac"), b"02:00:00:00:00:01").unwrap(); + } + + fn one(from: &Path, to: &Path) -> Vec { + vec![Part { from: from.to_owned(), to: to.to_owned(), skip: Vec::new() }] + } + + #[test] + fn a_relative_path_is_refused() { + let d = scratch("relative"); + data(&d.join("kiri")); + let e = check(&one(&d.join("kiri"), Path::new("External/kiri"))).unwrap_err(); + assert!(e.contains("isn't a full path"), "{e}"); + let e = check(&one(&d.join("kiri"), &d.join("a/../kiri2"))).unwrap_err(); + assert!(e.contains("isn't a full path"), "{e}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_folder_inside_the_data_or_around_it_is_refused() { + let d = scratch("nested"); + let root = d.join("kiri"); + data(&root); + let e = check(&one(&root, &root.join("vm/elsewhere"))).unwrap_err(); + assert!(e.contains("is inside Kiri's data folder"), "{e}"); + let e = check(&one(&root, &d)).unwrap_err(); + assert!(e.contains("is inside"), "{e}"); + let e = check(&one(&root, &root)).unwrap_err(); + assert!(e.contains("already in"), "{e}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_folder_with_other_files_is_refused_and_kiri_data_is_replaced() { + let d = scratch("nonempty"); + let root = d.join("kiri"); + data(&root); + let other = d.join("photos"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("cat.jpg"), b"meow").unwrap(); + let e = check(&one(&root, &other)).unwrap_err(); + assert!(e.contains("isn't empty"), "{e}"); + // Empty, or with only what a system puts there: fine. + let empty = d.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + std::fs::write(empty.join(".DS_Store"), b"").unwrap(); + assert!(!check(&one(&root, &empty)).unwrap().replaces); + // Kiri data from before (the marker): replaced, and said so. + let before = d.join("before"); + data(&before); + chosen::write_marker(&before).unwrap(); + assert!(check(&one(&root, &before)).unwrap().replaces); + let _ = std::fs::remove_dir_all(&d); + } + + /// A move copies the data, puts the marker there and commits the + /// choice; the old folder stays until Remove old data, which then + /// removes it. + #[test] + fn a_move_copies_marks_and_commits() { + let d = scratch("move"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + let mut copied = 0; + migrate(&one(&root, &target), &config, &choice, &mut |phase, n| { + if phase == COPYING { + copied += n; + } + Ok(()) + }) + .unwrap(); + assert_eq!(chosen::read_at(&config).unwrap(), Some(choice)); + assert!(chosen::has_marker(&target) && !target.join(MOVING).exists() && !target.join(REPLACED).exists()); + assert_eq!(std::fs::read(target.join("vm/mac")).unwrap(), b"02:00:00:00:00:01"); + assert!(std::os::unix::fs::MetadataExt::blocks(&std::fs::metadata(target.join("vm/data.img")).unwrap()) * 512 < 1 << 20, "the VM's disk stays sparse"); + assert!(copied < 1 << 20, "only data was copied: {copied}"); + assert!(root.join("images.json").is_file(), "the old folder is kept"); + assert!(remove_old_folder(&target, &target).is_err(), "never the data folder itself"); + remove_old_folder(&root, &target).unwrap(); + assert!(!root.exists()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A copy that fails before the commit leaves the data where it was, + /// storage.json unwritten, and nothing in the folder moved to. + #[test] + fn a_failed_copy_leaves_the_store_where_it_was() { + let d = scratch("fail"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let before = treecopy::sha256(&root.join("vm/mac")).unwrap(); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + let e = migrate(&one(&root, &target), &config, &choice, &mut |_, _| Err(io::Error::other("the drive went away"))).unwrap_err(); + assert!(e.to_string().contains("went away")); + assert!(!target.join(MOVING).exists() && !target.exists(), "the staging folder and the folder made for it are gone"); + assert_eq!(chosen::read_at(&config).unwrap(), None, "no commit"); + assert_eq!(treecopy::sha256(&root.join("vm/mac")).unwrap(), before); + assert!(root.join("images.json").is_file() && root.join("blobs/sha256").read_dir().unwrap().next().is_some()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A commit that fails (storage.json can't be written) undoes the + /// placing too: Kiri data that was in the folder comes back. + #[test] + fn a_failed_commit_puts_back_what_was_there() { + let d = scratch("commit"); + let (root, target) = (d.join("kiri"), d.join("before")); + data(&root); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("images.json"), b"[\"old\"]").unwrap(); + chosen::write_marker(&target).unwrap(); + // A file where storage.json's folder would be. + std::fs::write(d.join("state"), b"").unwrap(); + let config = d.join("state/storage.json"); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + assert!(migrate(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).is_err()); + assert_eq!(std::fs::read(target.join("images.json")).unwrap(), b"[\"old\"]"); + assert!(!target.join("vm").exists() && !target.join(REPLACED).exists() && !target.join(MOVING).exists()); + assert!(chosen::has_marker(&target), "it held Kiri data before, and still does"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A Linux host moves the agent's folder too: /var/lib/kiri for the + /// default data folder, `/agent` for a chosen one. + #[test] + fn a_linux_host_moves_the_agent_folder_too() { + let (def, ext, agent) = (Path::new("/var/lib/kiri-daemon/.local/share/kiri"), Path::new("/media/ssd/kiri"), Path::new("/var/lib/kiri")); + let p = parts(def, ext, def, Some(agent)); + assert_eq!(p[0], Part { from: def.into(), to: ext.into(), skip: vec!["agent"] }); + assert_eq!(p[1], Part { from: agent.into(), to: ext.join("agent"), skip: vec![] }); + let back = parts(ext, def, def, Some(agent)); + assert_eq!(back[1], Part { from: ext.join("agent"), to: agent.into(), skip: vec![] }); + assert_eq!(parts(def, ext, def, None), vec![Part { from: def.into(), to: ext.into(), skip: vec![] }]); + } + + /// Starting fresh writes the marker and commits without copying old + /// blobs, while keeping the old folder until Remove old data; a commit + /// failure rolls back cleanly. + #[test] + fn start_fresh_switches_without_copying_and_rolls_back_on_error() { + let d = scratch("fresh"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + migrate_fresh(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).unwrap(); + assert_eq!(chosen::read_at(&config).unwrap(), Some(choice)); + assert!(chosen::has_marker(&target)); + assert!(!target.join("images.json").exists(), "fresh target has no copied data"); + assert!(chosen::has_marker(&root) && root.join("images.json").is_file(), "old folder kept and marked"); + remove_old_folder(&root, &target).unwrap(); + assert!(!root.exists()); + // Failed commit on an existing fresh target rolls back cleanly. + let target2 = d.join("fresh2"); + std::fs::write(d.join("blocked"), b"").unwrap(); + let bad_cfg = d.join("blocked/storage.json"); + let choice2 = Choice { path: target2.clone(), previous: Some(target.clone()) }; + assert!(migrate_fresh(&one(&target, &target2), &bad_cfg, &choice2, &mut |_, _| Ok(())).is_err()); + assert!(!target2.exists(), "newly made fresh folder is removed on rollback"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A broken symlink or regular file at the target path is refused. + #[test] + fn non_directory_and_broken_symlink_targets_are_refused() { + let d = scratch("nondir"); + let root = d.join("kiri"); + data(&root); + let file = d.join("afile"); + std::fs::write(&file, b"hi").unwrap(); + assert!(check(&one(&root, &file)).unwrap_err().contains("isn't a folder")); + let broken = d.join("broken"); + std::os::unix::fs::symlink(d.join("missing"), &broken).unwrap(); + assert!(check(&one(&root, &broken)).unwrap_err().contains("isn't a folder")); + let _ = std::fs::remove_dir_all(&d); + } + + /// A chosen folder whose drive isn't connected is reported unavailable, + /// with nothing made there. + #[test] + fn a_missing_marker_reports_storage_unavailable() { + let d = scratch("unavailable"); + let gone = d.join("Volumes/External/kiri"); + let e = chosen::resolve(Some(Choice { path: gone.clone(), previous: None }), d.join("default")).unwrap_err(); + assert_eq!(chosen::unavailable(&e), Some(gone.as_path())); + let s = status(&gone, true); + assert_eq!(s["state"], "unavailable"); + assert_eq!(s["path"], gone.to_string_lossy().as_ref()); + assert!(s["used"].is_null() && s["free"].is_null()); + assert!(!gone.exists()); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri/src/daemon/treecopy.rs b/crates/kiri/src/daemon/treecopy.rs new file mode 100644 index 000000000..de2078292 --- /dev/null +++ b/crates/kiri/src/daemon/treecopy.rs @@ -0,0 +1,562 @@ +//! Copying Kiri's data folder to another place (Settings → Storage). +//! +//! `std::fs::copy` writes a sparse file out whole when it crosses volumes: +//! the VM's 64 GiB `data.img`, of which a few GB hold data, would take all +//! 64 GiB on the new drive. [`copy_sparse`] copies only the file's data +//! (`SEEK_DATA`/`SEEK_HOLE`, or skipping runs of zeros where the system +//! can't say where the holes are), so it stays as small as it was. +//! [`copy_tree`] copies a whole folder that way, keeping what a Linux +//! host's layers need: owners, modes, hard links, device nodes (overlay +//! whiteouts) and extended attributes (`trusted.overlay.opaque`). + +use std::collections::HashMap; +use std::ffi::CString; +use std::fs::{self, File, Metadata, OpenOptions}; +use std::io::{self, Read}; +use std::os::fd::AsRawFd; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{FileExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +/// How much is read at a time. +const CHUNK: usize = 1 << 20; +/// Zeros are skipped in runs of this size, at this alignment: what is left +/// unwritten stays a hole on any filesystem with blocks up to 64 KiB. +const BLOCK: usize = 64 << 10; + +/// Told the bytes just copied; an error it returns stops the copy. +pub type Progress<'a> = dyn FnMut(u64) -> io::Result<()> + 'a; + +/// Copies the file `src` to `dst`, which must not exist, writing only its +/// data: holes stay holes, and so do runs of zeros. Returns once the copy +/// is on disk. Permissions and owner are the caller's ([`copy_tree`]). +pub fn copy_sparse(src: &Path, dst: &Path, progress: &mut Progress<'_>) -> io::Result<()> { + let from = File::open(src)?; + let len = from.metadata()?.len(); + let to = OpenOptions::new().write(true).create_new(true).mode(0o600).open(dst)?; + let written = match copy_extents(&from, &to, len, progress) { + // No SEEK_DATA here (an older filesystem): every byte is read, and + // the zeros are left out. + Err(e) if unsupported(&e) => { + to.set_len(0)?; + copy_range(&from, &to, 0, len, progress)? + } + r => r?, + }; + finish_sparse(&to, len, &written) +} + +/// Sets `to`'s length to `len`, punches any unwritten gaps on macOS APFS +/// (where `pwrite` + `ftruncate` + `fsync` can otherwise allocate leading +/// or short trailing zero blocks), and syncs to disk. +fn finish_sparse(to: &File, len: u64, written: &[(u64, u64)]) -> io::Result<()> { + to.set_len(len)?; + let mut cursor = 0u64; + for &(start, end) in written { + if start > cursor { + punch_hole(to, cursor, start - cursor); + } + cursor = cursor.max(end); + } + if len > cursor { + punch_hole(to, cursor, len - cursor); + } + to.sync_all() +} + +/// Punches `[offset, offset + len)` as a sparse hole on macOS APFS. +/// Best-effort: filesystems that do not support `F_PUNCHHOLE` ignore it. +#[cfg(target_os = "macos")] +fn punch_hole(f: &File, offset: u64, len: u64) { + let (Ok(offset), Ok(len)) = (libc::off_t::try_from(offset), libc::off_t::try_from(len)) else { return }; + if len <= 0 { + return; + } + let hole = libc::fpunchhole_t { fp_flags: 0, reserved: 0, fp_offset: offset, fp_length: len }; + // SAFETY: `f` is an open writable file descriptor and `hole` matches F_PUNCHHOLE's struct. + unsafe { libc::fcntl(f.as_raw_fd(), libc::F_PUNCHHOLE, &hole) }; +} + +#[cfg(not(target_os = "macos"))] +fn punch_hole(_f: &File, _offset: u64, _len: u64) {} + +fn unsupported(e: &io::Error) -> bool { + let code = e.raw_os_error(); + code == Some(libc::EINVAL) || code == Some(libc::ENOTSUP) || code == Some(libc::EOPNOTSUPP) +} + +/// Copies each run of data `SEEK_DATA` finds. Returns sorted written ranges. +fn copy_extents(from: &File, to: &File, len: u64, progress: &mut Progress<'_>) -> io::Result> { + let mut pos = 0; + let mut written = Vec::new(); + while pos < len { + let data = match seek(from, pos, libc::SEEK_DATA) { + Ok(at) if at < len => at, + Ok(_) => break, + // Only a hole from here to the end. + Err(e) if e.raw_os_error() == Some(libc::ENXIO) => break, + Err(e) => return Err(e), + }; + let hole = seek(from, data, libc::SEEK_HOLE)?.min(len); + if hole <= data { + break; + } + written.extend(copy_range(from, to, data, hole, progress)?); + pos = hole; + } + Ok(written) +} + +fn seek(f: &File, at: u64, whence: libc::c_int) -> io::Result { + let at = libc::off_t::try_from(at).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: lseek on a descriptor `f` owns; it only moves its offset. + let r = unsafe { libc::lseek(f.as_raw_fd(), at, whence) }; + if r < 0 { Err(io::Error::last_os_error()) } else { Ok(r as u64) } +} + +/// Copies bytes `start..end`, leaving out blocks that are all zeros (the +/// new file reads zeros there anyway). Returns coalesced written ranges. +fn copy_range(from: &File, to: &File, start: u64, end: u64, progress: &mut Progress<'_>) -> io::Result> { + let mut buf = vec![0u8; CHUNK]; + let mut at = start; + let mut written: Vec<(u64, u64)> = Vec::new(); + while at < end { + let want = usize::try_from(end - at).unwrap_or(CHUNK).min(CHUNK); + let n = from.read_at(&mut buf[..want], at)?; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the file got shorter while it was copied")); + } + let mut off = 0; + while off < n { + // Up to the next BLOCK boundary of the file, so holes line up. + let file_off = at + off as u64; + let step = (BLOCK - (file_off % BLOCK as u64) as usize).min(n - off); + let piece = &buf[off..off + step]; + if piece.iter().any(|&b| b != 0) { + to.write_all_at(piece, file_off)?; + let piece_end = file_off + step as u64; + match written.last_mut() { + Some((_, last_end)) if *last_end == file_off => *last_end = piece_end, + _ => written.push((file_off, piece_end)), + } + } + off += step; + } + at += n as u64; + progress(n as u64)?; + } + Ok(written) +} + +/// Copies the folder `src` to `dst`, which must not exist, leaving out the +/// entries of `src` named in `skip`. Sockets are left out (whoever listens +/// makes them again). A folder on another filesystem than `src` (something +/// still mounted) stops the copy rather than copying what is mounted there. +pub fn copy_tree(src: &Path, dst: &Path, skip: &[&str], progress: &mut Progress<'_>) -> io::Result<()> { + let meta = fs::symlink_metadata(src)?; + // SAFETY: geteuid cannot fail. + let as_root = unsafe { libc::geteuid() } == 0; + let mut c = Copier { progress, links: HashMap::new(), dev: meta.dev(), as_root }; + fs::create_dir(dst)?; + c.contents(src, dst, skip)?; + c.finish(&meta, src, dst) +} + +struct Copier<'a, 'b> { + progress: &'a mut Progress<'b>, + /// Files with more than one name: the first copy of each, by device + /// and inode, which later names link to. + links: HashMap<(u64, u64), PathBuf>, + dev: u64, + as_root: bool, +} + +impl Copier<'_, '_> { + fn contents(&mut self, src: &Path, dst: &Path, skip: &[&str]) -> io::Result<()> { + for entry in fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + if skip.iter().any(|s| name == *s) { + continue; + } + self.entry(&entry.path(), &dst.join(&name))?; + } + Ok(()) + } + + fn entry(&mut self, src: &Path, dst: &Path) -> io::Result<()> { + let m = fs::symlink_metadata(src)?; + let kind = m.file_type(); + if kind.is_dir() { + if m.dev() != self.dev { + return Err(io::Error::other(format!("{} is a mount point: stop what uses it and try again", src.display()))); + } + fs::create_dir(dst)?; + self.contents(src, dst, &[])?; + } else if kind.is_file() { + if m.nlink() > 1 { + if let Some(first) = self.links.get(&(m.dev(), m.ino())) { + return fs::hard_link(first, dst); + } + self.links.insert((m.dev(), m.ino()), dst.to_owned()); + } + copy_sparse(src, dst, self.progress)?; + } else if kind.is_symlink() { + std::os::unix::fs::symlink(fs::read_link(src)?, dst)?; + } else if kind.is_socket() { + return Ok(()); + } else { + // A FIFO or a device node: an overlay whiteout is a 0/0 one. + let path = c_path(dst)?; + // SAFETY: a valid NUL-terminated path; mode and device as stat gave them. + if unsafe { libc::mknod(path.as_ptr(), m.mode() as libc::mode_t, m.rdev() as libc::dev_t) } != 0 { + return Err(io::Error::last_os_error()); + } + } + self.finish(&m, src, dst) + } + + /// The owner (when copying as root), extended attributes, mode and + /// times of `src` on `dst`. The mode after the owner: a change of + /// owner clears set-user-ID. + fn finish(&self, m: &Metadata, src: &Path, dst: &Path) -> io::Result<()> { + if self.as_root { + std::os::unix::fs::lchown(dst, Some(m.uid()), Some(m.gid()))?; + } + copy_xattrs(src, dst)?; + let link = m.file_type().is_symlink(); + if !link { + fs::set_permissions(dst, fs::Permissions::from_mode(m.mode() & 0o7777))?; + } + let times = [ + libc::timespec { tv_sec: m.atime() as _, tv_nsec: m.atime_nsec() as _ }, + libc::timespec { tv_sec: m.mtime() as _, tv_nsec: m.mtime_nsec() as _ }, + ]; + let path = c_path(dst)?; + // SAFETY: a valid NUL-terminated path and two timespecs. + if unsafe { libc::utimensat(libc::AT_FDCWD, path.as_ptr(), times.as_ptr(), libc::AT_SYMLINK_NOFOLLOW) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } +} + +fn c_path(p: &Path) -> io::Result { + CString::new(p.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput)) +} + +/// A Linux host's layers keep overlay attributes (`trusted.overlay.*`) +/// and file capabilities (`security.capability`). The SELinux label is the +/// new place's policy's to give. +#[cfg(target_os = "linux")] +fn copy_xattrs(src: &Path, dst: &Path) -> io::Result<()> { + let (s, d) = (c_path(src)?, c_path(dst)?); + // SAFETY: llistxattr with a null buffer asks for the size of the list. + let size = unsafe { libc::llistxattr(s.as_ptr(), std::ptr::null_mut(), 0) }; + if size < 0 { + let e = io::Error::last_os_error(); + return if unsupported(&e) { Ok(()) } else { Err(e) }; + } + if size == 0 { + return Ok(()); + } + let mut names = vec![0u8; size as usize]; + // SAFETY: the buffer is `names.len()` bytes. + let size = unsafe { libc::llistxattr(s.as_ptr(), names.as_mut_ptr().cast(), names.len()) }; + if size < 0 { + return Err(io::Error::last_os_error()); + } + for name in names[..size as usize].split(|&b| b == 0).filter(|n| !n.is_empty() && *n != b"security.selinux") { + let key = CString::new(name).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + // SAFETY: a null buffer asks for the value's size. + let len = unsafe { libc::lgetxattr(s.as_ptr(), key.as_ptr(), std::ptr::null_mut(), 0) }; + if len < 0 { + return Err(io::Error::last_os_error()); + } + let mut value = vec![0u8; len as usize]; + // SAFETY: the buffer is `value.len()` bytes. + let len = unsafe { libc::lgetxattr(s.as_ptr(), key.as_ptr(), value.as_mut_ptr().cast(), value.len()) }; + if len < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: valid strings and a buffer of `len` bytes. + if unsafe { libc::lsetxattr(d.as_ptr(), key.as_ptr(), value.as_ptr().cast(), len as usize, 0) } != 0 { + return Err(io::Error::other(format!("{}: {}: {}", dst.display(), String::from_utf8_lossy(name), io::Error::last_os_error()))); + } + } + Ok(()) +} + +/// A Mac's data folder needs none: Finder's and the quarantine's own +/// attributes aren't Kiri's. +#[cfg(not(target_os = "linux"))] +fn copy_xattrs(_src: &Path, _dst: &Path) -> io::Result<()> { + Ok(()) +} + +/// Checks that `dst` holds what `src` does (leaving out `skip` at the top): +/// every file there with the same size, small files with the same bytes, +/// and every blob (`blobs/sha256/`) matching its digest. +pub fn verify_tree(src: &Path, dst: &Path, skip: &[&str], progress: &mut Progress<'_>) -> io::Result<()> { + for entry in fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + if skip.iter().any(|s| name == *s) { + continue; + } + let (s, d) = (entry.path(), dst.join(&name)); + let m = fs::symlink_metadata(&s)?; + let differs = |what: &str| io::Error::other(format!("the copy of {} {what}", s.display())); + let got = fs::symlink_metadata(&d).map_err(|_| differs("is missing"))?; + if m.is_dir() { + if !got.is_dir() { + return Err(differs("isn't a folder")); + } + verify_tree(&s, &d, &[], progress)?; + } else if m.is_file() { + if !got.is_file() || got.len() != m.len() { + return Err(differs("has another size")); + } + let blob = s.parent().is_some_and(|p| p.ends_with("blobs/sha256")); + let hex = name.to_str().filter(|n| n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit())); + if let (true, Some(hex)) = (blob, hex) { + if sha256(&d)? != hex { + return Err(differs("doesn't match its digest")); + } + progress(m.len())?; + } else if m.len() <= CHUNK as u64 && fs::read(&s)? != fs::read(&d)? { + return Err(differs("has other contents")); + } + } else if m.file_type().is_symlink() && fs::read_link(&s)? != fs::read_link(&d).map_err(|_| differs("isn't a link"))? { + return Err(differs("points elsewhere")); + } + } + Ok(()) +} + +/// The SHA-256 of a file, in hex. +pub fn sha256(path: &Path) -> io::Result { + use sha2::Digest as _; + let mut f = File::open(path)?; + let mut h = sha2::Sha256::new(); + let mut buf = vec![0u8; CHUNK]; + loop { + let n = f.read(&mut buf)?; + if n == 0 { + break; + } + h.update(&buf[..n]); + } + Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// What the folder `dir` takes on its disk (blocks in use, a hard-linked +/// file once), leaving out `skip` at the top. What can't be read counts as +/// nothing. +pub fn allocated(dir: &Path, skip: &[&str]) -> u64 { + fn walk(dir: &Path, skip: &[&str], dev: u64, seen: &mut std::collections::HashSet<(u64, u64)>) -> u64 { + let Ok(entries) = fs::read_dir(dir) else { return 0 }; + let mut total = 0; + for entry in entries.flatten() { + if skip.iter().any(|s| entry.file_name() == *s) { + continue; + } + let Ok(m) = entry.metadata() else { continue }; + if m.nlink() > 1 && !m.is_dir() && !seen.insert((m.dev(), m.ino())) { + continue; + } + total += m.blocks() * 512; + if m.is_dir() && m.dev() == dev { + total += walk(&entry.path(), &[], dev, seen); + } + } + total + } + let Ok(m) = fs::symlink_metadata(dir) else { return 0 }; + walk(dir, skip, m.dev(), &mut std::collections::HashSet::new()) +} + +/// The nearest folder of `path` that exists: `path` itself, or the one a +/// new folder there would be made in. +pub fn existing_ancestor(path: &Path) -> Option<&Path> { + path.ancestors().find(|p| p.is_dir()) +} + +/// The filesystem's name: `apfs`, `msdos`, `exfat` (macOS's names), or on +/// Linux the name of its magic number when it is one Kiri knows. +pub fn fs_name(path: &Path) -> io::Result { + let c = c_path(path)?; + // SAFETY: statfs is plain data, filled in by the call. + let mut s: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: a valid path and a statfs to fill. + if unsafe { libc::statfs(c.as_ptr(), &mut s) } != 0 { + return Err(io::Error::last_os_error()); + } + #[cfg(target_os = "macos")] + { + // SAFETY: f_fstypename is a NUL-terminated C string the call filled. + Ok(unsafe { std::ffi::CStr::from_ptr(s.f_fstypename.as_ptr()) }.to_string_lossy().into_owned()) + } + #[cfg(not(target_os = "macos"))] + { + Ok(linux_fs_name(s.f_type as u64)) + } +} + +#[cfg(not(target_os = "macos"))] +fn linux_fs_name(magic: u64) -> String { + match magic { + 0xEF53 => "ext4".into(), + 0x5846_5342 => "xfs".into(), + 0x9123_683E => "btrfs".into(), + 0x0102_1994 => "tmpfs".into(), + 0x794C_7630 => "overlay".into(), + 0x2FC1_2FC1 => "zfs".into(), + 0x6969 => "nfs".into(), + 0x4d44 => "msdos".into(), + 0x2011_BAB0 => "exfat".into(), + 0x5346_544E => "ntfs".into(), + 0x6573_5546 => "fuseblk".into(), + m => format!("{m:#x}"), + } +} + +/// FAT and exFAT can't hold Kiri's data: no sparse files (the VM's disk +/// would take its whole 64 GiB, and FAT32 stops at 4 GiB a file), no owners +/// or permissions, no links. +pub fn refused_fs(name: &str) -> bool { + matches!(name, "msdos" | "vfat" | "exfat") +} + +/// Bytes free for this user on the filesystem of `path`. +pub fn free_space(path: &Path) -> io::Result { + let c = c_path(path)?; + // SAFETY: statvfs is plain data, filled in by the call. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: a valid path and a statvfs to fill. + if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(s.f_bavail as u64 * s.f_frsize as u64) +} + +/// The device a path is on. +pub fn device(path: &Path) -> io::Result { + Ok(fs::metadata(path)?.dev()) +} + +/// Writes a file into `dir`, syncs it and removes it: whether Kiri can +/// really write there (a read-only volume, or one this user may not write). +pub fn probe_writable(dir: &Path) -> io::Result<()> { + let probe = dir.join(format!(".kiri-probe-{}", std::process::id())); + let result = (|| { + let f = OpenOptions::new().write(true).create_new(true).open(&probe)?; + f.write_all_at(b"kiri", 0)?; + f.sync_all() + })(); + let _ = fs::remove_file(&probe); + result +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-treecopy-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + fn none(_: u64) -> io::Result<()> { + Ok(()) + } + + /// A 128 MiB file with two 64 KiB islands of data copies byte for byte + /// and stays sparse: well under 2 MiB on disk, not 128 MiB (#355: a + /// 2 GiB file using 16 KB took 2 GiB with std::fs::copy across volumes). + #[test] + fn a_sparse_file_stays_sparse() { + let d = scratch("sparse"); + let (src, dst) = (d.join("data.img"), d.join("copy.img")); + let f = File::create(&src).unwrap(); + f.set_len(128 << 20).unwrap(); + let island: Vec = (0..64 << 10).map(|i: u32| (i % 251) as u8 | 1).collect(); + f.write_all_at(&island, 10 << 20).unwrap(); + f.write_all_at(&island, 100 << 20).unwrap(); + f.sync_all().unwrap(); + drop(f); + let mut copied = 0; + copy_sparse(&src, &dst, &mut |n| { + copied += n; + Ok(()) + }) + .unwrap(); + assert_eq!(sha256(&src).unwrap(), sha256(&dst).unwrap(), "the copy has the same bytes"); + let m = fs::metadata(&dst).unwrap(); + assert_eq!(m.len(), 128 << 20); + assert!(m.blocks() * 512 < 2 << 20, "the copy takes {} bytes on disk, not under 2 MiB", m.blocks() * 512); + assert!(copied < 128 << 20, "only the data was read: {copied} bytes"); + let _ = fs::remove_dir_all(&d); + } + + /// Without SEEK_DATA the zeros are still left out. + #[test] + fn runs_of_zeros_are_left_out() { + let d = scratch("zeros"); + let (src, dst) = (d.join("a"), d.join("b")); + let mut bytes = vec![0u8; 8 << 20]; + bytes[3 << 20] = 7; + fs::write(&src, &bytes).unwrap(); + let (from, to) = (File::open(&src).unwrap(), OpenOptions::new().write(true).create_new(true).open(&dst).unwrap()); + let written = copy_range(&from, &to, 0, bytes.len() as u64, &mut none).unwrap(); + finish_sparse(&to, bytes.len() as u64, &written).unwrap(); + assert_eq!(fs::read(&dst).unwrap(), bytes); + assert!(fs::metadata(&dst).unwrap().blocks() * 512 < 1 << 20); + let _ = fs::remove_dir_all(&d); + } + + /// A folder comes over whole: files, links, modes, a hard link as one + /// file, and nothing of what `skip` names; the check passes, and finds + /// a changed blob. + #[test] + fn a_folder_copies_and_checks_whole() { + let d = scratch("tree"); + let src = d.join("src"); + let hex = sha256_of(b"layer"); + fs::create_dir_all(src.join("blobs/sha256")).unwrap(); + fs::create_dir_all(src.join("vm")).unwrap(); + fs::write(src.join("blobs/sha256").join(&hex), b"layer").unwrap(); + fs::write(src.join("images.json"), b"[]").unwrap(); + fs::write(src.join("vm/mac"), b"02:00:00:00:00:01").unwrap(); + fs::set_permissions(src.join("vm/mac"), fs::Permissions::from_mode(0o640)).unwrap(); + fs::hard_link(src.join("images.json"), src.join("images.link")).unwrap(); + std::os::unix::fs::symlink("images.json", src.join("current")).unwrap(); + fs::create_dir_all(src.join(".kiri-moving")).unwrap(); + let dst = d.join("dst"); + copy_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap(); + assert_eq!(fs::read(dst.join("blobs/sha256").join(&hex)).unwrap(), b"layer"); + assert_eq!(fs::metadata(dst.join("vm/mac")).unwrap().permissions().mode() & 0o777, 0o640); + assert_eq!(fs::metadata(dst.join("images.json")).unwrap().ino(), fs::metadata(dst.join("images.link")).unwrap().ino()); + assert_eq!(fs::read_link(dst.join("current")).unwrap(), Path::new("images.json")); + assert!(!dst.join(".kiri-moving").exists()); + verify_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap(); + fs::write(dst.join("blobs/sha256").join(&hex), b"LAYER").unwrap(); + assert!(verify_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap_err().to_string().contains("digest")); + let _ = fs::remove_dir_all(&d); + } + + fn sha256_of(b: &[u8]) -> String { + use sha2::Digest as _; + sha2::Sha256::digest(b).iter().map(|x| format!("{x:02x}")).collect() + } + + #[test] + fn fat_and_exfat_are_refused() { + assert!(refused_fs("msdos") && refused_fs("exfat") && refused_fs("vfat")); + assert!(!refused_fs("apfs") && !refused_fs("ext4")); + #[cfg(not(target_os = "macos"))] + assert_eq!((linux_fs_name(0x4d44), linux_fs_name(0x2011_BAB0)), ("msdos".to_owned(), "exfat".to_owned())); + } +} diff --git a/crates/kiri/src/guest.rs b/crates/kiri/src/guest.rs index 240466869..4eb66e21d 100644 --- a/crates/kiri/src/guest.rs +++ b/crates/kiri/src/guest.rs @@ -155,7 +155,7 @@ impl Guest { cmdline: String::new(), console: console_output(opts)?, agent_port: kiri_proto::HOST_PORT, - disk: None, + disk: if opts.data_disk { linux_agent_data()? } else { None }, share: None, rosetta_tag: None, nat_mac: None, @@ -381,6 +381,19 @@ fn unexpected(wanted: &str, got: &Msg<'_>) -> io::Error { io::Error::other(format!("expected {wanted}, got {got:?}")) } +/// The agent's data folder on a Linux host when Settings → Storage moved it +/// off the default location: `/agent`, which `kiri-init` bind-mounts +/// onto `/var/lib/kiri`. None when using the default folder or `KIRI_DATA_DIR`. +#[cfg(target_os = "linux")] +fn linux_agent_data() -> io::Result> { + if std::env::var_os("KIRI_DATA_DIR").is_some() { + return Ok(None); + } + let root = kiri_image::Store::default_root()?; + let default = kiri_image::Store::os_default_root()?; + Ok((root != default).then(|| root.join("agent"))) +} + /// The agent on a Linux host: `KIRI_AGENT`, else `kiri-init` beside `kiri`. #[cfg(target_os = "linux")] fn agent_binary() -> PathBuf { diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index df748f5fe..fdac70fdf 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -501,6 +501,41 @@ pub fn after_tools() -> io::Result<()> { builder().map(drop) } +/// After Settings → Storage moved the data folder from `old`: Kiri Lite's +/// docker link (`~/.kiri/bin/docker`) and docker's plugin folder, which +/// point into the data folder, point into the new one. +pub fn relink_cli(old: &Path) -> io::Result<()> { + let new = kiri_image::Store::default_root()?; + let link = bin_dir()?.join("docker"); + if let Some(to) = std::fs::read_link(&link).ok().and_then(|t| moved(&t, old, &new)) { + std::fs::remove_file(&link)?; + std::os::unix::fs::symlink(to, &link)?; + } + let path = docker_dir()?.join("config.json"); + let mut cfg = read_json(&path)?; + if repoint_plugin_dirs(&mut cfg, old, &new) { + write_json(&path, &cfg)?; + } + Ok(()) +} + +/// `path` under `new` instead of `old`, if it was under `old`. +fn moved(path: &Path, old: &Path, new: &Path) -> Option { + path.strip_prefix(old).ok().map(|rest| new.join(rest)) +} + +/// Moves docker's plugin folders under `old` to `new`; whether any moved. +fn repoint_plugin_dirs(cfg: &mut Value, old: &Path, new: &Path) -> bool { + let mut changed = false; + for d in cfg["cliPluginsExtraDirs"].as_array_mut().into_iter().flatten() { + if let Some(to) = d.as_str().and_then(|s| moved(Path::new(s), old, new)) { + *d = to.to_string_lossy().into_owned().into(); + changed = true; + } + } + changed +} + /// The context, as `docker context create kiri --docker host=…` writes it. fn context(socket: &Path) -> io::Result<()> { crate::dockerctx::write_context(&context_dir(CONTEXT.get())?, CONTEXT.get(), crate::flavor::APP.get(), &format!("unix://{}", socket.display())) @@ -1021,6 +1056,19 @@ mod tests { d } + /// Settings → Storage moved the data folder: Kiri Lite's plugin folder + /// follows it, and other plugin folders stay. + #[test] + fn plugin_folders_follow_the_data_folder() { + use std::path::Path; + let (old, new) = (Path::new("/Users/u/Library/Application Support/Kiri"), Path::new("/Volumes/External/kiri")); + let mut cfg = serde_json::json!({"cliPluginsExtraDirs": ["/opt/homebrew/lib/docker/cli-plugins", "/Users/u/Library/Application Support/Kiri/cli/cli-plugins"]}); + assert!(super::repoint_plugin_dirs(&mut cfg, old, new)); + assert_eq!(cfg["cliPluginsExtraDirs"], serde_json::json!(["/opt/homebrew/lib/docker/cli-plugins", "/Volumes/External/kiri/cli/cli-plugins"])); + assert!(!super::repoint_plugin_dirs(&mut cfg, old, new), "nothing left to move"); + assert_eq!(super::moved(Path::new("/elsewhere/docker"), old, new), None); + } + #[test] fn docker_sock_owner() { use crate::dockerctx::Endpoint::*; diff --git a/crates/kiri/src/ui/gtk.rs b/crates/kiri/src/ui/gtk.rs index 6af6a9cb5..4604c8ddc 100644 --- a/crates/kiri/src/ui/gtk.rs +++ b/crates/kiri/src/ui/gtk.rs @@ -406,6 +406,19 @@ pub(super) fn pick_compose_file(title: &str, filters: &[String; 2], done: impl F }); } +/// Settings → Storage → Change…: GTK's folder chooser (the desktop's portal +/// when there is one), on GTK's main thread. `done` gets the path, or None. +pub(super) fn pick_folder(title: &str, done: impl FnOnce(Option) + Send + 'static) { + let title = title.to_owned(); + glib::MainContext::default().invoke(move || { + let parent = WINDOW.with(|v| v.borrow().clone()); + let dialog = gtk::FileChooserNative::new(Some(&title), parent.as_ref(), gtk::FileChooserAction::SelectFolder, None, None); + let picked = if dialog.run() == gtk::ResponseType::Accept { dialog.filename() } else { None }; + dialog.destroy(); + done(picked); + }); +} + /// The installed font families, sorted; `mono` keeps the fixed-pitch ones. pub(super) fn font_families(mono: bool) -> Vec { let spacing = if mono { ":spacing=mono" } else { ":" }; diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index fe37d579e..682eb3702 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -1167,6 +1167,29 @@ .pref + .rp-notes { margin-top: -6px; } .pref .sockhint { display: inline-flex; align-items: center; gap: 4px; flex-wrap: wrap; margin-top: 4px; color: var(--text); } .pref .sockhint code { padding: 1px 6px; border-radius: 5px; background: var(--panel); border: 1px solid var(--line); font: var(--fs-mono) var(--mono-font); user-select: text; -webkit-user-select: text; } +/* Settings → Storage */ +.st-t { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.st-badge { font-size: var(--fs-small); font-weight: 500; padding: 1px 7px; border-radius: 99px; background: color-mix(in srgb, var(--blue) 16%, transparent); color: var(--text); } +.st-path { overflow-wrap: anywhere; word-break: break-word; color: var(--text); } +.st-meta { display: block; margin-top: 4px; font-variant-numeric: tabular-nums; } +.pref .st-acts { grid-row: 1 / span 2; grid-column: 2; display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; } +.st-box { border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; background: var(--panel); display: grid; gap: 8px; min-width: 0; } +.st-box.warn { border-color: color-mix(in srgb, var(--sun) 45%, var(--line)); background: color-mix(in srgb, var(--sun) 8%, var(--panel)); } +.st-box.err { border-color: color-mix(in srgb, var(--red) 45%, var(--line)); background: color-mix(in srgb, var(--red) 8%, var(--panel)); } +.st-box .st-hd { display: flex; align-items: center; gap: 8px; font-weight: 600; } +.st-box.warn .st-hd svg { color: var(--sun-text); flex: none; } +.st-box.err .st-hd svg { color: var(--red-text); flex: none; } +.st-box p { color: var(--muted); font-size: var(--fs); overflow-wrap: anywhere; } +.st-box .st-row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 4px; } +.st-bar { width: 100%; height: 6px; border-radius: 9px; background: var(--raised); overflow: hidden; } +.st-bar span { display: block; height: 100%; background: var(--blue); } +.st-opts { display: grid; gap: 8px; margin-top: 4px; } +.st-opt { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 2px 10px; align-items: start; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); cursor: pointer; } +.st-opt:has(input:checked) { border-color: var(--blue); background: color-mix(in srgb, var(--blue) 8%, var(--bg)); } +.st-opt input { margin-top: 3px; accent-color: var(--blue); } +.st-opt b { font-weight: 600; color: var(--text); } +.st-opt small { grid-column: 2; color: var(--muted); font-size: var(--fs-small); } +@media (max-width: 520px) { .pref.st-pref { grid-template-columns: minmax(0, 1fr); } .pref.st-pref .st-acts { grid-row: auto; grid-column: 1; justify-content: flex-start; margin-top: 8px; } } /* Chinese and Japanese break between any two characters: a short choice (关闭, 开启) stays on one line, as an English word does; Korean's too. Only in a CJK window, so English lays out as it did. */ @@ -2780,7 +2803,7 @@

Containers

({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); -const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, +const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, storage: null, stErr: "", proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, imp: { sources: null, source: null, inv: null, picked: { images: new Set(), volumes: new Set(), containers: new Set() }, steps: {}, running: false, summary: "" }, upd: null, engineStale: null, staleHidden: false, // The Builds view: the list, the picked build and its detail, and how its steps show. @@ -4543,6 +4566,125 @@

${tr("Use {app} for docker?", { app: esc(app) })}

return `

${tr("WSL integration")}

${rows}
`; } +/* Settings → Storage: where Kiri keeps images, containers, and volumes. */ +const stPhaseText = (p) => ({ + stopping: tr("Stopping containers…"), + copying: tr("Copying data…"), + verifying: tr("Verifying copy…"), + switching: tr("Switching storage…"), + restarting: tr("Restarting engine…"), +}[p] || tr("Moving data…")); + +function storageUnavailableBox(s, linkSettings) { + return ``; +} + +function renderStorageUnavailable() { + const s = ui.storage || {}; + $("content").innerHTML = `
+

${tr("Storage location unavailable")}

+

${tr("Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.", { path: `${esc(s.path || "")}` })}

+
+ + + + +
`; +} + +function storagePane() { + const s = ui.storage; + if (!s) return `

${tr("Storage")}

${tr("Loading…")}

`; + if (s.error && !s.path) return `

${tr("Storage")}

${tr("Start Kiri to change its storage location. ({error})", { error: esc(s.error) })}

`; + const moving = s.state === "moving", unavail = s.state === "unavailable", locked = moving || !!s.env; + const stats = [s.used != null ? tr("{size} used", { size: size(s.used) }) : "", s.free != null ? tr("{size} free", { size: size(s.free) }) : "", s.fs ? esc(s.fs) : ""].filter(Boolean).join(" · "); + const badge = !s.custom && !s.env ? `${tr("Default")}` : ""; + const m = s.moving; + const pct = m && m.total > 0 ? Math.min(100, Math.round((m.done / m.total) * 100)) : null; + const progressBox = moving && m ? `
+
${stPhaseText(m.phase)}
+

${tr("Moving Kiri's data to {path}.", { path: `${esc(m.to || "")}` })}

+ ${pct != null ? `

${size(m.done)} / ${size(m.total)} (${pct}%)

` : ""} +

${tr("Running containers pause while Kiri copies its data and start again once it's done.")}

+
` : ""; + const errText = ui.stErr || (!moving && s.error ? s.error : ""); + const errBox = errText ? `` : ""; + const oldRow = s.old && s.state === "ok" ? `
+ ${tr("Old data")} + ${tr("Previous data is still in {path}. Remove it once everything works in the new location.", { path: `${esc(s.old)}` })} + +
` : ""; + return `

${tr("Storage")}

+ ${unavail ? storageUnavailableBox(s, false) : ""} +
+ ${tr("Storage location")}${badge} + ${esc(s.path || "")}${stats ? `${stats}` : ""} + + + ${s.custom ? `` : ""} + +
+ ${s.env ? `

${tr("{var} sets Kiri's storage location, so it can't be changed here.", { var: `KIRI_DATA_DIR` })}

` : ""} + ${progressBox} + ${errBox} + ${oldRow} +

${tr("Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.")}

+
`; +} + +function storageConfirm(c) { + $("st-dlg")?.remove(); + const s = ui.storage || {}; + const unavail = s.state === "unavailable"; + const hasData = !unavail && ((s.used || 0) > 0 || ui.containers.length > 0 || ui.images.length > 0 || ui.volumes.length > 0); + const showMode = !c.reset && hasData; + const title = c.reset ? tr("Reset storage location to default?") : tr("Change storage location?"); + const meta = !unavail && c.free != null ? `

${tr("Destination: {path} ({free} free).", { path: `${esc(c.path)}`, free: size(c.free) })}

` + : `

${tr("Destination: {path}.", { path: `${esc(c.path)}` })}

`; + const warn = c.replaces ? `

${tr("Existing Kiri data in this folder will be replaced.")}

` : ""; + const modeHtml = showMode ? `
+ + +
` : `

${unavail ? tr("Kiri will switch to this folder and restart the engine.") : tr("Running containers will stop while Kiri moves your data and start again once it's done.")}

`; + const scrim = document.createElement("div"); + scrim.className = "scrim"; scrim.id = "st-dlg"; + scrim.innerHTML = ``; + document.body.append(scrim); + const goBtn = scrim.querySelector("[data-stgo]"); + const close = () => { scrim.remove(); document.removeEventListener("keydown", onKey); }; + const onKey = (ev) => { if (ev.key === "Escape") close(); }; + document.addEventListener("keydown", onKey); + scrim.querySelectorAll('input[name="st-mode"]').forEach((r) => r.addEventListener("change", () => { + goBtn.textContent = r.value === "fresh" && r.checked ? tr("Start fresh") : tr("Move data"); + })); + scrim.addEventListener("click", (ev) => { + if (ev.target === scrim || ev.target.closest("[data-stcancel]")) return close(); + if (ev.target.closest("[data-stgo]")) { + const fresh = scrim.querySelector('input[name="st-mode"]:checked')?.value === "fresh"; + ui.stErr = ""; + if (c.reset) send("storagereset"); + else send("storagemove", { path: c.path, value: { fresh } }); + close(); + } + }); + goBtn.focus(); +} + function renderSettings() { const tab = (id, icon, label) => ``; const opts = (list, current, system) => { @@ -4637,8 +4779,8 @@

${tr("Use {app} for docker?", { app: esc(app) })}

${tr("Made by")}
Canestack Labs

${tr("The name comes from the Igbo word ntakịrị, “small”.")}

`; - const html = `
${tab("appearance", "textaa", tr("Appearance"))}${tab("resources", "stack", tr("Resources"))}${tab("network", "globe", tr("Network"))}${tab("builds", "hammer", tr("Builds"))}${tab("registries", "lock", tr("Registries"))}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", tr("Import"))}${tab("domains", "network", tr("Domains"))}${tab("diagnostics", "bug", tr("Diagnostics"))}${tab("about", "info", tr("About"))}
- ${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}
`; + const html = `
${tab("appearance", "textaa", tr("Appearance"))}${tab("resources", "stack", tr("Resources"))}${tab("storage", "harddrive", tr("Storage"))}${tab("network", "globe", tr("Network"))}${tab("builds", "hammer", tr("Builds"))}${tab("registries", "lock", tr("Registries"))}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", tr("Import"))}${tab("domains", "network", tr("Domains"))}${tab("diagnostics", "bug", tr("Diagnostics"))}${tab("about", "info", tr("About"))}
+ ${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "storage" ? storagePane() : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}
`; // The container lists arrive every few seconds; rebuilding an unchanged page // closes an open menu. The font menus list names in the interface font: an // option in its own font made WebKit load every installed font (438 here) @@ -4693,7 +4835,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

if (view === "compose") { cmp.open = null; cmp.asked = 0; cmpAsk(); } if (view === "usb") usbPoll(); if (view === "share") { send("shares"); send("shareusage"); shPoll(); } - if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("dockersock"); send("proxy"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } + if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("storage"); send("dockersock"); send("proxy"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } render(); // From the top, as a container's or pod's page opens: leaving a page scrolled // down (a long Terminal or Logs tab) otherwise opened the next view below its rows. @@ -7053,6 +7195,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) if (v === "share") return renderShare(); // The devices are the computer's: listed whether the engine runs or not. if (v === "usb") return renderUsb(); + if (ui.storage?.state === "unavailable") return renderStorageUnavailable(); if (ui.vm === "stopped") return renderEmpty("stopped"); if ((v === "containers" || v === "compose") && ui.detail) { // The list refreshes while you edit the environment: keep your place. @@ -8316,6 +8459,17 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r break; } case "resources": ui.res = e; ui.resDraft = { cpus: e.cpus, memory_mib: e.memory_mib, ...(e.disk_gb != null ? { disk_gb: e.disk_gb } : {}) }; if (ui.view === "settings") render(); break; + case "storage": { + const wasUnavail = ui.storage?.state === "unavailable"; + ui.storage = e; + if (e.state === "moving") ui.stErr = ""; + if (ui.view === "settings" || e.state === "unavailable" || wasUnavail) render(); + break; + } + case "storagecheck": + if (e.error) { ui.stErr = e.error; if (ui.view === "settings") render(); else toast("error", e.error); } + else { ui.stErr = ""; storageConfirm(e); } + break; case "detail": openDetail(e.id); break; case "inspect": if (ui.detail?.id === e.id) { @@ -8415,7 +8569,20 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-g]"))) projectAsk(el.dataset.project, el.dataset.g); else if ((el = t("[data-group]"))) toggleGroup(el); else if (composeClick(t)) {} - else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "network") { send("proxy"); send("dockersock"); } if (prefs.tab === "builds") send("buildwith"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } + else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "storage") send("storage"); if (prefs.tab === "network") { send("proxy"); send("dockersock"); } if (prefs.tab === "builds") send("buildwith"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } + else if (t("[data-stpick]")) { ui.stErr = ""; send("storagepick"); } + else if (t("[data-streset]")) { + if (ui.storage?.state === "unavailable") { + confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => send("storagereset"), "primary"); + } else { + ui.stErr = ""; + send("storagecheck", { path: "", value: { reset: true } }); + } + } + else if (t("[data-stretry]")) { ui.stErr = ""; send("storageretry"); } + else if (t("[data-strmold]")) { confirmRemove(tr("Remove old data?"), tr("Everything in {path} will be deleted for good.", { path: `${esc(ui.storage?.old || "")}` }), tr("Remove"), () => send("storageremoveold")); } + else if (t("[data-sterrclose]")) { ui.stErr = ""; render(); } + else if (t("[data-stgoto]")) { prefs.tab = "storage"; show("settings"); } else if (diagClick(t)) {} else if ((el = t("[data-scale]"))) setPref("scale", +el.dataset.scale); else if ((el = t("[data-logsize]"))) setPref("logSize", +el.dataset.logsize); diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index da33e5e7a..a99112192 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1887,5 +1887,50 @@ "Switching…": "በመቀየር ላይ…", "{docker} command": "{docker} ትዕዛዝ", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock አሁን ወደ Kiri ያመለክታል", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sockን ማገናኘት አልተቻለም: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sockን ማገናኘት አልተቻለም: {error}", + "Stopping containers…": "ኮንቴይነሮችን በማቆም ላይ…", + "Copying data…": "ውሂብ በመቅዳት ላይ…", + "Verifying copy…": "ቅጂውን በማረጋገጥ ላይ…", + "Switching storage…": "ማከማቻ በመቀየር ላይ…", + "Restarting engine…": "ሞተሩን እንደገና በማስጀመር ላይ…", + "Moving data…": "ውሂብ በማንቀሳቀስ ላይ…", + "Storage location unavailable": "የማከማቻ ቦታው አይገኝም", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ውሂቡን በ{path} ውስጥ ማግኘት አልቻለም። ድራይቩን ያገናኙና እንደገና ይሞክሩ፣ ሌላ አቃፊ ይምረጡ ወይም ወደ ነባሪው ቦታ ይመልሱ።", + "Change…": "ቀይር…", + "Reset to default": "ወደ ነባሪ መልስ", + "Open storage settings": "የማከማቻ ቅንብሮችን ክፈት", + "Start Kiri to change its storage location. ({error})": "የማከማቻ ቦታውን ለመቀየር Kiriን ያስጀምሩ። ({error})", + "{size} used": "{size} ጥቅም ላይ ውሏል", + "{size} free": "{size} ነፃ", + "Default": "ነባሪ", + "Moving Kiri's data to {path}.": "የKiri ውሂብ ወደ {path} በማንቀሳቀስ ላይ።", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri ውሂቡን በሚቀዳበት ጊዜ የሚሰሩ ኮንቴይነሮች ይቆማሉ፣ ሲጨርስ እንደገና ይጀምራሉ።", + "Couldn't change storage location": "የማከማቻ ቦታውን መቀየር አልተቻለም", + "Old data": "የቆየ ውሂብ", + "Previous data is still in {path}. Remove it once everything works in the new location.": "የቀድሞው ውሂብ አሁንም በ{path} ውስጥ አለ። ሁሉም ነገር በአዲሱ ቦታ ሲሰራ ያስወግዱት።", + "Remove old data": "የቆየ ውሂብ አስወግድ", + "Storage location": "የማከማቻ ቦታ", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} የKiri የማከማቻ ቦታን ያዘጋጃል፣ ስለዚህ እዚህ መቀየር አይቻልም።", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "ምስሎች፣ ኮንቴይነሮች እና ቮልዩሞች በዚህ አቃፊ ውስጥ ይቀመጣሉ። ውጫዊ ድራይቮች የራሳቸውን የፋይል ሲስተም (APFS በmacOS፣ ext4/xfs/btrfs በLinux፣ NTFS በWindows) መጠቀም አለባቸው፤ FAT እና exFAT አይደገፉም።", + "Reset storage location to default?": "የማከማቻ ቦታውን ወደ ነባሪ ይመለስ?", + "Change storage location?": "የማከማቻ ቦታውን ይቀየር?", + "Destination: {path} ({free} free).": "መድረሻ፦ {path} ({free} ነፃ)።", + "Destination: {path}.": "መድረሻ፦ {path}።", + "Existing Kiri data in this folder will be replaced.": "በዚህ አቃፊ ውስጥ ያለው የKiri ውሂብ ይተካል።", + "Migration mode": "የማዛወሪያ ሁነታ", + "Move existing images, containers, and volumes": "ያሉትን ምስሎች፣ ኮንቴይነሮች እና ቮልዩሞች አዛውር", + "Stops running containers, copies your data, and starts them again.": "የሚሰሩ ኮንቴይነሮችን ያቆማል፣ ውሂብዎን ይቀዳል፣ እና እንደገና ያስጀምራቸዋል።", + "Start fresh": "ከባዶ ጀምር", + "Starts empty in the new folder. Your old folder stays until you remove it.": "በአዲሱ አቃፊ ውስጥ ባዶ ሆኖ ይጀምራል። የቆየው አቃፊዎ እስኪያስወግዱት ድረስ ይቆያል።", + "Kiri will switch to this folder and restart the engine.": "Kiri ወደዚህ አቃፊ ይቀይራል እና ሞተሩን እንደገና ያስጀምራል።", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri ውሂብዎን በሚያዛውርበት ጊዜ የሚሰሩ ኮንቴይነሮች ይቆማሉ፣ ሲጨርስ እንደገና ይጀምራሉ።", + "Move data": "ውሂብ አዛውር", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri ወደ ነባሪው አቃፊ ይመለሳል እና ሞተሩን እንደገና ያስጀምራል። በተነቀለው ድራይቭ ላይ ያለው ውሂብ አይሰረዝም።", + "Remove old data?": "የቆየ ውሂብ ይወገድ?", + "Everything in {path} will be deleted for good.": "በ{path} ውስጥ ያለው ሁሉም ነገር ለዘላለም ይሰረዛል።", + "Choose a storage folder": "የማከማቻ አቃፊ ይምረጡ", + "Kiri's data is moving already": "የKiri ውሂብ አሁን እየተዛወረ ነው", + "Kiri's data moved to {path}": "የKiri ውሂብ ወደ {path} ተዛውሯል", + "Storage is available again": "ማከማቻው እንደገና ይገኛል", + "Old data removed": "የቆየ ውሂብ ተወግዷል" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index b1e270953..685a5daa7 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1887,5 +1887,50 @@ "Switching…": "جارٍ التبديل…", "{docker} command": "أمر {docker}", "/var/run/docker.sock now points to Kiri": "يشير /var/run/docker.sock الآن إلى Kiri", - "Could not link /var/run/docker.sock: {error}": "تعذّر ربط /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "تعذّر ربط /var/run/docker.sock: {error}", + "Stopping containers…": "جارٍ إيقاف الحاويات…", + "Copying data…": "جارٍ نسخ البيانات…", + "Verifying copy…": "جارٍ التحقق من النسخة…", + "Switching storage…": "جارٍ تبديل التخزين…", + "Restarting engine…": "جارٍ إعادة تشغيل المحرك…", + "Moving data…": "جارٍ نقل البيانات…", + "Storage location unavailable": "موقع التخزين غير متاح", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "تعذر على Kiri العثور على بياناته في {path}. وصّل القرص وأعد المحاولة، أو اختر مجلدًا آخر، أو أعد التعيين إلى الموقع الافتراضي.", + "Change…": "تغيير…", + "Reset to default": "إعادة التعيين إلى الافتراضي", + "Open storage settings": "فتح إعدادات التخزين", + "Start Kiri to change its storage location. ({error})": "شغّل Kiri لتغيير موقع التخزين. ({error})", + "{size} used": "{size} مستخدم", + "{size} free": "{size} متاح", + "Default": "افتراضي", + "Moving Kiri's data to {path}.": "جارٍ نقل بيانات Kiri إلى {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "تتوقف الحاويات قيد التشغيل مؤقتًا أثناء نسخ Kiri لبياناته وتعود للعمل عند الانتهاء.", + "Couldn't change storage location": "تعذر تغيير موقع التخزين", + "Old data": "البيانات القديمة", + "Previous data is still in {path}. Remove it once everything works in the new location.": "لا تزال البيانات السابقة في {path}. أزلها بمجرد أن يعمل كل شيء في الموقع الجديد.", + "Remove old data": "إزالة البيانات القديمة", + "Storage location": "موقع التخزين", + "{var} sets Kiri's storage location, so it can't be changed here.": "يحدد {var} موقع تخزين Kiri، لذا لا يمكن تغييره من هنا.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "تُحفظ الصور والحاويات ووحدات التخزين في هذا المجلد. يجب أن تستخدم الأقراص الخارجية نظام ملفات أصليًا (APFS على macOS، وext4/xfs/btrfs على Linux، وNTFS على Windows)؛ أقراص FAT وexFAT غير مدعومة.", + "Reset storage location to default?": "إعادة تعيين موقع التخزين إلى الافتراضي؟", + "Change storage location?": "تغيير موقع التخزين؟", + "Destination: {path} ({free} free).": "الوجهة: {path} ({free} متاح).", + "Destination: {path}.": "الوجهة: {path}.", + "Existing Kiri data in this folder will be replaced.": "سيتم استبدال بيانات Kiri الموجودة في هذا المجلد.", + "Migration mode": "وضع النقل", + "Move existing images, containers, and volumes": "نقل الصور والحاويات ووحدات التخزين الحالية", + "Stops running containers, copies your data, and starts them again.": "يوقف الحاويات قيد التشغيل وينسخ بياناتك ثم يعيد تشغيلها.", + "Start fresh": "البدء من جديد", + "Starts empty in the new folder. Your old folder stays until you remove it.": "يبدأ فارغًا في المجلد الجديد. يبقى المجلد القديم حتى تزيله.", + "Kiri will switch to this folder and restart the engine.": "سينتقل Kiri إلى هذا المجلد ويعيد تشغيل المحرك.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "ستتوقف الحاويات قيد التشغيل أثناء نقل Kiri لبياناتك وتعود للعمل عند الانتهاء.", + "Move data": "نقل البيانات", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "سيعود Kiri إلى مجلده الافتراضي ويعيد تشغيل المحرك. لن تُحذف البيانات الموجودة على القرص المفصول.", + "Remove old data?": "إزالة البيانات القديمة؟", + "Everything in {path} will be deleted for good.": "سيُحذف كل شيء في {path} نهائيًا.", + "Choose a storage folder": "اختر مجلد التخزين", + "Kiri's data is moving already": "بيانات Kiri قيد النقل بالفعل", + "Kiri's data moved to {path}": "تم نقل بيانات Kiri إلى {path}", + "Storage is available again": "التخزين متاح مرة أخرى", + "Old data removed": "تمت إزالة البيانات القديمة" } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index ca4f4a324..2c5e42dce 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1887,5 +1887,50 @@ "Switching…": "Превключване…", "{docker} command": "Команда {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock вече сочи към Kiri", - "Could not link /var/run/docker.sock: {error}": "Неуспешно свързване на /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Неуспешно свързване на /var/run/docker.sock: {error}", + "Stopping containers…": "Спиране на контейнерите…", + "Copying data…": "Копиране на данните…", + "Verifying copy…": "Проверка на копието…", + "Switching storage…": "Превключване на хранилището…", + "Restarting engine…": "Рестартиране на двигателя…", + "Moving data…": "Преместване на данните…", + "Storage location unavailable": "Мястото за съхранение е недостъпно", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri не намери данните си в {path}. Свържете диска и опитайте отново, изберете друга папка или възстановете стандартното място.", + "Change…": "Промяна…", + "Reset to default": "Възстановяване по подразбиране", + "Open storage settings": "Отвори настройките за съхранение", + "Start Kiri to change its storage location. ({error})": "Стартирайте Kiri, за да промените мястото за съхранение. ({error})", + "{size} used": "{size} използвани", + "{size} free": "{size} свободни", + "Default": "По подразбиране", + "Moving Kiri's data to {path}.": "Преместване на данните на Kiri в {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Работещите контейнери спират, докато Kiri копира данните си, и се стартират отново след това.", + "Couldn't change storage location": "Мястото за съхранение не можа да бъде променено", + "Old data": "Стари данни", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Предишните данни все още са в {path}. Премахнете ги, след като всичко работи на новото място.", + "Remove old data": "Премахни старите данни", + "Storage location": "Място за съхранение", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} задава мястото за съхранение на Kiri, така че не може да се променя тук.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Образите, контейнерите и томовете се пазят в тази папка. Външните дискове трябва да използват локална файлова система (APFS за macOS, ext4/xfs/btrfs за Linux, NTFS за Windows); дискове FAT и exFAT не се поддържат.", + "Reset storage location to default?": "Възстановяване на стандартното място за съхранение?", + "Change storage location?": "Промяна на мястото за съхранение?", + "Destination: {path} ({free} free).": "Цел: {path} ({free} свободни).", + "Destination: {path}.": "Цел: {path}.", + "Existing Kiri data in this folder will be replaced.": "Съществуващите данни на Kiri в тази папка ще бъдат заменени.", + "Migration mode": "Режим на преместване", + "Move existing images, containers, and volumes": "Премести съществуващите образи, контейнери и томове", + "Stops running containers, copies your data, and starts them again.": "Спира работещите контейнери, копира данните ви и ги стартира отново.", + "Start fresh": "Започни на чисто", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Започва празно в новата папка. Старата папка остава, докато не я премахнете.", + "Kiri will switch to this folder and restart the engine.": "Kiri ще превключи към тази папка и ще рестартира двигателя.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Работещите контейнери ще спрат, докато Kiri мести данните ви, и ще се стартират отново след това.", + "Move data": "Премести данните", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri ще се върне към стандартната папка и ще рестартира двигателя. Данните на изключения диск не се изтриват.", + "Remove old data?": "Премахване на старите данни?", + "Everything in {path} will be deleted for good.": "Всичко в {path} ще бъде изтрито завинаги.", + "Choose a storage folder": "Изберете папка за съхранение", + "Kiri's data is moving already": "Данните на Kiri вече се местят", + "Kiri's data moved to {path}": "Данните на Kiri са преместени в {path}", + "Storage is available again": "Хранилището отново е достъпно", + "Old data removed": "Старите данни са премахнати" } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 0830e3816..8d97762a8 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1887,5 +1887,50 @@ "Switching…": "পরিবর্তন করা হচ্ছে…", "{docker} command": "{docker} কমান্ড", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock এখন Kiri-কে নির্দেশ করে", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock লিঙ্ক করা যায়নি: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock লিঙ্ক করা যায়নি: {error}", + "Stopping containers…": "কন্টেইনার বন্ধ করা হচ্ছে…", + "Copying data…": "ডেটা কপি করা হচ্ছে…", + "Verifying copy…": "কপি যাচাই করা হচ্ছে…", + "Switching storage…": "স্টোরেজ পরিবর্তন করা হচ্ছে…", + "Restarting engine…": "ইঞ্জিন পুনরায় চালু করা হচ্ছে…", + "Moving data…": "ডেটা সরানো হচ্ছে…", + "Storage location unavailable": "স্টোরেজ অবস্থান পাওয়া যাচ্ছে না", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri {path}-এ তার ডেটা খুঁজে পায়নি। ড্রাইভটি সংযুক্ত করে আবার চেষ্টা করুন, অন্য ফোল্ডার বেছে নিন অথবা ডিফল্ট অবস্থানে রিসেট করুন।", + "Change…": "পরিবর্তন করুন…", + "Reset to default": "ডিফল্টে রিসেট করুন", + "Open storage settings": "স্টোরেজ সেটিংস খুলুন", + "Start Kiri to change its storage location. ({error})": "স্টোরেজ অবস্থান পরিবর্তন করতে Kiri চালু করুন। ({error})", + "{size} used": "{size} ব্যবহৃত", + "{size} free": "{size} খালি", + "Default": "ডিফল্ট", + "Moving Kiri's data to {path}.": "Kiri-এর ডেটা {path}-এ সরানো হচ্ছে।", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri ডেটা কপি করার সময় চলমান কন্টেইনারগুলো থেমে থাকবে এবং কাজ শেষ হলে আবার চালু হবে।", + "Couldn't change storage location": "স্টোরেজ অবস্থান পরিবর্তন করা যায়নি", + "Old data": "পুরনো ডেটা", + "Previous data is still in {path}. Remove it once everything works in the new location.": "আগের ডেটা এখনো {path}-এ রয়েছে। নতুন অবস্থানে সবকিছু ঠিকঠাক কাজ করলে এটি সরিয়ে ফেলুন।", + "Remove old data": "পুরনো ডেটা সরান", + "Storage location": "স্টোরেজ অবস্থান", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri-এর স্টোরেজ অবস্থান নির্ধারণ করে, তাই এখান থেকে পরিবর্তন করা যাবে না।", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "ইমেজ, কন্টেইনার এবং ভলিউম এই ফোল্ডারে থাকে। বাহ্যিক ড্রাইভে নেটিভ ফাইলসিস্টেম থাকতে হবে (macOS-এ APFS, Linux-এ ext4/xfs/btrfs, Windows-এ NTFS); FAT এবং exFAT ড্রাইভ সমর্থিত নয়।", + "Reset storage location to default?": "স্টোরেজ অবস্থান ডিফল্টে রিসেট করবেন?", + "Change storage location?": "স্টোরেজ অবস্থান পরিবর্তন করবেন?", + "Destination: {path} ({free} free).": "গন্তব্য: {path} ({free} খালি)।", + "Destination: {path}.": "গন্তব্য: {path}।", + "Existing Kiri data in this folder will be replaced.": "এই ফোল্ডারে থাকা Kiri-এর ডেটা প্রতিস্থাপিত হবে।", + "Migration mode": "স্থানান্তর পদ্ধতি", + "Move existing images, containers, and volumes": "বিদ্যমান ইমেজ, কন্টেইনার এবং ভলিউম সরান", + "Stops running containers, copies your data, and starts them again.": "চলমান কন্টেইনার বন্ধ করে, আপনার ডেটা কপি করে এবং সেগুলো আবার চালু করে।", + "Start fresh": "নতুন করে শুরু করুন", + "Starts empty in the new folder. Your old folder stays until you remove it.": "নতুন ফোল্ডারে খালি অবস্থায় শুরু হয়। আপনি না সরানো পর্যন্ত পুরনো ফোল্ডারটি থাকবে।", + "Kiri will switch to this folder and restart the engine.": "Kiri এই ফোল্ডারে সরে যাবে এবং ইঞ্জিন পুনরায় চালু করবে।", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri আপনার ডেটা সরানোর সময় চলমান কন্টেইনার বন্ধ থাকবে এবং শেষ হলে আবার চালু হবে।", + "Move data": "ডেটা সরান", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri তার ডিফল্ট ফোল্ডারে ফিরে যাবে এবং ইঞ্জিন পুনরায় চালু করবে। সংযোগবিচ্ছিন্ন ড্রাইভের ডেটা মুছে যাবে না।", + "Remove old data?": "পুরনো ডেটা সরাবেন?", + "Everything in {path} will be deleted for good.": "{path}-এর সবকিছু স্থায়ীভাবে মুছে ফেলা হবে।", + "Choose a storage folder": "একটি স্টোরেজ ফোল্ডার বেছে নিন", + "Kiri's data is moving already": "Kiri-এর ডেটা ইতিমধ্যে সরানো হচ্ছে", + "Kiri's data moved to {path}": "Kiri-এর ডেটা {path}-এ সরানো হয়েছে", + "Storage is available again": "স্টোরেজ আবার পাওয়া যাচ্ছে", + "Old data removed": "পুরনো ডেটা সরানো হয়েছে" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 8a54aa171..5aa584590 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1887,5 +1887,50 @@ "Switching…": "Canviant…", "{docker} command": "Ordre {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ara apunta a Kiri", - "Could not link /var/run/docker.sock: {error}": "No s’ha pogut enllaçar /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "No s’ha pogut enllaçar /var/run/docker.sock: {error}", + "Stopping containers…": "Aturant els contenidors…", + "Copying data…": "Copiant les dades…", + "Verifying copy…": "Verificant la còpia…", + "Switching storage…": "Canviant l'emmagatzematge…", + "Restarting engine…": "Reiniciant el motor…", + "Moving data…": "Movent les dades…", + "Storage location unavailable": "Ubicació d'emmagatzematge no disponible", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "El Kiri no ha trobat les seves dades a {path}. Connecta el disc i torna-ho a provar, tria una altra carpeta o restableix la ubicació per defecte.", + "Change…": "Canvia…", + "Reset to default": "Restableix per defecte", + "Open storage settings": "Obre la configuració d'emmagatzematge", + "Start Kiri to change its storage location. ({error})": "Inicia el Kiri per canviar la ubicació d'emmagatzematge. ({error})", + "{size} used": "{size} usats", + "{size} free": "{size} lliures", + "Default": "Per defecte", + "Moving Kiri's data to {path}.": "Movent les dades del Kiri a {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Els contenidors en execució s'aturen mentre el Kiri copia les dades i tornen a arrencar en acabar.", + "Couldn't change storage location": "No s'ha pogut canviar la ubicació d'emmagatzematge", + "Old data": "Dades antigues", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Les dades anteriors encara són a {path}. Elimina-les quan tot funcioni a la ubicació nova.", + "Remove old data": "Elimina les dades antigues", + "Storage location": "Ubicació d'emmagatzematge", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} defineix la ubicació d'emmagatzematge del Kiri, així que no es pot canviar aquí.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Les imatges, els contenidors i els volums es guarden en aquesta carpeta. Els discos externs han d'usar un sistema de fitxers natiu (APFS a macOS, ext4/xfs/btrfs a Linux, NTFS a Windows); FAT i exFAT no són compatibles.", + "Reset storage location to default?": "Restablir la ubicació d'emmagatzematge per defecte?", + "Change storage location?": "Canviar la ubicació d'emmagatzematge?", + "Destination: {path} ({free} free).": "Destinació: {path} ({free} lliures).", + "Destination: {path}.": "Destinació: {path}.", + "Existing Kiri data in this folder will be replaced.": "Les dades del Kiri que ja hi ha en aquesta carpeta se substituiran.", + "Migration mode": "Mode de migració", + "Move existing images, containers, and volumes": "Mou les imatges, els contenidors i els volums existents", + "Stops running containers, copies your data, and starts them again.": "Atura els contenidors en execució, copia les dades i els torna a iniciar.", + "Start fresh": "Comença de zero", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Comença buit a la carpeta nova. La carpeta antiga es conserva fins que l'eliminis.", + "Kiri will switch to this folder and restart the engine.": "El Kiri canviarà a aquesta carpeta i reiniciarà el motor.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Els contenidors en execució s'aturaran mentre el Kiri mou les dades i tornaran a iniciar-se en acabar.", + "Move data": "Mou les dades", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "El Kiri tornarà a la carpeta per defecte i reiniciarà el motor. Les dades del disc desconnectat no s'eliminen.", + "Remove old data?": "Eliminar les dades antigues?", + "Everything in {path} will be deleted for good.": "Tot el contingut de {path} s'eliminarà definitivament.", + "Choose a storage folder": "Tria una carpeta d'emmagatzematge", + "Kiri's data is moving already": "Les dades del Kiri ja s'estan movent", + "Kiri's data moved to {path}": "Les dades del Kiri s'han mogut a {path}", + "Storage is available again": "L'emmagatzematge torna a estar disponible", + "Old data removed": "Dades antigues eliminades" } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index f0d3b9418..82e6526e6 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1887,5 +1887,50 @@ "Switching…": "دەگۆڕدرێت…", "{docker} command": "فەرمانی {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ئێستا ئاراستەی Kiri دەکات", - "Could not link /var/run/docker.sock: {error}": "نەتوانرا /var/run/docker.sock ببەسترێتەوە: {error}" + "Could not link /var/run/docker.sock: {error}": "نەتوانرا /var/run/docker.sock ببەسترێتەوە: {error}", + "Stopping containers…": "وەستاندنی کۆنتێنەرەکان…", + "Copying data…": "کۆپیکردنی داتاکان…", + "Verifying copy…": "دڵنیابوونەوە لە کۆپییەکە…", + "Switching storage…": "گۆڕینی بیرگە…", + "Restarting engine…": "داگیرساندنەوەی مۆتۆڕ…", + "Moving data…": "گواستنەوەی داتاکان…", + "Storage location unavailable": "شوێنی هەڵگرتن بەردەست نییە", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri داتاکانی لە {path} نەدۆزییەوە. درایڤەکە ببەستەوە و هەوڵ بدەوە، بوخچەیەکی تر هەڵبژێرە، یان بیگەڕێنەوە سەر شوێنی بنەڕەتی.", + "Change…": "گۆڕین…", + "Reset to default": "گەڕاندنەوە بۆ بنەڕەتی", + "Open storage settings": "کردنەوەی ڕێکخستنەکانی بیرگە", + "Start Kiri to change its storage location. ({error})": "بۆ گۆڕینی شوێنی هەڵگرتن Kiri دابگیرسێنە. ({error})", + "{size} used": "{size} بەکارهاتوو", + "{size} free": "{size} بەتاڵ", + "Default": "بنەڕەتی", + "Moving Kiri's data to {path}.": "گواستنەوەی داتاکانی Kiri بۆ {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "کۆنتێنەرە کاراکان دەوەستن تا Kiri داتاکانی کۆپی دەکات و پاش تەواوبوون دەستپێدەکەنەوە.", + "Couldn't change storage location": "نەتوانرا شوێنی هەڵگرتن بگۆڕدرێت", + "Old data": "داتای کۆن", + "Previous data is still in {path}. Remove it once everything works in the new location.": "داتای پێشوو هێشتا لە {path} ماوە. کاتێک هەموو شتێک لە شوێنی نوێ کار دەکات لایببە.", + "Remove old data": "سڕینەوەی داتای کۆن", + "Storage location": "شوێنی هەڵگرتن", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} شوێنی هەڵگرتنی Kiri دیاری دەکات، بۆیە لێرە ناگۆڕدرێت.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "وێنەکان، کۆنتێنەرەکان و ڤۆلیۆمەکان لەم بوخچەیەدا دەبن. درایڤە دەرەکییەکان دەبێت سیستەمی فایلی خۆماڵییان هەبێت (APFS لە macOS، ext4/xfs/btrfs لە Linux، NTFS لە Windows)؛ درایڤەکانی FAT و exFAT پشتگیری ناکرێن.", + "Reset storage location to default?": "شوێنی هەڵگرتن بگەڕێنرێتەوە بۆ بنەڕەتی؟", + "Change storage location?": "شوێنی هەڵگرتن بگۆڕدرێت؟", + "Destination: {path} ({free} free).": "مەبەست: {path} ({free} بەتاڵ).", + "Destination: {path}.": "مەبەست: {path}.", + "Existing Kiri data in this folder will be replaced.": "داتای Kiri کە پێشتر لەم بوخچەیەدایە جێگۆڕکێی پێ دەکرێت.", + "Migration mode": "شێوازی گواستنەوە", + "Move existing images, containers, and volumes": "گواستنەوەی وێنە و کۆنتێنەر و ڤۆلیۆمەکان", + "Stops running containers, copies your data, and starts them again.": "کۆنتێنەرە کاراکان دەوەستێنێت، داتاکانت کۆپی دەکات و دایاندەگیرسێنێتەوە.", + "Start fresh": "دەستپێکردن بە خاوێنی", + "Starts empty in the new folder. Your old folder stays until you remove it.": "بە بەتاڵی لە بوخچە نوێیەکەدا دەست پێ دەکات. بوخچە کۆنەکەت دەمێنێتەوە تا خۆت دەیسرێتەوە.", + "Kiri will switch to this folder and restart the engine.": "Kiri دەگوازێتەوە بۆ ئەم بوخچەیە و مۆتۆڕ دادەگیرسێنێتەوە.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "کۆنتێنەرە کاراکان دەوەستن تا Kiri داتاکانت دەگوازێتەوە و پاش تەواوبوون دەستپێدەکەنەوە.", + "Move data": "گواستنەوەی داتا", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri دەگەڕێتەوە بۆ بوخچەی بنەڕەتی و مۆتۆڕ دادەگیرسێنێتەوە. داتای سەر درایڤە پچڕاوەکە ناسڕدرێتەوە.", + "Remove old data?": "داتای کۆن بسڕدرێتەوە؟", + "Everything in {path} will be deleted for good.": "هەموو شتێک لە {path} بۆ هەمیشە دەسڕدرێتەوە.", + "Choose a storage folder": "بوخچەی هەڵگرتن هەڵبژێرە", + "Kiri's data is moving already": "داتاکانی Kiri ئێستا دەگوازرێنەوە", + "Kiri's data moved to {path}": "داتاکانی Kiri گواسترانەوە بۆ {path}", + "Storage is available again": "بیرگە دووبارە بەردەستە", + "Old data removed": "داتای کۆن سڕدرایەوە" } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index d6cc906c8..cf9486703 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1887,5 +1887,50 @@ "Switching…": "Přepíná se…", "{docker} command": "Příkaz {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock nyní směřuje na Kiri", - "Could not link /var/run/docker.sock: {error}": "Nepodařilo se propojit /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Nepodařilo se propojit /var/run/docker.sock: {error}", + "Stopping containers…": "Zastavování kontejnerů…", + "Copying data…": "Kopírování dat…", + "Verifying copy…": "Ověřování kopie…", + "Switching storage…": "Přepínání úložiště…", + "Restarting engine…": "Restartování enginu…", + "Moving data…": "Přesouvání dat…", + "Storage location unavailable": "Umístění úložiště není dostupné", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri nemohlo najít svá data v {path}. Připojte disk a zkuste to znovu, vyberte jinou složku nebo obnovte výchozí umístění.", + "Change…": "Změnit…", + "Reset to default": "Obnovit výchozí", + "Open storage settings": "Otevřít nastavení úložiště", + "Start Kiri to change its storage location. ({error})": "Pro změnu umístění úložiště spusťte Kiri. ({error})", + "{size} used": "{size} využito", + "{size} free": "{size} volných", + "Default": "Výchozí", + "Moving Kiri's data to {path}.": "Přesouvání dat Kiri do {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Běžící kontejnery se během kopírování dat pozastaví a po dokončení se znovu spustí.", + "Couldn't change storage location": "Umístění úložiště se nepodařilo změnit", + "Old data": "Stará data", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Předchozí data jsou stále v {path}. Odstraňte je, až vše v novém umístění poběží.", + "Remove old data": "Odstranit stará data", + "Storage location": "Umístění úložiště", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} nastavuje umístění úložiště Kiri, takže ho zde nelze změnit.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "V této složce jsou uloženy obrazy, kontejnery a svazky. Externí disky musí používat nativní souborový systém (APFS na macOS, ext4/xfs/btrfs na Linuxu, NTFS ve Windows); disky FAT a exFAT nejsou podporovány.", + "Reset storage location to default?": "Obnovit výchozí umístění úložiště?", + "Change storage location?": "Změnit umístění úložiště?", + "Destination: {path} ({free} free).": "Cíl: {path} ({free} volných).", + "Destination: {path}.": "Cíl: {path}.", + "Existing Kiri data in this folder will be replaced.": "Existující data Kiri v této složce budou nahrazena.", + "Migration mode": "Režim přesunu", + "Move existing images, containers, and volumes": "Přesunout stávající obrazy, kontejnery a svazky", + "Stops running containers, copies your data, and starts them again.": "Zastaví běžící kontejnery, zkopíruje vaše data a znovu je spustí.", + "Start fresh": "Začít načisto", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Začne prázdně v nové složce. Stará složka zůstane, dokud ji neodstraníte.", + "Kiri will switch to this folder and restart the engine.": "Kiri přepne na tuto složku a restartuje engine.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Běžící kontejnery se během přesunu zastaví a po dokončení se znovu spustí.", + "Move data": "Přesunout data", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri přepne zpět na výchozí složku a restartuje engine. Data na odpojeném disku se nesmažou.", + "Remove old data?": "Odstranit stará data?", + "Everything in {path} will be deleted for good.": "Vše v {path} bude trvale smazáno.", + "Choose a storage folder": "Vyberte složku úložiště", + "Kiri's data is moving already": "Data Kiri se již přesouvají", + "Kiri's data moved to {path}": "Data Kiri byla přesunuta do {path}", + "Storage is available again": "Úložiště je opět dostupné", + "Old data removed": "Stará data odstraněna" } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index 07751130e..f5520040d 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1887,5 +1887,50 @@ "Switching…": "Wechsle…", "{docker} command": "Befehl {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock verweist jetzt auf Kiri", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock konnte nicht verknüpft werden: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock konnte nicht verknüpft werden: {error}", + "Stopping containers…": "Container werden gestoppt…", + "Copying data…": "Daten werden kopiert…", + "Verifying copy…": "Kopie wird überprüft…", + "Switching storage…": "Speicher wird umgestellt…", + "Restarting engine…": "Engine wird neu gestartet…", + "Moving data…": "Daten werden verschoben…", + "Storage location unavailable": "Speicherort nicht verfügbar", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri konnte seine Daten in {path} nicht finden. Schließe das Laufwerk an und versuche es erneut, wähle einen anderen Ordner oder setze auf den Standardort zurück.", + "Change…": "Ändern…", + "Reset to default": "Auf Standard zurücksetzen", + "Open storage settings": "Speichereinstellungen öffnen", + "Start Kiri to change its storage location. ({error})": "Starte Kiri, um den Speicherort zu ändern. ({error})", + "{size} used": "{size} belegt", + "{size} free": "{size} frei", + "Default": "Standard", + "Moving Kiri's data to {path}.": "Kiris Daten werden nach {path} verschoben.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Laufende Container pausieren, während Kiri seine Daten kopiert, und starten danach wieder.", + "Couldn't change storage location": "Speicherort konnte nicht geändert werden", + "Old data": "Alte Daten", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Vorherige Daten liegen noch in {path}. Entferne sie, sobald am neuen Ort alles läuft.", + "Remove old data": "Alte Daten entfernen", + "Storage location": "Speicherort", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} legt Kiris Speicherort fest und kann hier nicht geändert werden.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Images, Container und Volumes liegen in diesem Ordner. Externe Laufwerke müssen ein natives Dateisystem nutzen (APFS unter macOS, ext4/xfs/btrfs unter Linux, NTFS unter Windows); FAT und exFAT werden nicht unterstützt.", + "Reset storage location to default?": "Speicherort auf Standard zurücksetzen?", + "Change storage location?": "Speicherort ändern?", + "Destination: {path} ({free} free).": "Ziel: {path} ({free} frei).", + "Destination: {path}.": "Ziel: {path}.", + "Existing Kiri data in this folder will be replaced.": "Vorhandene Kiri-Daten in diesem Ordner werden ersetzt.", + "Migration mode": "Migrationsmodus", + "Move existing images, containers, and volumes": "Vorhandene Images, Container und Volumes verschieben", + "Stops running containers, copies your data, and starts them again.": "Stoppt laufende Container, kopiert deine Daten und startet sie wieder.", + "Start fresh": "Neu beginnen", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Startet leer im neuen Ordner. Dein alter Ordner bleibt, bis du ihn entfernst.", + "Kiri will switch to this folder and restart the engine.": "Kiri wechselt zu diesem Ordner und startet die Engine neu.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Laufende Container werden angehalten, während Kiri deine Daten verschiebt, und starten danach wieder.", + "Move data": "Daten verschieben", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri wechselt zurück zum Standardordner und startet die Engine neu. Daten auf dem getrennten Laufwerk werden nicht gelöscht.", + "Remove old data?": "Alte Daten entfernen?", + "Everything in {path} will be deleted for good.": "Alles in {path} wird endgültig gelöscht.", + "Choose a storage folder": "Speicherordner wählen", + "Kiri's data is moving already": "Kiris Daten werden bereits verschoben", + "Kiri's data moved to {path}": "Kiris Daten wurden nach {path} verschoben", + "Storage is available again": "Speicher ist wieder verfügbar", + "Old data removed": "Alte Daten entfernt" } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 0f7c155a9..e747848db 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1887,5 +1887,50 @@ "Switching…": "Αλλαγή…", "{docker} command": "Εντολή {docker}", "/var/run/docker.sock now points to Kiri": "Το /var/run/docker.sock δείχνει πλέον στο Kiri", - "Could not link /var/run/docker.sock: {error}": "Αδυναμία σύνδεσης του /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Αδυναμία σύνδεσης του /var/run/docker.sock: {error}", + "Stopping containers…": "Διακοπή κοντέινερ…", + "Copying data…": "Αντιγραφή δεδομένων…", + "Verifying copy…": "Επαλήθευση αντιγράφου…", + "Switching storage…": "Αλλαγή αποθήκευσης…", + "Restarting engine…": "Επανεκκίνηση μηχανής…", + "Moving data…": "Μετακίνηση δεδομένων…", + "Storage location unavailable": "Η τοποθεσία αποθήκευσης δεν είναι διαθέσιμη", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Το Kiri δεν βρήκε τα δεδομένα του στο {path}. Συνδέστε τον δίσκο και δοκιμάστε ξανά, επιλέξτε άλλον φάκελο ή επαναφέρετε την προεπιλεγμένη τοποθεσία.", + "Change…": "Αλλαγή…", + "Reset to default": "Επαναφορά προεπιλογής", + "Open storage settings": "Άνοιγμα ρυθμίσεων αποθήκευσης", + "Start Kiri to change its storage location. ({error})": "Ξεκινήστε το Kiri για να αλλάξετε την τοποθεσία αποθήκευσης. ({error})", + "{size} used": "{size} σε χρήση", + "{size} free": "{size} ελεύθερα", + "Default": "Προεπιλογή", + "Moving Kiri's data to {path}.": "Μετακίνηση δεδομένων του Kiri στο {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Τα ενεργά κοντέινερ διακόπτονται προσωρινά όσο το Kiri αντιγράφει τα δεδομένα του και ξεκινούν ξανά μόλις ολοκληρωθεί.", + "Couldn't change storage location": "Δεν ήταν δυνατή η αλλαγή τοποθεσίας αποθήκευσης", + "Old data": "Παλιά δεδομένα", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Τα προηγούμενα δεδομένα βρίσκονται ακόμα στο {path}. Αφαιρέστε τα μόλις όλα λειτουργούν στη νέα τοποθεσία.", + "Remove old data": "Αφαίρεση παλιών δεδομένων", + "Storage location": "Τοποθεσία αποθήκευσης", + "{var} sets Kiri's storage location, so it can't be changed here.": "Η μεταβλητή {var} ορίζει την τοποθεσία αποθήκευσης του Kiri και δεν μπορεί να αλλάξει από εδώ.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Οι εικόνες, τα κοντέινερ και οι τόμοι αποθηκεύονται σε αυτόν τον φάκελο. Οι εξωτερικοί δίσκοι πρέπει να έχουν εγγενές σύστημα αρχείων (APFS σε macOS, ext4/xfs/btrfs σε Linux, NTFS σε Windows)· οι δίσκοι FAT και exFAT δεν υποστηρίζονται.", + "Reset storage location to default?": "Επαναφορά της τοποθεσίας αποθήκευσης στην προεπιλογή;", + "Change storage location?": "Αλλαγή τοποθεσίας αποθήκευσης;", + "Destination: {path} ({free} free).": "Προορισμός: {path} ({free} ελεύθερα).", + "Destination: {path}.": "Προορισμός: {path}.", + "Existing Kiri data in this folder will be replaced.": "Τα υπάρχοντα δεδομένα του Kiri σε αυτόν τον φάκελο θα αντικατασταθούν.", + "Migration mode": "Τρόπος μεταφοράς", + "Move existing images, containers, and volumes": "Μετακίνηση υπαρχουσών εικόνων, κοντέινερ και τόμων", + "Stops running containers, copies your data, and starts them again.": "Σταματά τα ενεργά κοντέινερ, αντιγράφει τα δεδομένα σας και τα ξεκινά ξανά.", + "Start fresh": "Νέα αρχή", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Ξεκινά κενό στον νέο φάκελο. Ο παλιός φάκελος παραμένει μέχρι να τον αφαιρέσετε.", + "Kiri will switch to this folder and restart the engine.": "Το Kiri θα μεταβεί σε αυτόν τον φάκελο και θα επανεκκινήσει τη μηχανή.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Τα ενεργά κοντέινερ θα σταματήσουν όσο το Kiri μετακινεί τα δεδομένα σας και θα ξεκινήσουν ξανά μόλις τελειώσει.", + "Move data": "Μετακίνηση δεδομένων", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Το Kiri θα επιστρέψει στον προεπιλεγμένο φάκελο και θα επανεκκινήσει τη μηχανή. Τα δεδομένα στον αποσυνδεδεμένο δίσκο δεν διαγράφονται.", + "Remove old data?": "Αφαίρεση παλιών δεδομένων;", + "Everything in {path} will be deleted for good.": "Όλα τα αρχεία στο {path} θα διαγραφούν οριστικά.", + "Choose a storage folder": "Επιλέξτε φάκελο αποθήκευσης", + "Kiri's data is moving already": "Τα δεδομένα του Kiri μετακινούνται ήδη", + "Kiri's data moved to {path}": "Τα δεδομένα του Kiri μετακινήθηκαν στο {path}", + "Storage is available again": "Η αποθήκευση είναι ξανά διαθέσιμη", + "Old data removed": "Τα παλιά δεδομένα αφαιρέθηκαν" } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index 0317582c2..f1c872450 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1887,5 +1887,50 @@ "Switching…": "Cambiando…", "{docker} command": "Comando {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ahora apunta a Kiri", - "Could not link /var/run/docker.sock: {error}": "No se pudo enlazar /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "No se pudo enlazar /var/run/docker.sock: {error}", + "Stopping containers…": "Deteniendo contenedores…", + "Copying data…": "Copiando datos…", + "Verifying copy…": "Verificando copia…", + "Switching storage…": "Cambiando almacenamiento…", + "Restarting engine…": "Reiniciando motor…", + "Moving data…": "Moviendo datos…", + "Storage location unavailable": "Ubicación de almacenamiento no disponible", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri no pudo encontrar sus datos en {path}. Conecta el disco y reintenta, elige otra carpeta o restablece la ubicación predeterminada.", + "Change…": "Cambiar…", + "Reset to default": "Restablecer predeterminada", + "Open storage settings": "Abrir ajustes de almacenamiento", + "Start Kiri to change its storage location. ({error})": "Inicia Kiri para cambiar su ubicación de almacenamiento. ({error})", + "{size} used": "{size} usados", + "{size} free": "{size} libres", + "Default": "Predeterminada", + "Moving Kiri's data to {path}.": "Moviendo los datos de Kiri a {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Los contenedores en ejecución se pausan mientras Kiri copia los datos y vuelven a iniciarse al terminar.", + "Couldn't change storage location": "No se pudo cambiar la ubicación de almacenamiento", + "Old data": "Datos anteriores", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Los datos anteriores siguen en {path}. Elimínalos cuando todo funcione en la nueva ubicación.", + "Remove old data": "Eliminar datos anteriores", + "Storage location": "Ubicación de almacenamiento", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} define la ubicación de almacenamiento de Kiri, así que no se puede cambiar aquí.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Las imágenes, los contenedores y los volúmenes se guardan en esta carpeta. Las unidades externas deben usar un sistema de archivos nativo (APFS en macOS, ext4/xfs/btrfs en Linux, NTFS en Windows); FAT y exFAT no son compatibles.", + "Reset storage location to default?": "¿Restablecer la ubicación de almacenamiento predeterminada?", + "Change storage location?": "¿Cambiar la ubicación de almacenamiento?", + "Destination: {path} ({free} free).": "Destino: {path} ({free} libres).", + "Destination: {path}.": "Destino: {path}.", + "Existing Kiri data in this folder will be replaced.": "Se reemplazarán los datos existentes de Kiri en esta carpeta.", + "Migration mode": "Modo de migración", + "Move existing images, containers, and volumes": "Mover imágenes, contenedores y volúmenes existentes", + "Stops running containers, copies your data, and starts them again.": "Detiene los contenedores en ejecución, copia tus datos y vuelve a iniciarlos.", + "Start fresh": "Empezar desde cero", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Empieza vacío en la nueva carpeta. Tu carpeta anterior se conserva hasta que la elimines.", + "Kiri will switch to this folder and restart the engine.": "Kiri cambiará a esta carpeta y reiniciará el motor.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Los contenedores en ejecución se detendrán mientras Kiri mueve tus datos y volverán a iniciarse al terminar.", + "Move data": "Mover datos", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri volverá a su carpeta predeterminada y reiniciará el motor. Los datos del disco desconectado no se borran.", + "Remove old data?": "¿Eliminar los datos anteriores?", + "Everything in {path} will be deleted for good.": "Todo lo que hay en {path} se eliminará de forma permanente.", + "Choose a storage folder": "Elige una carpeta de almacenamiento", + "Kiri's data is moving already": "Los datos de Kiri ya se están moviendo", + "Kiri's data moved to {path}": "Los datos de Kiri se movieron a {path}", + "Storage is available again": "El almacenamiento está disponible de nuevo", + "Old data removed": "Datos anteriores eliminados" } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index 6e4b66334..a1a6a5e69 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1887,5 +1887,50 @@ "Switching…": "در حال تغییر…", "{docker} command": "فرمان {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock اکنون به Kiri اشاره می‌کند", - "Could not link /var/run/docker.sock: {error}": "پیوند دادن /var/run/docker.sock ممکن نشد: {error}" + "Could not link /var/run/docker.sock: {error}": "پیوند دادن /var/run/docker.sock ممکن نشد: {error}", + "Stopping containers…": "در حال متوقف کردن کانتینرها…", + "Copying data…": "در حال کپی کردن داده‌ها…", + "Verifying copy…": "در حال بررسی نسخه کپی…", + "Switching storage…": "در حال تغییر محل ذخیره‌سازی…", + "Restarting engine…": "در حال راه‌اندازی مجدد موتور…", + "Moving data…": "در حال جابه‌جایی داده‌ها…", + "Storage location unavailable": "محل ذخیره‌سازی در دسترس نیست", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri داده‌های خود را در {path} پیدا نکرد. درایو را وصل کرده و دوباره تلاش کنید، پوشه دیگری انتخاب کنید یا به محل پیش‌فرض بازنشانی کنید.", + "Change…": "تغییر…", + "Reset to default": "بازنشانی به پیش‌فرض", + "Open storage settings": "باز کردن تنظیمات ذخیره‌سازی", + "Start Kiri to change its storage location. ({error})": "برای تغییر محل ذخیره‌سازی، Kiri را اجرا کنید. ({error})", + "{size} used": "{size} استفاده‌شده", + "{size} free": "{size} آزاد", + "Default": "پیش‌فرض", + "Moving Kiri's data to {path}.": "در حال جابه‌جایی داده‌های Kiri به {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "کانتینرهای در حال اجرا هنگام کپی داده‌های Kiri متوقف می‌شوند و پس از پایان دوباره اجرا خواهند شد.", + "Couldn't change storage location": "تغییر محل ذخیره‌سازی ناموفق بود", + "Old data": "داده‌های قدیمی", + "Previous data is still in {path}. Remove it once everything works in the new location.": "داده‌های قبلی هنوز در {path} قرار دارند. پس از اطمینان از کارکرد همه چیز در محل جدید، آن‌ها را حذف کنید.", + "Remove old data": "حذف داده‌های قدیمی", + "Storage location": "محل ذخیره‌سازی", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} محل ذخیره‌سازی Kiri را تعیین می‌کند، بنابراین اینجا قابل تغییر نیست.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "ایمیج‌ها، کانتینرها و والیوم‌ها در این پوشه نگهداری می‌شوند. درایوهای خارجی باید سیستم فایل بومی داشته باشند (APFS در macOS، ext4/xfs/btrfs در Linux، NTFS در Windows)؛ درایوهای FAT و exFAT پشتیبانی نمی‌شوند.", + "Reset storage location to default?": "محل ذخیره‌سازی به پیش‌فرض بازنشانی شود؟", + "Change storage location?": "محل ذخیره‌سازی تغییر کند؟", + "Destination: {path} ({free} free).": "مقصد: {path} ({free} آزاد).", + "Destination: {path}.": "مقصد: {path}.", + "Existing Kiri data in this folder will be replaced.": "داده‌های موجود Kiri در این پوشه جایگزین خواهند شد.", + "Migration mode": "حالت انتقال", + "Move existing images, containers, and volumes": "انتقال ایمیج‌ها، کانتینرها و والیوم‌های موجود", + "Stops running containers, copies your data, and starts them again.": "کانتینرهای در حال اجرا را متوقف می‌کند، داده‌ها را کپی می‌کند و دوباره آن‌ها را اجرا می‌کند.", + "Start fresh": "شروع تازه", + "Starts empty in the new folder. Your old folder stays until you remove it.": "در پوشه جدید به‌صورت خالی شروع می‌کند. پوشه قدیمی تا زمانی که خودتان حذفش کنید باقی می‌ماند.", + "Kiri will switch to this folder and restart the engine.": "Kiri به این پوشه منتقل شده و موتور را دوباره راه‌اندازی می‌کند.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "کانتینرهای در حال اجرا هنگام جابه‌جایی داده‌ها متوقف می‌شوند و پس از پایان دوباره اجرا خواهند شد.", + "Move data": "انتقال داده‌ها", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri به پوشه پیش‌فرض برمی‌گردد و موتور را دوباره راه‌اندازی می‌کند. داده‌های روی درایو قطع‌شده حذف نمی‌شوند.", + "Remove old data?": "داده‌های قدیمی حذف شوند؟", + "Everything in {path} will be deleted for good.": "همه چیز در {path} برای همیشه حذف خواهد شد.", + "Choose a storage folder": "یک پوشه ذخیره‌سازی انتخاب کنید", + "Kiri's data is moving already": "داده‌های Kiri همین الان در حال جابه‌جایی است", + "Kiri's data moved to {path}": "داده‌های Kiri به {path} منتقل شد", + "Storage is available again": "فضای ذخیره‌سازی دوباره در دسترس است", + "Old data removed": "داده‌های قدیمی حذف شد" } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index 4a58b9586..7c271c309 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1887,5 +1887,50 @@ "Switching…": "Vaihdetaan…", "{docker} command": "Komento {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock osoittaa nyt Kiriin", - "Could not link /var/run/docker.sock: {error}": "Polun /var/run/docker.sock linkittäminen epäonnistui: {error}" + "Could not link /var/run/docker.sock: {error}": "Polun /var/run/docker.sock linkittäminen epäonnistui: {error}", + "Stopping containers…": "Pysäytetään kontteja…", + "Copying data…": "Kopioidaan tietoja…", + "Verifying copy…": "Tarkistetaan kopiota…", + "Switching storage…": "Vaihdetaan tallennussijaintia…", + "Restarting engine…": "Käynnistetään moottoria uudelleen…", + "Moving data…": "Siirretään tietoja…", + "Storage location unavailable": "Tallennussijainti ei ole käytettävissä", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ei löytänyt tietojaan sijainnista {path}. Liitä levy ja yritä uudelleen, valitse toinen kansio tai palauta oletussijainti.", + "Change…": "Vaihda…", + "Reset to default": "Palauta oletus", + "Open storage settings": "Avaa tallennusasetukset", + "Start Kiri to change its storage location. ({error})": "Käynnistä Kiri vaihtaaksesi tallennussijaintia. ({error})", + "{size} used": "{size} käytetty", + "{size} free": "{size} vapaana", + "Default": "Oletus", + "Moving Kiri's data to {path}.": "Siirretään Kirin tietoja sijaintiin {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Käynnissä olevat kontit pysäytetään tietojen kopioinnin ajaksi ja käynnistetään uudelleen sen jälkeen.", + "Couldn't change storage location": "Tallennussijaintia ei voitu vaihtaa", + "Old data": "Vanhat tiedot", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Aiemmat tiedot ovat yhä sijainnissa {path}. Poista ne, kun kaikki toimii uudessa sijainnissa.", + "Remove old data": "Poista vanhat tiedot", + "Storage location": "Tallennussijainti", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} määrittää Kirin tallennussijainnin, joten sitä ei voi muuttaa täällä.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Levykuvat, kontit ja taltiot tallennetaan tähän kansioon. Ulkoisilla levyillä on oltava natiivi tiedostojärjestelmä (APFS macOS:ssa, ext4/xfs/btrfs Linuxissa, NTFS Windowsissa); FAT- ja exFAT-levyjä ei tueta.", + "Reset storage location to default?": "Palautetaanko oletustallennussijainti?", + "Change storage location?": "Vaihdetaanko tallennussijaintia?", + "Destination: {path} ({free} free).": "Kohde: {path} ({free} vapaana).", + "Destination: {path}.": "Kohde: {path}.", + "Existing Kiri data in this folder will be replaced.": "Tässä kansiossa olevat Kirin tiedot korvataan.", + "Migration mode": "Siirtotila", + "Move existing images, containers, and volumes": "Siirrä nykyiset levykuvat, kontit ja taltiot", + "Stops running containers, copies your data, and starts them again.": "Pysäyttää käynnissä olevat kontit, kopioi tiedot ja käynnistää ne uudelleen.", + "Start fresh": "Aloita puhtaalta pöydältä", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Aloittaa tyhjänä uudessa kansiossa. Vanha kansio säilyy, kunnes poistat sen.", + "Kiri will switch to this folder and restart the engine.": "Kiri vaihtaa tähän kansioon ja käynnistää moottorin uudelleen.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Käynnissä olevat kontit pysäytetään siirron ajaksi ja käynnistetään uudelleen sen jälkeen.", + "Move data": "Siirrä tiedot", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri palaa oletuskansioon ja käynnistää moottorin uudelleen. Irrotetun levyn tietoja ei poisteta.", + "Remove old data?": "Poistetaanko vanhat tiedot?", + "Everything in {path} will be deleted for good.": "Kaikki sijainnissa {path} poistetaan pysyvästi.", + "Choose a storage folder": "Valitse tallennuskansio", + "Kiri's data is moving already": "Kirin tietoja siirretään jo", + "Kiri's data moved to {path}": "Kirin tiedot siirrettiin sijaintiin {path}", + "Storage is available again": "Tallennussijainti on taas käytettävissä", + "Old data removed": "Vanhat tiedot poistettu" } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 09162ab1c..50df0b459 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1887,5 +1887,50 @@ "Switching…": "Changement…", "{docker} command": "Commande {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock pointe maintenant vers Kiri", - "Could not link /var/run/docker.sock: {error}": "Impossible de lier /var/run/docker.sock : {error}" + "Could not link /var/run/docker.sock: {error}": "Impossible de lier /var/run/docker.sock : {error}", + "Stopping containers…": "Arrêt des conteneurs…", + "Copying data…": "Copie des données…", + "Verifying copy…": "Vérification de la copie…", + "Switching storage…": "Changement de stockage…", + "Restarting engine…": "Redémarrage du moteur…", + "Moving data…": "Déplacement des données…", + "Storage location unavailable": "Emplacement de stockage indisponible", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri n'a pas trouvé ses données dans {path}. Branchez le disque et réessayez, choisissez un autre dossier ou rétablissez l'emplacement par défaut.", + "Change…": "Modifier…", + "Reset to default": "Rétablir par défaut", + "Open storage settings": "Ouvrir les réglages de stockage", + "Start Kiri to change its storage location. ({error})": "Démarrez Kiri pour modifier son emplacement de stockage. ({error})", + "{size} used": "{size} utilisés", + "{size} free": "{size} disponibles", + "Default": "Par défaut", + "Moving Kiri's data to {path}.": "Déplacement des données de Kiri vers {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Les conteneurs en cours s'arrêtent pendant la copie et redémarrent une fois l'opération terminée.", + "Couldn't change storage location": "Impossible de modifier l'emplacement de stockage", + "Old data": "Anciennes données", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Les données précédentes sont toujours dans {path}. Supprimez-les une fois que tout fonctionne au nouvel emplacement.", + "Remove old data": "Supprimer les anciennes données", + "Storage location": "Emplacement de stockage", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} définit l'emplacement de stockage de Kiri ; il ne peut pas être modifié ici.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Les images, conteneurs et volumes sont stockés dans ce dossier. Les disques externes doivent utiliser un système de fichiers natif (APFS sur macOS, ext4/xfs/btrfs sur Linux, NTFS sur Windows) ; FAT et exFAT ne sont pas pris en charge.", + "Reset storage location to default?": "Rétablir l'emplacement de stockage par défaut ?", + "Change storage location?": "Modifier l'emplacement de stockage ?", + "Destination: {path} ({free} free).": "Destination : {path} ({free} disponibles).", + "Destination: {path}.": "Destination : {path}.", + "Existing Kiri data in this folder will be replaced.": "Les données Kiri déjà présentes dans ce dossier seront remplacées.", + "Migration mode": "Mode de migration", + "Move existing images, containers, and volumes": "Déplacer les images, conteneurs et volumes existants", + "Stops running containers, copies your data, and starts them again.": "Arrête les conteneurs en cours, copie vos données et les redémarre.", + "Start fresh": "Repartir à zéro", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Démarre à vide dans le nouveau dossier. L'ancien dossier reste en place jusqu'à ce que vous le supprimiez.", + "Kiri will switch to this folder and restart the engine.": "Kiri passera sur ce dossier et redémarrera le moteur.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Les conteneurs en cours s'arrêteront pendant le déplacement et redémarreront une fois terminé.", + "Move data": "Déplacer les données", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri reviendra au dossier par défaut et redémarrera le moteur. Les données du disque débranché ne sont pas supprimées.", + "Remove old data?": "Supprimer les anciennes données ?", + "Everything in {path} will be deleted for good.": "Tout le contenu de {path} sera supprimé définitivement.", + "Choose a storage folder": "Choisir un dossier de stockage", + "Kiri's data is moving already": "Les données de Kiri sont déjà en cours de déplacement", + "Kiri's data moved to {path}": "Les données de Kiri ont été déplacées vers {path}", + "Storage is available again": "Le stockage est de nouveau disponible", + "Old data removed": "Anciennes données supprimées" } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index cf7983d5e..a2ae586db 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1887,5 +1887,50 @@ "Switching…": "बदल रहा है…", "{docker} command": "{docker} कमांड", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock अब Kiri की ओर इंगित करता है", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock लिंक नहीं हो सका: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock लिंक नहीं हो सका: {error}", + "Stopping containers…": "कंटेनर रोके जा रहे हैं…", + "Copying data…": "डेटा कॉपी किया जा रहा है…", + "Verifying copy…": "कॉपी सत्यापित की जा रही है…", + "Switching storage…": "स्टोरेज बदला जा रहा है…", + "Restarting engine…": "इंजन पुनः प्रारंभ हो रहा है…", + "Moving data…": "डेटा स्थानांतरित हो रहा है…", + "Storage location unavailable": "स्टोरेज स्थान उपलब्ध नहीं है", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri को {path} में अपना डेटा नहीं मिला। ड्राइव कनेक्ट करके फिर से प्रयास करें, कोई दूसरा फ़ोल्डर चुनें, या डिफ़ॉल्ट स्थान पर रीसेट करें।", + "Change…": "बदलें…", + "Reset to default": "डिफ़ॉल्ट पर रीसेट करें", + "Open storage settings": "स्टोरेज सेटिंग्स खोलें", + "Start Kiri to change its storage location. ({error})": "स्टोरेज स्थान बदलने के लिए Kiri प्रारंभ करें। ({error})", + "{size} used": "{size} उपयोग में", + "{size} free": "{size} खाली", + "Default": "डिफ़ॉल्ट", + "Moving Kiri's data to {path}.": "Kiri का डेटा {path} में ले जाया जा रहा है।", + "Running containers pause while Kiri copies its data and start again once it's done.": "जब Kiri अपना डेटा कॉपी करेगा तब चल रहे कंटेनर रुक जाएंगे और काम पूरा होने पर फिर से शुरू हो जाएंगे।", + "Couldn't change storage location": "स्टोरेज स्थान बदला नहीं जा सका", + "Old data": "पुराना डेटा", + "Previous data is still in {path}. Remove it once everything works in the new location.": "पिछला डेटा अभी भी {path} में है। नए स्थान पर सब कुछ ठीक से काम करने के बाद इसे हटा दें।", + "Remove old data": "पुराना डेटा हटाएं", + "Storage location": "स्टोरेज स्थान", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri का स्टोरेज स्थान निर्धारित करता है, इसलिए इसे यहां नहीं बदला जा सकता।", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "इमेज, कंटेनर और वॉल्यूम इस फ़ोल्डर में रहते हैं। बाहरी ड्राइव में नेटिव फ़ाइलसिस्टम होना चाहिए (macOS पर APFS, Linux पर ext4/xfs/btrfs, Windows पर NTFS); FAT और exFAT ड्राइव समर्थित नहीं हैं।", + "Reset storage location to default?": "स्टोरेज स्थान को डिफ़ॉल्ट पर रीसेट करें?", + "Change storage location?": "स्टोरेज स्थान बदलें?", + "Destination: {path} ({free} free).": "गंतव्य: {path} ({free} खाली)।", + "Destination: {path}.": "गंतव्य: {path}।", + "Existing Kiri data in this folder will be replaced.": "इस फ़ोल्डर में मौजूद Kiri डेटा बदल दिया जाएगा।", + "Migration mode": "स्थानांतरण मोड", + "Move existing images, containers, and volumes": "मौजूदा इमेज, कंटेनर और वॉल्यूम ले जाएं", + "Stops running containers, copies your data, and starts them again.": "चल रहे कंटेनर रोकता है, आपका डेटा कॉपी करता है और उन्हें फिर से शुरू करता है।", + "Start fresh": "नए सिरे से शुरू करें", + "Starts empty in the new folder. Your old folder stays until you remove it.": "नए फ़ोल्डर में खाली शुरू होता है। आपका पुराना फ़ोल्डर तब तक रहता है जब तक आप उसे हटा न दें।", + "Kiri will switch to this folder and restart the engine.": "Kiri इस फ़ोल्डर पर स्विच करेगा और इंजन पुनः प्रारंभ करेगा।", + "Running containers will stop while Kiri moves your data and start again once it's done.": "जब Kiri आपका डेटा ले जाएगा तब चल रहे कंटेनर रुक जाएंगे और काम पूरा होने पर फिर से शुरू हो जाएंगे।", + "Move data": "डेटा ले जाएं", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri अपने डिफ़ॉल्ट फ़ोल्डर पर वापस स्विच करेगा और इंजन पुनः प्रारंभ करेगा। डिस्कनेक्ट की गई ड्राइव का डेटा नहीं हटाया जाता।", + "Remove old data?": "पुराना डेटा हटाएं?", + "Everything in {path} will be deleted for good.": "{path} में सब कुछ हमेशा के लिए हटा दिया जाएगा।", + "Choose a storage folder": "स्टोरेज फ़ोल्डर चुनें", + "Kiri's data is moving already": "Kiri का डेटा पहले से स्थानांतरित हो रहा है", + "Kiri's data moved to {path}": "Kiri का डेटा {path} में ले जाया गया", + "Storage is available again": "स्टोरेज फिर से उपलब्ध है", + "Old data removed": "पुराना डेटा हटा दिया गया" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 088650b5c..8a87c6c5b 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1887,5 +1887,50 @@ "Switching…": "Váltás…", "{docker} command": "{docker} parancs", "/var/run/docker.sock now points to Kiri": "A /var/run/docker.sock mostantól a Kirire mutat", - "Could not link /var/run/docker.sock: {error}": "Nem sikerült csatolni a /var/run/docker.sock útvonalat: {error}" + "Could not link /var/run/docker.sock: {error}": "Nem sikerült csatolni a /var/run/docker.sock útvonalat: {error}", + "Stopping containers…": "Konténerek leállítása…", + "Copying data…": "Adatok másolása…", + "Verifying copy…": "Másolat ellenőrzése…", + "Switching storage…": "Tárhely átváltása…", + "Restarting engine…": "Motor újraindítása…", + "Moving data…": "Adatok áthelyezése…", + "Storage location unavailable": "A tárhely nem érhető el", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "A Kiri nem találta az adatait itt: {path}. Csatlakoztasd a meghajtót és próbáld újra, válassz másik mappát, vagy állítsd vissza az alapértelmezett helyet.", + "Change…": "Módosítás…", + "Reset to default": "Alapértelmezett visszaállítása", + "Open storage settings": "Tárhelybeállítások megnyitása", + "Start Kiri to change its storage location. ({error})": "Indítsd el a Kirit a tárhely módosításához. ({error})", + "{size} used": "{size} foglalt", + "{size} free": "{size} szabad", + "Default": "Alapértelmezett", + "Moving Kiri's data to {path}.": "A Kiri adatainak áthelyezése ide: {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "A futó konténerek szünetelnek az adatok másolása alatt, majd a végén újraindulnak.", + "Couldn't change storage location": "Nem sikerült megváltoztatni a tárhelyet", + "Old data": "Régi adatok", + "Previous data is still in {path}. Remove it once everything works in the new location.": "A korábbi adatok még itt vannak: {path}. Távolítsd el őket, ha az új helyen minden működik.", + "Remove old data": "Régi adatok eltávolítása", + "Storage location": "Tárhely helye", + "{var} sets Kiri's storage location, so it can't be changed here.": "A(z) {var} állítja be a Kiri tárhelyét, így itt nem módosítható.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "A lemezképek, konténerek és kötetek ebben a mappában találhatók. A külső meghajtóknak natív fájlrendszert kell használniuk (APFS macOS-en, ext4/xfs/btrfs Linuxon, NTFS Windowson); a FAT és exFAT meghajtók nem támogatottak.", + "Reset storage location to default?": "Visszaállítod az alapértelmezett tárhelyet?", + "Change storage location?": "Megváltoztatod a tárhely helyét?", + "Destination: {path} ({free} free).": "Cél: {path} ({free} szabad).", + "Destination: {path}.": "Cél: {path}.", + "Existing Kiri data in this folder will be replaced.": "A mappában lévő meglévő Kiri-adatok lecserélődnek.", + "Migration mode": "Áthelyezési mód", + "Move existing images, containers, and volumes": "Meglévő lemezképek, konténerek és kötetek áthelyezése", + "Stops running containers, copies your data, and starts them again.": "Leállítja a futó konténereket, átmásolja az adataidat, majd újraindítja őket.", + "Start fresh": "Újrakezdés tiszta lappal", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Üresen indul az új mappában. A régi mappa megmarad, amíg el nem távolítod.", + "Kiri will switch to this folder and restart the engine.": "A Kiri erre a mappára vált, és újraindítja a motort.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "A futó konténerek leállnak az áthelyezés idejére, majd a végén újraindulnak.", + "Move data": "Adatok áthelyezése", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "A Kiri visszavált az alapértelmezett mappára, és újraindítja a motort. A leválasztott meghajtón lévő adatok nem törlődnek.", + "Remove old data?": "Eltávolítod a régi adatokat?", + "Everything in {path} will be deleted for good.": "Minden véglegesen törlődik innen: {path}.", + "Choose a storage folder": "Tárhelymappa választása", + "Kiri's data is moving already": "A Kiri adatai már áthelyezés alatt állnak", + "Kiri's data moved to {path}": "A Kiri adatai áthelyezve ide: {path}", + "Storage is available again": "A tárhely újra elérhető", + "Old data removed": "Régi adatok eltávolítva" } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index e13d345d0..c266b79c9 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1887,5 +1887,50 @@ "Switching…": "Mengalihkan…", "{docker} command": "Perintah {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock kini mengarah ke Kiri", - "Could not link /var/run/docker.sock: {error}": "Tidak dapat menautkan /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Tidak dapat menautkan /var/run/docker.sock: {error}", + "Stopping containers…": "Menghentikan kontainer…", + "Copying data…": "Menyalin data…", + "Verifying copy…": "Memverifikasi salinan…", + "Switching storage…": "Mengalihkan penyimpanan…", + "Restarting engine…": "Memulai ulang mesin…", + "Moving data…": "Memindahkan data…", + "Storage location unavailable": "Lokasi penyimpanan tidak tersedia", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri tidak menemukan datanya di {path}. Sambungkan drive lalu coba lagi, pilih folder lain, atau kembalikan ke lokasi bawaan.", + "Change…": "Ubah…", + "Reset to default": "Kembalikan ke bawaan", + "Open storage settings": "Buka pengaturan penyimpanan", + "Start Kiri to change its storage location. ({error})": "Jalankan Kiri untuk mengubah lokasi penyimpanan. ({error})", + "{size} used": "{size} terpakai", + "{size} free": "{size} tersedia", + "Default": "Bawaan", + "Moving Kiri's data to {path}.": "Memindahkan data Kiri ke {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kontainer yang berjalan berhenti sementara saat Kiri menyalin datanya dan akan berjalan kembali setelah selesai.", + "Couldn't change storage location": "Tidak dapat mengubah lokasi penyimpanan", + "Old data": "Data lama", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Data sebelumnya masih ada di {path}. Hapus setelah semuanya berjalan baik di lokasi baru.", + "Remove old data": "Hapus data lama", + "Storage location": "Lokasi penyimpanan", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} mengatur lokasi penyimpanan Kiri, jadi tidak dapat diubah di sini.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Image, kontainer, dan volume disimpan di folder ini. Drive eksternal harus menggunakan sistem berkas bawaan (APFS di macOS, ext4/xfs/btrfs di Linux, NTFS di Windows); drive FAT dan exFAT tidak didukung.", + "Reset storage location to default?": "Kembalikan lokasi penyimpanan ke bawaan?", + "Change storage location?": "Ubah lokasi penyimpanan?", + "Destination: {path} ({free} free).": "Tujuan: {path} ({free} tersedia).", + "Destination: {path}.": "Tujuan: {path}.", + "Existing Kiri data in this folder will be replaced.": "Data Kiri yang sudah ada di folder ini akan diganti.", + "Migration mode": "Mode migrasi", + "Move existing images, containers, and volumes": "Pindahkan image, kontainer, dan volume yang ada", + "Stops running containers, copies your data, and starts them again.": "Menghentikan kontainer yang berjalan, menyalin data Anda, lalu menjalankannya kembali.", + "Start fresh": "Mulai dari awal", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Mulai kosong di folder baru. Folder lama tetap ada sampai Anda menghapusnya.", + "Kiri will switch to this folder and restart the engine.": "Kiri akan beralih ke folder ini dan memulai ulang mesin.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kontainer yang berjalan akan berhenti saat Kiri memindahkan data Anda dan berjalan kembali setelah selesai.", + "Move data": "Pindahkan data", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri akan kembali ke folder bawaan dan memulai ulang mesin. Data di drive yang terputus tidak dihapus.", + "Remove old data?": "Hapus data lama?", + "Everything in {path} will be deleted for good.": "Semua yang ada di {path} akan dihapus secara permanen.", + "Choose a storage folder": "Pilih folder penyimpanan", + "Kiri's data is moving already": "Data Kiri sedang dipindahkan", + "Kiri's data moved to {path}": "Data Kiri dipindahkan ke {path}", + "Storage is available again": "Penyimpanan tersedia kembali", + "Old data removed": "Data lama dihapus" } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 857cbc78b..7df786f6d 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1887,5 +1887,50 @@ "Switching…": "Cambio…", "{docker} command": "Comando {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ora punta a Kiri", - "Could not link /var/run/docker.sock: {error}": "Impossibile collegare /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Impossibile collegare /var/run/docker.sock: {error}", + "Stopping containers…": "Arresto dei container…", + "Copying data…": "Copia dei dati…", + "Verifying copy…": "Verifica della copia…", + "Switching storage…": "Cambio archiviazione…", + "Restarting engine…": "Riavvio del motore…", + "Moving data…": "Spostamento dei dati…", + "Storage location unavailable": "Posizione di archiviazione non disponibile", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri non ha trovato i suoi dati in {path}. Collega il disco e riprova, scegli un'altra cartella o ripristina la posizione predefinita.", + "Change…": "Cambia…", + "Reset to default": "Ripristina predefinita", + "Open storage settings": "Apri impostazioni di archiviazione", + "Start Kiri to change its storage location. ({error})": "Avvia Kiri per cambiare la posizione di archiviazione. ({error})", + "{size} used": "{size} usati", + "{size} free": "{size} liberi", + "Default": "Predefinita", + "Moving Kiri's data to {path}.": "Spostamento dei dati di Kiri in {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "I container in esecuzione vengono fermati mentre Kiri copia i dati e ripartono al termine.", + "Couldn't change storage location": "Impossibile cambiare la posizione di archiviazione", + "Old data": "Vecchi dati", + "Previous data is still in {path}. Remove it once everything works in the new location.": "I dati precedenti si trovano ancora in {path}. Rimuovili quando tutto funziona nella nuova posizione.", + "Remove old data": "Rimuovi vecchi dati", + "Storage location": "Posizione di archiviazione", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} imposta la posizione di archiviazione di Kiri, quindi non può essere cambiata qui.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Immagini, container e volumi risiedono in questa cartella. Le unità esterne devono usare un filesystem nativo (APFS su macOS, ext4/xfs/btrfs su Linux, NTFS su Windows); FAT ed exFAT non sono supportati.", + "Reset storage location to default?": "Ripristinare la posizione di archiviazione predefinita?", + "Change storage location?": "Cambiare la posizione di archiviazione?", + "Destination: {path} ({free} free).": "Destinazione: {path} ({free} liberi).", + "Destination: {path}.": "Destinazione: {path}.", + "Existing Kiri data in this folder will be replaced.": "I dati di Kiri già presenti in questa cartella verranno sostituiti.", + "Migration mode": "Modalità di migrazione", + "Move existing images, containers, and volumes": "Sposta immagini, container e volumi esistenti", + "Stops running containers, copies your data, and starts them again.": "Arresta i container in esecuzione, copia i dati e li riavvia.", + "Start fresh": "Riparti da zero", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Inizia a vuoto nella nuova cartella. La vecchia cartella rimane finché non la rimuovi.", + "Kiri will switch to this folder and restart the engine.": "Kiri passerà a questa cartella e riavvierà il motore.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "I container in esecuzione verranno fermati mentre Kiri sposta i dati e ripartiranno al termine.", + "Move data": "Sposta dati", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri tornerà alla cartella predefinita e riavvierà il motore. I dati sul disco scollegato non vengono eliminati.", + "Remove old data?": "Rimuovere i vecchi dati?", + "Everything in {path} will be deleted for good.": "Tutto il contenuto di {path} verrà eliminato definitivamente.", + "Choose a storage folder": "Scegli una cartella di archiviazione", + "Kiri's data is moving already": "I dati di Kiri sono già in fase di spostamento", + "Kiri's data moved to {path}": "Dati di Kiri spostati in {path}", + "Storage is available again": "Archiviazione di nuovo disponibile", + "Old data removed": "Vecchi dati rimossi" } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index bef9f00cb..f519f6908 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1887,5 +1887,50 @@ "Switching…": "切り替え中…", "{docker} command": "{docker} コマンド", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock が Kiri を指すようになりました", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock をリンクできませんでした: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock をリンクできませんでした: {error}", + "Stopping containers…": "コンテナを停止中…", + "Copying data…": "データをコピー中…", + "Verifying copy…": "コピーを検証中…", + "Switching storage…": "ストレージを切り替え中…", + "Restarting engine…": "エンジンを再起動中…", + "Moving data…": "データを移動中…", + "Storage location unavailable": "ストレージの場所が利用できません", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri は {path} でデータを見つけられませんでした。ドライブを接続して再試行するか、別のフォルダーを選ぶか、デフォルトの場所に戻してください。", + "Change…": "変更…", + "Reset to default": "デフォルトに戻す", + "Open storage settings": "ストレージ設定を開く", + "Start Kiri to change its storage location. ({error})": "ストレージの場所を変更するには Kiri を起動してください。({error})", + "{size} used": "{size} 使用中", + "{size} free": "{size} 空き", + "Default": "デフォルト", + "Moving Kiri's data to {path}.": "Kiri のデータを {path} に移動しています。", + "Running containers pause while Kiri copies its data and start again once it's done.": "データのコピー中は実行中のコンテナが一時停止し、完了後に自動で再開します。", + "Couldn't change storage location": "ストレージの場所を変更できませんでした", + "Old data": "古いデータ", + "Previous data is still in {path}. Remove it once everything works in the new location.": "以前のデータが {path} に残っています。新しい場所で問題なく動作することを確認してから削除してください。", + "Remove old data": "古いデータを削除", + "Storage location": "ストレージの場所", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} で Kiri のストレージの場所が指定されているため、ここでは変更できません。", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "イメージ、コンテナ、ボリュームはこのフォルダーに保存されます。外付けドライブはネイティブのファイルシステム(macOS は APFS、Linux は ext4/xfs/btrfs、Windows は NTFS)を使用する必要があります。FAT および exFAT は非対応です。", + "Reset storage location to default?": "ストレージの場所をデフォルトに戻しますか?", + "Change storage location?": "ストレージの場所を変更しますか?", + "Destination: {path} ({free} free).": "移動先:{path}(空き {free})。", + "Destination: {path}.": "移動先:{path}。", + "Existing Kiri data in this folder will be replaced.": "このフォルダーにある既存の Kiri データは置き換えられます。", + "Migration mode": "移行モード", + "Move existing images, containers, and volumes": "既存のイメージ、コンテナ、ボリュームを移動する", + "Stops running containers, copies your data, and starts them again.": "実行中のコンテナを停止し、データをコピーして再開します。", + "Start fresh": "新規に開始する", + "Starts empty in the new folder. Your old folder stays until you remove it.": "新しいフォルダーで空の状態から開始します。古いフォルダーは削除するまで残ります。", + "Kiri will switch to this folder and restart the engine.": "Kiri はこのフォルダーに切り替え、エンジンを再起動します。", + "Running containers will stop while Kiri moves your data and start again once it's done.": "データの移動中は実行中のコンテナが停止し、完了後に自動で再開します。", + "Move data": "データを移動", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri はデフォルトのフォルダーに戻り、エンジンを再起動します。取り外されたドライブ上のデータは削除されません。", + "Remove old data?": "古いデータを削除しますか?", + "Everything in {path} will be deleted for good.": "{path} 内のすべてが完全に削除されます。", + "Choose a storage folder": "ストレージフォルダーを選択", + "Kiri's data is moving already": "Kiri のデータはすでに移動中です", + "Kiri's data moved to {path}": "Kiri のデータを {path} に移動しました", + "Storage is available again": "ストレージが再び利用可能になりました", + "Old data removed": "古いデータを削除しました" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 3416e8519..4521b7f80 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1887,5 +1887,50 @@ "Switching…": "Ауыстырылуда…", "{docker} command": "{docker} командасы", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock енді Kiri-ге бағытталған", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock байланыстырылмады: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock байланыстырылмады: {error}", + "Stopping containers…": "Контейнерлер тоқтатылуда…", + "Copying data…": "Деректер көшірілуде…", + "Verifying copy…": "Көшірме тексерілуде…", + "Switching storage…": "Сақтау орны ауыстырылуда…", + "Restarting engine…": "Қозғалтқыш қайта іске қосылуда…", + "Moving data…": "Деректер жылжытылуда…", + "Storage location unavailable": "Сақтау орны қолжетімсіз", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri {path} ішінен деректерін таба алмады. Дискіні қосып қайталап көріңіз, басқа қалтаны таңдаңыз немесе әдепкі орынға қайтарыңыз.", + "Change…": "Өзгерту…", + "Reset to default": "Әдепкіге қайтару", + "Open storage settings": "Сақтау баптауларын ашу", + "Start Kiri to change its storage location. ({error})": "Сақтау орнын өзгерту үшін Kiri-ді іске қосыңыз. ({error})", + "{size} used": "{size} қолданылды", + "{size} free": "{size} бос", + "Default": "Әдепкі", + "Moving Kiri's data to {path}.": "Kiri деректері {path} ішіне жылжытылуда.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri деректерді көшіріп жатқанда жұмыс істеп тұрған контейнерлер тоқтайды және аяқталған соң қайта іске қосылады.", + "Couldn't change storage location": "Сақтау орнын өзгерту мүмкін болмады", + "Old data": "Ескі деректер", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Алдыңғы деректер әлі де {path} ішінде сақталған. Жаңа орында бәрі жұмыс істеген соң оны жойыңыз.", + "Remove old data": "Ескі деректерді жою", + "Storage location": "Сақтау орны", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri сақтау орнын белгілейді, сондықтан оны мұнда өзгертуге болмайды.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Бейнелер, контейнерлер және томдар осы қалтада сақталады. Сыртқы дискілер жергілікті файлдық жүйені пайдалануы тиіс (macOS-та APFS, Linux-та ext4/xfs/btrfs, Windows-та NTFS); FAT және exFAT дискілері қолдау таппайды.", + "Reset storage location to default?": "Сақтау орнын әдепкіге қайтару керек пе?", + "Change storage location?": "Сақтау орнын өзгерту керек пе?", + "Destination: {path} ({free} free).": "Мақсатты орын: {path} ({free} бос).", + "Destination: {path}.": "Мақсатты орын: {path}.", + "Existing Kiri data in this folder will be replaced.": "Осы қалтадағы бар Kiri деректері ауыстырылады.", + "Migration mode": "Көшіру режимі", + "Move existing images, containers, and volumes": "Бар бейнелерді, контейнерлерді және томдарды жылжыту", + "Stops running containers, copies your data, and starts them again.": "Жұмыс істеп тұрған контейнерлерді тоқтатады, деректеріңізді көшіреді және қайта іске қосады.", + "Start fresh": "Таза күйде бастау", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Жаңа қалтада бос күйде басталады. Ескі қалта сіз жойғанша сақталады.", + "Kiri will switch to this folder and restart the engine.": "Kiri осы қалтаға ауысып, қозғалтқышты қайта іске қосады.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri деректеріңізді жылжытып жатқанда жұмыс істеп тұрған контейнерлер тоқтайды және аяқталған соң қайта іске қосылады.", + "Move data": "Деректерді жылжыту", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri әдепкі қалтасына оралып, қозғалтқышты қайта іске қосады. Ажыратылған дискідегі деректер жойылмайды.", + "Remove old data?": "Ескі деректерді жою керек пе?", + "Everything in {path} will be deleted for good.": "{path} ішіндегі барлық нәрсе біржола жойылады.", + "Choose a storage folder": "Сақтау қалтасын таңдаңыз", + "Kiri's data is moving already": "Kiri деректері қазірдің өзінде жылжытылуда", + "Kiri's data moved to {path}": "Kiri деректері {path} ішіне жылжытылды", + "Storage is available again": "Сақтау орны қайта қолжетімді", + "Old data removed": "Ескі деректер жойылды" } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 669f8a477..b53f3e1a1 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1887,5 +1887,50 @@ "Switching…": "전환 중…", "{docker} command": "{docker} 명령", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock이(가) 이제 Kiri를 가리킵니다", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock을(를) 연결하지 못했습니다: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock을(를) 연결하지 못했습니다: {error}", + "Stopping containers…": "컨테이너 중지 중…", + "Copying data…": "데이터 복사 중…", + "Verifying copy…": "복사본 확인 중…", + "Switching storage…": "저장소 전환 중…", + "Restarting engine…": "엔진 재시작 중…", + "Moving data…": "데이터 이동 중…", + "Storage location unavailable": "저장 위치를 사용할 수 없음", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri가 {path}에서 데이터를 찾을 수 없습니다. 드라이브를 연결하고 다시 시도하거나, 다른 폴더를 선택하거나, 기본 위치로 재설정하세요.", + "Change…": "변경…", + "Reset to default": "기본값으로 재설정", + "Open storage settings": "저장소 설정 열기", + "Start Kiri to change its storage location. ({error})": "저장 위치를 변경하려면 Kiri를 시작하세요. ({error})", + "{size} used": "{size} 사용됨", + "{size} free": "{size} 여유", + "Default": "기본값", + "Moving Kiri's data to {path}.": "Kiri 데이터를 {path}(으)로 이동하는 중입니다.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri가 데이터를 복사하는 동안 실행 중인 컨테이너가 잠시 중지되며 완료되면 다시 시작됩니다.", + "Couldn't change storage location": "저장 위치를 변경할 수 없음", + "Old data": "이전 데이터", + "Previous data is still in {path}. Remove it once everything works in the new location.": "이전 데이터가 아직 {path}에 남아 있습니다. 새 위치에서 모든 것이 정상 작동하면 삭제하세요.", + "Remove old data": "이전 데이터 삭제", + "Storage location": "저장 위치", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var}이(가) Kiri의 저장 위치를 지정하므로 여기서는 변경할 수 없습니다.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "이미지, 컨테이너, 볼륨이 이 폴더에 저장됩니다. 외장 드라이브는 네이티브 파일 시스템(macOS의 APFS, Linux의 ext4/xfs/btrfs, Windows의 NTFS)을 사용해야 하며 FAT 및 exFAT 드라이브는 지원되지 않습니다.", + "Reset storage location to default?": "저장 위치를 기본값으로 재설정할까요?", + "Change storage location?": "저장 위치를 변경할까요?", + "Destination: {path} ({free} free).": "대상: {path} ({free} 여유).", + "Destination: {path}.": "대상: {path}.", + "Existing Kiri data in this folder will be replaced.": "이 폴더에 있는 기존 Kiri 데이터가 대체됩니다.", + "Migration mode": "이동 방식", + "Move existing images, containers, and volumes": "기존 이미지, 컨테이너 및 볼륨 이동", + "Stops running containers, copies your data, and starts them again.": "실행 중인 컨테이너를 중지하고 데이터를 복사한 뒤 다시 시작합니다.", + "Start fresh": "새로 시작", + "Starts empty in the new folder. Your old folder stays until you remove it.": "새 폴더에서 빈 상태로 시작합니다. 이전 폴더는 삭제하기 전까지 유지됩니다.", + "Kiri will switch to this folder and restart the engine.": "Kiri가 이 폴더로 전환하고 엔진을 재시작합니다.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri가 데이터를 이동하는 동안 실행 중인 컨테이너가 중지되며 완료되면 다시 시작됩니다.", + "Move data": "데이터 이동", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri가 기본 폴더로 돌아가고 엔진을 재시작합니다. 연결이 끊긴 드라이브의 데이터는 삭제되지 않습니다.", + "Remove old data?": "이전 데이터를 삭제할까요?", + "Everything in {path} will be deleted for good.": "{path}의 모든 항목이 영구적으로 삭제됩니다.", + "Choose a storage folder": "저장 폴더 선택", + "Kiri's data is moving already": "Kiri 데이터가 이미 이동 중입니다", + "Kiri's data moved to {path}": "Kiri 데이터가 {path}(으)로 이동되었습니다", + "Storage is available again": "저장소를 다시 사용할 수 있습니다", + "Old data removed": "이전 데이터가 삭제되었습니다" } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 7f7f8bd17..5b5af8ad1 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1887,5 +1887,50 @@ "Switching…": "ກຳລັງປ່ຽນ…", "{docker} command": "ຄຳສັ່ງ {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ຊີ້ໄປທີ່ Kiri ແລ້ວ", - "Could not link /var/run/docker.sock: {error}": "ບໍ່ສາມາດເຊື່ອມຕໍ່ /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "ບໍ່ສາມາດເຊື່ອມຕໍ່ /var/run/docker.sock: {error}", + "Stopping containers…": "ກຳລັງຢຸດຄອນເທນເນີ…", + "Copying data…": "ກຳລັງຄັດລອກຂໍ້ມູນ…", + "Verifying copy…": "ກຳລັງກວດສອບສຳເນົາ…", + "Switching storage…": "ກຳລັງປ່ຽນບ່ອນຈັດເກັບ…", + "Restarting engine…": "ກຳລັງເລີ່ມເຄື່ອງຈັກໃໝ່…", + "Moving data…": "ກຳລັງຍ້າຍຂໍ້ມູນ…", + "Storage location unavailable": "ບ່ອນຈັດເກັບຂໍ້ມູນບໍ່ພ້ອມໃຊ້ງານ", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ບໍ່ພົບຂໍ້ມູນຂອງມັນໃນ {path}. ເຊື່ອມຕໍ່ໄດຣຟ໌ແລ້ວລອງໃໝ່, ເລືອກໂຟນເດີອື່ນ ຫຼື ຣີເຊັດກັບໄປບ່ອນເລີ່ມຕົ້ນ.", + "Change…": "ປ່ຽນ…", + "Reset to default": "ຣີເຊັດເປັນຄ່າເລີ່ມຕົ້ນ", + "Open storage settings": "ເປີດການຕັ້ງຄ່າບ່ອນຈັດເກັບ", + "Start Kiri to change its storage location. ({error})": "ເລີ່ມ Kiri ເພື່ອປ່ຽນບ່ອນຈັດເກັບຂໍ້ມູນ. ({error})", + "{size} used": "ໃຊ້ແລ້ວ {size}", + "{size} free": "ວ່າງ {size}", + "Default": "ຄ່າເລີ່ມຕົ້ນ", + "Moving Kiri's data to {path}.": "ກຳລັງຍ້າຍຂໍ້ມູນຂອງ Kiri ໄປຍັງ {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "ຄອນເທນເນີທີ່ກຳລັງເຮັດວຽກຈະຢຸດຊົ່ວຄາວໃນຂະນະທີ່ Kiri ຄັດລອກຂໍ້ມູນ ແລະ ຈະເລີ່ມໃໝ່ເມື່ອສຳເລັດ.", + "Couldn't change storage location": "ບໍ່ສາມາດປ່ຽນບ່ອນຈັດເກັບຂໍ້ມູນໄດ້", + "Old data": "ຂໍ້ມູນເກົ່າ", + "Previous data is still in {path}. Remove it once everything works in the new location.": "ຂໍ້ມູນເກົ່າຍັງຢູ່ໃນ {path}. ລຶບມັນອອກເມື່ອທຸກຢ່າງເຮັດວຽກປົກກະຕິໃນບ່ອນໃໝ່.", + "Remove old data": "ລຶບຂໍ້ມູນເກົ່າ", + "Storage location": "ບ່ອນຈັດເກັບຂໍ້ມູນ", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} ກຳນົດບ່ອນຈັດເກັບຂໍ້ມູນຂອງ Kiri, ດັ່ງນັ້ນບໍ່ສາມາດປ່ຽນຢູ່ບ່ອນນີ້ໄດ້.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "ອິມເມຈ, ຄອນເທນເນີ ແລະ ວໍລູມ ຈະຢູ່ໃນໂຟນເດີນີ້. ໄດຣຟ໌ພາຍນອກຕ້ອງໃຊ້ລະບົບໄຟລ໌ພື້ນເມືອງ (APFS ໃນ macOS, ext4/xfs/btrfs ໃນ Linux, NTFS ໃນ Windows); ບໍ່ຮອງຮັບໄດຣຟ໌ FAT ແລະ exFAT.", + "Reset storage location to default?": "ຣີເຊັດບ່ອນຈັດເກັບຂໍ້ມູນເປັນຄ່າເລີ່ມຕົ້ນບໍ?", + "Change storage location?": "ປ່ຽນບ່ອນຈັດເກັບຂໍ້ມູນບໍ?", + "Destination: {path} ({free} free).": "ປາຍທາງ: {path} (ວ່າງ {free}).", + "Destination: {path}.": "ປາຍທາງ: {path}.", + "Existing Kiri data in this folder will be replaced.": "ຂໍ້ມູນ Kiri ທີ່ມີຢູ່ໃນໂຟນເດີນີ້ຈະຖືກແທນທີ່.", + "Migration mode": "ຮູບແບບການຍ້າຍ", + "Move existing images, containers, and volumes": "ຍ້າຍອິມເມຈ, ຄອນເທນເນີ ແລະ ວໍລູມ ທີ່ມີຢູ່", + "Stops running containers, copies your data, and starts them again.": "ຢຸດຄອນເທນເນີທີ່ກຳລັງເຮັດວຽກ, ຄັດລອກຂໍ້ມູນຂອງທ່ານ ແລະ ເລີ່ມພວກມັນໃໝ່.", + "Start fresh": "ເລີ່ມຕົ້ນໃໝ່", + "Starts empty in the new folder. Your old folder stays until you remove it.": "ເລີ່ມວ່າງເປົ່າໃນໂຟນເດີໃໝ່. ໂຟນເດີເກົ່າຈະຍັງຢູ່ຈົນກວ່າທ່ານຈະລຶບອອກ.", + "Kiri will switch to this folder and restart the engine.": "Kiri ຈະປ່ຽນໄປໃຊ້ໂຟນເດີນີ້ ແລະ ເລີ່ມເຄື່ອງຈັກໃໝ່.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "ຄອນເທນເນີທີ່ກຳລັງເຮັດວຽກຈະຢຸດໃນຂະນະທີ່ Kiri ຍ້າຍຂໍ້ມູນຂອງທ່ານ ແລະ ຈະເລີ່ມໃໝ່ເມື່ອສຳເລັດ.", + "Move data": "ຍ້າຍຂໍ້ມູນ", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri ຈະກັບໄປໃຊ້ໂຟນເດີເລີ່ມຕົ້ນ ແລະ ເລີ່ມເຄື່ອງຈັກໃໝ່. ຂໍ້ມູນໃນໄດຣຟ໌ທີ່ຖອດອອກຈະບໍ່ຖືກລຶບ.", + "Remove old data?": "ລຶບຂໍ້ມູນເກົ່າບໍ?", + "Everything in {path} will be deleted for good.": "ທຸກຢ່າງໃນ {path} ຈະຖືກລຶບຖາວອນ.", + "Choose a storage folder": "ເລືອກໂຟນເດີຈັດເກັບຂໍ້ມູນ", + "Kiri's data is moving already": "ຂໍ້ມູນຂອງ Kiri ກຳລັງຖືກຍ້າຍຢູ່ແລ້ວ", + "Kiri's data moved to {path}": "ຍ້າຍຂໍ້ມູນຂອງ Kiri ໄປຍັງ {path} ແລ້ວ", + "Storage is available again": "ບ່ອນຈັດເກັບຂໍ້ມູນພ້ອມໃຊ້ງານອີກຄັ້ງ", + "Old data removed": "ລຶບຂໍ້ມູນເກົ່າແລ້ວ" } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 580039bf0..a9f7d928a 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1887,5 +1887,50 @@ "Switching…": "Perjungiama…", "{docker} command": "{docker} komanda", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock dabar rodo į Kiri", - "Could not link /var/run/docker.sock: {error}": "Nepavyko susieti /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Nepavyko susieti /var/run/docker.sock: {error}", + "Stopping containers…": "Stabdomi konteineriai…", + "Copying data…": "Kopijuojami duomenys…", + "Verifying copy…": "Tikrinama kopija…", + "Switching storage…": "Perjungiama saugykla…", + "Restarting engine…": "Iš naujo paleidžiamas variklis…", + "Moving data…": "Perkeliami duomenys…", + "Storage location unavailable": "Saugyklos vieta nepasiekiama", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri nerado savo duomenų {path}. Prijunkite diską ir bandykite dar kartą, pasirinkite kitą aplanką arba atkurkite numatytąją vietą.", + "Change…": "Keisti…", + "Reset to default": "Atkurti numatytąją", + "Open storage settings": "Atidaryti saugyklos nustatymus", + "Start Kiri to change its storage location. ({error})": "Paleiskite Kiri, kad pakeistumėte saugyklos vietą. ({error})", + "{size} used": "{size} užimta", + "{size} free": "{size} laisva", + "Default": "Numatytoji", + "Moving Kiri's data to {path}.": "Kiri duomenys perkeliami į {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Veikiantys konteineriai pristabdomi, kol Kiri kopijuoja duomenis, ir baigus vėl paleidžiami.", + "Couldn't change storage location": "Nepavyko pakeisti saugyklos vietos", + "Old data": "Seni duomenys", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Ankstesni duomenys vis dar yra {path}. Pašalinkite juos, kai naujoje vietoje viskas veiks.", + "Remove old data": "Pašalinti senus duomenis", + "Storage location": "Saugyklos vieta", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} nustato Kiri saugyklos vietą, todėl čia jos keisti negalima.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Atvaizdai, konteineriai ir tomai laikomi šiame aplanke. Išoriniai diskai turi naudoti prigimtinę failų sistemą (APFS sistemoje macOS, ext4/xfs/btrfs sistemoje Linux, NTFS sistemoje Windows); FAT ir exFAT diskai nepalaikomi.", + "Reset storage location to default?": "Atkurti numatytąją saugyklos vietą?", + "Change storage location?": "Keisti saugyklos vietą?", + "Destination: {path} ({free} free).": "Paskirtis: {path} ({free} laisva).", + "Destination: {path}.": "Paskirtis: {path}.", + "Existing Kiri data in this folder will be replaced.": "Esami Kiri duomenys šiame aplanke bus pakeisti.", + "Migration mode": "Perkėlimo režimas", + "Move existing images, containers, and volumes": "Perkelti esamus atvaizdus, konteinerius ir tomus", + "Stops running containers, copies your data, and starts them again.": "Sustabdo veikiančius konteinerius, nukopijuoja jūsų duomenis ir vėl juos paleidžia.", + "Start fresh": "Pradėti iš naujo", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Pradeda tuščiai naujame aplanke. Senas aplankas lieka, kol jį pašalinsite.", + "Kiri will switch to this folder and restart the engine.": "Kiri persijungs į šį aplanką ir iš naujo paleis variklį.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Veikiantys konteineriai sustos, kol Kiri perkels jūsų duomenis, ir baigus vėl paleis.", + "Move data": "Perkelti duomenis", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri grįš į numatytąjį aplanką ir iš naujo paleis variklį. Duomenys atjungtame diske neištrinami.", + "Remove old data?": "Pašalinti senus duomenis?", + "Everything in {path} will be deleted for good.": "Viskas aplanke {path} bus ištrinta visam laikui.", + "Choose a storage folder": "Pasirinkite saugyklos aplanką", + "Kiri's data is moving already": "Kiri duomenys jau perkeliami", + "Kiri's data moved to {path}": "Kiri duomenys perkelti į {path}", + "Storage is available again": "Saugykla vėl pasiekiama", + "Old data removed": "Seni duomenys pašalinti" } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 5240843af..45e92ab55 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1887,5 +1887,50 @@ "Switching…": "Bytter…", "{docker} command": "{docker}-kommando", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock peker nå til Kiri", - "Could not link /var/run/docker.sock: {error}": "Kunne ikke lenke /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Kunne ikke lenke /var/run/docker.sock: {error}", + "Stopping containers…": "Stopper containere…", + "Copying data…": "Kopierer data…", + "Verifying copy…": "Bekrefter kopi…", + "Switching storage…": "Bytter lagring…", + "Restarting engine…": "Starter motoren på nytt…", + "Moving data…": "Flytter data…", + "Storage location unavailable": "Lagringsplassering utilgjengelig", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri fant ikke dataene sine i {path}. Koble til disken og prøv igjen, velg en annen mappe eller tilbakestill til standardplasseringen.", + "Change…": "Endre…", + "Reset to default": "Tilbakestill til standard", + "Open storage settings": "Åpne lagringsinnstillinger", + "Start Kiri to change its storage location. ({error})": "Start Kiri for å endre lagringsplassering. ({error})", + "{size} used": "{size} brukt", + "{size} free": "{size} ledig", + "Default": "Standard", + "Moving Kiri's data to {path}.": "Flytter Kiris data til {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kjørende containere settes på pause mens Kiri kopierer dataene, og starter igjen når det er ferdig.", + "Couldn't change storage location": "Kunne ikke endre lagringsplassering", + "Old data": "Gamle data", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Tidligere data ligger fortsatt i {path}. Fjern dem når alt fungerer på den nye plasseringen.", + "Remove old data": "Fjern gamle data", + "Storage location": "Lagringsplassering", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} angir Kiris lagringsplassering, så den kan ikke endres her.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Avbildninger, containere og volumer lagres i denne mappen. Eksterne disker må bruke et innebygd filsystem (APFS på macOS, ext4/xfs/btrfs på Linux, NTFS på Windows); FAT- og exFAT-disker støttes ikke.", + "Reset storage location to default?": "Tilbakestille lagringsplassering til standard?", + "Change storage location?": "Endre lagringsplassering?", + "Destination: {path} ({free} free).": "Mål: {path} ({free} ledig).", + "Destination: {path}.": "Mål: {path}.", + "Existing Kiri data in this folder will be replaced.": "Eksisterende Kiri-data i denne mappen blir erstattet.", + "Migration mode": "Flyttemodus", + "Move existing images, containers, and volumes": "Flytt eksisterende avbildninger, containere og volumer", + "Stops running containers, copies your data, and starts them again.": "Stopper kjørende containere, kopierer dataene dine og starter dem igjen.", + "Start fresh": "Start på nytt", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Starter tomt i den nye mappen. Den gamle mappen beholdes til du fjerner den.", + "Kiri will switch to this folder and restart the engine.": "Kiri bytter til denne mappen og starter motoren på nytt.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kjørende containere stoppes mens Kiri flytter dataene dine og starter igjen når det er ferdig.", + "Move data": "Flytt data", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri bytter tilbake til standardmappen og starter motoren på nytt. Data på den frakoblede disken slettes ikke.", + "Remove old data?": "Fjerne gamle data?", + "Everything in {path} will be deleted for good.": "Alt i {path} slettes for godt.", + "Choose a storage folder": "Velg en lagringsmappe", + "Kiri's data is moving already": "Kiris data flyttes allerede", + "Kiri's data moved to {path}": "Kiris data ble flyttet til {path}", + "Storage is available again": "Lagring er tilgjengelig igjen", + "Old data removed": "Gamle data fjernet" } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index ae0936d44..0a094d9da 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1887,5 +1887,50 @@ "Switching…": "Przełączanie…", "{docker} command": "Polecenie {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock wskazuje teraz na Kiri", - "Could not link /var/run/docker.sock: {error}": "Nie udało się dowiązać /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Nie udało się dowiązać /var/run/docker.sock: {error}", + "Stopping containers…": "Zatrzymywanie kontenerów…", + "Copying data…": "Kopiowanie danych…", + "Verifying copy…": "Weryfikowanie kopii…", + "Switching storage…": "Przełączanie pamięci…", + "Restarting engine…": "Ponowne uruchamianie silnika…", + "Moving data…": "Przenoszenie danych…", + "Storage location unavailable": "Lokalizacja danych niedostępna", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri nie znalazło swoich danych w {path}. Podłącz dysk i spróbuj ponownie, wybierz inny folder lub przywróć lokalizację domyślną.", + "Change…": "Zmień…", + "Reset to default": "Przywróć domyślną", + "Open storage settings": "Otwórz ustawienia pamięci", + "Start Kiri to change its storage location. ({error})": "Uruchom Kiri, aby zmienić lokalizację danych. ({error})", + "{size} used": "Użyto {size}", + "{size} free": "Wolne {size}", + "Default": "Domyślna", + "Moving Kiri's data to {path}.": "Przenoszenie danych Kiri do {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Działające kontenery zatrzymują się na czas kopiowania danych przez Kiri i uruchamiają ponownie po zakończeniu.", + "Couldn't change storage location": "Nie udało się zmienić lokalizacji danych", + "Old data": "Stare dane", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Poprzednie dane nadal są w {path}. Usuń je, gdy wszystko będzie działać w nowej lokalizacji.", + "Remove old data": "Usuń stare dane", + "Storage location": "Lokalizacja danych", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} ustawia lokalizację danych Kiri, więc nie można jej tu zmienić.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Obrazy, kontenery i wolumeny znajdują się w tym folderze. Dyski zewnętrzne muszą używać natywnego systemu plików (APFS w macOS, ext4/xfs/btrfs w Linux, NTFS w Windows); dyski FAT i exFAT nie są obsługiwane.", + "Reset storage location to default?": "Przywrócić domyślną lokalizację danych?", + "Change storage location?": "Zmienić lokalizację danych?", + "Destination: {path} ({free} free).": "Cel: {path} (wolne {free}).", + "Destination: {path}.": "Cel: {path}.", + "Existing Kiri data in this folder will be replaced.": "Istniejące dane Kiri w tym folderze zostaną zastąpione.", + "Migration mode": "Tryb migracji", + "Move existing images, containers, and volumes": "Przenieś istniejące obrazy, kontenery i wolumeny", + "Stops running containers, copies your data, and starts them again.": "Zatrzymuje działające kontenery, kopiuje dane i uruchamia je ponownie.", + "Start fresh": "Zacznij od nowa", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Zaczyna na czysto w nowym folderze. Stary folder zostaje, dopóki go nie usuniesz.", + "Kiri will switch to this folder and restart the engine.": "Kiri przełączy się na ten folder i uruchomi silnik ponownie.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Działające kontenery zatrzymają się na czas przenoszenia danych i uruchomią ponownie po zakończeniu.", + "Move data": "Przenieś dane", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri wróci do domyślnego folderu i uruchomi silnik ponownie. Dane na odłączonym dysku nie zostaną usunięte.", + "Remove old data?": "Usunąć stare dane?", + "Everything in {path} will be deleted for good.": "Wszystko w {path} zostanie trwale usunięte.", + "Choose a storage folder": "Wybierz folder danych", + "Kiri's data is moving already": "Dane Kiri są już przenoszone", + "Kiri's data moved to {path}": "Przeniesiono dane Kiri do {path}", + "Storage is available again": "Pamięć jest ponownie dostępna", + "Old data removed": "Stare dane usunięto" } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 3eca0f4ef..fc9feec2e 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1887,5 +1887,50 @@ "Switching…": "Alternando…", "{docker} command": "Comando {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock agora aponta para o Kiri", - "Could not link /var/run/docker.sock: {error}": "Não foi possível vincular /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Não foi possível vincular /var/run/docker.sock: {error}", + "Stopping containers…": "Parando contêineres…", + "Copying data…": "Copiando dados…", + "Verifying copy…": "Verificando cópia…", + "Switching storage…": "Alternando armazenamento…", + "Restarting engine…": "Reiniciando o mecanismo…", + "Moving data…": "Movendo dados…", + "Storage location unavailable": "Local de armazenamento indisponível", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "O Kiri não encontrou seus dados em {path}. Conecte o disco e tente novamente, escolha outra pasta ou volte para o local padrão.", + "Change…": "Alterar…", + "Reset to default": "Restaurar padrão", + "Open storage settings": "Abrir configurações de armazenamento", + "Start Kiri to change its storage location. ({error})": "Inicie o Kiri para alterar o local de armazenamento. ({error})", + "{size} used": "{size} usados", + "{size} free": "{size} livres", + "Default": "Padrão", + "Moving Kiri's data to {path}.": "Movendo os dados do Kiri para {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Os contêineres em execução param enquanto o Kiri copia os dados e iniciam novamente ao terminar.", + "Couldn't change storage location": "Não foi possível alterar o local de armazenamento", + "Old data": "Dados antigos", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Os dados anteriores ainda estão em {path}. Remova-os quando tudo estiver funcionando no novo local.", + "Remove old data": "Remover dados antigos", + "Storage location": "Local de armazenamento", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} define o local de armazenamento do Kiri, então não pode ser alterado aqui.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Imagens, contêineres e volumes ficam nesta pasta. Discos externos precisam usar um sistema de arquivos nativo (APFS no macOS, ext4/xfs/btrfs no Linux, NTFS no Windows); unidades FAT e exFAT não são compatíveis.", + "Reset storage location to default?": "Restaurar o local de armazenamento padrão?", + "Change storage location?": "Alterar o local de armazenamento?", + "Destination: {path} ({free} free).": "Destino: {path} ({free} livres).", + "Destination: {path}.": "Destino: {path}.", + "Existing Kiri data in this folder will be replaced.": "Os dados do Kiri já existentes nesta pasta serão substituídos.", + "Migration mode": "Modo de migração", + "Move existing images, containers, and volumes": "Mover imagens, contêineres e volumes existentes", + "Stops running containers, copies your data, and starts them again.": "Para os contêineres em execução, copia seus dados e os inicia novamente.", + "Start fresh": "Começar do zero", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Inicia vazio na nova pasta. A pasta antiga permanece até você removê-la.", + "Kiri will switch to this folder and restart the engine.": "O Kiri mudará para esta pasta e reiniciará o mecanismo.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Os contêineres em execução serão parados enquanto o Kiri move seus dados e iniciados novamente ao terminar.", + "Move data": "Mover dados", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "O Kiri voltará para a pasta padrão e reiniciará o mecanismo. Os dados no disco desconectado não são apagados.", + "Remove old data?": "Remover dados antigos?", + "Everything in {path} will be deleted for good.": "Tudo em {path} será excluído permanentemente.", + "Choose a storage folder": "Escolha uma pasta de armazenamento", + "Kiri's data is moving already": "Os dados do Kiri já estão sendo movidos", + "Kiri's data moved to {path}": "Dados do Kiri movidos para {path}", + "Storage is available again": "Armazenamento disponível novamente", + "Old data removed": "Dados antigos removidos" } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index c8edf1707..0601e384b 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1887,5 +1887,50 @@ "Switching…": "Se comută…", "{docker} command": "Comanda {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock indică acum spre Kiri", - "Could not link /var/run/docker.sock: {error}": "Nu s-a putut lega /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Nu s-a putut lega /var/run/docker.sock: {error}", + "Stopping containers…": "Se opresc containerele…", + "Copying data…": "Se copiază datele…", + "Verifying copy…": "Se verifică copia…", + "Switching storage…": "Se schimbă stocarea…", + "Restarting engine…": "Se repornește motorul…", + "Moving data…": "Se mută datele…", + "Storage location unavailable": "Locația de stocare nu este disponibilă", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri nu și-a găsit datele în {path}. Conectează discul și încearcă din nou, alege alt folder sau revino la locația implicită.", + "Change…": "Schimbă…", + "Reset to default": "Revino la implicit", + "Open storage settings": "Deschide setările de stocare", + "Start Kiri to change its storage location. ({error})": "Pornește Kiri pentru a schimba locația de stocare. ({error})", + "{size} used": "{size} folosiți", + "{size} free": "{size} liberi", + "Default": "Implicit", + "Moving Kiri's data to {path}.": "Se mută datele Kiri în {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Containerele active sunt oprite temporar cât Kiri copiază datele și repornesc la final.", + "Couldn't change storage location": "Nu s-a putut schimba locația de stocare", + "Old data": "Date vechi", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Datele anterioare sunt încă în {path}. Șterge-le după ce totul funcționează în noua locație.", + "Remove old data": "Elimină datele vechi", + "Storage location": "Locație de stocare", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} stabilește locația de stocare a Kiri, așa că nu poate fi schimbată aici.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Imaginile, containerele și volumele sunt păstrate în acest folder. Discurile externe trebuie să folosească un sistem de fișiere nativ (APFS pe macOS, ext4/xfs/btrfs pe Linux, NTFS pe Windows); FAT și exFAT nu sunt acceptate.", + "Reset storage location to default?": "Revii la locația de stocare implicită?", + "Change storage location?": "Schimbi locația de stocare?", + "Destination: {path} ({free} free).": "Destinație: {path} ({free} liberi).", + "Destination: {path}.": "Destinație: {path}.", + "Existing Kiri data in this folder will be replaced.": "Datele Kiri existente în acest folder vor fi înlocuite.", + "Migration mode": "Mod de migrare", + "Move existing images, containers, and volumes": "Mută imaginile, containerele și volumele existente", + "Stops running containers, copies your data, and starts them again.": "Oprește containerele active, copiază datele și le repornește.", + "Start fresh": "Începe de la zero", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Pornește gol în noul folder. Vechiul folder rămâne până îl elimini.", + "Kiri will switch to this folder and restart the engine.": "Kiri va trece pe acest folder și va reporni motorul.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Containerele active se vor opri cât Kiri mută datele și vor reporni la final.", + "Move data": "Mută datele", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri va reveni la folderul implicit și va reporni motorul. Datele de pe discul deconectat nu sunt șterse.", + "Remove old data?": "Elimini datele vechi?", + "Everything in {path} will be deleted for good.": "Tot ce se află în {path} va fi șters definitiv.", + "Choose a storage folder": "Alege un folder de stocare", + "Kiri's data is moving already": "Datele Kiri se mută deja", + "Kiri's data moved to {path}": "Datele Kiri au fost mutate în {path}", + "Storage is available again": "Stocarea este din nou disponibilă", + "Old data removed": "Datele vechi au fost eliminate" } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index 091cb47a3..862dcb9a2 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1887,5 +1887,50 @@ "Switching…": "Переключение…", "{docker} command": "Команда {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock теперь указывает на Kiri", - "Could not link /var/run/docker.sock: {error}": "Не удалось связать /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Не удалось связать /var/run/docker.sock: {error}", + "Stopping containers…": "Остановка контейнеров…", + "Copying data…": "Копирование данных…", + "Verifying copy…": "Проверка копии…", + "Switching storage…": "Переключение хранилища…", + "Restarting engine…": "Перезапуск движка…", + "Moving data…": "Перенос данных…", + "Storage location unavailable": "Папка хранилища недоступна", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri не удалось найти свои данные в {path}. Подключите диск и повторите, выберите другую папку или верните папку по умолчанию.", + "Change…": "Изменить…", + "Reset to default": "Сбросить по умолчанию", + "Open storage settings": "Открыть настройки хранилища", + "Start Kiri to change its storage location. ({error})": "Запустите Kiri, чтобы изменить расположение хранилища. ({error})", + "{size} used": "Занято {size}", + "{size} free": "Свободно {size}", + "Default": "По умолчанию", + "Moving Kiri's data to {path}.": "Перенос данных Kiri в {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Запущенные контейнеры приостанавливаются на время копирования и запускаются снова после завершения.", + "Couldn't change storage location": "Не удалось изменить расположение хранилища", + "Old data": "Старые данные", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Прежние данные всё ещё находятся в {path}. Удалите их, когда убедитесь, что на новом месте всё работает.", + "Remove old data": "Удалить старые данные", + "Storage location": "Расположение хранилища", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} задаёт папку хранилища Kiri, поэтому её нельзя изменить здесь.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Образы, контейнеры и тома хранятся в этой папке. Внешние диски должны использовать нативную файловую систему (APFS в macOS, ext4/xfs/btrfs в Linux, NTFS в Windows); диски FAT и exFAT не поддерживаются.", + "Reset storage location to default?": "Сбросить расположение хранилища по умолчанию?", + "Change storage location?": "Изменить расположение хранилища?", + "Destination: {path} ({free} free).": "Назначение: {path} (свободно {free}).", + "Destination: {path}.": "Назначение: {path}.", + "Existing Kiri data in this folder will be replaced.": "Существующие данные Kiri в этой папке будут заменены.", + "Migration mode": "Режим переноса", + "Move existing images, containers, and volumes": "Перенести существующие образы, контейнеры и тома", + "Stops running containers, copies your data, and starts them again.": "Останавливает запущенные контейнеры, копирует данные и запускает их снова.", + "Start fresh": "Начать с чистого листа", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Запускается с пустым хранилищем в новой папке. Старая папка остаётся, пока вы её не удалите.", + "Kiri will switch to this folder and restart the engine.": "Kiri переключится на эту папку и перезапустит движок.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Запущенные контейнеры остановятся на время переноса и запустятся снова после завершения.", + "Move data": "Перенести данные", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri вернётся к папке по умолчанию и перезапустит движок. Данные на отключённом диске не удаляются.", + "Remove old data?": "Удалить старые данные?", + "Everything in {path} will be deleted for good.": "Всё содержимое {path} будет удалено безвозвратно.", + "Choose a storage folder": "Выберите папку хранилища", + "Kiri's data is moving already": "Данные Kiri уже переносятся", + "Kiri's data moved to {path}": "Данные Kiri перенесены в {path}", + "Storage is available again": "Хранилище снова доступно", + "Old data removed": "Старые данные удалены" } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index a014e9425..d806d4ce6 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1887,5 +1887,50 @@ "Switching…": "Preklapljanje…", "{docker} command": "Ukaz {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock zdaj kaže na Kiri", - "Could not link /var/run/docker.sock: {error}": "Povezave /var/run/docker.sock ni bilo mogoče ustvariti: {error}" + "Could not link /var/run/docker.sock: {error}": "Povezave /var/run/docker.sock ni bilo mogoče ustvariti: {error}", + "Stopping containers…": "Ustavljanje vsebnikov…", + "Copying data…": "Kopiranje podatkov…", + "Verifying copy…": "Preverjanje kopije…", + "Switching storage…": "Preklapljanje shrambe…", + "Restarting engine…": "Ponovni zagon pogona…", + "Moving data…": "Premikanje podatkov…", + "Storage location unavailable": "Mesto shrambe ni na voljo", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ni našel svojih podatkov v {path}. Povežite disk in poskusite znova, izberite drugo mapo ali ponastavite na privzeto mesto.", + "Change…": "Spremeni…", + "Reset to default": "Ponastavi na privzeto", + "Open storage settings": "Odpri nastavitve shrambe", + "Start Kiri to change its storage location. ({error})": "Zaženite Kiri za spremembo mesta shrambe. ({error})", + "{size} used": "{size} porabljeno", + "{size} free": "{size} prosto", + "Default": "Privzeto", + "Moving Kiri's data to {path}.": "Premikanje podatkov Kiri v {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Delujoči vsebniki se med kopiranjem ustavijo in po koncu znova zaženejo.", + "Couldn't change storage location": "Mesta shrambe ni bilo mogoče spremeniti", + "Old data": "Stari podatki", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Prejšnji podatki so še vedno v {path}. Odstranite jih, ko na novem mestu vse deluje.", + "Remove old data": "Odstrani stare podatke", + "Storage location": "Mesto shrambe", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} določa mesto shrambe Kiri, zato ga tukaj ni mogoče spremeniti.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Slike, vsebniki in nosilci so shranjeni v tej mapi. Zunanji diski morajo uporabljati domorodni datotečni sistem (APFS v macOS, ext4/xfs/btrfs v Linuxu, NTFS v sistemu Windows); diski FAT in exFAT niso podprti.", + "Reset storage location to default?": "Ponastavim mesto shrambe na privzeto?", + "Change storage location?": "Spremenim mesto shrambe?", + "Destination: {path} ({free} free).": "Cilj: {path} ({free} prosto).", + "Destination: {path}.": "Cilj: {path}.", + "Existing Kiri data in this folder will be replaced.": "Obstoječi podatki Kiri v tej mapi bodo zamenjani.", + "Migration mode": "Način prenosa", + "Move existing images, containers, and volumes": "Premakni obstoječe slike, vsebnike in nosilce", + "Stops running containers, copies your data, and starts them again.": "Ustavi delujoče vsebnike, kopira podatke in jih znova zažene.", + "Start fresh": "Začni na novo", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Začne prazno v novi mapi. Stara mapa ostane, dokler je ne odstranite.", + "Kiri will switch to this folder and restart the engine.": "Kiri bo preklopil na to mapo in znova zagnal pogon.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Delujoči vsebniki se bodo ustavili med premikanjem podatkov in se po koncu znova zagnali.", + "Move data": "Premakni podatke", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri bo preklopil nazaj na privzeto mapo in znova zagnal pogon. Podatki na odklopljenem disku se ne izbrišejo.", + "Remove old data?": "Odstranim stare podatke?", + "Everything in {path} will be deleted for good.": "Vse v {path} bo trajno izbrisano.", + "Choose a storage folder": "Izberite mapo za shrambo", + "Kiri's data is moving already": "Podatki Kiri se že premikajo", + "Kiri's data moved to {path}": "Podatki Kiri so bili premaknjeni v {path}", + "Storage is available again": "Shramba je spet na voljo", + "Old data removed": "Stari podatki odstranjeni" } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 268312399..25b73f65b 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1887,5 +1887,50 @@ "Switching…": "Duke ndërruar…", "{docker} command": "Komanda {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock tani tregon te Kiri", - "Could not link /var/run/docker.sock: {error}": "Nuk u lidh dot /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Nuk u lidh dot /var/run/docker.sock: {error}", + "Stopping containers…": "Duke ndalur kontejnerët…", + "Copying data…": "Duke kopjuar të dhënat…", + "Verifying copy…": "Duke verifikuar kopjen…", + "Switching storage…": "Duke ndërruar hapësirën…", + "Restarting engine…": "Duke rinisur motorin…", + "Moving data…": "Duke zhvendosur të dhënat…", + "Storage location unavailable": "Vendndodhja e ruajtjes nuk është e disponueshme", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri nuk i gjeti të dhënat e tij në {path}. Lidheni diskun dhe provoni përsëri, zgjidhni një dosje tjetër ose riktheni vendndodhjen e parazgjedhur.", + "Change…": "Ndrysho…", + "Reset to default": "Rikthe parazgjedhjen", + "Open storage settings": "Hap cilësimet e ruajtjes", + "Start Kiri to change its storage location. ({error})": "Nisni Kiri për të ndryshuar vendndodhjen e ruajtjes. ({error})", + "{size} used": "{size} përdorur", + "{size} free": "{size} të lira", + "Default": "Parazgjedhje", + "Moving Kiri's data to {path}.": "Duke zhvendosur të dhënat e Kiri në {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kontejnerët aktivë ndalen përkohësisht ndërsa Kiri kopjon të dhënat dhe rinisin sapo të përfundojë.", + "Couldn't change storage location": "Vendndodhja e ruajtjes nuk u ndryshua dot", + "Old data": "Të dhënat e vjetra", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Të dhënat e mëparshme janë ende në {path}. Hiqini pasi gjithçka të funksionojë në vendndodhjen e re.", + "Remove old data": "Hiq të dhënat e vjetra", + "Storage location": "Vendndodhja e ruajtjes", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} përcakton vendndodhjen e ruajtjes së Kiri, ndaj nuk mund të ndryshohet këtu.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Imazhet, kontejnerët dhe volumet ruhen në këtë dosje. Disqet e jashtme duhet të përdorin sistem skedarësh vendas (APFS në macOS, ext4/xfs/btrfs në Linux, NTFS në Windows); disqet FAT dhe exFAT nuk mbështeten.", + "Reset storage location to default?": "Ta riktheni vendndodhjen e ruajtjes në parazgjedhje?", + "Change storage location?": "Ta ndryshoni vendndodhjen e ruajtjes?", + "Destination: {path} ({free} free).": "Destinacioni: {path} ({free} të lira).", + "Destination: {path}.": "Destinacioni: {path}.", + "Existing Kiri data in this folder will be replaced.": "Të dhënat ekzistuese të Kiri në këtë dosje do të zëvendësohen.", + "Migration mode": "Mënyra e kalimit", + "Move existing images, containers, and volumes": "Zhvendos imazhet, kontejnerët dhe volumet ekzistuese", + "Stops running containers, copies your data, and starts them again.": "Ndal kontejnerët aktivë, kopjon të dhënat tuaja dhe i rinis ato.", + "Start fresh": "Fillo nga e para", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Fillon bosh në dosjen e re. Dosja e vjetër mbetet derisa ta hiqni.", + "Kiri will switch to this folder and restart the engine.": "Kiri do të kalojë në këtë dosje dhe do të rinisë motorin.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kontejnerët aktivë do të ndalen ndërsa Kiri zhvendos të dhënat tuaja dhe do të rinisin sapo të përfundojë.", + "Move data": "Zhvendos të dhënat", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri do të kthehet në dosjen e parazgjedhur dhe do të rinisë motorin. Të dhënat në diskun e shkëputur nuk fshihen.", + "Remove old data?": "Të hiqen të dhënat e vjetra?", + "Everything in {path} will be deleted for good.": "Gjithçka në {path} do të fshihet përgjithmonë.", + "Choose a storage folder": "Zgjidhni një dosje ruajtjeje", + "Kiri's data is moving already": "Të dhënat e Kiri po zhvendosen tashmë", + "Kiri's data moved to {path}": "Të dhënat e Kiri u zhvendosën në {path}", + "Storage is available again": "Ruajtja është sërish e disponueshme", + "Old data removed": "Të dhënat e vjetra u hoqën" } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index f50e3e8c1..10826cba2 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1887,5 +1887,50 @@ "Switching…": "மாற்றுகிறது…", "{docker} command": "{docker} கட்டளை", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock இப்போது Kiri ஐக் குறிக்கிறது", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ஐ இணைக்க முடியவில்லை: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ஐ இணைக்க முடியவில்லை: {error}", + "Stopping containers…": "கன்டெய்னர்களை நிறுத்துகிறது…", + "Copying data…": "தரவை நகலெடுக்கிறது…", + "Verifying copy…": "நகலைச் சரிபார்க்கிறது…", + "Switching storage…": "சேமிப்பகத்தை மாற்றுகிறது…", + "Restarting engine…": "இயந்திரத்தை மறுதொடக்கம் செய்கிறது…", + "Moving data…": "தரவை நகர்த்துகிறது…", + "Storage location unavailable": "சேமிப்பக இடம் கிடைக்கவில்லை", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "{path} இல் Kiri தனது தரவைக் கண்டறிய முடியவில்லை. இயக்ககத்தை இணைத்து மீண்டும் முயற்சிக்கவும், வேறு கோப்புறையைத் தேர்ந்தெடுக்கவும் அல்லது இயல்புநிலை இடத்திற்கு மீட்டமைக்கவும்.", + "Change…": "மாற்று…", + "Reset to default": "இயல்புநிலைக்கு மீட்டமை", + "Open storage settings": "சேமிப்பக அமைப்புகளைத் திற", + "Start Kiri to change its storage location. ({error})": "சேமிப்பக இடத்தை மாற்ற Kiri ஐத் தொடங்கவும். ({error})", + "{size} used": "{size} பயன்படுத்தப்பட்டது", + "{size} free": "{size} காலி", + "Default": "இயல்புநிலை", + "Moving Kiri's data to {path}.": "Kiri தரவை {path} க்கு நகர்த்துகிறது.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri தரவை நகலெடுக்கும்போது இயங்கும் கன்டெய்னர்கள் இடைநிறுத்தப்பட்டு, முடிந்ததும் மீண்டும் தொடங்கும்.", + "Couldn't change storage location": "சேமிப்பக இடத்தை மாற்ற முடியவில்லை", + "Old data": "பழைய தரவு", + "Previous data is still in {path}. Remove it once everything works in the new location.": "முந்தைய தரவு இன்னும் {path} இல் உள்ளது. புதிய இடத்தில் எல்லாம் வேலை செய்ததும் அதை அகற்றவும்.", + "Remove old data": "பழைய தரவை அகற்று", + "Storage location": "சேமிப்பக இடம்", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri இன் சேமிப்பக இடத்தை அமைக்கிறது, எனவே இதை இங்கே மாற்ற முடியாது.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "படங்கள், கன்டெய்னர்கள் மற்றும் வால்யூம்கள் இந்தக் கோப்புறையில் இருக்கும். வெளிப்புற இயக்ககங்கள் சொந்த கோப்பு முறைமையைப் பயன்படுத்த வேண்டும் (macOS இல் APFS, Linux இல் ext4/xfs/btrfs, Windows இல் NTFS); FAT மற்றும் exFAT இயக்ககங்கள் ஆதரிக்கப்படவில்லை.", + "Reset storage location to default?": "சேமிப்பக இடத்தை இயல்புநிலைக்கு மீட்டமைக்கவா?", + "Change storage location?": "சேமிப்பக இடத்தை மாற்றவா?", + "Destination: {path} ({free} free).": "இலக்கு: {path} ({free} காலி).", + "Destination: {path}.": "இலக்கு: {path}.", + "Existing Kiri data in this folder will be replaced.": "இந்தக் கோப்புறையில் உள்ள ஏற்கனவே உள்ள Kiri தரவு மாற்றப்படும்.", + "Migration mode": "இடமாற்ற முறை", + "Move existing images, containers, and volumes": "ஏற்கனவே உள்ள படங்கள், கன்டெய்னர்கள் மற்றும் வால்யூம்களை நகர்த்து", + "Stops running containers, copies your data, and starts them again.": "இயங்கும் கன்டெய்னர்களை நிறுத்தி, உங்கள் தரவை நகலெடுத்து, மீண்டும் தொடங்கும்.", + "Start fresh": "புதிதாகத் தொடங்கு", + "Starts empty in the new folder. Your old folder stays until you remove it.": "புதிய கோப்புறையில் காலியாகத் தொடங்கும். நீங்கள் அகற்றும் வரை பழைய கோப்புறை இருக்கும்.", + "Kiri will switch to this folder and restart the engine.": "Kiri இந்தக் கோப்புறைக்கு மாறி இயந்திரத்தை மறுதொடக்கம் செய்யும்.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri உங்கள் தரவை நகர்த்தும்போது இயங்கும் கன்டெய்னர்கள் நின்று, முடிந்ததும் மீண்டும் தொடங்கும்.", + "Move data": "தரவை நகர்த்து", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri தனது இயல்புநிலை கோப்புறைக்குத் திரும்பி இயந்திரத்தை மறுதொடக்கம் செய்யும். துண்டிக்கப்பட்ட இயக்ககத்தின் தரவு நீக்கப்படாது.", + "Remove old data?": "பழைய தரவை அகற்றவா?", + "Everything in {path} will be deleted for good.": "{path} இல் உள்ள அனைத்தும் நிரந்தரமாக நீக்கப்படும்.", + "Choose a storage folder": "சேமிப்பகக் கோப்புறையைத் தேர்ந்தெடுக்கவும்", + "Kiri's data is moving already": "Kiri தரவு ஏற்கனவே நகர்த்தப்படுகிறது", + "Kiri's data moved to {path}": "Kiri தரவு {path} க்கு நகர்த்தப்பட்டது", + "Storage is available again": "சேமிப்பகம் மீண்டும் கிடைக்கிறது", + "Old data removed": "பழைய தரவு அகற்றப்பட்டது" } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 822d1f51a..ee5e29b91 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1887,5 +1887,50 @@ "Switching…": "మారుతోంది…", "{docker} command": "{docker} ఆదేశం", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ఇప్పుడు Kiri కు చూపుతోంది", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ను లింక్ చేయడం సాధ్యం కాలేదు: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock ను లింక్ చేయడం సాధ్యం కాలేదు: {error}", + "Stopping containers…": "కంటైనర్లను ఆపుతోంది…", + "Copying data…": "డేటాను కాపీ చేస్తోంది…", + "Verifying copy…": "కాపీని ధృవీకరిస్తోంది…", + "Switching storage…": "స్టోరేజీని మారుస్తోంది…", + "Restarting engine…": "ఇంజిన్‌ను పునఃప్రారంభిస్తోంది…", + "Moving data…": "డేటాను తరలిస్తోంది…", + "Storage location unavailable": "స్టోరేజీ స్థానం అందుబాటులో లేదు", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "{path} లో Kiri తన డేటాను కనుగొనలేకపోయింది. డ్రైవ్‌ను కనెక్ట్ చేసి మళ్ళీ ప్రయత్నించండి, మరో ఫోల్డర్‌ను ఎంచుకోండి లేదా డిఫాల్ట్ స్థానానికి రీసెట్ చేయండి.", + "Change…": "మార్చు…", + "Reset to default": "డిఫాల్ట్‌కు రీసెట్ చేయి", + "Open storage settings": "స్టోరేజీ సెట్టింగ్‌లను తెరువు", + "Start Kiri to change its storage location. ({error})": "స్టోరేజీ స్థానాన్ని మార్చడానికి Kiriని ప్రారంభించండి. ({error})", + "{size} used": "{size} వినియోగించబడింది", + "{size} free": "{size} ఖాళీ", + "Default": "డిఫాల్ట్", + "Moving Kiri's data to {path}.": "Kiri డేటాను {path} కు తరలిస్తోంది.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri డేటాను కాపీ చేస్తున్నప్పుడు నడుస్తున్న కంటైనర్లు ఆగిపోయి, పూర్తయిన తర్వాత మళ్ళీ ప్రారంభమవుతాయి.", + "Couldn't change storage location": "స్టోరేజీ స్థానాన్ని మార్చడం సాధ్యం కాలేదు", + "Old data": "పాత డేటా", + "Previous data is still in {path}. Remove it once everything works in the new location.": "మునుపటి డేటా ఇంకా {path} లో ఉంది. కొత్త స్థానంలో అంతా పనిచేసిన తర్వాత దాన్ని తొలగించండి.", + "Remove old data": "పాత డేటాను తొలగించు", + "Storage location": "స్టోరేజీ స్థానం", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri స్టోరేజీ స్థానాన్ని సెట్ చేస్తుంది, కాబట్టి ఇక్కడ మార్చడం సాధ్యం కాదు.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "ఇమేజ్‌లు, కంటైనర్లు మరియు వాల్యూమ్‌లు ఈ ఫోల్డర్‌లో ఉంటాయి. బాహ్య డ్రైవ్‌లు స్థానిక ఫైల్‌సిస్టమ్‌ను ఉపయోగించాలి (macOSలో APFS, Linuxలో ext4/xfs/btrfs, Windowsలో NTFS); FAT మరియు exFAT డ్రైవ్‌లకు మద్దతు లేదు.", + "Reset storage location to default?": "స్టోరేజీ స్థానాన్ని డిఫాల్ట్‌కు రీసెట్ చేయాలా?", + "Change storage location?": "స్టోరేజీ స్థానాన్ని మార్చాలా?", + "Destination: {path} ({free} free).": "గమ్యస్థానం: {path} ({free} ఖాళీ).", + "Destination: {path}.": "గమ్యస్థానం: {path}.", + "Existing Kiri data in this folder will be replaced.": "ఈ ఫోల్డర్‌లో ఉన్న Kiri డేటా భర్తీ చేయబడుతుంది.", + "Migration mode": "తరలింపు విధానం", + "Move existing images, containers, and volumes": "ఉన్న ఇమేజ్‌లు, కంటైనర్లు మరియు వాల్యూమ్‌లను తరలించు", + "Stops running containers, copies your data, and starts them again.": "నడుస్తున్న కంటైనర్లను ఆపి, మీ డేటాను కాపీ చేసి, వాటిని మళ్ళీ ప్రారంభిస్తుంది.", + "Start fresh": "కొత్తగా ప్రారంభించు", + "Starts empty in the new folder. Your old folder stays until you remove it.": "కొత్త ఫోల్డర్‌లో ఖాళీగా ప్రారంభమవుతుంది. మీరు తొలగించే వరకు పాత ఫోల్డర్ ఉంటుంది.", + "Kiri will switch to this folder and restart the engine.": "Kiri ఈ ఫోల్డర్‌కు మారి ఇంజిన్‌ను పునఃప్రారంభిస్తుంది.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri మీ డేటాను తరలిస్తున్నప్పుడు నడుస్తున్న కంటైనర్లు ఆగి, పూర్తయిన తర్వాత మళ్ళీ ప్రారంభమవుతాయి.", + "Move data": "డేటాను తరలించు", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri డిఫాల్ట్ ఫోల్డర్‌కు తిరిగి మారి ఇంజిన్‌ను పునఃప్రారంభిస్తుంది. డిస్కనెక్ట్ అయిన డ్రైవ్‌లోని డేటా తొలగించబడదు.", + "Remove old data?": "పాత డేటాను తొలగించాలా?", + "Everything in {path} will be deleted for good.": "{path} లోని ప్రతిదీ శాశ్వతంగా తొలగించబడుతుంది.", + "Choose a storage folder": "స్టోరేజీ ఫోల్డర్‌ను ఎంచుకోండి", + "Kiri's data is moving already": "Kiri డేటా ఇప్పటికే తరలించబడుతోంది", + "Kiri's data moved to {path}": "Kiri డేటా {path} కు తరలించబడింది", + "Storage is available again": "స్టోరేజీ మళ్ళీ అందుబాటులో ఉంది", + "Old data removed": "పాత డేటా తొలగించబడింది" } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index 9dd3e0551..ae2638dc8 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1887,5 +1887,50 @@ "Switching…": "กำลังสลับ…", "{docker} command": "คำสั่ง {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock ชี้ไปที่ Kiri แล้ว", - "Could not link /var/run/docker.sock: {error}": "ไม่สามารถลิงก์ /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "ไม่สามารถลิงก์ /var/run/docker.sock: {error}", + "Stopping containers…": "กำลังหยุดคอนเทนเนอร์…", + "Copying data…": "กำลังคัดลอกข้อมูล…", + "Verifying copy…": "กำลังตรวจสอบสำเนา…", + "Switching storage…": "กำลังสลับที่เก็บข้อมูล…", + "Restarting engine…": "กำลังรีสตาร์ตเอนจิน…", + "Moving data…": "กำลังย้ายข้อมูล…", + "Storage location unavailable": "ไม่สามารถเข้าถึงตำแหน่งที่เก็บข้อมูลได้", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ไม่พบข้อมูลใน {path} เชื่อมต่อไดรฟ์แล้วลองใหม่ เลือกโฟลเดอร์อื่น หรือรีเซ็ตเป็นตำแหน่งเริ่มต้น", + "Change…": "เปลี่ยน…", + "Reset to default": "รีเซ็ตเป็นค่าเริ่มต้น", + "Open storage settings": "เปิดการตั้งค่าที่เก็บข้อมูล", + "Start Kiri to change its storage location. ({error})": "เริ่ม Kiri เพื่อเปลี่ยนตำแหน่งที่เก็บข้อมูล ({error})", + "{size} used": "ใช้ไป {size}", + "{size} free": "ว่าง {size}", + "Default": "ค่าเริ่มต้น", + "Moving Kiri's data to {path}.": "กำลังย้ายข้อมูลของ Kiri ไปยัง {path}", + "Running containers pause while Kiri copies its data and start again once it's done.": "คอนเทนเนอร์ที่ทำงานอยู่จะหยุดชั่วคราวระหว่างที่ Kiri คัดลอกข้อมูล และจะเริ่มใหม่เมื่อเสร็จสิ้น", + "Couldn't change storage location": "ไม่สามารถเปลี่ยนตำแหน่งที่เก็บข้อมูลได้", + "Old data": "ข้อมูลเก่า", + "Previous data is still in {path}. Remove it once everything works in the new location.": "ข้อมูลเดิมยังอยู่ใน {path} ลบออกได้เมื่อทุกอย่างทำงานปกติในตำแหน่งใหม่แล้ว", + "Remove old data": "ลบข้อมูลเก่า", + "Storage location": "ตำแหน่งที่เก็บข้อมูล", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} กำหนดตำแหน่งที่เก็บข้อมูลของ Kiri จึงไม่สามารถเปลี่ยนที่นี่ได้", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "อิมเมจ คอนเทนเนอร์ และโวลุ่มจะเก็บไว้ในโฟลเดอร์นี้ ไดรฟ์ภายนอกต้องใช้ระบบไฟล์เนทีฟ (APFS บน macOS, ext4/xfs/btrfs บน Linux, NTFS บน Windows) ไม่รองรับไดรฟ์ FAT และ exFAT", + "Reset storage location to default?": "รีเซ็ตตำแหน่งที่เก็บข้อมูลเป็นค่าเริ่มต้นหรือไม่", + "Change storage location?": "เปลี่ยนตำแหน่งที่เก็บข้อมูลหรือไม่", + "Destination: {path} ({free} free).": "ปลายทาง: {path} (ว่าง {free})", + "Destination: {path}.": "ปลายทาง: {path}", + "Existing Kiri data in this folder will be replaced.": "ข้อมูล Kiri ที่มีอยู่เดิมในโฟลเดอร์นี้จะถูกแทนที่", + "Migration mode": "โหมดการย้าย", + "Move existing images, containers, and volumes": "ย้ายอิมเมจ คอนเทนเนอร์ และโวลุ่มที่มีอยู่", + "Stops running containers, copies your data, and starts them again.": "หยุดคอนเทนเนอร์ที่ทำงานอยู่ คัดลอกข้อมูลของคุณ แล้วเริ่มใหม่", + "Start fresh": "เริ่มต้นใหม่", + "Starts empty in the new folder. Your old folder stays until you remove it.": "เริ่มใหม่แบบว่างในโฟลเดอร์ใหม่ โฟลเดอร์เก่าจะยังคงอยู่จนกว่าคุณจะลบออก", + "Kiri will switch to this folder and restart the engine.": "Kiri จะสลับไปยังโฟลเดอร์นี้และรีสตาร์ตเอนจิน", + "Running containers will stop while Kiri moves your data and start again once it's done.": "คอนเทนเนอร์ที่ทำงานอยู่จะหยุดระหว่างที่ Kiri ย้ายข้อมูล และจะเริ่มใหม่เมื่อเสร็จสิ้น", + "Move data": "ย้ายข้อมูล", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri จะสลับกลับไปยังโฟลเดอร์เริ่มต้นและรีสตาร์ตเอนจิน ข้อมูลบนไดรฟ์ที่ถอดออกจะไม่ถูกลบ", + "Remove old data?": "ลบข้อมูลเก่าหรือไม่", + "Everything in {path} will be deleted for good.": "ทุกอย่างใน {path} จะถูกลบอย่างถาวร", + "Choose a storage folder": "เลือกโฟลเดอร์ที่เก็บข้อมูล", + "Kiri's data is moving already": "กำลังย้ายข้อมูลของ Kiri อยู่แล้ว", + "Kiri's data moved to {path}": "ย้ายข้อมูลของ Kiri ไปยัง {path} แล้ว", + "Storage is available again": "ที่เก็บข้อมูลพร้อมใช้งานอีกครั้ง", + "Old data removed": "ลบข้อมูลเก่าแล้ว" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index ed196364e..8d47511a9 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1887,5 +1887,50 @@ "Switching…": "Geçiliyor…", "{docker} command": "{docker} komutu", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock artık Kiri’yi gösteriyor", - "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock bağlanamadı: {error}" + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock bağlanamadı: {error}", + "Stopping containers…": "Konteynerler durduruluyor…", + "Copying data…": "Veriler kopyalanıyor…", + "Verifying copy…": "Kopya doğrulanıyor…", + "Switching storage…": "Depolama değiştiriliyor…", + "Restarting engine…": "Motor yeniden başlatılıyor…", + "Moving data…": "Veriler taşınıyor…", + "Storage location unavailable": "Depolama konumu kullanılamıyor", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri verilerini {path} konumunda bulamadı. Sürücüyü bağlayıp yeniden deneyin, başka bir klasör seçin veya varsayılan konuma sıfırlayın.", + "Change…": "Değiştir…", + "Reset to default": "Varsayılana sıfırla", + "Open storage settings": "Depolama ayarlarını aç", + "Start Kiri to change its storage location. ({error})": "Depolama konumunu değiştirmek için Kiri'yi başlatın. ({error})", + "{size} used": "{size} kullanıldı", + "{size} free": "{size} boş", + "Default": "Varsayılan", + "Moving Kiri's data to {path}.": "Kiri verileri {path} konumuna taşınıyor.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri verilerini kopyalarken çalışan konteynerler duraklatılır ve işlem bittiğinde yeniden başlatılır.", + "Couldn't change storage location": "Depolama konumu değiştirilemedi", + "Old data": "Eski veriler", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Önceki veriler hâlâ {path} konumunda. Yeni konumda her şey çalıştıktan sonra kaldırabilirsiniz.", + "Remove old data": "Eski verileri kaldır", + "Storage location": "Depolama konumu", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var}, Kiri'nin depolama konumunu belirlediğinden burada değiştirilemez.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "İmajlar, konteynerler ve birimler bu klasörde bulunur. Harici sürücüler yerel bir dosya sistemi kullanmalıdır (macOS'te APFS, Linux'ta ext4/xfs/btrfs, Windows'ta NTFS); FAT ve exFAT sürücüleri desteklenmez.", + "Reset storage location to default?": "Depolama konumu varsayılana sıfırlansın mı?", + "Change storage location?": "Depolama konumu değiştirilsin mi?", + "Destination: {path} ({free} free).": "Hedef: {path} ({free} boş).", + "Destination: {path}.": "Hedef: {path}.", + "Existing Kiri data in this folder will be replaced.": "Bu klasördeki mevcut Kiri verileri değiştirilecektir.", + "Migration mode": "Taşıma modu", + "Move existing images, containers, and volumes": "Mevcut imajları, konteynerleri ve birimleri taşı", + "Stops running containers, copies your data, and starts them again.": "Çalışan konteynerleri durdurur, verilerinizi kopyalar ve yeniden başlatır.", + "Start fresh": "Sıfırdan başla", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Yeni klasörde boş olarak başlar. Eski klasörünüz siz kaldırana kadar kalır.", + "Kiri will switch to this folder and restart the engine.": "Kiri bu klasöre geçecek ve motoru yeniden başlatacaktır.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri verilerinizi taşırken çalışan konteynerler durdurulur ve işlem bittiğinde yeniden başlatılır.", + "Move data": "Verileri taşı", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri varsayılan klasöre dönecek ve motoru yeniden başlatacaktır. Bağlı olmayan sürücüdeki veriler silinmez.", + "Remove old data?": "Eski veriler kaldırılsın mı?", + "Everything in {path} will be deleted for good.": "{path} konumundaki her şey kalıcı olarak silinecek.", + "Choose a storage folder": "Depolama klasörü seçin", + "Kiri's data is moving already": "Kiri verileri zaten taşınıyor", + "Kiri's data moved to {path}": "Kiri verileri {path} konumuna taşındı", + "Storage is available again": "Depolama yeniden kullanılabilir", + "Old data removed": "Eski veriler kaldırıldı" } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 3b9ece504..43b7f5f05 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1887,5 +1887,50 @@ "Switching…": "Перемикання…", "{docker} command": "Команда {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock тепер вказує на Kiri", - "Could not link /var/run/docker.sock: {error}": "Не вдалося зв’язати /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Не вдалося зв’язати /var/run/docker.sock: {error}", + "Stopping containers…": "Зупинення контейнерів…", + "Copying data…": "Копіювання даних…", + "Verifying copy…": "Перевірка копії…", + "Switching storage…": "Перемикання сховища…", + "Restarting engine…": "Перезапуск рушія…", + "Moving data…": "Перенесення даних…", + "Storage location unavailable": "Розташування сховища недоступне", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri не знайшов свої дані в {path}. Під'єднайте диск і повторіть спробу, виберіть іншу теку або скиньте до типового розташування.", + "Change…": "Змінити…", + "Reset to default": "Скинути до типового", + "Open storage settings": "Відкрити налаштування сховища", + "Start Kiri to change its storage location. ({error})": "Запустіть Kiri, щоб змінити розташування сховища. ({error})", + "{size} used": "Зайнято {size}", + "{size} free": "Вільно {size}", + "Default": "Типово", + "Moving Kiri's data to {path}.": "Перенесення даних Kiri до {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Запущені контейнери призупиняються на час копіювання та запускаються знову після завершення.", + "Couldn't change storage location": "Не вдалося змінити розташування сховища", + "Old data": "Старі дані", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Попередні дані все ще в {path}. Видаліть їх, коли переконаєтеся, що в новому місці все працює.", + "Remove old data": "Видалити старі дані", + "Storage location": "Розташування сховища", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} задає розташування сховища Kiri, тому тут його змінити не можна.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Образи, контейнери та томи зберігаються в цій теці. Зовнішні диски мають використовувати нативну файлову систему (APFS у macOS, ext4/xfs/btrfs у Linux, NTFS у Windows); диски FAT і exFAT не підтримуються.", + "Reset storage location to default?": "Скинути розташування сховища до типового?", + "Change storage location?": "Змінити розташування сховища?", + "Destination: {path} ({free} free).": "Призначення: {path} (вільно {free}).", + "Destination: {path}.": "Призначення: {path}.", + "Existing Kiri data in this folder will be replaced.": "Наявні дані Kiri в цій теці буде замінено.", + "Migration mode": "Режим перенесення", + "Move existing images, containers, and volumes": "Перенести наявні образи, контейнери та томи", + "Stops running containers, copies your data, and starts them again.": "Зупиняє запущені контейнери, копіює ваші дані та запускає їх знову.", + "Start fresh": "Почати з нуля", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Починає порожнім у новій теці. Стара тека залишиться, доки ви її не видалите.", + "Kiri will switch to this folder and restart the engine.": "Kiri перемкнеться на цю теку та перезапустить рушій.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Запущені контейнери зупиняться на час перенесення та запустяться знову після завершення.", + "Move data": "Перенести дані", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri повернеться до типової теки та перезапустить рушій. Дані на від'єднаному диску не видаляються.", + "Remove old data?": "Видалити старі дані?", + "Everything in {path} will be deleted for good.": "Усе в {path} буде видалено назавжди.", + "Choose a storage folder": "Виберіть теку сховища", + "Kiri's data is moving already": "Дані Kiri вже переносяться", + "Kiri's data moved to {path}": "Дані Kiri перенесено до {path}", + "Storage is available again": "Сховище знову доступне", + "Old data removed": "Старі дані видалено" } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index d7d659dd6..01da876c4 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1887,5 +1887,50 @@ "Switching…": "Đang chuyển…", "{docker} command": "Lệnh {docker}", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock hiện trỏ tới Kiri", - "Could not link /var/run/docker.sock: {error}": "Không thể liên kết /var/run/docker.sock: {error}" + "Could not link /var/run/docker.sock: {error}": "Không thể liên kết /var/run/docker.sock: {error}", + "Stopping containers…": "Đang dừng các container…", + "Copying data…": "Đang sao chép dữ liệu…", + "Verifying copy…": "Đang xác minh bản sao…", + "Switching storage…": "Đang chuyển đổi lưu trữ…", + "Restarting engine…": "Đang khởi động lại động cơ…", + "Moving data…": "Đang di chuyển dữ liệu…", + "Storage location unavailable": "Vị trí lưu trữ không khả dụng", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri không tìm thấy dữ liệu của mình tại {path}. Hãy kết nối ổ đĩa rồi thử lại, chọn thư mục khác hoặc đặt lại về vị trí mặc định.", + "Change…": "Thay đổi…", + "Reset to default": "Đặt lại mặc định", + "Open storage settings": "Mở cài đặt lưu trữ", + "Start Kiri to change its storage location. ({error})": "Khởi động Kiri để thay đổi vị trí lưu trữ. ({error})", + "{size} used": "Đã dùng {size}", + "{size} free": "Còn trống {size}", + "Default": "Mặc định", + "Moving Kiri's data to {path}.": "Đang di chuyển dữ liệu Kiri đến {path}.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Các container đang chạy sẽ tạm dừng khi Kiri sao chép dữ liệu và chạy lại sau khi hoàn tất.", + "Couldn't change storage location": "Không thể thay đổi vị trí lưu trữ", + "Old data": "Dữ liệu cũ", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Dữ liệu trước đó vẫn nằm tại {path}. Hãy xóa khi mọi thứ hoạt động ổn định ở vị trí mới.", + "Remove old data": "Xóa dữ liệu cũ", + "Storage location": "Vị trí lưu trữ", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} đặt vị trí lưu trữ của Kiri nên không thể thay đổi tại đây.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Image, container và volume nằm trong thư mục này. Ổ đĩa ngoài phải dùng hệ thống tệp gốc (APFS trên macOS, ext4/xfs/btrfs trên Linux, NTFS trên Windows); ổ FAT và exFAT không được hỗ trợ.", + "Reset storage location to default?": "Đặt lại vị trí lưu trữ về mặc định?", + "Change storage location?": "Thay đổi vị trí lưu trữ?", + "Destination: {path} ({free} free).": "Đích: {path} (còn trống {free}).", + "Destination: {path}.": "Đích: {path}.", + "Existing Kiri data in this folder will be replaced.": "Dữ liệu Kiri hiện có trong thư mục này sẽ bị thay thế.", + "Migration mode": "Chế độ di chuyển", + "Move existing images, containers, and volumes": "Di chuyển image, container và volume hiện có", + "Stops running containers, copies your data, and starts them again.": "Dừng các container đang chạy, sao chép dữ liệu và khởi động lại chúng.", + "Start fresh": "Bắt đầu mới", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Bắt đầu trống trong thư mục mới. Thư mục cũ vẫn giữ nguyên cho đến khi bạn xóa.", + "Kiri will switch to this folder and restart the engine.": "Kiri sẽ chuyển sang thư mục này và khởi động lại động cơ.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Các container đang chạy sẽ dừng trong khi Kiri di chuyển dữ liệu và chạy lại sau khi hoàn tất.", + "Move data": "Di chuyển dữ liệu", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri sẽ quay về thư mục mặc định và khởi động lại động cơ. Dữ liệu trên ổ đĩa đã ngắt kết nối sẽ không bị xóa.", + "Remove old data?": "Xóa dữ liệu cũ?", + "Everything in {path} will be deleted for good.": "Mọi thứ trong {path} sẽ bị xóa vĩnh viễn.", + "Choose a storage folder": "Chọn thư mục lưu trữ", + "Kiri's data is moving already": "Dữ liệu Kiri đang được di chuyển", + "Kiri's data moved to {path}": "Đã di chuyển dữ liệu Kiri đến {path}", + "Storage is available again": "Lưu trữ đã khả dụng trở lại", + "Old data removed": "Đã xóa dữ liệu cũ" } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index ef975a9ca..e7f40070f 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1887,5 +1887,50 @@ "Switching…": "正在切换…", "{docker} command": "{docker} 命令", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock 现已指向 Kiri", - "Could not link /var/run/docker.sock: {error}": "无法链接 /var/run/docker.sock:{error}" + "Could not link /var/run/docker.sock: {error}": "无法链接 /var/run/docker.sock:{error}", + "Stopping containers…": "正在停止容器…", + "Copying data…": "正在复制数据…", + "Verifying copy…": "正在校验副本…", + "Switching storage…": "正在切换存储…", + "Restarting engine…": "正在重启引擎…", + "Moving data…": "正在移动数据…", + "Storage location unavailable": "存储位置不可用", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri 在 {path} 中找不到数据。请连接该磁盘后重试、选择其他文件夹,或重置为默认位置。", + "Change…": "更改…", + "Reset to default": "恢复默认", + "Open storage settings": "打开存储设置", + "Start Kiri to change its storage location. ({error})": "请先启动 Kiri 再更改存储位置。({error})", + "{size} used": "已用 {size}", + "{size} free": "可用 {size}", + "Default": "默认", + "Moving Kiri's data to {path}.": "正在将 Kiri 的数据移动到 {path}。", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri 复制数据时,运行中的容器会暂停,完成后自动重新启动。", + "Couldn't change storage location": "无法更改存储位置", + "Old data": "旧数据", + "Previous data is still in {path}. Remove it once everything works in the new location.": "之前的数据仍在 {path} 中。确认新位置一切正常后再将其删除。", + "Remove old data": "删除旧数据", + "Storage location": "存储位置", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} 指定了 Kiri 的存储位置,因此无法在此更改。", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "镜像、容器和卷均保存在此文件夹中。外置硬盘必须使用原生文件系统(macOS 为 APFS,Linux 为 ext4/xfs/btrfs,Windows 为 NTFS);不支持 FAT 和 exFAT 硬盘。", + "Reset storage location to default?": "要将存储位置恢复为默认吗?", + "Change storage location?": "要更改存储位置吗?", + "Destination: {path} ({free} free).": "目标:{path}(可用 {free})。", + "Destination: {path}.": "目标:{path}。", + "Existing Kiri data in this folder will be replaced.": "此文件夹中已有的 Kiri 数据将被替换。", + "Migration mode": "迁移方式", + "Move existing images, containers, and volumes": "移动现有镜像、容器和卷", + "Stops running containers, copies your data, and starts them again.": "停止运行中的容器,复制数据并重新启动它们。", + "Start fresh": "全新开始", + "Starts empty in the new folder. Your old folder stays until you remove it.": "在新文件夹中从空状态开始。旧文件夹会保留,直到你将其删除。", + "Kiri will switch to this folder and restart the engine.": "Kiri 将切换到此文件夹并重启引擎。", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri 移动数据时,运行中的容器会停止,完成后自动重新启动。", + "Move data": "移动数据", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri 将切回默认文件夹并重启引擎。已断开磁盘上的数据不会被删除。", + "Remove old data?": "要删除旧数据吗?", + "Everything in {path} will be deleted for good.": "{path} 中的所有内容将被永久删除。", + "Choose a storage folder": "选择存储文件夹", + "Kiri's data is moving already": "Kiri 的数据已在移动中", + "Kiri's data moved to {path}": "Kiri 的数据已移动到 {path}", + "Storage is available again": "存储已重新可用", + "Old data removed": "旧数据已删除" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 36635b9f3..283c4763f 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1887,5 +1887,50 @@ "Switching…": "正在切換…", "{docker} command": "{docker} 指令", "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock 現已指向 Kiri", - "Could not link /var/run/docker.sock: {error}": "無法連結 /var/run/docker.sock:{error}" + "Could not link /var/run/docker.sock: {error}": "無法連結 /var/run/docker.sock:{error}", + "Stopping containers…": "正在停止容器…", + "Copying data…": "正在複製資料…", + "Verifying copy…": "正在驗證複本…", + "Switching storage…": "正在切換儲存位置…", + "Restarting engine…": "正在重新啟動引擎…", + "Moving data…": "正在移動資料…", + "Storage location unavailable": "儲存位置無法使用", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri 在 {path} 中找不到資料。請連接該磁碟並重試、選擇其他資料夾,或重設為預設位置。", + "Change…": "變更…", + "Reset to default": "重設為預設值", + "Open storage settings": "開啟儲存設定", + "Start Kiri to change its storage location. ({error})": "請先啟動 Kiri 再變更儲存位置。({error})", + "{size} used": "已使用 {size}", + "{size} free": "可用 {size}", + "Default": "預設", + "Moving Kiri's data to {path}.": "正在將 Kiri 的資料移動到 {path}。", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri 複製資料時,執行中的容器會暫停,完成後自動重新啟動。", + "Couldn't change storage location": "無法變更儲存位置", + "Old data": "舊資料", + "Previous data is still in {path}. Remove it once everything works in the new location.": "先前的資料仍在 {path} 中。確認新位置一切正常後再將其移除。", + "Remove old data": "移除舊資料", + "Storage location": "儲存位置", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} 設定了 Kiri 的儲存位置,因此無法在此變更。", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "映像檔、容器和磁碟區皆儲存在此資料夾中。外接硬碟必須使用原生檔案系統(macOS 為 APFS、Linux 為 ext4/xfs/btrfs、Windows 為 NTFS);不支援 FAT 與 exFAT 硬碟。", + "Reset storage location to default?": "要將儲存位置重設為預設值嗎?", + "Change storage location?": "要變更儲存位置嗎?", + "Destination: {path} ({free} free).": "目標:{path}(可用 {free})。", + "Destination: {path}.": "目標:{path}。", + "Existing Kiri data in this folder will be replaced.": "此資料夾中現有的 Kiri 資料將會被取代。", + "Migration mode": "移轉模式", + "Move existing images, containers, and volumes": "移動現有的映像檔、容器和磁碟區", + "Stops running containers, copies your data, and starts them again.": "停止執行中的容器、複製您的資料並重新啟動它們。", + "Start fresh": "全新開始", + "Starts empty in the new folder. Your old folder stays until you remove it.": "在新資料夾中以空白狀態開始。舊資料夾會保留,直到您將其移除。", + "Kiri will switch to this folder and restart the engine.": "Kiri 將切換到此資料夾並重新啟動引擎。", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri 移動資料時,執行中的容器會停止,完成後自動重新啟動。", + "Move data": "移動資料", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri 將切回預設資料夾並重新啟動引擎。已中斷連接磁碟上的資料不會被刪除。", + "Remove old data?": "要移除舊資料嗎?", + "Everything in {path} will be deleted for good.": "{path} 中的所有內容將會永久刪除。", + "Choose a storage folder": "選擇儲存資料夾", + "Kiri's data is moving already": "Kiri 的資料已在移動中", + "Kiri's data moved to {path}": "Kiri 的資料已移動到 {path}", + "Storage is available again": "儲存位置已恢復可用", + "Old data removed": "舊資料已移除" } diff --git a/crates/kiri/src/ui/mac.rs b/crates/kiri/src/ui/mac.rs index 4f601b3a0..fc4694a16 100644 --- a/crates/kiri/src/ui/mac.rs +++ b/crates/kiri/src/ui/mac.rs @@ -511,6 +511,34 @@ pub(super) fn pick_compose_file(title: &str, _filters: &[String; 2], done: impl }); } +/// Settings → Storage → Change…: AppKit's open panel for choosing a folder +/// (with New Folder enabled). `done` gets the path, or None when cancelled. +pub(super) fn pick_folder(title: &str, done: impl FnOnce(Option) + Send + 'static) { + let title = title.to_owned(); + DispatchQueue::main().exec_async(move || { + // SAFETY: on the main thread (main queue); NSOpenPanel's documented + // messages, with the argument types AppKit declares. + let picked = (|| unsafe { + let panel: Retained = msg_send![objc2::class!(NSOpenPanel), openPanel]; + let _: () = msg_send![&*panel, setCanChooseFiles: false]; + let _: () = msg_send![&*panel, setCanChooseDirectories: true]; + let _: () = msg_send![&*panel, setCanCreateDirectories: true]; + let _: () = msg_send![&*panel, setAllowsMultipleSelection: false]; + let words = NSString::from_str(&title); + let _: () = msg_send![&*panel, setTitle: &*words]; + let _: () = msg_send![&*panel, setMessage: &*words]; + let answer: isize = msg_send![&*panel, runModal]; + if answer != 1 { + return None; + } + let url: Option> = msg_send![&*panel, URL]; + let path: Option> = msg_send![&*url?, path]; + Some(std::path::PathBuf::from(path?.to_string())) + })(); + done(picked); + }); +} + /// The installed font families, sorted; `mono` keeps the fixed-pitch ones. pub(super) fn font_families(mono: bool) -> Vec { use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType}; diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index dff5721c4..b37ade196 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -733,6 +733,162 @@ fn router_ports(set: Option) { emit(v.to_string()); } +/// Settings → Storage: reads current location, space, and migration state. +fn storage_status() { + match client::get_background("/kiri/storage") { + Ok(mut v) => { + v["type"] = "storage".into(); + emit(v.to_string()); + } + Err(e) => emit(serde_json::json!({"type": "storage", "error": e.to_string()}).to_string()), + } +} + +/// Validates a proposed storage folder and emits `storagecheck` to the page. +fn storage_check(path: Option, fresh: bool, reset: bool) { + let mut body = serde_json::json!({"fresh": fresh}); + if let Some(p) = path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + body["path"] = p.into(); + } + let shown_path = path.unwrap_or_default(); + let ev = match client::request("POST", "/kiri/storage/check", Some(&body)) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = "storagecheck".into(); + v["reset"] = reset.into(); + v + } + Ok(r) => serde_json::json!({"type": "storagecheck", "path": shown_path, "error": r.error(), "reset": reset}), + Err(e) => serde_json::json!({"type": "storagecheck", "path": shown_path, "error": e.to_string(), "reset": reset}), + }; + emit(ev.to_string()); +} + +/// Polls `GET /kiri/storage` until a move finishes (surviving the brief +/// socket gap while the daemon execs itself onto the new folder). +fn watch_storage_move(tx: Sender) { + let mut disconnected = 0u32; + for _ in 0..7200 { + std::thread::sleep(Duration::from_millis(400)); + match client::get_background("/kiri/storage") { + Ok(mut v) => { + disconnected = 0; + let state = v["state"].as_str().unwrap_or("").to_owned(); + let err = v["error"].as_str().map(str::to_owned); + let path = v["path"].as_str().unwrap_or("").to_owned(); + v["type"] = "storage".into(); + emit(v.to_string()); + if state != "moving" { + if let Some(e) = err { + emit(notice("error", &e)); + } else if state == "ok" && !path.is_empty() { + emit(notice("ok", &trf("Kiri's data moved to {path}", &[("path", &path)]))); + } + let _ = tx.send(Cmd::Refresh); + return; + } + } + Err(_) => { + disconnected += 1; + if disconnected > 75 { + storage_status(); + let _ = tx.send(Cmd::Refresh); + return; + } + } + } + } +} + +/// Starts moving Kiri's data to `path` (or back to default when None). +fn storage_move(path: Option, fresh: bool, tx: Sender) { + let mut body = serde_json::json!({"fresh": fresh}); + if let Some(p) = path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + body["path"] = p.into(); + } + match client::request("POST", "/kiri/storage", Some(&body)) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = "storage".into(); + emit(v.to_string()); + watch_storage_move(tx); + } + Ok(r) => { + emit(notice("error", &r.error())); + storage_status(); + } + Err(e) => { + emit(notice("error", &e.to_string())); + storage_status(); + } + } +} + +fn storage_reset(tx: Sender) { + match client::request("POST", "/kiri/storage/reset", None) { + Ok(r) if r.ok() => { + if r.status == 204 { + // Unavailable mode: daemon restarts on default folder. + watch_storage_move(tx); + } else { + let mut v = r.json(); + v["type"] = "storage".into(); + emit(v.to_string()); + watch_storage_move(tx); + } + } + Ok(r) => { + emit(notice("error", &r.error())); + storage_status(); + } + Err(e) => { + emit(notice("error", &e.to_string())); + storage_status(); + } + } +} + +fn storage_retry(tx: Sender) { + match client::request("POST", "/kiri/storage/retry", None) { + Ok(r) if r.ok() => { + for _ in 0..50 { + std::thread::sleep(Duration::from_millis(200)); + if let Ok(mut v) = client::get_background("/kiri/storage") + && v["state"] != "unavailable" + { + v["type"] = "storage".into(); + emit(v.to_string()); + emit(notice("ok", &tr("Storage is available again"))); + let _ = tx.send(Cmd::Refresh); + return; + } + } + storage_status(); + } + Ok(r) => { + emit(notice("error", &r.error())); + storage_status(); + } + Err(e) => { + emit(notice("error", &e.to_string())); + storage_status(); + } + } +} + +fn storage_remove_old() { + match client::request("DELETE", "/kiri/storage/old", None) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = "storage".into(); + emit(v.to_string()); + emit(notice("ok", &tr("Old data removed"))); + } + Ok(r) => emit(notice("error", &r.error())), + Err(e) => emit(notice("error", &e.to_string())), + } +} + /// Reads (or saves, then reads) the VM's CPUs and memory for Settings. fn resources(save: Option) { let saved = save.map(|body| client::request("POST", "/kiri/resources", Some(&body))); @@ -1287,6 +1443,13 @@ fn vm_panel(connected: &mut bool) { *connected = false; } emit(state("stopped", None)); + if client::alive() + && let Ok(mut v) = client::get_background("/kiri/storage") + && v["state"] == "unavailable" + { + v["type"] = "storage".into(); + emit(v.to_string()); + } } } } @@ -2245,6 +2408,47 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { std::thread::spawn(move || router_ports(Some(body))); Ok(()) } + // Settings → Storage: data directory location, validation, and moving. + "storage" => { + std::thread::spawn(storage_status); + Ok(()) + } + "storagepick" => { + window::pick_folder(&tr("Choose a storage folder"), |path| { + if let Some(p) = path { + std::thread::spawn(move || storage_check(Some(p.to_string_lossy().into_owned()), false, false)); + } + }); + Ok(()) + } + "storagecheck" => { + let path = (!msg.path.trim().is_empty()).then(|| msg.path.clone()); + let fresh = msg.value["fresh"] == true; + let reset = msg.value["reset"] == true; + std::thread::spawn(move || storage_check(path, fresh, reset)); + Ok(()) + } + "storagemove" => { + let path = (!msg.path.trim().is_empty()).then(|| msg.path.clone()); + let fresh = msg.value["fresh"] == true; + let tx = tx.clone(); + std::thread::spawn(move || storage_move(path, fresh, tx)); + Ok(()) + } + "storagereset" => { + let tx = tx.clone(); + std::thread::spawn(move || storage_reset(tx)); + Ok(()) + } + "storageretry" => { + let tx = tx.clone(); + std::thread::spawn(move || storage_retry(tx)); + Ok(()) + } + "storageremoveold" => { + std::thread::spawn(storage_remove_old); + Ok(()) + } // Settings → Resources. "resources" => { std::thread::spawn(|| resources(None)); @@ -2490,6 +2694,7 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { } emit(domains_event()); emit_docker_state(); + std::thread::spawn(storage_status); // A crash since the window last opened, for the page to // offer a report; crash files go if the person allowed it. std::thread::spawn(|| { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 4a6a82162..4137ec278 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 +### #355 Settings → Storage: move Kiri's data folder to another drive (unreleased) +- Fixes: #355 Custom storage directory (Settings → Storage location) +- Caused: none known +- Caused by: - +- Check: `tests/ui/storage-location.js` + ### #577 Network: show default Docker socket owner and accurate CLI binding across macOS, Linux, Windows, and Windows setup (unreleased) - Fixes: #577 Settings → Network: show who owns the default Docker socket (`/var/run/docker.sock` / `\\.\pipe\docker_engine`), offer to link it when free on macOS, and show `DOCKER_HOST` hint when another engine owns it; #369 report plain `docker` CLI binding accurately when another context or `DOCKER_HOST`/`DOCKER_CONTEXT` overrides Kiri, and apply "Make Kiri the default for docker" in Windows setup - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 348744553..8e2cce0b1 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -279,3 +279,4 @@ hostnet-dns-kiri #732 a --network host container asked the Mac's resolver for th socket-container-uid-group #127 a standalone root-run Linux daemon put its 0600 socket under /root/.kiri/run/docker.sock instead of a 0660 /run/kiri/docker.sock, locking out containerized SDK clients whose numeric uid has no host account tests/disk-grow.py #384 the macOS VM data disk stayed fixed at 64 GiB instead of growing via KIRI_DISK_GB / vm.json and online ext4 resize tests/ui/resources-disk.js #384 Settings -> Resources had no Disk image size control for macOS VM disk growth without shrinking +tests/ui/storage-location.js #355 Settings → Storage had no way to move images, containers, volumes and the VM disk to another folder or external drive, or recover when an external drive is unplugged diff --git a/tests/ui/storage-location.js b/tests/ui/storage-location.js new file mode 100644 index 000000000..9982ad2ab --- /dev/null +++ b/tests/ui/storage-location.js @@ -0,0 +1,167 @@ +// Settings → Storage: custom storage location, native picker command, move vs +// start fresh confirmation, progress, old-data cleanup, and unavailable drive banner. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const last = (cmd) => sent.filter((m) => m.type === cmd).at(-1); + +t("Settings → Storage tab asks for storage status and renders default location", () => { + show("settings"); + const tab = document.querySelector('[data-stab="storage"]'); + if (!tab) throw new Error("missing Storage tab"); + tab.click(); + if (!last("storage")) throw new Error("didn't request storage status"); + kiri.on({ + type: "storage", + path: "/Users/me/Library/Application Support/Kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: false, + env: false, + state: "ok", + used: 4_200_000_000, + free: 120_000_000_000, + fs: "apfs", + moving: null, + error: null, + old: null, + }); + const pane = document.querySelector(".settings .pane"); + if (!pane.textContent.includes("/Users/me/Library/Application Support/Kiri")) throw new Error("missing path"); + if (!pane.querySelector(".st-badge")?.textContent.includes("Default")) throw new Error("missing Default badge"); + if (pane.querySelector("[data-streset]")) throw new Error("Reset to default shouldn't show on default path"); + if (!pane.querySelector("[data-stpick]")) throw new Error("missing Change… button"); +}); + +t("Change… sends storagepick, validation error renders cleanly", () => { + document.querySelector("[data-stpick]").click(); + if (!last("storagepick")) throw new Error("didn't send storagepick"); + kiri.on({ type: "storagecheck", path: "/Volumes/FAT/kiri", error: "/Volumes/FAT/kiri is on a exFAT drive, which can't hold Kiri's data" }); + const err = document.querySelector(".st-box.err"); + if (!err || !err.textContent.includes("exFAT")) throw new Error("missing validation error"); + err.querySelector("[data-sterrclose]").click(); + if (document.querySelector(".st-box.err")) throw new Error("error didn't dismiss"); +}); + +t("valid storagecheck opens confirmation dialog with move and start fresh modes", () => { + kiri.on({ type: "storagecheck", path: "/Volumes/SSD/kiri", needed: 5_000_000_000, free: 400_000_000_000, replaces: false, reset: false }); + const dlg = document.getElementById("st-dlg"); + if (!dlg) throw new Error("confirm dialog didn't open"); + if (!dlg.textContent.includes("/Volumes/SSD/kiri")) throw new Error("missing target path"); + const moveOpt = dlg.querySelector('input[name="st-mode"][value="move"]'); + const freshOpt = dlg.querySelector('input[name="st-mode"][value="fresh"]'); + if (!moveOpt?.checked || !freshOpt) throw new Error("missing move/fresh options"); + freshOpt.checked = true; + freshOpt.dispatchEvent(new Event("change")); + if (!dlg.querySelector("[data-stgo]").textContent.includes("Start fresh")) throw new Error("primary button didn't update for Start fresh"); + dlg.querySelector("[data-stgo]").click(); + if (document.getElementById("st-dlg")) throw new Error("dialog didn't close"); + const req = last("storagemove"); + if (!req || req.path !== "/Volumes/SSD/kiri" || req.value?.fresh !== true) throw new Error("bad storagemove: " + JSON.stringify(req)); +}); + +t("default move mode sends fresh: false", () => { + kiri.on({ type: "storagecheck", path: "/Volumes/SSD/kiri", needed: 5_000_000_000, free: 400_000_000_000, replaces: true, reset: false }); + const dlg = document.getElementById("st-dlg"); + if (!dlg.textContent.includes("Existing Kiri data in this folder will be replaced")) throw new Error("missing replaces warning"); + dlg.querySelector("[data-stgo]").click(); + const req = last("storagemove"); + if (!req || req.path !== "/Volumes/SSD/kiri" || req.value?.fresh !== false) throw new Error("bad storagemove: " + JSON.stringify(req)); +}); + +t("moving state shows progress bar and disables action buttons", () => { + kiri.on({ + type: "storage", + path: "/Users/me/Library/Application Support/Kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: false, + env: false, + state: "moving", + used: null, + free: 120_000_000_000, + fs: "apfs", + moving: { to: "/Volumes/SSD/kiri", phase: "copying", done: 2_100_000_000, total: 4_200_000_000 }, + error: null, + old: null, + }); + const pane = document.querySelector(".settings .pane"); + if (!pane.textContent.includes("Copying data…") || !pane.textContent.includes("50%")) throw new Error("missing copying progress"); + if (!pane.querySelector("[data-stpick]").disabled) throw new Error("Change… should be disabled while moving"); +}); + +t("custom location shows Reset to default and Old data cleanup", () => { + kiri.on({ + type: "storage", + path: "/Volumes/SSD/kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: true, + env: false, + state: "ok", + used: 4_200_000_000, + free: 400_000_000_000, + fs: "apfs", + moving: null, + error: null, + old: "/Users/me/Library/Application Support/Kiri", + }); + const pane = document.querySelector(".settings .pane"); + if (pane.querySelector(".st-badge")) throw new Error("Default badge shouldn't show on custom path"); + if (!pane.querySelector("[data-streset]")) throw new Error("missing Reset to default"); + if (!pane.querySelector("[data-strmold]")) throw new Error("missing Remove old data"); + pane.querySelector("[data-streset]").click(); + const chk = last("storagecheck"); + if (!chk || chk.path !== "" || chk.value?.reset !== true) throw new Error("Reset should check default first: " + JSON.stringify(chk)); + pane.querySelector("[data-strmold]").click(); + const go = document.querySelector(".scrim [data-go]"); + if (!go) throw new Error("Remove old data didn't ask to confirm"); + go.click(); + if (!last("storageremoveold")) throw new Error("didn't send storageremoveold"); +}); + +t("KIRI_DATA_DIR override disables changing storage", () => { + kiri.on({ + type: "storage", + path: "/custom/env/kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: false, + env: true, + state: "ok", + used: 100_000_000, + free: 10_000_000_000, + fs: "apfs", + moving: null, + error: null, + old: null, + }); + const pane = document.querySelector(".settings .pane"); + if (!pane.querySelector("[data-stpick]").disabled) throw new Error("Change… must be disabled under KIRI_DATA_DIR"); + if (!pane.textContent.includes("KIRI_DATA_DIR")) throw new Error("missing KIRI_DATA_DIR note"); +}); + +t("unavailable storage shows Retry, Change…, and Reset to default in settings and main view", () => { + kiri.on({ + type: "storage", + path: "/Volumes/Unplugged/kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: true, + env: false, + state: "unavailable", + used: null, + free: null, + fs: null, + moving: null, + error: null, + old: null, + }); + const warn = document.querySelector(".st-box.warn"); + if (!warn || !warn.textContent.includes("/Volumes/Unplugged/kiri")) throw new Error("missing unavailable banner in settings"); + warn.querySelector("[data-stretry]").click(); + if (!last("storageretry")) throw new Error("Retry didn't send storageretry"); + warn.querySelector("[data-streset]").click(); + const confirmReset = document.querySelector(".scrim [data-go]"); + if (!confirmReset) throw new Error("Reset while unavailable didn't confirm"); + confirmReset.click(); + if (!last("storagereset")) throw new Error("didn't send storagereset"); + show("containers"); + if (!document.getElementById("content").textContent.includes("Storage location unavailable")) throw new Error("main view didn't show unavailable message"); +}); + +report(R); From 44563447a4dd938bbf2c27e0be76d935a65aba2a Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:47:26 +0100 Subject: [PATCH 047/157] Network: respect explicit EnableIPv6=false on custom bridge networks (#433) (#830) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Đoàn Phương Nam <120766900+DPhngNam@users.noreply.github.com> --- crates/kiri/src/daemon/api.rs | 93 +++++++++++++++++++++++++++++++ crates/kiri/src/daemon/network.rs | 73 +++++++++++++++++++++--- docs/fix-registry.md | 6 ++ tests/e2e.sh | 3 + tests/linux-host.sh | 3 + tests/regressions.tsv | 1 + 6 files changed, 171 insertions(+), 8 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 067b0436e..fd852858d 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -5363,6 +5363,99 @@ mod tests { drop(engine); let _ = std::fs::remove_dir_all(root); } + + #[test] + fn network_create_ignores_ipv6_ipam_when_ipv6_disabled() { + let root = std::env::temp_dir().join(format!("kiri-net-ipv6-off-api-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + let post = |body: Value| network_create(&Request::internal("POST", "/networks/create", &[], serde_json::to_vec(&body).unwrap()), &engine); + + // 1a. Explicit EnableIPv6: false + IPv4 & IPv6 subnets (mailcow-dockerized). + post(json!({ + "Name": "mailcow", + "EnableIPv6": false, + "IPAM": { + "Driver": "default", + "Config": [ + {"Subnet": "172.22.1.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow").unwrap(); + assert_eq!(ins["EnableIPv4"], json!(true)); + assert_eq!(ins["EnableIPv6"], json!(false)); + assert_eq!(ins["IPAM"]["Config"], json!([{"Subnet": "172.22.1.0/24", "Gateway": "172.22.1.1"}])); + + // 1b. EnableIPv6 omitted + IPv4 & IPv6 subnets. + post(json!({ + "Name": "mailcow-omitted", + "IPAM": { + "Config": [ + {"Subnet": "172.22.2.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow-omitted").unwrap(); + assert_eq!(ins["EnableIPv6"], json!(false)); + assert_eq!(ins["IPAM"]["Config"], json!([{"Subnet": "172.22.2.0/24", "Gateway": "172.22.2.1"}])); + + // 2. EnableIPv6: false + ONLY an IPv6 subnet: auto-allocates IPv4 subnet. + post(json!({ + "Name": "v6-only-cfg", + "EnableIPv6": false, + "IPAM": {"Config": [{"Subnet": "fd4d:6169:6c63:6f77::/64"}]} + })) + .unwrap(); + let ins = network_inspect(&engine, "v6-only-cfg").unwrap(); + assert_eq!(ins["EnableIPv4"], json!(true)); + assert_eq!(ins["EnableIPv6"], json!(false)); + let cfg = ins["IPAM"]["Config"].as_array().unwrap(); + assert_eq!(cfg.len(), 1); + let sub = cfg[0]["Subnet"].as_str().unwrap(); + assert!(sub.contains('.') && !sub.contains(':'), "expected auto IPv4 subnet, got {sub}"); + + // 3. Malformed subnet strings with EnableIPv6: false are still 400 BadRequest. + for bad in [ + json!([{"Subnet": "fd4d::not-a-cidr"}]), + json!([{"Subnet": "172.22.3.0/24"}, {"Subnet": "fd4d::not-a-cidr"}]), + json!([{"Subnet": "not-an-ip/64"}]), + json!([{"Subnet": "172.22.3.0/24"}, {"Subnet": "not-an-ip/64"}]), + ] { + let res = post(json!({"Name": "bad-cidr", "EnableIPv6": false, "IPAM": {"Config": bad}})); + assert!(matches!(res, Err(Error::BadRequest(ref m)) if m.contains("invalid CIDR block notation")), "{bad} -> {res:?}"); + } + + // 4. EnableIPv6: true + valid IPv6 subnet still works identically. + post(json!({ + "Name": "mailcow-on", + "EnableIPv6": true, + "IPAM": { + "Config": [ + {"Subnet": "172.22.4.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow-on").unwrap(); + assert_eq!(ins["EnableIPv6"], json!(true)); + assert_eq!( + ins["IPAM"]["Config"], + json!([ + {"Subnet": "172.22.4.0/24", "Gateway": "172.22.4.1"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64", "Gateway": "fd4d:6169:6c63:6f77::1"} + ]) + ); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } } #[cfg(test)] diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index 63d9c7d4e..b368848da 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -527,10 +527,11 @@ pub fn parse_ipam_both(v: &serde_json::Value) -> Result<(Option, Option Result<(Option, Option 30 || prefix < 8 { return Err(format!("invalid subnet {subnet}: Kiri supports prefixes from /8 to /30")); } @@ -748,9 +749,7 @@ impl Networks { used: BTreeSet::new(), }) } else { - if s.ipam6.is_some() { - return Err("invalid network config: an IPv6 subnet needs IPv6 enabled (--ipv6, Compose enable_ipv6: true)".into()); - } + // An IPv6 IPAM entry without --ipv6 is ignored, as Docker does (#433). None }; let index = (1..).find(|i| !self.list.iter().any(|n| n.bridge == format!("kiri{i}"))).expect("unbounded"); @@ -1284,9 +1283,9 @@ mod tests { assert_eq!(kv.subnet_str(), "fc00:f853:ccd:e793::/64"); assert_eq!(ip6_str(kv.gateway), "fc00:f853:ccd:e793::1"); assert!(n.create("again", v6(ipam("fc00:f853:ccd:e793::/80"))).unwrap_err().contains("Pool overlaps")); - // A subnet without --ipv6 is refused, not dropped. - let no = Settings { ipam6: ipam("fd00:9::/64"), ..Default::default() }; - assert!(n.create("no", no).unwrap_err().contains("IPv6 enabled")); + // A subnet without --ipv6 is ignored, not refused (#433). + let no = n.create("no", Settings { ipam6: ipam("fd00:9::/64"), ..Default::default() }).unwrap(); + assert!(no.v6.is_none()); // Fixed addresses: in the subnet, free, not the gateway. let want = parse_ip6("fc00:f853:ccd:e793::10"); assert_eq!(n.allocate6("kind", want, &[]), Ok(want)); @@ -1311,6 +1310,64 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn ipv6_ipam_subnet_is_ignored_when_ipv6_disabled() { + let (mut n, dir) = nets(); + // 1. mailcow-dockerized shape: EnableIPv6=false with IPv4 + IPv6 subnets. + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Driver": "default", + "Config": [ + {"Subnet": "172.22.1.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"}, + ] + })) + .unwrap(); + let mailcow = n.create("mailcow", Settings { ipam, ipam6, ipv6: false, ..Default::default() }).unwrap(); + assert_eq!(mailcow.subnet_str(), "172.22.1.0/24"); + assert_eq!(ip_str(mailcow.gateway), "172.22.1.1"); + assert!(mailcow.user_subnet); + assert!(mailcow.v6.is_none()); + + // 2. EnableIPv6=false with ONLY an IPv6 subnet: auto-allocates IPv4 from pool. + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Config": [{"Subnet": "fd4d:6169:6c63:6f77::/64"}] + })) + .unwrap(); + assert!(ipam.is_none() && ipam6.is_some()); + let auto = n.create("v6only-config-off", Settings { ipam, ipam6, ipv6: false, ..Default::default() }).unwrap(); + assert!(auto.v6.is_none()); + assert!(!auto.user_subnet); + assert_ne!(auto.subnet, [0; 4]); + assert!(auto.contains(auto.gateway)); + assert!(!overlaps((auto.subnet, auto.prefix), (mailcow.subnet, mailcow.prefix))); + + // 3. Malformed IPv6/non-IP subnet strings are still rejected as invalid CIDRs. + for cfg in [ + serde_json::json!({"Config": [{"Subnet": "fd4d::not-a-cidr"}]}), + serde_json::json!({"Config": [{"Subnet": "172.22.1.0/24"}, {"Subnet": "fd4d::not-a-cidr"}]}), + serde_json::json!({"Config": [{"Subnet": "not-an-ip/64"}]}), + serde_json::json!({"Config": [{"Subnet": "172.22.1.0/24"}, {"Subnet": "not-an-ip/64"}]}), + ] { + let err = parse_ipam_both(&cfg).unwrap_err(); + assert!(err.contains("invalid CIDR block notation"), "{cfg} -> {err}"); + } + + // 4. EnableIPv6=true with the same IPv6 subnet still works (was not claimed above). + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Config": [ + {"Subnet": "172.22.2.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"}, + ] + })) + .unwrap(); + let enabled = n.create("mailcow-v6", Settings { ipam, ipam6, ipv6: true, ..Default::default() }).unwrap(); + assert_eq!(enabled.subnet_str(), "172.22.2.0/24"); + let kv = enabled.v6.unwrap(); + assert_eq!(kv.subnet_str(), "fd4d:6169:6c63:6f77::/64"); + assert_eq!(ip6_str(kv.gateway), "fd4d:6169:6c63:6f77::1"); + let _ = std::fs::remove_dir_all(dir); + } + fn host(dev: &str, addr: [u8; 4], prefix: u8) -> HostNet { HostNet::new(dev, addr, mask4(prefix)) } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 4137ec278..77107711c 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 +### #454 Networks: ignore IPv6 IPAM subnets when IPv6 is disabled, as Docker does (unreleased) +- Fixes: #433 `POST /networks/create` with `EnableIPv6: false` (or omitted) and an IPv6 subnet in `IPAM.Config` was refused instead of ignoring the IPv6 subnet as Docker does (`mailcow-dockerized`) +- Caused: none known +- Caused by: - +- Check: `network-ipv6-subnet-ignored-when-disabled` + ### #355 Settings → Storage: move Kiri's data folder to another drive (unreleased) - Fixes: #355 Custom storage directory (Settings → Storage location) - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 88c977273..b3223a711 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -838,6 +838,9 @@ t ipv6-pool-ula " fd" $D network inspect v6net -f '{{range .IPAM.Config}} {{.Sub # A chosen subnet and gateway, as kind and Compose's ipam ask. t ipv6-subnet "fd00:db8:7::/64 fd00:db8:7::fe" bash -c "$D network create --ipv6 --subnet fd00:db8:7::/64 --gateway fd00:db8:7::fe v6sub >/dev/null && $D network inspect v6sub -f '{{range .IPAM.Config}}{{.Subnet}} {{.Gateway}} {{end}}'" t ipv6-overlap "Pool overlaps" $D network create --ipv6 --subnet fd00:db8:7::/80 v6dup +# An IPv6 IPAM subnet without --ipv6 is ignored, as Docker does (#433): +# both with an IPv4 subnet (mailcow-dockerized) and with only an IPv6 subnet. +t network-ipv6-subnet-ignored-when-disabled "false 1 10.234.0.0/24 false 1 v4" bash -c "$D network create --subnet 10.234.0.0/24 --subnet fd4d:6169:6c63:6f77::/64 v6off >/dev/null && a=\$($D network inspect v6off -f '{{.EnableIPv6}} {{len .IPAM.Config}} {{(index .IPAM.Config 0).Subnet}}') && $D network create --subnet fd4d:6169:6c63:6f77::/64 v6off-auto >/dev/null && b=\$($D network inspect v6off-auto -f '{{.EnableIPv6}} {{len .IPAM.Config}}') && s=\$($D network inspect v6off-auto -f '{{(index .IPAM.Config 0).Subnet}}') && case \"\$s\" in *.*/*) v=v4;; *) v=bad:\$s;; esac && echo \"\$a \$b \$v\"; $D network rm v6off v6off-auto >/dev/null 2>&1" # IPv6-only (--ipv4=false), as Docker 28 has: no IPv4 address on eth0. t ipv6-only-create "false" bash -c "$D network create --ipv6 --ipv4=false v6only >/dev/null && $D network inspect v6only -f '{{.EnableIPv4}}'" t ipv6-only-no-v4 "inet6 0" $D run --rm --network v6only alpine sh -c 'echo $(ip -6 addr show eth0 scope global | grep -o inet6 | head -1) $(ip -4 addr show eth0 | grep -c inet)' diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 269d7f1bd..f6e3d68c0 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -186,6 +186,9 @@ t internal-first-second-external "1:eth1-ok" "docker network connect lh-na lh-la t disconnect-hands-default-on "eth2-ok" "docker network disconnect lh-na lh-late && gw=\$(docker network inspect lh-nb -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker exec lh-late ip -4 route show default | grep -q \"default via \$gw dev eth2\" && echo eth2-ok; docker rm -f lh-late >/dev/null; docker network rm lh-ni lh-na lh-nb >/dev/null" t internal-first-ipv6-no-default "none" "docker network create --internal --ipv6 --subnet fd00:193:0::/64 lh-ni6 >/dev/null && docker network create --ipv6 --subnet fd00:193:1::/64 --gateway fd00:193:1::1 lh-na6 >/dev/null && docker network create --ipv6 --subnet fd00:193:2::/64 --gateway fd00:193:2::1 lh-nb6 >/dev/null && docker run -d --name lh-late6 --network lh-ni6 alpine sleep 60 >/dev/null && (docker exec lh-late6 ip -6 route show default | grep -q default && echo default || echo none)" t disconnect-hands-ipv6-default-on "default via fd00:193:2::1 dev eth2" "docker network connect lh-na6 lh-late6 && docker network connect lh-nb6 lh-late6 && docker network disconnect lh-na6 lh-late6 && docker exec lh-late6 ip -6 route show default; docker rm -f lh-late6 >/dev/null; docker network rm lh-ni6 lh-na6 lh-nb6 >/dev/null" +# An IPv6 IPAM subnet without --ipv6 is ignored, as Docker does (#433): +# both with an IPv4 subnet (mailcow-dockerized) and with only an IPv6 subnet. +t network-ipv6-subnet-ignored-when-disabled "false 1 10.234.0.0/24 false 1 v4" "docker network create --subnet 10.234.0.0/24 --subnet fd4d:6169:6c63:6f77::/64 lh6off >/dev/null && a=\$(docker network inspect lh6off -f '{{.EnableIPv6}} {{len .IPAM.Config}} {{(index .IPAM.Config 0).Subnet}}') && docker network create --subnet fd4d:6169:6c63:6f77::/64 lh6off-auto >/dev/null && b=\$(docker network inspect lh6off-auto -f '{{.EnableIPv6}} {{len .IPAM.Config}}') && s=\$(docker network inspect lh6off-auto -f '{{(index .IPAM.Config 0).Subnet}}') && case \"\$s\" in *.*/*) v=v4;; *) v=bad:\$s;; esac && echo \"\$a \$b \$v\"; docker network rm lh6off lh6off-auto >/dev/null 2>&1" # A build's --add-host host-gateway is the bridge gateway, as for docker run (not the Mac VM's 198.19.248.254). t build-host-gateway "GW-OK" "gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}'); mkdir -p /bhg && printf 'FROM $KIRI_REG/alpine:3.21\\nRUN grep -w hgw /etc/hosts\\n' > /bhg/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache --add-host hgw:host-gateway /bhg 2>&1 | grep -q \"\$gw\" && echo GW-OK" # A privileged container must not touch the host's /dev. The kernel has one diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 8e2cce0b1..9e92d0863 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -280,3 +280,4 @@ socket-container-uid-group #127 a standalone root-run Linux daemon put its 0600 tests/disk-grow.py #384 the macOS VM data disk stayed fixed at 64 GiB instead of growing via KIRI_DISK_GB / vm.json and online ext4 resize tests/ui/resources-disk.js #384 Settings -> Resources had no Disk image size control for macOS VM disk growth without shrinking tests/ui/storage-location.js #355 Settings → Storage had no way to move images, containers, volumes and the VM disk to another folder or external drive, or recover when an external drive is unplugged +network-ipv6-subnet-ignored-when-disabled #433 POST /networks/create with EnableIPv6 false (or omitted) and an IPv6 subnet in IPAM.Config was refused instead of ignoring the IPv6 subnet as Docker does (mailcow-dockerized) From f2576cd74c40b060f72189a4fde0d7c65981ec87 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:55:32 +0100 Subject: [PATCH 048/157] Mac: report port-already-allocated errors clearly when host bind fails (#258) (#831) Co-authored-by: sundarshahi --- crates/kiri/src/daemon/ports.rs | 25 ++++++++++++++++++++++--- docs/fix-registry.md | 6 ++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index 756c9568b..38994a17d 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -1010,7 +1010,8 @@ pub const HOST_ADDR: &str = "198.19.248.254"; pub const HOST_BOUND_PORT: u32 = 1026; /// One host-bound connection from a container: the guest sends -/// `ip[4] port[2]` (always 127.0.0.1 today), and we connect there on the Mac. +/// `ip[4] port[2]` (always 127.0.0.1 today), and we connect to the Mac's +/// loopback at that port. pub fn serve_host_bound(stream: kiri_vmm::VsockStream) { let _ = std::thread::Builder::new().name("kiri-host-bound".into()).spawn(move || { let _ = host_bound(stream); @@ -1029,7 +1030,7 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { } // Refused or unreachable: dropping closes the container's connection, // which is what it would see from a real host too. - let target = TcpStream::connect((ip, port))?; + let target = dial_loopback(port)?; target.set_nodelay(true)?; let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); let mut target_read = target.try_clone()?; @@ -1046,6 +1047,11 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { Ok(()) } +/// The Mac's loopback at `port`: IPv4, then IPv6 for a server on `::1` only (#258). +fn dial_loopback(port: u16) -> io::Result { + TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, port)).or_else(|e| TcpStream::connect((std::net::Ipv6Addr::LOCALHOST, port)).map_err(|_| e)) +} + /// The guest's relay only ever asks for the Mac's loopback; anything else is /// a guest process speaking the protocol itself. A router's port is refused /// too: it serves this Mac, and would take a container to any container. @@ -1868,7 +1874,7 @@ pub fn listening>(lines: &[S], host_network: bool) -> (Vec, V #[cfg(test)] mod tests { - use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, host_bound_allowed, kernel_forwards, kernel_host_ip, listening, nat_port, relays_too, tcp_permit}; + use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, dial_loopback, host_bound_allowed, kernel_forwards, kernel_host_ip, listening, nat_port, relays_too, tcp_permit}; use std::net::IpAddr; use std::sync::atomic::Ordering; @@ -1885,6 +1891,19 @@ mod tests { assert!(!host_bound_allowed(std::net::Ipv4Addr::new(10, 0, 0, 1), 5432, router), "loopback only"); } + /// A Mac server on `::1` only (Node's `localhost`) is reached; one on + /// both loopbacks is reached on 127.0.0.1, as before (#258). + #[test] + fn host_docker_internal_reaches_a_server_on_either_loopback() { + let v6 = std::net::TcpListener::bind("[::1]:0").unwrap(); + let port = v6.local_addr().unwrap().port(); + assert_eq!(dial_loopback(port).unwrap().peer_addr().unwrap().ip(), IpAddr::from(std::net::Ipv6Addr::LOCALHOST)); + let v4 = std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(); + assert_eq!(dial_loopback(port).unwrap().peer_addr().unwrap().ip(), IpAddr::from(std::net::Ipv4Addr::LOCALHOST)); + drop((v4, v6)); + assert_eq!(dial_loopback(port).unwrap_err().kind(), std::io::ErrorKind::ConnectionRefused); + } + /// A clash names the other program holding the port, never Kiri itself. #[test] fn a_taken_port_names_the_program_that_has_it() { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 77107711c..8f2cd0f15 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 +### #589 Mac: host.docker.internal reaches a server on ::1, such as Node's localhost (unreleased) +- Fixes: #258 macOS: host.docker.internal reaches only the Mac's 127.0.0.1, not ::1, so localhost dev servers are unreachable +- Caused: none known +- Caused by: - +- Check: none + ### #454 Networks: ignore IPv6 IPAM subnets when IPv6 is disabled, as Docker does (unreleased) - Fixes: #433 `POST /networks/create` with `EnableIPv6: false` (or omitted) and an IPv6 subnet in `IPAM.Config` was refused instead of ignoring the IPv6 subnet as Docker does (`mailcow-dockerized`) - Caused: none known From 33c8a7f074e1300a8a28a2bbcbcb48f69bc87fd8 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:13:17 +0100 Subject: [PATCH 049/157] API: accept HTTP/1.1 absolute-form request targets from proxy-aware SDKs (#757) (#832) --- crates/kiri/src/daemon/api.rs | 31 ++++++- crates/kiri/src/daemon/http.rs | 161 ++++++++++++++++++++++++++++++++- docs/fix-registry.md | 6 ++ tests/e2e.sh | 4 + tests/linux-host.sh | 4 + tests/regressions.tsv | 2 + 6 files changed, 203 insertions(+), 5 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index fd852858d..ae2b6d543 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -24,7 +24,15 @@ use super::time; pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Result<()> { let mut w = stream.try_clone()?; let mut r = BufReader::new(stream); - while let Some(req) = http::read_request(&mut r, streams_body)? { + loop { + let req = match http::read_request(&mut r, streams_body) { + Ok(Some(req)) => req, + Ok(None) => break, + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + return http::refuse_bad_request(&mut w, &mut r, &e.to_string()).or(Ok(())); + } + Err(e) => return Err(e), + }; // A body too large to hold: answered and ended, never routed. if req.too_large() { return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); @@ -4566,6 +4574,27 @@ mod tests { // A close asked for on the second request ends it after that one. let (got, ended) = exchange("GET /_ping HTTP/1.1\r\nHost: d\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n"); assert!(ended && got.matches("HTTP/1.1 200 ").count() == 2 && got.matches("Connection: close\r\n").count() == 1, "{got}"); + // Absolute-form targets route as origin-form (#757), while malformed + // targets or request lines answer 400 Bad Request and close cleanly. + let (got, ended) = exchange("GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\nConnection: close\r\n\r\n"); + assert!(ended && got.starts_with("HTTP/1.1 200 OK\r\n") && got.ends_with("OK"), "{got}"); + for bad in [ + "GET http:///containers/json HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET ftp://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET\t/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + ] { + let (got, ended) = exchange(bad); + assert!( + ended && got.starts_with("HTTP/1.1 400 Bad Request\r\n") && got.contains("Connection: close\r\n") && got.contains("\"message\":\"bad request "), + "{bad:?}: {got}" + ); + } + let (got, ended) = exchange("GET /_ping HTTP/1.1\r\nHost: d\r\n\r\nGET http:///bad HTTP/1.1\r\nHost: d\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"); + assert!( + ended && got.matches("HTTP/1.1 200 OK\r\n").count() == 1 && got.matches("HTTP/1.1 400 Bad Request\r\n").count() == 1 && got.matches("Connection: close\r\n").count() == 1, + "{got}" + ); drop(engine); let _ = std::fs::remove_dir_all(root); } diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index a7e7ab8f4..fe471746f 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -111,6 +111,8 @@ impl Request { /// When `stream(method, path)` is true the body stays unread: the handler /// reads it through [`Body`]. pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) -> bool) -> io::Result> { + SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); + CLOSING.with(|c| c.set(false)); // The request line and headers are read through a cap, so a client // cannot exhaust memory with an endless line. The body is read after. let (method, path, api_version, query, headers, http10) = { @@ -119,13 +121,24 @@ pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) - if head.read_line(&mut line)? == 0 { return Ok(None); } - let mut parts = line.split_whitespace(); - let (Some(method), Some(target)) = (parts.next(), parts.next()) else { + let Some(req_line) = line.strip_suffix('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) else { return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); }; - let http10 = parts.next().is_some_and(|v| v.eq_ignore_ascii_case("HTTP/1.0")); + let mut parts = req_line.split(' '); + let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + }; + if [method, target, version].iter().any(|p| p.is_empty() || p.chars().any(|c| c.is_ascii_control() || c.is_whitespace())) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + } + if !version.eq_ignore_ascii_case("HTTP/1.1") && !version.eq_ignore_ascii_case("HTTP/1.0") { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + } + let http10 = version.eq_ignore_ascii_case("HTTP/1.0"); let method = method.to_owned(); - let (raw_path, raw_query) = target.split_once('?').unwrap_or((target, "")); + let Some((raw_path, raw_query)) = parse_target(target) else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request target")); + }; // Decoded once, here, so every route that reads a name from the // path — an image's `%2F` repository slash above all — resolves the // name, not its encoding, as Docker's router does. @@ -215,6 +228,15 @@ pub fn refuse_too_large(req: &Request, w: &mut UnixStream, r: &mut BufReader, message: &str) -> io::Result<()> { + SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); + let sent = error_closing(w, 400, message); + close(w, r); + sent +} + /// After a streamed request's response: whether the connection can serve /// the client's next request. A body its handler left unread (a pull sent /// with one, as docker-modem sends its options) is read out first, up to @@ -338,6 +360,50 @@ impl Read for Body<'_> { } } +/// Splits an RFC 9112 §3.2.1 `origin-form` or §3.2.2 `absolute-form` +/// request-target into `(path, query)`. Clients such as docker-modem send +/// `GET http://127.0.0.1:2376/containers/json HTTP/1.1` over the Unix socket +/// or named pipe when configured with a default host and port (#757). +fn parse_target(target: &str) -> Option<(&str, &str)> { + if target.contains('#') { + return None; + } + if target.starts_with('/') { + return Some(target.split_once('?').unwrap_or((target, ""))); + } + let (scheme, rest) = target.split_once("://")?; + if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { + return None; + } + let (authority, tail) = match rest.find(['/', '?']) { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, ""), + }; + if !valid_authority(authority) { + return None; + } + match tail.strip_prefix('?') { + Some(q) => Some(("/", q)), + None if tail.is_empty() => Some(("/", "")), + None => Some(tail.split_once('?').unwrap_or((tail, ""))), + } +} + +fn valid_authority(authority: &str) -> bool { + let valid_port = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n > 0); + if let Some(rest) = authority.strip_prefix('[') { + let Some((v6, after)) = rest.split_once(']') else { return false }; + return v6.parse::().is_ok() && (after.is_empty() || after.strip_prefix(':').is_some_and(valid_port)); + } + let (host, port) = match authority.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (authority, None), + }; + !host.is_empty() + && host.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) + && port.is_none_or(valid_port) +} + /// `/v1.47/containers/json` → `/containers/json`. fn strip_version(path: &str) -> &str { if let Some(rest) = path.strip_prefix("/v") @@ -697,6 +763,93 @@ mod tests { assert_eq!(path_of("/images/100%/json"), "/images/100%/json"); } + /// Clients such as docker-modem send an RFC 9112 §3.2.2 absolute-form + /// request-target over the Unix socket or named pipe when configured with + /// a default host and port (#757). + #[test] + fn reads_absolute_form_request_targets() { + use std::io::Write; + let try_parse = |target: &str| { + let (mut a, b) = UnixStream::pair().unwrap(); + a.write_all(format!("GET {target} HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n").as_bytes()) + .unwrap(); + drop(a); + read_request(&mut BufReader::new(b), |_, _| false) + }; + + let req = try_parse("http://127.0.0.1:2376/containers/json?all=1").unwrap().unwrap(); + assert_eq!(req.path, "/containers/json"); + assert_eq!(req.api_version, None); + assert_eq!(req.query("all"), Some("1")); + + let req = try_parse("HTTP://[::1]:2375/v1.47/version").unwrap().unwrap(); + assert_eq!(req.path, "/version"); + assert_eq!(req.api_version, Some((1, 47))); + + let req = try_parse("https://docker:2376/_ping").unwrap().unwrap(); + assert_eq!(req.path, "/_ping"); + assert_eq!(req.api_version, None); + + let req = try_parse("http://localhost:2375").unwrap().unwrap(); + assert_eq!(req.path, "/"); + assert!(req.query.is_empty()); + + let req = try_parse("http://localhost:2375?foo=bar").unwrap().unwrap(); + assert_eq!(req.path, "/"); + assert_eq!(req.query("foo"), Some("bar")); + + let req = try_parse("http://127.0.0.1:2376//v1.47/containers/json").unwrap().unwrap(); + assert_eq!(req.path, "//v1.47/containers/json"); + assert_eq!(req.api_version, None); + + let req = try_parse("http://127.0.0.1:2376/v1.44/images/mongodb%2Fmongodb-atlas-local:8.0/json").unwrap().unwrap(); + assert_eq!(req.path, "/images/mongodb/mongodb-atlas-local:8.0/json"); + assert_eq!(req.api_version, Some((1, 44))); + + for bad in [ + "http:///containers/json", + "https:///containers/json", + "http://", + "http://?a=1", + "ftp://127.0.0.1:2376/_ping", + "unix:///var/run/docker.sock", + "http:/containers/json", + "containers/json", + "http://:2376/_ping", + "http://127.0.0.1:/_ping", + "http://127.0.0.1:99999/_ping", + "http://[::1/_ping", + "http://[not-an-ip]/_ping", + "http://user@127.0.0.1:2376/_ping", + "http://127.0.0.1:2376/_ping#frag", + "/_ping#frag", + "http://127.0.0.1:2376/containers/json extra", + "/_ping\u{00a0}extra", + "/_ping\x7f", + ] { + assert!(try_parse(bad).is_err(), "accepted malformed target: {bad}"); + } + + let try_raw = |raw: &str| { + let (mut a, b) = UnixStream::pair().unwrap(); + a.write_all(raw.as_bytes()).unwrap(); + drop(a); + read_request(&mut BufReader::new(b), |_, _| false) + }; + for bad_line in [ + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + " GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1 \r\nHost: d\r\n\r\n", + "GET\thttp://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping\tHTTP/1.1\r\nHost: d\r\n\r\n", + "GET HTTP/1.1\r\nHost: d\r\n\r\n", + "GET /_ping HTTP/2.0\r\nHost: d\r\n\r\n", + ] { + assert!(try_raw(bad_line).is_err(), "accepted malformed request line: {bad_line:?}"); + } + } + /// `attach` and `exec` start answer `101` only to a client that asked to /// upgrade (the docker CLI). docker-java, so Testcontainers, does not, and /// gets `200 OK` with the raw stream as the body, as from Docker. diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 8f2cd0f15..df192d3a3 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 +### #757 API: accept RFC 9112 §3.2.2 absolute-form HTTP request targets on the Docker socket (unreleased) +- Fixes: #757 `GET http://127.0.0.1:2376/containers/json HTTP/1.1` over the Docker socket fails with 404 (dockerode / docker-modem / Lando) +- Caused: none known +- Caused by: - +- Check: `absolute-form-ping`, `absolute-form-containers` + ### #589 Mac: host.docker.internal reaches a server on ::1, such as Node's localhost (unreleased) - Fixes: #258 macOS: host.docker.internal reaches only the Mac's 127.0.0.1, not ::1, so localhost dev servers are unreachable - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index b3223a711..6940d82bf 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -286,6 +286,10 @@ t http10-start-closes "304 closed" python3 -c "$PROBE" "$SOCK" 'POST /v1.44/cont t keep-alive-start-stays "304 open" python3 -c "$PROBE" "$SOCK" 'POST /v1.44/containers/e2e-close/start HTTP/1.1\r\nHost: d\r\n\r\n' t connection-close-said "Connection: close" curl -s -m 5 -o /dev/null -D - --unix-socket "$SOCK" -H 'Connection: close' http://d/_ping t http10-ping-closes "200 closed" python3 -c "$PROBE" "$SOCK" 'GET /_ping HTTP/1.0\r\n\r\n' +# docker-modem sends an RFC 9112 §3.2.2 absolute-form request-target over the +# socket when configured with a default host and port (#757). +t absolute-form-ping "200 closed" python3 -c "$PROBE" "$SOCK" 'GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\nConnection: close\r\n\r\n' +t absolute-form-containers "200 closed" python3 -c "$PROBE" "$SOCK" 'GET http://127.0.0.1:2376/containers/json HTTP/1.1\r\nHost: 127.0.0.1:2376\r\nConnection: close\r\n\r\n' # A body past the 8 MiB a request read whole may send is answered (413, in # Docker's error shape) and the connection ends cleanly: it was dropped with # no answer, and curl, still sending, failed with "Send failure" (exit 55). diff --git a/tests/linux-host.sh b/tests/linux-host.sh index f6e3d68c0..76848ec5c 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -126,6 +126,10 @@ t archive-directory-contents "PASS stopped docker cp of a parent into new direct for c in version cmd keepalive close follow follow-created timestamps endpoints; do t "testcontainers-$c" "ok $c" "for i in \$(seq 60); do command -v python3 >/dev/null && break; sleep 1; done; python3 /testcontainers-api.py /root/.kiri/run/docker.sock $c" done +# docker-modem sends an RFC 9112 §3.2.2 absolute-form request-target over the +# socket when configured with a default host and port (#757). +t absolute-form-ping "200 OK" "python3 -c 'import socket; s = socket.socket(socket.AF_UNIX); s.connect(\"/root/.kiri/run/docker.sock\"); s.sendall(b\"GET http://127.0.0.1:2376/_ping HTTP/1.1\\r\\nHost: 127.0.0.1:2376\\r\\nConnection: close\\r\\n\\r\\n\"); r = b\"\".join(iter(lambda: s.recv(4096), b\"\")).decode(); print(r.split()[1], r.splitlines()[-1])'" +t absolute-form-containers "200 [" "python3 -c 'import socket; s = socket.socket(socket.AF_UNIX); s.connect(\"/root/.kiri/run/docker.sock\"); s.sendall(b\"GET http://127.0.0.1:2376/containers/json HTTP/1.1\\r\\nHost: 127.0.0.1:2376\\r\\nConnection: close\\r\\n\\r\\n\"); r = b\"\".join(iter(lambda: s.recv(4096), b\"\")).decode(); print(r.split()[1], r.splitlines()[-1][:1])'" t socket-mount-reaches-kiri "Kiri" "docker run --rm -v /root/.kiri/run/docker.sock:/var/run/docker.sock docker:cli docker version --format '{{.Server.Platform.Name}}'" # A container given the engine's socket uses Docker's API, not Kiri's own # settings: the same CLI that changes them here is refused from inside one. diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 9e92d0863..f329addca 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -281,3 +281,5 @@ tests/disk-grow.py #384 the macOS VM data disk stayed fixed at 64 GiB instead of tests/ui/resources-disk.js #384 Settings -> Resources had no Disk image size control for macOS VM disk growth without shrinking tests/ui/storage-location.js #355 Settings → Storage had no way to move images, containers, volumes and the VM disk to another folder or external drive, or recover when an external drive is unplugged network-ipv6-subnet-ignored-when-disabled #433 POST /networks/create with EnableIPv6 false (or omitted) and an IPv6 subnet in IPAM.Config was refused instead of ignoring the IPv6 subnet as Docker does (mailcow-dockerized) +absolute-form-ping #757 an RFC 9112 §3.2.2 absolute-form request-target over the Docker socket left the scheme and authority in the path and answered 404 +absolute-form-containers #757 docker-modem requests such as GET http://127.0.0.1:2376/containers/json HTTP/1.1 over the Docker socket answered 404 instead of routing /containers/json From 0d05a5674db5b0b01a650f2a9ee71f50794c6898 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:23:08 +0100 Subject: [PATCH 050/157] UI: support --view builds in kiri ui (#456) (#834) --- crates/kiri/src/builds.rs | 140 ++++++++++++++++++++++++++++++++------ docs/fix-registry.md | 6 ++ 2 files changed, 125 insertions(+), 21 deletions(-) diff --git a/crates/kiri/src/builds.rs b/crates/kiri/src/builds.rs index 3f67abca1..e45a80a04 100644 --- a/crates/kiri/src/builds.rs +++ b/crates/kiri/src/builds.rs @@ -17,13 +17,27 @@ use crate::flavor::{CONTEXT, Name}; /// Kiri's BuildKit builder, a docker-container one on Kiri's context. pub const BUILDER: Name = Name("kiri-build", "kiri-dev-build"); +#[cfg(unix)] +fn kiri_host() -> io::Result { + Ok(format!("unix://{}", crate::client::socket()?.display())) +} + +#[cfg(windows)] +fn kiri_host() -> io::Result { + Ok(format!("npipe://{}", crate::client::pipe().replace('\\', "/"))) +} + fn buildx(args: &[&str]) -> io::Result<(String, String)> { let docker = crate::client::docker_cli().ok_or_else(|| io::Error::other("no docker CLI found (Kiri.app bundles one)"))?; + let host = kiri_host()?; let mut cmd = Command::new(docker); // No console window flashing up from Kiri's window on Windows. #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let out = cmd.args(["--context", CONTEXT.get(), "buildx"]).args(args).stdin(Stdio::null()).output()?; + // Clear DOCKER_CONTEXT and point DOCKER_HOST at Kiri's socket/pipe so the + // implicit "default" builder (used by `docker compose build`) resolves to + // Kiri's engine while named builders on Kiri's context still work. + let out = cmd.env_remove("DOCKER_CONTEXT").env("DOCKER_HOST", host).arg("buildx").args(args).stdin(Stdio::null()).output()?; let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()); if !out.status.success() { let msg = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("buildx failed").trim_start_matches("ERROR: ").to_owned(); @@ -37,7 +51,45 @@ fn values(s: &str) -> Vec { serde_json::Deserializer::from_str(s).into_iter::().map_while(Result::ok).collect() } -/// The docker-container builders on Kiri's context whose BuildKit container exists. +fn endpoint_is_kiri(endpoint: Option<&str>, kiri_context: &str, kiri_host: &str) -> bool { + let Some(ep) = endpoint.filter(|s| !s.is_empty()) else { return false }; + if ep == kiri_context || ep == "default" || ep == kiri_host { + return true; + } + if kiri_host.get(..8).is_some_and(|s| s.eq_ignore_ascii_case("npipe://")) && ep.get(..8).is_some_and(|s| s.eq_ignore_ascii_case("npipe://")) { + return ep.replace('\\', "/").eq_ignore_ascii_case(&kiri_host.replace('\\', "/")); + } + false +} + +fn builders_from(buildx_ls: &[Value], containers: &Value, kiri_context: &str, kiri_host: &str) -> Vec { + let have: Vec = containers + .as_array() + .into_iter() + .flatten() + .flat_map(|c| c["Names"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(|n| n.trim_start_matches('/').to_owned()))) + .collect(); + let mut found = Vec::new(); + for b in buildx_ls { + if b["Driver"] != "docker-container" { + continue; + } + let on_kiri = b["Nodes"].as_array().into_iter().flatten().any(|n| { + endpoint_is_kiri(n["Endpoint"].as_str(), kiri_context, kiri_host) + && n["Name"].as_str().is_some_and(|name| have.iter().any(|c| *c == format!("buildx_buildkit_{name}"))) + }); + if on_kiri + && let Some(name) = b["Name"].as_str() + && !name.is_empty() + && !found.iter().any(|existing| existing == name) + { + found.push(name.to_owned()); + } + } + found +} + +/// The docker-container builders on Kiri's engine whose BuildKit container exists. /// No buildx plugin (a distribution's plain docker CLI) means no builds yet, not an error. fn builders() -> io::Result> { // Without the plugin, docker reads `buildx` as an unknown command or flag. @@ -45,22 +97,8 @@ fn builders() -> io::Result> { return Ok(Vec::new()); } let (out, _) = buildx(&["ls", "--format", "json"])?; - let have: Vec = crate::client::get_background("/containers/json?all=1")? - .as_array() - .into_iter() - .flatten() - .flat_map(|c| c["Names"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(|n| n.trim_start_matches('/').to_owned()))) - .collect(); - Ok(values(&out) - .into_iter() - .filter(|b| b["Driver"] == "docker-container") - .filter(|b| { - b["Nodes"].as_array().into_iter().flatten().any(|n| { - n["Endpoint"] == CONTEXT.get() && n["Name"].as_str().is_some_and(|name| have.iter().any(|c| *c == format!("buildx_buildkit_{name}"))) - }) - }) - .filter_map(|b| b["Name"].as_str().map(str::to_owned)) - .collect()) + let containers = crate::client::get_background("/containers/json?all=1")?; + Ok(builders_from(&values(&out), &containers, CONTEXT.get(), &kiri_host()?)) } /// The newest builds first, from every builder: {builder, id, name, status, @@ -83,10 +121,14 @@ pub fn list() -> io::Result> { Ok(all) } +fn valid_build_ref(builder: &str, id: &str) -> bool { + !builder.is_empty() && !builder.starts_with('-') && !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric()) +} + /// One build: the record, its steps in the order they ran (each with its /// start, end, cached, error and output) and its warnings. pub fn detail(builder: &str, id: &str) -> io::Result { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } let (info, _) = buildx(&["history", "inspect", "--builder", builder, id, "--format", "json"])?; @@ -172,7 +214,7 @@ pub fn detail(builder: &str, id: &str) -> io::Result { /// config, read from the manifest and config BuildKit keeps with the record. /// Builds that made no image (cache only, or failed) have none. pub fn layers(builder: &str, id: &str) -> io::Result { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } let (info, _) = buildx(&["history", "inspect", "--builder", builder, id, "--format", "json"])?; @@ -271,7 +313,7 @@ pub(crate) fn image(manifest: &Value, config: &Value, platform: Option<&str>) -> /// Removes a build from the history. pub fn remove(builder: &str, id: &str) -> io::Result<()> { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } already_gone(buildx(&["history", "rm", "--builder", builder, id]).map(|_| ()), id, || listed(builder, id)) @@ -470,6 +512,62 @@ mod tests { assert_eq!(values("{\"a\":1}\n{\"a\":2}").len(), 2); assert_eq!(values("{\"a\":1}{\"a\":2}").len(), 2); } + + #[test] + fn discovers_every_buildkit_builder_on_kiris_engine() { + let host = "unix:///Users/alice/.kiri/run/docker.sock"; + let buildx_ls = vec![ + json!({"Name": "kiri-build", "Driver": "docker-container", "Nodes": [{"Name": "kiri-build0", "Endpoint": "kiri"}]}), + json!({"Name": "default", "Driver": "docker-container", "Nodes": [{"Name": "default", "Endpoint": "default"}]}), + json!({"Name": "compose-url", "Driver": "docker-container", "Nodes": [{"Name": "compose-url0", "Endpoint": host}]}), + json!({"Name": "custom-kiri", "Driver": "docker-container", "Nodes": [{"Name": "custom-kiri0", "Endpoint": "kiri"}]}), + // Duplicate name must appear only once, keeping first-seen order. + json!({"Name": "kiri-build", "Driver": "docker-container", "Nodes": [{"Name": "kiri-build0", "Endpoint": "kiri"}]}), + // Builder on Kiri without an existing BuildKit container must be skipped (never wake/create). + json!({"Name": "not-started", "Driver": "docker-container", "Nodes": [{"Name": "not-started0", "Endpoint": "kiri"}]}), + json!({"Name": "default-missing", "Driver": "docker-container", "Nodes": [{"Name": "default-missing0", "Endpoint": "default"}]}), + // Non-docker-container driver must be skipped. + json!({"Name": "plain-docker", "Driver": "docker", "Nodes": [{"Name": "default", "Endpoint": "default"}]}), + // Foreign contexts / sockets must be rejected even if a container of that name exists. + json!({"Name": "desktop-builder", "Driver": "docker-container", "Nodes": [{"Name": "desktop-builder0", "Endpoint": "desktop-linux"}]}), + json!({"Name": "orb-builder", "Driver": "docker-container", "Nodes": [{"Name": "orb-builder0", "Endpoint": "orbstack"}]}), + json!({"Name": "other-sock", "Driver": "docker-container", "Nodes": [{"Name": "other-sock0", "Endpoint": "unix:///var/run/other.sock"}]}), + ]; + let containers = json!([ + {"Names": ["/buildx_buildkit_kiri-build0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_default"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_compose-url0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_custom-kiri0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_desktop-builder0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_orb-builder0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_other-sock0"], "Image": "moby/buildkit:buildx-stable-1"}, + ]); + let found = builders_from(&buildx_ls, &containers, "kiri", host); + assert_eq!(found, vec!["kiri-build", "default", "compose-url", "custom-kiri"]); + } + + #[test] + fn matches_windows_npipe_endpoints_case_and_slash_insensitively() { + let host = "npipe:////./pipe/kiri"; + let buildx_ls = vec![ + json!({"Name": "default", "Driver": "docker-container", "Nodes": [{"Name": "default", "Endpoint": r"NPIPE://\\.\pipe\KIRI"}]}), + json!({"Name": "other-pipe", "Driver": "docker-container", "Nodes": [{"Name": "other-pipe0", "Endpoint": "npipe:////./pipe/docker_engine"}]}), + ]; + let containers = json!([ + {"Names": ["/buildx_buildkit_default"]}, + {"Names": ["/buildx_buildkit_other-pipe0"]}, + ]); + assert_eq!(builders_from(&buildx_ls, &containers, "kiri", host), vec!["default"]); + } + + #[test] + fn rejects_empty_or_flag_like_builder_in_detail_layers_and_remove() { + for (builder, id) in [("", "abc123"), ("-bad", "abc123"), ("--builder", "abc123"), ("kiri-build", ""), ("kiri-build", "bad/id")] { + assert_eq!(detail(builder, id).unwrap_err().to_string(), "not a build", "detail({builder:?}, {id:?})"); + assert_eq!(layers(builder, id).unwrap_err().to_string(), "not a build", "layers({builder:?}, {id:?})"); + assert_eq!(remove(builder, id).unwrap_err().to_string(), "not a build", "remove({builder:?}, {id:?})"); + } + } } /// An image in a real store: diff --git a/docs/fix-registry.md b/docs/fix-registry.md index df192d3a3..52edb3d16 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 +### #456 Builds: include Kiri's default BuildKit builder from compose builds (unreleased) +- Fixes: #456 Builds view misses `docker compose build` history from Kiri's `default` builder +- Caused: none known +- Caused by: - +- Check: none + ### #757 API: accept RFC 9112 §3.2.2 absolute-form HTTP request targets on the Docker socket (unreleased) - Fixes: #757 `GET http://127.0.0.1:2376/containers/json HTTP/1.1` over the Docker socket fails with 404 (dockerode / docker-modem / Lando) - Caused: none known From 24252d57b2559fa326deda081d0a35303bfe83dc Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:45:59 +0100 Subject: [PATCH 051/157] Import: strip OrbStack /mnt/mac prefix from imported host bind mounts (#411) (#835) --- crates/kiri/src/import.rs | 311 ++++++++++++++++++++++++++++++++++++-- docs/fix-registry.md | 6 + tests/import.sh | 20 ++- tests/regressions.tsv | 3 + 4 files changed, 325 insertions(+), 15 deletions(-) diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index d212d332d..9e442f492 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -833,7 +833,7 @@ pub fn container_with(source: &str, name: &str, force: bool, joining: &[&str]) - let info = json_lines(ctx, &["inspect", "--type", "container", "--format", "{{json .}}", name])?.into_iter().next().ok_or_else(|| io::Error::other(format!("{name}: not found in {ctx}")))?; let image = info["Config"]["Image"].as_str().unwrap_or("").to_owned(); if !has(kiri, "image", &image) { - self::image(source, &image)?; + self::image(source, &image).map_err(|e| io::Error::other(format!("image {image}: {e}")))?; } // Else create would make them in Kiri, empty. for v in volumes_of(&info) { @@ -869,11 +869,73 @@ pub fn container_with(source: &str, name: &str, force: bool, joining: &[&str]) - } let r = client::request("POST", &format!("/containers/create?name={name}"), Some(&create_body(&info, &mode, networks.into())))?; if !r.ok() { - return Err(io::Error::other(r.error())); + return Err(io::Error::other(create_error(r.status, &r.error()))); } Ok(()) } +/// Non-empty reason for a failed `/containers/create` call, falling back to +/// the HTTP status if the daemon returned an empty body (#411). +fn create_error(status: u16, msg: &str) -> String { + let trimmed = msg.trim(); + if trimmed.is_empty() { format!("HTTP {status}") } else { trimmed.to_owned() } +} + +/// Translates Docker Desktop's VM-internal host-mount paths to host paths Kiri +/// can bind directly (#411): +/// - macOS Docker Desktop: `/host_mnt/` -> `/` +/// - Windows Docker Desktop: `/run/desktop/mnt/host//` and +/// `/host_mnt//` -> `:/` +/// +/// Bare prefixes (`/host_mnt`, `/host_mnt/`, `/run/desktop/mnt/host/`), +/// look-alike prefixes (`/host_mnt_other/...`), and paths containing `..` +/// segments stay unchanged so normalization never collapses to `/` or +/// traverses outside the intended path. +fn translate_bind_source_for(src: &str, windows: bool) -> String { + let has_dotdot = |p: &str| p.split('/').any(|s| s == ".."); + let drive_path = |rest: &str| -> Option { + let trimmed = rest.trim_start_matches('/'); + if trimmed.is_empty() || has_dotdot(trimmed) { + return None; + } + let (drive, tail) = trimmed.split_once('/').unwrap_or((trimmed, "")); + if drive.len() != 1 || !drive.as_bytes()[0].is_ascii_alphabetic() { + return None; + } + let tail = tail.trim_start_matches('/'); + if tail.is_empty() { Some(format!("{}:/", drive.to_ascii_uppercase())) } else { Some(format!("{}:/{tail}", drive.to_ascii_uppercase())) } + }; + if windows { + if let Some(rest) = src.strip_prefix("/run/desktop/mnt/host/") { + return drive_path(rest).unwrap_or_else(|| src.to_owned()); + } + if let Some(rest) = src.strip_prefix("/host_mnt/") { + return drive_path(rest).unwrap_or_else(|| src.to_owned()); + } + return src.to_owned(); + } + if let Some(rest) = src.strip_prefix("/host_mnt/") { + let trimmed = rest.trim_start_matches('/'); + if !has_dotdot(trimmed) && trimmed.split('/').any(|s| !s.is_empty() && s != ".") { + return format!("/{trimmed}"); + } + } + src.to_owned() +} + +/// Translates the source side of a `HostConfig.Binds` entry (`SRC:DST[:OPTS]`), +/// preserving the destination and any mount options (`:ro`, `:delegated`, etc.). +fn translate_bind_spec_for(spec: &str, windows: bool) -> String { + let Some((src, rest)) = spec.split_once(':') else { + return spec.to_owned(); + }; + if !rest.starts_with('/') { + return spec.to_owned(); + } + let translated = translate_bind_source_for(src, windows); + if translated == src { spec.to_owned() } else { format!("{translated}:{rest}") } +} + /// The volumes a container has on the source, named and anonymous. fn volumes_of(info: &Value) -> Vec { let mut names: Vec = Vec::new(); @@ -893,6 +955,10 @@ fn volumes_of(info: &Value) -> Vec { /// new empty ones. Beside `container:` mode, what Docker and Kiri refuse /// there is left out: the source fills some of it in itself (#375). fn create_body(info: &Value, mode: &str, networks: Value) -> Value { + create_body_for(info, mode, networks, cfg!(windows)) +} + +fn create_body_for(info: &Value, mode: &str, networks: Value, windows: bool) -> Value { let (cfg, hc) = (&info["Config"], &info["HostConfig"]); let anon: Vec<(&str, &str, bool)> = info["Mounts"] .as_array() @@ -902,12 +968,29 @@ fn create_body(info: &Value, mode: &str, networks: Value) -> Value { .filter_map(|m| Some((m["Name"].as_str().filter(|n| anonymous(n))?, m["Destination"].as_str()?, m["RW"] != false))) .collect(); let mut mounts = hc["Mounts"].clone(); - for m in mounts.as_array_mut().into_iter().flatten().filter(|m| m["Type"] == "volume" && m["Source"].as_str().unwrap_or("").is_empty()) { - if let Some((n, _, _)) = anon.iter().find(|(_, d, _)| m["Target"].as_str() == Some(d)) { - m["Source"] = (*n).into(); + for m in mounts.as_array_mut().into_iter().flatten() { + if m["Type"] == "volume" && m["Source"].as_str().unwrap_or("").is_empty() { + if let Some((n, _, _)) = anon.iter().find(|(_, d, _)| m["Target"].as_str() == Some(d)) { + m["Source"] = (*n).into(); + } + } else if m["Type"].as_str().unwrap_or("bind") == "bind" + && let Some(src) = m["Source"].as_str() + { + let translated = translate_bind_source_for(src, windows); + if translated != src { + m["Source"] = translated.into(); + } } } let mut binds = hc["Binds"].clone(); + for b in binds.as_array_mut().into_iter().flatten() { + if let Some(spec) = b.as_str() { + let translated = translate_bind_spec_for(spec, windows); + if translated != spec { + *b = translated.into(); + } + } + } for (n, d, rw) in &anon { if !mounts.as_array().into_iter().flatten().any(|m| m["Target"].as_str() == Some(d)) { let bind = format!("{n}:{d}{}", if *rw { "" } else { ":ro" }); @@ -1049,12 +1132,14 @@ pub fn run(args: &[String]) -> io::Result<()> { } return Ok(()); } - let mut failed = 0; - let mut step = |what: &str, name: &str, r: io::Result<()>| match r { + let mut failures: Vec<(&str, String, String)> = Vec::new(); + let mut step = |what: &'static str, name: &str, r: io::Result<()>| match r { Ok(()) => println!("{what} {name}: done"), Err(e) => { - failed += 1; - println!("{what} {name}: {e}"); + let reason = e.to_string(); + let why = if reason.trim().is_empty() { "unknown error" } else { reason.trim() }; + println!("{what} {name}: skipped ({why})"); + failures.push((what, name.to_owned(), why.to_owned())); } }; for v in list("images").iter().filter(|v| v["have"] != true) { @@ -1065,14 +1150,41 @@ pub fn run(args: &[String]) -> io::Result<()> { let n = v["name"].as_str().unwrap_or(""); step("volume", n, volume_with(source, n, force)); } - for v in list("containers").iter().filter(|v| v["have"] != true) { + for v in list("containers") { let n = v["name"].as_str().unwrap_or(""); - // Already brought as the one another joins the network of. - if !has(crate::flavor::CONTEXT.get(), "container", n) { - step("container", n, container_with(source, n, force, &[])); + let already_had = v["have"] == true; + let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); + if let Some(why) = container_skip_reason(already_had, already_imported) { + println!("container {n}: skipped ({why})"); + continue; } + step("container", n, container_with(source, n, force, &[])); } - if failed > 0 { Err(io::Error::other(format!("{failed} items could not be imported"))) } else { Ok(()) } + if !failures.is_empty() { Err(io::Error::other(format_failures(&failures))) } else { Ok(()) } +} + +/// Why a container in `kiri import` is skipped without calling `container_with` (#411). +fn container_skip_reason(already_had: bool, already_imported: bool) -> Option<&'static str> { + if already_had { + Some("already in Kiri") + } else if already_imported { + Some("already imported as a network target") + } else { + None + } +} + +/// Summary returned when one or more items could not be imported, naming each +/// item and its reason so nothing is skipped silently (#411). +fn format_failures(failures: &[(&str, String, String)]) -> String { + let n = failures.len(); + let items = if n == 1 { "item" } else { "items" }; + let mut out = format!("{n} {items} could not be imported:"); + for (kind, name, reason) in failures { + let why = if reason.trim().is_empty() { "unknown error" } else { reason.trim() }; + out.push_str(&format!("\n {kind} {name}: {why}")); + } + out } #[cfg(test)] @@ -1623,4 +1735,175 @@ mod tests { assert_eq!(seen, [("odd size=5 name".to_owned(), 3_000_000, body), ("next".to_owned(), 0, b"abc".to_vec())]); } + // #411: Docker Desktop's `/host_mnt/` bind-mount sources map to + // `/` on macOS in both HostConfig.Binds (keeping mount options) and + // HostConfig.Mounts, while non-/host_mnt binds and edge cases stay intact. + #[test] + fn translates_docker_desktop_host_mnt_binds() { + use serde_json::json; + let info = json!({ + "Config": {"Image": "postgres:16"}, + "HostConfig": { + "Binds": [ + "/host_mnt/Users/alice/project/docker/volumes/db/data:/var/lib/postgresql/data", + "/Users/alice/project/docker/volumes/db/pooler.sql:/docker-entrypoint-initdb.d/99-pooler.sql:ro", + "/host_mnt/Users/alice/app:/app:delegated", + "/host_mnt/private/tmp/x:/tmp/x:rw,cached", + "/host_mnt/Users/alice/cfg:/cfg:ro", + "/host_mnt/Users/alice/rw:/rw:rw", + "/host_mnt/Users/alice/selinux:/selinux:z", + "/host_mnt/Users/alice/selinux2:/selinux2:Z", + "/host_mnt/Users/alice/dir..name/file:/file", + "/host_mnt//Users/alice/double:/double", + "/host_mnt:/bare", + "/host_mnt/:/bare-slash", + "/host_mnt///:/bare-slashes", + "/host_mnt/.:/bare-dot", + "/host_mnt/..:/dotdot", + "/host_mnt/../etc:/escape", + "/host_mnt/Users/../etc:/mid-dotdot", + "/host_mnt_other/Users/alice:/other", + "pgdata:/pgdata" + ], + "Mounts": [ + {"Type": "bind", "Source": "/host_mnt/Users/alice/data", "Target": "/data", "ReadOnly": true}, + {"Type": "bind", "Source": "/Users/alice/plain", "Target": "/plain"}, + {"Type": "bind", "Source": "/host_mnt", "Target": "/m-bare"}, + {"Type": "bind", "Source": "/host_mnt/", "Target": "/m-slash"}, + {"Type": "bind", "Source": "/host_mnt/.", "Target": "/m-dot"}, + {"Type": "bind", "Source": "/host_mnt/..", "Target": "/m-dotdot"}, + {"Type": "bind", "Source": "/host_mnt_other/x", "Target": "/m-other"}, + {"Type": "volume", "Source": "pgvol", "Target": "/vol"} + ] + }, + "Mounts": [] + }); + let body = super::create_body_for(&info, "bridge", json!({}), false); + assert_eq!( + body["HostConfig"]["Binds"], + json!([ + "/Users/alice/project/docker/volumes/db/data:/var/lib/postgresql/data", + "/Users/alice/project/docker/volumes/db/pooler.sql:/docker-entrypoint-initdb.d/99-pooler.sql:ro", + "/Users/alice/app:/app:delegated", + "/private/tmp/x:/tmp/x:rw,cached", + "/Users/alice/cfg:/cfg:ro", + "/Users/alice/rw:/rw:rw", + "/Users/alice/selinux:/selinux:z", + "/Users/alice/selinux2:/selinux2:Z", + "/Users/alice/dir..name/file:/file", + "/Users/alice/double:/double", + "/host_mnt:/bare", + "/host_mnt/:/bare-slash", + "/host_mnt///:/bare-slashes", + "/host_mnt/.:/bare-dot", + "/host_mnt/..:/dotdot", + "/host_mnt/../etc:/escape", + "/host_mnt/Users/../etc:/mid-dotdot", + "/host_mnt_other/Users/alice:/other", + "pgdata:/pgdata" + ]) + ); + assert_eq!( + body["HostConfig"]["Mounts"], + json!([ + {"Type": "bind", "Source": "/Users/alice/data", "Target": "/data", "ReadOnly": true}, + {"Type": "bind", "Source": "/Users/alice/plain", "Target": "/plain"}, + {"Type": "bind", "Source": "/host_mnt", "Target": "/m-bare"}, + {"Type": "bind", "Source": "/host_mnt/", "Target": "/m-slash"}, + {"Type": "bind", "Source": "/host_mnt/.", "Target": "/m-dot"}, + {"Type": "bind", "Source": "/host_mnt/..", "Target": "/m-dotdot"}, + {"Type": "bind", "Source": "/host_mnt_other/x", "Target": "/m-other"}, + {"Type": "volume", "Source": "pgvol", "Target": "/vol"} + ]) + ); + } + + // #411: Windows Docker Desktop bind sources under `/run/desktop/mnt/host//...` + // and `/host_mnt//...` translate to `:/...` so Kiri's WSL bind + // parser maps them to the active automount root; `/mnt/wsl/...`, look-alikes, + // non-drive prefixes and `..` traversals stay unchanged. + #[test] + fn translates_windows_docker_desktop_binds() { + use serde_json::json; + let info = json!({ + "Config": {"Image": "alpine"}, + "HostConfig": { + "Binds": [ + "/run/desktop/mnt/host/c/Users/alice/app:/app:ro", + "/run/desktop/mnt/host/d/work/db:/data:delegated", + "/run/desktop/mnt/host/c:/drive-root", + "/host_mnt/c/Users/alice/legacy:/legacy:rw", + "C:\\Users\\alice\\native:/native", + "/mnt/wsl/shared:/shared", + "/run/desktop/mnt/host:/bare", + "/run/desktop/mnt/host/:/bare-slash", + "/run/desktop/mnt/host/..:/dotdot", + "/run/desktop/mnt/host/c/../d/secret:/escape", + "/run/desktop/mnt/host/wsl/foo:/not-drive", + "/run/desktop/mnt/host_other/c/foo:/lookalike", + "/host_mnt/Users/alice:/non-drive-host-mnt", + "/host_mnt_other/c/foo:/host-mnt-lookalike" + ], + "Mounts": [ + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/Users/alice/cfg", "Target": "/cfg", "ReadOnly": true}, + {"Type": "bind", "Source": "/host_mnt/e/files", "Target": "/files"}, + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/../x", "Target": "/bad"}, + {"Type": "bind", "Source": "/mnt/wsl/shared", "Target": "/shared2"} + ] + }, + "Mounts": [] + }); + let body = super::create_body_for(&info, "bridge", json!({}), true); + assert_eq!( + body["HostConfig"]["Binds"], + json!([ + "C:/Users/alice/app:/app:ro", + "D:/work/db:/data:delegated", + "C:/:/drive-root", + "C:/Users/alice/legacy:/legacy:rw", + "C:\\Users\\alice\\native:/native", + "/mnt/wsl/shared:/shared", + "/run/desktop/mnt/host:/bare", + "/run/desktop/mnt/host/:/bare-slash", + "/run/desktop/mnt/host/..:/dotdot", + "/run/desktop/mnt/host/c/../d/secret:/escape", + "/run/desktop/mnt/host/wsl/foo:/not-drive", + "/run/desktop/mnt/host_other/c/foo:/lookalike", + "/host_mnt/Users/alice:/non-drive-host-mnt", + "/host_mnt_other/c/foo:/host-mnt-lookalike" + ]) + ); + assert_eq!( + body["HostConfig"]["Mounts"], + json!([ + {"Type": "bind", "Source": "C:/Users/alice/cfg", "Target": "/cfg", "ReadOnly": true}, + {"Type": "bind", "Source": "E:/files", "Target": "/files"}, + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/../x", "Target": "/bad"}, + {"Type": "bind", "Source": "/mnt/wsl/shared", "Target": "/shared2"} + ]) + ); + } + + // #411: every container not imported has an explicit reason (never dropped + // silently or left with a blank error). + #[test] + fn reports_skip_and_failure_reasons() { + assert_eq!(super::container_skip_reason(true, false), Some("already in Kiri")); + assert_eq!(super::container_skip_reason(false, true), Some("already imported as a network target")); + assert_eq!(super::container_skip_reason(false, false), None); + assert_eq!(super::create_error(400, "bind source path does not exist"), "bind source path does not exist"); + assert_eq!(super::create_error(500, " "), "HTTP 500"); + assert_eq!( + super::format_failures(&[("container", "db".into(), "bind source path does not exist".into())]), + "1 item could not be imported:\n container db: bind source path does not exist" + ); + assert_eq!( + super::format_failures(&[ + ("container", "db".into(), "missing bind".into()), + ("container", "web".into(), "".into()), + ]), + "2 items could not be imported:\n container db: missing bind\n container web: unknown error" + ); + } + } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 52edb3d16..c9b1e046a 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 +### #411 Import: translate Docker Desktop `/host_mnt` and `/run/desktop/mnt/host` bind sources and report reasons for unimported containers (unreleased) +- Fixes: #411 Docker Desktop import: containers with `/host_mnt` bind-mount sources are skipped silently +- Caused: none known +- Caused by: - +- Check: `import-host-mnt-container`, `import-host-mnt-binds`, `import-host-mnt-reads` + ### #456 Builds: include Kiri's default BuildKit builder from compose builds (unreleased) - Fixes: #456 Builds view misses `docker compose build` history from Kiri's `default` builder - Caused: none known diff --git a/tests/import.sh b/tests/import.sh index 59919f10e..64523f315 100755 --- a/tests/import.sh +++ b/tests/import.sh @@ -75,12 +75,13 @@ kiri_rm() { for v in $v; do [[ "$v" =~ ^[0-9a-f]{64}$ ]] && "${K[@]}" volume rm -f "$v" >/dev/null 2>&1; done done } -OURS_C="imp-digest imp-net-joiner imp-net-target imp-vol-user imp-vol-writer imp-vol-idle imp-vol-cutter imp-vol-kiri-user imp-vol-kiri-paused imp-vol-kiri-again imp-vol-kiri-stopped" +OURS_C="imp-digest imp-host-mnt imp-net-joiner imp-net-target imp-vol-user imp-vol-writer imp-vol-idle imp-vol-cutter imp-vol-kiri-user imp-vol-kiri-paused imp-vol-kiri-again imp-vol-kiri-stopped" # An image named like an official one, with a creation date ahead: its # sh, tar, rm and find leave a mark and refuse the work. Never to be run. LOOKALIKE=localhost/imp-x/library/busybox:9 UNTAGGED_ID= LA_DIR= +HM_DIR= OURS_V="imp-vol-la imp-vol-la-new imp-vol-data imp-vol-xattrs imp-vol-named imp-vol-keep imp-vol-busy imp-vol-huge imp-vol-cut imp-probe" cleanup() { kiri_rm $OURS_C @@ -95,6 +96,7 @@ cleanup() { for ctx in "$SRC" "$DOCKER_CONTEXT"; do docker --context "$ctx" rmi "$LOOKALIKE" >/dev/null 2>&1; done [ -n "$UNTAGGED_ID" ] && "${K[@]}" rmi "$UNTAGGED_ID" >/dev/null 2>&1 [ -n "$LA_DIR" ] && rm -rf "$LA_DIR" + [ -n "$HM_DIR" ] && rm -rf "$HM_DIR" rm -f /tmp/imp-cut-seen.$$ [ -n "$PINNED_OURS" ] && "${S[@]}" rmi "$PINNED" >/dev/null 2>&1 for i in ${FETCHED_SRC[@]+"${FETCHED_SRC[@]}"}; do "${S[@]}" rmi "$i" >/dev/null 2>&1; done @@ -406,5 +408,21 @@ t digest-kept-on-container "$PINNED" "${K[@]}" inspect -f '{{.Config.Image}}' im t digest-image-by-reference "[\"$PINNED\"]" "${K[@]}" image inspect -f '{{json .RepoTags}}' "$PINNED" t digest-runs "Hello from Docker" "${K[@]}" start -a imp-digest +section "#411 Docker Desktop /host_mnt bind-mount sources" +HM_DIR=$(mktemp -d /tmp/imp-hm.XXXXXX) +printf 'from-host-mnt\n' > "$HM_DIR/a.txt" +printf 'from-direct\n' > "$HM_DIR/b.txt" +"${S[@]}" create --name imp-host-mnt --network none \ + -v "/host_mnt${HM_DIR}:/from-host-mnt:ro,delegated" \ + -v "${HM_DIR}/b.txt:/from-direct:ro" \ + --entrypoint sh "$TOOL" -c 'echo "$(cat /from-host-mnt/a.txt) $(cat /from-direct)"' >/dev/null +t import-host-mnt-container "container imp-host-mnt: done" "$KIRI" import "$SRC" container imp-host-mnt +t import-host-mnt-binds "ok" bash -c ' + got=$("$1" --context "$2" inspect -f "{{json .HostConfig.Binds}}" imp-host-mnt) + python3 -c "import json, sys; b = set(json.loads(sys.argv[1]) or []); d = sys.argv[2]; want = {f\"{d}:/from-host-mnt:ro,delegated\", f\"{d}/b.txt:/from-direct:ro\"}; print(\"ok\" if b == want else sorted(b))" "$got" "$3" +' _ docker "$DOCKER_CONTEXT" "$HM_DIR" +t import-host-mnt-reads "from-host-mnt from-direct" "${K[@]}" start -a imp-host-mnt +kiri_rm imp-host-mnt + printf '\n%d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] || { printf 'failed: %s\n' "${FAILED[*]}"; exit 1; } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index f329addca..9d3bc80d1 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -283,3 +283,6 @@ tests/ui/storage-location.js #355 Settings → Storage had no way to move images network-ipv6-subnet-ignored-when-disabled #433 POST /networks/create with EnableIPv6 false (or omitted) and an IPv6 subnet in IPAM.Config was refused instead of ignoring the IPv6 subnet as Docker does (mailcow-dockerized) absolute-form-ping #757 an RFC 9112 §3.2.2 absolute-form request-target over the Docker socket left the scheme and authority in the path and answered 404 absolute-form-containers #757 docker-modem requests such as GET http://127.0.0.1:2376/containers/json HTTP/1.1 over the Docker socket answered 404 instead of routing /containers/json +import-host-mnt-container #411 importing a container with a Docker Desktop /host_mnt bind-mount source did not translate the path to the host path +import-host-mnt-binds #411 imported container HostConfig.Binds kept the /host_mnt prefix or dropped bind mount options instead of stripping /host_mnt +import-host-mnt-reads #411 a container imported with a /host_mnt bind source mounted an empty VM directory instead of the host files From 4aeabd44ebc303d965987360c2deed1e0251f1a4 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:29 +0100 Subject: [PATCH 052/157] Windows: replace JSON config files atomically via MoveFileExW (#493) (#838) Co-authored-by: AD PAO <266653520+paopaonyapi-creator@users.noreply.github.com> --- crates/kiri-image/src/jsonfile.rs | 44 ++++++++++++++++++++++++++++++- docs/fix-registry.md | 6 +++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/kiri-image/src/jsonfile.rs b/crates/kiri-image/src/jsonfile.rs index 2aacc95d0..d29953db9 100644 --- a/crates/kiri-image/src/jsonfile.rs +++ b/crates/kiri-image/src/jsonfile.rs @@ -77,7 +77,7 @@ pub fn replace(path: &Path, bytes: &[u8], durable: Durable) -> io::Result<()> { /// folder, so the rename itself is on disk. Nothing to do if there is no /// file (yet). pub fn sync(path: &Path) -> io::Result<()> { - match File::open(path) { + match open_for_sync(path) { Ok(f) => synced(&f)?, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), Err(e) => return Err(e), @@ -86,6 +86,20 @@ pub fn sync(path: &Path) -> io::Result<()> { Ok(()) } +/// Opens `path` so [`File::sync_all`] can flush it. Windows' +/// `FlushFileBuffers` rejects a read-only handle (`ERROR_ACCESS_DENIED`), +/// so ask for write access (without creating, truncating or modifying +/// anything) and fall back to read-only when the file cannot be opened for +/// writing. +fn open_for_sync(path: &Path) -> io::Result { + fs::OpenOptions::new().read(true).write(true).open(path).or_else(|e| match e.kind() { + io::ErrorKind::PermissionDenied + | io::ErrorKind::ReadOnlyFilesystem + | io::ErrorKind::IsADirectory => File::open(path), + _ => Err(e), + }) +} + fn parent(path: &Path) -> &Path { path.parent().unwrap_or(Path::new(".")) } @@ -231,6 +245,34 @@ mod tests { let _ = fs::remove_dir_all(d); } + #[test] + fn sync_keeps_contents_and_falls_back_read_only() { + let d = dir("sync"); + let p = d.join("list.json"); + let missing = d.join("missing.json"); + fs::write(&p, b"[1,2]").unwrap(); + + let before = syncs_here(); + sync(&p).unwrap(); + assert_eq!(syncs_here(), before + 1); + assert_eq!(fs::read(&p).unwrap(), b"[1,2]"); + + sync(&missing).unwrap(); + assert!(!missing.exists(), "sync never creates a missing file"); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&p, fs::Permissions::from_mode(0o444)).unwrap(); + sync(&p).unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"[1,2]"); + sync(&d).unwrap(); + fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); + } + + let _ = fs::remove_dir_all(d); + } + #[test] fn move_aside_keeps_the_bytes_and_is_listed() { let d = dir("aside"); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index c9b1e046a..3461015aa 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 +### #493 Windows: open jsonfile for writing before sync so FlushFileBuffers succeeds (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: #452 +- Check: none + ### #411 Import: translate Docker Desktop `/host_mnt` and `/run/desktop/mnt/host` bind sources and report reasons for unimported containers (unreleased) - Fixes: #411 Docker Desktop import: containers with `/host_mnt` bind-mount sources are skipped silently - Caused: none known From 885c9c7cd405dfc28c56cd89e56246a2de8376a4 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:01:34 +0100 Subject: [PATCH 053/157] Windows: cancel in-flight image pulls cleanly when the client disconnects (#259) (#842) Co-authored-by: AD PAO <266653520+paopaonyapi-creator@users.noreply.github.com> --- crates/kiri-image/src/cancel.rs | 36 ++++++++++++++++++- crates/kiri-image/src/connect.rs | 59 ++++++++++++++++++++++++++++++- crates/kiri-image/src/registry.rs | 34 ++++++++++++++++++ docs/fix-registry.md | 6 ++++ 4 files changed, 133 insertions(+), 2 deletions(-) diff --git a/crates/kiri-image/src/cancel.rs b/crates/kiri-image/src/cancel.rs index a87a9a90d..bd537a48b 100644 --- a/crates/kiri-image/src/cancel.rs +++ b/crates/kiri-image/src/cancel.rs @@ -13,6 +13,24 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; +/// Windows does not reliably interrupt a blocking Winsock read when another +/// thread calls `shutdown`, so a cancellable read must not block for longer +/// than one poll: it runs nonblocking, and a poll with nothing to read waits +/// [`POLL`]. Everywhere else (Linux, or a pull no one can cancel) reads stay +/// blocking with the full budget, exactly as before. +pub(crate) const POLL: Duration = Duration::from_millis(100); + +/// Whether the current thread is inside a cancellable pull, on Windows. +/// Only there can a cross-thread `shutdown` leave the blocking recv asleep. +pub(crate) fn polling() -> bool { + cfg!(windows) && active() +} + +/// Whether the current thread is inside a cancellable pull. +pub(crate) fn active() -> bool { + CURRENT.with(|c| c.borrow().is_some()) +} + /// A pull's cancel switch. Clones share it. #[derive(Debug, Clone, Default)] pub struct Cancel(Arc); @@ -126,7 +144,23 @@ mod tests { let _on = cancel.enter(); watch(&client).unwrap(); let started = Instant::now(); - let n = (&*client).read(&mut [0u8; 16]).unwrap_or(0); + // The transport reads nonblocking under a cancellable pull on + // Windows (blocking Winsock reads ignore a cross-thread + // shutdown). A raw read must still end promptly once the + // switch flips, so poll the switch like await_input does. + let n = if polling() { + client.set_nonblocking(true).unwrap(); + loop { + match (&*client).read(&mut [0u8; 16]) { + Err(e) if e.kind() == io::ErrorKind::WouldBlock && !cancel.is_cancelled() => { + std::thread::sleep(Duration::from_millis(50)); + } + res => break res.unwrap_or(0), + } + } + } else { + (&*client).read(&mut [0u8; 16]).unwrap_or(0) + }; (n, started.elapsed()) }) }; diff --git a/crates/kiri-image/src/connect.rs b/crates/kiri-image/src/connect.rs index 9668b4211..8d534f15b 100644 --- a/crates/kiri-image/src/connect.rs +++ b/crates/kiri-image/src/connect.rs @@ -247,6 +247,46 @@ impl Transport for TcpTransport { crate::cancel::watch(&self.stream)?; let started = Instant::now(); let input = self.buffers.input_append_buf(); + // Windows inside a cancellable pull: a cross-thread `shutdown` may + // leave the blocking recv asleep (verified: it waited out its whole + // timeout past the shutdown), so read nonblocking and check the + // cancel switch at most every POLL. `limit` stays the one full + // budget for this call: a poll that finds nothing loops on, it does + // not end the read; only `limit` running out does. Everywhere else + // the plain blocking read below keeps the socket timeout semantics + // unchanged. + if crate::cancel::polling() { + self.stream.set_nonblocking(true)?; + let result = loop { + if crate::cancel::current_cancelled() { + break Err(Error::Io(io::Error::other("pull cancelled"))); + } + match (&*self.stream).read(input) { + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + // Nothing yet: wait one poll, then check the switch again. + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + let left = limit.map(|l| l.saturating_sub(started.elapsed())); + if left.is_some_and(|l| l.is_zero()) { + break Err(Error::Timeout(timeout.reason)); + } + std::thread::sleep(left.map_or(crate::cancel::POLL, |l| l.min(crate::cancel::POLL))); + } + // EOF, or a real error (a shutdown from the cancel side + // reads as ConnectionAborted/Reset): restore the mode, + // and report a cancelled pull as its own error. + Ok(n) => break Ok(n), + Err(_) if crate::cancel::current_cancelled() => { + break Err(Error::Io(io::Error::other("pull cancelled"))); + } + Err(e) => break Err(io_error(e, timeout.reason)), + } + }; + let restore = self.stream.set_nonblocking(false); + let amount = result?; + restore?; + self.buffers.input_appended(amount); + return Ok(amount > 0); + } let amount = loop { match (&*self.stream).read(input) { // A signal: Linux does not restart a socket read that has a @@ -262,7 +302,24 @@ impl Transport for TcpTransport { self.stream.set_read_timeout(Some(left))?; self.timeout_read = Some(left); } - result => break result.map_err(|e| io_error(e, timeout.reason))?, + result => { + break result.map_err(|e| { + if crate::cancel::current_cancelled() + && matches!( + e.kind(), + io::ErrorKind::TimedOut + | io::ErrorKind::WouldBlock + | io::ErrorKind::ConnectionReset + | io::ErrorKind::ConnectionAborted + | io::ErrorKind::BrokenPipe + ) + { + Error::Io(io::Error::other("pull cancelled")) + } else { + io_error(e, timeout.reason) + } + })?; + } } }; self.buffers.input_appended(amount); diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 9c7865d72..26375d914 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -2658,6 +2658,40 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + #[test] + fn a_cancellable_download_keeps_its_read_budget_for_slow_data() { + let (data, digest) = blob(); + let body = data.clone(); + let (host, served) = blob_server(move |_, c| { + // Both response headers and body data may take longer than a + // cancellation poll. Neither is a stall within the 2 s budget. + std::thread::sleep(Duration::from_millis(400)); + let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()); + let _ = c.write_all(&body[..body.len() / 2]); + std::thread::sleep(Duration::from_millis(400)); + let _ = c.write_all(&body[body.len() / 2..]); + }); + let root = std::env::temp_dir().join(format!("kiri-slow-cancel-test-{}", std::process::id())); + let store = Store::open(&root).unwrap(); + let reference = Reference::parse(&format!("{host}/test/blob:1")).unwrap(); + let config = ureq::Agent::config_builder().http_status_as_error(false).build(); + let agent = ureq::Agent::with_parts(config, crate::connect::connector_with(Duration::from_secs(2)), ureq::unversioned::resolver::DefaultResolver::default()); + let client = Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None }; + let _ = client.base(&host); + let cancel = Cancel::new(); + let result = { + let _on = cancel.enter(); + client.download_with(&store, &reference, &digest, u64::MAX, None, &|_| {}, &cancel) + }; + quit(&host); + let requests = served.join().unwrap(); + let saved = store.has_blob(&digest, data.len() as u64); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(result.unwrap(), data.len() as u64); + assert!(saved); + assert_eq!(requests, [0], "slow data must not start a retry"); + } + #[test] fn a_cancelled_download_stops_at_once_and_leaves_nothing() { let (data, digest) = blob(); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 3461015aa..4146b7f3d 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 +### #259 Windows: cancellable pull reads on Windows (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #493 Windows: open jsonfile for writing before sync so FlushFileBuffers succeeds (unreleased) - Fixes: no issue - Caused: none known From a9a419c77b29d362b40f7e0c65cfe514f3448dcc Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:10:35 +0100 Subject: [PATCH 054/157] Windows: expand kiri-win unit tests for config, pipe, and CLI parsing (#652) (#843) Co-authored-by: h4nz4 <18464660+h4nz4@users.noreply.github.com> --- crates/kiri-win/src/term.rs | 5 ++-- crates/kiri/src/ui/compose.rs | 51 ++++++++++++++++++++++++++--------- docs/fix-registry.md | 6 +++++ 3 files changed, 47 insertions(+), 15 deletions(-) diff --git a/crates/kiri-win/src/term.rs b/crates/kiri-win/src/term.rs index 48aba41bd..98304de15 100644 --- a/crates/kiri-win/src/term.rs +++ b/crates/kiri-win/src/term.rs @@ -520,8 +520,9 @@ mod tests { EVENTS.lock().unwrap().push(tx); handle("open", "w1", &serde_json::json!({"shell": "cmd", "cols": 100, "rows": 20}), record); let typed = |s: &str| handle("input", "w1", &Value::String(termwire::b64(s.as_bytes())), record); - // cmd prints its prompt once it's ready for input. - output_until(&rx, "w1", ">"); + // cmd's banner: its prompt is the user's own (Clink's AutoRun draws `❯`, not `>`), + // and what is typed before it shows waits in the console's input. + output_until(&rx, "w1", "Microsoft Corporation"); typed("set /a 40+2 & echo. & echo DONE\r"); let (out, _) = output_until(&rx, "w1", "DONE"); assert!(out.contains("42"), "{out}"); diff --git a/crates/kiri/src/ui/compose.rs b/crates/kiri/src/ui/compose.rs index c43828d3f..1de0e1fc4 100644 --- a/crates/kiri/src/ui/compose.rs +++ b/crates/kiri/src/ui/compose.rs @@ -2321,7 +2321,8 @@ fn yaml_at(e: &str, p: &Project, full: bool) -> Option { /// `path` relative to `dir` (`../x/compose.yaml` outside it). fn relative(dir: &Path, path: &Path) -> String { - let (d, f) = (std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_owned()), std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned())); + // Plain on both sides: on Windows a canonical path is `\\?\C:\…`, one that isn't there stays `C:\…`. + let (d, f) = (real_path(dir).unwrap_or_else(|_| dir.to_owned()), real_path(path).unwrap_or_else(|_| path.to_owned())); let (a, b): (Vec<_>, Vec<_>) = (d.components().collect(), f.components().collect()); let same = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); let mut out = PathBuf::new(); @@ -5563,12 +5564,24 @@ mod tests { /// The docker CLI with no engine to reach (`config --environment` needs /// none) and an environment of its own, so a test sees only its `.env`. fn dcli() -> io::Result { - let mut c = Command::new(client::docker_cli().expect("a docker CLI")); + Ok(bare(Command::new(client::docker_cli().expect("a docker CLI")))) + } + + /// `c` with only what the docker CLI needs of this environment, and no + /// engine to reach. + fn bare(mut c: Command) -> Command { c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock"); - if let Some(d) = std::env::var_os("DOCKER_CONFIG") { - c.env("DOCKER_CONFIG", d); + // On Windows the CLI finds its plugins (compose) under USERPROFILE, and + // its network needs SystemRoot; HOME is not set there. + for k in ["DOCKER_CONFIG", "USERPROFILE", "SystemRoot"] { + if let Some(v) = std::env::var_os(k) { + c.env(k, v); + } } - Ok(c) + // As the app's own CLI: no console window for each of the tests' many runs. + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut c, 0x0800_0000); + c } fn dproj(d: &Path) -> Project { @@ -5832,7 +5845,7 @@ mod tests { let d = std::env::temp_dir().join(format!("kiri-compose-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); - std::fs::canonicalize(&d).unwrap() + real_path(&d).unwrap() } #[test] @@ -5976,7 +5989,7 @@ mod tests { fn outside(p: &Path) { std::fs::write(p, "services: {}\n# theirs\n").unwrap(); } - *BETWEEN.lock().unwrap() = Some((std::fs::canonicalize(&f).unwrap(), outside)); + *BETWEEN.lock().unwrap() = Some((real_path(&f).unwrap(), outside)); let r = save(&f, "services:\n a: {}\n", &base); *BETWEEN.lock().unwrap() = None; assert!(r.as_ref().is_err_and(changed), "{r:?}"); @@ -6061,6 +6074,17 @@ mod tests { assert!(!a.iter().any(|x| x.starts_with(r"\\?\")), "{a:?}"); } + #[test] + fn relative_names_a_file_inside_or_outside_an_existing_folder() { + let d = tdir("rel"); + std::fs::create_dir_all(d.join("sub")).unwrap(); + std::fs::write(d.join("sub/compose.yaml"), "services: {}\n").unwrap(); + assert_eq!(relative(&d, &d.join("sub/compose.yaml")), "sub/compose.yaml"); + assert_eq!(relative(&d, &d.join("../up.yaml")), "../up.yaml"); + assert_eq!(relative(&d, &d.parent().unwrap().join("up.yaml")), "../up.yaml"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn only_compose_files_open() { assert!(compose_text("name: x\nservices:\n web:\n image: nginx\n")); @@ -6868,7 +6892,7 @@ mod tests { let m = config(dcli, &p, Some(draft), &[]).unwrap(); let v = service_view("x", &m["services"]["x"]); assert_eq!(v["ports"], json!(["8080:80"])); - assert!(v["volumes"][0].as_str().unwrap().ends_with("certs/server.key:/k"), "{v}"); + assert!(v["volumes"][0].as_str().unwrap().replace('\\', "/").ends_with("certs/server.key:/k"), "{v}"); let _ = std::fs::remove_dir_all(&d); } @@ -7228,7 +7252,8 @@ mod tests { assert_eq!(m["services"]["inc"]["image"], "reg/app:${DB_PASSWORD}"); assert_eq!(m["services"]["deep"]["image"], "reg/deep:${DEEP_TOKEN}"); assert_eq!(m["services"]["long"]["image"], "reg/long:${API_SECRET}"); - assert!(text.contains("/sub/data/${DB_PASSWORD}"), "{text}"); + // On Windows a JSON string's `\` is `\\`. + assert!(text.replace(r"\\", "/").contains("/sub/data/${DB_PASSWORD}"), "{text}"); // An error that quotes the value names the variable. std::fs::write(d.join("sub/compose.yaml"), "services:\n inc:\n image: alpine\n ports: [\"${DB_PASSWORD}:80\"]\n").unwrap(); let e = config(dcli, &p, None, &[]).unwrap_err(); @@ -8055,8 +8080,8 @@ mod tests { fn hangs() -> io::Result { let docker = client::docker_cli().expect("a docker CLI"); let script = format!("case \"$*\" in *'config --quiet'*) sleep 5; exit 1;; esac; exec '{}' \"$@\"", std::path::Path::new(&docker).display()); - let mut c = Command::new("sh"); - c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock").args(["-c", &script, "sh"]); + let mut c = bare(Command::new("sh")); + c.args(["-c", &script, "sh"]); Ok(c) } let d = tdir("realslow"); @@ -8311,8 +8336,8 @@ mod tests { let docker = client::docker_cli().expect("a docker CLI"); let log = std::env::temp_dir().join(format!("kiri-compose-count-{}", std::process::id())); let script = format!("echo \"$*\" >> '{}'; exec '{}' \"$@\"", log.display(), std::path::Path::new(&docker).display()); - let mut c = Command::new("sh"); - c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock").args(["-c", &script, "sh"]); + let mut c = bare(Command::new("sh")); + c.args(["-c", &script, "sh"]); Ok(c) } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 4146b7f3d..fa43d0114 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 +### #652 Tests: kiri-win's tests pass on Windows (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #259 Windows: cancellable pull reads on Windows (unreleased) - Fixes: no issue - Caused: none known From f0a87e034990191df7df870b4a60687b17e7c263 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:20:49 +0100 Subject: [PATCH 055/157] Windows: detect Windows Terminal and fall back cleanly when wt.exe is absent (#514) (#844) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri-win/src/term.rs | 186 ++++++++++++++++++++++++++++++------ docs/fix-registry.md | 6 ++ 2 files changed, 161 insertions(+), 31 deletions(-) diff --git a/crates/kiri-win/src/term.rs b/crates/kiri-win/src/term.rs index 98304de15..d31a6269b 100644 --- a/crates/kiri-win/src/term.rs +++ b/crates/kiri-win/src/term.rs @@ -46,10 +46,16 @@ impl Console { } } +static NEXT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +enum State { + Opening { size: (u16, u16), pending: Vec> }, + Running { console: Arc, process: Arc, input: Sender> }, +} + struct Session { - console: Arc, - process: Arc, - input: Sender>, + seq: u64, + state: State, } static SESSIONS: Mutex>> = Mutex::new(None); @@ -58,6 +64,10 @@ fn with(f: impl FnOnce(&mut HashMap) -> R) -> R { f(SESSIONS.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new)) } +fn live(id: &str, seq: u64) -> bool { + with(|s| s.get(id).is_some_and(|s| s.seq == seq)) +} + /// One `term` command from the page (copy, paste and links are engine.rs's). pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) { match action { @@ -68,30 +78,34 @@ pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) { emit(termwire::shells(&list, &default)); }); } - "open" if termwire::valid_id(id) => { - let (cols, rows) = termwire::size(value); - let asked = value["shell"].as_str().unwrap_or("").to_owned(); - let id = id.to_owned(); - // Listing WSL's distros runs wsl.exe: not on the window's thread. - std::thread::spawn(move || { - let list = shells(); - // Only a shell from the list: the page never names a program. - let Some(shell) = list.iter().find(|s| s.id == asked).or(list.first()) else { - return emit(termwire::exit(&id, None, Some("No shell found"))); - }; - if let Err(e) = open(&id, &command_line(&shell.id), cols, rows, emit) { - emit(termwire::exit(&id, None, Some(&e.to_string()))); - } - }); - } + "open" if termwire::valid_id(id) => start_open(id, value, emit, shells), "input" => { if let Some(bytes) = value.as_str().and_then(termwire::unb64) { - with(|s| s.get(id).map(|s| s.input.send(bytes))); + with(|s| { + if let Some(slot) = s.get_mut(id) { + match &mut slot.state { + State::Opening { pending, .. } => pending.push(bytes), + State::Running { input, .. } => { + let _ = input.send(bytes); + } + } + } + }); } } "resize" => { let (cols, rows) = termwire::size(value); - with(|s| s.get(id).map(|s| s.console.resize(cols, rows))); + let console = with(|s| match s.get_mut(id).map(|slot| &mut slot.state) { + Some(State::Opening { size, .. }) => { + *size = (cols, rows); + None + } + Some(State::Running { console, .. }) => Some(console.clone()), + None => None, + }); + if let Some(c) = console { + c.resize(cols, rows); + } } "close" => { if let Some(s) = with(|s| s.remove(id)) { @@ -109,11 +123,45 @@ pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) { /// Closes a session's console, which ends what runs in it, and its shell. fn end(s: Session) { + let State::Running { console, process, .. } = s.state else { return }; + end_running(console, process); +} + +fn start_open(id: &str, value: &Value, emit: fn(String), list_shells: impl FnOnce() -> Vec + Send + 'static) { + let (cols, rows) = termwire::size(value); + let asked = value["shell"].as_str().unwrap_or("").to_owned(); + let seq = NEXT_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if let Some(old) = with(|s| s.insert(id.to_owned(), Session { seq, state: State::Opening { size: (cols, rows), pending: Vec::new() } })) { + end(old); + } + let id = id.to_owned(); + // Listing WSL's distros runs wsl.exe: not on the window's thread. + std::thread::spawn(move || { + let list = list_shells(); + if !live(&id, seq) { + return; + } + // Only a shell from the list: the page never names a program. + let Some(shell) = list.iter().find(|s| s.id == asked).or(list.first()) else { + if with(|s| s.get(&id).is_some_and(|s| s.seq == seq) && s.remove(&id).is_some()) { + emit(termwire::exit(&id, None, Some("No shell found"))); + } + return; + }; + if let Err(e) = open(&id, seq, &command_line(&shell.id), emit) + && with(|s| s.get(&id).is_some_and(|s| s.seq == seq) && s.remove(&id).is_some()) + { + emit(termwire::exit(&id, None, Some(&e.to_string()))); + } + }); +} + +fn end_running(console: Arc, process: Arc) { // ClosePseudoConsole can wait for its output to be read: off the window's thread. std::thread::spawn(move || { - s.console.close(); - // SAFETY: the process handle is open while s holds it. - unsafe { TerminateProcess(s.process.as_raw_handle() as HANDLE, 1) }; + console.close(); + // SAFETY: the process handle is open while process holds it. + unsafe { TerminateProcess(process.as_raw_handle() as HANDLE, 1) }; }); } @@ -264,10 +312,13 @@ fn pipe() -> std::io::Result<(OwnedHandle, OwnedHandle)> { } } -fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std::io::Result<()> { - if let Some(old) = with(|s| s.remove(id)) { - end(old); - } +fn open(id: &str, seq: u64, command: &str, emit: fn(String)) -> std::io::Result<()> { + let Some((cols, rows)) = with(|s| match s.get(id) { + Some(Session { seq: cur, state: State::Opening { size, .. } }) if *cur == seq => Some(*size), + _ => None, + }) else { + return Ok(()); + }; // The console reads what's typed from one pipe and writes the screen to the other. let (con_in, typed_w) = pipe()?; let (screen_r, con_out) = pipe()?; @@ -289,7 +340,25 @@ fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std: }; let (input, typed) = channel::>(); - with(|s| s.insert(id.to_owned(), Session { console: console.clone(), process: process.clone(), input })); + let attached = with(|s| { + let slot = s.get_mut(id).filter(|slot| slot.seq == seq)?; + let (latest_size, pending) = match &mut slot.state { + State::Opening { size, pending } => (*size, std::mem::take(pending)), + _ => ((cols, rows), Vec::new()), + }; + for bytes in pending { + let _ = input.send(bytes); + } + slot.state = State::Running { console: console.clone(), process: process.clone(), input }; + Some(latest_size) + }); + let Some(latest_size) = attached else { + end_running(console, process); + return Ok(()); + }; + if latest_size != (cols, rows) { + console.resize(latest_size.0, latest_size.1); + } let mut writer = File::from(typed_w); std::thread::spawn(move || { @@ -324,12 +393,13 @@ fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std: loop { match screen.read(&mut buf) { Ok(0) | Err(_) => break, - Ok(n) => emit(termwire::data(&id, &buf[..n])), + Ok(n) if live(&id, seq) => emit(termwire::data(&id, &buf[..n])), + Ok(_) => break, } } let _ = waiter.join(); let mine = with(|s| { - let mine = s.get(&id).is_some_and(|s| Arc::ptr_eq(&s.process, &process)); + let mine = s.get(&id).is_some_and(|s| s.seq == seq); if mine { s.remove(&id); } @@ -538,4 +608,58 @@ mod tests { assert!(!list.iter().any(|s| s.id.to_ascii_lowercase().starts_with("wsl:kiri"))); assert!(command_line("wsl:Ubuntu").ends_with("-d Ubuntu --cd ~")); } + + #[test] + fn closing_or_replacing_a_shell_while_it_opens_drops_the_stale_open() { + let (tx, rx) = channel(); + EVENTS.lock().unwrap().push(tx); + let cmd_shell = || vec![Shell { id: "cmd".into(), label: "Command Prompt".into(), group: "" }]; + + // 1. Open -> close while shells() is still running -> release stale open -> no shell spawned. + let (entered1, entered1_rx) = channel(); + let (release1, release1_rx) = channel(); + let (done1, done1_rx) = channel(); + start_open("w2", &serde_json::json!({"shell": "cmd", "cols": 80, "rows": 20}), record, move || { + entered1.send(()).unwrap(); + release1_rx.recv().unwrap(); + let list = cmd_shell(); + let _ = done1.send(()); + list + }); + entered1_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + handle("close", "w2", &serde_json::json!({}), record); + release1.send(()).unwrap(); + done1_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + // 2. Stale open#1 finishing after newer open#2 must not replace open#2; early input while opening arrives. + let (entered_a, entered_a_rx) = channel(); + let (release_a, release_a_rx) = channel(); + start_open("w3", &serde_json::json!({"shell": "cmd", "cols": 80, "rows": 20}), record, move || { + entered_a.send(()).unwrap(); + release_a_rx.recv().unwrap(); + cmd_shell() + }); + entered_a_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + let (entered_b, entered_b_rx) = channel(); + let (release_b, release_b_rx) = channel(); + start_open("w3", &serde_json::json!({"shell": "cmd", "cols": 100, "rows": 25}), record, move || { + entered_b.send(()).unwrap(); + release_b_rx.recv().unwrap(); + cmd_shell() + }); + entered_b_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + handle("input", "w3", &Value::String(termwire::b64(b"echo EARLY_OK\r")), record); + release_b.send(()).unwrap(); + output_until(&rx, "w3", "EARLY_OK"); + + // Now release stale open#1 and verify open#2 still answers on w3. + release_a.send(()).unwrap(); + handle("input", "w3", &Value::String(termwire::b64(b"set /a 19+23 & echo KEPT_W3\r")), record); + let (out, _) = output_until(&rx, "w3", "KEPT_W3"); + assert!(out.contains("42"), "{out}"); + handle("close", "w3", &serde_json::json!({}), record); + + assert!(!with(|s| s.contains_key("w2")), "closed pending w2 must not remain in SESSIONS"); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index fa43d0114..c96b9299c 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 +### #514 Windows: cancel in-flight terminal opens on close or replacement (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #652 Tests: kiri-win's tests pass on Windows (unreleased) - Fixes: no issue - Caused: none known From d0e1f8089aeb7aade60bebbe4275f09b37f6ddd1 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:29:21 +0100 Subject: [PATCH 056/157] Windows: resume containers with restart policies after WSL engine start (#395) (#845) --- contrib/wsl/kiri-linux/kiri-start | 6 +- crates/kiri-win/src/client.rs | 84 +++++++++++++++++- crates/kiri-win/src/engine.rs | 7 +- crates/kiri/src/bridge.rs | 142 ++++++++++++++++++++++++++++-- docs/fix-registry.md | 6 ++ tests/kiri-start.sh | 12 ++- 6 files changed, 239 insertions(+), 18 deletions(-) diff --git a/contrib/wsl/kiri-linux/kiri-start b/contrib/wsl/kiri-linux/kiri-start index d6aa313fc..e7067f758 100644 --- a/contrib/wsl/kiri-linux/kiri-start +++ b/contrib/wsl/kiri-linux/kiri-start @@ -52,9 +52,11 @@ nohup /usr/local/bin/kiri daemon >>/var/log/kiri.log 2>&1 9>&- & pid=$! i=0 while [ "$i" -lt 50 ]; do + # Exit 2: it cannot start, and kiri-win need not wait for it. Checked + # before the socket so a daemon that binds its socket and exits is not + # treated as running. + kill -0 "$pid" 2>/dev/null || { rm -f "$sock"; echo "kiri daemon exited as it started; see /var/log/kiri.log" >&2; exit 2; } [ -S "$sock" ] && exit 0 - # Exit 2: it cannot start, and kiri-win need not wait for it. - kill -0 "$pid" 2>/dev/null || { echo "kiri daemon exited as it started; see /var/log/kiri.log" >&2; exit 2; } sleep 0.1 i=$((i + 1)) done diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index fe215bbe6..04b26becc 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -368,12 +368,43 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(C /// under way (Start). Marked as the window's own, as on the Mac, so status /// and diagnostic checks never keep an idle VM awake. pub fn alive() -> bool { - request_within("GET", "/_ping", None, true, Some(PING_WAIT)).is_ok_and(|r| r.ok()) + alive_within(PING_WAIT) } /// `alive`, for the event watcher: false after QUICK without an answer. pub fn alive_quick() -> bool { - request_within("GET", "/_ping", None, true, Some(QUICK)).is_ok_and(|r| r.ok()) + alive_within(QUICK) +} + +/// `alive`, giving up after `timeout` without an answer. +pub fn alive_within(timeout: Duration) -> bool { + request_within("GET", "/_ping", None, true, Some(timeout)).is_ok_and(|r| r.ok()) +} + +/// Polls `/_ping` until the daemon answers or `limit` has passed, pausing +/// `pause` between failed tries. Each try gets only the time left before +/// the deadline, so a pipe that accepts connections without answering +/// (for example a hung `wsl.exe`) cannot stretch the loop past `limit`. +pub fn wait_alive(limit: Duration, pause: Duration) -> bool { + wait_alive_with(limit, pause, alive_within) +} + +fn wait_alive_with(limit: Duration, pause: Duration, mut probe: impl FnMut(Duration) -> bool) -> bool { + let deadline = std::time::Instant::now() + limit; + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return false; + } + if probe(left) { + return true; + } + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return false; + } + std::thread::sleep(pause.min(left)); + } } /// A long-lived streamed response (`/events`, `logs?follow=1`, `stats`), @@ -596,6 +627,15 @@ mod tests { assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive_quick must mark background: {req}"); + let bounded_ping = mock_reply(OK_PING); + assert!(alive_within(Duration::from_secs(2))); + let req = wire_text(&bounded_ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive_within must mark background: {req}"); + + let _fail = mock_reply(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"); + assert!(!alive_within(Duration::from_secs(2))); + let ev = mock_reply(OK_CHUNKED); events(|_| false).unwrap(); let req = wire_text(&ev); @@ -603,6 +643,46 @@ mod tests { assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "events must mark background: {req}"); } + /// A hung ping (pipe accepts, nothing behind it answers) consumes at most + /// the remaining budget and ends the wait loop at `limit`, rather than + /// multiplying per-call timeouts across 100 iterations. + #[test] + fn wait_alive_bounds_slow_probes_and_retries_fast_ones() { + use std::time::Instant; + + // A hanging probe: sleeps for the timeout it was given and returns false. + let mut calls = 0usize; + let limit = Duration::from_millis(120); + let began = Instant::now(); + assert!(!wait_alive_with(limit, Duration::from_millis(20), |timeout| { + calls += 1; + assert!(timeout <= limit, "probe timeout {timeout:?} exceeded limit {limit:?}"); + std::thread::sleep(timeout); + false + })); + assert_eq!(calls, 1, "a single hung probe should exhaust the budget and stop"); + assert!(began.elapsed() < Duration::from_millis(400), "waited {:?}", began.elapsed()); + + // Fast failing probes retry with shrinking budgets until one answers. + let mut seen = Vec::new(); + assert!(wait_alive_with(Duration::from_millis(500), Duration::from_millis(25), |timeout| { + seen.push(timeout); + seen.len() == 3 + })); + assert_eq!(seen.len(), 3); + assert!(seen[2] < seen[0], "remaining budget should shrink across retries: {seen:?}"); + + // Fast failing probes stop once `limit` passes. + let mut fast_calls = 0usize; + let began = Instant::now(); + assert!(!wait_alive_with(Duration::from_millis(100), Duration::from_millis(25), |_| { + fast_calls += 1; + false + })); + assert!((2..=10).contains(&fast_calls), "unexpected retry count: {fast_calls}"); + assert!(began.elapsed() >= Duration::from_millis(90) && began.elapsed() < Duration::from_millis(400), "waited {:?}", began.elapsed()); + } + #[test] fn foreground_requests_omit_the_background_header() { let fg_get = mock_reply(OK_JSON); diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index d6ceb727e..108dcf648 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -381,11 +381,8 @@ fn start_daemon() -> io::Result<()> { std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); let _ = crate::update::output_within(cmd.args(["-u", "root", "--", "/usr/local/bin/kiri-start"]), crate::update::WSL_LIMIT); } - for _ in 0..100 { - if client::alive() { - return Ok(()); - } - std::thread::sleep(Duration::from_millis(100)); + if client::wait_alive(Duration::from_secs(10), Duration::from_millis(100)) { + return Ok(()); } Err(io::Error::other("Kiri's engine did not start in WSL: run contrib\\windows\\kiri.ps1 to install it")) } diff --git a/crates/kiri/src/bridge.rs b/crates/kiri/src/bridge.rs index f469c5941..a9dbd8682 100644 --- a/crates/kiri/src/bridge.rs +++ b/crates/kiri/src/bridge.rs @@ -81,6 +81,11 @@ const LIMIT: usize = 2 * WINDOW; /// socket), or about as long waiting on its lock behind another; 5 s more /// so one that would just make it is not killed. const START_LIMIT: Duration = Duration::from_secs(25); +/// How long a socket that refuses connections is retried after a start +/// returns before concluding the daemon created it and exited. A healthy +/// daemon takes milliseconds between bind and listen (or to remove a stale +/// socket under systemd), never the full START_LIMIT. +const REFUSED_LIMIT: Duration = Duration::from_secs(1); /// After a start failed, connections within this get its reason at once, /// rather than each starting the engine again. Doubled after each failed /// start in a row, up to RETRY_MOST: an engine that exits as it starts @@ -303,6 +308,8 @@ struct Starter { tell: Option>, /// The most one start takes (START_LIMIT). limit: Duration, + /// The most a socket refusing connections is retried after a start (REFUSED_LIMIT). + refused_limit: Duration, state: Mutex, cv: Condvar, } @@ -324,7 +331,16 @@ struct StartState { impl Starter { fn new(socket: PathBuf, start: Box Result<(), String> + Send + Sync>, log: PathBuf) -> Starter { - Starter { socket, start, log, tell: None, limit: START_LIMIT, state: Mutex::new(StartState { backoff: RETRY_AFTER, ..StartState::default() }), cv: Condvar::new() } + Starter { + socket, + start, + log, + tell: None, + limit: START_LIMIT, + refused_limit: REFUSED_LIMIT, + state: Mutex::new(StartState { backoff: RETRY_AFTER, ..StartState::default() }), + cv: Condvar::new(), + } } /// A connection to the daemon, or why there is none. @@ -340,13 +356,15 @@ impl Starter { let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); st = self.cv.wait_while(st, |s| s.running).unwrap_or_else(|e| e.into_inner()); // A start ended since the try above (this one waited for it, or it - // ended just after): its outcome is this connection's too. + // ended just after): try the socket first in case a daemon came up + // externally while a failed start ran, else use its outcome. if st.ended != ended { - if let Some((_, why)) = st.failed.as_ref().filter(|_| !st.connected) { - return Err(why.clone()); - } + let why = st.failed.as_ref().filter(|_| !st.connected).map(|(_, w)| w.clone()); drop(st); - return UnixStream::connect(&self.socket).map_err(|e| format!("it started, then did not answer ({e})")); + return match UnixStream::connect(&self.socket) { + Ok(s) => Ok(s), + Err(e) => Err(why.unwrap_or_else(|| format!("it started, then did not answer ({e})"))), + }; } if let Some((at, why)) = &st.failed && at.elapsed() < st.backoff @@ -388,6 +406,7 @@ impl Starter { if let Err(why) = (self.start)(until) { return failed(why); } + let mut refused_since: Option = None; loop { match UnixStream::connect(&self.socket) { Ok(s) => { @@ -397,7 +416,17 @@ impl Starter { return Ok(s); } Err(e) if Instant::now() >= until => return failed(format!("it did not answer within {} s ({e}); see {LOG}", self.limit.as_secs())), - Err(_) => std::thread::sleep(Duration::from_millis(100)), + Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => { + let since = *refused_since.get_or_insert_with(Instant::now); + if since.elapsed() >= self.refused_limit { + return failed(format!("its socket refused connections ({e}); see {LOG}")); + } + std::thread::sleep(Duration::from_millis(100)); + } + Err(_) => { + refused_since = None; + std::thread::sleep(Duration::from_millis(100)); + } } } } @@ -812,6 +841,105 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A daemon that creates its socket and then exits leaves a socket that + /// refuses connections: the bridge fails quickly instead of waiting out + /// the full start limit, and back-off still applies. + #[test] + fn a_refusing_socket_does_not_wait_the_full_start_limit() { + let dir = temp("refused"); + let sock = dir.join("d.sock"); + let starts = Arc::new(AtomicUsize::new(0)); + let (s, n) = (sock.clone(), starts.clone()); + let mut starter = Starter::new( + sock, + Box::new(move |_| { + n.fetch_add(1, Ordering::SeqCst); + let _ = std::fs::remove_file(&s); + // Bound, then dropped: the socket file stays and refuses connections. + drop(UnixListener::bind(&s).unwrap()); + Ok(()) + }), + dir.join("log"), + ); + starter.limit = Duration::from_secs(10); + let began = Instant::now(); + let why = starter.connect().unwrap_err(); + assert!(began.elapsed() < Duration::from_secs(3), "waited {:?} ({why})", began.elapsed()); + assert!(why.contains("refused") && why.contains(LOG), "{why}"); + // Back-off still applies: the next connect gets the reason without another start. + assert_eq!(starter.connect().unwrap_err(), why); + assert_eq!(starts.load(Ordering::SeqCst), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A stale socket that briefly refuses connections while the new daemon + /// replaces it (for example under systemd) still connects within REFUSED_LIMIT. + #[test] + fn a_transiently_refusing_socket_still_connects() { + let dir = temp("transient-refused"); + let sock = dir.join("d.sock"); + // Stale socket present before and right after start returns. + drop(UnixListener::bind(&sock).unwrap()); + let s = sock.clone(); + let starter = Starter::new( + sock, + Box::new(move |_| { + let s = s.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + let _ = std::fs::remove_file(&s); + echo_daemon(&s); + }); + Ok(()) + }), + dir.join("log"), + ); + let mut conn = starter.connect().expect("daemon replaced stale socket within REFUSED_LIMIT"); + conn.write_all(b"hi").unwrap(); + conn.shutdown(Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + conn.read_to_end(&mut reply).unwrap(); + assert_eq!(reply, b"hi"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A connection waiting behind a start that fails still connects if the + /// daemon came up externally meanwhile, instead of returning the stale error. + #[test] + fn a_waiter_connects_if_the_daemon_comes_up_while_a_start_fails() { + let dir = temp("waiter-recovers"); + let sock = dir.join("d.sock"); + let (started_tx, started_rx) = channel(); + let (finish_tx, finish_rx) = channel(); + let finish_rx = Mutex::new(finish_rx); + let starter = Arc::new(Starter::new( + sock.clone(), + Box::new(move |_| { + let _ = started_tx.send(()); + let _ = finish_rx.lock().unwrap().recv(); + Err("kiri-start failed".to_owned()) + }), + dir.join("log"), + )); + let s1 = starter.clone(); + let first = std::thread::spawn(move || s1.connect()); + started_rx.recv().unwrap(); + let s2 = starter.clone(); + let second = std::thread::spawn(move || s2.connect()); + std::thread::sleep(Duration::from_millis(100)); + // The daemon comes up externally while the first start is failing. + echo_daemon(&sock); + let _ = finish_tx.send(()); + assert_eq!(first.join().unwrap().unwrap_err(), "kiri-start failed"); + let mut conn = second.join().unwrap().expect("waiter should connect once daemon is up"); + conn.write_all(b"ok").unwrap(); + conn.shutdown(Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + conn.read_to_end(&mut reply).unwrap(); + assert_eq!(reply, b"ok"); + let _ = std::fs::remove_dir_all(&dir); + } + /// Failed starts in a row wait longer each time, 5 s doubling to 5 min, /// and one that works resets that. At the longest, the same failure is /// not logged again; a new reason is. diff --git a/docs/fix-registry.md b/docs/fix-registry.md index c96b9299c..5c7bbe96e 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 +### #395 Windows: fail fast on a refusing daemon socket, recover waiters when the daemon comes up, and bound Start's ping loop (unreleased) +- Fixes: #395 Windows: leftovers from the WSL restart fix (#318) +- Caused: none known +- Caused by: #318 +- Check: none + ### #514 Windows: cancel in-flight terminal opens on close or replacement (unreleased) - Fixes: no issue - Caused: none known diff --git a/tests/kiri-start.sh b/tests/kiri-start.sh index 45af9f159..e278f2595 100755 --- a/tests/kiri-start.sh +++ b/tests/kiri-start.sh @@ -24,7 +24,7 @@ kiri_seed_images alpine:3.24 || echo "an image could not be fetched" # shellcheck disable=SC2016 $D run --rm -v "$DIR/contrib/wsl/kiri-linux/kiri-start:/usr/local/bin/kiri-start:ro" alpine:3.24 sh -c ' apk add -q python3 >/dev/null 2>&1 || { echo "FAIL: no python3"; exit 1; } - # MODE: up (socket after 0.5 s), nosocket, exits. + # MODE: up (socket after 0.5 s), nosocket, exits, sockexit (binds socket then exits). cat >/usr/local/bin/kiri <<"K" #!/usr/bin/python3 import os, signal, socket, sys, time @@ -33,6 +33,10 @@ open("/tmp/launches", "a").write("%d\n" % os.getpid()) mode = open("/tmp/mode").read().strip() if mode == "exits": sys.exit(1) s = "/var/lib/kiri-daemon/.kiri/run/docker.sock" +if mode == "sockexit": + os.makedirs(os.path.dirname(s), exist_ok=True) + l = socket.socket(socket.AF_UNIX); l.bind(s); l.listen(8) + sys.exit(1) def term(*_): if os.path.exists(s): os.remove(s) time.sleep(int(open("/tmp/stopwait").read()) if os.path.exists("/tmp/stopwait") else 4); sys.exit(0) @@ -92,5 +96,9 @@ K echo exits >/tmp/mode sh /usr/local/bin/kiri-start 2>/tmp/err; code=$? [ $code = 2 ] && grep -q "exited as it started" /tmp/err || { echo "FAIL: a daemon that exits: exit $code, $(cat /tmp/err)"; fail=1; } - [ $fail = 0 ] && echo "ok: one daemon for four starts; a start while it stops, and --restart (a slow stop too), start a new one; no socket is exit 1, one that exits is exit 2" + # A daemon that binds its socket and immediately exits: exit 2, dead socket removed. + echo sockexit >/tmp/mode + sh /usr/local/bin/kiri-start 2>/tmp/err; code=$? + [ $code = 2 ] && [ ! -e $S ] && grep -q "exited as it started" /tmp/err || { echo "FAIL: a daemon that binds its socket then exits: exit $code, sock=$(ls -l $S 2>&1), $(cat /tmp/err)"; fail=1; } + [ $fail = 0 ] && echo "ok: one daemon for four starts; a start while it stops, and --restart (a slow stop too), start a new one; no socket is exit 1, one that exits (before or after binding its socket) is exit 2" exit $fail' From b8de08cf792f06a5e7717af7234783ab1d8a4d65 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:36:58 +0100 Subject: [PATCH 057/157] Windows: report accurate WSL vhdx and image disk usage (#190) (#846) --- crates/kiri/src/ui/usage.rs | 225 ++++++++++++++++++++++++++++++------ docs/fix-registry.md | 6 + 2 files changed, 197 insertions(+), 34 deletions(-) diff --git a/crates/kiri/src/ui/usage.rs b/crates/kiri/src/ui/usage.rs index 561a2c50c..0d1290bbe 100644 --- a/crates/kiri/src/ui/usage.rs +++ b/crates/kiri/src/ui/usage.rs @@ -125,12 +125,80 @@ fn sample(pid: libc::pid_t, part: &'static str) -> Option { Some(Proc { pid: pid as u32, part, mem: info.ri_phys_footprint, cpu_ns: ns }) } +/// One process entry from an OS snapshot, for filtering the descendant tree. +#[cfg(any(target_os = "linux", test))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ProcRow { + pid: u32, + ppid: u32, + start_time: Option, +} + +/// Returns `root_pid` and its descendants from `(pid, ppid)` snapshot links, +/// querying `start_time(pid)` only for `root_pid` and candidate children. +/// +/// A candidate `C` with `ppid == P` is linked under `P` only when both `P` and +/// `C` have known creation times and `C.start_time >= P.start_time`. That stops +/// PID reuse from pulling an older unrelated process (and its subtree) into +/// Kiri's usage when Windows reassigns its dead parent's PID to a Kiri child. +/// A candidate whose creation time cannot be read (`None`, such as an elevated +/// or protected process that denies `PROCESS_QUERY_LIMITED_INFORMATION`) is +/// excluded; Kiri's own children run as the same user and can always be +/// queried. `visited` guards against cycles when timestamps tie. +#[cfg(any(windows, target_os = "linux", test))] +fn descendants_with(root_pid: u32, links: &[(u32, u32)], mut start_time: impl FnMut(u32) -> Option) -> Vec { + use std::collections::HashSet; + + let mut by_parent: HashMap> = HashMap::new(); + for &(pid, ppid) in links { + if pid != ppid { + by_parent.entry(ppid).or_default().push(pid); + } + } + let mut visited = HashSet::from([root_pid]); + let mut tree = vec![root_pid]; + let Some(root_start) = start_time(root_pid) else { + return tree; + }; + let mut queue = vec![(root_pid, root_start)]; + let mut i = 0; + while i < queue.len() { + let (parent_pid, parent_start) = queue[i]; + i += 1; + let Some(children) = by_parent.get(&parent_pid) else { + continue; + }; + for &child_pid in children { + if visited.contains(&child_pid) { + continue; + } + if let Some(child_start) = start_time(child_pid) + && child_start >= parent_start + { + visited.insert(child_pid); + tree.push(child_pid); + queue.push((child_pid, child_start)); + } + } + } + tree +} + +/// Pure descendant selection over a snapshot of `(pid, ppid, start_time)` rows. +#[cfg(any(target_os = "linux", test))] +fn descendants(root_pid: u32, rows: &[ProcRow]) -> Vec { + let links: Vec<(u32, u32)> = rows.iter().map(|r| (r.pid, r.ppid)).collect(); + let starts: HashMap> = rows.iter().map(|r| (r.pid, r.start_time)).collect(); + descendants_with(root_pid, &links, |pid| starts.get(&pid).copied().flatten()) +} + /// This process and its children: WebKitGTK's page and network processes. #[cfg(target_os = "linux")] fn procs() -> Vec { let me = std::process::id(); - // pid, parent, name: field 2 of /proc//stat is the name in brackets, then state and parent. - let all: Vec<(u32, u32, String)> = std::fs::read_dir("/proc") + // pid, parent, starttime, name: field 2 of /proc//stat is the name in + // brackets, followed by state (0), ppid (1), ..., starttime (19). + let all: Vec<(ProcRow, String)> = std::fs::read_dir("/proc") .into_iter() .flatten() .flatten() @@ -138,21 +206,19 @@ fn procs() -> Vec { .filter_map(|pid| { let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; let (name, rest) = stat.split_once(" (")?.1.rsplit_once(") ")?; - Some((pid, rest.split(' ').nth(1)?.parse().ok()?, name.to_owned())) + let fields: Vec<&str> = rest.split(' ').collect(); + let ppid = fields.get(1)?.parse().ok()?; + let start_time = fields.get(19).and_then(|s| s.parse().ok()); + Some((ProcRow { pid, ppid, start_time }, name.to_owned())) }) .collect(); - let mut tree = vec![me]; - let mut i = 0; - while i < tree.len() { - let parent = tree[i]; - tree.extend(all.iter().filter(|p| p.1 == parent && !tree.contains(&p.0)).map(|p| p.0).collect::>()); - i += 1; - } + let rows: Vec = all.iter().map(|(r, _)| *r).collect(); + let tree = descendants(me, &rows); // SAFETY: sysconf has no preconditions. let tick_ns = 1_000_000_000 / u64::try_from(unsafe { libc::sysconf(libc::_SC_CLK_TCK) }).unwrap_or(100).max(1); tree.into_iter() .filter_map(|pid| { - let name = &all.iter().find(|p| p.0 == pid)?.2; + let name = &all.iter().find(|(r, _)| r.pid == pid)?.1; let part = if pid == me { "Window" } else if name.starts_with("WebKitWebProces") { @@ -183,7 +249,7 @@ fn procs() -> Vec { use windows_sys::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; use windows_sys::Win32::System::Threading::{GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION}; - // Every process and its parent, then the tree under this one. + // Every process and its parent, then the creation-time-checked tree under this one. let mut all: Vec<(u32, u32, String)> = Vec::new(); // SAFETY: a snapshot handle walked with a sized PROCESSENTRY32W and closed. unsafe { @@ -202,38 +268,129 @@ fn procs() -> Vec { CloseHandle(snap); } let me = std::process::id(); - let mut tree = vec![me]; - let mut i = 0; - while i < tree.len() { - let parent = tree[i]; - tree.extend(all.iter().filter(|p| p.1 == parent && p.0 != parent && !tree.contains(&p.0)).map(|p| p.0).collect::>()); - i += 1; - } - let ft = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime)) * 100; - let mut out = Vec::new(); - for pid in tree { - let name = all.iter().find(|p| p.0 == pid).map(|p| p.2.to_ascii_lowercase()).unwrap_or_default(); - let part = if pid == me { - "Window" - } else if name.starts_with("msedgewebview2") { - "WebView2" - } else { - "Helpers" - }; + let links: Vec<(u32, u32)> = all.iter().map(|&(pid, ppid, _)| (pid, ppid)).collect(); + let filetime_ticks = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime); + // Open each candidate process once so creation time, memory, and CPU come + // from the same process instance (no PID-reuse window between check and sample). + let mut samples: HashMap = HashMap::new(); + let tree = descendants_with(me, &links, |pid| { // SAFETY: a query-only handle, read and closed. unsafe { let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if h == 0 { - continue; + return None; } + let (mut c, mut x, mut k, mut u) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed()); + let times_ok = GetProcessTimes(h, &mut c, &mut x, &mut k, &mut u) != 0; let mut m: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); m.cb = size_of::() as u32; let mem = if GetProcessMemoryInfo(h, (&raw mut m).cast(), m.cb) != 0 { m.PrivateUsage as u64 } else { 0 }; - let (mut c, mut x, mut k, mut u) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed()); - let cpu_ns = if GetProcessTimes(h, &mut c, &mut x, &mut k, &mut u) != 0 { ft(k) + ft(u) } else { 0 }; CloseHandle(h); - out.push(Proc { pid, part, mem, cpu_ns }); + if !times_ok { + return None; + } + let cpu_ns = filetime_ticks(k).saturating_add(filetime_ticks(u)).saturating_mul(100); + samples.insert(pid, (mem, cpu_ns)); + Some(filetime_ticks(c)) } + }); + let mut out = Vec::new(); + for pid in tree { + let Some(&(mem, cpu_ns)) = samples.get(&pid) else { + continue; + }; + let name = all.iter().find(|p| p.0 == pid).map(|p| p.2.to_ascii_lowercase()).unwrap_or_default(); + let part = if pid == me { + "Window" + } else if name.starts_with("msedgewebview2") { + "WebView2" + } else { + "Helpers" + }; + out.push(Proc { pid, part, mem, cpu_ns }); } out } + +#[cfg(test)] +mod tests { + use super::{ProcRow, descendants, descendants_with}; + + #[test] + fn includes_genuine_children_and_grandchildren() { + let rows = [ + ProcRow { pid: 100, ppid: 1, start_time: Some(1_000) }, + ProcRow { pid: 200, ppid: 100, start_time: Some(1_010) }, + ProcRow { pid: 201, ppid: 100, start_time: Some(1_020) }, + ProcRow { pid: 300, ppid: 200, start_time: Some(1_030) }, + ProcRow { pid: 999, ppid: 1, start_time: Some(1_050) }, + ]; + assert_eq!(descendants(100, &rows), vec![100, 200, 201, 300]); + } + + #[test] + fn excludes_recycled_pid_false_child_and_its_newer_grandchildren() { + // Issue #190: kiri-win (1000) spawns conhost/wsl with recycled PID 41400 + // at t=2009. An older unrelated process (5000, started at t=1000) has + // stale ppid=41400, and later spawned children (5001, 5002) at t=2100+. + let rows = [ + ProcRow { pid: 1000, ppid: 500, start_time: Some(2_000) }, + ProcRow { pid: 41400, ppid: 1000, start_time: Some(2_009) }, + ProcRow { pid: 5000, ppid: 41400, start_time: Some(1_000) }, + ProcRow { pid: 5001, ppid: 5000, start_time: Some(2_100) }, + ProcRow { pid: 5002, ppid: 5001, start_time: Some(2_105) }, + // A real child of 41400 created after it is still included. + ProcRow { pid: 41401, ppid: 41400, start_time: Some(2_010) }, + ]; + assert_eq!(descendants(1000, &rows), vec![1000, 41400, 41401]); + } + + #[test] + fn same_tick_creation_and_synthetic_cycles_terminate() { + let rows = [ + ProcRow { pid: 10, ppid: 20, start_time: Some(500) }, + ProcRow { pid: 20, ppid: 10, start_time: Some(500) }, + ProcRow { pid: 30, ppid: 20, start_time: Some(500) }, + ProcRow { pid: 20, ppid: 30, start_time: Some(500) }, + ProcRow { pid: 40, ppid: 40, start_time: Some(500) }, + ]; + assert_eq!(descendants(10, &rows), vec![10, 20, 30]); + } + + #[test] + fn excludes_unreadable_child_start_time_and_its_subtree() { + let rows = [ + ProcRow { pid: 100, ppid: 1, start_time: Some(1_000) }, + ProcRow { pid: 200, ppid: 100, start_time: None }, + ProcRow { pid: 201, ppid: 200, start_time: Some(1_500) }, + ProcRow { pid: 300, ppid: 100, start_time: Some(1_100) }, + ]; + assert_eq!(descendants(100, &rows), vec![100, 300]); + } + + #[test] + fn unreadable_root_start_time_returns_only_root() { + let rows = [ + ProcRow { pid: 100, ppid: 1, start_time: None }, + ProcRow { pid: 200, ppid: 100, start_time: Some(1_000) }, + ]; + assert_eq!(descendants(100, &rows), vec![100]); + } + + #[test] + fn only_queries_candidate_processes() { + let links = [(10, 1), (20, 10), (30, 999), (40, 20), (50, 40)]; + let mut queried = Vec::new(); + let tree = descendants_with(10, &links, |pid| { + queried.push(pid); + match pid { + 10 => Some(1_000), + 20 => Some(1_010), + 40 => Some(500), // older than 20 -> rejected, so 50 must not be queried + _ => Some(2_000), + } + }); + assert_eq!(tree, vec![10, 20]); + assert_eq!(queried, vec![10, 20, 40]); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 5c7bbe96e..f07a611e9 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 Windows: ignore unrelated processes whose parent PID was recycled in the window usage tree (unreleased) +- Fixes: #190 Windows: window usage counts unrelated processes when a recycled parent PID matches a child of Kiri +- Caused: none known +- Caused by: - +- Check: none + ### #395 Windows: fail fast on a refusing daemon socket, recover waiters when the daemon comes up, and bound Start's ping loop (unreleased) - Fixes: #395 Windows: leftovers from the WSL restart fix (#318) - Caused: none known From 66157d2167e17b400af83a7311b9f6bc4f421db5 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:50:04 +0100 Subject: [PATCH 058/157] Mac: keep custom titlebar draggable across toolbar gaps (#337) (#847) Co-authored-by: Ramene Anthony --- crates/kiri/src/ui/mac.rs | 138 +++++++++++++++++++++++++++++++++++--- docs/fix-registry.md | 6 ++ 2 files changed, 136 insertions(+), 8 deletions(-) diff --git a/crates/kiri/src/ui/mac.rs b/crates/kiri/src/ui/mac.rs index fc4694a16..8a61cf3d0 100644 --- a/crates/kiri/src/ui/mac.rs +++ b/crates/kiri/src/ui/mac.rs @@ -35,6 +35,11 @@ thread_local! { /// Scripts for a page made again, kept until it says `ready`: the menu /// bar's Settings… or a container shows the window and sends at once. static QUEUED: RefCell>> = const { RefCell::new(None) }; + /// The last left mouse-down the app received (`watch_presses`), so a + /// drag the page asks for starts where the button went down. + static PRESS: RefCell>> = const { RefCell::new(None) }; + /// The event monitor that keeps `PRESS`; kept for as long as the app runs. + static PRESS_MONITOR: RefCell>> = const { RefCell::new(None) }; } /// `autostart` boots the VM as soon as the page has loaded; `view` picks the @@ -123,6 +128,7 @@ fn make_window(mtm: MainThreadMarker, tx: Sender, autostart: bool, view: Op place_lights(&window); WEBVIEW.with(|w| *w.borrow_mut() = Some(webview)); WINDOW.with(|w| *w.borrow_mut() = Some(window.clone())); + watch_presses(); Ok(window) } @@ -168,6 +174,37 @@ fn release_page() { super::page_gone(); } +/// Keeps each left mouse-down AppKit delivers, before the window gets it, +/// for `drag`, and clears it on mouse-up. The monitor hands every event on +/// unchanged. +fn watch_presses() { + use std::ptr::NonNull; + use objc2_app_kit::{NSEvent, NSEventMask}; + let handler = block2::RcBlock::new(|event: NonNull| -> *mut NSEvent { + // SAFETY: AppKit calls a local monitor on the main thread with a valid event. + record_press(unsafe { event.as_ref() }); + event.as_ptr() + }); + let mask = NSEventMask::LeftMouseDown | NSEventMask::LeftMouseUp; + // SAFETY: an NSEvent class method on the main thread; the handler + // returns the event it was given, so delivery is as before. + let monitor: Option> = + unsafe { msg_send![objc2::class!(NSEvent), addLocalMonitorForEventsMatchingMask: mask, handler: &*handler] }; + PRESS_MONITOR.with(|m| *m.borrow_mut() = monitor); +} + +fn record_press(event: &objc2_app_kit::NSEvent) { + use objc2_app_kit::NSEventType; + let press = if event.r#type() == NSEventType::LeftMouseDown { + // SAFETY: `event` is a live NSEvent reference; retaining it keeps it + // alive after the current run-loop turn's autorelease pool drains. + unsafe { Retained::retain(std::ptr::from_ref(event).cast_mut()) } + } else { + None + }; + PRESS.with(|p| *p.borrow_mut() = press); +} + /// The page's strip across the top (index.html's `.strip`), in points. const STRIP: f64 = 44.0; @@ -426,21 +463,41 @@ pub(super) fn quit() { /// The page covers the title bar, and WebKit ignores CSS drag regions, so /// the page asks for the drag itself on mouse-down over empty chrome. The -/// message lands after the mouse-down: if the button is already up (a quick -/// click), AppKit's current event is the mouse-up, and a drag started then -/// waits for a release that already happened, holding the window until the -/// next click. +/// message lands after the mouse-down, when AppKit's current event is often +/// no longer it (a hand already moving sends mouse-dragged events, a Force +/// Touch trackpad pressure ones), so nothing moved (#337). The drag starts +/// from the real press `watch_presses` kept instead: its place and time, +/// so the window follows the pointer from where the button went down. Only +/// while the button is held: after a quick click the current event is the +/// mouse-up, and a drag started then waits for a release that already +/// happened, holding the window until the next click. pub(super) fn drag() { + use objc2_app_kit::NSEvent; let Some(mtm) = MainThreadMarker::new() else { return }; + let buttons = NSEvent::pressedMouseButtons(); WINDOW.with(|w| { - if let (Some(window), Some(event)) = (w.borrow().as_ref(), NSApplication::sharedApplication(mtm).currentEvent()) { - if event.r#type() == objc2_app_kit::NSEventType::LeftMouseDown && objc2_app_kit::NSEvent::pressedMouseButtons() & 1 != 0 { - window.performWindowDragWithEvent(&event); - } + let Some(window) = w.borrow().clone() else { return }; + if let Some(down) = press_for_drag(window.windowNumber(), buttons, || NSApplication::sharedApplication(mtm).currentEvent()) { + window.performWindowDragWithEvent(&down); } }); } +fn press_for_drag( + window_number: isize, + buttons: usize, + current: impl FnOnce() -> Option>, +) -> Option> { + use objc2_app_kit::NSEventType; + if buttons & 1 == 0 { + PRESS.with(|p| *p.borrow_mut() = None); + return None; + } + let ours = |e: &objc2_app_kit::NSEvent| e.r#type() == NSEventType::LeftMouseDown && e.windowNumber() == window_number; + // This window's press; without one (none seen yet), the current event if it is a press. + PRESS.with(|p| p.borrow().clone()).filter(|e| ours(e)).or_else(|| current().filter(|e| ours(e))) +} + /// Closes the window, as the menu's Close Window did before ⌘W went to the page. /// The page asks from inside WebKit's message callback, and closing can let /// go of that same page (`release_page`), so the close waits for the main @@ -830,3 +887,68 @@ impl AppDelegate { unsafe { msg_send![super(this), init] } } } + +#[cfg(test)] +mod tests { + use objc2::msg_send; + use objc2::rc::{Retained, autoreleasepool}; + use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType}; + use objc2_foundation::NSPoint; + + use super::{PRESS, press_for_drag, record_press}; + + fn mouse_event(kind: NSEventType, window_number: isize, event_number: isize) -> Retained { + // SAFETY: AppKit event constructor with valid value arguments and a nil graphics context. + let event: Option> = unsafe { + msg_send![ + objc2::class!(NSEvent), + mouseEventWithType: kind, + location: NSPoint::new(24.0, 12.0), + modifierFlags: NSEventModifierFlags::empty(), + timestamp: 1.0f64, + windowNumber: window_number, + context: Option::<&objc2::runtime::AnyObject>::None, + eventNumber: event_number, + clickCount: 1isize, + pressure: 1.0f32, + ] + }; + event.expect("mouse event") + } + + #[test] + fn drag_uses_the_kept_press_across_autorelease_pools_until_release() { + PRESS.with(|p| *p.borrow_mut() = None); + + // A mouse-down captured in an earlier run-loop turn survives the pool + // drain and is chosen even after the current event has moved on. + autoreleasepool(|_| { + let down = mouse_event(NSEventType::LeftMouseDown, 7, 101); + record_press(&down); + }); + let dragged = mouse_event(NSEventType::LeftMouseDragged, 7, 102); + let picked = press_for_drag(7, 1, || Some(dragged)).expect("kept press"); + assert_eq!((picked.r#type(), picked.windowNumber(), picked.eventNumber()), (NSEventType::LeftMouseDown, 7, 101)); + + // Another window never takes this window's press, nor lends its own. + assert!(press_for_drag(8, 1, || None).is_none()); + let other = mouse_event(NSEventType::LeftMouseDown, 8, 103); + record_press(&other); + assert!(press_for_drag(7, 1, || Some(other)).is_none()); + + // Once the button is up, a late drag message starts nothing and clears the press. + let down = mouse_event(NSEventType::LeftMouseDown, 7, 104); + record_press(&down); + assert!(press_for_drag(7, 0, || None).is_none()); + assert!(PRESS.with(|p| p.borrow().is_none())); + + // A mouse-up also clears the kept press, and without one a live mouse-down fallback works. + record_press(&down); + let up = mouse_event(NSEventType::LeftMouseUp, 7, 105); + record_press(&up); + assert!(PRESS.with(|p| p.borrow().is_none())); + assert!(press_for_drag(7, 1, || None).is_none()); + let fallback = press_for_drag(7, 1, || Some(down)).expect("current mouse-down fallback"); + assert_eq!(fallback.eventNumber(), 104); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index f07a611e9..e8b2bae74 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 +### #512 Mac: the window drags from its strip from where the button went down (unreleased) +- Fixes: #337 macOS 26: dragging the window from the top strip doesn't move the window +- Caused: none known +- Caused by: - +- Check: none + ### #190 Windows: ignore unrelated processes whose parent PID was recycled in the window usage tree (unreleased) - Fixes: #190 Windows: window usage counts unrelated processes when a recycled parent PID matches a child of Kiri - Caused: none known From 59ab4aa84c97f44810e6e992ce5ce8a1e042546f Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:07:30 +0100 Subject: [PATCH 059/157] UI: refine Persian (fa) translations and terminology (#272) (#848) Co-authored-by: Sadeq N. Yazdi --- crates/kiri/src/ui/lang/fa.json | 114 ++++++++++++++++---------------- docs/fix-registry.md | 6 ++ 2 files changed, 63 insertions(+), 57 deletions(-) diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index a1a6a5e69..8c5c75389 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -127,7 +127,7 @@ "CLI": "CLI", "CPU": "CPU", "CPU is a share of all {n} cores: 100% would be every core busy.": "CPU سهمی از همهٔ {n} هسته است: 100% یعنی همهٔ هسته‌ها مشغول‌اند.", - "CPUs": "CPUها", + "CPUs": "CPU‌ها", "Cached": "در حافظهٔ پنهان", "Camera": "دوربین", "Can't be shared": "قابل اشتراک‌گذاری نیست", @@ -312,7 +312,7 @@ "Environment": "متغیرهای محیطی", "Error": "خطا", "Errors": "خطاها", - "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "همه‌چیز داخل آن حذف می‌شود: podها، serviceها، والیوم‌ها و منابع دیگر، و context {context} در kubectl. شروع بعدی یک کلاستر تازه و خالی می‌سازد.", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "همه‌چیز داخل آن حذف می‌شود: pod‌ها، service‌ها، والیوم‌ها و منابع دیگر، و context {context} در kubectl. شروع بعدی یک کلاستر تازه و خالی می‌سازد.", "Everything in the window.": "همه‌چیز در پنجره.", "Everything is in Kiri.": "همه‌چیز در Kiri است.", "Exit code": "کد خروج", @@ -322,14 +322,14 @@ "External": "خارجی", "Failed": "ناموفق", "Failed ({code})": "ناموفق ({code})", - "Failing": "در حال شکست", + "Failing": "با خطا", "Feedback": "بازخورد", "Files": "فایل‌ها", - "Find": "یافتن", - "Find ({keys})": "یافتن ({keys})", - "Find a path, method or status": "یافتن مسیر، متد یا وضعیت", - "Find in logs": "یافتن در لاگ‌ها", - "Find in the terminal": "یافتن در ترمینال", + "Find": "جست‌وجو", + "Find ({keys})": "جست‌وجو ({keys})", + "Find a path, method or status": "جست‌وجوی مسیر، متد یا وضعیت", + "Find in logs": "جست‌وجو در لاگ‌ها", + "Find in the terminal": "جست‌وجو در ترمینال", "Finish updating to Kiri {version}": "تکمیل به‌روزرسانی به Kiri {version}", "Finished": "پایان یافت", "Fix all": "رفع همه", @@ -369,7 +369,7 @@ "Hand it to Kiri's containers": "سپردن به کانتینرهای Kiri", "Has a fix": "اصلاحیه دارد", "Have": "موجود", - "Headless: there's no cluster address to share. Share one of its pods.": "Headless: نشانی کلاستری برای اشتراک‌گذاری وجود ندارد. یکی از podهای آن را به اشتراک بگذارید.", + "Headless: there's no cluster address to share. Share one of its pods.": "Headless: نشانی کلاستری برای اشتراک‌گذاری وجود ندارد. یکی از pod‌های آن را به اشتراک بگذارید.", "Health check": "بررسی سلامت", "Helpers|process": "فرایندهای کمکی", "Hide": "پنهان کردن", @@ -385,7 +385,7 @@ "How it runs": "نحوهٔ اجرا", "How should you reach your containers?": "چطور می‌خواهید به کانتینرهایتان دسترسی داشته باشید؟", "ID": "ID", - "IDs, commands and code.": "IDها، فرمان‌ها و کد.", + "IDs, commands and code.": "ID‌ها، فرمان‌ها و کد.", "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "نشانی‌های IP یا نام‌های دامنه، جداشده با ویرگول، که گواهی سرور API هم آن‌ها را پوشش می‌دهد، مانند نشانی این {host} در شبکهٔ شما. ذخیره کلاستر را دوباره راه‌اندازی می‌کند.", "If Kiri's useful, a star on GitHub helps others find it.": "اگر Kiri به کارتان آمده، یک ستاره در GitHub به دیگران کمک می‌کند آن را پیدا کنند.", "If it's private, run {cmd} first.": "اگر خصوصی است، ابتدا {cmd} را اجرا کنید.", @@ -407,7 +407,7 @@ "Importing…": "در حال وارد کردن…", "In Kiri": "در Kiri", "In a container": "در کانتینر", - "In a week": "یک هفتهٔ دیگر", + "In a week": "یک هفته بعد", "In use": "در حال استفاده", "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "در حال استفاده: {used}. ماشین مجازی هم‌اکنون می‌تواند تا {target} بگیرد و با نیاز کانتینرها بیشتر می‌شود.", "In use: {proxy}, except {hosts}.": "در حال استفاده: {proxy}، به‌جز {hosts}.", @@ -428,7 +428,7 @@ "Interface font": "قلم رابط", "Internal steps": "مراحل داخلی", "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "می‌خواهد خود ماشین مجازی Linux را تغییر دهد، که «اجرا» اجازه نمی‌دهد. اگر به {image} اعتماد دارید، خودتان آن را با {cmd} اجرا کنید.", - "It has no selector, so it picks no pods.": "selector ندارد، پس هیچ podی را انتخاب نمی‌کند.", + "It has no selector, so it picks no pods.": "selector ندارد، پس هیچ pod را انتخاب نمی‌کند.", "It restarts, so open connections drop.": "دوباره راه‌اندازی می‌شود، پس اتصال‌های باز قطع می‌شوند.", "It stays up while Kiri is running.": "تا وقتی Kiri در حال اجراست فعال می‌ماند.", "It takes effect when it next starts.": "در شروع بعدی اعمال می‌شود.", @@ -455,7 +455,7 @@ "Keep": "نگه داشتن", "Keep building with Docker": "ادامهٔ ساخت با Docker", "Keep building with Docker.": "ادامهٔ ساخت با Docker.", - "Keep typing to search Docker Hub.": "برای جست‌وجو در Docker Hub به تایپ ادامه دهید.", + "Keep typing to search Docker Hub.": "به تایپ ادامه دهید تا در Docker Hub جست‌وجو شود.", "Keep using your PC meanwhile.": "در این مدت می‌توانید به کار با رایانه ادامه دهید.", "Kept in Credential Manager": "در Credential Manager نگه داشته می‌شود", "Kept in the Keychain": "در Keychain نگه داشته می‌شود", @@ -532,7 +532,7 @@ "Later: Kiri waits in the tray and picks up after your next restart.": "بعداً: Kiri در سینی سیستم منتظر می‌ماند و پس از راه‌اندازی مجدد بعدی ادامه می‌دهد.", "Layer": "لایه", "Layers": "لایه‌ها", - "Let it pick a random one": "انتخاب تصادفی", + "Let it pick a random one": "یکی به‌صورت تصادفی انتخاب شود", "Lets {user} run containers without sudo": "به {user} اجازه می‌دهد کانتینرها را بدون sudo اجرا کند", "Level": "سطح", "Light": "روشن", @@ -561,7 +561,7 @@ "Looking for OrbStack and Docker Desktop…": "در حال جست‌وجوی OrbStack و Docker Desktop…", "Looking for USB devices…": "در حال جست‌وجوی دستگاه‌های USB…", "Looking for crash reports…": "در حال جست‌وجوی گزارش‌های خرابی…", - "Looking for shells…": "در حال جست‌وجوی shellها…", + "Looking for shells…": "در حال جست‌وجوی shell‌ها…", "Low": "پایین", "MFA code": "کد MFA", "Mac": "Mac", @@ -577,13 +577,13 @@ "Memory full · {mem}": "حافظه پر است · {mem}", "Method": "متد", "Mirror address": "نشانی آینه", - "Modified": "تغییر", + "Modified": "تغییریافته", "Monospace font": "قلم هم‌عرض", "More": "بیشتر", "More actions for {name}": "عملیات بیشتر برای {name}", "More memory": "حافظهٔ بیشتر", "More settings": "تنظیمات بیشتر", - "Mounts": "Mountها", + "Mounts": "Mount‌ها", "Mouse": "ماوس", "MySQL won't start until you choose how its root account signs in.": "MySQL تا وقتی روش ورود حساب root آن را انتخاب نکنید شروع نمی‌شود.", "Name": "نام", @@ -623,15 +623,15 @@ "No password, no login and no TLS. Fine on this Mac, not for anything shared.": "بدون گذرواژه، بدون ورود و بدون TLS. روی این Mac مشکلی ندارد، برای چیزهای اشتراکی نه.", "No password, no login and no TLS. Fine on this PC, not for anything shared.": "بدون گذرواژه، بدون ورود و بدون TLS. روی این رایانه مشکلی ندارد، برای چیزهای اشتراکی نه.", "No password, no login and no TLS. Fine on this computer, not for anything shared.": "بدون گذرواژه، بدون ورود و بدون TLS. روی این رایانه مشکلی ندارد، برای چیزهای اشتراکی نه.", - "No pods": "podی نیست", - "No pods match its selector.": "هیچ podی با selector آن مطابقت ندارد.", + "No pods": "pod‌ای نیست", + "No pods match its selector.": "هیچ pod با selector آن مطابقت ندارد.", "No ports to share": "پورتی برای اشتراک‌گذاری نیست", "No proxy is in use.": "هیچ پراکسی‌ای استفاده نمی‌شود.", "No requests match.": "هیچ درخواستی مطابقت ندارد.", "No requests yet": "هنوز درخواستی نیست", "No results": "نتیجه‌ای نیست", - "No service points at it, so the link goes straight to the pod.": "هیچ serviceی به آن اشاره نمی‌کند، پس پیوند مستقیم به pod می‌رود.", - "No services": "serviceی نیست", + "No service points at it, so the link goes straight to the pod.": "هیچ service به آن اشاره نمی‌کند، پس پیوند مستقیم به pod می‌رود.", + "No services": "service‌ای نیست", "No steps here.": "مرحله‌ای اینجا نیست.", "No visitors in the last 2 minutes": "در 2 دقیقهٔ گذشته بازدیدکننده‌ای نبود", "No volumes yet": "هنوز والیومی نیست", @@ -648,8 +648,8 @@ "Not created yet": "هنوز ساخته نشده", "Not found.": "پیدا نشد.", "Not in use: no container was made from it": "استفاده نشده: هیچ کانتینری از آن ساخته نشده", - "Not now": "الان نه", - "Not now: ask again in a week": "الان نه: یک هفتهٔ دیگر دوباره بپرس", + "Not now": "فعلاً نه", + "Not now: ask again in a week": "فعلاً نه: یک هفته بعد دوباره یادآوری شود", "Not running": "در حال اجرا نیست", "Not sent": "ارسال نشد", "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "هنوز راه‌اندازی نشده است. در نخستین ساخت شما ایجاد می‌شود که BuildKit (حدود 110 MB) را یک بار دانلود می‌کند.", @@ -677,7 +677,7 @@ "Off: Kiri checks only when you click Check now.": "خاموش: Kiri فقط وقتی روی «بررسی اکنون» کلیک کنید بررسی می‌کند.", "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "خاموش: کانتینرها روی <name>.kiri.localhost پاسخ می‌دهند که به تنظیم نیاز ندارد.", "Off: press Start engine to run containers. It stays off after a restart until you start it.": "خاموش: برای اجرای کانتینرها «شروع موتور» را بزنید. پس از راه‌اندازی مجدد هم تا وقتی شروعش نکنید خاموش می‌ماند.", - "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "خاموش: سرور API و serviceهای LoadBalancer فقط روی این {host} (127.0.0.1) پاسخ می‌دهند.", + "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "خاموش: سرور API و service‌های LoadBalancer فقط روی این {host} (127.0.0.1) پاسخ می‌دهند.", "Official": "رسمی", "On": "روشن", "On disk": "روی دیسک", @@ -688,7 +688,7 @@ "On: Kiri checks each time it opens. It never updates without asking.": "روشن: Kiri هر بار که باز می‌شود بررسی می‌کند. هرگز بدون پرسیدن به‌روز نمی‌شود.", "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "روشن: کانتینرها با گواهی خود Kiri روی https:// باز می‌شوند که فقط نام‌های .kiri.local و .kiri.localhost را تضمین می‌کند.", "On: running containers answer at <name>.kiri.local.": "روشن: کانتینرهای در حال اجرا روی <name>.kiri.local پاسخ می‌دهند.", - "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "روشن: سرور API و serviceهای LoadBalancer روی همهٔ رابط‌های شبکه پاسخ می‌دهند، پس دستگاه‌های دیگر شبکهٔ شما می‌توانند به آن‌ها دسترسی داشته باشند.", + "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "روشن: سرور API و service‌های LoadBalancer روی همهٔ رابط‌های شبکه پاسخ می‌دهند، پس دستگاه‌های دیگر شبکهٔ شما می‌توانند به آن‌ها دسترسی داشته باشند.", "One more step: log out and back in.": "یک مرحلهٔ دیگر: خارج شوید و دوباره وارد شوید.", "One more step: set it up, or skip.": "یک مرحلهٔ دیگر: راه‌اندازی‌اش کنید یا رد شوید.", "One restart to finish WSL": "یک راه‌اندازی مجدد برای تکمیل WSL", @@ -732,9 +732,9 @@ "Paste {n} lines? Each line runs as a command.": "{n} خط جای‌گذاری شود؟ هر خط به‌عنوان یک فرمان اجرا می‌شود.", "Path": "مسیر", "Pause": "مکث", - "Paused": "متوقف موقت", - "Paused · nobody can open the link": "متوقف موقت · هیچ کس نمی‌تواند پیوند را باز کند", - "Paused: nobody can open the link until you resume.": "متوقف موقت: تا وقتی ادامه ندهید، هیچ کس نمی‌تواند پیوند را باز کند.", + "Paused": "مکث‌شده", + "Paused · nobody can open the link": "مکث‌شده · هیچ کس نمی‌تواند پیوند را باز کند", + "Paused: nobody can open the link until you resume.": "مکث‌شده: تا وقتی ادامه ندهید، هیچ کس نمی‌تواند پیوند را باز کند.", "Peak {rate}": "اوج {rate}", "Pin tab": "سنجاق کردن زبانه", "Pink": "صورتی", @@ -746,13 +746,13 @@ "Pod in {ns}": "Pod در {ns}", "Pod in {ns} · on {node}": "Pod در {ns} · روی {node}", "Pods": "Pods", - "Pods you create with kubectl show up here, grouped by namespace.": "podهایی که با kubectl می‌سازید، گروه‌بندی‌شده بر اساس namespace، اینجا نمایش داده می‌شوند.", + "Pods you create with kubectl show up here, grouped by namespace.": "pod‌هایی که با kubectl می‌سازید، گروه‌بندی‌شده بر اساس namespace، اینجا نمایش داده می‌شوند.", "Port": "پورت", "Port in the container": "پورت در کانتینر", "Port on your {host}": "پورت روی {host} شما", "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "پورت روی {host} شما (localhost) ← پورت داخل کانتینر. سمت {host} را خالی بگذارید تا یک پورت آزاد انتخاب شود.", "Port {port} is already in use on this {host}": "پورت {port} از قبل روی این {host} در حال استفاده است", - "Port {port}. The link keeps working when pods restart.": "پورت {port}. پیوند هنگام راه‌اندازی مجدد podها همچنان کار می‌کند.", + "Port {port}. The link keeps working when pods restart.": "پورت {port}. پیوند هنگام راه‌اندازی مجدد pod‌ها همچنان کار می‌کند.", "Ports": "پورت‌ها", "Ports changed": "پورت‌ها تغییر کردند", "Ports for {name}": "پورت‌های {name}", @@ -760,7 +760,7 @@ "Ports saved: {ports}": "پورت‌ها ذخیره شدند: {ports}", "Ports…": "پورت‌ها…", "Postgres won't start without a superuser password.": "Postgres بدون گذرواژهٔ superuser شروع نمی‌شود.", - "Powered by": "با قدرت", + "Powered by": "با پشتیبانی", "Press Share on a running container to give it a public https link anyone can open.": "روی یک کانتینر در حال اجرا اشتراک‌گذاری را بزنید تا یک پیوند https عمومی بگیرد که هر کسی بتواند بازش کند.", "Press to see it, or disconnect it.": "برای دیدن یا قطع اتصال آن بزنید.", "Press to try again": "برای تلاش دوباره بزنید", @@ -780,7 +780,7 @@ "Publish on {targets}": "انتشار روی {targets}", "Publish the port {name} listens on, and give it a public https link": "انتشار پورتی که {name} روی آن گوش می‌دهد و دادن یک پیوند https عمومی به آن", "Pull": "Pull", - "Pull again": "pull دوباره", + "Pull again": "دوباره pull", "Pull an image": "pull یک ایمیج", "Pull an image ({key})": "pull یک ایمیج ({key})", "Pull exactly this": "pull دقیقاً همین", @@ -811,7 +811,7 @@ "Ready": "آماده", "Recent crashes": "خرابی‌های اخیر", "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "لاگ‌های اخیر، گزارش‌های خرابی و نسخه‌ها در یک فایل با اطلاعات حساس پوشانده‌شده، برای وقتی که مشکلی پیش می‌آید.", - "Recent pulls": "pullهای اخیر", + "Recent pulls": "pull‌های اخیر", "Recommended": "پیشنهادی", "Reconnecting": "در حال اتصال مجدد", "Reconnecting {name}…": "در حال اتصال مجدد {name}…", @@ -881,7 +881,7 @@ "Running, not ready": "در حال اجرا، آماده نیست", "Running: it rests by itself when nothing runs and wakes when you use it.": "در حال اجرا: وقتی چیزی اجرا نمی‌شود خودش استراحت می‌کند و با استفادهٔ شما بیدار می‌شود.", "Running: {cmd}": "در حال اجرا: {cmd}", - "Runs": "اجرا می‌کند", + "Runs": "دستور اجرا", "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "هر فرمان را با {sh} در {name} اجرا می‌کند؛ {cd} حفظ می‌شود. ↑ و ↓ فرمان‌های قبلی را مرور می‌کنند.", "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "همین‌جا روی Mac شما روی نسخهٔ ایمیج در Kiri اجرا می‌شود؛ چیزی بارگذاری نمی‌شود.", "Runs your containers": "کانتینرهای شما را اجرا می‌کند", @@ -915,7 +915,7 @@ "Search Kiri": "جست‌وجو در Kiri", "Search Kiri…": "جست‌وجو در Kiri…", "Search containers, images…": "جست‌وجوی کانتینرها، ایمیج‌ها…", - "Search languages": "جستجوی زبان", + "Search languages": "جست‌وجوی زبان", "Search {view}…": "جست‌وجو در {view}…", "Searching Docker Hub": "در حال جست‌وجو در Docker Hub", "Security": "امنیت", @@ -927,7 +927,7 @@ "Select All": "انتخاب همه", "Select all": "انتخاب همه", "Select all {n}": "انتخاب همهٔ {n} مورد", - "Select none": "انتخاب هیچ", + "Select none": "لغو انتخاب همه", "Select {name}": "انتخاب {name}", "Selected {what}": "انتخاب‌شده: {what}", "Selection, focus rings and primary buttons.": "انتخاب، حلقه‌های فوکوس و دکمه‌های اصلی.", @@ -945,7 +945,7 @@ "Serial": "سریال", "Serial number": "شمارهٔ سریال", "Services": "Services", - "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "serviceهایی که با kubectl expose می‌سازید اینجا نمایش داده می‌شوند. serviceهای LoadBalancer روی localhost پاسخ می‌دهند.", + "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "service‌هایی که با kubectl expose می‌سازید اینجا نمایش داده می‌شوند. service‌های LoadBalancer روی localhost پاسخ می‌دهند.", "Session": "نشست", "Set it and start": "تنظیم و شروع", "Set up": "راه‌اندازی", @@ -995,7 +995,7 @@ "Show password": "نمایش گذرواژه", "Show shares": "نمایش اشتراک‌ها", "Show the crash report": "نمایش گزارش خرابی", - "Show the pulls in Images": "نمایش pullها در ایمیج‌ها", + "Show the pulls in Images": "نمایش pull‌ها در ایمیج‌ها", "Show the sidebar": "نمایش نوار کناری", "Show the terminal ({keys})": "نمایش ترمینال ({keys})", "Show the update": "نمایش به‌روزرسانی", @@ -1008,7 +1008,7 @@ "Sign in to {registry}": "ورود به {registry}", "Sign in with AWS": "ورود با AWS", "Sign in with GitHub": "ورود با GitHub", - "Sign out": "خروج", + "Sign out": "خروج از حساب", "Sign out of {registry}": "خروج از {registry}", "Sign out of {registry}?": "از {registry} خارج می‌شوید؟", "Sign-in failed: {error}": "ورود ناموفق بود: {error}", @@ -1023,7 +1023,7 @@ "Signing in…": "در حال ورود…", "Signing out…": "در حال خروج…", "Size": "اندازه", - "Skip": "رد شدن", + "Skip": "رد کردن", "Skip this version": "رد کردن این نسخه", "Skipped: docker build builds where docker points": "رد شد: docker build همان جایی می‌سازد که docker اشاره می‌کند", "Skipped: docker keeps using the engine it has now": "رد شد: docker همچنان از موتور فعلی‌اش استفاده می‌کند", @@ -1046,7 +1046,7 @@ "Start Kiri to change its registry settings. ({error})": "برای تغییر تنظیمات رجیستری، Kiri را شروع کنید. ({error})", "Start Kiri to change its resources. ({error})": "برای تغییر منابع Kiri، آن را شروع کنید. ({error})", "Start Kiri to change the ports names answer on.": "برای تغییر پورت‌هایی که نام‌ها روی آن‌ها پاسخ می‌دهند، Kiri را شروع کنید.", - "Start Kiri when I sign in (in the tray)": "شروع Kiri هنگام ورود من (در سینی سیستم)", + "Start Kiri when I sign in (in the tray)": "شروع Kiri هنگام ورود به حساب (در سینی سیستم)", "Start Kubernetes": "شروع Kubernetes", "Start Linux VM": "شروع ماشین مجازی Linux", "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "یک کلاستر تک‌node (k3s) را در یک کانتینر Kiri شروع می‌کند. API آن روی {api} (یا پورت آزاد بعدی) است و kubectl، context {context} را می‌گیرد، مانند kiri k8s start.", @@ -1088,7 +1088,7 @@ "Stop {name}": "توقف {name}", "Stop {name} on {host}?": "{name} روی {host} متوقف شود؟", "Stopped": "متوقف", - "Stopped {when}": "متوقف شد {when}", + "Stopped {when}": "{when} متوقف شد", "Stopped {when}, when the {vm} stopped. Start it again whenever you like.": "{when} متوقف شد، وقتی {vm} متوقف شد. هر وقت خواستید دوباره شروعش کنید.", "Stopped {when}: its memory ran out": "{when} متوقف شد: حافظه‌اش تمام شد", "Stopped {when}: its memory ran out (the VM has {mem})": "{when} متوقف شد: حافظه‌اش تمام شد (ماشین مجازی {mem} دارد)", @@ -1220,8 +1220,8 @@ "Untagged; another tag still uses it": "تگ برداشته شد؛ تگ دیگری هنوز از آن استفاده می‌کند", "Unused": "استفاده‌نشده", "Up to date": "به‌روز", - "Up {time}": "فعال از {time}", - "Up {time} (Paused)": "فعال از {time} (متوقف موقت)", + "Up {time}": "{time} در حال اجرا", + "Up {time} (Paused)": "{time} در حال اجرا (مکث‌شده)", "Updating": "در حال به‌روزرسانی", "Updating the vulnerability database (about 200 MB the first time)": "در حال به‌روزرسانی پایگاه دادهٔ آسیب‌پذیری‌ها (حدود 200 MB بار اول)", "Upper and lower case, a digit and a symbol, 8 or more": "حروف بزرگ و کوچک، یک رقم و یک نماد، دست‌کم 8 نویسه", @@ -1241,11 +1241,11 @@ "Use your password, or a robot account's name and token.": "از گذرواژهٔ خود، یا نام و توکن یک حساب ربات استفاده کنید.", "Use {app} for docker?": "از {app} برای docker استفاده شود؟", "Use {name} instead": "به‌جای آن از {name} استفاده شود", - "Used by": "مورد استفادهٔ", + "Used by": "استفاده‌شده توسط", "User": "کاربر", "Username": "نام کاربری", "Using the Ubuntu already on this PC: nothing to download.": "استفاده از Ubuntu موجود روی این رایانه: چیزی برای دانلود نیست.", - "VPNs need no setting: container traffic leaves through macOS.": "VPNها به تنظیم نیاز ندارند: ترافیک کانتینرها از طریق macOS خارج می‌شود.", + "VPNs need no setting: container traffic leaves through macOS.": "VPN‌ها به تنظیم نیاز ندارند: ترافیک کانتینرها از طریق macOS خارج می‌شود.", "Value": "مقدار", "Version {version}": "نسخهٔ {version}", "Versions, macOS, whether the engine runs, how many containers and images": "نسخه‌ها، macOS، اجرا بودن یا نبودن موتور، تعداد کانتینرها و ایمیج‌ها", @@ -1296,7 +1296,7 @@ "You can change it later in Settings → Appearance.": "بعداً می‌توانید آن را در تنظیمات ← ظاهر تغییر دهید.", "You can change this later in Settings → Domains.": "بعداً می‌توانید این را در تنظیمات ← دامنه‌ها تغییر دهید.", "You can keep working while they copy.": "هنگام کپی شدن می‌توانید به کار ادامه دهید.", - "You can pull it again later.": "بعداً می‌توانید دوباره pullش کنید.", + "You can pull it again later.": "بعداً می‌توانید آن را دوباره pull کنید.", "You can still pull the name as typed.": "همچنان می‌توانید نام را همان‌طور که تایپ شده pull کنید.", "You can switch any time in Settings → Builds.": "هر وقت بخواهید می‌توانید در تنظیمات ← ساخت‌ها تغییرش دهید.", "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "{ref} را دارید، {when}. برای گرفتن به‌روزرسانی‌ها دوباره pull کنید؛ فقط لایه‌های تغییرکرده دانلود می‌شوند.", @@ -1322,7 +1322,7 @@ "Your test container said hello. Open a new terminal and try it yourself:": "کانتینر آزمایشی‌تان سلام کرد. یک ترمینال جدید باز کنید و خودتان امتحان کنید:", "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "ایمیج‌ها و کانتینرهای {engine} در {engine} می‌مانند. {app} تا وقتی آن‌ها را منتقل نکنید آن‌ها را نمی‌بیند.", "Your {engine} images stay there. Bring them over any time from Settings → Import.": "ایمیج‌های {engine} آنجا می‌مانند. هر وقت خواستید از تنظیمات ← وارد کردن منتقلشان کنید.", - "Yours": "مال شما", + "Yours": "حساب شما", "Zoom In": "بزرگ‌نمایی", "Zoom Out": "کوچک‌نمایی", "a container": "یک کانتینر", @@ -1403,8 +1403,8 @@ "layers": "لایه‌ها", "line {n}": "خط {n}", "links open in this app": "پیوندها در این برنامه باز می‌شوند", - "live": "زنده", - "live {time}": "فعال از {time}", + "live": "فعال", + "live {time}": "فعال به مدت {time}", "macOS will ask for an administrator password next.": "macOS در ادامه گذرواژهٔ مدیر سیستم را می‌پرسد.", "made {ago}": "ساخته‌شده {ago}", "move": "جابه‌جایی", @@ -1429,7 +1429,7 @@ "owner/image on {registry}, such as {example}": "owner/image در {registry}، مانند {example}", "peak {rate}": "اوج {rate}", "pinned digest": "digest ثابت", - "pods": "podها", + "pods": "pod‌ها", "port {port}": "پورت {port}", "port {port} is in use": "پورت {port} در حال استفاده است", "pull": "pull", @@ -1447,7 +1447,7 @@ "saved with {v}": "ذخیره‌شده با {v}", "sent to visitors": "فرستاده‌شده به بازدیدکنندگان", "serial port": "درگاه سریال", - "services": "serviceها", + "services": "service‌ها", "sets {var}, for local use only.": "{var} را تنظیم می‌کند، فقط برای استفادهٔ محلی.", "sets {var}, so it runs without a login or TLS.": "{var} را تنظیم می‌کند، پس بدون ورود یا TLS اجرا می‌شود.", "sets {var}; it prints the password once in its log.": "{var} را تنظیم می‌کند؛ گذرواژه را یک بار در لاگ خود چاپ می‌کند.", @@ -1475,11 +1475,11 @@ "tunnels in use": "تونل‌های در حال استفاده", "untagged": "بدون تگ", "untagged images": "ایمیج‌های بدون تگ", - "up": "متصل", + "up": "فعال", "up to {size}": "تا {size}", - "up {time}": "فعال از {time}", + "up {time}": "فعال به مدت {time}", "usbipd-win is installed": "usbipd-win نصب است", - "used by {names}": "مورد استفادهٔ {names}", + "used by {names}": "استفاده‌شده توسط {names}", "value": "مقدار", "video": "ویدیو", "volumes": "والیوم‌ها", @@ -1515,9 +1515,9 @@ "{image} is a whole Kubernetes cluster in a container.": "{image} یک کلاستر کامل Kubernetes در یک کانتینر است.", "{image} needs {what} to start": "{image} برای شروع به {what} نیاز دارد", "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s} کلاستر Kubernetes خود Kiri است. حذف آن Kubernetes را خاموش می‌کند. داده‌های کلاستر در والیوم {k8s} می‌ماند؛ «حذف کلاستر» در تنظیمات ← Kubernetes همه‌چیز را حذف می‌کند.", - "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} کلاستر Kubernetes خود Kiri است. توقف آن Kubernetes را خاموش می‌کند و podهای آن تا شروع دوباره متوقف می‌مانند.", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} کلاستر Kubernetes خود Kiri است. توقف آن Kubernetes را خاموش می‌کند و pod‌های آن تا شروع دوباره متوقف می‌مانند.", "{kind} names are off: port {port} is in use. Pick another.": "نام‌های {kind} خاموش‌اند: پورت {port} در حال استفاده است. پورت دیگری انتخاب کنید.", - "{kind} names are paused: a container has port {port}.": "نام‌های {kind} متوقف موقت‌اند: یک کانتینر پورت {port} را دارد.", + "{kind} names are paused: a container has port {port}.": "نام‌های {kind} مکث‌شده‌اند: یک کانتینر پورت {port} را دارد.", "{label}, last minute": "{label}، دقیقهٔ اخیر", "{list} and {last}": "{list} و {last}", "{list} are running from this image. Stop them first, then remove the image.": "{list} از این ایمیج در حال اجرا هستند. ابتدا آن‌ها را متوقف کنید، سپس ایمیج را حذف کنید.", diff --git a/docs/fix-registry.md b/docs/fix-registry.md index e8b2bae74..32ae9d3fb 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 +### #272 UI: Persian wording, consistent terms and half-spaces (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #512 Mac: the window drags from its strip from where the button went down (unreleased) - Fixes: #337 macOS 26: dragging the window from the top strip doesn't move the window - Caused: none known From 98739cfaccd6fc0a836047da56a2c2855b38c590 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:24:24 +0100 Subject: [PATCH 060/157] Linux: persist clipboard contents on Wayland and X11 via GTK Clipboard (#290) (#849) Co-authored-by: zamkara --- crates/kiri/src/ui/k8s.rs | 11 +++++++++-- docs/fix-registry.md | 6 ++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/ui/k8s.rs b/crates/kiri/src/ui/k8s.rs index 6edf81986..47f8c0d11 100644 --- a/crates/kiri/src/ui/k8s.rs +++ b/crates/kiri/src/ui/k8s.rs @@ -73,8 +73,15 @@ pub fn handle(action: &str, value: &Value) { } } -/// Settings' Copy buttons (the API server's address, a kubectl command), by -/// pbcopy: the page's own clipboard needs a gesture WebKit doesn't always see. +/// Settings' Copy buttons (the API server's address, a kubectl command): +/// the page's own clipboard needs a gesture WebKit doesn't always see. +#[cfg(target_os = "linux")] +fn copy(text: &str) { + super::window::copy(text); + emit(notice("ok", &super::trf("Copied {text}", &[("text", &text)]))); +} + +#[cfg(not(target_os = "linux"))] fn copy(text: &str) { use std::io::Write; let done = std::process::Command::new("/usr/bin/pbcopy").stdin(std::process::Stdio::piped()).spawn().and_then(|mut c| { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 32ae9d3fb..5a679228f 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 +### #290 Linux: use GTK clipboard for Kubernetes Settings Copy buttons (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #272 UI: Persian wording, consistent terms and half-spaces (unreleased) - Fixes: no issue - Caused: none known From 758c17bfedb746f78bff854b6294ab1599a2195e Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:40:11 +0100 Subject: [PATCH 061/157] Tests: widen wait_alive retry window for loaded CI runners (#395) (#851) --- crates/kiri-win/src/client.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index 04b26becc..38006a67e 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -672,15 +672,16 @@ mod tests { assert_eq!(seen.len(), 3); assert!(seen[2] < seen[0], "remaining budget should shrink across retries: {seen:?}"); - // Fast failing probes stop once `limit` passes. + // Fast failing probes stop once `limit` passes (generous window so a + // 5 ms sleep oversleeping on a loaded CI VM still gets >= 2 tries). let mut fast_calls = 0usize; let began = Instant::now(); - assert!(!wait_alive_with(Duration::from_millis(100), Duration::from_millis(25), |_| { + assert!(!wait_alive_with(Duration::from_millis(450), Duration::from_millis(5), |_| { fast_calls += 1; false })); - assert!((2..=10).contains(&fast_calls), "unexpected retry count: {fast_calls}"); - assert!(began.elapsed() >= Duration::from_millis(90) && began.elapsed() < Duration::from_millis(400), "waited {:?}", began.elapsed()); + assert!(fast_calls >= 2, "unexpected retry count: {fast_calls}"); + assert!(began.elapsed() >= Duration::from_millis(400) && began.elapsed() < Duration::from_secs(3), "waited {:?}", began.elapsed()); } #[test] From f774a15597c7c002bfe47190ce5590712f8dfd14 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:48:13 +0100 Subject: [PATCH 062/157] CLI: allow kiri domains set and reset while the engine is stopped (#744) (#852) --- crates/kiri/src/domains_cli.rs | 29 +++++++++++++++++++++++++++-- docs/fix-registry.md | 6 ++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index 5ffd12c72..5ca458bf1 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -76,7 +76,15 @@ fn answer(r: client::Response) -> io::Result { } pub fn run(args: &[String]) -> io::Result<()> { - let v = match parse(args).map_err(io::Error::other)? { + run_with(args, client::alive) +} + +fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { + 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 }; @@ -92,8 +100,9 @@ pub fn run(args: &[String]) -> io::Result<()> { #[cfg(test)] mod tests { - use super::{Cmd, format, parse}; + use super::{Cmd, format, parse, run_with}; use serde_json::json; + use std::io; fn args(s: &str) -> Vec { s.split_whitespace().map(String::from).collect() @@ -130,4 +139,20 @@ mod tests { let moved = json!({"http": {"port": 18780, "running": true, "serving": false, "env": "KIRI_HTTP_PORT"}, "https": {"port": 18743, "running": true, "serving": true, "env": null}}); assert_eq!(format(&moved), "HTTP 18780 on, a container has the port for now (set by KIRI_HTTP_PORT)\nHTTPS 18743 on\n"); } + + #[test] + fn bad_arguments_fail_before_touching_the_socket() { + for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown"] { + let err = run_with(&args(bad), || panic!("checked daemon before arguments: {bad}")).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad}: {err}"); + } + } + + #[test] + fn says_when_the_daemon_is_not_running() { + for cmd in ["", "set --http 8080 --https 8443", "set --http 8080", "reset"] { + 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/docs/fix-registry.md b/docs/fix-registry.md index 5a679228f..2848f770d 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 +### #744 CLI: `kiri domains` says when the daemon is not running (unreleased) +- Fixes: #744 kiri domains prints "No such file or directory (os error 2)" with no engine +- Caused: none known +- Caused by: - +- Check: none + ### #290 Linux: use GTK clipboard for Kubernetes Settings Copy buttons (unreleased) - Fixes: no issue - Caused: none known From ad9b58fb95da6cccff7f66a9c4bec01a1bf39792 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:00:42 +0100 Subject: [PATCH 063/157] Import: carry over container writable layers and allow diff before first start (#410) (#853) --- crates/kiri-init/src/linux/container.rs | 13 +- crates/kiri-init/src/linux/copy.rs | 194 +++++++ crates/kiri-init/src/linux/layers.rs | 5 +- crates/kiri-proto/src/lib.rs | 7 +- crates/kiri-win/src/client.rs | 79 +++ crates/kiri/src/client.rs | 87 +++ crates/kiri/src/daemon/api.rs | 70 ++- crates/kiri/src/daemon/engine.rs | 6 +- crates/kiri/src/daemon/ops.rs | 2 +- crates/kiri/src/import.rs | 677 +++++++++++++++++++++++- docs/fix-registry.md | 6 + tests/e2e.sh | 33 +- tests/import.sh | 22 +- tests/regressions.tsv | 10 + 14 files changed, 1197 insertions(+), 14 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 329d5d469..97e24598d 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -861,7 +861,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

io::Result { Ok(true) } +/// Marks a writable layer that `kiri import` brought in whole as plain +/// (see `plain_upper`): it holds whole files, whole directories, whiteouts +/// and opaque marks, and no overlayfs redirects or metadata-only copies +/// (`copy` strips those attributes). Without the mark its first mount would +/// find it already written to and keep the kernel's defaults, under which +/// later writes may redirect directories that `docker diff` and `commit` +/// can't read. +pub(super) fn mark_plain_upper(base: &Path) -> io::Result<()> { + fs::write(base.join(PLAIN_UPPER), b"") +} + /// The overlayfs features to mount with, whatever the kernel's defaults /// (Arch, CachyOS and xanmod turn them on, #227): /// - index=off always: with index on, a second mount of an upper dir still diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index c9f550c09..23b71afd8 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -191,6 +191,8 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa let result = match spec.op { // These read the writable layer itself, next to the image's layers. copy_op::DIFF | copy_op::COMMIT => layer_job(&mut conn, &spec, paths), + // And this one writes it, before the container ever runs. + copy_op::UPPER => upper_job(&mut conn, &spec, running, paths, &chan), _ => { let mounts = match enter(&spec, running, paths, &chan) { Ok(m) => m, @@ -1051,6 +1053,114 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res w.flush() } +/// `kiri import`: the writable layer a container had on the engine it came +/// from, as an OCI layer tar (see `copy_op::UPPER`), becomes its own before +/// it ever runs. Writing under the upper dir of a mounted overlay is +/// undefined behaviour to the kernel, so a running container, or one whose +/// root is mounted for a copy, is refused, as is one that has a writable +/// layer already. +fn upper_job(conn: &mut fs::File, spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> { + if spec.layers.is_empty() { + return reply_error(conn, "no such container"); + } + container::valid_id(spec.id)?; + // `h` holds a root only when it is mounted; this child exits soon and + // lets it go again. + if running.iter().any(|(id, _)| *id == spec.id) || ask(chan, 'h', spec).is_ok() { + return reply_error(conn, &format!("container {} is in use: its writable layer can only be brought in before it runs", spec.id)); + } + let base = paths.containers.join(spec.id); + if fs::read_dir(base.join("upper")).is_ok_and(|mut d| d.next().is_some()) { + return reply_error(conn, &format!("container {} already has a writable layer of its own", spec.id)); + } + let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) }; + import_upper(BufReader::with_capacity(256 * 1024, source), &base)?; + done(conn) +} + +/// Unpacks the layer `reader` holds into `/upper`. It is unpacked +/// beside it first and moved in whole, so a copy cut short leaves the +/// container as it was; overlayfs's own attributes are stripped, and the +/// layer is marked plain (`container::mark_plain_upper`). +fn import_upper(mut reader: impl Read, base: &Path) -> io::Result<()> { + let upper = base.join("upper"); + let staging = base.join("upper.import"); + fs::create_dir_all(base)?; + match fs::remove_dir_all(&staging) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + fs::create_dir(&staging)?; + let unpacked = (|| -> io::Result<()> { + // The root of the container's filesystem takes this directory's + // mode and owner, as with the `upper` a first start makes. + fs::set_permissions(&staging, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + super::layers::untar(&mut reader, &staging)?; + // The archive's trailing padding, so the host's writes complete. + io::copy(&mut reader, &mut io::sink())?; + strip_overlay_xattrs(&staging)?; + // An empty `upper` an earlier copy's mount left goes first. + match fs::remove_dir(&upper) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + fs::rename(&staging, &upper) + })(); + if let Err(e) = unpacked { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + container::mark_plain_upper(base) +} + +/// Removes overlayfs's own attributes (`trusted.overlay.*`: redirects, +/// metacopy, origin) from everything under `root`, keeping the opaque mark +/// `layers::untar` sets for `.wh..wh..opq`. An imported layer is whole +/// files and directories; an attribute an archive carried must not make +/// the mount look elsewhere for them. +fn strip_overlay_xattrs(root: &Path) -> io::Result<()> { + let mut stack = vec![root.to_path_buf()]; + while let Some(path) = stack.pop() { + let meta = fs::symlink_metadata(&path)?; + let c = sys::cstr(&path)?; + let mut names = vec![0u8; 4096]; + let n = loop { + // SAFETY: valid NUL-terminated path; fills at most `names.len()` bytes. + let n = unsafe { libc::llistxattr(c.as_ptr(), names.as_mut_ptr().cast(), names.len()) }; + if n >= 0 { + break n as usize; + } + match io::Error::last_os_error() { + e if e.raw_os_error() == Some(libc::ERANGE) && names.len() < 1 << 20 => names.resize(names.len() * 4, 0), + e if e.raw_os_error() == Some(libc::ENOTSUP) => break 0, + e => return Err(e), + } + }; + for name in names[..n].split(|b| *b == 0).filter(|name| overlay_own(name)) { + let name = std::ffi::CString::new(name).map_err(io::Error::other)?; + // SAFETY: valid NUL-terminated path and attribute name. + if unsafe { libc::lremovexattr(c.as_ptr(), name.as_ptr()) } != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ENODATA) { + return Err(e); + } + } + } + if meta.is_dir() { + for e in fs::read_dir(&path)? { + stack.push(e?.path()); + } + } + } + Ok(()) +} + +/// Whether an extended attribute is one overlayfs reads in an upper dir, +/// other than the opaque mark. +fn overlay_own(name: &[u8]) -> bool { + name.starts_with(b"trusted.overlay.") && name != b"trusted.overlay.opaque" +} + fn reply_error(conn: &mut fs::File, msg: &str) -> io::Result<()> { let mut out = Vec::new(); Msg::Error(msg).encode(&mut out); @@ -1069,6 +1179,90 @@ fn read_frame(conn: &mut impl Read, buf: &mut Vec) -> io::Result<()> { mod tests { use super::*; + #[test] + fn only_overlayfs_own_attributes_but_the_opaque_mark_are_stripped() { + assert!(overlay_own(b"trusted.overlay.redirect")); + assert!(overlay_own(b"trusted.overlay.metacopy")); + assert!(overlay_own(b"trusted.overlay.origin")); + assert!(!overlay_own(b"trusted.overlay.opaque")); + assert!(!overlay_own(b"security.capability")); + assert!(!overlay_own(b"user.overlay.redirect")); + assert!(!overlay_own(b"trusted.overlayx")); + } + + /// `kiri import` (#410): a writable layer from another engine becomes + /// the container's `upper`, whiteouts and opaque marks as overlayfs reads + /// them, owners and links kept, overlayfs's own attributes gone, marked + /// plain; one cut short leaves nothing behind. + #[test] + fn an_imported_writable_layer_becomes_the_upper_dir_whole() { + // SAFETY: a plain getter. + if unsafe { libc::geteuid() } != 0 { + eprintln!("skipped: needs root for owners, whiteouts and trusted attributes"); + return; + } + let base = std::env::temp_dir().join(format!("kiri-import-upper-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let layer = |cut: bool| { + let mut b = tar::Builder::new(Vec::new()); + let h = |kind: tar::EntryType, size: u64, mode: u32, owner: u64| { + let mut h = tar::Header::new_ustar(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(mode); + h.set_uid(owner); + h.set_gid(owner); + h.set_mtime(1_700_000_000); + h + }; + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750, 1000), "added/", io::empty()).unwrap(); + b.append_pax_extensions([("SCHILY.xattr.trusted.overlay.redirect", &b"/elsewhere"[..])]).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 5, 0o640, 1000), "added/file", &b"hello"[..]).unwrap(); + b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777, 0), "link", "added/file").unwrap(); + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "etc/", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "etc/.wh.gone", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 4, 0o644, 0), "etc/motd", &b"new\n"[..]).unwrap(); + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "again/", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "again/.wh..wh..opq", io::empty()).unwrap(); + let mut bytes = b.into_inner().unwrap(); + if cut { + // Inside the first file's body. + bytes.truncate(512 * 4 + 2); + } + bytes + }; + + // Cut short: an error, and neither `upper` nor its staging is left. + assert!(import_upper(&layer(true)[..], &base).is_err()); + assert!(!base.join("upper").exists() && !base.join("upper.import").exists() && !base.join(super::container::PLAIN_UPPER).exists()); + + // An empty `upper` (an earlier copy's mount made it) is taken over. + fs::create_dir_all(base.join("upper")).unwrap(); + import_upper(&layer(false)[..], &base).unwrap(); + let upper = base.join("upper"); + let meta = |p: &str| fs::symlink_metadata(upper.join(p)).unwrap(); + assert!(!base.join("upper.import").exists()); + assert!(base.join(super::container::PLAIN_UPPER).exists(), "marked plain"); + assert_eq!(meta("").mode() & 0o7777, 0o755); + let added = meta("added"); + assert_eq!((added.uid(), added.gid(), added.mode() & 0o7777, added.mtime()), (1000, 1000, 0o750, 1_700_000_000)); + let file = meta("added/file"); + assert_eq!((file.uid(), file.gid(), file.mode() & 0o7777), (1000, 1000, 0o640)); + assert_eq!(fs::read(upper.join("added/file")).unwrap(), b"hello"); + assert_eq!(fs::read_link(upper.join("link")).unwrap(), Path::new("added/file")); + assert_eq!(fs::read(upper.join("etc/motd")).unwrap(), b"new\n"); + assert!(is_whiteout(&meta("etc/gone")), "a 0:0 character device"); + assert!(!upper.join("etc/.wh.gone").exists()); + assert!(is_opaque(&upper.join("again"))); + assert!(!upper.join("again/.wh..wh..opq").exists()); + let c = sys::cstr(upper.join("added/file")).unwrap(); + // SAFETY: valid path and name; a size query. + let redirect = unsafe { libc::lgetxattr(c.as_ptr(), c"trusted.overlay.redirect".as_ptr(), std::ptr::null_mut(), 0) }; + assert!(redirect < 0, "overlayfs's own attribute stripped"); + + let _ = fs::remove_dir_all(&base); + } + #[test] fn contents_keep_dot_prefix_and_long_names() { for length in [4, 98, 99, 100, 101, 255] { diff --git a/crates/kiri-init/src/linux/layers.rs b/crates/kiri-init/src/linux/layers.rs index 9160c7179..f02f067dc 100644 --- a/crates/kiri-init/src/linux/layers.rs +++ b/crates/kiri-init/src/linux/layers.rs @@ -221,8 +221,9 @@ fn unpack(blob: &mut impl Read, media_type: &str, dest: &Path, compressed: u64) /// Unpacks a layer tarball, translating OCI whiteouts into the form overlayfs /// reads: `.wh.name` becomes a 0:0 character device `name`, and -/// `.wh..wh..opq` marks its directory opaque. -fn untar(reader: impl Read, dest: &Path) -> io::Result { +/// `.wh..wh..opq` marks its directory opaque. Also how `copy` unpacks a +/// container's imported writable layer. +pub(super) fn untar(reader: impl Read, dest: &Path) -> io::Result { untar_in(reader, dest, in_user_namespace) } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 292ce064c..16653c059 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -283,6 +283,11 @@ pub mod copy_op { /// `docker commit`: the writable layer as an OCI layer tar (whiteouts as /// `.wh.` files). pub const COMMIT: u8 = 6; + /// `kiri import`: a writable layer brought from another engine, as an + /// OCI layer tar (whiteouts as `.wh.` files) sent like `IN`'s archive, + /// becomes the writable layer of a container that is not running and + /// has none yet. Answers `CopyDone` (or `Error`) once it is in place. + pub const UPPER: u8 = 7; } pub mod copy_flags { @@ -314,7 +319,7 @@ pub struct CopySpec<'a> { pub layers: StrList<'a>, /// The container's mounts (`source\ttarget\tflags[\t…]`, as in /// [`RunSpec::mounts`]). Empty from an older daemon, and empty for - /// `EXPORT`, `DIFF` and `COMMIT`. + /// `EXPORT`, `DIFF`, `COMMIT` and `UPPER`. pub mounts: StrList<'a>, } diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index 38006a67e..76d4fdb5a 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -248,6 +248,11 @@ pub fn request_within(method: &str, path: &str, body: Option<&Value>, background background_header(background), payload.len() )?; + answer(s) +} + +/// The answer to a request just sent; the whole body is read, chunked or not. +fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut body = Vec::new(); @@ -267,6 +272,56 @@ pub fn request_within(method: &str, path: &str, body: Option<&Value>, background Ok(Response { status, body }) } +/// A POST whose body `write` streams, chunked, so its length need not be +/// known first: `kiri import`'s copy of a container's writable layer, as +/// crates/kiri/src/client.rs sends it. A body `write` gives up on is never +/// ended, so the daemon sees it cut short, not as a whole one; if the daemon +/// stopped reading first (it refused the request), its answer is returned, +/// which says why. +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + line_safe(path)?; + line_safe(content_type)?; + let mut s = open_conn(None)?; + write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\nContent-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n")?; + match stream_body(&mut s, write) { + Ok(()) => answer(s), + Err(e) if matches!(e.kind(), io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionAborted) => match answer(s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + +/// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when +/// `write` succeeds. +fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { + let mut body = io::BufWriter::with_capacity(256 << 10, Chunked(to)); + write(&mut body)?; + let mut chunked = body.into_inner().map_err(io::IntoInnerError::into_error)?; + chunked.0.write_all(b"0\r\n\r\n")?; + chunked.0.flush() +} + +/// HTTP/1.1 chunked transfer coding: each write is one chunk. +struct Chunked(W); + +impl Write for Chunked { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + write!(self.0, "{:x}\r\n", buf.len())?; + self.0.write_all(buf)?; + self.0.write_all(b"\r\n")?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + /// Kiri's own version from a `/version` answer: `KiriVersion`, or `Version` /// from an engine older than that field (it reported Kiri's version there; /// it is now the Docker Engine version clients gate on). @@ -613,6 +668,30 @@ mod tests { assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "background proxy push must mark background: {req}"); } + #[test] + fn a_streamed_body_is_chunked_and_ended_only_when_whole() { + let sent = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + let r = post_stream("/kiri/containers/db/upper", "application/x-tar", |w| { + w.write_all(b"hello")?; + w.write_all(b" world") + }) + .unwrap(); + assert_eq!(r.status, 204); + let req = wire_text(&sent); + assert!(req.starts_with("POST /kiri/containers/db/upper HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nTransfer-Encoding: chunked\r\n") && req.contains("\r\nContent-Type: application/x-tar\r\n"), "{req}"); + assert!(req.ends_with("\r\n\r\nb\r\nhello world\r\n0\r\n\r\n"), "{req}"); + + let cut = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + let e = post_stream("/kiri/containers/db/upper", "application/x-tar", |w| { + w.write_all(b"part")?; + Err(io::Error::other("the source failed")) + }) + .unwrap_err(); + assert_eq!(e.to_string(), "the source failed"); + assert!(!wire_text(&cut).ends_with("0\r\n\r\n"), "a body cut short is never ended"); + } + #[test] fn alive_and_events_carry_the_background_header() { let ping = mock_reply(OK_PING); diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index 29d5a218c..5f82e7ad0 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -122,6 +122,11 @@ fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Resu "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", payload.len() )?; + answer(s) +} + +/// The answer to a request just sent; the whole body is read, chunked or not. +fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut body = Vec::new(); @@ -142,6 +147,60 @@ fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Resu Ok(Response { status, body }) } +/// A POST whose body `write` streams, chunked, so its length need not be +/// known first: `kiri import`'s copy of a container's writable layer. A +/// body `write` gives up on is never ended, so the daemon sees it cut +/// short, not as a whole one; if the daemon stopped reading first (it +/// refused the request), its answer is returned, which says why. +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + let s = connect(Some(Duration::from_secs(300)))?; + let op = crate::diag::op_header(); + (&s).write_all(format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes())?; + match stream_body(&s, write) { + Ok(()) => answer(&s), + Err(e) if refused(&e) => match answer(&s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + +/// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when +/// `write` succeeds. +pub(crate) fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { + let mut body = io::BufWriter::with_capacity(256 << 10, Chunked(to)); + write(&mut body)?; + let mut chunked = body.into_inner().map_err(io::IntoInnerError::into_error)?; + chunked.0.write_all(b"0\r\n\r\n")?; + chunked.0.flush() +} + +/// Whether a write failed because the other end closed: the daemon may +/// have answered before reading the whole body. +fn refused(e: &io::Error) -> bool { + matches!(e.kind(), io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionAborted) +} + +/// HTTP/1.1 chunked transfer coding: each write is one chunk. +struct Chunked(W); + +impl Write for Chunked { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + write!(self.0, "{:x}\r\n", buf.len())?; + self.0.write_all(buf)?; + self.0.write_all(b"\r\n")?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + /// Kiri's own version from a `/version` answer: `KiriVersion`, or `Version` /// from an engine older than that field (it reported Kiri's version there; /// it is now the Docker Engine version clients gate on). @@ -313,3 +372,31 @@ fn lite_cli() -> Option { fn lite_cli() -> Option { None } + +#[cfg(test)] +mod tests { + use std::io; + + /// `kiri import` streams a container's writable layer (#410): the body + /// is chunked, and ended only when all of it was written, so the daemon + /// never takes a copy cut short for a whole one. + #[test] + fn a_streamed_body_is_chunked_and_ended_only_when_whole() { + let mut wire = Vec::new(); + super::stream_body(&mut wire, |w| { + w.write_all(b"hello")?; + w.write_all(b" world") + }) + .unwrap(); + assert_eq!(wire, b"b\r\nhello world\r\n0\r\n\r\n"); + let mut wire = Vec::new(); + let e = super::stream_body(&mut wire, |w| { + w.write_all(b"part")?; + Err(io::Error::other("the source failed")) + }) + .unwrap_err(); + assert_eq!(e.to_string(), "the source failed"); + assert!(!wire.ends_with(b"0\r\n\r\n"), "{:?}", String::from_utf8_lossy(&wire)); + assert!(super::refused(&io::Error::from(io::ErrorKind::BrokenPipe)) && !super::refused(&io::Error::other("x"))); + } +} diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index ae2b6d543..1b54b0025 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -86,7 +86,9 @@ pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Res /// (`/images/create` is `docker import`'s; a pull's, when a client sends /// one, is read out after it, by `http::finish_body`). fn streams_body(method: &str, path: &str) -> bool { - matches!((method, path), ("PUT", p) if p.starts_with("/containers/") && p.ends_with("/archive")) || (method == "POST" && matches!(path, "/images/load" | "/images/create" | "/build")) + matches!((method, path), ("PUT", p) if p.starts_with("/containers/") && p.ends_with("/archive")) + || matches!((method, path), ("POST", p) if p.starts_with("/kiri/containers/") && p.ends_with("/upper")) + || (method == "POST" && matches!(path, "/images/load" | "/images/create" | "/build")) } pub(super) enum Next { @@ -236,6 +238,12 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea let id = p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/env")).unwrap_or_default(); return reply(w, set_env(req, engine, id), 204); } + // `kiri import`: the writable layer a container had on the engine + // it came from (an OCI layer tar), before it first runs here. + ("POST", p) if p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/upper")).is_some_and(|id| !id.is_empty()) => { + let id = p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/upper")).unwrap_or_default(); + return upper_put(req, engine, id, w, r); + } // An image's page for kiri-win, whose window can't read the store // inside WSL: its layers and its Grype scans (crate::scan), as the // Mac's window reads them itself. @@ -3840,6 +3848,64 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: } } +/// `POST /kiri/containers/{id}/upper`: `kiri import`'s copy of the writable +/// layer a container had on Docker Desktop or OrbStack, an uncompressed OCI +/// layer tar (whiteouts as `.wh.` files), unpacked by the guest into the +/// container's own writable layer (copy.rs, `copy_op::UPPER`). Only for a +/// container that is not running and has no writable layer yet. A +/// container's connection never gets here (`container_may`). +fn upper_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: &mut BufReader) -> io::Result { + let refused = match engine.with(id, |c| c.status == Status::Running || c.paused) { + Ok(true) => Some(Error::Conflict(format!("container {id} is running: its writable layer can only be brought in before it runs"))), + Ok(false) => None, + Err(e) => Some(e), + }; + if let Some(e) = refused { + error_closing(w, e)?; + return Ok(Next::Close); + } + let mut body = http::Body::new(req, r); + let stream = match engine.copy(id, kiri_proto::copy_op::UPPER, "/", kiri_proto::copy_flags::CHUNKED) { + Ok(s) => s, + Err(e) => { + error_closing(w, e)?; + return Ok(Next::Close); + } + }; + let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); + if let Err(e) = send_chunks(&mut body, &mut to_guest) { + // Cut short: dropping the stream ends the guest's copy, which then + // leaves the container as it was. + error_closing(w, Error::BadRequest(format!("the layer could not be read: {e}")))?; + return Ok(Next::Close); + } + let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); + let result = match guest_frame(&mut from_guest) { + Ok(frame) => match kiri_proto::decode(&frame) { + Ok(kiri_proto::Msg::CopyDone) => Ok(()), + Ok(kiri_proto::Msg::Error(m)) if m.contains("in use") || m.contains("already has") => Err(Error::Conflict(m.to_owned())), + Ok(kiri_proto::Msg::Error(m)) => Err(copy_error(m)), + Ok(other) => Err(Error::Io(io::Error::other(format!("unexpected copy reply: {other:?}")))), + Err(e) => Err(Error::Io(io::Error::other(format!("bad copy reply: {e:?}")))), + }, + Err(e) => Err(Error::Io(e)), + }; + match result { + Ok(()) if io::copy(&mut body, &mut io::sink()).is_ok() => { + http::empty(w, 204)?; + Ok(Next::KeepAlive) + } + Ok(()) => { + error_closing(w, Error::BadRequest("the layer could not be read to its end".into()))?; + Ok(Next::Close) + } + Err(e) => { + error_closing(w, e)?; + Ok(Next::Close) + } + } +} + /// A signal by name or number for a stop signal Docker has already /// accepted; one it could not parse is SIGTERM, Docker's default. pub(super) fn signal(name: &str) -> u32 { @@ -4657,7 +4723,7 @@ mod tests { }; let mut routes = kiri_routes(body_of(include_str!("api.rs"), "\nfn route(")); routes.extend(kiri_routes(body_of(include_str!("ops.rs"), "\npub fn route("))); - for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] { + for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("POST", "/kiri/containers/1/upper"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] { assert!(routes.iter().any(|(m, p)| (m.as_str(), p.as_str()) == known), "{known:?} not found in route(): {routes:?}"); } for (m, p) in &routes { diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 7e4d66a85..79d2b2b94 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -6084,8 +6084,8 @@ fn close_monitor(h: &mut HealthRun) { /// Mounts and flags carried on a guest `Copy` frame. Archive ops (`IN`, `OUT`, /// `STAT`) carry the container's mounts (with refreshed bind sources) and -/// `READONLY_ROOTFS` for `IN`; `EXPORT`, `DIFF` and `COMMIT` operate on the -/// container's rootfs/layer alone, without mounts. +/// `READONLY_ROOTFS` for `IN`; `EXPORT`, `DIFF`, `COMMIT` and `UPPER` operate +/// on the container's rootfs/layer alone, without mounts. fn copy_mounts_and_flags(spec: &Spec, op: u8, flags: u32) -> (Vec, u32) { if !matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT) { return (Vec::new(), flags); @@ -7696,7 +7696,7 @@ mod start_wait_tests { assert_eq!(mounts, s.mounts); assert_eq!(flags, 0); } - for op in [kiri_proto::copy_op::EXPORT, kiri_proto::copy_op::DIFF, kiri_proto::copy_op::COMMIT] { + for op in [kiri_proto::copy_op::EXPORT, kiri_proto::copy_op::DIFF, kiri_proto::copy_op::COMMIT, kiri_proto::copy_op::UPPER] { let (mounts, flags) = copy_mounts_and_flags(&s, op, 0); assert!(mounts.is_empty(), "op {op} must not mount volumes/binds"); assert_eq!(flags, 0); diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index c2c00018f..27cf366af 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -190,7 +190,7 @@ fn changes(engine: &Engine, key: &str) -> Result { Some(json!({"Path": path, "Kind": kind})) }) .collect(); - Ok(if list.is_empty() { Value::Null } else { Value::Array(list) }) + Ok(Value::Array(list)) } fn export(engine: &Engine, key: &str, w: &mut UnixStream) -> io::Result { diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index 9e442f492..59301d0f6 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -5,7 +5,9 @@ //! mounts it read-only and is removed after (keeping file owners and `user.*` //! extended attributes, which `docker cp` or a copy through the Finder would //! lose; falling back to `docker cp` when offline without GNU tar). -//! Containers arrive stopped. +//! Containers arrive stopped, with the files they wrote outside their +//! volumes: what `docker diff` lists, read path by path with `docker cp` +//! into the container's writable layer in Kiri (#410). use std::io::{self, Read, Write}; use std::path::PathBuf; @@ -871,6 +873,553 @@ pub fn container_with(source: &str, name: &str, force: bool, joining: &[&str]) - if !r.ok() { return Err(io::Error::other(create_error(r.status, &r.error()))); } + if let Err(e) = writable_layer(ctx, &info, name) { + // Without the files it wrote, the container is not the one it was: + // it goes again, and the reason is said. Its volumes stay. + let _ = client::request("DELETE", &format!("/containers/{name}?force=1"), None); + return Err(io::Error::other(format!("its writable layer: {e}"))); + } + Ok(()) +} + +/// The engine's own files, which each engine makes and mounts over the +/// container's for itself: never carried over. +const ENGINE_FILES: [&str; 4] = ["/etc/hosts", "/etc/hostname", "/etc/resolv.conf", "/.dockerenv"]; + +/// The kernel's filesystems and the engine's `/dev`, mounted in every +/// container: nothing at or under them is carried over. +const KERNEL_TREES: [&str; 3] = ["/proc", "/sys", "/dev"]; + +/// How many `docker cp` run at once to read the paths a layer changed. +const READERS: usize = 8; + +/// A file up to this size is read ahead, in parallel, while the paths +/// before it are written; a bigger one is read when its turn comes. +const READ_AHEAD_FILE: u64 = 1 << 20; + +/// What the files read ahead may hold at once, all together. +const READ_AHEAD_TOTAL: u64 = 64 << 20; + +/// The container's writable layer on the source (#410): the files it wrote +/// outside its volumes, its changes to the image's files and what it +/// deleted of them, as `docker diff` lists them, become the writable layer +/// of the container just made as `name` in Kiri, before it first runs. +/// Nothing is made on the source: each path is read with `docker cp`, only +/// what changed, never the image's unchanged files, and nothing at or under +/// the container's mounts (volumes are copied as volumes, binds stay where +/// they are). A container that changed nothing costs one `docker diff`. +fn writable_layer(ctx: &str, info: &Value, name: &str) -> io::Result<()> { + let id = info["Id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| io::Error::other("the source gave no container id"))?; + let out = cli()?.args(["--context", ctx, "container", "diff", id]).stdin(Stdio::null()).stderr(Stdio::piped()).output()?; + if !out.status.success() { + return Err(io::Error::other(format!("{ctx}: docker diff: {}", String::from_utf8_lossy(&out.stderr).trim()))); + } + let plan = plan_layer(&parse_diff(&String::from_utf8_lossy(&out.stdout)), &mount_points(info)); + if plan.is_empty() { + return Ok(()); + } + let r = client::post_stream(&format!("/kiri/containers/{name}/upper"), "application/x-tar", |w| write_layer(ctx, id, &plan, w))?; + if !r.ok() { + return Err(io::Error::other(create_error(r.status, &r.error()))); + } + Ok(()) +} + +/// `docker diff`'s lines as (kind, path): `A` added, `C` changed, `D` +/// deleted. A line that is none of these, or names a path that is not +/// absolute and plain (no `.`, `..` or empty steps), is left out. +fn parse_diff(text: &str) -> Vec<(char, String)> { + text.lines() + .filter_map(|l| { + let (kind, path) = l.strip_suffix('\r').unwrap_or(l).split_once(' ')?; + let kind = match kind { + "A" => 'A', + "C" => 'C', + "D" => 'D', + _ => return None, + }; + let plain = path.len() > 1 && path.starts_with('/') && path[1..].split('/').all(|c| !matches!(c, "" | "." | "..")); + plain.then(|| (kind, path.to_owned())) + }) + .collect() +} + +/// Where the container has something mounted on the source: volumes, binds +/// and tmpfs, as absolute paths without a trailing `/`. +fn mount_points(info: &Value) -> Vec { + let hc = &info["HostConfig"]; + let mut found: Vec<&str> = info["Mounts"].as_array().into_iter().flatten().filter_map(|m| m["Destination"].as_str()).collect(); + found.extend(hc["Mounts"].as_array().into_iter().flatten().filter_map(|m| m["Target"].as_str())); + found.extend(hc["Tmpfs"].as_object().into_iter().flatten().map(|(k, _)| k.as_str())); + let mut points: Vec = Vec::new(); + for p in found { + let clean = format!("/{}", p.split('/').filter(|c| !c.is_empty() && *c != ".").collect::>().join("/")); + if clean != "/" && !points.contains(&clean) { + points.push(clean); + } + } + points +} + +/// Whether `path` is `top` or under it. +fn at_or_under(path: &str, top: &str) -> bool { + path == top || below(path, top) +} + +/// Whether `path` is under `top` (not `top` itself). +fn below(path: &str, top: &str) -> bool { + path.strip_prefix(top).is_some_and(|rest| rest.starts_with('/')) +} + +/// Paths in the order a layer lists them: each directory right before +/// what is under it. +fn path_order(a: &str, b: &str) -> std::cmp::Ordering { + a.split('/').cmp(b.split('/')) +} + +/// What of a container's writable layer is carried over, from what `docker +/// diff` lists. `docker diff` names every path the layer holds (an added +/// directory's contents too) and the directories they are in, so each is +/// read on its own; only a new directory with nothing mounted under it is +/// read whole, in one go. +#[derive(Debug, Default, PartialEq)] +struct LayerPlan { + /// Deleted on the source: a whiteout each, unless the path is there + /// again (a directory deleted and made again, which turns opaque). + deleted: Vec, + /// Carried over by their own entry: a file whole, a directory with its + /// mode, owner and time and none of what is in it, which is listed (or + /// unchanged in the image) on its own. `/etc` changed because a file was + /// added to it brings that file and `/etc`'s own entry, not all of `/etc`. + entries: Vec, + /// New directories, not in the image, carried over whole. + trees: Vec, +} + +impl LayerPlan { + fn is_empty(&self) -> bool { + self.deleted.is_empty() && self.entries.is_empty() && self.trees.is_empty() + } +} + +/// The plan for `changes` (`docker diff`'s lines) of a container with +/// `mounts`: nothing at or under a mount, the engine's own files or the +/// kernel's filesystems; a directory listed only for those is left out; +/// every directory a path is in comes too, so the layer keeps its mode +/// and owner. +fn plan_layer(changes: &[(char, String)], mounts: &[String]) -> LayerPlan { + let left_out = |p: &str| ENGINE_FILES.contains(&p) || KERNEL_TREES.iter().copied().chain(mounts.iter().map(String::as_str)).any(|t| at_or_under(p, t)); + let mut sorted: Vec<&(char, String)> = changes.iter().collect(); + sorted.sort_by(|a, b| path_order(&a.1, &b.1)); + sorted.dedup_by(|a, b| a.1 == b.1); + let mut plan = LayerPlan::default(); + let mut i = 0; + while i < sorted.len() { + let (kind, path) = (sorted[i].0, sorted[i].1.as_str()); + let end = sorted[i + 1..].iter().position(|(_, p)| !below(p, path)).map_or(sorted.len(), |n| i + 1 + n); + let inside = &sorted[i + 1..end]; + i += 1; + if left_out(path) { + continue; + } + match kind { + 'D' => plan.deleted.push(path.to_owned()), + 'A' if !inside.is_empty() && inside.iter().all(|(k, p)| *k == 'A' && !left_out(p)) => { + plan.trees.push(path.to_owned()); + i = end; + } + 'C' if !inside.is_empty() && inside.iter().all(|(_, p)| left_out(p)) => {} + _ => plan.entries.push(path.to_owned()), + } + } + let mut have: std::collections::HashSet = plan.deleted.iter().chain(&plan.entries).chain(&plan.trees).cloned().collect(); + let mut parents = Vec::new(); + for p in plan.deleted.iter().chain(&plan.entries).chain(&plan.trees) { + let mut at = p.as_str(); + while let Some((parent, _)) = at.rsplit_once('/').filter(|(parent, _)| !parent.is_empty()) { + if have.insert(parent.to_owned()) { + parents.push(parent.to_owned()); + } + at = parent; + } + } + plan.entries.extend(parents); + plan.entries.sort_by(|a, b| path_order(a, b)); + plan +} + +/// One path the layer brings, read on its own ahead of its turn. +enum Read1 { + /// Not there (gone since `docker diff`), or nothing a tar can hold (a socket). + Missing, + /// A directory's own entry. + Dir(Vec), + /// Anything else, whole. + Whole(Vec), + /// A file too big to read ahead: read when its turn comes. + Later, +} + +/// Writes the layer `plan` names as an OCI layer tar (whiteouts as `.wh.` +/// files, opaque directories with `.wh..wh..opq`), each path read from the +/// source container `id` with `docker cp`. What the writer refuses keeps +/// its error kind: `client::post_stream` then reads the daemon's reason. +fn write_layer(ctx: &str, id: &str, plan: &LayerPlan, out: &mut dyn Write) -> io::Result<()> { + let ahead: Vec<&str> = plan.entries.iter().chain(&plan.deleted).map(String::as_str).collect(); + let mut read = read_ahead(ctx, id, &ahead)?.into_iter(); + let mut got: std::collections::HashMap<&str, Read1> = ahead.iter().map(|p| (*p, read.next().unwrap_or(Read1::Later))).collect(); + let mut steps: Vec<(&str, u8)> = plan.entries.iter().map(|p| (p.as_str(), b'e')).collect(); + steps.extend(plan.deleted.iter().map(|p| (p.as_str(), b'd'))); + steps.extend(plan.trees.iter().map(|p| (p.as_str(), b't'))); + steps.sort_by(|a, b| path_order(a.0, b.0)); + for (path, step) in steps { + if step == b't' { + read_paths(ctx, id, path, out, true)?; + continue; + } + match (got.remove(path).unwrap_or(Read1::Later), step) { + (Read1::Missing, b'd') => write_marker(out, &whiteout_name(path))?, + (Read1::Missing, _) => {} + // Deleted, and a directory there again: what the image had in it is gone. + (Read1::Dir(bytes), b'd') => { + out.write_all(&bytes)?; + write_marker(out, &format!("{}/.wh..wh..opq", &path[1..]))?; + } + (Read1::Dir(bytes) | Read1::Whole(bytes), _) => out.write_all(&bytes)?, + (Read1::Later, _) => read_paths(ctx, id, path, out, false)?, + } + } + out.write_all(&[0u8; 1024]) +} + +/// The name of the whiteout that deletes `path`: `.wh.` and its name, in +/// its directory. +fn whiteout_name(path: &str) -> String { + let (dir, base) = path.rsplit_once('/').unwrap_or(("", path)); + format!("{}.wh.{base}", if dir.is_empty() { String::new() } else { format!("{}/", &dir[1..]) }) +} + +/// Reads `paths` from the source container, [`READERS`] at a time: each +/// one's entry, in the order given, ready to write. +fn read_ahead(ctx: &str, id: &str, paths: &[&str]) -> io::Result> { + use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; + let next = AtomicUsize::new(0); + let held = AtomicU64::new(0); + let failed = AtomicBool::new(false); + let slots: Vec>>> = paths.iter().map(|_| std::sync::Mutex::new(None)).collect(); + std::thread::scope(|s| { + for _ in 0..READERS.min(paths.len()) { + s.spawn(|| { + while !failed.load(Ordering::Relaxed) { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = paths.get(i) else { break }; + let r = read_one(ctx, id, path, &held); + failed.fetch_or(r.is_err(), Ordering::Relaxed); + *slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + } + }); + } + }); + slots.into_iter().map(|s| s.into_inner().unwrap_or_else(|e| e.into_inner()).unwrap_or(Ok(Read1::Later))).collect() +} + +/// One path's own entry, read ahead: a directory's without what is in it, +/// a small file's whole; a big one is left for later, so what is read +/// ahead stays under [`READ_AHEAD_TOTAL`] (`held`). +fn read_one(ctx: &str, id: &str, path: &str, held: &std::sync::atomic::AtomicU64) -> io::Result { + use std::sync::atomic::Ordering; + let mut cp = Cp::start(ctx, id, path)?; + let entry = match read_entry(&mut cp.out) { + Ok(Some(e)) => e, + Ok(None) => return cp.finish().map(|_| Read1::Missing), + Err(e) => return cp.failed(e).map(|()| Read1::Missing), + }; + let mut bytes = Vec::new(); + write_renamed(&mut bytes, &entry, path)?; + if entry.header[156] == b'5' { + cp.stop(); + return Ok(Read1::Dir(bytes)); + } + let padded = entry.size.div_ceil(512) * 512; + if entry.size > READ_AHEAD_FILE || held.fetch_add(padded, Ordering::Relaxed) + padded > READ_AHEAD_TOTAL { + cp.stop(); + return Ok(Read1::Later); + } + if let Err(e) = copy_body(&mut cp.out, &mut bytes, padded) { + return cp.failed(e).map(|()| Read1::Missing); + } + cp.stop(); + Ok(Read1::Whole(bytes)) +} + +/// Writes `path` read from the source container now: its own entry (a +/// directory's without what is in it), or with `whole` everything under +/// it. Gone since `docker diff` (a running container), it is left out. +fn read_paths(ctx: &str, id: &str, path: &str, out: &mut dyn Write, whole: bool) -> io::Result<()> { + let mut cp = Cp::start(ctx, id, path)?; + loop { + let entry = match read_entry(&mut cp.out) { + Ok(Some(e)) => e, + Ok(None) => return cp.finish().map(|_| ()), + Err(e) => return cp.failed(e), + }; + write_renamed(out, &entry, path)?; + if !whole && entry.header[156] == b'5' { + cp.stop(); + return Ok(()); + } + let padded = entry.size.div_ceil(512) * 512; + let mut body = (&mut cp.out).take(padded); + let copied = io::copy(&mut body, out)?; + if copied != padded { + return cp.failed(io::Error::new(io::ErrorKind::UnexpectedEof, "cut off inside a file's body")); + } + if !whole { + cp.stop(); + return Ok(()); + } + } +} + +/// `docker cp` of one path out of the source container, as a tar stream. +struct Cp { + child: std::process::Child, + out: std::process::ChildStdout, + said: Option>, + path: String, +} + +impl Cp { + fn start(ctx: &str, id: &str, path: &str) -> io::Result { + let mut child = cli()?.args(["--context", ctx, "cp", &format!("{id}:{path}"), "-"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; + let out = child.stdout.take().ok_or_else(|| io::Error::other("no output from docker"))?; + // Read meanwhile: a full pipe would stop it. + let said = child.stderr.take().map(|mut e| { + std::thread::spawn(move || { + let mut text = String::new(); + let _ = e.read_to_string(&mut text); + text.trim().to_owned() + }) + }); + Ok(Cp { child, out, said, path: path.to_owned() }) + } + + /// Stops it: all that was wanted of it is read. + fn stop(self) { + drop(self); + } + + /// Waits for it to end. `Ok(false)` when the path is not there. + fn finish(mut self) -> io::Result { + let _ = io::copy(&mut self.out, &mut io::sink()); + let status = self.child.wait()?; + let said = self.said.take().and_then(|t| t.join().ok()).unwrap_or_default(); + if status.success() { + return Ok(true); + } + if gone(&said) { + return Ok(false); + } + Err(io::Error::other(format!("docker cp {}: {}", self.path, if said.is_empty() { "failed" } else { &said }))) + } + + /// After reading its output failed with `e`: `Ok` when the path is + /// simply not there, else what docker said, or `e`. + fn failed(mut self, e: io::Error) -> io::Result<()> { + self.end(); + let said = self.said.take().and_then(|t| t.join().ok()).unwrap_or_default(); + if gone(&said) { + return Ok(()); + } + let why = if said.is_empty() { e.to_string() } else { said }; + Err(io::Error::new(if e.kind() == io::ErrorKind::BrokenPipe { io::ErrorKind::Other } else { e.kind() }, format!("docker cp {}: {why}", self.path))) + } +} + +impl Cp { + fn end(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// One stopped early, or left when writing failed, ends with it. +impl Drop for Cp { + fn drop(&mut self) { + self.end(); + } +} + +/// Whether `docker cp` said the path is not there. +fn gone(said: &str) -> bool { + let said = said.to_ascii_lowercase(); + said.contains("could not find the file") || said.contains("no such container:path") +} + +/// A tar entry as read: its header, its pax records (`path` and +/// `linkpath` taken out into `name` and `link`), and its body's size. +struct TarEntry { + header: [u8; 512], + pax: Vec<(String, String)>, + name: String, + link: String, + size: u64, +} + +/// The next entry's headers in a tar stream, its body still to read; +/// `None` at the archive's end. Pax and GNU long-name headers are folded +/// into the entry they come before. +fn read_entry(r: &mut dyn Read) -> io::Result> { + let bad = |what: &str| io::Error::new(io::ErrorKind::InvalidData, format!("tar stream: {what}")); + let text = |b: &[u8]| String::from_utf8_lossy(b.split(|c| *c == 0).next().unwrap_or_default()).into_owned(); + let mut pax: Vec<(String, String)> = Vec::new(); + let (mut long_name, mut long_link) = (None, None); + loop { + let mut h = [0u8; 512]; + r.read_exact(&mut h).map_err(|e| if e.kind() == io::ErrorKind::UnexpectedEof { bad("cut off before the archive's end") } else { e })?; + if h.iter().all(|b| *b == 0) { + return Ok(None); + } + let size = get_number(&h[124..136]).ok_or_else(|| bad("a damaged header"))?; + if matches!(h[156], b'x' | b'g' | b'L' | b'K') { + if size > 16 << 20 { + return Err(bad("a header too large")); + } + let mut data = vec![0u8; (size.div_ceil(512) * 512) as usize]; + r.read_exact(&mut data).map_err(|e| if e.kind() == io::ErrorKind::UnexpectedEof { bad("cut off inside a header") } else { e })?; + data.truncate(size as usize); + match h[156] { + b'x' => pax.extend(pax_records(&data)), + b'L' => long_name = Some(text(&data)), + b'K' => long_link = Some(text(&data)), + // A global header says nothing about this entry. + _ => {} + } + continue; + } + let posix = &h[257..263] == b"ustar\0"; + let mut name = long_name.unwrap_or_else(|| match text(&h[345..500]) { + prefix if posix && !prefix.is_empty() => format!("{prefix}/{}", text(&h[..100])), + _ => text(&h[..100]), + }); + let mut link = long_link.unwrap_or_else(|| text(&h[157..257])); + let mut size = size; + pax.retain(|(k, v)| match k.as_str() { + "path" => { + name.clone_from(v); + false + } + "linkpath" => { + link.clone_from(v); + false + } + "size" => { + size = v.parse().unwrap_or(size); + true + } + _ => true, + }); + return Ok(Some(TarEntry { header: h, pax, name, link, size })); + } +} + +/// Writes `e`, which `docker cp` of `path` named from `path`'s last step +/// (`hosts2` for `/etc/hosts2`), under its path in the layer instead +/// (`etc/hosts2`); a hard link's target likewise. Anything else under +/// that name is not what was asked for. +fn write_renamed(out: &mut dyn Write, e: &TarEntry, path: &str) -> io::Result<()> { + let base = path.rsplit('/').next().unwrap_or_default(); + let rebase = |name: &str| -> Option { + let rest = name.trim_start_matches("./").trim_start_matches('/').strip_prefix(base)?; + (rest.is_empty() || rest.starts_with('/')).then(|| format!("{}{rest}", &path[1..])) + }; + let name = rebase(&e.name).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("docker cp {path}: an entry named {:?}", e.name)))?; + let link = if e.header[156] == b'1' { rebase(&e.link).unwrap_or_else(|| e.link.clone()) } else { e.link.clone() }; + write_entry(out, e, &name, &link) +} + +/// Writes `e`'s headers as `name` (and `link`): in the header where they +/// fit, else in a pax header before it, which also keeps the records it +/// came with, less overlayfs's own attributes. Size, owner and group a pax +/// record gives go in the header too, as [`retar`] puts them. +fn write_entry(out: &mut dyn Write, e: &TarEntry, name: &str, link: &str) -> io::Result<()> { + let mut pax: Vec<(String, String)> = e.pax.iter().filter(|(k, _)| !k.starts_with("SCHILY.xattr.trusted.overlay.")).cloned().collect(); + if name.len() > 100 { + pax.push(("path".into(), name.into())); + } + if link.len() > 100 { + pax.push(("linkpath".into(), link.into())); + } + let mut h = e.header; + put_text(&mut h[..100], name); + put_text(&mut h[157..257], link); + if &h[257..263] == b"ustar\0" { + h[345..500].fill(0); + } + for (key, at) in [("size", 124..136), ("uid", 108..116), ("gid", 116..124)] { + if let Some(v) = pax.iter().find(|(k, _)| k == key).and_then(|(_, v)| v.parse::().ok()) { + put_number(&mut h[at], v); + } + } + put_checksum(&mut h); + if !pax.is_empty() { + let mut data = Vec::new(); + for (k, v) in &pax { + let rest = k.len() + v.len() + 3; + let mut len = rest + 1; + while rest + len.to_string().len() != len { + len = rest + len.to_string().len(); + } + data.extend_from_slice(format!("{len} {k}={v}\n").as_bytes()); + } + let mut x = plain_header(b'x', "././@PaxHeader", data.len() as u64, 0o644); + put_checksum(&mut x); + out.write_all(&x)?; + data.resize(data.len().div_ceil(512) * 512, 0); + out.write_all(&data)?; + } + out.write_all(&h) +} + +/// An empty file named `name`, owned by root: a whiteout or opaque mark. +fn write_marker(out: &mut dyn Write, name: &str) -> io::Result<()> { + let e = TarEntry { header: plain_header(b'0', "", 0, 0o644), pax: Vec::new(), name: name.to_owned(), link: String::new(), size: 0 }; + write_entry(out, &e, name, "") +} + +/// A ustar header of kind `kind`, owned by root, with a time of 0. +fn plain_header(kind: u8, name: &str, size: u64, mode: u32) -> [u8; 512] { + let mut h = [0u8; 512]; + put_text(&mut h[..100], name); + put_number(&mut h[100..108], u64::from(mode)); + put_number(&mut h[108..116], 0); + put_number(&mut h[116..124], 0); + put_number(&mut h[124..136], size); + put_number(&mut h[136..148], 0); + h[156] = kind; + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + h +} + +/// A text field: as much of `s` as fits, the rest NUL. +fn put_text(field: &mut [u8], s: &str) { + field.fill(0); + let n = s.len().min(field.len()); + field[..n].copy_from_slice(&s.as_bytes()[..n]); +} + +fn put_checksum(h: &mut [u8; 512]) { + h[148..156].fill(b' '); + let sum: u32 = h.iter().map(|b| u32::from(*b)).sum(); + h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); +} + +/// An entry's body, padded to whole blocks, from `from` to `to`. +fn copy_body(from: &mut dyn Read, to: &mut Vec, padded: u64) -> io::Result<()> { + if (&mut *from).take(padded).read_to_end(to)? as u64 != padded { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "cut off inside a file's body")); + } Ok(()) } @@ -1195,6 +1744,132 @@ mod tests { assert!(!super::anonymous("pgdata")); } + /// #410: what of a container's writable layer `kiri import` reads. `/etc` + /// changed because a file was added to it brings that file and `/etc`'s + /// own entry, never the rest of `/etc`; a new directory comes whole in + /// one read, unless something is mounted under it; nothing at or under a + /// mount, the engine's own files or the kernel's filesystems; every + /// directory a path is in comes too. + #[test] + fn plans_only_what_the_writable_layer_changed() { + let diff = "C /etc\nA /etc/hosts2\nC /etc/hosts\nA /app\nA /app/x\nA /app/sub\nA /app/sub/y\nA /srv\nA /srv/cache\nA /srv/keep\nA /data\n\ + C /usr\nC /usr/share\nD /usr/share/doc\nC /opt\nD /opt/again\nA /opt/again/new\nA /var/lib/x\nC /proc\nA /dev/shm/x\n\ + C /run\nA /run/tmp\nA /.dockerenv\n"; + let mounts = ["/data".to_owned(), "/srv/cache".to_owned(), "/run/tmp".to_owned()]; + let plan = super::plan_layer(&super::parse_diff(diff), &mounts); + let v = |s: &[&str]| s.iter().map(|p| (*p).to_owned()).collect::>(); + assert_eq!( + plan, + super::LayerPlan { + deleted: v(&["/opt/again", "/usr/share/doc"]), + entries: v(&["/etc", "/etc/hosts2", "/opt", "/opt/again/new", "/srv", "/srv/keep", "/usr", "/usr/share", "/var", "/var/lib", "/var/lib/x"]), + trees: v(&["/app"]), + } + ); + // Nothing changed, or only what each engine makes for itself: one + // `docker diff`, and nothing sent. + assert!(super::plan_layer(&[], &mounts).is_empty()); + assert!(super::plan_layer(&super::parse_diff("C /etc\nA /etc/hostname\nC /etc/resolv.conf\nA /data\n"), &mounts).is_empty()); + // A changed directory alone (its mode, say) is its own entry. + assert_eq!(super::plan_layer(&super::parse_diff("C /tmp\n"), &[]).entries, v(&["/tmp"])); + } + + #[test] + fn reads_docker_diff_lines() { + let got = super::parse_diff("C /etc\r\nA /etc/a b\nX /x\nA relative\nA /a/../b\nA /a//b\nA /\nD /gone\n\n"); + assert_eq!(got, [('C', "/etc".to_owned()), ('A', "/etc/a b".to_owned()), ('D', "/gone".to_owned())]); + } + + #[test] + fn finds_where_a_container_has_mounts() { + let info = serde_json::json!({ + "Mounts": [{"Type": "volume", "Destination": "/data/"}, {"Type": "bind", "Destination": "/src"}], + "HostConfig": {"Mounts": [{"Type": "tmpfs", "Target": "/cache"}, {"Target": "/src"}], "Tmpfs": {"/run/tmp": "size=1m"}}, + }); + assert_eq!(super::mount_points(&info), ["/data", "/src", "/cache", "/run/tmp"]); + } + + /// `docker cp ctr:/srv/app -` names its entries from `app`: each is + /// written under its path in the layer, a hard link's target too, a + /// symlink's target as it is; long names go in pax; owners and + /// attributes stay, but overlayfs's own; a stream cut short is an error. + #[test] + fn writes_what_docker_cp_read_under_its_path_in_the_layer() { + use std::io::Read; + let entry = |kind: u8, name: &str, link: &str, size: u64, pax: &[(&str, &str)]| { + let mut header = super::plain_header(kind, "", size, if kind == b'5' { 0o750 } else { 0o640 }); + super::put_number(&mut header[108..116], 1000); + super::put_number(&mut header[116..124], 1001); + let pax = pax.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); + super::TarEntry { header, pax, name: name.to_owned(), link: link.to_owned(), size } + }; + let long = format!("app/{}", "n".repeat(120)); + let mut src = Vec::new(); + for (e, body) in [ + (entry(b'5', "app/", "", 0, &[]), &b""[..]), + (entry(b'0', "app/f", "", 5, &[("SCHILY.xattr.trusted.overlay.redirect", "/x"), ("SCHILY.xattr.user.k", "v")]), b"hello"), + (entry(b'2', "app/l", "f", 0, &[]), b""), + (entry(b'1', "app/h", "app/f", 0, &[]), b""), + (entry(b'0', &long, "", 0, &[]), b""), + ] { + super::write_entry(&mut src, &e, &e.name.clone(), &e.link.clone()).unwrap(); + src.extend_from_slice(body); + src.resize(src.len().div_ceil(512) * 512, 0); + } + src.extend_from_slice(&[0u8; 1024]); + + let mut out = Vec::new(); + let mut r = &src[..]; + while let Some(e) = super::read_entry(&mut r).unwrap() { + super::write_renamed(&mut out, &e, "/srv/app").unwrap(); + let padded = e.size.div_ceil(512) * 512; + std::io::copy(&mut (&mut r).take(padded), &mut out).unwrap(); + } + out.extend_from_slice(&[0u8; 1024]); + + let mut r = &out[..]; + let mut got = Vec::new(); + for block in out.chunks(512).filter(|b| b.iter().any(|c| *c != 0) && (b[257..263] == *b"ustar\0")) { + let mut h: [u8; 512] = block.try_into().unwrap(); + let sum = h[148..156].to_vec(); + super::put_checksum(&mut h); + assert_eq!(sum, h[148..156], "a valid checksum"); + } + while let Some(e) = super::read_entry(&mut r).unwrap() { + let mut body = vec![0u8; (e.size.div_ceil(512) * 512) as usize]; + r.read_exact(&mut body).unwrap(); + body.truncate(e.size as usize); + let owner = (super::get_number(&e.header[108..116]), super::get_number(&e.header[116..124])); + got.push((e.name.clone(), e.link.clone(), e.pax.clone(), String::from_utf8(body).unwrap(), owner)); + } + let none: Vec<(String, String)> = Vec::new(); + let owner = (Some(1000), Some(1001)); + assert_eq!(got[0], ("srv/app/".to_owned(), String::new(), none.clone(), String::new(), owner)); + assert_eq!(got[1], ("srv/app/f".to_owned(), String::new(), vec![("SCHILY.xattr.user.k".to_owned(), "v".to_owned())], "hello".to_owned(), owner)); + assert_eq!(got[2], ("srv/app/l".to_owned(), "f".to_owned(), none.clone(), String::new(), owner)); + assert_eq!(got[3], ("srv/app/h".to_owned(), "srv/app/f".to_owned(), none.clone(), String::new(), owner)); + assert_eq!(got[4].0, format!("srv/{long}")); + assert_eq!(got.len(), 5); + + // Only what was asked for: an entry by another name is an error. + let mut sink = Vec::new(); + assert!(super::write_renamed(&mut sink, &entry(b'0', "apples", "", 0, &[]), "/srv/app").is_err()); + assert!(super::write_renamed(&mut sink, &entry(b'0', "app", "", 0, &[]), "/srv/app").is_ok()); + // Cut short, inside a header or before the archive's end. + assert!(super::read_entry(&mut &src[..300]).is_err()); + assert!(super::read_entry(&mut &src[..0]).is_err()); + } + + #[test] + fn names_whiteouts_beside_what_they_delete() { + assert_eq!(super::whiteout_name("/etc/gone"), "etc/.wh.gone"); + assert_eq!(super::whiteout_name("/gone"), ".wh.gone"); + let mut out = Vec::new(); + super::write_marker(&mut out, &format!("d/{}/.wh..wh..opq", "x".repeat(100))).unwrap(); + let e = super::read_entry(&mut &out[..]).unwrap().unwrap(); + assert_eq!((e.name, e.size, e.header[156]), (format!("d/{}/.wh..wh..opq", "x".repeat(100)), 0, b'0')); + } + // #266: a fresh machine with neither engine gets a plain answer, not // docker's "context not found"; with no source named, the first that // answers is used, and only as many engines are asked as needed. diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 2848f770d..6dfb6fcc2 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 +### #410 Import: containers keep the files they wrote outside their volumes (unreleased) +- Fixes: #410 Docker Desktop import drops each container's writable layer (data outside volumes is lost); docker diff fails with chroot error +- Caused: none known +- Caused by: - +- Check: `upper-import-accepted`, `upper-diff-before-start`, `upper-size-rw`, `upper-start-sees-added`, `upper-start-hides-deleted`, `upper-refused-once-started`, `import-upper-imports`, `import-upper-nothing-left`, `import-upper-not-whole-etc`, `import-upper-runs-with-files`, `diff-never-started`, `commit-never-started` + ### #744 CLI: `kiri domains` says when the daemon is not running (unreleased) - Fixes: #744 kiri domains prints "No such file or directory (os error 2)" with no engine - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 6940d82bf..a40bcfe89 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2349,8 +2349,39 @@ t cp-sys-by-link "1" bash -c "$D cp ans:/data/root/sys - | tar -t | wc -l | tr - t cp-link-still-copies "hi" bash -c "$D cp ans:/data/root/f.txt - | tar -xO" t cp-tar-mode "0000644" bash -c "$D cp ans:/f.txt - | dd bs=1 skip=100 count=7 2>/dev/null" # A container that never started: nothing changed yet, and it commits. -t diff-never-started "0" bash -c "$D rm -f ans0 >/dev/null; $D create --name ans0 alpine true >/dev/null; $D diff ans0 | wc -l | tr -d ' '" +t diff-never-started "0" bash -c "set -o pipefail; $D rm -f ans0 >/dev/null; $D create --name ans0 alpine true >/dev/null; $D diff ans0 | wc -l | tr -d ' '" t commit-never-started "committed" bash -c "$D commit ans0 anstag:c >/dev/null && $D run --rm anstag:c echo committed" +# kiri import (#410): a writable layer brought in before the container +# first runs. docker diff and docker system df see it, and the container +# sees what was added and changed, and not what was deleted. +UPPER_TAR=$(mktemp) +python3 - "$UPPER_TAR" <<'PY' +import io, sys, tarfile +t = tarfile.open(sys.argv[1], "w", format=tarfile.PAX_FORMAT) +def add(name, kind=tarfile.REGTYPE, data=b"", mode=0o644, owner=0, link=""): + i = tarfile.TarInfo(name) + i.type, i.mode, i.uid, i.gid, i.size, i.linkname, i.mtime = kind, mode, owner, owner, len(data), link, 1700000000 + t.addfile(i, io.BytesIO(data)) +add("imported", tarfile.DIRTYPE, mode=0o750, owner=1000) +add("imported/file", data=b"added\n", owner=1000) +add("imported/link", tarfile.SYMTYPE, link="file") +add("etc", tarfile.DIRTYPE, mode=0o755) +add("etc/motd", data=b"changed\n") +add("etc/.wh.issue") +t.close() +PY +UPPER_POST="$API -o /dev/null -w %{http_code} -X POST -H Expect: -H Content-Type:application/x-tar -H Transfer-Encoding:chunked --data-binary @$UPPER_TAR" +$D rm -f ansup >/dev/null 2>&1 +$D create --name ansup alpine sleep 1d >/dev/null +t upper-import-accepted "204" $UPPER_POST http://d/kiri/containers/ansup/upper +t upper-diff-before-start "6" bash -c "$D diff ansup | grep -cxE 'C /etc|D /etc/issue|C /etc/motd|A /imported|A /imported/file|A /imported/link'" +t upper-size-rw "counted" bash -c "$API http://d/system/df | python3 -c 'import json, sys; print(\"counted\" if [c.get(\"SizeRw\", 0) for c in json.load(sys.stdin)[\"Containers\"] if \"/ansup\" in c[\"Names\"]][0] > 0 else \"not counted\")'" +$D start ansup >/dev/null +t upper-start-sees-added "added changed 1000:1000 750 file" $D exec ansup sh -c 'echo $(cat /imported/file) $(cat /etc/motd) $(stat -c %u:%g /imported/file) $(stat -c %a /imported) $(readlink /imported/link)' +t upper-start-hides-deleted "gone" $D exec ansup sh -c 'test -e /etc/issue && echo there || echo gone' +t upper-refused-once-started "409" $UPPER_POST http://d/kiri/containers/ansup/upper +$D rm -f ansup >/dev/null 2>&1 +rm -f "$UPPER_TAR" # A network that doesn't exist: created, refused at start, and the CLI # does not read it as a missing image and pull. t create-missing-network "201" $API -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' -d '{"Image":"alpine","HostConfig":{"NetworkMode":"ans-nosuch"}}' 'http://d/containers/create?name=ans-n' diff --git a/tests/import.sh b/tests/import.sh index 64523f315..08b9d317a 100755 --- a/tests/import.sh +++ b/tests/import.sh @@ -75,14 +75,14 @@ kiri_rm() { for v in $v; do [[ "$v" =~ ^[0-9a-f]{64}$ ]] && "${K[@]}" volume rm -f "$v" >/dev/null 2>&1; done done } -OURS_C="imp-digest imp-host-mnt imp-net-joiner imp-net-target imp-vol-user imp-vol-writer imp-vol-idle imp-vol-cutter imp-vol-kiri-user imp-vol-kiri-paused imp-vol-kiri-again imp-vol-kiri-stopped" +OURS_C="imp-digest imp-host-mnt imp-upper imp-net-joiner imp-net-target imp-vol-user imp-vol-writer imp-vol-idle imp-vol-cutter imp-vol-kiri-user imp-vol-kiri-paused imp-vol-kiri-again imp-vol-kiri-stopped" # An image named like an official one, with a creation date ahead: its # sh, tar, rm and find leave a mark and refuse the work. Never to be run. LOOKALIKE=localhost/imp-x/library/busybox:9 UNTAGGED_ID= LA_DIR= HM_DIR= -OURS_V="imp-vol-la imp-vol-la-new imp-vol-data imp-vol-xattrs imp-vol-named imp-vol-keep imp-vol-busy imp-vol-huge imp-vol-cut imp-probe" +OURS_V="imp-upper-vol imp-vol-la imp-vol-la-new imp-vol-data imp-vol-xattrs imp-vol-named imp-vol-keep imp-vol-busy imp-vol-huge imp-vol-cut imp-probe" cleanup() { kiri_rm $OURS_C "${S[@]}" rm -fv $OURS_C >/dev/null 2>&1 @@ -424,5 +424,23 @@ t import-host-mnt-binds "ok" bash -c ' t import-host-mnt-reads "from-host-mnt from-direct" "${K[@]}" start -a imp-host-mnt kiri_rm imp-host-mnt +section "#410 a container's writable layer" +# Made on the source by its first run: a new folder owned by 1000 with a +# file and a link, a changed and a deleted file of the image, a file added +# to /etc, and a file in a volume. Each later run only reports, and says +# "kept" when the first run's files are there. +UP_SCRIPT='if [ -e /srv/app ]; then printf kept; else mkdir -p /srv/app/sub && echo added > /srv/app/sub/f && ln -s sub/f /srv/app/l && chown -R 1000:1000 /srv/app && echo changed > /etc/motd && rm /etc/issue && echo added2 > /etc/hosts2 && echo in-volume > /data/v && printf made; fi; echo " $(cat /srv/app/sub/f /etc/motd /etc/hosts2) $(stat -c %u:%g /srv/app/sub/f) $(readlink /srv/app/l) $(test -e /etc/issue && echo issue-there || echo issue-gone) $(cat /data/v)"' +"${S[@]}" run --name imp-upper --network none -v imp-upper-vol:/data --entrypoint sh "$TOOL" -c "$UP_SCRIPT" >/dev/null +src_before=$("${S[@]}" ps -aq | wc -l) +t import-upper-imports "container imp-upper: done" "$KIRI" import "$SRC" container imp-upper +t import-upper-nothing-left "$src_before" bash -c '"$@" ps -aq | wc -l' _ "${S[@]}" +t import-upper-diff-before-start "D /etc/issue" "${K[@]}" diff imp-upper +t import-upper-only-what-changed "A /etc/hosts2" bash -c '"$@" diff imp-upper | grep "^A /etc/" | tr "\n" " "' _ "${K[@]}" +# Under /etc only its three changes, none of its unchanged files. +t import-upper-not-whole-etc "3" bash -c '"$@" diff imp-upper | grep -c "^[ACD] /etc/"' _ "${K[@]}" +t import-upper-no-volume-files "absent" bash -c '"$@" diff imp-upper | grep -q "^A /data/" && echo present || echo absent' _ "${K[@]}" +t import-upper-runs-with-files "kept added changed added2 1000:1000 sub/f issue-gone in-volume" "${K[@]}" start -a imp-upper +kiri_rm imp-upper + printf '\n%d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] || { printf 'failed: %s\n' "${FAILED[*]}"; exit 1; } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 9d3bc80d1..2a292fd50 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -286,3 +286,13 @@ absolute-form-containers #757 docker-modem requests such as GET http://127.0.0.1 import-host-mnt-container #411 importing a container with a Docker Desktop /host_mnt bind-mount source did not translate the path to the host path import-host-mnt-binds #411 imported container HostConfig.Binds kept the /host_mnt prefix or dropped bind mount options instead of stripping /host_mnt import-host-mnt-reads #411 a container imported with a /host_mnt bind source mounted an empty VM directory instead of the host files +upper-import-accepted #410 kiri import had no way to bring a container's writable layer into Kiri, so files it wrote outside its volumes were lost +upper-diff-before-start #410 a container's imported writable layer must show in docker diff before its first start +upper-size-rw #410 a container's imported writable layer must count in docker system df (SizeRw) before its first start +upper-start-sees-added #410 files added and changed in an imported writable layer (owners, modes, links) were missing once the container started +upper-start-hides-deleted #410 a file the source container deleted from its image came back after import (its whiteout was lost) +upper-refused-once-started #410 an imported writable layer must never be written under a running container's mounted root +import-upper-imports #410 Docker Desktop import dropped each container's writable layer (data outside volumes was lost) +import-upper-nothing-left #410 reading a container's writable layer must leave no container behind on the source +import-upper-not-whole-etc #410 a directory changed only because a file was added to it must not bring all of its unchanged files +import-upper-runs-with-files #410 an imported container started without the files it wrote outside its volumes From 65b7edb4e279ffb705401eb9ec492c2b118cbf23 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:10:18 +0100 Subject: [PATCH 064/157] Networks: allow disconnecting and reconnecting a running container's first network (#789) (#854) Co-authored-by: Randy Fay --- crates/kiri-init/src/linux/agent.rs | 125 ++++-- crates/kiri-init/src/linux/container.rs | 33 +- crates/kiri-init/src/linux/dns.rs | 178 +++++--- crates/kiri-init/src/linux/net.rs | 26 ++ crates/kiri/src/daemon/api.rs | 19 +- crates/kiri/src/daemon/engine.rs | 512 ++++++++++++++++++------ docs/fix-registry.md | 6 + tests/e2e.sh | 12 +- tests/regressions.tsv | 3 + 9 files changed, 683 insertions(+), 231 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 60e4728b6..917011bc5 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -703,48 +703,68 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { - if let Some(name) = kiri_proto::net_opts::values(n.opts, kiri_proto::net_opts::NETWORK).next() { - dns.name_network(n.bridge, name); - } - if !plug.no_ipv4 { - dns.register(n.bridge, n.dns_names.iter(), n.ip); - } - if let Some(v) = v6 { - dns.register6(n.bridge, n.dns_names.iter(), n.ip, v.ip); + if is_user { + if let Some(name) = kiri_proto::net_opts::values(n.opts, kiri_proto::net_opts::NETWORK).next() { + dns.name_network(n.bridge, name); + } + if !plug.no_ipv4 { + dns.register(n.bridge, n.dns_names.iter(), n.ip); + } + if let Some(v) = v6 { + dns.register6(n.bridge, n.dns_names.iter(), n.ip, v.ip); + } } if let Some(p) = procs.get_mut(&pid) { - p.run.dns_entries.push((n.bridge.to_owned(), n.ip)); + if is_user { + record_dns_entry(&mut p.run, n.bridge, n.ip); + } p.run.uplinks.retain(|u| u.veth != host_if); p.run.uplinks.extend(net::Uplink::of(&host_if, ifname, n.gateway, v6, plug)); - p.run.veths.push(host_if.clone()); + p.run.veths.retain(|(iface, _)| iface != ifname); + p.run.veths.push((ifname.to_owned(), host_if.clone())); } // A user network's names come from the embedded // DNS, which now answers in the container: its // resolv.conf names it from here on (#449). - if n.bridge != "kiri0" && !plug.no_ipv4 { + if is_user { let upstream = dhcp.as_ref().and_then(|d| d.lease.as_ref()).map_or(&host_dns[..], |l| &l.dns); let is_kiri = |a: [u8; 4]| upstream.contains(&a) || dns.serves_at(a) || a == [1, 1, 1, 1]; match container::use_embedded_dns(id, is_kiri) { Ok(Some(servers)) if !servers.is_empty() => { - if let Some(owner) = dns.owner_of(pid) { - dns.set_upstream(owner, servers); + dns.set_container_upstream(pid, servers.clone()); + dns.set_upstream(n.ip, servers); + } + Ok(_) => { + if let Some(servers) = dns.container_upstream(pid) { + dns.set_upstream(n.ip, servers); } } - Ok(_) => {} Err(e) => eprintln!("kiri-init: {id}: resolv.conf: {e}"), } + } else { + attach_kiri0_upstream(&mut dns, procs, pid, n.bridge, n.ip); } Msg::Ack.encode(&mut out) } @@ -791,12 +811,15 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap match netns_pid(procs, id) { Some(pid) => { let num: u32 = ifname.strip_prefix("eth").and_then(|v| v.parse().ok()).unwrap_or(1); + let host_if = procs + .get(&pid) + .and_then(|p| p.run.veth_for(ifname).map(str::to_owned)) + .unwrap_or_else(|| extra_veth(id, num)); dns.unregister(bridge, ip); dns.leave(pid, bridge); - let host_if = extra_veth(id, num); if let Some(p) = procs.get_mut(&pid) { p.run.dns_entries.retain(|(b, a)| !(b == bridge && *a == ip)); - p.run.veths.retain(|v| *v != host_if); + p.run.veths.retain(|(iface, _)| iface != ifname); } match net::detach(&host_if) { Ok(()) => { @@ -919,6 +942,25 @@ fn live_pid(procs: &HashMap, id: &str) -> Option /// and is not yet entered: its child has perhaps not joined it, and /// `/proc//ns/net` could still be the host's. Answered as for a /// container that is not running. +/// Records `(bridge, ip)` once in `run.dns_entries` so container exit (or +/// `NetDetach`) cleans up any names and per-IP DNS upstreams registered for it. +fn record_dns_entry(run: &mut Process, bridge: &str, ip: [u8; 4]) { + if !run.dns_entries.iter().any(|(b, a)| b == bridge && *a == ip) { + run.dns_entries.push((bridge.to_owned(), ip)); + } +} + +/// Applies the container's `--dns` upstreams to a newly attached `kiri0` +/// address and records it in `dns_entries` so exit without `NetDetach` drops it. +fn attach_kiri0_upstream(dns: &mut super::dns::Dns, procs: &mut HashMap, pid: libc::pid_t, bridge: &str, ip: [u8; 4]) { + if let Some(servers) = dns.container_upstream(pid) { + dns.set_upstream(ip, servers); + if let Some(p) = procs.get_mut(&pid) { + record_dns_entry(&mut p.run, bridge, ip); + } + } +} + /// Whether a `DnsRename` may change names: `ip` on `bridge` is a live /// container's own entry, and the bridge is one of Kiri's user networks. fn rename_allowed(procs: &HashMap, id: &str, bridge: &str, ip: [u8; 4]) -> bool { @@ -1335,6 +1377,27 @@ mod running_tests { assert!(!rename_allowed(&procs, "c1", "kiri1", ip)); } + #[test] + fn kiri0_upstream_is_recorded_in_dns_entries_and_cleaned_up_on_exit() { + let kiri0_ip = [172, 17, 0, 5]; + let mut dns = super::super::dns::Dns::default(); + let mut procs = HashMap::new(); + procs.insert(100, new_proc(Process::for_test("c1", 100), 0, 0)); + dns.set_container_upstream(100, vec![[8, 8, 8, 8]]); + + super::attach_kiri0_upstream(&mut dns, &mut procs, 100, "kiri0", kiri0_ip); + assert_eq!(procs[&100].run.dns_entries, [("kiri0".to_owned(), kiri0_ip)]); + assert_eq!(dns.ip_upstream(kiri0_ip), Some(vec![[8, 8, 8, 8]])); + assert!(!rename_allowed(&procs, "c1", "kiri0", kiri0_ip), "kiri0 stays disallowed for DnsRename"); + + let (_host, mut conn) = pipe(); + let mut exited = procs.remove(&100).unwrap(); + exited.exited = Some((0, 0)); + super::finish(&mut conn, &mut dns, &procs, exited, true).unwrap(); + assert_eq!(dns.ip_upstream(kiri0_ip), None, "container exit cleans up kiri0 per-IP upstream"); + assert_eq!(dns.container_upstream(100), None); + } + #[test] fn a_restarted_container_is_found_never_its_exited_run() { // Each map hashes with its own seed, so 20 of them walk the two @@ -1694,3 +1757,19 @@ mod clock_tests { } } +#[cfg(test)] +mod veth_tests { + use super::extra_veth; + use super::super::container::Process; + + #[test] + fn detach_looks_up_first_kv_and_fallback_kx_veths() { + let mut p = Process::for_test("0123456789abcdef", 10); + p.veths.push(("eth0".into(), "kv0123456780001".into())); + p.veths.push(("eth1".into(), extra_veth(&p.id, 1))); + assert_eq!(p.veth_for("eth0"), Some("kv0123456780001")); + assert_eq!(p.veth_for("eth1"), Some("kx0123456781")); + assert_eq!(p.veth_for("eth2"), None); + } +} + diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 97e24598d..edf6c824f 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -86,10 +86,10 @@ pub struct Process { pub tty: bool, /// (bridge, ip) registered with the DNS server, to drop on exit. pub dns_entries: Vec<(String, [u8; 4])>, - /// Host sides of its veths. Deleted on exit: a container sharing this - /// network namespace would otherwise keep them, and the address that - /// goes back to the pool, alive. - pub veths: Vec, + /// `(ifname, host_veth)` for each attached bridge interface. Deleted on + /// exit: a container sharing this network namespace would otherwise keep + /// them, and the address that goes back to the pool, alive. + pub veths: Vec<(String, String)>, /// Its non-internal networks, in the order they were plugged in: which /// one takes the default route when the one holding it is disconnected. pub uplinks: Vec, @@ -135,6 +135,11 @@ pub enum Root { } impl Process { + /// Host-side veth currently plugged in as container interface `ifname`. + pub fn veth_for(&self, ifname: &str) -> Option<&str> { + self.veths.iter().find(|(iface, _)| iface == ifname).map(|(_, host)| host.as_str()) + } + /// Settles where its root stands, without waiting: the child's byte /// means ready, the pipe's end means it ended first, nothing yet means /// still starting. @@ -764,7 +769,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

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

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

bool { /// deletes them (see `net::retire`). pub fn teardown(p: &Process, netns_shared: bool) { if netns_shared { - for v in &p.veths { + for (_, v) in &p.veths { let _ = net::detach(v); } } else { - net::retire(&p.veths); + let host_veths: Vec = p.veths.iter().map(|(_, v)| v.clone()).collect(); + net::retire(&host_veths); } if let Some(t) = &p.teardown { undo_now(t, t.remove); @@ -1214,11 +1221,15 @@ pub fn sweep(paths: &Paths, cgroup: &std::path::Path) { remove_cgroup(&cg); } } - // Host-side veths are kv<9 characters of the id><4 hex digits>. + // Host-side veths are kv<9 characters of the id><4 hex digits> or kx<9>. let Ok(links) = fs::read_dir("/sys/class/net") else { return }; for link in links.flatten() { let Ok(name) = link.file_name().into_string() else { continue }; - let ours = name.strip_prefix("kv").and_then(|rest| rest.get(..9)).is_some_and(|p| ids.iter().any(|id| id.starts_with(p))); + let ours = name + .strip_prefix("kv") + .or_else(|| name.strip_prefix("kx")) + .and_then(|rest| rest.get(..9)) + .is_some_and(|p| ids.iter().any(|id| id.starts_with(p))); if ours { let _ = net::detach(&name); } diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index 19baf817d..385a94489 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -80,6 +80,15 @@ const MAX_RELAYED: usize = 2 + 65_535; /// Docker's embedded DNS address, inside each container. pub const EMBEDDED: [u8; 4] = [127, 0, 0, 11]; +/// Who owns a forwarded DNS query (`Pending`) or `--dns` upstream list. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum ClientKey { + /// A container queried a bridge's gateway from this source IP. + Ip([u8; 4]), + /// A container queried 127.0.0.11 in its own network namespace (PID 1). + Container(i32), +} + struct Server { /// Its own number, never reused: what a forwarded query names it by. id: u64, @@ -87,9 +96,9 @@ struct Server { /// network of the container it is in. bridges: Vec, sock: OwnedFd, - /// In a container's namespace: (its PID, the address its `--dns` - /// servers are kept under). Every query there comes from 127.0.0.1. - container: Option<(i32, [u8; 4])>, + /// PID of the container whose namespace this 127.0.0.11 server is in; + /// every query there comes from 127.0.0.1. + container: Option, } struct Pending { @@ -101,8 +110,8 @@ struct Pending { sock: OwnedFd, /// The ID it went out with. our: u16, - /// Who asked, for `MAX_PER_CLIENT`: the container's address. - key: [u8; 4], + /// Who asked, for `MAX_PER_CLIENT`. + key: ClientKey, /// The server the query came in on (`Server::id`). server: u64, client: libc::sockaddr_in, @@ -138,8 +147,11 @@ pub struct Dns { /// bridge → its Docker network's name: the order a container's server /// searches its networks in. networks: HashMap, - /// Container address → its `--dns` servers, used instead of the VM's. + /// Container address → its `--dns` servers, used on a gateway listener. clients: HashMap<[u8; 4], Vec<[u8; 4]>>, + /// Container PID → its `--dns` servers, used on 127.0.0.11 so custom + /// resolvers survive disconnecting and reconnecting even the first network. + container_upstreams: HashMap>, pending: Vec, /// Lookups the VM's resolver fails go through the host (in the VM; a /// Linux host's agent asks the host's resolvers itself). @@ -239,41 +251,36 @@ impl Dns { /// Starts answering at 127.0.0.11:53 in container `pid`'s network /// namespace `netns` (lo up) for the names on `bridge`, or adds `bridge` - /// to the networks its server answers for. `owner` is the address its - /// `--dns` servers are kept under (`set_upstream`). - pub fn serve_in(&mut self, netns: &std::fs::File, pid: i32, owner: [u8; 4], bridge: &str) -> io::Result<()> { - if let Some(s) = self.servers.iter_mut().find(|s| s.container.is_some_and(|(p, _)| p == pid)) { + /// to the networks its server answers for. + pub fn serve_in(&mut self, netns: &std::fs::File, pid: i32, bridge: &str) -> io::Result<()> { + if let Some(s) = self.servers.iter_mut().find(|s| s.container == Some(pid)) { if !s.bridges.iter().any(|b| b == bridge) { s.bridges.push(bridge.to_owned()); } return Ok(()); } let sock = super::netlink::in_netns(netns, embedded_socket)?; - self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: Some((pid, owner)) }); + self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: Some(pid) }); Ok(()) } /// Container `pid` left `bridge` (`network disconnect`). pub fn leave(&mut self, pid: i32, bridge: &str) { - for s in self.servers.iter_mut().filter(|s| s.container.is_some_and(|(p, _)| p == pid)) { + for s in self.servers.iter_mut().filter(|s| s.container == Some(pid)) { s.bridges.retain(|b| b != bridge); } } - /// The address container `pid`'s 127.0.0.11 server keeps its `--dns` - /// servers under (`set_upstream`), if it has one. - pub fn owner_of(&self, pid: i32) -> Option<[u8; 4]> { - self.servers.iter().find_map(|s| s.container.filter(|(p, _)| *p == pid).map(|(_, owner)| owner)) - } - /// Whether the agent answers DNS at `ip` on a bridge (its gateway). pub fn serves_at(&self, ip: [u8; 4]) -> bool { self.servers.iter().filter(|s| s.container.is_none()).any(|s| local_addr(&s.sock) == Some(ip)) } - /// Container `pid` is gone: its 127.0.0.11 server goes. + /// Container `pid` is gone: its 127.0.0.11 server and `--dns` servers go. pub fn drop_container(&mut self, pid: i32) { - self.servers.retain(|s| !s.container.is_some_and(|(p, _)| p == pid)); + self.servers.retain(|s| s.container != Some(pid)); + self.container_upstreams.remove(&pid); + self.pending.retain(|p| p.key != ClientKey::Container(pid)); self.forget_pending(); } @@ -335,11 +342,38 @@ impl Dns { } } + /// Where queries from container `pid`'s 127.0.0.11 listener go; kept per + /// container so disconnecting its first network does not erase `--dns`. + pub fn set_container_upstream(&mut self, pid: i32, mut servers: Vec<[u8; 4]>) { + servers.truncate(MAX_OWN_SERVERS); + if servers.is_empty() { + self.container_upstreams.remove(&pid); + } else { + self.container_upstreams.insert(pid, servers); + } + } + + pub fn container_upstream(&self, pid: i32) -> Option> { + self.container_upstreams.get(&pid).cloned() + } + + #[cfg(test)] + pub fn ip_upstream(&self, ip: [u8; 4]) -> Option> { + self.clients.get(&ip).cloned() + } + + fn own_servers(&self, key: ClientKey) -> Option<&Vec<[u8; 4]>> { + match key { + ClientKey::Ip(ip) => self.clients.get(&ip), + ClientKey::Container(pid) => self.container_upstreams.get(&pid), + } + } + pub fn unregister(&mut self, bridge: &str, ip: [u8; 4]) { self.clients.remove(&ip); // Its queries in flight go with it: a container given the address // next never gets them, or their answers. - self.pending.retain(|p| p.key != ip); + self.pending.retain(|p| p.key != ClientKey::Ip(ip)); self.drop_names(bridge, ip); } @@ -528,8 +562,8 @@ impl Dns { self.fail(at); } } - let key = self.servers[server].container.map_or(client.sin_addr.s_addr.to_ne_bytes(), |(_, owner)| owner); - let own = self.clients.get(&key).map(|v| (v.len(), v.first().copied())); + let key = self.servers[server].container.map_or_else(|| ClientKey::Ip(client.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); + let own = self.own_servers(key).map(|v| (v.len(), v.first().copied())); let Some((_, _, end)) = parse_question(q) else { return; }; @@ -555,7 +589,7 @@ impl Dns { let sock = match own { // The first of its own servers that can be sent to. Some((len, _)) => (0..len).find_map(|i| { - let sock = self.clients.get(&key).and_then(|v| v.get(i)).and_then(|d| ask(*d, &msg))?; + let sock = self.own_servers(key).and_then(|v| v.get(i)).and_then(|d| ask(*d, &msg))?; at = Some(i); Some(sock) }), @@ -620,7 +654,7 @@ impl Dns { let p = &self.pending[at]; let Some(mut i) = p.own else { return false }; let key = p.key; - if p.started.elapsed() >= OWN_DEADLINE || self.clients.get(&key).is_none_or(|v| i + 1 >= v.len()) { + if p.started.elapsed() >= OWN_DEADLINE || self.own_servers(key).is_none_or(|v| i + 1 >= v.len()) { return false; } let Some(our) = random_id() else { return false }; @@ -628,7 +662,7 @@ impl Dns { self.pending[at].query[0..2].copy_from_slice(&our.to_be_bytes()); loop { i += 1; - let Some(dest) = self.clients.get(&key).and_then(|v| v.get(i)).copied() else { break }; + let Some(dest) = self.own_servers(key).and_then(|v| v.get(i)).copied() else { break }; if let Some(sock) = ask(dest, &self.pending[at].query) { let p = &mut self.pending[at]; p.sock = sock; @@ -1022,7 +1056,7 @@ mod tests { #[test] fn a_containers_server_answers_for_each_of_its_networks() { let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some((42, [10, 5, 0, 2])) }); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.register("kiri1", ["web"].iter(), [10, 5, 0, 3]); dns.register("kiri2", ["db"].iter(), [10, 6, 0, 3]); let q = query("db", 1); @@ -1184,7 +1218,7 @@ mod tests { // (shared network, project network, which one answers) for (shared, project, shared_answers) in [("kiri_shared_t", "kra_default", true), ("ddev_default", "ddev-a_default", false), ("zz_shared", "kca_default", false)] { let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some((42, [10, 1, 0, 2])) }); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.name_network("kiri1", shared); dns.name_network("kiri2", project); // This project's db on both networks, another project's on the shared one. @@ -1301,10 +1335,9 @@ mod tests { let from = super::sockaddr(addr.ip().octets(), addr.port()); // One server still works; refusals move through the list in order. for servers in [vec![resolver_ip], vec![[127, 0, 0, 4], resolver_ip], vec![[127, 0, 0, 4], [127, 0, 0, 6], resolver_ip]] { - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers.clone()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers.clone()); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); assert_eq!(dns.pending.len(), 1); @@ -1358,10 +1391,9 @@ mod tests { let client = UdpSocket::bind("127.0.0.1:0").unwrap(); let std::net::SocketAddr::V4(addr) = client.local_addr().unwrap() else { panic!() }; let from = super::sockaddr(addr.ip().octets(), addr.port()); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![unsendable, resolver_ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![unsendable, resolver_ip]); dns.forward(0, &query("example.com", 1), from, &[]); assert_eq!(dns.pending.len(), 1); assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), resolver_ip, "the server that can't be sent to was skipped"); @@ -1371,8 +1403,8 @@ mod tests { assert_eq!(&buf[..n], &dns.pending[0].query[..]); // With nothing to send to, no query is kept and the host is not asked. let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![unsendable]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![unsendable]); dns.forward(0, &query("example.com", 1), from, &[]); assert!(dns.pending.is_empty()); assert!(dns.relay_down_until.is_none(), "no host relay was tried"); @@ -1396,7 +1428,6 @@ mod tests { let client = UdpSocket::bind("127.0.0.1:0").unwrap(); let std::net::SocketAddr::V4(addr) = client.local_addr().unwrap() else { panic!() }; let from = super::sockaddr(addr.ip().octets(), addr.port()); - let owner = [10, 5, 0, 2]; // Answers the query waiting at `server` with `rcode`. let reply = |server: &UdpSocket, rcode: u8| { let mut buf = [0u8; 512]; @@ -1409,8 +1440,8 @@ mod tests { }; for (rcode, servers, answered_by) in [(5u8, vec![first_ip, second_ip], 1usize), (2, vec![first_ip, second_ip], 1), (5, vec![first_ip], 0)] { let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers.clone()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers.clone()); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); reply(&first, rcode); @@ -1464,10 +1495,9 @@ mod tests { let _silent = std::net::UdpSocket::from(super::bound(silent_ip, 53).unwrap()); let next = std::net::UdpSocket::from(super::bound(next_ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![silent_ip, next_ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![silent_ip, next_ip]); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); let first_query = dns.pending[0].query.clone(); @@ -1510,10 +1540,9 @@ mod tests { let (client, from) = client(); for servers in [vec![[127, 0, 0, 7]], vec![[127, 0, 0, 7], [127, 0, 0, 8]]] { let attempts = servers.len(); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers); let q = query("example.com", 1); dns.forward(0, &q, from, &[vm_ip]); assert_eq!(dns.pending.len(), 1); @@ -1550,10 +1579,9 @@ mod tests { let ips = [[127, 0, 0, 30], [127, 0, 0, 31], [127, 0, 0, 32]]; let _held: Vec<_> = ips.iter().map(|ip| std::net::UdpSocket::from(super::bound(*ip, 53).unwrap())).collect(); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, ips.to_vec()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, ips.to_vec()); dns.forward(0, &query("example.com", 1), from, &[]); dns.pending[0].started = Instant::now() - super::OWN_DEADLINE; dns.pending[0].sent = Instant::now(); @@ -1587,10 +1615,9 @@ mod tests { let _a = std::net::UdpSocket::from(super::bound(a, 53).unwrap()); let _b = std::net::UdpSocket::from(super::bound(b, 53).unwrap()); let (_client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![a, b]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![a, b]); dns.forward(0, &query("example.com", 1), from, &[]); let first = dns.pending[0].our; assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), a); @@ -1605,9 +1632,16 @@ mod tests { fn own_servers_go_with_the_container() { let mut dns = Dns::default(); dns.set_upstream([10, 5, 0, 2], vec![[8, 8, 8, 8]]); + dns.set_container_upstream(42, vec![[8, 8, 8, 8]]); assert_eq!(dns.clients.get(&[10, 5, 0, 2]), Some(&vec![[8, 8, 8, 8]])); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]])); dns.unregister("kiri1", [10, 5, 0, 2]); assert!(dns.clients.is_empty()); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]]), "disconnection keeps 127.0.0.11 --dns servers"); + dns.leave(42, "kiri1"); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]])); + dns.drop_container(42); + assert!(dns.container_upstreams.is_empty()); dns.set_upstream([10, 5, 0, 3], vec![]); assert!(dns.clients.is_empty()); } @@ -1618,17 +1652,32 @@ mod tests { fn a_containers_queries_in_flight_go_with_it() { let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); + let gw_id = super::server_id(); + dns.servers.push(Server { id: gw_id, bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let c_id = super::server_id(); + dns.servers.push(Server { id: c_id, bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.set_upstream(owner, vec![[127, 0, 0, 1], [127, 0, 0, 2]]); let mut p = pending(); - p.key = owner; + p.server = gw_id; + p.key = super::ClientKey::Ip(owner); p.own = Some(0); dns.pending.push(p); let mut other = pending(); - other.key = [10, 5, 0, 3]; + other.server = gw_id; + other.key = super::ClientKey::Ip([10, 5, 0, 3]); dns.pending.push(other); + let mut in_ns = pending(); + in_ns.server = c_id; + in_ns.key = super::ClientKey::Container(42); + in_ns.own = Some(0); + dns.pending.push(in_ns); dns.unregister("kiri1", owner); + assert_eq!(dns.pending.len(), 2, "gateway queries for left IP go; 127.0.0.11 and another IP stay"); + assert_eq!(dns.pending[0].key, super::ClientKey::Ip([10, 5, 0, 3]), "another container's stay"); + assert_eq!(dns.pending[1].key, super::ClientKey::Container(42)); + dns.drop_container(42); assert_eq!(dns.pending.len(), 1); - assert_eq!(dns.pending[0].key, [10, 5, 0, 3], "another container's stay"); + assert_eq!(dns.pending[0].key, super::ClientKey::Ip([10, 5, 0, 3])); } /// A query names the server it came in on by a number that is never @@ -1667,13 +1716,12 @@ mod tests { let ip = [127, 0, 0, 61]; let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![ip]); for _ in 0..super::MAX_OWN_PER_CLIENT { let mut p = pending(); - p.key = owner; + p.key = super::ClientKey::Container(42); p.own = Some(0); p.server = dns.servers[0].id; p.client = from; @@ -1694,10 +1742,9 @@ mod tests { let ip = [127, 0, 0, 62]; let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![ip]); for _ in 0..super::MAX_OWN_PER_CLIENT { dns.forward(0, &query("example.com", 1), from, &[]); } @@ -1718,10 +1765,9 @@ mod tests { let next = std::net::UdpSocket::from(super::bound(b, 53).unwrap()); next.set_nonblocking(true).unwrap(); let (_client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![a, b]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![a, b]); dns.forward(0, &query("example.com", 1), from, &[]); let sent = dns.pending[0].query.clone(); dns.pending[0].started = Instant::now() - super::OWN_DEADLINE; @@ -1880,7 +1926,7 @@ mod tests { Pending { sock: udp_socket().unwrap(), our: 1, - key: [0; 4], + key: super::ClientKey::Ip([0; 4]), server: 0, client: unsafe { std::mem::zeroed() }, id: 7, @@ -1917,7 +1963,7 @@ mod tests { let client = super::sockaddr([172, 17, 0, 2], 4000); for _ in 0..super::MAX_PER_CLIENT { let mut p = pending(); - p.key = [172, 17, 0, 2]; + p.key = super::ClientKey::Ip([172, 17, 0, 2]); dns.pending.push(p); } let q = query("example.com", 1); diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 3edc41713..3d3c0932a 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -1136,6 +1136,32 @@ fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 000000 assert_eq!(route_holders(&[]), (None, None)); } + #[test] + fn leaving_first_of_three_networks_promotes_first_attached_external_gateway_and_ifname() { + let gw_a = [10, 98, 0, 1]; + let gw_zeta = [10, 98, 1, 1]; + let gw_beta = [10, 98, 2, 1]; + let mut ups = Vec::new(); + ups.extend(Uplink::of("kva0", "eth0", gw_a, None, Plug::default())); + // An internal network attached in between produces no uplink. + ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, no_ipv4: false })); + ups.extend(Uplink::of("kxz2", "eth2", gw_zeta, None, Plug::default())); + ups.extend(Uplink::of("kxb3", "eth3", gw_beta, None, Plug::default())); + + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth0", Some(gw_a)))); + + // Disconnecting `a` promotes `zeta` on eth2 (first-plugged external), not `beta` on eth3. + ups.retain(|u| u.veth != "kva0"); + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth2", Some(gw_zeta)))); + + // Disconnecting `zeta` promotes `beta` on eth3. + ups.retain(|u| u.veth != "kxz2"); + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth3", Some(gw_beta)))); + } + #[test] fn a_disconnect_that_takes_no_default_route_touches_nothing() { // The pid is never used: nothing to hand over, so no namespace is opened. diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 1b54b0025..5964b9638 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2967,14 +2967,19 @@ fn list(req: &Request, engine: &Engine) -> Result { return None; } let labels = if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }; - let net = networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge")); + let first = (!c.spec.left_all_networks) + .then(|| networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge"))) + .flatten(); let keep = f.any("id", |v| c.id.starts_with(v)) && f.name(&c.name) && f.labels(&labels) && f.any("status", |v| v == state_word(c)) && f.any("exited", |v| c.status == Status::Exited && v.parse() == Ok(c.exit_code)) && ancestors.as_ref().is_none_or(|ids| ids.contains(&c.spec.image_id)) - && f.any("network", |v| net.is_some_and(|n| n.name == v || n.id.starts_with(v))) + && f.any("network", |v| { + first.is_some_and(|n| n.name == v || n.id.starts_with(v)) + || c.spec.extra_networks.iter().any(|x| networks.iter().find(|n| n.name == x.name).is_some_and(|n| n.name == v || n.id.starts_with(v))) + }) && f.any("volume", |v| c.spec.volumes.iter().chain(&c.spec.anon_volumes).any(|n| n == v) || c.spec.mount_info.iter().any(|m| m["Destination"] == v || m["Source"] == v)) && f.any("health", |v| v == health.get(&c.id).map_or("none", |h| h.status.as_str())); if !keep { @@ -6457,9 +6462,19 @@ mod leave_first_network_tests { let networks: Vec = engine.lock_net().all().to_vec(); assert_eq!(names(&container_inspect(&engine, &id).unwrap()["NetworkSettings"]["Networks"]), ["probe-net"]); assert_eq!(names(&engine.with(&id, |c| network_settings(c, &networks)).unwrap()["Networks"]), ["probe-net"]); + let filter_has = |net: &str| { + let filters = format!(r#"{{"network":["{net}"]}}"#); + let req = Request::internal("GET", "/containers/json", &[("all", "1"), ("filters", &filters)], Vec::new()); + list(&req, &engine).unwrap().as_array().unwrap().iter().any(|r| r["Id"] == id) + }; + assert!(filter_has("probe-net")); + assert!(!filter_has("bridge")); engine.disconnect("probe-net", &id).unwrap(); assert!(names(&container_inspect(&engine, &id).unwrap()["NetworkSettings"]["Networks"]).is_empty()); assert!(names(&engine.with(&id, |c| network_settings(c, &networks)).unwrap()["Networks"]).is_empty()); + assert!(!filter_has("probe-net")); + assert!(!filter_has("none")); + assert!(engine.network_members("none").is_empty()); drop(engine); let _ = std::fs::remove_dir_all(root); } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 79d2b2b94..512b7dadc 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -597,22 +597,23 @@ impl Spec { self.network_mode == network || (network == "bridge" && matches!(self.network_mode.as_str(), "default" | "")) } - /// Leaves the first network of a container that is not running, as + /// Leaves the first network of a container (running or stopped), as /// `docker network disconnect` does on Docker for any of its networks. /// Kiri keeps the first network apart (`network_mode`, `aliases`, /// `ipv4_address`, `ipv6_address`, `mac_address`) because only it gives /// the default route and the main address, so one of the others takes /// its place, with its own aliases, fixed addresses and MAC: none of the /// left network's settings follow, or a fixed `--ip` would be asked for - /// on a network it does not belong to. The one picked is the one Docker - /// gives the default route to: a network that reaches outside before an - /// `internal` one (which gives no default route), then by name, as - /// libnetwork orders a container's endpoints when none has a gateway - /// priority (Kiri keeps none), and as create picks the primary of - /// several endpoints. `internal` says whether a network is internal. - /// With no other network it is left with none, as with `--network none`. + /// on a network it does not belong to. The one picked is the first + /// remaining network in attachment order that reaches outside (not + /// `internal`), or the first one if every remaining network is + /// `internal`, matching `kiri-init`'s `route_holders` (which keeps the + /// first-plugged non-internal uplink on the default route) and + /// `start_on_vm` (which attaches `network_mode` then `extra_networks` in + /// order). `internal` says whether a network is internal. With no other + /// network it is left with none, as with `--network none`. pub fn leave_first_network(&mut self, internal: impl Fn(&str) -> bool) { - let next = self.extra_networks.iter().enumerate().min_by(|(_, a), (_, b)| internal(&a.name).cmp(&internal(&b.name)).then_with(|| a.name.cmp(&b.name))).map(|(i, _)| i); + let next = self.extra_networks.iter().position(|x| !internal(&x.name)).or_else(|| (!self.extra_networks.is_empty()).then_some(0)); match next { Some(i) => { let x = self.extra_networks.remove(i); @@ -871,6 +872,11 @@ pub struct Container { pub paused: bool, /// Addresses on `spec.extra_networks` while running, as (network, ip). pub extra_ips: Vec<(String, [u8; 4])>, + /// The interface `spec.network_mode` is plugged in as while running, as + /// `n` for `eth{n}`: `Some(0)` at start on a bridge network, or the + /// promoted network's number after leaving the first; `None` when stopped + /// or after leaving all networks. + pub first_if: Option, /// The interface each extra network is plugged in as while running, /// as (network, n) for `eth{n}`. A disconnect leaves a gap, so the /// number can't be worked out from the network's place in the list. @@ -1002,6 +1008,27 @@ struct Records { on_disk: Option<(usize, u64)>, } +/// Lowest unused `eth{n}` interface index at or above `min`. +fn free_eth(c: &Container, min: u32) -> u32 { + (min..).find(|n| c.first_if != Some(*n) && !c.extra_ifs.iter().any(|(_, x)| x == n)).expect("a free number") +} + +/// Reconstructs port bindings to target a newly promoted network IP while +/// preserving ephemeral host ports already bound for `0` entries. +fn rebind_bindings(ports: &[super::ports::Binding], bound: &[(super::ports::Binding, String, u16)]) -> Vec { + ports + .iter() + .map(|b| { + let host_port = if b.host_port == 0 { + bound.iter().find(|(bb, ..)| bb == b).map_or(0, |(_, _, p)| *p) + } else { + b.host_port + }; + super::ports::Binding { host_port, ..b.clone() } + }) + .collect() +} + /// Length and hash of a file's bytes, enough to tell whether it is the one /// this engine last read or wrote. fn fingerprint(bytes: &[u8]) -> (usize, u64) { @@ -2357,6 +2384,7 @@ impl Engine { start_owed: false, paused: false, extra_ips: Vec::new(), + first_if: None, extra_ifs: Vec::new(), ip6: None, extra_ip6s: Vec::new(), @@ -2624,6 +2652,7 @@ impl Engine { for (net, ip) in std::mem::take(&mut c.extra_ips) { self.release_ip(&net, ip); } + c.first_if = None; c.extra_ifs.clear(); self.release_ip6s(c); c.paused = false; @@ -2752,6 +2781,7 @@ impl Engine { for (net, ip) in std::mem::take(&mut c.extra_ips) { self.release_ip(&net, ip); } + c.first_if = None; c.extra_ifs.clear(); self.release_ip6s(c); c.paused = false; @@ -3257,6 +3287,7 @@ impl Engine { start_owed: false, paused: false, extra_ips: Vec::new(), + first_if: None, extra_ifs: Vec::new(), ip6: None, extra_ip6s: Vec::new(), @@ -3569,6 +3600,7 @@ impl Engine { if ip != [0; 4] { if let Some(c) = self.lock().containers.get_mut(&id) { c.ip = Some(ip); + c.first_if = Some(0); } } // A restarted container keeps its writable layer, so only --rm deletes it. @@ -3677,8 +3709,20 @@ impl Engine { } if flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0 && joined.is_none() { for (i, extra) in spec.extra_networks.iter().enumerate() { - if let Err(e) = self.attach_extra(&vm, &id, i as u32 + 1, extra) { - crate::diag::warn!("container not attached to a network", id = &id[..12], network = extra.name, error = format!("{e:?}")); + let n = i as u32 + 1; + let sync = self.names_sync(&id); + let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); + match self.attach_network(&vm, &id, n, extra, false) { + Ok((net, ip, ip6)) => { + if let Some(c) = self.lock().containers.get_mut(&id) { + c.extra_ips.push((net.name.clone(), ip)); + c.extra_ifs.push((net.name.clone(), n)); + if let Some(a) = ip6 { + c.extra_ip6s.push((net.name, a)); + } + } + } + Err(e) => crate::diag::warn!("container not attached to a network", id = &id[..12], network = extra.name, error = format!("{e:?}")), } } } @@ -4000,6 +4044,8 @@ impl Engine { for (net, ip) in std::mem::take(&mut c.extra_ips) { self.release_ip(&net, ip); } + c.first_if = None; + c.extra_ifs.clear(); self.release_ip6s(c); } if !spec.auto_remove && st.containers.get(id).is_some_and(|c| c.vm_stopped) { @@ -4128,6 +4174,7 @@ impl Engine { let c = st.containers.get_mut(id).unwrap(); c.status = Status::Running; c.ip = Some(ip); + c.first_if = Some(0); } /// For the Finder view (macOS). @@ -4227,7 +4274,7 @@ impl Engine { let canonical = self.lock_networks().find(network).map(|n| n.name.clone()).unwrap_or_default(); self.each(|c| { let theirs = self.lock_networks().find(&c.spec.network_mode).map(|n| n.name.clone()).unwrap_or_default(); - if theirs == canonical { + if !c.spec.left_all_networks && theirs == canonical { return Some((c.id.clone(), c.name.clone(), c.ip, c.ip6)); } c.spec.extra_networks.iter().any(|x| x.name == canonical).then(|| { @@ -4368,13 +4415,20 @@ impl Engine { } /// SIGTERM, then SIGKILL after `timeout` if it is still running. - /// Plugs a running container into one more network as `eth{n}`. - fn attach_extra(&self, vm: &VmLink, id: &str, n: u32, extra: &ExtraNetwork) -> Result<(), Error> { - // Held from the name read to the network being recorded, so a rename - // lands before (and the guest then has the new name) or after (and - // renames this network too). - let sync = self.names_sync(id); - let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); + fn release_attached_ips(&self, net_name: &str, ip: Option<[u8; 4]>, ip6: Option<[u8; 16]>) { + if let Some(ip) = ip { + self.release_ip(net_name, ip); + } + if let Some(a) = ip6 { + self.lock_networks().release6(net_name, a); + } + } + + /// Allocates addresses and plugs a running container into `extra` as + /// `eth{n}`. Caller must hold `names_sync` for `id`. Does not mutate + /// container state; returns `(net, ip, ip6)` so the caller can commit them + /// or roll back if the container exited or ports could not be bound. + fn attach_network(&self, vm: &VmLink, id: &str, n: u32, extra: &ExtraNetwork, is_first: bool) -> Result<(super::network::Network, [u8; 4], Option<[u8; 16]>), Error> { let net = { let mut nets = self.lock_networks(); nets.settle(&extra.name).map_err(Error::Conflict)?; @@ -4390,17 +4444,31 @@ impl Engine { self.lock_networks().allocate_avoiding(&net.name, &avoid).ok_or_else(|| Error::Conflict(format!("no free address left on network {}", net.name)))? } }; - let off6 = self.lock().containers.get(id).is_some_and(|c| c.spec.ipv6_disabled(&format!("eth{n}"))); + let (off6, names) = { + let st = self.lock(); + let Some(c) = st.containers.get(id).filter(|c| c.status == Status::Running) else { + drop(st); + self.release_ip(&net.name, ip); + return Err(Error::Conflict(format!("Container {} is not running", &id[..12]))); + }; + let off6 = c.spec.ipv6_disabled(&format!("eth{n}")); + let names = if net.builtin() { + Vec::new() + } else { + let host = if is_first && !c.spec.hostname.is_empty() { c.spec.hostname.clone() } else { c.short_id().to_owned() }; + let mut v = vec![c.name.clone(), host]; + v.extend(extra.aliases.iter().cloned()); + v + }; + (off6, names) + }; let ip6 = match if off6 { Ok(None) } else { self.allocate_ip6(&net, &extra.ipv6_address) } { Ok(a) => a, Err(e) => { - self.lock_networks().release(&net.name, ip); + self.release_ip(&net.name, ip); return Err(e); } }; - let (name, hostname) = self.lock().containers.get(id).map(|c| (c.name.clone(), c.short_id().to_owned())).unwrap_or_default(); - let mut names = vec![name, hostname]; - names.extend(extra.aliases.iter().cloned()); let mut opts: Vec = if extra.mac_address.is_empty() { Vec::new() } else { vec![format!("{}={}", kiri_proto::net_opts::MAC, extra.mac_address)] }; if let (Some(a), Some(v)) = (ip6, &net.v6) { opts.push(format!("{}={}/{}", kiri_proto::net_opts::IP6, super::network::ip6_str(a), v.prefix)); @@ -4414,21 +4482,10 @@ impl Engine { } opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, net.name)); if let Err(e) = vm.net_attach(id, n, &net.bridge, ip, net.prefix, net.gateway, &names, &opts) { - let mut nets = self.lock_networks(); - nets.release(&net.name, ip); - if let Some(a) = ip6 { - nets.release6(&net.name, a); - } + self.release_attached_ips(&net.name, Some(ip), ip6); return Err(Error::Io(e)); } - if let Some(c) = self.lock().containers.get_mut(id) { - c.extra_ips.push((net.name.clone(), ip)); - c.extra_ifs.push((net.name.clone(), n)); - if let Some(a) = ip6 { - c.extra_ip6s.push((net.name.clone(), a)); - } - } - Ok(()) + Ok((net, ip, ip6)) } /// `docker network connect`. @@ -4436,57 +4493,93 @@ impl Engine { // After the start, as when the guest answered nothing else during // it, so this and the start's own networks are numbered in turn. let id = self.resolve_after_start(key)?; + // Serializes name reads/updates and runtime attachment with disconnect + // and rename so neither overwrites the other's DNS names or state. + let sync = self.names_sync(&id); + let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?; + if net.driver != "bridge" { + return Err(Error::BadRequest(format!("only bridge networks can be connected, not {}", net.driver))); + } if let Some(ip) = super::network::parse_ip(&ipv4_address) { net.check_static(ip).map_err(Error::BadRequest)?; } if let Some(ip) = super::network::parse_ip6(&ipv6_address) { net.check_static6(ip).map_err(Error::BadRequest)?; } - let (n, running) = { + let extra = ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }; + let (n, was_left_all, ports) = { let mut st = self.lock(); let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?; - if c.spec.first_network_is(&net.name) || c.spec.extra_networks.iter().any(|x| x.name == net.name) { + if (!c.spec.left_all_networks && c.spec.first_network_is(&net.name)) || c.spec.extra_networks.iter().any(|x| x.name == net.name) { return Err(Error::Conflict(format!("endpoint with name {} already exists in network {}", c.name, net.name))); } - // It left every network it had: the one it joins becomes its - // first, which a start sets up as such. A running one has only - // loopback and its resolver set for no network, which a plug-in - // alone would not change. - if c.spec.left_all_networks { - if c.status == Status::Running { - return Err(Error::Conflict(format!("Kiri cannot connect a running container that left all its networks to {}; stop the container first", net.name))); + let was_left_all = c.spec.left_all_networks; + if !was_left_all && matches!(c.spec.network_mode.as_str(), "host" | "none") { + return Err(Error::BadRequest(format!("container cannot be connected to {} while on {}", net.name, c.spec.network_mode))); + } + if !was_left_all && c.spec.network_mode.starts_with("container:") { + return Err(Error::BadRequest("container sharing network namespace with another container or host cannot be connected to any other network".into())); + } + if c.status != Status::Running { + if was_left_all { + c.spec.join_first_network(extra); + } else { + c.spec.extra_networks.push(extra); } - c.spec.join_first_network(ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }); drop(st); self.save(); self.emit_network("connect", &net, &id); return Ok(()); } - if matches!(c.spec.network_mode.as_str(), "host" | "none") { - return Err(Error::BadRequest(format!("container cannot be connected to {} while on {}", net.name, c.spec.network_mode))); - } - if c.spec.network_mode.starts_with("container:") { - return Err(Error::BadRequest("container sharing network namespace with another container or host cannot be connected to any other network".into())); + let min = if was_left_all { 0 } else { 1 }; + let n = free_eth(c, min); + let ports = if was_left_all { c.spec.ports.clone() } else { Vec::new() }; + (n, was_left_all, ports) + }; + let vm = self.vm()?; + let (attached_net, ip, ip6) = self.attach_network(&vm, &id, n, &extra, was_left_all)?; + let fw = if was_left_all && !ports.is_empty() { + match super::ports::start(vm.clone(), &id, &ports, ip) { + Ok(fw) => Some(fw), + Err(e) => { + let _ = vm.net_detach(&id, n, &attached_net.bridge, ip); + self.release_attached_ips(&attached_net.name, Some(ip), ip6); + return Err(Error::Conflict(e.to_string())); + } } - c.spec.extra_networks.push(ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }); - // The lowest eth number not in use: a disconnect may have freed - // one below the top. - let n = (1..).find(|n| !c.extra_ifs.iter().any(|(_, x)| x == n)).expect("a free number"); - (n, c.status == Status::Running) + } else { + None }; - self.save(); - if running { - let extra = self.lock().containers.get(&id).and_then(|c| c.spec.extra_networks.last().cloned()).ok_or_else(|| gone(&id))?; - let vm = self.vm()?; - if let Err(e) = self.attach_extra(&vm, &id, n, &extra) { - if let Some(c) = self.lock().containers.get_mut(&id) { - c.spec.extra_networks.retain(|x| x.name != net.name); + { + let mut st = self.lock(); + if let Some(c) = st.containers.get_mut(&id).filter(|c| c.status == Status::Running && !vm.is_disconnected()) { + if was_left_all { + c.spec.join_first_network(extra); + c.ip = Some(ip); + c.ip6 = ip6; + c.first_if = Some(n); + c.forwards = fw; + } else { + c.spec.extra_networks.push(extra); + c.extra_ips.push((attached_net.name.clone(), ip)); + c.extra_ifs.push((attached_net.name.clone(), n)); + if let Some(a) = ip6 { + c.extra_ip6s.push((attached_net.name.clone(), a)); + } } - return Err(e); + } else { + drop(st); + drop(fw); + if !vm.is_disconnected() { + let _ = vm.net_detach(&id, n, &attached_net.bridge, ip); + } + self.release_attached_ips(&attached_net.name, Some(ip), ip6); + return Err(Error::Conflict(format!("Container {} is not running", &id[..12]))); } } - self.emit_network("connect", &net, &id); + self.save(); + self.emit_network("connect", &attached_net, &id); Ok(()) } @@ -4499,7 +4592,22 @@ impl Engine { let sync = self.names_sync(&id); let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?; - let (n, ip) = { + enum Detached { + Extra { + n: Option, + ip: Option<[u8; 4]>, + }, + First { + n: Option, + ip: Option<[u8; 4]>, + ip6: Option<[u8; 16]>, + old_fw: Option, + rebind_ports: Vec, + new_target: Option<[u8; 4]>, + running: bool, + }, + } + let work = { let mut st = self.lock(); let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?; if c.spec.first_network_is(&net.name) && matches!(net.name.as_str(), "host" | "none") { @@ -4509,52 +4617,91 @@ impl Engine { return Err(Error::BadRequest(format!("container cannot be disconnected from {} network", net.name))); } if c.spec.first_network_is(&net.name) { - // A running container's first network holds its default - // route, its main address (which published ports go to) and - // its resolver: moving those to another network while it - // runs needs the guest to do more than unplug it. - if c.status == Status::Running { - return Err(Error::Conflict(format!("Kiri cannot disconnect a running container from its first network ({}); stop the container first", net.name))); - } - let left = (c.ip.take(), c.ip6.take()); + let ip = c.ip.take(); + let ip6 = c.ip6.take(); + let n = c.first_if.take(); let nets = self.lock_networks(); c.spec.leave_first_network(|name| nets.find(name).is_some_and(|n| n.internal)); drop(nets); - drop(st); - // Not running, it holds no address; one left from a run that - // did not hand it back goes back to the pool all the same. - if let Some(ip) = left.0 { - self.release_ip(&net.name, ip); + if !c.spec.left_all_networks { + let promoted = c.spec.network_mode.clone(); + if let Some(i) = c.extra_ips.iter().position(|(x, _)| *x == promoted) { + c.ip = Some(c.extra_ips.remove(i).1); + } + if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == promoted) { + c.ip6 = Some(c.extra_ip6s.remove(i).1); + } + if let Some(i) = c.extra_ifs.iter().position(|(x, _)| *x == promoted) { + c.first_if = Some(c.extra_ifs.remove(i).1); + } } - if let Some(a) = left.1 { + let old_fw = c.forwards.take(); + let new_target = c.ip; + let running = c.status == Status::Running; + let rebind_ports = match &old_fw { + Some(fw) if running && new_target.is_some() && !c.spec.ports.is_empty() => rebind_bindings(&c.spec.ports, &fw.bound), + _ => Vec::new(), + }; + Detached::First { n, ip, ip6, old_fw, rebind_ports, new_target, running } + } else { + let Some(pos) = c.spec.extra_networks.iter().position(|x| x.name == net.name) else { + return Err(Error::NotFound(format!("container {} is not connected to network {}", &id[..12], net.name))); + }; + c.spec.extra_networks.remove(pos); + let ip = c.extra_ips.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ips.remove(i).1); + if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == net.name) { + let (_, a) = c.extra_ip6s.remove(i); self.lock_networks().release6(&net.name, a); } + let n = c.extra_ifs.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ifs.remove(i).1); + Detached::Extra { n, ip } + } + }; + match work { + Detached::Extra { n, ip } => { + self.save(); + if let Some(ip) = ip { + let unplugged = match (self.awake(), n) { + (Some(vm), Some(n)) => vm.net_detach(&id, n, &net.bridge, ip), + _ => Ok(()), + }; + // The network is gone from the container either way: its + // address goes back too, or the network can never be removed. + self.release_ip(&net.name, ip); + unplugged?; + } + } + Detached::First { n, ip, ip6, old_fw, rebind_ports, new_target, running } => { + // Closing listeners joins their threads: never under self.lock(). + drop(old_fw); + let unplugged = match (self.awake(), n, ip) { + (Some(vm), Some(n), Some(ip)) => vm.net_detach(&id, n, &net.bridge, ip), + _ => Ok(()), + }; + self.release_attached_ips(&net.name, ip, ip6); + if unplugged.is_ok() + && running + && !rebind_ports.is_empty() + && let (Some(vm), Some(target)) = (self.awake(), new_target) + { + match super::ports::start(vm.clone(), &id, &rebind_ports, target) { + Ok(fw) => { + let mut st = self.lock(); + if let Some(c) = st.containers.get_mut(&id).filter(|c| c.status == Status::Running && c.ip == Some(target) && !vm.is_disconnected()) { + c.forwards = Some(fw); + } else { + drop(st); + drop(fw); + } + } + Err(e) => crate::diag::warn!("published ports could not be moved after network disconnect", id = &id[..12], error = e), + } + } self.save(); self.emit_network("disconnect", &net, &id); + unplugged?; return Ok(()); } - let Some(pos) = c.spec.extra_networks.iter().position(|x| x.name == net.name) else { - return Err(Error::NotFound(format!("container {} is not connected to network {}", &id[..12], net.name))); - }; - c.spec.extra_networks.remove(pos); - let ip = c.extra_ips.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ips.remove(i).1); - if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == net.name) { - let (_, a) = c.extra_ip6s.remove(i); - self.lock_networks().release6(&net.name, a); - } - let n = c.extra_ifs.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ifs.remove(i).1); - (n, ip) - }; - self.save(); - if let Some(ip) = ip { - let unplugged = match (self.awake(), n) { - (Some(vm), Some(n)) => vm.net_detach(&id, n, &net.bridge, ip), - _ => Ok(()), - }; - // The network is gone from the container either way: its - // address goes back too, or the network can never be removed. - self.release_ip(&net.name, ip); - unplugged?; } self.emit_network("disconnect", &net, &id); Ok(()) @@ -8284,25 +8431,25 @@ mod leave_first_network_tests { done(engine, dir); } - /// With two others, the next first is the one Docker gives the default - /// route to: one that reaches outside before an internal one, then by - /// name, whatever the order they were connected in. The other stays an - /// extra network with its settings. + /// With two others, the next first is the first network in attachment order + /// that reaches outside (not `internal`), falling back to the first + /// attached internal network when none reaches outside. The others stay as + /// extra networks with their settings. #[test] - fn with_two_others_the_first_by_name_that_reaches_outside_takes_its_place() { - let (engine, id, dir) = engine("two", &[("zeta", false), ("alpha", true), ("beta", false)]); - connect(&engine, "zeta", &id, &["z"], "10.98.0.7"); + fn with_two_others_the_first_attached_that_reaches_outside_takes_its_place() { + let (engine, id, dir) = engine("two", &[("alpha", true), ("zeta", false), ("beta", false)]); connect(&engine, "alpha", &id, &["a"], ""); + connect(&engine, "zeta", &id, &["z"], "10.98.1.7"); connect(&engine, "beta", &id, &["b"], "10.98.2.9"); engine.disconnect("bridge", &id).unwrap(); let s = spec(&engine, &id); - assert_eq!(s.network_mode, "beta", "alpha is internal; beta comes before zeta"); - assert_eq!((s.aliases.as_slice(), s.ipv4_address.as_str()), (&["b".to_owned()][..], "10.98.2.9")); - assert_eq!(s.extra_networks.iter().map(|x| (x.name.as_str(), x.ipv4_address.as_str())).collect::>(), [("zeta", "10.98.0.7"), ("alpha", "")]); - // Leaving that one too: zeta reaches outside, alpha does not. - engine.disconnect("beta", &id).unwrap(); - assert_eq!(spec(&engine, &id).network_mode, "zeta"); + assert_eq!(s.network_mode, "zeta", "alpha is internal; zeta was attached before beta"); + assert_eq!((s.aliases.as_slice(), s.ipv4_address.as_str()), (&["z".to_owned()][..], "10.98.1.7")); + assert_eq!(s.extra_networks.iter().map(|x| (x.name.as_str(), x.ipv4_address.as_str())).collect::>(), [("alpha", ""), ("beta", "10.98.2.9")]); + // Leaving that one too: beta reaches outside, alpha does not. engine.disconnect("zeta", &id).unwrap(); + assert_eq!(spec(&engine, &id).network_mode, "beta"); + engine.disconnect("beta", &id).unwrap(); assert_eq!(spec(&engine, &id).network_mode, "alpha", "an internal network when it is the only one left"); done(engine, dir); } @@ -8392,22 +8539,130 @@ mod leave_first_network_tests { done(engine, dir); } - /// A running container is refused, with what to do instead, and - /// nothing changes: moving its default route, address and resolver to - /// another network while it runs is more than an unplug. + /// Disconnecting the first network on a running container removes it, + /// promotes the surviving secondary network's runtime attachment (`ip`, + /// `ip6`, `first_if`), and releases the left network's address. #[test] - fn a_running_container_must_be_stopped_first() { - let (engine, id, dir) = engine("running", &[("probe-net", false)]); - connect(&engine, "probe-net", &id, &[], ""); - engine.lock().containers.get_mut(&id).unwrap().status = Status::Running; - let r = engine.disconnect("bridge", &id); - assert!(matches!(&r, Err(Error::Conflict(m)) if m.contains("stop the container first")), "{r:?}"); - let s = spec(&engine, &id); - assert_eq!(s.network_mode, "bridge"); - assert_eq!(s.extra_networks.len(), 1); + fn running_disconnect_from_first_network_promotes_secondary() { + let (engine, id, dir) = engine("running-promote", &[("probe-net", false)]); + let bridge_ip = engine.lock_networks().allocate_avoiding("bridge", &[]).unwrap(); + let probe_ip = engine.lock_networks().reserve("probe-net", [10, 98, 0, 20]).map(|()| [10, 98, 0, 20]).unwrap(); + connect(&engine, "probe-net", &id, &["web"], ""); + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Running; + c.ip = Some(bridge_ip); + c.first_if = Some(0); + c.extra_ips.push(("probe-net".into(), probe_ip)); + c.extra_ifs.push(("probe-net".into(), 1)); + } + engine.disconnect("bridge", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "probe-net"); + assert_eq!(c.spec.aliases, ["web"]); + assert!(!c.spec.left_all_networks); + assert!(c.spec.extra_networks.is_empty()); + assert_eq!(c.ip, Some(probe_ip)); + assert_eq!(c.first_if, Some(1)); + assert!(c.extra_ips.is_empty()); + assert!(c.extra_ifs.is_empty()); + assert_eq!(super::free_eth(c, 0), 0, "eth0 was freed"); + assert_eq!(super::free_eth(c, 1), 2, "eth1 stays in use by probe-net"); + } + assert_eq!(engine.lock_networks().allocate_avoiding("bridge", &[]), Some(bridge_ip), "left IP returned to pool"); + engine.lock_networks().release("bridge", bridge_ip); + // Leaving the promoted last network leaves no network at all. + engine.disconnect("probe-net", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert!(c.spec.left_all_networks); + assert_eq!(c.spec.network_mode, "none"); + assert_eq!(c.ip, None); + assert_eq!(c.first_if, None); + assert_eq!(super::free_eth(c, 0), 0); + } + engine.lock_networks().reserve("probe-net", probe_ip).expect("promoted IP returned to pool"); + engine.lock_networks().release("probe-net", probe_ip); + done(engine, dir); + } + + /// With three external networks attached in order (`a` on eth0, `zeta` on + /// eth1, `beta` on eth2), disconnecting `a` promotes `zeta` (eth1, its IP + /// and gateway) rather than sorting `beta` ahead of `zeta`, matching + /// `kiri-init`'s `route_holders` and a subsequent `stop`/`start`. + #[test] + fn running_disconnect_with_three_networks_promotes_first_attached_ip_gateway_and_interface() { + let (engine, id, dir) = engine("three-promote", &[("a", false), ("zeta", false), ("beta", false)]); + let a_ip = [10, 98, 0, 10]; + let zeta_ip = [10, 98, 1, 20]; + let beta_ip = [10, 98, 2, 30]; + engine.lock_networks().reserve("a", a_ip).unwrap(); + engine.lock_networks().reserve("zeta", zeta_ip).unwrap(); + engine.lock_networks().reserve("beta", beta_ip).unwrap(); + connect(&engine, "a", &id, &["a-alias"], ""); + engine.disconnect("bridge", &id).unwrap(); + connect(&engine, "zeta", &id, &["z-alias"], ""); + connect(&engine, "beta", &id, &["b-alias"], ""); + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Running; + c.ip = Some(a_ip); + c.first_if = Some(0); + c.extra_ips = vec![("zeta".into(), zeta_ip), ("beta".into(), beta_ip)]; + c.extra_ifs = vec![("zeta".into(), 1), ("beta".into(), 2)]; + } + engine.disconnect("a", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "zeta"); + assert_eq!(c.spec.aliases, ["z-alias"]); + assert_eq!(c.ip, Some(zeta_ip)); + assert_eq!(c.first_if, Some(1), "eth1 matches kiri-init's promoted route holder"); + assert_eq!(c.spec.extra_networks.iter().map(|x| x.name.as_str()).collect::>(), ["beta"]); + assert_eq!(c.extra_ips, [("beta".to_owned(), beta_ip)]); + assert_eq!(c.extra_ifs, [("beta".to_owned(), 2)]); + } + assert_eq!(engine.lock_networks().find("zeta").unwrap().gateway, [10, 98, 1, 1]); + + engine.disconnect("zeta", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "beta"); + assert_eq!(c.spec.aliases, ["b-alias"]); + assert_eq!(c.ip, Some(beta_ip)); + assert_eq!(c.first_if, Some(2)); + assert!(c.spec.extra_networks.is_empty()); + assert!(c.extra_ips.is_empty()); + assert!(c.extra_ifs.is_empty()); + } + assert_eq!(engine.lock_networks().find("beta").unwrap().gateway, [10, 98, 2, 1]); done(engine, dir); } + #[test] + fn rebind_bindings_preserves_ephemeral_host_ports() { + let bindings = vec![ + super::super::ports::Binding { container_port: 80, proto: "tcp".into(), host_ip: String::new(), host_port: 0 }, + super::super::ports::Binding { container_port: 443, proto: "tcp".into(), host_ip: "127.0.0.1".into(), host_port: 8443 }, + ]; + let bound = vec![ + (bindings[0].clone(), "0.0.0.0".into(), 49152), + (bindings[0].clone(), "::".into(), 49152), + (bindings[1].clone(), "127.0.0.1".into(), 8443), + ]; + let rebound = super::rebind_bindings(&bindings, &bound); + assert_eq!(rebound.len(), 2); + assert_eq!(rebound[0].host_port, 49152); + assert_eq!(rebound[1].host_port, 8443); + } + /// Records saved before a container could leave all its networks load, /// as on a network. #[test] @@ -8486,6 +8741,7 @@ mod layer_gc_tests { start_owed: false, paused: false, extra_ips: Vec::new(), + first_if: None, extra_ifs: Vec::new(), ip6: None, extra_ip6s: Vec::new(), diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 6dfb6fcc2..6ad8c1e7c 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 +### #810 Networks: disconnect and reconnect a running container's first network cleanly at Layer 2/3, DNS, and port forwarding (unreleased) +- Fixes: #789 A running container can't leave its first network, so its network aliases can't be changed (follow-up to #418) +- Caused: none known +- Caused by: - +- Check: `leave-first-running-disconnect`, `leave-first-running-reconnect`, `leave-first-running-promote` + ### #410 Import: containers keep the files they wrote outside their volumes (unreleased) - Fixes: #410 Docker Desktop import drops each container's writable layer (data outside volumes is lost); docker diff fails with chroot error - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index a40bcfe89..32a8c3e6b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2035,10 +2035,20 @@ t leave-first-inspect "[probe-net ]" bash -c "echo \"[\$($D inspect -f '{{range t leave-first-default-route "default via" $D exec probe ip route t leave-first-dns "Name:" $D exec probe nslookup probe-peer t leave-first-no-eth1 "eth0 only" bash -c "$D exec probe ip -o link | grep -q eth1 && echo also-eth1 || echo eth0 only" -t leave-first-running-refused "stop the container first" bash -c "$D network connect bridge probe && $D network disconnect probe-net probe 2>&1" t leave-last-network "lo only" bash -c "$D rm -f probe >/dev/null; $D create --name probe alpine sleep 300 >/dev/null && $D network disconnect bridge probe && $D start probe >/dev/null && ($D exec probe ip -o link | grep -q eth0 && echo has-eth0 || echo lo only)" t leave-last-reconnect "Name:" bash -c "$D stop -t 0 probe >/dev/null && $D network connect probe-net probe && $D start probe >/dev/null && $D exec probe nslookup probe-peer" $D rm -f probe probe-peer >/dev/null; t leave-first-network-rm "removed" bash -c "$D network rm probe-net >/dev/null && echo removed" +# A running container can also leave its first network and join again with new +# aliases, disconnecting at Layer 2/3, dropping DNS, promoting any secondary +# default route, and updating published port targets (#789). +$D rm -f lfn-web lfn-p1 lfn-p2 >/dev/null 2>&1; $D network rm lfn1 lfn2 >/dev/null 2>&1 +$D network create lfn1 >/dev/null; $D network create lfn2 >/dev/null +$D run -d --name lfn-p1 --network lfn1 alpine sleep 300 >/dev/null +$D run -d --name lfn-p2 --network lfn2 alpine sleep 300 >/dev/null +t leave-first-running-disconnect "ok" bash -c "p1=\$($D inspect -f '{{.NetworkSettings.Networks.lfn1.IPAddress}}' lfn-p1); $D rm -f lfn-web >/dev/null 2>&1; [ -n \"\$p1\" ] && $D run -d --name lfn-web --network lfn1 --network-alias oldalias -p 18789:80 nginx:alpine >/dev/null && for _ in \$(seq 30); do curl -sf -m 1 http://localhost:18789 >/dev/null && break; sleep 0.2; done && $D network disconnect lfn1 lfn-web && [ \"\$($D inspect -f '{{json .NetworkSettings.Networks}}' lfn-web)\" = '{}' ] && ! ($D exec lfn-web ip -o link | grep -qE '^[0-9]+: eth[0-9]') && ! $D exec lfn-web ping -c 1 -W 1 \"\$p1\" >/dev/null 2>&1 && ! $D exec lfn-p1 nslookup lfn-web >/dev/null 2>&1 && ! $D exec lfn-p1 nslookup oldalias >/dev/null 2>&1 && ! curl -sf -m 2 http://localhost:18789 >/dev/null 2>&1 && echo ok; $D rm -f lfn-web >/dev/null 2>&1" +t leave-first-running-reconnect "ok" bash -c "p1=\$($D inspect -f '{{.NetworkSettings.Networks.lfn1.IPAddress}}' lfn-p1); $D rm -f lfn-web >/dev/null 2>&1; [ -n \"\$p1\" ] && $D run -d --name lfn-web --network lfn1 --network-alias oldalias -p 18789:80 nginx:alpine >/dev/null && for _ in \$(seq 30); do curl -sf -m 1 http://localhost:18789 >/dev/null && break; sleep 0.2; done && $D network disconnect lfn1 lfn-web && $D network connect --alias newalias lfn1 lfn-web && for _ in \$(seq 30); do curl -sf -m 1 http://localhost:18789 >/dev/null && break; sleep 0.2; done && $D exec lfn-web ping -c 1 -W 2 \"\$p1\" >/dev/null && $D exec lfn-p1 nslookup newalias >/dev/null && ! $D exec lfn-p1 nslookup oldalias >/dev/null 2>&1 && curl -sf -m 3 http://localhost:18789 | grep -q 'Welcome to nginx' && echo ok; $D rm -f lfn-web >/dev/null 2>&1" +t leave-first-running-promote "ok" bash -c "p1=\$($D inspect -f '{{.NetworkSettings.Networks.lfn1.IPAddress}}' lfn-p1); p2=\$($D inspect -f '{{.NetworkSettings.Networks.lfn2.IPAddress}}' lfn-p2); gw2=\$($D network inspect -f '{{(index .IPAM.Config 0).Gateway}}' lfn2); $D rm -f lfn-web >/dev/null 2>&1; [ -n \"\$p1\" ] && [ -n \"\$p2\" ] && [ -n \"\$gw2\" ] && $D run -d --name lfn-web --network lfn1 -p 18789:80 nginx:alpine >/dev/null && $D network connect lfn2 lfn-web && for _ in \$(seq 30); do curl -sf -m 1 http://localhost:18789 >/dev/null && break; sleep 0.2; done && $D network disconnect lfn1 lfn-web && for _ in \$(seq 30); do curl -sf -m 1 http://localhost:18789 >/dev/null && break; sleep 0.2; done && ! $D exec lfn-web ping -c 1 -W 1 \"\$p1\" >/dev/null 2>&1 && $D exec lfn-web ping -c 1 -W 2 \"\$p2\" >/dev/null && $D exec lfn-web ip -4 route show default | grep -q \"default via \$gw2 dev eth1\" && [ \"\$($D inspect -f '{{range \$k, \$v := .NetworkSettings.Networks}}{{\$k}} {{end}}' lfn-web)\" = 'lfn2 ' ] && curl -sf -m 3 http://localhost:18789 | grep -q 'Welcome to nginx' && echo ok; $D rm -f lfn-web >/dev/null 2>&1" +$D rm -f lfn-p1 lfn-p2 >/dev/null; $D network rm lfn1 lfn2 >/dev/null section "events, prune, system df, search" t events "start" bash -c "($D events --filter container=evt --format '{{.Action}}' & p=\$!; sleep 0.5; $D run --name evt alpine true >/dev/null; sleep 0.5; kill \$p) 2>/dev/null" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 2a292fd50..f215fd111 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -296,3 +296,6 @@ import-upper-imports #410 Docker Desktop import dropped each container's writabl import-upper-nothing-left #410 reading a container's writable layer must leave no container behind on the source import-upper-not-whole-etc #410 a directory changed only because a file was added to it must not bring all of its unchanged files import-upper-runs-with-files #410 an imported container started without the files it wrote outside its volumes +leave-first-running-disconnect #789 disconnecting a running container from its only network was refused (or left its veth, routes, and published ports active instead of isolating it) +leave-first-running-reconnect #789 reconnecting a running container after leaving its first network failed to restore veth connectivity, DNS aliases, or published ports +leave-first-running-promote #789 disconnecting a running container's first network when attached to a second network failed to isolate the left network, promote the default route, or rebind published ports From 723695a8ee524c4adfefbf7b11aca4598c5bc88d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:18:58 +0100 Subject: [PATCH 065/157] Windows: relay host.docker.internal via 192.168.65.254 to Windows loopback (#550) (#855) --- crates/kiri-init/src/linux/container.rs | 52 +- crates/kiri-init/src/linux/dns.rs | 38 +- crates/kiri-init/src/linux/net.rs | 98 ++- crates/kiri-init/src/linux/netlink.rs | 72 +- crates/kiri-win/src/engine.rs | 1 + crates/kiri-win/src/relay.rs | 200 ++++- crates/kiri-win/src/serve.rs | 23 +- crates/kiri/src/daemon/api.rs | 56 +- crates/kiri/src/daemon/builder.rs | 11 +- crates/kiri/src/daemon/engine.rs | 16 +- crates/kiri/src/hostrelay.rs | 933 +++++++++++++++++++++++- crates/kiri/src/k8s.rs | 6 +- docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + 14 files changed, 1388 insertions(+), 125 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index edf6c824f..4fecf139b 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1381,18 +1381,18 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; } } } - // On a Linux host there is no loopback redirect; host.docker.internal - // points at the bridge gateway, like Docker's host-gateway, so it reaches - // host services on 0.0.0.0 but not ones bound only to 127.0.0.1. - // A host-network container is on the host already, loopback included, - // so there the name is the loopback address. + // On a plain Linux host there is no loopback redirect; host.docker.internal + // points at the bridge gateway (or 127.0.0.1 for `--network host`). + // On Windows (WSL 2) when `kiri hostrelay` is active (`192.168.65.254` on + // `lo`), host.docker.internal / host.kiri.internal / host-gateway point at + // `192.168.65.254` for all networks (default bridge, user networks, and + // `--network host`), matching Docker Desktop. let host_addr = net::ip_str(net::HOST_ADDR); let host_net = spec.flags & run_flags::NET_HOST != 0; - let gateway = if host_net { "127.0.0.1".to_owned() } else { net::ip_str(spec.net.gateway) }; - let map_host = super::transport::is_host_process() && (host_net || spec.net.gateway != [0; 4]); + let mapped = host_etc_target(super::transport::is_host_process(), net::wsl_host_relay_active(), host_net, spec.net.gateway); for line in spec.net.extra_hosts.iter() { - if map_host { - hosts.push_str(&line.replace(&host_addr, &gateway)); + if let Some(target) = mapped.as_deref() { + hosts.push_str(&line.replace(&host_addr, target)); } else { hosts.push_str(line); } @@ -1409,6 +1409,25 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; Ok(out) } +/// Target IP replacing `net::HOST_ADDR` in container `/etc/hosts` lines. +/// Returns `None` in the macOS VM (keep `198.19.248.254`) and for `--network none` +/// on a plain Linux host. +fn host_etc_target(host_process: bool, wsl_relay_active: bool, host_net: bool, gateway: [u8; 4]) -> Option { + if !host_process { + return None; + } + if wsl_relay_active { + return Some(net::ip_str(net::WSL_HOST_ADDR)); + } + if host_net { + Some("127.0.0.1".to_owned()) + } else if gateway != [0; 4] { + Some(net::ip_str(gateway)) + } else { + None + } +} + /// The container's resolv.conf. On a user-defined network the embedded DNS /// at 127.0.0.11 is the only nameserver, as with Docker (it forwards to /// `--dns` servers); elsewhere `--dns` servers replace the VM's. @@ -4083,4 +4102,19 @@ mod tests { let _ = std::fs::remove_dir_all(&base); } + + #[test] + fn host_etc_target_maps_wsl_host_relay_across_all_network_modes() { + // macOS VM keeps 198.19.248.254 unchanged. + assert_eq!(super::host_etc_target(false, false, false, [172, 17, 0, 1]), None); + assert_eq!(super::host_etc_target(false, true, true, [0; 4]), None); + // Plain Linux host uses bridge gateway or 127.0.0.1 for --network host. + assert_eq!(super::host_etc_target(true, false, false, [172, 17, 0, 1]).as_deref(), Some("172.17.0.1")); + assert_eq!(super::host_etc_target(true, false, true, [0; 4]).as_deref(), Some("127.0.0.1")); + assert_eq!(super::host_etc_target(true, false, false, [0; 4]), None); + // WSL 2 with active Windows host relay resolves to 192.168.65.254 everywhere. + assert_eq!(super::host_etc_target(true, true, false, [172, 17, 0, 1]).as_deref(), Some("192.168.65.254")); + assert_eq!(super::host_etc_target(true, true, false, [172, 18, 0, 1]).as_deref(), Some("192.168.65.254")); + assert_eq!(super::host_etc_target(true, true, true, [0; 4]).as_deref(), Some("192.168.65.254")); + } } diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index 385a94489..ef2ee50e0 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -484,8 +484,16 @@ impl Dns { /// Answers a query for a name on this network, or None to forward it. fn answer(&self, server: usize, q: &[u8]) -> Option> { + self.answer_with_host_fn(server, q, super::net::effective_host_addr) + } + + #[cfg(test)] + fn answer_with_host(&self, server: usize, q: &[u8], host_ip: [u8; 4]) -> Option> { + self.answer_with_host_fn(server, q, || host_ip) + } + + fn answer_with_host_fn(&self, server: usize, q: &[u8], host_ip: impl FnOnce() -> [u8; 4]) -> Option> { let (name, qtype, end) = parse_question(q)?; - let host = vec![super::net::HOST_ADDR]; // Of the server's networks that have the name, the first by Docker // network name answers, as with Docker: not the first joined. A // name Compose gives a service on every network it joins then @@ -514,20 +522,25 @@ impl Dns { let addrs = bridge.and_then(|b| self.names.get(b)).and_then(|t| t.get(lookup)); let addrs6 = bridge.and_then(|b| self.names6.get(b)).and_then(|t| t.get(lookup)); // The host's names answer A with the host's address, and AAAA with - // no records: the host relay is IPv4 only. - let addrs = match addrs { - None if is_host => Some(&host), - a => a, + // no records: the host relay is IPv4 only. Resolve the host IP lazily + // so non-host DNS queries never touch the filesystem or procfs. + let host: [u8; 4]; + let a_addrs: Option<&[[u8; 4]]> = match addrs { + None if is_host => { + host = host_ip(); + Some(std::slice::from_ref(&host)) + } + a => a.map(Vec::as_slice), }; // A container name with no address of the asked type is NODATA, not // forwarded: the name is this network's. - if addrs.is_none() && addrs6.is_none() { + if a_addrs.is_none() && addrs6.is_none() { return None; } // A service name has no records of its own: the container it // belongs to has the addresses, and the caller looks those up by // the container's name. - let a: &[[u8; 4]] = if service.is_none() && (qtype == 1 || qtype == 255) { addrs.map_or(&[], Vec::as_slice) } else { &[] }; + let a: &[[u8; 4]] = if service.is_none() && (qtype == 1 || qtype == 255) { a_addrs.unwrap_or(&[]) } else { &[] }; let aaaa: &[([u8; 4], [u8; 16])] = if service.is_none() && (qtype == 28 || qtype == 255) { addrs6.map_or(&[], Vec::as_slice) } else { &[] }; let mut r = Vec::with_capacity(end + 16 * a.len() + 28 * aaaa.len()); r.extend_from_slice(&q[0..2]); // id @@ -1051,6 +1064,17 @@ mod tests { assert_eq!((r[3] & 0x0f, answers(&r, q6.len()).len()), (0, 0)); let q = query("gateway.docker.internal", 255); assert_eq!(answers(&dns.answer(0, &q).unwrap(), q.len()), [(1, super::super::net::HOST_ADDR.to_vec())]); + // Non-host queries must not invoke the host IP lookup callback at all. + assert!(dns.answer_with_host_fn(0, other, || panic!("host IP lookup called for non-host query")).is_none()); + // On WSL 2 with Windows host relay active, all host names answer 192.168.65.254 (A) and NODATA (AAAA). + let wsl = super::super::net::WSL_HOST_ADDR; + for name in ["host.docker.internal", "host.kiri.internal", "gateway.docker.internal"] { + let qa = query(name, 1); + assert_eq!(answers(&dns.answer_with_host(0, &qa, wsl).unwrap(), qa.len()), [(1, wsl.to_vec())], "{name} A"); + let qaaaa = query(name, 28); + let r = dns.answer_with_host(0, &qaaaa, wsl).unwrap(); + assert_eq!((r[3] & 0x0f, answers(&r, qaaaa.len()).len()), (0, 0), "{name} AAAA NODATA"); + } } #[test] diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 3d3c0932a..bbf35c10c 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -11,11 +11,79 @@ use super::netlink::{self, Netlink}; use super::sys; pub const UPLINK: &str = "eth0"; -/// What `host.docker.internal` resolves to inside containers. Connections to -/// it are redirected to the agent and relayed to the Mac's localhost. +/// What `host.docker.internal` resolves to inside containers in the VM. +/// Connections to it are redirected to the agent and relayed to the Mac's localhost. pub const HOST_ADDR: [u8; 4] = [198, 19, 248, 254]; +/// What `host.docker.internal`, `host.kiri.internal`, and `host-gateway` +/// resolve to on Windows (WSL 2) when `kiri hostrelay` is active, matching +/// Docker Desktop. +pub const WSL_HOST_ADDR: [u8; 4] = [192, 168, 65, 254]; /// Where the redirect lands: the agent's listener for host-bound connections. pub const HOST_RELAY_PORT: u16 = 1026; + +/// True when running under Microsoft's WSL 2 kernel. +pub fn is_wsl() -> bool { + static WSL: std::sync::OnceLock = std::sync::OnceLock::new(); + *WSL.get_or_init(|| { + std::fs::read_to_string("/proc/sys/kernel/osrelease") + .is_ok_and(|r| r.to_ascii_lowercase().contains("microsoft")) + }) +} + +const HOST_RELAY_PID_FILE: &str = "/run/kiri-hostrelay.pid"; + +/// Checks whether a Linux `/proc//cmdline` (NUL-separated argv) belongs +/// to `kiri hostrelay` (empty cmdline also excludes unreaped zombies). +fn is_hostrelay_cmdline(cmdline: &[u8]) -> bool { + let mut args = cmdline.split(|&b| b == 0); + let Some(argv0) = args.next() else { return false }; + let Some(argv1) = args.next() else { return false }; + !argv0.is_empty() && argv1 == b"hostrelay" +} + +fn read_pid_file(path: &std::path::Path) -> Option { + std::fs::read_to_string(path).ok()?.trim().parse::().ok().filter(|&p| p > 0) +} + +fn pid_is_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + if pid <= 0 { + return false; + } + // SAFETY: signal 0 checks process existence without sending a signal. + if unsafe { libc::kill(pid, 0) } == 0 { + return true; + } + io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) +} + +fn pid_file_alive(path: &std::path::Path, verify: impl FnOnce(u32) -> bool) -> bool { + read_pid_file(path).is_some_and(|pid| pid_is_alive(pid) && verify(pid)) +} + +fn hostrelay_pid_matches(pid: u32) -> bool { + std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| is_hostrelay_cmdline(&c)) +} + +/// True when running on WSL 2 with a live `kiri hostrelay` process owning +/// `192.168.65.254` (verified via `/run/kiri-hostrelay.pid`, `kill(pid, 0)`, +/// and `/proc//cmdline`, catching unclean exits without `getifaddrs()`). +pub fn wsl_host_relay_active() -> bool { + is_wsl() && pid_file_alive(std::path::Path::new(HOST_RELAY_PID_FILE), hostrelay_pid_matches) +} + +/// Address answered for `host.docker.internal` / `host.kiri.internal` / +/// `gateway.docker.internal` in the embedded DNS: `192.168.65.254` on WSL 2 +/// when the Windows host relay is active, else `HOST_ADDR`. +pub fn effective_host_addr() -> [u8; 4] { + effective_host_addr_for(super::transport::is_host_process(), wsl_host_relay_active()) +} + +pub fn effective_host_addr_for(host_process: bool, wsl_relay_active: bool) -> [u8; 4] { + if host_process && wsl_relay_active { WSL_HOST_ADDR } else { HOST_ADDR } +} /// Where outbound container TCP connections to VPN tunnel prefixes or under /// host egress land, to be relayed over vsock to the host dialer. pub const EGRESS_RELAY_PORT: u16 = 1038; @@ -340,8 +408,9 @@ fn install_nat(nat: Nat) -> io::Result<()> { let egress = EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clone(); let skip = if egress.is_empty() { Vec::new() } else { egress_skip_subnets() }; let any_addr = nat.dnat.iter().any(|d| d.host_ip == [0; 4]); + let wsl_host = (!nat.redirect && is_wsl()).then_some(WSL_HOST_ADDR); let install = |local: Option<&[[u8; 4]]>| { - netlink::install_nat_with_egress( + netlink::install_nat_full( nat.uplink, HOST_ADDR, HOST_RELAY_PORT, @@ -353,6 +422,7 @@ fn install_nat(nat: Nat) -> io::Result<()> { EGRESS_RELAY_PORT, &egress, &skip, + wsl_host, ) }; let r = if any_addr && NO_FIB4.load(Ordering::Relaxed) { @@ -453,7 +523,9 @@ fn local_addrs() -> Vec<[u8; 4]> { if !ifa.ifa_addr.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET { // SAFETY: an AF_INET address is a sockaddr_in. let a = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); - if a[0] != 127 && !out.contains(&a) { + // Exclude loopback and (on WSL 2) the Windows host-gateway address so + // published-port DNAT fallback rules never hijack host.docker.internal. + if a[0] != 127 && (!is_wsl() || a != WSL_HOST_ADDR) && !out.contains(&a) { out.push(a); } } @@ -1238,4 +1310,22 @@ fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 000000 assert!(!dhcp.apply_static_with([192, 168, 64, 9], 24, [192, 168, 64, 1], [0; 4], |_| panic!("must not reconfigure")).unwrap()); assert_eq!(dhcp.lease.as_ref().unwrap().ip, [192, 168, 64, 2]); } + + #[test] + fn effective_host_addr_uses_wsl_host_addr_only_when_wsl_relay_active() { + assert_eq!(effective_host_addr_for(false, false), HOST_ADDR); + assert_eq!(effective_host_addr_for(false, true), HOST_ADDR); + assert_eq!(effective_host_addr_for(true, false), HOST_ADDR); + assert_eq!(effective_host_addr_for(true, true), WSL_HOST_ADDR); + assert!(is_hostrelay_cmdline(b"/usr/local/bin/kiri\0hostrelay\0")); + assert!(!is_hostrelay_cmdline(b"/usr/local/bin/kiri\0daemon\0")); + assert!(!is_hostrelay_cmdline(b"")); + let pid_path = std::env::temp_dir().join(format!("kiri-net-hostrelay-{}.pid", std::process::id())); + let _ = std::fs::remove_file(&pid_path); + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, format!("{}\n", std::process::id())).unwrap(); + assert!(pid_file_alive(&pid_path, |_| true)); + assert!(!pid_file_alive(&pid_path, |_| false)); + let _ = std::fs::remove_file(&pid_path); + } } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 2af717914..7468d421f 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -605,20 +605,20 @@ pub struct Dnat { pub to_port: u16, } -/// `[ip daddr | fib daddr type local ip daddr != 127.0.0.0/8] +/// `[ip daddr | fib daddr type local [ip daddr != ] ip daddr != 127.0.0.0/8] /// dport dnat to :`. -fn dnat_rule(chain: &str, d: &Dnat) -> Msg { - dnat_rule_from(chain, d, None) +fn dnat_rule(chain: &str, d: &Dnat, exclude_ip: Option<[u8; 4]>) -> Msg { + dnat_rule_from(chain, d, None, exclude_ip) } /// `dnat_rule`, matching only packets that arrive on interface `from.0` /// from address `from.1` (`iif ip saddr ...`). -fn dnat_rule_from(chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>) -> Msg { - dnat_rule_in("kiri", chain, d, from) +fn dnat_rule_from(chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>, exclude_ip: Option<[u8; 4]>) -> Msg { + dnat_rule_in("kiri", chain, d, from, exclude_ip) } /// `dnat_rule_from` in table `table`. -fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>) -> Msg { +fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>, exclude_ip: Option<[u8; 4]>) -> Msg { let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, table).attr_str(2, chain); rule.nest(4); @@ -634,10 +634,14 @@ fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])> // fib daddr type => reg 1 (NFTA_FIB_DREG, RESULT = ADDRTYPE 3, FLAGS = DADDR 2); cmp eq RTN_LOCAL rule.nest(1).attr_str(1, "fib").nest(2).attr_be32(1, 1).attr_be32(2, 3).attr_be32(3, 2).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &2u32.to_ne_bytes()).end().end().end(); - // payload daddr => reg 1; reg 1 &= 255.0.0.0; cmp neq 127.0.0.0. Without - // it a packet for 127.0.0.1 is rewritten before routing: one arriving - // from the LAN would reach the container instead of being dropped. + // payload daddr => reg 1; optional cmp neq exclude_ip (WSL host-gateway + // 192.168.65.254 on `lo`); then reg 1 &= 255.0.0.0; cmp neq 127.0.0.0. + // Without the loopback guard a packet for 127.0.0.1 is rewritten before + // routing: one arriving from the LAN would reach the container instead of being dropped. rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + if let Some(skip) = exclude_ip { + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &skip).end().end().end(); + } rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); rule.nest(4).attr(1, &[255, 0, 0, 0]).end().nest(5).attr(1, &[0; 4]).end().end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &[127, 0, 0, 0]).end().end().end(); @@ -938,10 +942,10 @@ fn host_relay_guard_in(family: u8, port: u16) -> Msg { /// A published port's DNAT rules: one, or with `local` (a kernel without /// nft_fib_ipv4, so no `fib daddr type local`) one per address of this /// machine for a port published on every address. -fn dnat_rules(chain: &str, d: &Dnat, local: Option<&[[u8; 4]]>) -> Vec { +fn dnat_rules(chain: &str, d: &Dnat, local: Option<&[[u8; 4]]>, exclude_ip: Option<[u8; 4]>) -> Vec { match local { - Some(addrs) if d.host_ip == [0; 4] => addrs.iter().map(|a| dnat_rule(chain, &Dnat { host_ip: *a, ..*d })).collect(), - _ => vec![dnat_rule(chain, d)], + Some(addrs) if d.host_ip == [0; 4] => addrs.iter().map(|a| dnat_rule(chain, &Dnat { host_ip: *a, ..*d }, None)).collect(), + _ => vec![dnat_rule(chain, d, exclude_ip)], } } @@ -1072,7 +1076,7 @@ fn embedded_dns_batch(addr: [u8; 4], port: u16) -> Vec { // that took 15-30 ms of every container start. let mut flush = nft(NFT_MSG_DELRULE, NLM_F_ACK); flush.attr_str(1, EMBEDDED_DNS_TABLE).attr_str(2, "output"); - let rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: port }, None); + let rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: port }, None, None); let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); vec![begin, table, chain, flush, rule, end] @@ -1218,6 +1222,7 @@ pub fn remove_nat() -> io::Result<()> { /// Mac reaches over the NAT network, so they match only connections from /// the uplink's gateway `gateway` (the Mac itself): other VMs on the NAT /// network, or the LAN routed through the Mac, never reach a container. +#[cfg(test)] #[allow(clippy::too_many_arguments)] pub fn install_nat_with_egress( uplink_index: i32, @@ -1231,6 +1236,24 @@ pub fn install_nat_with_egress( egress_port: u16, egress_routes: &[([u8; 4], u8)], egress_skip: &[([u8; 4], u8)], +) -> io::Result<()> { + install_nat_full(uplink_index, host_addr, host_port, redirect, dnat, gateway, bridges, local, egress_port, egress_routes, egress_skip, None) +} + +#[allow(clippy::too_many_arguments)] +pub fn install_nat_full( + uplink_index: i32, + host_addr: [u8; 4], + host_port: u16, + redirect: bool, + dnat: &[Dnat], + gateway: [u8; 4], + bridges: &[String], + local: Option<&[[u8; 4]]>, + egress_port: u16, + egress_routes: &[([u8; 4], u8)], + egress_skip: &[([u8; 4], u8)], + wsl_host: Option<[u8; 4]>, ) -> io::Result<()> { let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; // The table is replaced, not appended to (on a Linux host it outlives @@ -1275,9 +1298,14 @@ pub fn install_nat_with_egress( } msgs.push(nat_chain("prerouting", 0, -100)); msgs.push(nat_chain("output", 3, -100)); + if let Some(wsl_addr) = wsl_host { + // UDP 53 sent to 192.168.65.254 from container bridges goes to + // the embedded DNS on the receiving bridge's gateway. + msgs.push(dns_redirect_rule(wsl_addr)); + } for d in dnat { - msgs.extend(dnat_rules("prerouting", d, local)); - msgs.extend(dnat_rules("output", d, local)); + msgs.extend(dnat_rules("prerouting", d, local, wsl_host)); + msgs.extend(dnat_rules("output", d, local, wsl_host)); } if have_egress { for &(subnet, prefix) in egress_skip { @@ -1314,7 +1342,7 @@ pub fn install_nat_with_egress( msgs.push(loopback_published_rule(d.host_port, host_port)); } } else { - msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)))); + msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)), None)); } } if have_egress { @@ -1643,4 +1671,16 @@ mod tests { assert_eq!(verdict(&r), libc::NF_DROP as u32); } } + + #[test] + fn published_dnat_excludes_wsl_host_gateway_when_set() { + let d = Dnat { udp: false, host_ip: [0; 4], host_port: 8080, to_ip: [172, 17, 0, 2], to_port: 80 }; + let plain = dnat_rule("prerouting", &d, None); + let wsl = dnat_rule("prerouting", &d, Some([192, 168, 65, 254])); + assert_eq!(names(&plain), ["fib", "cmp", "payload", "bitwise", "cmp", "meta", "cmp", "payload", "cmp", "immediate", "immediate", "nat"]); + assert_eq!(names(&wsl), ["fib", "cmp", "payload", "cmp", "bitwise", "cmp", "meta", "cmp", "payload", "cmp", "immediate", "immediate", "nat"]); + let e = exprs(&wsl); + assert_eq!(be32(get(&e[3].1, 2)), 1, "cmp neq"); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &[192, 168, 65, 254]); + } } diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 108dcf648..9ccbf5e92 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -343,6 +343,7 @@ pub(crate) fn ensure_daemon() -> io::Result<()> { if !client::alive() { start_daemon()?; } + crate::relay::ensure_started(); std::thread::spawn(crate::update::catch_up_engine); crate::wslconfig::sync_wsl_integration_soon(); Ok(()) diff --git a/crates/kiri-win/src/relay.rs b/crates/kiri-win/src/relay.rs index 5c0deeefe..522a2bf6c 100644 --- a/crates/kiri-win/src/relay.rs +++ b/crates/kiri-win/src/relay.rs @@ -1,21 +1,56 @@ -//! Windows' end of the proxy relay (crates/kiri/src/hostrelay.rs): a proxy -//! on Windows' own 127.0.0.1, as most Windows proxy apps set, can't be -//! reached from WSL, so `kiri hostrelay` in the distro listens for it and -//! sends each connection here over wsl.exe's stdio, and this dials the proxy. +//! Windows' end of the host and proxy relay (crates/kiri/src/hostrelay.rs): +//! services and proxies on Windows' own loopback (`127.0.0.1` / `[::1]`) +//! can't be reached directly from WSL 2, so `kiri hostrelay` in the distro +//! listens for static proxy ports on `127.0.0.1` and for `host.docker.internal` +//! / `host.kiri.internal` on `192.168.65.254` (via nftables DNAT + +//! `SO_ORIGINAL_DST`), sends each connection here over wsl.exe's stdio, and +//! this dials Windows' loopback (`127.0.0.1`, then `[::1]` on refusal). use std::collections::{HashMap, HashSet}; +use std::io::{self, Write}; use std::os::windows::process::CommandExt; -use std::process::Stdio; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::process::{ChildStdin, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::{Duration, Instant}; use crate::hostrelay::{self, Out}; +/// Minimum interval between automatic background restart attempts after the +/// relay exits or fails to start. +const RETRY_WAIT: Duration = Duration::from_secs(2); + +/// Stdin handle to `wsl.exe` that can be closed on demand (`renew`) so the +/// WSL-side `kiri hostrelay` sees EOF and tears down cleanly. +struct CloseableStdin(Option); + +impl Write for CloseableStdin { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self.0.as_mut() { + Some(w) => w.write(buf), + None => Err(io::Error::new(io::ErrorKind::BrokenPipe, "relay closed")), + } + } + + fn flush(&mut self) -> io::Result<()> { + match self.0.as_mut() { + Some(w) => w.flush(), + None => Ok(()), + } + } +} + struct Relay { out: Out, + stdin: Arc>, distro: Option, - /// Windows ports it was asked to listen for: the only ones dialled. + kiri: String, + /// Dynamic host-gateway forwarding (`host.docker.internal` -> any non-zero + /// Windows loopback port). + host_enabled: AtomicBool, + /// Catch-all relay port reported by WSL (`LISTENING_HOST`), or 0. + host_port: AtomicU16, + /// Static proxy ports requested via `LISTEN`. allowed: Mutex>, /// Windows port → the distro's port; 0 when it couldn't listen. ports: Mutex>, @@ -23,7 +58,17 @@ struct Relay { dead: AtomicBool, } +impl Relay { + fn close(&self) { + self.dead.store(true, Ordering::SeqCst); + let _ = lock(&self.stdin).0.take(); + self.changed.notify_all(); + } +} + static RELAY: Mutex>> = Mutex::new(None); +/// Last automatic start attempt, to throttle retries if WSL is unavailable. +static LAST_START: Mutex> = Mutex::new(None); /// The last failure logged, so a minute's retry doesn't repeat it. static LAST_ERROR: Mutex = Mutex::new(String::new()); @@ -39,73 +84,160 @@ fn log_once(msg: String) { } } -fn start(distro: Option) -> std::io::Result> { +fn current_distro_and_kiri() -> Option<(String, String)> { + if crate::storage::moving() || crate::storage::unavailable().is_some() { + return None; + } + // The bridge's distro, the engine's, or during setup the one setup just made. + // None before setup has made one: WSL's default distro may be anything. + let distro = crate::serve::distro().or_else(crate::engine::distro).or_else(crate::setup::distro)?; + Some((distro, crate::serve::kiri())) +} + +fn start(distro: Option, kiri: String) -> io::Result> { let mut cmd = crate::win::tool("wsl.exe"); if let Some(d) = &distro { cmd.args(["-d", d]); } let mut child = cmd - .args(["-u", "root", "--", "/usr/local/bin/kiri", "hostrelay"]) + .args(["-u", "root", "--", &kiri, "hostrelay"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .creation_flags(0x0800_0000) .spawn()?; - let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { return Err(std::io::Error::other("wsl.exe has no stdio")) }; + let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { + return Err(io::Error::other("wsl.exe has no stdio")); + }; + let stdin = Arc::new(Mutex::new(CloseableStdin(Some(input)))); + let out: Out = stdin.clone(); let relay = Arc::new(Relay { - out: Arc::new(Mutex::new(input)), + out, + stdin, distro, + kiri, + host_enabled: AtomicBool::new(true), + host_port: AtomicU16::new(0), allowed: Mutex::new(HashSet::new()), ports: Mutex::new(HashMap::new()), changed: Condvar::new(), dead: AtomicBool::new(false), }); + // Ask WSL immediately to bind 192.168.65.254 and install its nftables DNAT. + // An older `kiri hostrelay` ignores unknown frame kinds cleanly. + let _ = hostrelay::send(&relay.out, hostrelay::LISTEN_HOST, 0, &[]); let r = relay.clone(); std::thread::spawn(move || { - let (a, p) = (r.clone(), r.clone()); - let end = hostrelay::dial_side( + let (a, p, h) = (r.clone(), r.clone(), r.clone()); + let end = hostrelay::dial_side_with_host( output, &r.out, - move |port| lock(&a.allowed).contains(&port), + move |port| port != 0 && (a.host_enabled.load(Ordering::SeqCst) || lock(&a.allowed).contains(&port)), move |target, local| { lock(&p.ports).insert(target, local); p.changed.notify_all(); }, + move |local| { + h.host_port.store(local, Ordering::SeqCst); + h.changed.notify_all(); + if local != 0 { + log_once(format!( + "host relay: {} -> Windows loopback (WSL port {local})", + hostrelay::WSL_HOST_ADDR_STR + )); + } else { + log_once(format!( + "host relay: WSL could not bind {}", + hostrelay::WSL_HOST_ADDR_STR + )); + } + }, ); r.dead.store(true, Ordering::SeqCst); r.changed.notify_all(); let status = child.wait(); - log_once(format!("proxy relay ended: {end:?}, {status:?}")); + log_once(format!("host relay ended: {end:?}, {status:?}")); }); Ok(relay) } -/// For each Windows loopback port, the distro's port that leads to it, -/// starting the relay when it isn't running. Empty when it can't run (an -/// engine from before the relay), and the proxy is used as set. -pub fn ports(targets: &[u16]) -> HashMap { - if targets.is_empty() { - return HashMap::new(); - } - // The engine's distro, or during setup the one setup just made, as the bridge finds it. - // None before setup has made one: WSL's default distro may be anything. - let Some(distro) = crate::engine::distro().or_else(crate::setup::distro) else { return HashMap::new() }; +fn ensure_relay(distro: String, kiri: String) -> Option> { let distro = Some(distro); - let relay = { - let mut slot = lock(&RELAY); - match slot.as_ref() { - Some(r) if !r.dead.load(Ordering::SeqCst) && r.distro == distro => r.clone(), - _ => match start(distro) { + let mut slot = lock(&RELAY); + match slot.as_ref() { + Some(r) if !r.dead.load(Ordering::SeqCst) && r.distro == distro && r.kiri == kiri => Some(r.clone()), + old => { + if let Some(old) = old { + old.close(); + } + match start(distro, kiri) { Ok(r) => { *slot = Some(r.clone()); - r + Some(r) } Err(e) => { - log_once(format!("proxy relay: {e}")); - return HashMap::new(); + log_once(format!("host relay: {e}")); + None } - }, + } + } + } +} + +/// Ensures the WSL host relay is running in the background so CLI-only users +/// (serving `\\.\pipe\kiri` or `\\.\pipe\docker_engine` without opening the +/// window) get `host.docker.internal` automatically. Non-blocking and throttled +/// when a recent attempt just failed. +pub fn ensure_started() { + let Some((distro, kiri)) = current_distro_and_kiri() else { + return; + }; + { + let slot = lock(&RELAY); + if slot.as_ref().is_some_and(|r| !r.dead.load(Ordering::SeqCst) && r.distro.as_deref() == Some(distro.as_str()) && r.kiri == kiri) { + return; + } + } + { + let mut last = lock(&LAST_START); + if last.is_some_and(|t| t.elapsed() < RETRY_WAIT) { + return; + } + *last = Some(Instant::now()); + } + let _ = std::thread::Builder::new().name("kiri-hostrelay-start".into()).spawn(move || { + let _ = ensure_relay(distro, kiri); + }); +} + +/// Replaces the running host relay (e.g. after setup picks a distro or an +/// engine update replaces `/usr/local/bin/kiri` in WSL). +pub fn renew() { + let old = lock(&RELAY).take(); + *lock(&LAST_START) = None; + let _ = std::thread::Builder::new().name("kiri-hostrelay-renew".into()).spawn(move || { + if let Some(old) = old { + old.close(); + } + if let Some((distro, kiri)) = current_distro_and_kiri() { + let _ = ensure_relay(distro, kiri); } + }); +} + +/// For each Windows loopback proxy port, the distro's port that leads to it, +/// starting the relay when it isn't running. Also ensures the `host.docker.internal` +/// catch-all relay is active even when no proxy ports are configured. +pub fn ports(targets: &[u16]) -> HashMap { + if targets.is_empty() { + ensure_started(); + return HashMap::new(); + } + let Some((distro, kiri)) = current_distro_and_kiri() else { + return HashMap::new(); + }; + let Some(relay) = ensure_relay(distro, kiri) else { + return HashMap::new(); }; for &t in targets { if lock(&relay.allowed).insert(t) { diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index cfdc000f7..3e0ca7855 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -161,6 +161,18 @@ pub fn docker_engine_endpoint() -> crate::dockerctx::Endpoint { other_engine().map(|o| crate::dockerctx::Endpoint::Taken(o.to_owned())).unwrap_or(crate::dockerctx::Endpoint::Free) } +/// The WSL distro the pipe bridge targets, once `serve::start` has run. +pub fn distro() -> Option { + HUB.get().and_then(|hub| hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).distro.clone()) +} + +/// The `kiri` binary path inside WSL configured for the pipe bridge. +pub fn kiri() -> String { + HUB.get() + .map(|hub| hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).kiri.clone()) + .unwrap_or_else(|| "/usr/local/bin/kiri".to_owned()) +} + /// Carries connections to `distro` from now on (setup has just made it); /// the bridge to the old one is left to end. pub fn set_distro(distro: &str) { @@ -168,6 +180,7 @@ pub fn set_distro(distro: &str) { hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).distro = Some(distro.to_owned()); hub.retire(); } + crate::relay::renew(); } /// The engine in WSL was replaced by this version's: connections from now @@ -180,6 +193,7 @@ pub fn renew_bridge() { { log("bridge: the engine in WSL was replaced; new connections get a bridge from the new one"); } + crate::relay::renew(); } /// Serves the pipe on threads of its own. Fails if another kiri-win @@ -192,7 +206,9 @@ pub fn start(cfg: Config) -> io::Result<()> { let _ = HUB.set(hub.clone()); let h = hub.clone(); thread::Builder::new().name("kiri-docker-engine".into()).spawn(move || docker_engine(&h))?; - // Start WSL now, so the first docker command does not wait for it. + // Start WSL and the Windows host relay now, so the first docker command + // gets both the daemon and host.docker.internal without waiting for the UI. + crate::relay::ensure_started(); let h = hub.clone(); thread::spawn(move || { if let Err(e) = h.bridge() { @@ -258,6 +274,7 @@ fn docker_engine(hub: &Arc) { }; set_docker_engine_owner(crate::dockerctx::Endpoint::Kiri); say(format!("serving {DOCKER_ENGINE} as well (no other engine has it)")); + crate::relay::ensure_started(); let (h, mut new) = (hub.clone(), NewEngines::default()); serve_while_free( DOCKER_ENGINE, @@ -1491,6 +1508,7 @@ impl Bridge { .spawn()?; let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { return Err(io::Error::other("wsl.exe has no stdio")) }; log("bridge started"); + crate::relay::ensure_started(); Ok(Bridge::over(Box::new(input), output, Box::new(Wsl(child)))) } @@ -1718,6 +1736,9 @@ fn serve_shared(hub: &Hub, pipe: Arc) { } return; } + if HUB.get().is_some() { + crate::relay::ensure_started(); + } // A bridge can die between hub.bridge() and the insert below: while WSL // is still booting, wsl.exe exits at once. `replies` ends every // connection it finds when that happens, but one registered after that diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 5964b9638..f1ff7e6ab 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -1669,12 +1669,39 @@ fn fresh_bind_sources_with(guest: &[String], info: &[Value], engine_socket: impl .collect() } +/// Parses `--add-host name:ip` entries into `/etc/hosts` lines (`ip\tname`). +/// `host-gateway` is always stored as `HOST_ADDR` (never baking `192.168.65.254` +/// into the saved container spec) so `kiri-init`'s `host_etc_target` maps it +/// dynamically at container start time based on whether the WSL host relay is +/// live, falling back to the bridge gateway if the relay isn't running later. +fn extra_hosts_from(raw: &[String]) -> Result, Error> { + let mut extra_hosts = Vec::with_capacity(raw.len()); + for h in raw { + let Some((name, ip)) = h.split_once(':') else { continue }; + let ip = if ip == "host-gateway" { super::ports::HOST_ADDR } else { ip }; + if ip.parse::().is_err() { + return Err(Error::BadRequest(format!("invalid IP address: {ip}"))); + } + if !valid_hosts_name(name) { + return Err(Error::BadRequest(format!("invalid host name ({name})"))); + } + extra_hosts.push(format!("{ip}\t{name}")); + } + Ok(extra_hosts) +} + /// An NFS or CIFS server name as an address the guest kernel can use. -/// `host.docker.internal` is the Mac, as it is for containers. +/// `host.docker.internal` is the Mac (or the Windows host under WSL 2), +/// as it is for containers. fn resolve_server(host: &str) -> Option { use std::net::ToSocketAddrs; - if cfg!(target_os = "macos") && matches!(host, "host.docker.internal" | "host.kiri.internal") { - return Some(super::ports::HOST_ADDR.to_owned()); + if matches!(host, "host.docker.internal" | "host.kiri.internal") { + if cfg!(target_os = "macos") { + return Some(super::ports::HOST_ADDR.to_owned()); + } + if crate::hostrelay::wsl_host_active() { + return Some(crate::hostrelay::WSL_HOST_ADDR_STR.to_owned()); + } } let addrs: Vec = (host, 0).to_socket_addrs().ok()?.collect(); addrs.iter().find(|a| a.is_ipv4()).or(addrs.first()).map(|a| a.ip().to_string()) @@ -2558,18 +2585,7 @@ pub(super) fn create_for(req: &Request, engine: &Engine, wsl_distro: Option<&str // `--add-host name:ip` arrives as "name:ip"; /etc/hosts wants "ip name". // Both are written into the container's /etc/hosts by the guest, so a // newline in either would add lines of its own. - let mut extra_hosts = Vec::new(); - for h in strings(&host["ExtraHosts"]).unwrap_or_default() { - let Some((name, ip)) = h.split_once(':') else { continue }; - let ip = if ip == "host-gateway" { super::ports::HOST_ADDR } else { ip }; - if ip.parse::().is_err() { - return Err(Error::BadRequest(format!("invalid IP address: {ip}"))); - } - if !valid_hosts_name(name) { - return Err(Error::BadRequest(format!("invalid host name ({name})"))); - } - extra_hosts.push(format!("{ip}\t{name}")); - } + let extra_hosts = extra_hosts_from(&strings(&host["ExtraHosts"]).unwrap_or_default())?; let mut warnings: Vec<&str> = Vec::new(); if seccomp_unconfined { warnings.push(SECCOMP_UNCONFINED_WARNING); @@ -6537,4 +6553,14 @@ mod resources_disk_tests { let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn host_gateway_extra_host_stores_placeholder_not_wsl_addr() { + let raw = vec!["myhost:host-gateway".to_owned(), "db:10.0.0.2".to_owned()]; + assert_eq!( + extra_hosts_from(&raw).unwrap(), + vec![format!("{}\tmyhost", super::super::ports::HOST_ADDR), "10.0.0.2\tdb".to_owned()] + ); + assert!(extra_hosts_from(&["bad:not-an-ip".to_owned()]).is_err()); + } } diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index 41bd711ac..b0b7f5efe 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -1010,9 +1010,14 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu return Ok(Next::Close); } }; - // `host-gateway` was parsed as the Mac's address; on a Linux host it's - // the bridge gateway, as `docker run` gives (kiri-init maps it there). - let host = super::mirror::host_addr(engine); + // `host-gateway` was parsed as the Mac's address; on WSL 2 with the Windows + // host relay active it's 192.168.65.254, and on a plain Linux host it's the + // bridge gateway, as `docker run` gives (kiri-init maps it there). + let host = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR.to_owned() + } else { + super::mirror::host_addr(engine) + }; if host != super::ports::HOST_ADDR { let mac = format!("={}", super::ports::HOST_ADDR); for h in o.extra_hosts.iter_mut().filter(|h| h.ends_with(&mac)) { diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 512b7dadc..2cf3dbae5 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -3620,13 +3620,19 @@ impl Engine { flags |= run_flags::INIT; } flags |= spec.security_flags(); - // Every container can reach the Mac, as with Docker Desktop and OrbStack. - // --add-host and links come first: /etc/hosts takes the first match, - // so `--add-host host.docker.internal:IP` overrides Kiri's, as on Docker. + // Every container can reach the Mac (or Windows host on WSL 2), as with + // Docker Desktop and OrbStack. --add-host and links come first: + // /etc/hosts takes the first match, so `--add-host host.docker.internal:IP` + // overrides Kiri's, as on Docker. let mut hosts = spec.extra_hosts.clone(); hosts.extend(links); - hosts.push(format!("{}\thost.docker.internal host.kiri.internal", super::ports::HOST_ADDR)); - hosts.push(format!("{}\tgateway.docker.internal", super::ports::HOST_ADDR)); + let host_ip = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR + } else { + super::ports::HOST_ADDR + }; + hosts.push(format!("{host_ip}\thost.docker.internal host.kiri.internal")); + hosts.push(format!("{host_ip}\tgateway.docker.internal")); 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))); diff --git a/crates/kiri/src/hostrelay.rs b/crates/kiri/src/hostrelay.rs index 0ad8e0abb..2ccd5cc13 100644 --- a/crates/kiri/src/hostrelay.rs +++ b/crates/kiri/src/hostrelay.rs @@ -1,16 +1,20 @@ -//! `kiri hostrelay`: lets Kiri's engine in WSL2 reach a proxy on Windows' own -//! loopback, `127.0.0.1:7892`, where most Windows proxy apps listen. In +//! `kiri hostrelay`: lets Kiri's engine and containers in WSL2 reach services +//! on Windows' own loopback (`127.0.0.1` / `[::1]`): both Windows loopback +//! proxies (`127.0.0.1:7892`, where most Windows proxy apps listen) and +//! `host.docker.internal` / `host.kiri.internal` (`192.168.65.254`). In //! WSL's default NAT networking the distro's 127.0.0.1 is its own, and //! Windows' firewall keeps the WSL network away from Windows' ports, so a -//! proxy the browser uses was refused to every image pull. +//! service or proxy on Windows' loopback was unreachable from WSL and +//! containers. //! //! The connections take the way kiri-win already talks to WSL: a wsl.exe //! process's stdin and stdout. kiri-win (crates/kiri-win/src/relay.rs) -//! starts this and asks it to LISTEN for each proxy port; it listens on the -//! distro's 127.0.0.1 and sends each connection to it back as frames, and -//! kiri-win dials the proxy on Windows. kiri-win dials only the ports it -//! asked for, so nothing in WSL can reach any other Windows port this way. -//! The engine pulls through `127.0.0.1:` (daemon/proxy.rs). +//! starts this and asks it to LISTEN for static proxy ports (on the distro's +//! 127.0.0.1) and LISTEN_HOST for the dynamic `192.168.65.254` catch-all +//! host-gateway listener (using `SO_ORIGINAL_DST` with nftables DNAT on +//! `iifname "kiri*"` and local `OUTPUT` for TCP ports != 53). Each connection +//! goes back as frames, and kiri-win dials Windows' loopback (`127.0.0.1`, +//! falling back to `[::1]` on `ConnectionRefused`). //! //! Both ends share this file. Frames are the bridge's (crates/kiri/src/bridge.rs): //! kind, connection id (u32 BE), length (u32 BE), then the data. @@ -27,7 +31,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; -/// WSL → Windows: a connection to the proxy on the port in the data (u16 BE). +/// WSL → Windows: a connection to the proxy or host-gateway on the port in the data (u16 BE). pub const OPEN: u8 = 1; pub const DATA: u8 = 2; /// No more data from this side (a half-close). @@ -39,6 +43,111 @@ pub const LISTEN: u8 = 6; /// WSL → Windows: the Windows port, then the distro's port that leads to /// it (both u16 BE); 0 when it could not listen. pub const LISTENING: u8 = 7; +/// Windows → WSL: start the dynamic `192.168.65.254` catch-all host-gateway +/// listener (empty data, or 4-byte IPv4 override). +pub const LISTEN_HOST: u8 = 8; +/// WSL → Windows: the distro's catch-all host-gateway port (u16 BE), or 0 +/// when it could not listen or configure nftables. +pub const LISTENING_HOST: u8 = 9; + +/// What `host.docker.internal`, `host.kiri.internal`, and `host-gateway` +/// resolve to inside WSL 2 containers when the Windows host relay is active, +/// matching Docker Desktop. +pub const WSL_HOST_ADDR: [u8; 4] = [192, 168, 65, 254]; +pub const WSL_HOST_ADDR_STR: &str = "192.168.65.254"; + +/// True when running under Microsoft's WSL 2 kernel. +pub fn is_wsl() -> bool { + #[cfg(target_os = "linux")] + { + static WSL: std::sync::OnceLock = std::sync::OnceLock::new(); + *WSL.get_or_init(|| { + std::fs::read_to_string("/proc/sys/kernel/osrelease") + .is_ok_and(|r| r.to_ascii_lowercase().contains("microsoft")) + }) + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +#[cfg(unix)] +const HOST_LOCK_FILE: &str = "/run/kiri-hostrelay.lock"; +#[cfg(unix)] +const HOST_PID_FILE: &str = "/run/kiri-hostrelay.pid"; + +/// Checks whether a Linux `/proc//cmdline` (NUL-separated argv) belongs +/// to `kiri hostrelay` (empty cmdline also excludes unreaped zombies). +fn is_hostrelay_cmdline(cmdline: &[u8]) -> bool { + let mut args = cmdline.split(|&b| b == 0); + let Some(argv0) = args.next() else { return false }; + let Some(argv1) = args.next() else { return false }; + !argv0.is_empty() && argv1 == b"hostrelay" +} + +#[cfg(unix)] +fn read_pid_file(path: &std::path::Path) -> Option { + std::fs::read_to_string(path).ok()?.trim().parse::().ok().filter(|&p| p > 0) +} + +#[cfg(unix)] +fn write_pid_file(path: &std::path::Path, pid: u32) -> io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + let mut tmp = path.as_os_str().to_os_string(); + tmp.push(format!(".{pid}.tmp")); + let tmp = std::path::PathBuf::from(tmp); + let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o644).open(&tmp)?; + if let Err(e) = file.write_all(format!("{pid}\n").as_bytes()).and_then(|()| file.flush()) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + drop(file); + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +#[cfg(unix)] +fn pid_is_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + if pid <= 0 { + return false; + } + // SAFETY: signal 0 checks process existence without sending a signal. + if unsafe { libc::kill(pid, 0) } == 0 { + return true; + } + io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) +} + +#[cfg(unix)] +fn pid_file_alive(path: &std::path::Path, verify: impl FnOnce(u32) -> bool) -> bool { + read_pid_file(path).is_some_and(|pid| pid_is_alive(pid) && verify(pid)) +} + +#[cfg(target_os = "linux")] +fn hostrelay_pid_matches(pid: u32) -> bool { + std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| is_hostrelay_cmdline(&c)) +} + +/// True when running on WSL 2 with a live `kiri hostrelay` process owning +/// `192.168.65.254` (verified via `/run/kiri-hostrelay.pid`, `kill(pid, 0)`, +/// and `/proc//cmdline`, catching unclean exits without `getifaddrs()`). +pub fn wsl_host_active() -> bool { + #[cfg(target_os = "linux")] + { + is_wsl() && pid_file_alive(std::path::Path::new(HOST_PID_FILE), hostrelay_pid_matches) + } + #[cfg(not(target_os = "linux"))] + { + false + } +} /// Neither end sends more data than this in a frame; a longer one is refused /// before it is allocated. @@ -268,34 +377,63 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS /// The WSL end (`kiri hostrelay`): listens as kiri-win asks and sends each /// connection over `out`, until kiri-win goes, and the listeners with it. pub fn listen_side(input: impl Read, out: &Out) -> io::Result<()> { + // Declared before `_close` so open connections drop (freeing FDs) before + // `HostGateway::drop` acquires the teardown lock. + #[cfg(target_os = "linux")] + let mut host_gateway: Option = None; let conns = Arc::new(Conns::default()); let _close = CloseAll(conns.clone()); let next = Arc::new(AtomicU32::new(1)); let mut listening: HashMap = HashMap::new(); let mut r = BufReader::with_capacity(CHUNK, input); while let Some((kind, id, data)) = read_frame(&mut r)? { - if kind != LISTEN { - conns.dispatch(kind, id, data); - continue; - } - let Some(target) = port_of(&data, 0) else { continue }; - let local = match listening.get(&target) { - Some(&p) => p, - None => { - let p = listen(target, &conns, out, &next).unwrap_or(0); - if p != 0 { - listening.insert(target, p); - } - p + match kind { + LISTEN => { + let Some(target) = port_of(&data, 0) else { continue }; + let local = match listening.get(&target) { + Some(&p) => p, + None => { + let p = listen(target, &conns, out, &next).unwrap_or(0); + if p != 0 { + listening.insert(target, p); + } + p + } + }; + let mut reply = target.to_be_bytes().to_vec(); + reply.extend_from_slice(&local.to_be_bytes()); + send(out, LISTENING, 0, &reply)?; } - }; - let mut reply = target.to_be_bytes().to_vec(); - reply.extend_from_slice(&local.to_be_bytes()); - send(out, LISTENING, 0, &reply)?; + LISTEN_HOST => { + #[cfg(target_os = "linux")] + let port = match &host_gateway { + Some(hg) => hg.port, + None => { + let addr: [u8; 4] = data.get(..4).and_then(|b| b.try_into().ok()).unwrap_or(WSL_HOST_ADDR); + match start_host_gateway(addr, &conns, out, &next) { + Ok(hg) => { + let p = hg.port; + host_gateway = Some(hg); + p + } + Err(_) => 0, + } + } + }; + #[cfg(not(target_os = "linux"))] + let port: u16 = 0; + send(out, LISTENING_HOST, 0, &port.to_be_bytes())?; + } + _ => conns.dispatch(kind, id, data), + } } Ok(()) } +/// Backoff on transient `accept()` errors (such as `EMFILE` / `ENFILE`) so +/// listener threads never busy-spin. +const ACCEPT_ERR_BACKOFF: Duration = Duration::from_millis(50); + /// Listens on the distro's loopback for `target`; its port. fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> io::Result { let l = TcpListener::bind(("127.0.0.1", 0))?; @@ -303,7 +441,15 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> let (conns, out, next) = (conns.clone(), out.clone(), next.clone()); std::thread::spawn(move || { for s in l.incoming() { - let Ok(s) = s else { continue }; + let s = match s { + Ok(s) => s, + Err(e) => { + if e.kind() != io::ErrorKind::Interrupted { + std::thread::sleep(ACCEPT_ERR_BACKOFF); + } + continue; + } + }; let id = next.fetch_add(1, Ordering::SeqCst); let Some(rx) = conns.open(id) else { let _ = s.shutdown(Shutdown::Both); @@ -320,16 +466,546 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> Ok(port) } +/// Acquires an exclusive `flock` on `lock_path` (never unlinked so concurrent +/// setup and teardown always synchronize on the same inode). +#[cfg(unix)] +fn lock_host_gateway(lock_path: &std::path::Path) -> io::Result { + use std::os::fd::AsRawFd; + let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lock_path)?; + loop { + // SAFETY: `file` owns a valid open descriptor. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 { + return Ok(file); + } + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } +} + +/// Serializes host-gateway setup under `lock_path`, publishing `pid` to +/// `pid_path` only after `setup` succeeds and rolling back if publishing fails. +#[cfg(unix)] +fn acquire_host_gateway( + lock_path: &std::path::Path, + pid_path: &std::path::Path, + pid: u32, + setup: impl FnOnce() -> io::Result, + rollback: impl FnOnce(T), +) -> io::Result { + let _lock = lock_host_gateway(lock_path)?; + let val = setup()?; + if let Err(e) = write_pid_file(pid_path, pid) { + if read_pid_file(pid_path) == Some(pid) { + let _ = std::fs::remove_file(pid_path); + } + rollback(val); + return Err(e); + } + Ok(val) +} + +/// Serializes host-gateway teardown under `lock_path`, removing `pid_path` and +/// running `teardown` only after verifying `pid` is still the active owner. +#[cfg(unix)] +fn release_host_gateway(lock_path: &std::path::Path, pid_path: &std::path::Path, pid: u32, teardown: impl FnOnce()) { + let Ok(_lock) = lock_host_gateway(lock_path) else { return }; + if read_pid_file(pid_path) == Some(pid) { + let _ = std::fs::remove_file(pid_path); + teardown(); + } +} + +/// Active catch-all host-gateway state on Linux (WSL 2): keeps `192.168.65.254/32` +/// on `lo` and `table ip kiri_host` alive until `listen_side` ends, then cleans +/// them up if no newer `kiri hostrelay` has taken ownership. +#[cfg(target_os = "linux")] +struct HostGateway { + addr: [u8; 4], + port: u16, + pid: u32, +} + +#[cfg(target_os = "linux")] +impl Drop for HostGateway { + fn drop(&mut self) { + // Serialize with any concurrent `start_host_gateway` so an exiting + // relay can never tear down a newer relay's `lo` address or nftables. + release_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + self.pid, + || { + let _ = host_net::remove_nft(); + let _ = host_net::del_lo_addr(self.addr); + }, + ); + } +} + +/// Checks whether `SO_ORIGINAL_DST` returned a valid host-gateway target port +/// destined to `host_addr` (non-zero and not TCP port 53). +fn host_gateway_target(dst_ip: [u8; 4], dst_port: u16, host_addr: [u8; 4]) -> Option { + (dst_ip == host_addr && dst_port != 0 && dst_port != 53).then_some(dst_port) +} + +#[cfg(target_os = "linux")] +fn original_dst_port(fd: std::os::fd::RawFd, host_addr: [u8; 4]) -> Option { + const SO_ORIGINAL_DST: libc::c_int = 80; + // SAFETY: `SO_ORIGINAL_DST` fills `sockaddr_in` with the pre-DNAT destination. + unsafe { + let mut dst: libc::sockaddr_in = std::mem::zeroed(); + let mut len = std::mem::size_of::() as libc::socklen_t; + if libc::getsockopt(fd, libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) != 0 { + return None; + } + host_gateway_target(dst.sin_addr.s_addr.to_ne_bytes(), u16::from_be(dst.sin_port), host_addr) + } +} + +/// Assigns `addr/32` to `lo`, binds a catch-all TCP listener on `addr:0`, +/// installs `table ip kiri_host` nftables DNAT + input guard rules, and spawns +/// the accept loop that extracts each connection's target port via +/// `SO_ORIGINAL_DST`. +#[cfg(target_os = "linux")] +fn start_host_gateway(addr: [u8; 4], conns: &Arc, out: &Out, next: &Arc) -> io::Result { + use std::os::fd::AsRawFd; + let pid = std::process::id(); + let (listener, port, added) = acquire_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + pid, + || { + let added = host_net::add_lo_addr(addr)?; + let listener = match TcpListener::bind((std::net::Ipv4Addr::from(addr), 0)) { + Ok(l) => l, + Err(e) => { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + }; + let port = match listener.local_addr() { + Ok(a) => a.port(), + Err(e) => { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + }; + if let Err(e) = host_net::install_nft(addr, port) { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + Ok((listener, port, added)) + }, + |(_listener, _port, added)| { + let _ = host_net::remove_nft(); + if added { + let _ = host_net::del_lo_addr(addr); + } + }, + )?; + let (conns, out, next) = (conns.clone(), out.clone(), next.clone()); + if let Err(e) = std::thread::Builder::new().name("kiri-hostrelay-gw".into()).spawn(move || { + for s in listener.incoming() { + let s = match s { + Ok(s) => s, + Err(e) => { + if e.kind() != io::ErrorKind::Interrupted { + std::thread::sleep(ACCEPT_ERR_BACKOFF); + } + continue; + } + }; + let Some(target) = original_dst_port(s.as_raw_fd(), addr) else { + let _ = s.shutdown(Shutdown::Both); + continue; + }; + let id = next.fetch_add(1, Ordering::SeqCst); + let Some(rx) = conns.open(id) else { + let _ = s.shutdown(Shutdown::Both); + return; + }; + if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { + conns.close(id); + let _ = s.shutdown(Shutdown::Both); + return; + } + attach(&conns, &out, id, rx, s); + } + }) { + release_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + pid, + || { + let _ = host_net::remove_nft(); + if added { + let _ = host_net::del_lo_addr(addr); + } + }, + ); + return Err(e); + } + Ok(HostGateway { addr, port, pid }) +} + +/// Minimal rtnetlink and nf_tables netlink helpers for WSL 2's catch-all +/// `192.168.65.254` host-gateway listener (`kiri hostrelay` runs in minimal +/// WSL distros with neither `ip` nor `nft` binaries). +#[cfg(target_os = "linux")] +mod host_net { + use std::io; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + + const NLMSG_ERROR: u16 = 2; + const NLMSG_DONE: u16 = 3; + const NLM_F_REQUEST: u16 = 0x1; + const NLM_F_ACK: u16 = 0x4; + const NLM_F_EXCL: u16 = 0x200; + const NLM_F_CREATE: u16 = 0x400; + const NLM_F_APPEND: u16 = 0x800; + + const RTM_NEWADDR: u16 = 20; + const RTM_DELADDR: u16 = 21; + const IFA_ADDRESS: u16 = 1; + const IFA_LOCAL: u16 = 2; + + const NFNL_SUBSYS_NFTABLES: u16 = 10; + const NFNL_MSG_BATCH_BEGIN: u16 = 0x10; + const NFNL_MSG_BATCH_END: u16 = 0x11; + const NFT_MSG_NEWTABLE: u16 = 0; + const NFT_MSG_DELTABLE: u16 = 2; + const NFT_MSG_NEWCHAIN: u16 = 3; + const NFT_MSG_NEWRULE: u16 = 6; + + pub const TABLE: &str = "kiri_host"; + const BRIDGE_PREFIX: &[u8] = b"kiri"; + /// Runs after conntrack (-200) and before `table ip kiri` (-100) so + /// host-gateway traffic is never caught by published-port DNAT rules. + const NAT_PRIORITY: i32 = -110; + + pub struct Msg { + pub buf: Vec, + nests: Vec, + } + + fn pad(buf: &mut Vec) { + while buf.len() % 4 != 0 { + buf.push(0); + } + } + + impl Msg { + fn new(ty: u16, flags: u16) -> Self { + let mut buf = vec![0u8; 16]; + buf[4..6].copy_from_slice(&ty.to_ne_bytes()); + buf[6..8].copy_from_slice(&(flags | NLM_F_REQUEST).to_ne_bytes()); + Self { buf, nests: Vec::new() } + } + + fn raw(&mut self, bytes: &[u8]) -> &mut Self { + self.buf.extend_from_slice(bytes); + pad(&mut self.buf); + self + } + + fn attr(&mut self, ty: u16, data: &[u8]) -> &mut Self { + self.buf.extend_from_slice(&((4 + data.len()) as u16).to_ne_bytes()); + self.buf.extend_from_slice(&ty.to_ne_bytes()); + self.buf.extend_from_slice(data); + pad(&mut self.buf); + self + } + + fn attr_str(&mut self, ty: u16, s: &str) -> &mut Self { + let mut v = s.as_bytes().to_vec(); + v.push(0); + self.attr(ty, &v) + } + + fn attr_be32(&mut self, ty: u16, v: u32) -> &mut Self { + self.attr(ty, &v.to_be_bytes()) + } + + fn nest(&mut self, ty: u16) -> &mut Self { + self.nests.push(self.buf.len()); + self.buf.extend_from_slice(&[0, 0]); + self.buf.extend_from_slice(&(ty | 0x8000).to_ne_bytes()); + self + } + + fn end(&mut self) -> &mut Self { + let start = self.nests.pop().expect("nest() before end()"); + let len = (self.buf.len() - start) as u16; + self.buf[start..start + 2].copy_from_slice(&len.to_ne_bytes()); + self + } + + fn finish(&mut self, seq: u32) -> &[u8] { + let len = self.buf.len() as u32; + self.buf[0..4].copy_from_slice(&len.to_ne_bytes()); + self.buf[8..12].copy_from_slice(&seq.to_ne_bytes()); + &self.buf + } + } + + struct Netlink { + fd: OwnedFd, + seq: u32, + buf: Vec, + } + + impl Netlink { + fn open(protocol: i32) -> io::Result { + // SAFETY: plain socket creation; owned immediately. + let fd = unsafe { libc::socket(libc::AF_NETLINK, libc::SOCK_RAW | libc::SOCK_CLOEXEC, protocol) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `fd` is a fresh descriptor owned only here. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + Ok(Self { fd, seq: 1, buf: vec![0u8; 16 * 1024] }) + } + + fn request(&mut self, msgs: &mut [Msg]) -> io::Result<()> { + let mut out = Vec::new(); + let first = self.seq; + for m in msgs.iter_mut() { + out.extend_from_slice(m.finish(self.seq)); + self.seq += 1; + } + // SAFETY: sending our own buffer on our own socket. + if unsafe { libc::send(self.fd.as_raw_fd(), out.as_ptr().cast(), out.len(), 0) } < 0 { + return Err(io::Error::last_os_error()); + } + let mut acked = 0; + let want = msgs.iter().filter(|m| u16::from_ne_bytes([m.buf[6], m.buf[7]]) & NLM_F_ACK != 0).count(); + while acked < want { + // SAFETY: receiving into our own buffer on our own socket. + let n = unsafe { libc::recv(self.fd.as_raw_fd(), self.buf.as_mut_ptr().cast(), self.buf.len(), 0) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + let n = n as usize; + let mut off = 0; + while off + 16 <= n { + let len = u32::from_ne_bytes(self.buf[off..off + 4].try_into().expect("4")) as usize; + let ty = u16::from_ne_bytes(self.buf[off + 4..off + 6].try_into().expect("2")); + let seq = u32::from_ne_bytes(self.buf[off + 8..off + 12].try_into().expect("4")); + if len < 16 || off + len > n { + break; + } + if ty == NLMSG_ERROR && seq >= first && seq < self.seq { + let code = i32::from_ne_bytes(self.buf[off + 16..off + 20].try_into().expect("4")); + acked += 1; + if code != 0 { + return Err(io::Error::from_raw_os_error(-code)); + } + } else if ty == NLMSG_DONE { + acked = want; + } + off += (len + 3) & !3; + } + } + Ok(()) + } + } + + fn lo_index() -> io::Result { + // SAFETY: valid NUL-terminated static C string. + let i = unsafe { libc::if_nametoindex(c"lo".as_ptr()) }; + if i == 0 { + return Err(io::Error::new(io::ErrorKind::NotFound, "no lo interface")); + } + Ok(i) + } + + fn lo_addr_msg(ty: u16, flags: u16, index: u32, addr: [u8; 4]) -> Msg { + let mut m = Msg::new(ty, flags); + let mut ifa = [0u8; 8]; + ifa[0] = libc::AF_INET as u8; + ifa[1] = 32; + ifa[3] = libc::RT_SCOPE_HOST; + ifa[4..8].copy_from_slice(&index.to_ne_bytes()); + m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); + m + } + + /// Adds `addr/32` to `lo`. Returns `Ok(true)` if added, `Ok(false)` if already present. + pub fn add_lo_addr(addr: [u8; 4]) -> io::Result { + let index = lo_index()?; + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + let msg = lo_addr_msg(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL, index, addr); + match nl.request(&mut [msg]) { + Ok(()) => Ok(true), + Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(false), + Err(e) => Err(e), + } + } + + /// Removes `addr/32` from `lo`; already absent is fine. + pub fn del_lo_addr(addr: [u8; 4]) -> io::Result<()> { + let index = lo_index()?; + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + let msg = lo_addr_msg(RTM_DELADDR, NLM_F_ACK, index, addr); + match nl.request(&mut [msg]) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::EADDRNOTAVAIL) => Ok(()), + Err(e) => Err(e), + } + } + + fn nfgen(family: u8, res_id: u16) -> [u8; 4] { + let mut b = [0u8; 4]; + b[0] = family; + b[2..4].copy_from_slice(&res_id.to_be_bytes()); + b + } + + fn nft(msg: u16, flags: u16) -> Msg { + let mut m = Msg::new((NFNL_SUBSYS_NFTABLES << 8) | msg, flags); + m.raw(&nfgen(libc::NFPROTO_IPV4 as u8, 0)); + m + } + + /// Linux 3.13+ compatible table clear: add (no-op if present), then delete. + fn clear_table() -> [Msg; 2] { + let mut add = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); + add.attr_str(1, TABLE); + let mut delete = nft(NFT_MSG_DELTABLE, NLM_F_ACK); + delete.attr_str(1, TABLE); + [add, delete] + } + + fn chain(name: &str, hook: u32, priority: i32, kind: &str) -> Msg { + let mut c = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + c.attr_str(1, TABLE).attr_str(3, name); + c.nest(4).attr_be32(1, hook).attr_be32(2, priority as u32).end(); + c.attr_be32(5, libc::NF_ACCEPT as u32).attr_str(7, kind); + c + } + + /// `[iifname "kiri*"] ip daddr tcp dport != 53 dnat to :`. + pub fn dnat_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | NLM_F_APPEND); + rule.attr_str(1, TABLE).attr_str(2, chain); + rule.nest(4); + if from_bridges { + // meta iifname (6) => reg 1; cmp eq "kiri" prefix + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + } + // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + // meta l4proto (16) => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload transport header + 2 (dport), 2 bytes => reg 1; cmp neq 53 + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 2).attr_be32(4, 2).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &53u16.to_be_bytes()).end().end().end(); + // immediate reg 1 = addr, reg 2 = port; nat dnat ip addr reg 1 proto reg 2 + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &addr).end().end().end(); + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 2).nest(2).attr(1, &port.to_be_bytes()).end().end().end(); + rule.nest(1).attr_str(1, "nat").nest(2).attr_be32(1, 1).attr_be32(2, libc::AF_INET as u32).attr_be32(3, 1).attr_be32(5, 2).attr_be32(7, 2).end().end(); + rule.end(); + rule + } + + /// `ip daddr iifname != "kiri*" iifname != "lo" drop`: keeps + /// external LAN / non-container interfaces off the host-gateway relay. + pub fn input_guard_rule(addr: [u8; 4]) -> Msg { + let mut lo_full = [0u8; 16]; + lo_full[..2].copy_from_slice(b"lo"); + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | NLM_F_APPEND); + rule.attr_str(1, TABLE).attr_str(2, "input"); + rule.nest(4); + // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + // meta iifname (6) => reg 1; cmp neq "kiri" prefix + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + // meta iifname (6) => reg 1; cmp neq "lo" exact (16-byte NUL-padded) + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &lo_full).end().end().end(); + // verdict DROP + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); + rule.end(); + rule + } + + pub fn install_batch(addr: [u8; 4], port: u16) -> Vec { + let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); + begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let [add, delete] = clear_table(); + let mut table = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); + table.attr_str(1, TABLE); + let pre = chain("prerouting", 0, NAT_PRIORITY, "nat"); + let out = chain("output", 3, NAT_PRIORITY, "nat"); + let input = chain("input", 1, 0, "filter"); + let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); + end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + vec![ + begin, + add, + delete, + table, + pre, + out, + input, + dnat_rule("prerouting", addr, port, true), + dnat_rule("output", addr, port, false), + input_guard_rule(addr), + end, + ] + } + + pub fn install_nft(addr: [u8; 4], port: u16) -> io::Result<()> { + let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; + nl.request(&mut install_batch(addr, port)) + } + + pub fn remove_nft() -> io::Result<()> { + let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; + let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); + begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let [add, delete] = clear_table(); + let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); + end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + nl.request(&mut [begin, add, delete, end]) + } +} + /// The Windows end: dials the proxy for each connection the WSL end sends, /// on the ports `allowed` names, and hands LISTENING replies to `listening`. pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, listening: impl Fn(u16, u16)) -> io::Result<()> { + dial_side_with_host(input, out, allowed, listening, |_| {}) +} + +/// Like [`dial_side`], also delivering `LISTENING_HOST` replies (the WSL +/// catch-all host-gateway relay port, or 0 on failure) to `listening_host`. +pub fn dial_side_with_host( + input: impl Read, + out: &Out, + allowed: impl Fn(u16) -> bool, + listening: impl Fn(u16, u16), + listening_host: impl Fn(u16), +) -> io::Result<()> { let conns = Arc::new(Conns::default()); let _close = CloseAll(conns.clone()); let mut r = BufReader::with_capacity(CHUNK, input); while let Some((kind, id, data)) = read_frame(&mut r)? { match kind { OPEN => { - let target = port_of(&data, 0).filter(|&p| allowed(p)); + let target = port_of(&data, 0).filter(|&p| p != 0 && allowed(p)); let Some(target) = target else { send(out, CLOSE, id, &[])?; continue; @@ -350,16 +1026,29 @@ pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, lis listening(target, local); } } + LISTENING_HOST => { + if let Some(local) = port_of(&data, 0) { + listening_host(local); + } + } _ => conns.dispatch(kind, id, data), } } Ok(()) } -/// This machine's loopback at `port`: IPv4, then IPv6. +/// This machine's loopback at `port`: `127.0.0.1` first, falling back to +/// `[::1]` on `ConnectionRefused` (for IPv6-only localhost servers such as +/// Node/Vite on Windows). fn dial(port: u16) -> io::Result { let wait = Duration::from_secs(5); - TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), wait).or_else(|e| TcpStream::connect_timeout(&(std::net::Ipv6Addr::LOCALHOST, port).into(), wait).map_err(|_| e)) + match TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), wait) { + Ok(s) => Ok(s), + Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable) => { + TcpStream::connect_timeout(&(std::net::Ipv6Addr::LOCALHOST, port).into(), wait).map_err(|_| e) + } + Err(e) => Err(e), + } } /// Where in a proxy address its host and port are, when the host is this @@ -715,4 +1404,188 @@ mod tests { } assert!(read_frame(&mut out_rx).unwrap().is_none(), "no OPEN frame emitted after teardown"); } + + #[test] + fn host_gateway_target_validates_ip_and_port() { + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 17433, WSL_HOST_ADDR), Some(17433)); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 80, WSL_HOST_ADDR), Some(80)); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 0, WSL_HOST_ADDR), None, "port 0 rejected"); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 53, WSL_HOST_ADDR), None, "DNS port 53 excluded"); + assert_eq!(host_gateway_target([172, 17, 0, 1], 17433, WSL_HOST_ADDR), None, "wrong IP rejected"); + assert_eq!(host_gateway_target([127, 0, 0, 1], 17433, WSL_HOST_ADDR), None, "loopback rejected"); + } + + #[test] + fn dial_side_with_host_allows_dynamic_ipv4_and_ipv6_ports_and_rejects_port_zero() { + let srv4 = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port4 = srv4.local_addr().unwrap().port(); + std::thread::spawn(move || { + if let Ok((mut s, _)) = srv4.accept() { + let _ = s.write_all(b"v4-ok"); + } + }); + let srv6 = TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, 0)).ok(); + let port6 = srv6.as_ref().map(|l| l.local_addr().unwrap().port()); + if let Some(l) = srv6 { + std::thread::spawn(move || { + if let Ok((mut s, _)) = l.accept() { + let _ = s.write_all(b"v6-ok"); + } + }); + } + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let got_host = Arc::new(std::sync::atomic::AtomicU16::new(0)); + let gh = got_host.clone(); + let h = std::thread::spawn(move || { + dial_side_with_host(in_rx, &o, |_| true, |_, _| {}, move |p| gh.store(p, Ordering::SeqCst)) + }); + + // LISTENING_HOST delivers the reported relay port. + send(&in_out, LISTENING_HOST, 0, &41234u16.to_be_bytes()).unwrap(); + // Port 0 is always refused even when `allowed` returns true. + send(&in_out, OPEN, 1, &0u16.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((CLOSE, 1, vec![]))); + assert_eq!(got_host.load(Ordering::SeqCst), 41234); + + // IPv4 loopback server reachable dynamically without prior LISTEN. + send(&in_out, OPEN, 2, &port4.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 2, b"v4-ok".to_vec()))); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((EOF, 2, vec![]))); + + // IPv6-only loopback server reachable via ConnectionRefused fallback. + if let Some(p6) = port6 { + send(&in_out, OPEN, 3, &p6.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 3, b"v6-ok".to_vec()))); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((EOF, 3, vec![]))); + } + + drop(in_out); + h.join().unwrap().unwrap(); + } + + #[test] + fn host_gateway_lock_serializes_setup_and_teardown_and_checks_owner_pid() { + let dir = std::env::temp_dir().join(format!("kiri-hostrelay-lock-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lock = dir.join("kiri-hostrelay.lock"); + let pid_path = dir.join("kiri-hostrelay.pid"); + + // 1. Failed setup never creates a stale pidfile. + let err = acquire_host_gateway(&lock, &pid_path, 111, || Err::<(), _>(io::Error::other("boom")), |_| panic!("rollback on setup err")); + assert!(err.is_err()); + assert!(!pid_path.exists(), "failed setup must not leave a pidfile"); + + // 2. Relay 1 acquires; a concurrent failed start of relay 2 must not clobber relay 1's pidfile. + acquire_host_gateway(&lock, &pid_path, 111, || Ok(()), |_| {}).unwrap(); + assert_eq!(read_pid_file(&pid_path), Some(111)); + assert!(acquire_host_gateway(&lock, &pid_path, 222, || Err::<(), _>(io::Error::other("bind failed")), |_| {}).is_err()); + assert_eq!(read_pid_file(&pid_path), Some(111)); + + // 3. Rollback fires if writing the pidfile fails (e.g., pid_path is a directory). + let bad_pid = dir.join("pid-dir"); + std::fs::create_dir_all(&bad_pid).unwrap(); + let rolled_back = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let rb = rolled_back.clone(); + assert!(acquire_host_gateway(&lock, &bad_pid, 333, || Ok(42u32), move |v| { + assert_eq!(v, 42); + rb.store(true, Ordering::SeqCst); + }) + .is_err()); + assert!(rolled_back.load(Ordering::SeqCst)); + + // 4. Simulate the Drop race: relay 2 holds the flock while taking over; + // relay 1's Drop waits on the flock, then sees relay 2's PID and does NOT tear down. + let guard = lock_host_gateway(&lock).unwrap(); + let lock2 = lock.clone(); + let pid2 = pid_path.clone(); + let old_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let otd = old_tore_down.clone(); + let drop_thread = std::thread::spawn(move || { + release_host_gateway(&lock2, &pid2, 111, move || otd.store(true, Ordering::SeqCst)); + }); + std::thread::sleep(Duration::from_millis(30)); + assert!(!old_tore_down.load(Ordering::SeqCst), "old Drop must wait for the flock"); + write_pid_file(&pid_path, 222).unwrap(); + drop(guard); + drop_thread.join().unwrap(); + assert!(!old_tore_down.load(Ordering::SeqCst), "old Drop must not tear down newer relay"); + assert_eq!(read_pid_file(&pid_path), Some(222), "newer relay's pidfile preserved"); + + // 5. When relay 2 itself drops, it is the active owner so it removes the pidfile and tears down. + let new_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ntd = new_tore_down.clone(); + release_host_gateway(&lock, &pid_path, 222, move || ntd.store(true, Ordering::SeqCst)); + assert!(new_tore_down.load(Ordering::SeqCst)); + assert!(!pid_path.exists()); + + // 6. A missing pidfile must NEVER trigger teardown for a stale Drop. + let ghost_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let gtd = ghost_tore_down.clone(); + release_host_gateway(&lock, &pid_path, 111, move || gtd.store(true, Ordering::SeqCst)); + assert!(!ghost_tore_down.load(Ordering::SeqCst)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn host_gateway_liveness_detects_live_and_dead_pids_and_cmdline() { + let dir = std::env::temp_dir().join(format!("kiri-hostrelay-live-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pid_path = dir.join("kiri-hostrelay.pid"); + + // Missing or invalid pidfile -> inactive. + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, "not-a-pid\n").unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, "0\n").unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true)); + + // Live PID (current test process) -> active iff cmdline verifier passes. + write_pid_file(&pid_path, std::process::id()).unwrap(); + assert!(pid_file_alive(&pid_path, |_| true)); + assert!(!pid_file_alive(&pid_path, |_| false)); + + // Dead PID (exited & reaped child, simulating kill -9 leaving stale pidfile) -> inactive. + let mut child = std::process::Command::new("/bin/sh").args(["-c", "exit 0"]).spawn().unwrap(); + let dead_pid = child.id(); + let _ = child.wait().unwrap(); + write_pid_file(&pid_path, dead_pid).unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true), "dead PID must be treated as inactive"); + + // Cmdline matching: accepts `kiri hostrelay`, rejects zombies and reused PIDs. + assert!(is_hostrelay_cmdline(b"/usr/local/bin/kiri\0hostrelay\0")); + assert!(is_hostrelay_cmdline(b"kiri\0hostrelay")); + assert!(!is_hostrelay_cmdline(b"/usr/local/bin/kiri\0daemon\0")); + assert!(!is_hostrelay_cmdline(b"/bin/sh\0-c\0hostrelay\0")); + assert!(!is_hostrelay_cmdline(b"")); + assert!(!is_hostrelay_cmdline(b"\0hostrelay\0")); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(target_os = "linux")] + #[test] + fn host_gateway_nft_batch_matches_bridges_output_and_guards_input() { + let batch = host_net::install_batch(WSL_HOST_ADDR, 45678); + assert_eq!(batch.len(), 11); + let has = |m: &host_net::Msg, needle: &[u8]| m.buf.windows(needle.len()).any(|w| w == needle); + let pre = &batch[7]; + let out = &batch[8]; + let guard = &batch[9]; + // prerouting DNAT matches iifname "kiri*", daddr 192.168.65.254, tcp dport != 53 -> :45678 + assert!(has(pre, b"kiri_host\0") && has(pre, b"prerouting\0")); + assert!(has(pre, b"kiri") && has(pre, &WSL_HOST_ADDR) && has(pre, &53u16.to_be_bytes()) && has(pre, &45678u16.to_be_bytes())); + // output DNAT has no bridge iifname match, still skips port 53 + assert!(has(out, b"output\0") && has(out, &WSL_HOST_ADDR) && has(out, &53u16.to_be_bytes()) && has(out, &45678u16.to_be_bytes())); + // input guard drops non-kiri*, non-lo traffic to 192.168.65.254 + let mut lo_full = [0u8; 16]; + lo_full[..2].copy_from_slice(b"lo"); + assert!(has(guard, b"input\0") && has(guard, &WSL_HOST_ADDR) && has(guard, &lo_full)); + } } diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 35a83fbf1..d37074865 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -355,7 +355,11 @@ const HOST_MANIFEST: &str = "kiri-host-names.yaml"; /// everything else resolves as before. A `hosts` block in a `.override` /// would clash with the NodeHosts one k3s' Corefile already has. fn host_manifest() -> String { - let addr = crate::daemon::ports::HOST_ADDR; + let addr = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR + } else { + crate::daemon::ports::HOST_ADDR + }; let zones: Vec = HOST_NAMES.iter().map(|n| format!("{n}:53")).collect(); format!( "# Written by Kiri at each `kiri k8s start`: pods resolve the host's names, as containers do.\n\ diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 6ad8c1e7c..60ad4eddc 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 +### #550 Windows: resolve host.docker.internal and host.kiri.internal to 192.168.65.254 and relay to Windows loopback (unreleased) +- Fixes: #550 Windows: host.docker.internal resolves to the WSL VM's bridge gateway (172.17.0.1) instead of the Windows host, unlike Docker Desktop +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/hostrelay.rs` + ### #810 Networks: disconnect and reconnect a running container's first network cleanly at Layer 2/3, DNS, and port forwarding (unreleased) - Fixes: #789 A running container can't leave its first network, so its network aliases can't be changed (follow-up to #418) - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index f215fd111..8195fddf6 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -299,3 +299,4 @@ import-upper-runs-with-files #410 an imported container started without the file leave-first-running-disconnect #789 disconnecting a running container from its only network was refused (or left its veth, routes, and published ports active instead of isolating it) leave-first-running-reconnect #789 reconnecting a running container after leaving its first network failed to restore veth connectivity, DNS aliases, or published ports leave-first-running-promote #789 disconnecting a running container's first network when attached to a second network failed to isolate the left network, promote the default route, or rebind published ports +crates/kiri/src/hostrelay.rs #550 on Windows (WSL 2), host.docker.internal resolved to the WSL bridge gateway (172.17.0.1) instead of 192.168.65.254 relayed to Windows 127.0.0.1 and [::1] From 32be331efdb94ecf145c807344f4c68347ef44cc Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:43:24 +0100 Subject: [PATCH 066/157] Windows: forward published UDP and host-IP ports and write diag reports on Windows (#640, #218, #761) (#857) --- crates/kiri-win/src/engine.rs | 3 + crates/kiri-win/src/main.rs | 5 + crates/kiri-win/src/ports.rs | 981 ++++++++++++++++++++++++++++++ crates/kiri-win/src/serve.rs | 21 +- crates/kiri/src/daemon/api.rs | 27 + crates/kiri/src/daemon/engine.rs | 23 + crates/kiri/src/daemon/mod.rs | 2 +- crates/kiri/src/daemon/network.rs | 22 +- crates/kiri/src/daemon/ports.rs | 377 +++++++++++- crates/kiri/src/diag/report.rs | 41 +- crates/kiri/src/main.rs | 2 +- crates/kiri/src/wsl.rs | 164 ++++- docs/fix-registry.md | 6 + tests/regressions.tsv | 3 + 14 files changed, 1640 insertions(+), 37 deletions(-) create mode 100644 crates/kiri-win/src/ports.rs diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 9ccbf5e92..aade5b9db 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -254,9 +254,11 @@ fn watch(tx: Sender) { // A Kubernetes node already running gets its kubectl context. crate::k8s::sync_soon(); crate::watch::notify_containers_changed(); + crate::ports::notify(); crate::wslconfig::sync_wsl_integration_soon(); let _ = client::events(|_| { crate::watch::notify_containers_changed(); + crate::ports::notify(); tx.send(Cmd::Refresh).is_ok() }); } @@ -712,6 +714,7 @@ fn host_ports(info: &Value, with_inner: bool) -> Vec { fn set_ports(id: &str, ports: Value) -> io::Result<()> { expect_ok(client::request("POST", &format!("/kiri/containers/{id}/ports"), Some(&json!({"ports": ports}))))?; + crate::ports::sync_now(); let now = host_ports(&client::get(&format!("/containers/{id}/json"))?, true); emit(notice("ok", &if now.is_empty() { tr("Ports removed") } else { trf("Ports saved: {ports}", &[("ports", &now.join(", "))]) })); Ok(()) diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index d8f98acd4..034f69a1e 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -117,6 +117,10 @@ mod refuse; // path mapping, buffer decoding and coalescing tested on any host. #[cfg(any(windows, test))] mod watch; +// Windows inbound published-port forwarder (UDP and non-loopback host-IP TCP +// to WSL 2's eth0 IPv4 address): tested on any host. +#[cfg(any(windows, test))] +mod ports; // Settings → Storage: custom WSL distro location in %LOCALAPPDATA%\Kiri\storage.json. #[cfg(any(windows, test))] mod storage; @@ -188,6 +192,7 @@ fn main() -> std::process::ExitCode { return std::process::ExitCode::FAILURE; } client::set_pipe(&cfg.pipe); + ports::start(); if let Err(e) = dns::start() { serve::log(&format!("dns on 127.0.0.1:53: {e}")); } diff --git a/crates/kiri-win/src/ports.rs b/crates/kiri-win/src/ports.rs new file mode 100644 index 000000000..10912a1eb --- /dev/null +++ b/crates/kiri-win/src/ports.rs @@ -0,0 +1,981 @@ +//! Published container ports on Windows (`#640`, `#218`). +//! +//! WSL 2's built-in `localhostForwarding` (`wslrelay.exe`) only forwards TCP on +//! Windows loopback (`127.0.0.1:/tcp` and `[::1]:/tcp`): +//! - It never forwards UDP at all (`#640`). +//! - It never binds non-loopback Windows host interface addresses (``) +//! for `-p 0.0.0.0:port:cport` or `-p :port:cport` (`#218`). +//! +//! This module pushes the Windows host's interface IPs to the WSL daemon via +//! `POST /kiri/win-ports` (so `-p :port:cport` binds WSL's internal +//! `eth0` IP without leaking `127.0.0.1:port` on Windows, while bogus IPs still +//! fail with `Address not available (os error 99)`), and maintains Windows-side +//! UDP and non-loopback TCP forwarders to `:`. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::collections::{BTreeSet, HashMap}; +use std::io::{self, Read, Write}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6, TcpListener, TcpStream, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +/// Idle timeout for a per-client UDP forwarding session, matching conntrack. +const UDP_IDLE: Duration = Duration::from_secs(60); +/// Read timeout on UDP sockets so the loop can check `stop` and reap idle sessions. +const UDP_POLL: Duration = Duration::from_millis(250); +/// Poll interval on non-blocking `TcpListener::accept` so `stop()` joins within ~100ms +/// without needing a self-connect that could hang if the bound IP disappeared. +const TCP_ACCEPT_POLL: Duration = Duration::from_millis(100); +/// Maximum concurrent UDP client sessions per published UDP port. +const MAX_UDP_SESSIONS: usize = 1024; +/// Connect timeout when dialing the WSL 2 `eth0` target for a forwarded TCP connection. +const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Proto { + Tcp, + Udp, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct PublishedPort { + pub proto: String, + pub host_ip: String, + pub host_port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ForwardSpec { + pub proto: Proto, + pub bind_addr: SocketAddr, + pub target_addr: SocketAddr, +} + +/// Parses a bare or bracketed IPv4/IPv6 address, stripping any `%scope` suffix. +pub fn parse_ip(s: &str) -> Option { + let bare = s.trim().strip_prefix('[').and_then(|i| i.strip_suffix(']')).unwrap_or(s.trim()); + let bare = bare.split('%').next().unwrap_or(bare); + bare.parse::().ok().map(|a| a.to_canonical()) +} + +/// Computes the Windows-side TCP and UDP listeners needed for `published`, +/// forwarding to `wsl_ip:`: +/// - UDP: every published UDP port (`0.0.0.0:port`, `[::]:port`, `127.0.0.1:port`, +/// `[::1]:port`, or `:port`), since `wslrelay.exe` never forwards UDP. +/// - TCP: +/// - `127.0.0.1` and `::1` are left to `wslrelay.exe`. +/// - `0.0.0.0` (or `""`) expands to every non-loopback Windows IPv4 interface +/// address in `win_ipv4` so `-p 0.0.0.0:port:cport` answers on both +/// `127.0.0.1:port` (via `wslrelay.exe`) and `:port`. +/// - `::` expands to every non-loopback global Windows IPv6 interface address +/// in `win_ipv6`. +/// - A specific non-loopback `` binds `:port` alone. +pub fn plan_forwards( + wsl_ip: Ipv4Addr, + published: &[PublishedPort], + win_ipv4: &[Ipv4Addr], + win_ipv6: &[Ipv6Addr], +) -> Vec { + // In WSL 2 mirrored or bridged networking mode, `wsl_ip` is itself one of + // the Windows host's interface addresses; skip Windows-side forwarding so + // we never create a self-forwarding loop. + if wsl_ip.is_loopback() || wsl_ip.is_unspecified() || win_ipv4.contains(&wsl_ip) { + return Vec::new(); + } + let mut specs = BTreeSet::new(); + for p in published { + if p.host_port == 0 { + continue; + } + let target_addr = SocketAddr::V4(SocketAddrV4::new(wsl_ip, p.host_port)); + let host_ip = p.host_ip.trim(); + match p.proto.as_str() { + "udp" => { + if host_ip.is_empty() || host_ip == "0.0.0.0" { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, p.host_port)), + target_addr, + }); + } else if host_ip == "::" || host_ip == "[::]" { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, p.host_port, 0, 0)), + target_addr, + }); + } else if let Some(ip) = parse_ip(host_ip) + && ip != IpAddr::V4(wsl_ip) + { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::new(ip, p.host_port), + target_addr, + }); + } + } + "tcp" => { + if host_ip.is_empty() || host_ip == "0.0.0.0" { + for &ip4 in win_ipv4 { + if !ip4.is_loopback() + && !ip4.is_unspecified() + && !ip4.is_multicast() + && !(ip4.octets()[0] == 169 && ip4.octets()[1] == 254) + && ip4 != wsl_ip + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::V4(SocketAddrV4::new(ip4, p.host_port)), + target_addr, + }); + } + } + } else if host_ip == "::" || host_ip == "[::]" { + for &ip6 in win_ipv6 { + if !ip6.is_loopback() + && !ip6.is_unspecified() + && !ip6.is_multicast() + && (ip6.segments()[0] & 0xffc0) != 0xfe80 + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::V6(SocketAddrV6::new(ip6, p.host_port, 0, 0)), + target_addr, + }); + } + } + } else if let Some(ip) = parse_ip(host_ip) + && !ip.is_loopback() + && !ip.is_unspecified() + && !ip.is_multicast() + && ip != IpAddr::V4(wsl_ip) + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::new(ip, p.host_port), + target_addr, + }); + } + } + _ => {} + } + } + specs.into_iter().collect() +} + +/// Whether the initial bytes of an HTTP request on Kiri's pipe represent a +/// container or engine lifecycle mutation that can create, start, stop, or +/// update published ports. +pub fn is_port_affecting_request(head: &[u8]) -> bool { + let line_end = head.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(head.len().min(256)); + let Ok(line) = std::str::from_utf8(&head[..line_end]) else { + return false; + }; + let mut parts = line.split_whitespace(); + let Some(method) = parts.next() else { + return false; + }; + let Some(path) = parts.next() else { + return false; + }; + if !matches!(method, "POST" | "DELETE") { + return false; + } + let path = path.split('?').next().unwrap_or(path); + path.contains("/containers") + || matches!(path, "/kiri/stop" | "/kiri/sleep" | "/kiri/wake") +} + +fn wake_connect_addr(bound: SocketAddr) -> SocketAddr { + match bound { + SocketAddr::V4(v4) if v4.ip().is_unspecified() => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, v4.port())), + SocketAddr::V6(v6) if v6.ip().is_unspecified() => SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, v6.port(), 0, 0)), + other => other, + } +} + +pub struct TcpForwarder { + local_addr: SocketAddr, + stop: Arc, + thread: Option>, +} + +impl TcpForwarder { + pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { + let listener = TcpListener::bind(bind_addr)?; + listener.set_nonblocking(true)?; + let local_addr = listener.local_addr()?; + let stop = Arc::new(AtomicBool::new(false)); + let stop_loop = stop.clone(); + let thread = std::thread::Builder::new() + .name(format!("kiri-win-tcp-{}", local_addr.port())) + .spawn(move || tcp_accept_loop(listener, target_addr, stop_loop))?; + Ok(TcpForwarder { + local_addr, + stop, + thread: Some(thread), + }) + } + + #[cfg(test)] + pub fn local_addr(&self) -> SocketAddr { + self.local_addr + } + + pub fn stop(mut self) { + self.stop_inner(); + } + + fn stop_inner(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +impl Drop for TcpForwarder { + fn drop(&mut self) { + self.stop_inner(); + } +} + +fn tcp_accept_loop(listener: TcpListener, target_addr: SocketAddr, stop: Arc) { + while !stop.load(Ordering::SeqCst) { + let (client, _) = match listener.accept() { + Ok(pair) => pair, + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + std::thread::sleep(TCP_ACCEPT_POLL); + continue; + } + Err(_) => { + if stop.load(Ordering::SeqCst) { + break; + } + std::thread::sleep(TCP_ACCEPT_POLL); + continue; + } + }; + if stop.load(Ordering::SeqCst) { + break; + } + let _ = client.set_nonblocking(false); + let _ = std::thread::Builder::new().name("kiri-win-tcp-conn".into()).spawn(move || { + let _ = relay_tcp_conn(client, target_addr); + }); + } +} + +fn relay_tcp_conn(client: TcpStream, target_addr: SocketAddr) -> io::Result<()> { + let backend = TcpStream::connect_timeout(&target_addr, TCP_CONNECT_TIMEOUT)?; + let _ = client.set_nodelay(true); + let _ = backend.set_nodelay(true); + let mut client_read = client.try_clone()?; + let mut backend_write = backend.try_clone()?; + let up = std::thread::Builder::new().name("kiri-win-tcp-up".into()).spawn(move || { + let how = if copy_stream(&mut client_read, &mut backend_write).is_ok() { + Shutdown::Write + } else { + Shutdown::Both + }; + let _ = backend_write.shutdown(how); + })?; + let mut backend_read = backend; + let mut client_write = client; + let how = if copy_stream(&mut backend_read, &mut client_write).is_ok() { + Shutdown::Write + } else { + Shutdown::Both + }; + let _ = client_write.shutdown(how); + let _ = up.join(); + Ok(()) +} + +fn copy_stream(from: &mut impl Read, to: &mut impl Write) -> io::Result<()> { + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = from.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + to.write_all(&buf[..n])?; + } +} + +struct UdpClientSession { + backend: UdpSocket, + last: Arc>, + stop: Arc, + reader: JoinHandle<()>, +} + +impl UdpClientSession { + fn open(listener: &UdpSocket, target_addr: SocketAddr, client_addr: SocketAddr) -> io::Result { + let bind_any = if target_addr.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) + }; + let backend = UdpSocket::bind(bind_any)?; + disable_udp_connreset(&backend); + backend.connect(target_addr)?; + let backend_read = backend.try_clone()?; + backend_read.set_read_timeout(Some(UDP_POLL))?; + let reply_sock = listener.try_clone()?; + let last = Arc::new(Mutex::new(Instant::now())); + let last_r = last.clone(); + let stop = Arc::new(AtomicBool::new(false)); + let stop_r = stop.clone(); + let reader = std::thread::Builder::new().name("kiri-win-udp-reply".into()).spawn(move || { + let mut rbuf = vec![0u8; 65_536]; + while !stop_r.load(Ordering::Relaxed) { + match backend_read.recv(&mut rbuf) { + Ok(n) => { + *last_r.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); + let _ = reply_sock.send_to(&rbuf[..n], client_addr); + } + Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::Interrupted) => { + if last_r.lock().unwrap_or_else(PoisonError::into_inner).elapsed() >= UDP_IDLE { + break; + } + } + Err(_) => break, + } + } + })?; + Ok(UdpClientSession { + backend, + last, + stop, + reader, + }) + } + + fn last_active(&self) -> Instant { + *self.last.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn touch(&self) { + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); + } + + fn close(self) { + self.stop.store(true, Ordering::SeqCst); + } +} + +impl Drop for UdpClientSession { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + } +} + +pub struct UdpForwarder { + local_addr: SocketAddr, + stop: Arc, + thread: Option>, +} + +impl UdpForwarder { + pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { + let listener = UdpSocket::bind(bind_addr)?; + disable_udp_connreset(&listener); + listener.set_read_timeout(Some(UDP_POLL))?; + let local_addr = listener.local_addr()?; + let stop = Arc::new(AtomicBool::new(false)); + let stop_loop = stop.clone(); + let thread = std::thread::Builder::new() + .name(format!("kiri-win-udp-{}", local_addr.port())) + .spawn(move || udp_forward_loop(listener, target_addr, stop_loop))?; + Ok(UdpForwarder { + local_addr, + stop, + thread: Some(thread), + }) + } + + #[cfg(test)] + pub fn local_addr(&self) -> SocketAddr { + self.local_addr + } + + pub fn stop(mut self) { + self.stop_inner(); + } + + fn stop_inner(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let wake_target = wake_connect_addr(self.local_addr); + let bind_any = if wake_target.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) + }; + if let Ok(waker) = UdpSocket::bind(bind_any) { + let _ = waker.send_to(&[], wake_target); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +impl Drop for UdpForwarder { + fn drop(&mut self) { + self.stop_inner(); + } +} + +fn udp_forward_loop(listener: UdpSocket, target_addr: SocketAddr, stop: Arc) { + let mut sessions: HashMap = HashMap::new(); + let mut buf = vec![0u8; 65_536]; + let mut last_reap = Instant::now(); + while !stop.load(Ordering::SeqCst) { + match listener.recv_from(&mut buf) { + Ok((len, peer)) => { + if stop.load(Ordering::SeqCst) { + break; + } + let stale = sessions.get(&peer).is_some_and(|s| s.reader.is_finished()); + if stale && let Some(old) = sessions.remove(&peer) { + old.close(); + } + if !sessions.contains_key(&peer) { + if sessions.len() >= MAX_UDP_SESSIONS + && let Some(oldest) = sessions.iter().min_by_key(|(_, s)| s.last_active()).map(|(k, _)| *k) + && let Some(old) = sessions.remove(&oldest) + { + old.close(); + } + match UdpClientSession::open(&listener, target_addr, peer) { + Ok(s) => { + sessions.insert(peer, s); + } + Err(_) => continue, + } + } + if let Some(s) = sessions.get(&peer) { + s.touch(); + if s.backend.send(&buf[..len]).is_err() + && let Some(dead) = sessions.remove(&peer) + { + dead.close(); + } + } + } + Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::ConnectionReset | io::ErrorKind::Interrupted) => {} + Err(_) => { + if stop.load(Ordering::SeqCst) { + break; + } + } + } + if last_reap.elapsed() >= Duration::from_secs(1) { + last_reap = Instant::now(); + let expired: Vec = sessions + .iter() + .filter(|(_, s)| s.last_active().elapsed() >= UDP_IDLE || s.reader.is_finished()) + .map(|(k, _)| *k) + .collect(); + for k in expired { + if let Some(s) = sessions.remove(&k) { + s.close(); + } + } + } + } + for (_, s) in sessions.drain() { + s.close(); + } +} + +/// Disables WinSock's `SIO_UDP_CONNRESET` on `sock` so an ICMP Port Unreachable +/// from one closed client does not make the next `recv_from` return `WSAECONNRESET`. +#[cfg(windows)] +fn disable_udp_connreset(sock: &UdpSocket) { + use std::os::windows::io::AsRawSocket; + use windows_sys::Win32::Networking::WinSock::{WSAIoctl, SOCKET}; + const SIO_UDP_CONNRESET: u32 = 0x9800_000C; + let enable: u32 = 0; + let mut bytes_returned: u32 = 0; + // SAFETY: valid socket handle and 4-byte boolean buffer for SIO_UDP_CONNRESET. + unsafe { + let _ = WSAIoctl( + sock.as_raw_socket() as SOCKET, + SIO_UDP_CONNRESET, + (&enable as *const u32).cast(), + std::mem::size_of::() as u32, + std::ptr::null_mut(), + 0, + &mut bytes_returned, + std::ptr::null_mut(), + None, + ); + } +} + +#[cfg(not(windows))] +fn disable_udp_connreset(_sock: &UdpSocket) {} + +#[cfg(windows)] +mod runtime { + use super::*; + use std::collections::HashSet; + use std::os::windows::io::AsRawSocket; + use std::sync::Condvar; + use serde_json::json; + use windows_sys::Win32::Networking::WinSock::{ + AF_INET, AF_INET6, SIO_ADDRESS_LIST_QUERY, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ADDRESS_LIST, WSAIoctl, + }; + + const RESYNC_INTERVAL: Duration = Duration::from_secs(3); + + enum ActiveForwarder { + Tcp(TcpForwarder), + Udp(UdpForwarder), + } + + impl ActiveForwarder { + fn stop(self) { + match self { + ActiveForwarder::Tcp(f) => f.stop(), + ActiveForwarder::Udp(f) => f.stop(), + } + } + } + + static ACTIVE: AtomicBool = AtomicBool::new(false); + static WAKE: std::sync::LazyLock<(Mutex, Condvar)> = std::sync::LazyLock::new(|| (Mutex::new(false), Condvar::new())); + static SYNC_LOCK: Mutex<()> = Mutex::new(()); + static LAST_SYNC: Mutex> = Mutex::new(None); + static FORWARDERS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + + /// Queries WinSock `SIO_ADDRESS_LIST_QUERY` for all active local IPv4 and + /// IPv6 interface addresses on the Windows host. + pub fn query_windows_host_ips() -> (Vec, Vec, Vec) { + let mut all = BTreeSet::from(["127.0.0.1".to_owned(), "::1".to_owned()]); + let mut v4_set = BTreeSet::new(); + let mut v6_set = BTreeSet::new(); + + if let Ok(sock4) = UdpSocket::bind("127.0.0.1:0") { + let mut buf = vec![0usize; 2048]; + let cap = (buf.len() * std::mem::size_of::()) as u32; + let mut returned = 0u32; + // SAFETY: `buf` is usize-aligned and sized to `cap` bytes for SOCKET_ADDRESS_LIST. + let rc = unsafe { + WSAIoctl( + sock4.as_raw_socket() as SOCKET, + SIO_ADDRESS_LIST_QUERY, + std::ptr::null(), + 0, + buf.as_mut_ptr().cast(), + cap, + &mut returned, + std::ptr::null_mut(), + None, + ) + }; + if rc == 0 && (returned as usize) >= std::mem::size_of::() { + // SAFETY: WSAIoctl succeeded and filled ` SOCKET_ADDRESS_LIST` inside `buf`. + unsafe { + let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); + let count = (list.iAddressCount.max(0) as usize).min(256); + let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); + for entry in addrs { + if !entry.lpSockaddr.is_null() + && (entry.iSockaddrLength as usize) >= std::mem::size_of::() + && (*entry.lpSockaddr).sa_family == AF_INET + { + let sin = &*(entry.lpSockaddr as *const SOCKADDR_IN); + let ip = Ipv4Addr::from(sin.sin_addr.S_un.S_addr.to_ne_bytes()); + if !ip.is_unspecified() && !ip.is_multicast() { + all.insert(ip.to_string()); + if !ip.is_loopback() && !(ip.octets()[0] == 169 && ip.octets()[1] == 254) { + v4_set.insert(ip); + } + } + } + } + } + } + } + + if let Ok(sock6) = UdpSocket::bind("[::1]:0") { + let mut buf = vec![0usize; 2048]; + let cap = (buf.len() * std::mem::size_of::()) as u32; + let mut returned = 0u32; + // SAFETY: `buf` is usize-aligned and sized to `cap` bytes for SOCKET_ADDRESS_LIST. + let rc = unsafe { + WSAIoctl( + sock6.as_raw_socket() as SOCKET, + SIO_ADDRESS_LIST_QUERY, + std::ptr::null(), + 0, + buf.as_mut_ptr().cast(), + cap, + &mut returned, + std::ptr::null_mut(), + None, + ) + }; + if rc == 0 && (returned as usize) >= std::mem::size_of::() { + // SAFETY: WSAIoctl succeeded and filled `SOCKET_ADDRESS_LIST` inside `buf`. + unsafe { + let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); + let count = (list.iAddressCount.max(0) as usize).min(256); + let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); + for entry in addrs { + if !entry.lpSockaddr.is_null() + && (entry.iSockaddrLength as usize) >= std::mem::size_of::() + && (*entry.lpSockaddr).sa_family == AF_INET6 + { + let sin6 = &*(entry.lpSockaddr as *const SOCKADDR_IN6); + let ip = Ipv6Addr::from(sin6.sin6_addr.u.Byte); + if !ip.is_unspecified() && !ip.is_multicast() { + all.insert(ip.to_string()); + if !ip.is_loopback() && (ip.segments()[0] & 0xffc0) != 0xfe80 { + v6_set.insert(ip); + } + } + } + } + } + } + } + + ( + all.into_iter().collect(), + v4_set.into_iter().collect(), + v6_set.into_iter().collect(), + ) + } + + fn clear_all_forwarders() { + let old: Vec = FORWARDERS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .drain() + .map(|(_, f)| f) + .collect(); + for f in old { + f.stop(); + } + } + + /// Synchronizes Windows host interface IPs and published container port + /// forwarders with the WSL daemon right now. + pub fn sync_now() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let _guard = SYNC_LOCK.lock().unwrap_or_else(PoisonError::into_inner); + let (all_ips, win_v4, win_v6) = query_windows_host_ips(); + let body = json!({ "host_ips": all_ips }); + let resp = match crate::client::request_within("POST", "/kiri/win-ports", Some(&body), true, Some(Duration::from_secs(3))) { + Ok(r) => r, + // Do not tear down active port forwarders on a transient HTTP + // read timeout when WSL is still running and busy. + Err(e) if matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => return, + Err(_) => { + clear_all_forwarders(); + return; + } + }; + if !resp.ok() { + if resp.status == 503 || resp.error().contains("stopped") || resp.error().contains("did not start") { + clear_all_forwarders(); + } + return; + } + *LAST_SYNC.lock().unwrap_or_else(PoisonError::into_inner) = Some(Instant::now()); + let payload = resp.json(); + let Some(wsl_ip) = payload["wsl_ip"].as_str().and_then(|s| s.parse::().ok()) else { + clear_all_forwarders(); + return; + }; + let mut published = Vec::new(); + for item in payload["ports"].as_array().into_iter().flatten() { + let Some(proto) = item["proto"].as_str() else { continue }; + let host_ip = item["host_ip"].as_str().unwrap_or("").to_owned(); + let Some(host_port) = item["host_port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { continue }; + published.push(PublishedPort { + proto: proto.to_owned(), + host_ip, + host_port, + }); + } + let want = plan_forwards(wsl_ip, &published, &win_v4, &win_v6); + let want_set: HashSet = want.iter().cloned().collect(); + + let to_stop: Vec = { + let mut active = FORWARDERS.lock().unwrap_or_else(PoisonError::into_inner); + let remove_keys: Vec = active.keys().filter(|k| !want_set.contains(*k)).cloned().collect(); + remove_keys.into_iter().filter_map(|k| active.remove(&k)).collect() + }; + for f in to_stop { + f.stop(); + } + + let mut active = FORWARDERS.lock().unwrap_or_else(PoisonError::into_inner); + for spec in want { + if active.contains_key(&spec) { + continue; + } + let started = match spec.proto { + Proto::Tcp => TcpForwarder::start(spec.bind_addr, spec.target_addr).map(ActiveForwarder::Tcp), + Proto::Udp => UdpForwarder::start(spec.bind_addr, spec.target_addr).map(ActiveForwarder::Udp), + }; + match started { + Ok(fwd) => { + active.insert(spec, fwd); + } + Err(e) => { + crate::serve::log(&format!("ports: could not bind {:?} {} -> {}: {e}", spec.proto, spec.bind_addr, spec.target_addr)); + } + } + } + } + + /// Ensures the WSL daemon has received the Windows host's current interface + /// IPs before a container create/start request is processed. + pub fn before_container_op() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let stale = LAST_SYNC + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_none_or(|t| t.elapsed() >= Duration::from_secs(2)); + if stale { + sync_now(); + } + } + + /// Synchronizes Windows TCP and UDP port forwarders immediately after a + /// container start/stop/remove/ports request completes, before the HTTP + /// response returns to the Docker client. + pub fn after_container_op() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + sync_now(); + } + + /// Wakes the background port forwarder thread to synchronize with WSL. + pub fn notify() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let (m, cv) = &*WAKE; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + + /// Starts the background Windows port forwarder synchronization loop. + pub fn start() { + if ACTIVE.swap(true, Ordering::SeqCst) { + return; + } + let _ = std::thread::Builder::new().name("kiri-win-ports".into()).spawn(|| { + loop { + sync_now(); + let (m, cv) = &*WAKE; + let mut signaled = m.lock().unwrap_or_else(PoisonError::into_inner); + if !*signaled { + let (g, _) = cv.wait_timeout(signaled, RESYNC_INTERVAL).unwrap_or_else(PoisonError::into_inner); + signaled = g; + } + *signaled = false; + } + }); + } +} + +#[cfg(windows)] +pub use runtime::{after_container_op, before_container_op, notify, start, sync_now}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plans_udp_and_non_loopback_tcp_forwards() { + let wsl_ip = Ipv4Addr::new(198, 51, 100, 107); + let win_v4 = vec![ + Ipv4Addr::new(192, 0, 2, 50), + Ipv4Addr::new(198, 51, 100, 1), + Ipv4Addr::new(169, 254, 10, 20), // link-local APIPA ignored for 0.0.0.0 expansion + ]; + let win_v6 = vec![ + "2001:db8::42".parse::().unwrap(), + "fe80::1".parse::().unwrap(), // link-local ignored for :: expansion + ]; + let published = vec![ + // -p 18120:18120/udp (produces 0.0.0.0 and :: in daemon) + PublishedPort { proto: "udp".into(), host_ip: "0.0.0.0".into(), host_port: 18120 }, + PublishedPort { proto: "udp".into(), host_ip: "::".into(), host_port: 18120 }, + // -p 127.0.0.1:18121:18121/udp + PublishedPort { proto: "udp".into(), host_ip: "127.0.0.1".into(), host_port: 18121 }, + // -p 192.0.2.50:18122:18122/udp + PublishedPort { proto: "udp".into(), host_ip: "192.0.2.50".into(), host_port: 18122 }, + // -p 127.0.0.1:18079:8080/tcp (left to wslrelay.exe) + PublishedPort { proto: "tcp".into(), host_ip: "127.0.0.1".into(), host_port: 18079 }, + PublishedPort { proto: "tcp".into(), host_ip: "::1".into(), host_port: 18079 }, + // -p 192.0.2.50:18080:8080/tcp (specific Windows host IP only) + PublishedPort { proto: "tcp".into(), host_ip: "192.0.2.50".into(), host_port: 18080 }, + // -p 0.0.0.0:18082:8080/tcp (expands to non-loopback Windows IPv4 interfaces) + PublishedPort { proto: "tcp".into(), host_ip: "0.0.0.0".into(), host_port: 18082 }, + PublishedPort { proto: "tcp".into(), host_ip: "::".into(), host_port: 18082 }, + ]; + let specs = plan_forwards(wsl_ip, &published, &win_v4, &win_v6); + let expected = vec![ + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "192.0.2.50:18080".parse().unwrap(), + target_addr: "198.51.100.107:18080".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "192.0.2.50:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "198.51.100.1:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "[2001:db8::42]:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "0.0.0.0:18120".parse().unwrap(), + target_addr: "198.51.100.107:18120".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "127.0.0.1:18121".parse().unwrap(), + target_addr: "198.51.100.107:18121".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "192.0.2.50:18122".parse().unwrap(), + target_addr: "198.51.100.107:18122".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "[::]:18120".parse().unwrap(), + target_addr: "198.51.100.107:18120".parse().unwrap(), + }, + ]; + assert_eq!(specs, expected); + } + + #[test] + fn skips_self_forwarding_in_mirrored_or_bridged_wsl_mode() { + let mirrored_ip = Ipv4Addr::new(192, 0, 2, 50); + let win_v4 = vec![mirrored_ip, Ipv4Addr::new(203, 0, 113, 10)]; + let win_v6 = vec!["2001:db8::42".parse::().unwrap()]; + let published = vec![ + PublishedPort { proto: "udp".into(), host_ip: "0.0.0.0".into(), host_port: 18120 }, + PublishedPort { proto: "udp".into(), host_ip: "127.0.0.1".into(), host_port: 18121 }, + PublishedPort { proto: "tcp".into(), host_ip: "0.0.0.0".into(), host_port: 18082 }, + PublishedPort { proto: "tcp".into(), host_ip: "192.0.2.50".into(), host_port: 18080 }, + ]; + assert!(plan_forwards(mirrored_ip, &published, &win_v4, &win_v6).is_empty()); + } + + #[test] + fn detects_port_affecting_http_requests() { + assert!(is_port_affecting_request(b"POST /v1.47/containers/create HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_port_affecting_request(b"POST /containers/abc123/start HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /containers/abc123/stop?t=10 HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"DELETE /v1.47/containers/abc123?force=1 HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /kiri/containers/abc123/ports HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /kiri/stop HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"GET /containers/json?all=1 HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"GET /_ping HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"POST /kiri/win-ports HTTP/1.1\r\n")); + } + + #[test] + fn udp_forwarder_relays_datagrams_and_replies_per_client_session() { + // Stand-in for the container's UDP echo service reachable on WSL's eth0 IP. + let backend = UdpSocket::bind("127.0.0.1:0").unwrap(); + backend.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let echo_thread = std::thread::spawn(move || { + let mut buf = [0u8; 1024]; + let mut seen_peers = Vec::new(); + for _ in 0..2 { + let (n, peer) = backend.recv_from(&mut buf).unwrap(); + seen_peers.push(peer); + let mut reply = b"echo:".to_vec(); + reply.extend_from_slice(&buf[..n]); + backend.send_to(&reply, peer).unwrap(); + } + seen_peers + }); + + let fwd = UdpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + let fwd_addr = fwd.local_addr(); + + let client1 = UdpSocket::bind("127.0.0.1:0").unwrap(); + client1.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let client2 = UdpSocket::bind("127.0.0.1:0").unwrap(); + client2.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + + client1.send_to(b"one", fwd_addr).unwrap(); + client2.send_to(b"two", fwd_addr).unwrap(); + + let mut r1 = [0u8; 64]; + let (n1, from1) = client1.recv_from(&mut r1).unwrap(); + assert_eq!(&r1[..n1], b"echo:one"); + assert_eq!(from1, fwd_addr); + + let mut r2 = [0u8; 64]; + let (n2, from2) = client2.recv_from(&mut r2).unwrap(); + assert_eq!(&r2[..n2], b"echo:two"); + assert_eq!(from2, fwd_addr); + + // Two distinct clients get distinct backend session sockets. + let peers = echo_thread.join().unwrap(); + assert_ne!(peers[0], peers[1]); + fwd.stop(); + } + + #[test] + fn tcp_forwarder_relays_streams_and_releases_port_on_stop() { + let backend = TcpListener::bind("127.0.0.1:0").unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut s, _) = backend.accept().unwrap(); + let mut req = Vec::new(); + s.read_to_end(&mut req).unwrap(); + s.write_all(b"reply:").unwrap(); + s.write_all(&req).unwrap(); + let _ = s.shutdown(Shutdown::Write); + }); + + let fwd = TcpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + let fwd_addr = fwd.local_addr(); + + let mut client = TcpStream::connect(fwd_addr).unwrap(); + client.write_all(b"hello-win-tcp").unwrap(); + client.shutdown(Shutdown::Write).unwrap(); + let mut resp = Vec::new(); + client.read_to_end(&mut resp).unwrap(); + assert_eq!(resp, b"reply:hello-win-tcp"); + + server.join().unwrap(); + fwd.stop(); + // Port is immediately free to bind again after stop(). + let rebound = TcpListener::bind(fwd_addr); + assert!(rebound.is_ok(), "port should be released after TcpForwarder::stop()"); + } +} diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 3e0ca7855..8c29923f9 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -1865,13 +1865,22 @@ fn serve_shared(hub: &Hub, pipe: Arc) { // Whether the client's request has come, and is a HEAD: a refusal // waits for it (see `refuse_new`). let request = Arc::new(Arrival::default()); - let (p, b, w, r) = (pipe.clone(), bridge.clone(), window.clone(), request.clone()); - let writer = thread::spawn(move || to_client(&p, &rx, &queued, &b, w.as_deref().map(|w| (id, w)), &r)); + let port_op = Arc::new(AtomicBool::new(false)); + let (p, b, w, r, po) = (pipe.clone(), bridge.clone(), window.clone(), request.clone(), port_op.clone()); + 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 end = loop { match pipe.read(&mut buf) { Ok(0) => break EOF, Ok(n) => { + if first_chunk { + first_chunk = false; + if crate::ports::is_port_affecting_request(&buf[..n]) { + port_op.store(true, Ordering::SeqCst); + crate::ports::before_container_op(); + } + } request.set(is_head(&buf[..n])); // Out of credit with the client gone (nothing to read its // reply), or the connection closed: stop. @@ -1906,6 +1915,9 @@ fn serve_shared(hub: &Hub, pipe: Arc) { }); } let replies_ended = writer.join().unwrap_or(false); + if port_op.load(Ordering::Relaxed) { + crate::ports::notify(); + } let aborted = pipe.is_aborted(); if end == EOF && replies_ended && !aborted { linger(pipe); @@ -1945,7 +1957,7 @@ fn gave_up(waited: Duration) -> bool { /// bridge (`credit`) as they go when it does flow control. True if they /// ended with EOF, or the client was told why the engine could not serve /// it (once its `request` had come). -fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &Bridge, credit: Option<(u32, &Window)>, request: &Arrival) -> bool { +fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &Bridge, credit: Option<(u32, &Window)>, request: &Arrival, port_op: &AtomicBool) -> bool { let mut done = 0usize; let mut answered = false; loop { @@ -1982,6 +1994,9 @@ fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &B // that is EOF reads as one only with no data queued ahead of // it; behind data it is merged away and the client waits on. Reply::Eof => { + if port_op.load(Ordering::Relaxed) { + crate::ports::after_container_op(); + } pipe.flush(); return !pipe.is_aborted() && pipe.write(&[]).is_ok(); } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index f1ff7e6ab..6982f00ac 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -276,6 +276,8 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea ("POST", "/kiri/builder") => return reply(w, super::builder::set_settings(req).map(|()| super::builder::settings_report(engine)), 200), ("GET", "/kiri/watch-roots") => return reply(w, Ok(watch_roots(engine)), 200), ("POST", "/kiri/fs-events") => return reply(w, fs_events(req, engine), 204), + ("GET", "/kiri/win-ports") => return reply(w, Ok(win_ports(engine)), 200), + ("POST", "/kiri/win-ports") => return reply(w, sync_win_ports(req, engine), 200), ("GET", "/images/json") => return reply(w, images(req, engine), 200), ("POST", "/images/create") if req.query("fromSrc").is_some_and(|s| !s.is_empty()) => return image_import(req, engine, w, r), ("POST", "/images/create") => return pull(req, engine, w), @@ -1235,6 +1237,31 @@ fn fs_events(req: &Request, engine: &Engine) -> Result { Ok(Value::Null) } +/// Active published ports and WSL's internal `eth0` IPv4 address for +/// `kiri-win`'s Windows UDP and host-IP port forwarder. +fn win_ports(engine: &Engine) -> Value { + let wsl_ip = super::ports::wsl_ipv4().map(|ip| ip.to_string()); + let ports: Vec = engine + .published_ports() + .into_iter() + .map(|p| json!({"proto": p.proto, "host_ip": p.host_ip, "host_port": p.host_port})) + .collect(); + json!({ + "wsl_ip": wsl_ip, + "ports": ports, + }) +} + +fn sync_win_ports(req: &Request, engine: &Engine) -> Result { + if !req.body.is_empty() { + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + if let Some(ips) = strings(&body["host_ips"]) { + super::ports::set_windows_host_ips(&ips); + } + } + Ok(win_ports(engine)) +} + /// A registry client with the credentials the CLI sent, if any. fn client_for(req: &Request) -> Client { Client::new().with_credentials(req.header("x-registry-auth").and_then(kiri_image::Credentials::from_header)) diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 2cf3dbae5..35a8ae1b2 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -2294,6 +2294,29 @@ impl Engine { out } + /// Active published port bindings across all running containers, for + /// `kiri-win`'s Windows UDP and host-IP port forwarder (`/kiri/win-ports`). + pub fn published_ports(&self) -> Vec { + let st = self.lock(); + let mut out = Vec::new(); + for c in st.containers.values() { + if c.status != Status::Running { + continue; + } + let Some(fw) = &c.forwards else { continue }; + for (b, host_ip, host_port) in &fw.bound { + out.push(super::ports::PublishedPort { + proto: b.proto.clone(), + host_ip: host_ip.clone(), + host_port: *host_port, + }); + } + } + out.sort(); + out.dedup(); + out + } + /// The WSL drive bind sources (`/mnt/` or `/mnt//...`) of /// running containers, under `automount_root` (e.g. `/mnt/`). pub fn wsl_bind_sources(&self, automount_root: &str) -> Vec { diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index f41ce1887..9937ec92b 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -5,7 +5,7 @@ #[cfg(target_os = "linux")] pub mod access; mod api; -mod binds; +pub(crate) mod binds; mod builder; mod caller; mod daemon_json; diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index b368848da..7f4d3637a 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -866,21 +866,29 @@ fn free_subnet_with(taken: &[([u8; 4], u8)], default_bridge: bool, host: &[HostN /// A subnet the host itself is on, outside Kiri's bridges: an on-link route /// or an interface's address, and the interface it is on. Or one Docker /// will take back when it starts (`docker_saved`): not on the host now. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Eq)] struct HostNet { net: u32, mask: u32, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + addr: [u8; 4], dev: String, saved: bool, } +impl PartialEq for HostNet { + fn eq(&self, other: &Self) -> bool { + (self.net, self.mask, &self.dev, self.saved) == (other.net, other.mask, &other.dev, other.saved) + } +} + fn mask4(prefix: u8) -> u32 { if prefix == 0 { 0 } else { u32::MAX << (32 - prefix as u32) } } impl HostNet { fn new(dev: &str, addr: [u8; 4], mask: u32) -> HostNet { - HostNet { net: u32::from_be_bytes(addr) & mask, mask, dev: dev.to_owned(), saved: false } + HostNet { net: u32::from_be_bytes(addr) & mask, mask, addr, dev: dev.to_owned(), saved: false } } /// Shares any address with `subnet`: a new subnet keeps clear of it. @@ -1038,6 +1046,16 @@ fn host_networks() -> Vec { Vec::new() } +#[cfg(target_os = "linux")] +pub(super) fn host_interface_ipv4() -> Vec<(String, std::net::Ipv4Addr)> { + host_addrs().into_iter().map(|h| (h.dev, std::net::Ipv4Addr::from(h.addr))).collect() +} + +#[cfg(not(target_os = "linux"))] +pub(super) fn host_interface_ipv4() -> Vec<(String, std::net::Ipv4Addr)> { + Vec::new() +} + /// The subnets this machine's interfaces have addresses on, outside Kiri's /// bridges and loopback. An address stays on an interface whose route is /// gone (a `noprefixroute` one) or not yet there, so this catches what the diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index 38994a17d..9934901ec 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -197,6 +197,225 @@ pub struct Binding { pub host_port: u16, } +/// One active published port binding reported to `kiri-win` (`/kiri/win-ports`). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct PublishedPort { + pub proto: String, + pub host_ip: String, + pub host_port: u16, +} + +static WINDOWS_HOST_IPS: Mutex>> = Mutex::new(None); +static LAST_IPCONFIG_PROBE: Mutex> = Mutex::new(None); + +/// Parses a bare or bracketed IPv4/IPv6 host address, stripping any `%scope` +/// suffix and canonicalizing IPv4-mapped IPv6 addresses. +pub fn parse_host_ip(s: &str) -> Option { + let bare = s.trim().strip_prefix('[').and_then(|i| i.strip_suffix(']')).unwrap_or(s.trim()); + let bare = bare.split('%').next().unwrap_or(bare); + bare.parse::().ok().map(|a| a.to_canonical()) +} + +/// Records the Windows host interface IPs pushed by `kiri-win` and persists +/// them in the daemon state directory when the list changes so container +/// starts after a daemon restart still recognize Windows interface addresses. +pub fn set_windows_host_ips(ips: &[String]) { + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + for s in ips { + if let Some(ip) = parse_host_ip(s) + && !ip.is_unspecified() + && !ip.is_multicast() + { + set.insert(ip); + } + } + { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = load_persisted_windows_host_ips(); + } + if guard.as_ref() == Some(&set) { + return; + } + *guard = Some(set.clone()); + } + if let Ok(dir) = super::state_dir() { + let list: Vec = set.iter().map(ToString::to_string).collect(); + if let Ok(bytes) = serde_json::to_vec(&list) { + let tmp = dir.join("win-host-ips.json.tmp"); + let path = dir.join("win-host-ips.json"); + if std::fs::write(&tmp, bytes).is_ok() { + let _ = std::fs::rename(&tmp, &path); + } + } + } +} + +fn load_persisted_windows_host_ips() -> Option> { + let path = super::state_dir().ok()?.join("win-host-ips.json"); + let bytes = std::fs::read(path).ok()?; + let list: Vec = serde_json::from_slice(&bytes).ok()?; + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + for s in &list { + if let Some(ip) = parse_host_ip(s) + && !ip.is_unspecified() + && !ip.is_multicast() + { + set.insert(ip); + } + } + Some(set) +} + +/// Extracts Windows host interface IPv4 and IPv6 addresses from `ipconfig.exe` +/// output in a locale-independent way: in every Windows locale, each adapter's +/// IPv4 address line is immediately followed by its `255.x.x.x` subnet mask +/// line, whereas the default gateway comes after the subnet mask. +pub fn parse_ipconfig_addrs(output: &str) -> BTreeSet { + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + let mut pending_v4: Option = None; + let mut seen_mask_in_section = false; + for raw_line in output.lines() { + let line = raw_line.trim(); + if line.is_empty() { + continue; + } + // Adapter section header (e.g. `Ethernet adapter vEthernet (WSL):`). + if line.ends_with(':') && !line.contains(". :") && !line.contains(" : ") { + pending_v4 = None; + seen_mask_in_section = false; + continue; + } + let val = match line.split_once(": ") { + Some((_, right)) => right.trim(), + None => match line.strip_suffix(':') { + Some(_) => continue, + None => line, + }, + }; + let token = val.split(['(', '%', ' ']).next().unwrap_or("").trim(); + if token.is_empty() { + continue; + } + if let Ok(v4) = token.parse::() { + if v4.octets()[0] == 255 { + seen_mask_in_section = true; + if let Some(interface_ip) = pending_v4.take() + && !interface_ip.is_unspecified() + && !interface_ip.is_multicast() + { + set.insert(IpAddr::V4(interface_ip)); + } + } else { + pending_v4 = Some(v4); + } + } else if !seen_mask_in_section + && let Some(IpAddr::V6(v6)) = parse_host_ip(token) + && !v6.is_unspecified() + && !v6.is_multicast() + { + set.insert(IpAddr::V6(v6)); + } + } + set +} + +fn probe_windows_host_ips_from_wsl() -> Option> { + let wsl = super::binds::wsl()?; + { + let mut last = LAST_IPCONFIG_PROBE.lock().unwrap_or_else(|e| e.into_inner()); + if last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) { + return None; + } + *last = Some(Instant::now()); + } + let ipconfig = format!("{}c/Windows/System32/ipconfig.exe", wsl.root); + let out = std::process::Command::new(ipconfig) + .stderr(std::process::Stdio::null()) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stdout); + let parsed = parse_ipconfig_addrs(&text); + (parsed.len() > 2).then_some(parsed) +} + +/// Whether `ip` is a valid interface address on the Windows host when running +/// inside WSL 2. +pub fn is_windows_host_ip(ip: &str) -> bool { + let Some(addr) = parse_host_ip(ip) else { + return false; + }; + if addr.is_unspecified() || addr.is_multicast() { + return false; + } + { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = load_persisted_windows_host_ips(); + } + if let Some(set) = guard.as_ref() + && set.contains(&addr) + { + return true; + } + } + if let Some(probed) = probe_windows_host_ips_from_wsl() { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + let set = guard.get_or_insert_with(BTreeSet::new); + set.extend(probed); + return set.contains(&addr); + } + false +} + +/// The WSL 2 distro's primary internal IPv4 address (`eth0` / default route +/// interface), which `kiri-win` on Windows forwards TCP and UDP ports to. +pub fn wsl_ipv4() -> Option { + let default_iface = std::fs::read_to_string("/proc/net/route") + .ok() + .and_then(|routes| { + routes.lines().skip(1).find_map(|l| { + let mut f = l.split_whitespace(); + let iface = f.next()?; + let dst = f.next()?; + (dst == "00000000").then(|| iface.to_owned()) + }) + }); + let addrs: Vec<(String, std::net::Ipv4Addr)> = super::network::host_interface_ipv4() + .into_iter() + .filter(|(_, ip)| !ip.is_loopback() && !ip.is_unspecified()) + .collect(); + if let Some(def) = default_iface.as_deref() + && let Some((_, ip)) = addrs.iter().find(|(n, _)| n == def) + { + return Some(*ip); + } + if let Some((_, ip)) = addrs.iter().find(|(n, _)| n == "eth0") { + return Some(*ip); + } + addrs + .into_iter() + .find(|(n, _)| { + !n.starts_with("lo") + && !n.starts_with("kiri") + && !n.starts_with("veth") + && !n.starts_with("docker") + && !n.starts_with("br-") + && !n.starts_with("cni") + && !n.starts_with("flannel") + }) + .map(|(_, ip)| ip) +} + /// A running forward for one container; dropping it closes every listener. pub struct Forwards { wake: Vec, @@ -402,8 +621,18 @@ fn holder_in(lsof: &str) -> Option { /// Binds every port first (so a clash fails the start cleanly), then starts /// one accept thread per listener. pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4]) -> io::Result { - let mut listeners = Vec::with_capacity(bindings.len()); - let mut udp = Vec::new(); + let in_wsl = super::binds::wsl().is_some(); + // In WSL 2 NAT mode, `wsl_ipv4()` is WSL's dedicated internal `eth0` IP. + // In mirrored/bridged mode, `wsl_ipv4()` is itself one of the Windows host + // interface IPs; filter it out so we never bind an extra LAN socket for a + // loopback-only (`-p 127.0.0.1:port/udp`) binding. + let wsl_eth0 = if in_wsl { + wsl_ipv4().filter(|ip| !is_windows_host_ip(&ip.to_string())) + } else { + None + }; + let mut listeners: Vec<(Binding, Option, String, u16, TcpListener)> = Vec::with_capacity(bindings.len()); + let mut udp: Vec<(Binding, Option, String, u16, UdpSocket)> = Vec::new(); for b in bindings { // A port picked by the kernel (0) is picked once: the `::` listener // takes the one 0.0.0.0 got. @@ -420,11 +649,41 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] e } }; + let is_udp = b.proto == "udp"; // Kiri's own container-domain router on this port lets it go // (domains::step_aside), and the bind goes again. - let bound = bind_socket(addr, b.proto == "udp").or_else(|e| { - if e.kind() == io::ErrorKind::AddrInUse && b.proto == "tcp" && port != 0 && super::domains::step_aside(port) { bind_socket(addr, false) } else { Err(e) } - }); + let try_bind = |a: SocketAddr| { + bind_socket(a, is_udp).or_else(|e| { + if e.kind() == io::ErrorKind::AddrInUse && !is_udp && port != 0 && super::domains::step_aside(port) { + bind_socket(a, false) + } else { + Err(e) + } + }) + }; + let (bound, bind_ip) = match try_bind(addr) { + Ok(s) => (Ok(s), ip.clone()), + // In WSL 2, a Windows host interface IP (`-p :port:cport`) + // is not assigned inside the Linux VM (`EADDRNOTAVAIL` / os error 99). + // When the IP belongs to a Windows host interface and WSL has a + // distinct internal `eth0` IPv4 address, bind WSL's `eth0` address + // (never 0.0.0.0, which would make wslrelay.exe expose 127.0.0.1:port + // on Windows) while `kiri-win` binds `:port` on Windows and + // forwards to `:`. + Err(e) + if in_wsl + && (e.kind() == io::ErrorKind::AddrNotAvailable || e.raw_os_error() == Some(libc::EADDRNOTAVAIL)) + && is_windows_host_ip(&ip) => + { + if let Some(fallback_ip) = wsl_eth0 { + let fallback_addr = SocketAddr::new(IpAddr::V4(fallback_ip), port); + (try_bind(fallback_addr), fallback_ip.to_string()) + } else { + (Err(e), ip.clone()) + } + } + Err(e) => (Err(e), ip.clone()), + }; let sock = match bound { Ok(s) => s, Err(e) if required => return Err(taken(e)), @@ -435,17 +694,45 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] continue; } }; - if b.proto == "udp" { + if is_udp { let s = UdpSocket::from(sock); s.set_nonblocking(true)?; port = s.local_addr()?.port(); - udp.push((b.clone(), ip, port, s)); + udp.push((b.clone(), Some(ip), bind_ip.clone(), port, s)); + // WSL 2's localhostForwarding never forwards UDP, so `kiri-win` + // forwards Windows UDP ports (including 127.0.0.1:port/udp) to + // `:/udp`. Ensure `:/udp` is + // also bound/DNATed inside WSL when the primary bind was loopback + // or IPv6-only. + if let Some(eth0) = wsl_eth0 { + let eth0_str = eth0.to_string(); + if bind_ip != "0.0.0.0" + && bind_ip != eth0_str + && !udp.iter().any(|(_, _, bip, p, _)| *p == port && (bip == "0.0.0.0" || bip == ð0_str)) + && let Ok(aux_fd) = bind_socket(SocketAddr::new(IpAddr::V4(eth0), port), true) + { + let aux = UdpSocket::from(aux_fd); + let _ = aux.set_nonblocking(true); + udp.push((b.clone(), None, eth0_str, port, aux)); + } + } continue; } let l = TcpListener::from(sock); l.set_nonblocking(true)?; port = l.local_addr()?.port(); - listeners.push((b.clone(), ip, port, l)); + listeners.push((b.clone(), Some(ip.clone()), bind_ip.clone(), port, l)); + if let Some(eth0) = wsl_eth0 { + let eth0_str = eth0.to_string(); + if ip == "::" + && !listeners.iter().any(|(_, _, bip, p, _)| *p == port && (bip == "0.0.0.0" || bip == ð0_str)) + && let Ok(aux_fd) = bind_socket(SocketAddr::new(IpAddr::V4(eth0), port), false) + { + let aux = TcpListener::from(aux_fd); + let _ = aux.set_nonblocking(true); + listeners.push((b.clone(), None, eth0_str, port, aux)); + } + } } } let mut fw = Forwards { wake: Vec::new(), threads: Vec::new(), kernel: None, nat: None, loopback: None, bound: Vec::new() }; @@ -455,10 +742,20 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] // loopback. The listeners below relay the rest. A target on loopback (a // --network host container) stays relayed: that is a local socket. if cfg!(target_os = "linux") && target_ip != [127, 0, 0, 1] { - let all = udp.iter().map(|(b, ip, port, _)| (b, ip, *port, true)).chain(listeners.iter().map(|(b, ip, port, _)| (b, ip, *port, false))); + let all = udp + .iter() + .map(|(b, _, bind_ip, port, _)| (b, bind_ip, *port, true)) + .chain(listeners.iter().map(|(b, _, bind_ip, port, _)| (b, bind_ip, *port, false))); let mut published = Ok(false); - for (b, ip, port, is_udp) in all.filter(|(_, ip, ..)| kernel_forwards(ip)) { - let p = kiri_proto::Publish { id, udp: is_udp, host_ip: kernel_host_ip(ip).expect("checked IPv4 binding"), host_port: port, to_ip: target_ip, to_port: b.container_port }; + for (b, bind_ip, port, is_udp) in all.filter(|(_, bind_ip, ..)| kernel_forwards(bind_ip)) { + let p = kiri_proto::Publish { + id, + udp: is_udp, + host_ip: kernel_host_ip(bind_ip).expect("checked IPv4 binding"), + host_port: port, + to_ip: target_ip, + to_port: b.container_port, + }; published = vm.publish(p).map(|()| true); if published.is_err() { break; @@ -467,10 +764,10 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] match published { Ok(any) => { // Sockets only the kernel serves stay bound, so the ports read as taken. - let (kernel_udp, relay_udp): (Vec<_>, Vec<_>) = udp.into_iter().partition(|(_, ip, ..)| !relays_too(ip)); - let (kernel_tcp, relay_tcp): (Vec<_>, Vec<_>) = listeners.into_iter().partition(|(_, ip, ..)| !relays_too(ip)); - fw.bound.extend(kernel_udp.iter().map(|(b, ip, port, _)| (b.clone(), ip.clone(), *port))); - fw.bound.extend(kernel_tcp.iter().map(|(b, ip, port, _)| (b.clone(), ip.clone(), *port))); + let (kernel_udp, relay_udp): (Vec<_>, Vec<_>) = udp.into_iter().partition(|(_, _, bind_ip, ..)| !relays_too(bind_ip)); + let (kernel_tcp, relay_tcp): (Vec<_>, Vec<_>) = listeners.into_iter().partition(|(_, _, bind_ip, ..)| !relays_too(bind_ip)); + fw.bound.extend(kernel_udp.iter().filter_map(|(b, rep_ip, _, port, _)| rep_ip.as_ref().map(|ip| (b.clone(), ip.clone(), *port)))); + fw.bound.extend(kernel_tcp.iter().filter_map(|(b, rep_ip, _, port, _)| rep_ip.as_ref().map(|ip| (b.clone(), ip.clone(), *port)))); if any { fw.kernel = Some((vm.clone(), id.to_owned(), kernel_tcp.into_iter().map(|(.., s)| s).collect(), kernel_udp.into_iter().map(|(.., s)| s).collect())); } @@ -483,7 +780,7 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] } } } - for (b, ip, port, sock) in udp { + for (b, rep_ip, _bind_ip, port, sock) in udp { let (wake_r, wake_w) = pipe()?; fw.wake.push(wake_w); let vm = vm.clone(); @@ -491,7 +788,9 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] fw.threads.push(std::thread::Builder::new().name(format!("kiri-udp-{port}")).spawn(move || { udp_loop(&sock, &wake_r, &vm, target_ip, container_port); })?); - fw.bound.push((b, ip, port)); + if let Some(ip) = rep_ip { + fw.bound.push((b, ip, port)); + } } // In the VM: the guest kernel forwards each TCP binding from a port of // its own on the NAT network. A target on loopback stays relayed. @@ -512,7 +811,7 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] // listener. As on Docker, where a published port is bound in the host's // namespace. A target on loopback is itself a host-network container. if cfg!(target_os = "macos") && target_ip != [127, 0, 0, 1] { - let ports = loopback_ports(listeners.iter().map(|(b, ip, port, _)| (b.container_port, ip.as_str(), *port))); + let ports = loopback_ports(listeners.iter().filter_map(|(b, rep_ip, _, port, _)| rep_ip.as_deref().map(|ip| (b.container_port, ip, *port)))); let mut published = false; for (to_port, host_port) in ports { let p = kiri_proto::Publish { id, udp: false, host_ip: [127, 0, 0, 1], host_port, to_ip: target_ip, to_port }; @@ -525,7 +824,7 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] fw.loopback = Some((vm.clone(), id.to_owned())); } } - for ((b, ip, port, listener), nat) in listeners.into_iter().zip(nat) { + for ((b, rep_ip, _bind_ip, port, listener), nat) in listeners.into_iter().zip(nat) { let (wake_r, wake_w) = pipe()?; fw.wake.push(wake_w); let vm = vm.clone(); @@ -533,7 +832,9 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] fw.threads.push(std::thread::Builder::new().name(format!("kiri-port-{port}")).spawn(move || { accept_loop(&listener, &wake_r, &vm, target_ip, container_port, nat); })?); - fw.bound.push((b, ip, port)); + if let Some(ip) = rep_ip { + fw.bound.push((b, ip, port)); + } } Ok(fw) } @@ -2356,4 +2657,40 @@ mod tests { vec!["10.254.99.0/24"] ); } + + #[test] + fn ipconfig_parser_extracts_windows_interface_ips_and_excludes_gateways_and_masks() { + let sample = "\ +Windows IP Configuration\r\n\ +\r\n\ +Ethernet adapter vEthernet (WSL):\r\n\ +\r\n\ + Connection-specific DNS Suffix . : \r\n\ + Link-local IPv6 Address . . . . . : fe80::1234:5678:9abc:def0%42\r\n\ + IPv4 Address. . . . . . . . . . . : 198.51.100.1\r\n\ + Subnet Mask . . . . . . . . . . . : 255.255.240.0\r\n\ + Default Gateway . . . . . . . . . : \r\n\ +\r\n\ +Wireless LAN adapter Wi-Fi:\r\n\ +\r\n\ + Connection-specific DNS Suffix . : lan\r\n\ + IPv6 Address. . . . . . . . . . . : 2001:db8::42(Preferred)\r\n\ + Link-local IPv6 Address . . . . . : fe80::abcd:ef01:2345:6789%18\r\n\ + IPv4 Address. . . . . . . . . . . : 192.0.2.50(Preferred)\r\n\ + Subnet Mask . . . . . . . . . . . : 255.255.255.0\r\n\ + Default Gateway . . . . . . . . . : fe80::1%18\r\n\ + 192.0.2.1\r\n"; + let ips = super::parse_ipconfig_addrs(sample); + assert!(ips.contains(&"127.0.0.1".parse().unwrap())); + assert!(ips.contains(&"::1".parse().unwrap())); + assert!(ips.contains(&"198.51.100.1".parse().unwrap())); + assert!(ips.contains(&"192.0.2.50".parse().unwrap())); + assert!(ips.contains(&"2001:db8::42".parse().unwrap())); + // Subnet masks, default gateways, and arbitrary bogus IPs must not match. + assert!(!ips.contains(&"255.255.255.0".parse().unwrap())); + assert!(!ips.contains(&"255.255.240.0".parse().unwrap())); + assert!(!ips.contains(&"192.0.2.1".parse().unwrap())); + assert!(!ips.contains(&"fe80::1".parse().unwrap())); + assert!(!ips.contains(&"203.0.113.99".parse().unwrap())); + } } diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index d334a69c8..d12fc2dd4 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -488,12 +488,28 @@ fn default_out() -> io::Result { Ok(if desktop.is_dir() { desktop } else { home }.join(format!("kiri-report-{stamp}.txt"))) } +/// Resolves an explicit `--out` path (translating a Windows drive path like +/// `C:\Temp\report.txt` to `/mnt/c/Temp/report.txt` when running inside WSL 2) +/// or falls back to `default_out()`. +fn resolve_out_path(out: Option, wsl: Option<&crate::daemon::binds::Wsl>) -> io::Result { + let Some(p) = out else { + return default_out(); + }; + if let (Some(w), Some(s)) = (wsl, p.to_str()) + && (s.contains('\\') || s.as_bytes().get(1) == Some(&b':')) + && let Ok(mapped) = crate::daemon::binds::source(s, w) + { + return Ok(PathBuf::from(mapped)); + } + Ok(p) +} + /// Writes the report, readable only by this user. Returns where. pub fn save_report(text: &str, out: Option) -> io::Result { - let path = match out { - Some(p) => p, - None => default_out()?, - }; + let path = resolve_out_path(out, crate::daemon::binds::wsl())?; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + let _ = std::fs::create_dir_all(parent); + } let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&path)?; f.write_all(text.as_bytes())?; Ok(path) @@ -1048,4 +1064,21 @@ mod tests { assert!(text.contains("==== Guest console (~/.kiri/logs/guest-console.log) ====") && text.contains("configured eth0 statically as 192.168.64.2/24"), "{text}"); let _ = std::fs::remove_dir_all(&home); } + + #[test] + fn resolves_windows_out_path_in_wsl() { + let wsl = crate::daemon::binds::Wsl { root: "/mnt/".into(), distro: Some("kiri".into()) }; + assert_eq!( + resolve_out_path(Some(PathBuf::from(r"C:\Temp\kiri-test-report.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/mnt/c/Temp/kiri-test-report.txt") + ); + assert_eq!( + resolve_out_path(Some(PathBuf::from("D:/reports/out.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/mnt/d/reports/out.txt") + ); + assert_eq!( + resolve_out_path(Some(PathBuf::from("/tmp/kiri-report.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/tmp/kiri-report.txt") + ); + } } diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index e7602d460..fced5e890 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -74,7 +74,7 @@ mod setup; mod usb; #[cfg(unix)] mod stale; -#[cfg(windows)] +#[cfg(any(windows, test))] mod wsl; #[cfg(any(unix, windows))] mod share; diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 5f44253d0..2e3b3573f 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -2,13 +2,17 @@ //! `kiri registry` and `kiri scan` on Windows: the engine's own //! commands, run by the Linux `kiri` in the WSL distro Kiri's engine lives //! in, as the engine runs (root, with its HOME), so it finds the daemon's -//! socket and store. Arguments go through as they are: Windows paths are not -//! translated. `kiri machine shell` is the exception: it needs a terminal -//! and a docker CLI, so it runs on Windows (machine_shell below). +//! socket and store. `kiri diag report [--out PATH]` writes the report file +//! directly to the Windows filesystem (rather than inside the WSL Linux +//! rootfs), and `kiri machine shell` runs on Windows where it has the console +//! terminal and `docker.exe`. -use std::io; +#![cfg_attr(not(windows), allow(dead_code))] + +use std::io::{self, Read, Seek, SeekFrom}; use std::path::PathBuf; -use std::process::Command; +use std::process::{Command, Stdio}; +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"]; @@ -17,6 +21,126 @@ pub const COMMANDS: &[&str] = &["k8s", "machine", "diag", "usb", "domains", "reg /// 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 "$@""#; +/// 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 +/// write the output file directly on the Windows filesystem. +const REPORT_SCRIPT: &str = r#"export HOME=/var/lib/kiri-daemon; [ -x /usr/local/bin/kiri-start ] && /usr/local/bin/kiri-start >/dev/null 2>&1; tmp="$(mktemp /tmp/kiri-report.XXXXXX)" || exit $?; trap 'rm -f "$tmp"' EXIT; if [ "$1" = "--send" ]; then /usr/local/bin/kiri diag report --out "$tmp" --send | grep -v '^saved the report to ' >&2 || exit $?; else /usr/local/bin/kiri diag report --out "$tmp" >/dev/null || exit $?; fi; cat "$tmp""#; + +/// Parses `kiri diag report` arguments (`[--out PATH | -o PATH | --out=PATH] [--send]`). +/// Returns `None` if unrecognized flags are present so WSL's `kiri diag report` +/// prints usage and exits with its error code. +pub fn parse_diag_report_args(args: &[String]) -> Option<(Option, bool)> { + let mut out = None; + let mut send_it = false; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--out" | "-o" => { + let p = it.next()?.trim(); + if p.is_empty() { + return None; + } + out = Some(PathBuf::from(p)); + } + s if s.starts_with("--out=") => { + let p = s["--out=".len()..].trim(); + if p.is_empty() { + return None; + } + out = Some(PathBuf::from(p)); + } + "--send" => send_it = true, + _ => return None, + } + } + Some((out, send_it)) +} + +fn default_windows_report_out() -> io::Result { + let home = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + .ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let desktop = home.join("Desktop"); + let secs = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let dir = if desktop.is_dir() { desktop } else { home }; + Ok(dir.join(format!("kiri-report-{secs}.txt"))) +} + +fn redact_windows_home(text: &str) -> String { + let Some(home) = std::env::var("USERPROFILE").ok().filter(|h| !h.is_empty()) else { + return text.to_owned(); + }; + let slash = home.replace('\\', "/"); + text.replace(&home, "~").replace(&slash, "~") +} + +fn windows_ui_log_section() -> String { + const TAIL_MAX: u64 = 120 << 10; + let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") else { + return String::new(); + }; + let path = PathBuf::from(local_app_data).join("Kiri").join("kiri-win.log"); + let Ok(mut f) = std::fs::File::open(&path) else { + return String::new(); + }; + let len = f.metadata().map_or(0, |m| m.len()); + let from = len.saturating_sub(TAIL_MAX); + if f.seek(SeekFrom::Start(from)).is_err() { + return String::new(); + } + let mut buf = Vec::new(); + let _ = f.take(TAIL_MAX).read_to_end(&mut buf); + let raw = String::from_utf8_lossy(&buf); + let body = match (from > 0, raw.find('\n')) { + (true, Some(i)) => &raw[i + 1..], + (true, None) => "", + (false, _) => &raw, + }; + if body.trim().is_empty() { + return String::new(); + } + let redacted = redact_windows_home(body.trim_end()); + format!("\n==== Windows UI log (%LOCALAPPDATA%\\Kiri\\kiri-win.log) ====\n{redacted}\n") +} + +fn diag_report(rest: &[String]) -> io::Result { + let Some((chosen_out, send_it)) = parse_diag_report_args(rest) else { + return Ok(false); + }; + let out_path = match chosen_out { + Some(p) => p, + None => default_windows_report_out()?, + }; + let distro = distro().ok_or_else(|| io::Error::other("Kiri isn't set up yet. Open Kiri from the Start menu first"))?; + let system = std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + let mut cmd = Command::new(system.join("System32").join("wsl.exe")); + cmd.args(["-d", &distro, "-u", "root", "-e", "sh", "-c", REPORT_SCRIPT, "kiri"]); + if send_it { + cmd.arg("--send"); + } + let output = cmd + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .output() + .map_err(|e| io::Error::other(format!("could not run wsl.exe ({e})")))?; + if !output.status.success() { + std::process::exit(output.status.code().unwrap_or(1)); + } + let mut text = String::from_utf8_lossy(&output.stdout).into_owned(); + if text.trim().is_empty() { + text = format!("Kiri diagnostics report\nVersion: {}\n", env!("CARGO_PKG_VERSION")); + } + text.push_str(&windows_ui_log_section()); + let text = redact_windows_home(&text); + if let Some(parent) = out_path.parent().filter(|p| !p.as_os_str().is_empty()) { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write(&out_path, text.as_bytes())?; + println!("saved the report to {}", redact_windows_home(&out_path.display().to_string())); + Ok(true) +} + /// Runs `kiri ` in WSL and exits with its exit code. pub fn run(args: &[String]) -> io::Result<()> { if let [m, verb, name, rest @ ..] = args @@ -25,6 +149,13 @@ pub fn run(args: &[String]) -> io::Result<()> { { return machine_shell(name, rest); } + if let [d, verb, rest @ ..] = args + && d == "diag" + && verb == "report" + && diag_report(rest)? + { + return Ok(()); + } let distro = distro().ok_or_else(|| io::Error::other("Kiri isn't set up yet. Open Kiri from the Start menu first"))?; // wsl.exe from System32, never one found in the current folder. let system = std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); @@ -63,10 +194,31 @@ fn machine_shell(name: &str, rest: &[String]) -> io::Result<()> { #[cfg(test)] mod tests { - use super::COMMANDS; + use super::{COMMANDS, parse_diag_report_args}; + use std::path::PathBuf; #[test] fn forwards_scan_to_wsl() { assert!(COMMANDS.contains(&"scan")); } + + #[test] + fn parses_windows_diag_report_out_and_send_flags() { + let s = |list: &[&str]| list.iter().map(|x| (*x).to_owned()).collect::>(); + assert_eq!(parse_diag_report_args(&s(&[])), Some((None, false))); + assert_eq!( + parse_diag_report_args(&s(&["--out", r"C:\Temp\kiri-test-report.txt"])), + Some((Some(PathBuf::from(r"C:\Temp\kiri-test-report.txt")), false)) + ); + assert_eq!( + parse_diag_report_args(&s(&["-o", r"C:\Temp\report.txt", "--send"])), + Some((Some(PathBuf::from(r"C:\Temp\report.txt")), true)) + ); + assert_eq!( + parse_diag_report_args(&s(&[r"--out=C:\Temp\eq-report.txt"])), + Some((Some(PathBuf::from(r"C:\Temp\eq-report.txt")), false)) + ); + assert_eq!(parse_diag_report_args(&s(&["--out"])), None); + assert_eq!(parse_diag_report_args(&s(&["--unknown"])), None); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 60ad4eddc..261ea9355 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 +### #640, #218, #761 Windows: forward published UDP and host-IP/LAN TCP ports to WSL 2, and write `kiri diag report --out` on the Windows filesystem (unreleased) +- Fixes: #640 [Windows] Published UDP Ports Are Not Forwarding Packets to Containers; #218 Windows: publishing a port on a host IP (-p IP:port:port) fails with 'Address not available (os error 99)'; 0.0.0.0 is loopback-only; #761 `kiri diag report --out ` on Windows wrote inside the WSL rootfs instead of the Windows path +- Caused: none known +- Caused by: - +- Check: `crates/kiri-win/src/ports.rs`, `crates/kiri/src/daemon/ports.rs`, `crates/kiri/src/wsl.rs` + ### #550 Windows: resolve host.docker.internal and host.kiri.internal to 192.168.65.254 and relay to Windows loopback (unreleased) - Fixes: #550 Windows: host.docker.internal resolves to the WSL VM's bridge gateway (172.17.0.1) instead of the Windows host, unlike Docker Desktop - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 8195fddf6..613c3a1ed 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -300,3 +300,6 @@ leave-first-running-disconnect #789 disconnecting a running container from its o leave-first-running-reconnect #789 reconnecting a running container after leaving its first network failed to restore veth connectivity, DNS aliases, or published ports leave-first-running-promote #789 disconnecting a running container's first network when attached to a second network failed to isolate the left network, promote the default route, or rebind published ports crates/kiri/src/hostrelay.rs #550 on Windows (WSL 2), host.docker.internal resolved to the WSL bridge gateway (172.17.0.1) instead of 192.168.65.254 relayed to Windows 127.0.0.1 and [::1] +crates/kiri-win/src/ports.rs #640 WSL 2's localhostForwarding only forwards loopback TCP, so published UDP container ports and non-loopback Windows host-IP or 0.0.0.0 LAN TCP bindings were unreachable on Windows (#218) +crates/kiri/src/daemon/ports.rs #218 publishing a container port on a Windows host interface IP (-p IP:port:port) failed inside WSL 2 with EADDRNOTAVAIL (os error 99) instead of binding WSL's eth0 address for kiri-win to forward +crates/kiri/src/wsl.rs #761 running kiri.exe diag report [--out PATH] on Windows wrote the report file inside the WSL Linux rootfs instead of the Windows filesystem From cb06615c6ed6a416798307708a1b0699eb92b786 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:05:10 +0100 Subject: [PATCH 067/157] Build: serve digest-pinned local bases, relay default-bridge stub DNS, and support host-network builds (#209, #288, #330) (#859) --- crates/kiri-image/src/registry.rs | 36 +- crates/kiri-image/src/store.rs | 53 +- crates/kiri-init/src/linux/agent.rs | 48 +- crates/kiri-init/src/linux/container.rs | 44 +- crates/kiri-init/src/linux/dns.rs | 813 ++++++++++++++++++++++-- crates/kiri-init/src/linux/net.rs | 7 +- crates/kiri-init/src/linux/netlink.rs | 48 +- crates/kiri-init/src/linux/transport.rs | 71 ++- crates/kiri/src/daemon/api.rs | 2 +- crates/kiri/src/daemon/builder.rs | 175 ++++- crates/kiri/src/daemon/dns.rs | 81 ++- crates/kiri/src/daemon/mirror.rs | 114 +++- docs/fix-registry.md | 6 + tests/linux-host.sh | 36 +- tests/regressions.tsv | 3 + 15 files changed, 1361 insertions(+), 176 deletions(-) diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 26375d914..2737975fe 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -1141,7 +1141,7 @@ impl Client { // An index lists one manifest per platform; pick ours and fetch it. let index_digest = manifest.manifests.is_some().then(|| sha256_digest(&bytes)); - let (manifest, digest) = if let Some(entries) = manifest.manifests { + let (index_bytes, manifest, manifest_bytes, digest) = if let Some(entries) = manifest.manifests { let wanted = entries.iter().find(|m| { m.platform.as_ref().is_some_and(|p| p.os == platform.os && p.architecture == platform.architecture) }); @@ -1156,19 +1156,20 @@ impl Client { .collect(), }); }; - let (bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?; - if sha256_digest(&bytes) != entry.digest { + let (entry_bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?; + if sha256_digest(&entry_bytes) != entry.digest { return Err(Error::Manifest(format!("manifest {} failed digest check", entry.digest))); } - let m: Manifest = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(e.to_string()))?; - (m, entry.digest.clone()) + let m: Manifest = serde_json::from_slice(&entry_bytes).map_err(|e| Error::Manifest(e.to_string()))?; + (Some(bytes), m, entry_bytes, entry.digest.clone()) } else { if r.is_digest() && sha256_digest(&bytes) != r.reference { return Err(Error::Manifest("manifest failed digest check".into())); } - (manifest, sha256_digest(&bytes)) + let d = sha256_digest(&bytes); + (None, manifest, bytes, d) }; - Ok(Resolved { target: r.clone(), index_digest, digest, manifest, media_type }) + Ok(Resolved { target: r.clone(), index_digest, index_bytes, digest, manifest, manifest_bytes, media_type }) } /// The second half of a pull: the config and layers of `resolved`, @@ -1183,7 +1184,7 @@ impl Client { progress: &(dyn Fn(Progress) + Sync), cancel: &Cancel, ) -> Result { - let Resolved { target, index_digest, digest, manifest, media_type } = resolved; + let Resolved { target, index_digest, index_bytes, digest, manifest, manifest_bytes, media_type } = resolved; let (Some(config), Some(layers)) = (manifest.config.as_ref(), manifest.layers.as_ref()) else { return Err(Error::Manifest(format!("{media_type} has no config or layers"))); }; @@ -1299,6 +1300,23 @@ impl Client { }, mirror, }; + // Keep the registry's exact manifest and multi-arch index bytes in the + // blob store so Kiri's build mirror can serve digest-pinned FROM + // references (`FROM repo:tag@sha256:…` and `FROM repo@sha256:…`) with + // matching SHA-256 digests (#288, #330). + let save_raw = |d: &str, bytes: &[u8]| -> Result<(), Error> { + if store.has_blob(d, bytes.len() as u64) { + return Ok(()); + } + let mut w = store.blob_writer(d)?; + w.write_all(bytes)?; + w.finish()?; + Ok(()) + }; + save_raw(digest, manifest_bytes)?; + if let (Some(idx_digest), Some(idx_bytes)) = (index_digest.as_deref(), index_bytes.as_deref()) { + save_raw(idx_digest, idx_bytes)?; + } // The last moment a cancel can stop it: after this it is pulled. if cancel.is_cancelled() { return Err(Error::Cancelled); @@ -1879,8 +1897,10 @@ struct Token { struct Resolved { target: Reference, index_digest: Option, + index_bytes: Option>, digest: String, manifest: Manifest, + manifest_bytes: Vec, media_type: String, } diff --git a/crates/kiri-image/src/store.rs b/crates/kiri-image/src/store.rs index 969e20d85..34f4eb4e9 100644 --- a/crates/kiri-image/src/store.rs +++ b/crates/kiri-image/src/store.rs @@ -121,6 +121,18 @@ impl Image { let same_repo = Reference::parse(&self.name).is_ok_and(|n| n.registry == r.registry && n.repository == r.repository); same_repo && (self.digest == r.reference || self.index_digest.as_deref() == Some(r.reference.as_str())) } + + /// Every blob digest this image record owns in the store: its config, + /// its layers, and (when pulled from a registry) its raw manifest and + /// multi-arch index blobs so Kiri's build mirror can serve exact + /// digest-verified bytes. + pub fn referenced_digests(&self) -> impl Iterator { + let manifest = (self.digest != self.config_digest).then_some(self.digest.as_str()); + std::iter::once(self.config_digest.as_str()) + .chain(manifest) + .chain(self.index_digest.as_deref()) + .chain(self.layers.iter().map(|l| l.digest.as_str())) + } } #[derive(Debug)] @@ -494,8 +506,8 @@ impl Store { let Some(pos) = images.iter().position(|i| i.name == name) else { return Ok(None) }; let removed = images.remove(pos); self.write_index(&images)?; - let in_use = |d: &str| images.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d)); - for d in std::iter::once(&removed.config_digest).chain(removed.layers.iter().map(|l| &l.digest)) { + let in_use = |d: &str| images.iter().any(|i| i.referenced_digests().any(|r| r == d)); + for d in removed.referenced_digests() { if !in_use(d) { self.remove_unpinned(d); } @@ -509,7 +521,7 @@ impl Store { pub fn remove_if_unused(&self, digest: &str) -> io::Result<()> { let _lock = self.lock_index()?; let images = self.read_locked()?; - if !images.iter().any(|i| i.config_digest == digest || i.layers.iter().any(|l| l.digest == digest)) { + if !images.iter().any(|i| i.referenced_digests().any(|r| r == digest)) { self.remove_unpinned(digest); } Ok(()) @@ -747,6 +759,41 @@ mod tests { fs::remove_dir_all(&root).unwrap(); } + #[test] + fn removes_raw_manifest_and_index_blobs_when_no_image_references_them() { + let root = std::env::temp_dir().join(format!("kiri-store-raw-manifest-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root).unwrap(); + let put = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let (cfg, cfg_sz) = put(b"{\"os\":\"linux\",\"architecture\":\"amd64\"}"); + let (man, man_sz) = put(b"{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\"}"); + let (idx, idx_sz) = put(b"{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"}"); + let img = |name: &str| Image { + name: name.into(), + digest: man.clone(), + index_digest: Some(idx.clone()), + config_digest: cfg.clone(), + layers: Vec::new(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: RunConfig::default(), + mirror: None, + }; + store.put_image(img("app:1")).unwrap(); + store.put_image(img("app:latest")).unwrap(); + store.remove_image("app:1").unwrap(); + assert!(store.has_blob(&cfg, cfg_sz) && store.has_blob(&man, man_sz) && store.has_blob(&idx, idx_sz), "second tag still holds all blobs"); + store.remove_image("app:latest").unwrap(); + assert!(!store.has_blob(&cfg, cfg_sz) && !store.has_blob(&man, man_sz) && !store.has_blob(&idx, idx_sz), "last tag frees raw manifest and index blobs"); + fs::remove_dir_all(&root).unwrap(); + } + #[test] fn a_push_leaves_the_registry_manifest_in_repo_digests() { let root = std::env::temp_dir().join(format!("kiri-store-push-test-{}", std::process::id())); diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 917011bc5..0e6deca01 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -47,6 +47,30 @@ impl Proc { /// How long a hung-up terminal waits before it's polled again. const TTY_HUP_WAIT: std::time::Duration = std::time::Duration::from_millis(100); +type FileStamp = Option<(u64, u64, i64, i64)>; + +/// Caches the host's DNS servers by the metadata of `/etc/resolv.conf` and +/// `/run/systemd/resolve/resolv.conf`, so DNS listener wake-ups only re-read +/// them when either file's inode, size or modification time has changed. +#[derive(Default)] +struct HostDns { + stamp: Option<[FileStamp; 2]>, + servers: Vec<[u8; 4]>, +} + +impl HostDns { + fn get(&mut self) -> &[[u8; 4]] { + use std::os::unix::fs::MetadataExt; + let stat = |p: &str| std::fs::metadata(p).ok().map(|m| (m.ino(), m.len(), m.mtime(), m.mtime_nsec())); + let now = [stat("/etc/resolv.conf"), stat("/run/systemd/resolve/resolv.conf")]; + if self.stamp != Some(now) { + self.servers = super::transport::host_dns(); + self.stamp = Some(now); + } + &self.servers + } +} + pub fn serve(conn: File, paths: &Paths) -> io::Result<()> { let mut procs: HashMap = HashMap::new(); let served = serve_loop(conn, paths, &mut procs); @@ -78,7 +102,10 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap = Vec::new(); - let host_dns = if host_process { super::transport::host_dns() } else { Vec::new() }; + let mut host_dns = HostDns::default(); + if host_process { + host_dns.get(); + } let mut dhcp: Option = if host_process { if let Err(e) = net::host_uplink() { eprintln!("kiri-init: no uplink: {e}"); @@ -147,9 +174,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { @@ -749,7 +780,10 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 4fecf139b..d45e8814c 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1447,11 +1447,12 @@ fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]], relay: bool) -> bool { /// container reaches it. As the default bridge's containers do, its /// lookups then go through the Mac when the Mac's resolver for the VM /// network doesn't answer (dns.rs), where asking that resolver directly -/// would just fail. Not on a Linux host (the container has the host's own -/// resolv.conf), nor with `--dns`. On a fresh VM before any bridged -/// container has started, `kiri0` is brought up on demand with the default -/// bridge's gateway and prefix. None, the VM's upstream as before, when -/// the bridge can't be brought up or the agent can't listen there. +/// would just fail. Not on a Linux host (the container runs in the host's +/// network namespace and reaches `127.0.0.53` on host loopback directly), +/// nor with `--dns`. On a fresh VM before any bridged container has +/// started, `kiri0` is brought up on demand with the default bridge's +/// gateway and prefix. None, the VM's upstream as before, when the bridge +/// can't be brought up or the agent can't listen there. fn host_network_resolver(spec: &RunSpec<'_>, bridges: &mut net::Bridges, dns: &mut super::dns::Dns) -> Option<[u8; 4]> { if !host_network_uses_agent(spec, dns.relay) { return None; @@ -1556,12 +1557,17 @@ fn resolv_conf(spec: &RunSpec<'_>, upstream: &[[u8; 4]], embedded: Option<[u8; 4 for d in servers { resolv.push_str(&format!("nameserver {d}\n")); } - } else if upstream.is_empty() { - // The VM has no lease yet; a public resolver beats none. - resolv.push_str("nameserver 1.1.1.1\n"); } else { - for d in upstream { + let host_net = spec.flags & run_flags::NET_HOST != 0; + let mut wrote = false; + for d in upstream.iter().filter(|d| host_net || d[0] != 127) { resolv.push_str(&format!("nameserver {}\n", net::ip_str(*d))); + wrote = true; + } + if !wrote { + // The VM has no lease yet, or only a loopback stub remained + // without an agent listener; a public resolver beats none. + resolv.push_str("nameserver 1.1.1.1\n"); } } // `--dns-search .` means no search domains. @@ -3733,6 +3739,17 @@ mod tests { // TEST-NET-3: no machine running the tests has it. assert!(!super::embedded_dns(&spec, &[[203, 0, 113, 53]], false), "a resolver elsewhere is asked directly"); assert!(!super::embedded_dns(&spec, &[], false), "no resolver: the public fallback, not the agent"); + // systemd-resolved's 127.0.0.53 stub and Tailscale's 100.100.100.100 + // live in the host's network namespace: default-bridge containers ask + // the agent at the bridge gateway (172.17.0.1), never 127.0.0.53 (#330). + for stub in [&[[127, 0, 0, 53]][..], &[[127, 0, 0, 53], [168, 63, 129, 16]][..], &[[100, 100, 100, 100]][..]] { + assert!(super::embedded_dns(&spec, stub, false), "{stub:?} goes through the agent"); + assert_eq!(super::resolv_conf(&spec, stub, Some(super::embedded_address(&spec))), "nameserver 172.17.0.1\n"); + } + // Even if no agent listener could be made, a bridged container strips + // 127/8 stubs and keeps non-loopback fallbacks or 1.1.1.1. + assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53], [168, 63, 129, 16]], None), "nameserver 168.63.129.16\n"); + assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53]], None), "nameserver 1.1.1.1\n"); } #[test] @@ -3753,7 +3770,10 @@ mod tests { // Mac too (#732); not with --dns, nor on a Linux host (no relay). spec_with(run_flags::NET_HOST, &[], &|s| assert!(super::host_network_uses_agent(s, true))); spec_with(run_flags::NET_HOST, &["nameserver=8.8.8.8"], &|s| assert!(!super::host_network_uses_agent(s, true), "--dns servers are asked directly")); - spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::host_network_uses_agent(s, false), "a Linux host keeps its own resolv.conf")); + spec_with(run_flags::NET_HOST, &[], &|s| { + assert!(!super::host_network_uses_agent(s, false), "a Linux host has its own resolv.conf"); + assert_eq!(super::resolv_conf(s, &[[127, 0, 0, 53]], None), "nameserver 127.0.0.53\n", "Linux --network host keeps 127.0.0.53 directly"); + }); spec_with(0, &[], &|s| assert!(!super::host_network_uses_agent(s, true), "a bridged container has its own")); // Named by the bridge's gateway, not 127.0.0.11: builders keep it // for their steps rather than swapping in 8.8.8.8. @@ -3778,7 +3798,9 @@ mod tests { let mut bridges = super::net::Bridges::default(); let mut dns = super::super::dns::Dns::default(); - check([172, 17, 0, 1], 16, &[], &mut |s| assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "no relay on a Linux host")); + check([172, 17, 0, 1], 16, &[], &mut |s| { + assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "no relay on a Linux host"); + }); dns.relay = true; check([172, 17, 0, 1], 16, &["nameserver=8.8.8.8"], &mut |s| { assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "--dns bypasses agent resolver"); diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index ef2ee50e0..868f22b2e 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -74,8 +74,12 @@ const OWN_DEADLINE: Duration = Duration::from_secs(4 * MAX_OWN_SERVERS as u64); /// than `MAX_PER_CLIENT`. One more is answered SERVFAIL at once. const MAX_OWN_PER_CLIENT: usize = 16; const _: () = assert!(MAX_OWN_PER_CLIENT < MAX_PER_CLIENT); -/// Largest reply the host relay may send (a DNS over TCP frame's limit). +/// Largest reply the host relay or a TCP upstream may send (a DNS over TCP frame's limit). const MAX_RELAYED: usize = 2 + 65_535; +/// Concurrent TCP DNS client connections accepted across all listeners. +const MAX_TCP_CLIENTS: usize = 64; +/// Maximum queued reply bytes for one TCP DNS client before it is dropped. +const MAX_TCP_SEND: usize = 65_536; /// Docker's embedded DNS address, inside each container. pub const EMBEDDED: [u8; 4] = [127, 0, 0, 11]; @@ -101,6 +105,17 @@ struct Server { container: Option, } +struct TcpClient { + id: u64, + server: u64, + key: ClientKey, + sock: OwnedFd, + recv: Vec, + send: Vec, + eof: bool, + started: Instant, +} + struct Pending { /// Its own socket, connected to the resolver: a fresh source port for /// every query, as Docker's embedded DNS does, so one lost or blocked @@ -115,6 +130,8 @@ struct Pending { /// The server the query came in on (`Server::id`). server: u64, client: libc::sockaddr_in, + /// `Some(TcpClient::id)` when the client asked over TCP; `None` for UDP. + tcp_client: Option, id: u16, question: Vec, /// When it was asked of the server it is with now. @@ -124,13 +141,20 @@ struct Pending { /// The query as sent (with `our` ID), to send again. query: Vec, /// With the container's own `--dns` servers (kept under `key`): the - /// position of the one it is with. None for the VM's resolver. + /// position of the one it is with. None for the VM's / host's resolver. own: Option, + /// Host/VM upstream servers and the index currently asked when `own` is None. + upstreams: Vec<[u8; 4]>, + upstream_at: usize, /// It may still go through the host: in the VM, asked of the VM's own /// resolver (not `--dns` servers), and not tried there yet. may_relay: bool, /// Sent through the host: the reply's bytes so far, `u16 len | reply`. relayed: Option>, + /// Sent over TCP to an upstream server: remaining request bytes to write, + /// while `tcp_recv` collects the `u16 len | reply` answer. + tcp_send: Option>, + tcp_recv: Vec, } /// One name's IPv6 addresses, each with its container's IPv4 address. @@ -139,6 +163,9 @@ type Owned6 = Vec<([u8; 4], [u8; 16])>; #[derive(Default)] pub struct Dns { servers: Vec, + /// `(Server::id, listener)` for DNS over TCP on gateways and `127.0.0.11`. + tcp_servers: Vec<(u64, OwnedFd)>, + tcp_clients: Vec, /// bridge → name (lowercase) → addresses. names: HashMap>>, /// bridge → name → (the container's IPv4 address there, its IPv6 one): @@ -222,7 +249,11 @@ impl Dns { self.forget_pending(); } let sock = bound(gateway, 53)?; - self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: None }); + let id = server_id(); + if let Ok(tcp) = tcp_bound(gateway, 53) { + self.tcp_servers.push((id, tcp)); + } + self.servers.push(Server { id, bridges: vec![bridge.to_owned()], sock, container: None }); Ok(()) } @@ -259,8 +290,12 @@ impl Dns { } return Ok(()); } - let sock = super::netlink::in_netns(netns, embedded_socket)?; - self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: Some(pid) }); + let (sock, tcp) = super::netlink::in_netns(netns, embedded_socket)?; + let id = server_id(); + if let Some(tcp) = tcp { + self.tcp_servers.push((id, tcp)); + } + self.servers.push(Server { id, bridges: vec![bridge.to_owned()], sock, container: Some(pid) }); Ok(()) } @@ -281,12 +316,15 @@ impl Dns { self.servers.retain(|s| s.container != Some(pid)); self.container_upstreams.remove(&pid); self.pending.retain(|p| p.key != ClientKey::Container(pid)); + self.tcp_clients.retain(|c| c.key != ClientKey::Container(pid)); self.forget_pending(); } - /// Forwarded queries whose server is gone go too. + /// Forwarded queries and TCP sockets whose server is gone go too. fn forget_pending(&mut self) { let servers = &self.servers; + self.tcp_servers.retain(|(sid, _)| servers.iter().any(|s| s.id == *sid)); + self.tcp_clients.retain(|c| servers.iter().any(|s| s.id == c.server)); self.pending.retain(|p| servers.iter().any(|s| s.id == p.server)); } @@ -374,6 +412,7 @@ impl Dns { // Its queries in flight go with it: a container given the address // next never gets them, or their answers. self.pending.retain(|p| p.key != ClientKey::Ip(ip)); + self.tcp_clients.retain(|c| c.key != ClientKey::Ip(ip)); self.drop_names(bridge, ip); } @@ -409,9 +448,47 @@ impl Dns { } } - /// Descriptors to poll: each server's, plus each forwarded query's. + /// Descriptors to poll: each server's (UDP and TCP), accepted TCP clients, + /// and forwarded queries in flight. pub fn fds(&self) -> impl Iterator + '_ { - self.servers.iter().map(|s| s.sock.as_raw_fd()).chain(self.pending.iter().map(|p| p.sock.as_raw_fd())) + self.servers + .iter() + .map(|s| s.sock.as_raw_fd()) + .chain(self.tcp_servers.iter().map(|(_, s)| s.as_raw_fd())) + .chain(self.tcp_clients.iter().map(|c| c.sock.as_raw_fd())) + .chain(self.pending.iter().map(|p| p.sock.as_raw_fd())) + } + + /// Appends poll descriptors with read/write interest for the agent's loop. + pub fn interest(&self, fds: &mut Vec) { + for s in &self.servers { + fds.push(libc::pollfd { fd: s.sock.as_raw_fd(), events: libc::POLLIN, revents: 0 }); + } + for (_, tcp) in &self.tcp_servers { + fds.push(libc::pollfd { fd: tcp.as_raw_fd(), events: libc::POLLIN, revents: 0 }); + } + for c in &self.tcp_clients { + let events = if !c.send.is_empty() { + libc::POLLOUT + } else if !c.eof { + libc::POLLIN + } else { + 0 + }; + if events != 0 { + fds.push(libc::pollfd { fd: c.sock.as_raw_fd(), events, revents: 0 }); + } + } + for p in &self.pending { + let events = if p.tcp_send.as_ref().is_some_and(|b| !b.is_empty()) { libc::POLLIN | libc::POLLOUT } else { libc::POLLIN }; + fds.push(libc::pollfd { fd: p.sock.as_raw_fd(), events, revents: 0 }); + } + } + + /// True when `fd` is a server listener (UDP socket or TCP listener), so + /// the host agent refreshes `/etc/resolv.conf` on new queries. + pub fn is_listener(&self, fd: RawFd) -> bool { + self.servers.iter().any(|s| s.sock.as_raw_fd() == fd) || self.tcp_servers.iter().any(|(_, s)| s.as_raw_fd() == fd) } pub fn owns(&self, fd: RawFd) -> bool { @@ -425,6 +502,10 @@ impl Dns { self.read_relayed(at); return; } + if self.pending[at].tcp_send.is_some() { + self.step_tcp_upstream(at); + return; + } // A forwarded answer: hand it back to whoever asked. loop { // SAFETY: receiving into a buffer we own. @@ -441,10 +522,15 @@ impl Dns { let msg = &mut buf[..n as usize]; let p = &self.pending[at]; if u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(msg, p) { - // REFUSED or SERVFAIL from one of its own servers: the - // next one, as with Docker. From the last, it goes back. - if matches!(msg[3] & 0x0f, 2 | 5) && self.pending[at].own.is_some() && self.ask_next_own(at) { - break; + // REFUSED or SERVFAIL from one of its own servers (or when + // another host upstream is listed): try the next one. + if matches!(msg[3] & 0x0f, 2 | 5) { + if self.pending[at].own.is_some() && self.ask_next_own(at) { + break; + } + if self.pending[at].own.is_none() && self.ask_next_upstream(at) { + break; + } } // A macOS security network extension intercepting the VM // bridge's DNS answers with a Fake-IP in 198.18.0.0/15 @@ -462,6 +548,14 @@ impl Dns { } return; } + if let Some(at) = self.tcp_clients.iter().position(|c| c.sock.as_raw_fd() == fd) { + self.step_tcp_client(at, upstream); + return; + } + if let Some(&(sid, _)) = self.tcp_servers.iter().find(|(_, s)| s.as_raw_fd() == fd) { + self.accept_tcp_clients(fd, sid); + return; + } let Some(server) = self.servers.iter().position(|s| s.sock.as_raw_fd() == fd) else { return; }; @@ -565,6 +659,21 @@ impl Dns { } fn forward(&mut self, server: usize, q: &[u8], client: libc::sockaddr_in, upstream: &[[u8; 4]]) { + let key = self.servers[server] + .container + .map_or_else(|| ClientKey::Ip(client.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); + self.forward_with(server, q, client, None, key, upstream); + } + + fn forward_with( + &mut self, + server: usize, + q: &[u8], + client: libc::sockaddr_in, + tcp_client: Option, + key: ClientKey, + upstream: &[[u8; 4]], + ) { let now = Instant::now(); // A query past its deadline is answered SERVFAIL here too, before // the slots are counted: `on_readable` runs before `on_timer`. @@ -575,8 +684,7 @@ impl Dns { self.fail(at); } } - let key = self.servers[server].container.map_or_else(|| ClientKey::Ip(client.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); - let own = self.own_servers(key).map(|v| (v.len(), v.first().copied())); + let own = self.own_servers(key).map(|v| v.len()); let Some((_, _, end)) = parse_question(q) else { return; }; @@ -586,10 +694,11 @@ impl Dns { mine_own += usize::from(p.own.is_some()); } if self.pending.len() >= MAX_PENDING || mine >= MAX_PER_CLIENT || (own.is_some() && mine_own >= MAX_OWN_PER_CLIENT) { - // With its own servers the client is told at once (they may - // hold a slot for `OWN_DEADLINE`); else it asks again. - if own.is_some() { - send_to(self.servers[server].sock.as_raw_fd(), &servfail(id_of(q), rd(q), &q[12..end]), &client); + // With its own servers (or over TCP) the client is told at once; + // else UDP asks again. + if own.is_some() || tcp_client.is_some() { + let fail = servfail(id_of(q), rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); } return; } @@ -598,26 +707,39 @@ impl Dns { let id = u16::from_be_bytes([msg[0], msg[1]]); msg[0..2].copy_from_slice(&our.to_be_bytes()); let may_relay = self.relay && own.is_none(); - let mut at = None; - let sock = match own { + let use_tcp = tcp_client.is_some(); + let mut own_at = None; + let mut upstream_at = 0; + let upstreams: Vec<[u8; 4]> = if own.is_none() { upstream.to_vec() } else { Vec::new() }; + let dialed = match own { // The first of its own servers that can be sent to. - Some((len, _)) => (0..len).find_map(|i| { - let sock = self.own_servers(key).and_then(|v| v.get(i)).and_then(|d| ask(*d, &msg))?; - at = Some(i); - Some(sock) + Some(len) => (0..len).find_map(|i| { + let d = self.own_servers(key).and_then(|v| v.get(i)).copied()?; + let s = ask_dest(d, &msg, use_tcp)?; + own_at = Some(i); + Some(s) }), None if self.prefer_relay && may_relay => None, - None => upstream.first().and_then(|d| ask(*d, &msg)), + None => upstreams.iter().enumerate().find_map(|(i, d)| { + let s = ask_dest(*d, &msg, use_tcp)?; + upstream_at = i; + Some(s) + }), }; // No resolver yet, or it can't be reached (or `prefer_relay` chose the host): the host, if allowed. - let (sock, relayed) = match sock { - Some(s) => (s, false), + let (sock, tcp_send, relayed) = match dialed { + Some((s, tcp_send)) => (s, tcp_send, false), None => match may_relay.then(|| self.relay_stream(&msg)).flatten() { - Some(s) => (s, true), - None if self.prefer_relay && own.is_none() => match upstream.first().and_then(|d| ask(*d, &msg)) { - Some(s) => (s, false), + Some(s) => (s, None, true), + None if self.prefer_relay && own.is_none() => match upstreams.iter().enumerate().find_map(|(i, d)| { + let s = ask_dest(*d, &msg, use_tcp)?; + upstream_at = i; + Some(s) + }) { + Some((s, tcp_send)) => (s, tcp_send, false), None => { - send_to(self.servers[server].sock.as_raw_fd(), &servfail(id, rd(q), &q[12..end]), &client); + let fail = servfail(id, rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); return; } }, @@ -626,7 +748,8 @@ impl Dns { // answer at once rather than leave Go's resolver to time // out waiting for a reply that will never come (#715). None => { - send_to(self.servers[server].sock.as_raw_fd(), &servfail(id, rd(q), &q[12..end]), &client); + let fail = servfail(id, rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); return; } }, @@ -637,23 +760,38 @@ impl Dns { key, server: self.servers[server].id, client, + tcp_client, id, question: q[12..end].to_vec(), sent: now, started: now, query: msg, - own: at, + own: own_at, + upstreams, + upstream_at, may_relay: may_relay && !relayed, relayed: relayed.then(Vec::new), + tcp_send, + tcp_recv: Vec::new(), }; self.pending.push(p); } + fn reply_now(&mut self, server: usize, client: libc::sockaddr_in, tcp_client: Option, msg: &[u8]) { + if let Some(cid) = tcp_client { + self.send_tcp_reply(cid, msg); + } else { + send_to(self.servers[server].sock.as_raw_fd(), msg, &client); + } + } + /// Hands a matching answer to whoever asked, and forgets the query. fn answered(&mut self, at: usize, msg: &mut [u8]) { let p = self.pending.swap_remove(at); msg[0..2].copy_from_slice(&p.id.to_be_bytes()); - if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { + if let Some(cid) = p.tcp_client { + self.send_tcp_reply(cid, msg); + } else if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { send_to(s.sock.as_raw_fd(), msg, &p.client); } } @@ -667,6 +805,7 @@ impl Dns { let p = &self.pending[at]; let Some(mut i) = p.own else { return false }; let key = p.key; + let use_tcp = p.tcp_client.is_some(); if p.started.elapsed() >= OWN_DEADLINE || self.own_servers(key).is_none_or(|v| i + 1 >= v.len()) { return false; } @@ -676,12 +815,44 @@ impl Dns { loop { i += 1; let Some(dest) = self.own_servers(key).and_then(|v| v.get(i)).copied() else { break }; - if let Some(sock) = ask(dest, &self.pending[at].query) { + if let Some((sock, tcp_send)) = ask_dest(dest, &self.pending[at].query, use_tcp) { let p = &mut self.pending[at]; p.sock = sock; p.our = our; p.own = Some(i); p.sent = Instant::now(); + p.tcp_send = tcp_send; + p.tcp_recv.clear(); + return true; + } + } + self.pending[at].query[0..2].copy_from_slice(&was); + false + } + + /// Sends pending query `at` to the next host/VM upstream server (e.g. + /// `systemd-resolved`'s upstream fallback when `127.0.0.53` refuses). + fn ask_next_upstream(&mut self, at: usize) -> bool { + let p = &self.pending[at]; + if p.own.is_some() || p.upstream_at + 1 >= p.upstreams.len() { + return false; + } + let mut i = p.upstream_at; + let use_tcp = p.tcp_client.is_some(); + let Some(our) = random_id() else { return false }; + let was = [p.query[0], p.query[1]]; + self.pending[at].query[0..2].copy_from_slice(&our.to_be_bytes()); + while i + 1 < self.pending[at].upstreams.len() { + i += 1; + let dest = self.pending[at].upstreams[i]; + if let Some((sock, tcp_send)) = ask_dest(dest, &self.pending[at].query, use_tcp) { + let p = &mut self.pending[at]; + p.sock = sock; + p.our = our; + p.upstream_at = i; + p.sent = Instant::now(); + p.tcp_send = tcp_send; + p.tcp_recv.clear(); return true; } } @@ -690,10 +861,10 @@ impl Dns { } /// The server a query is with can't be reached or refused: the next of - /// the container's own, else the host if the query may go through it, - /// else SERVFAIL to the client. + /// the container's own, else the next host upstream, else the host relay + /// if the query may go through it, else SERVFAIL to the client. fn hand_over(&mut self, at: usize) { - if !self.ask_next_own(at) && !self.relay(at) { + if !self.ask_next_own(at) && !self.ask_next_upstream(at) && !self.relay(at) { self.fail(at); } } @@ -701,8 +872,10 @@ impl Dns { /// Answers pending query `at` SERVFAIL and forgets it (closing its socket). fn fail(&mut self, at: usize) { let p = self.pending.swap_remove(at); - if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { - let reply = servfail(p.id, rd(&p.query), &p.question); + let reply = servfail(p.id, rd(&p.query), &p.question); + if let Some(cid) = p.tcp_client { + self.send_tcp_reply(cid, &reply); + } else if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { send_to(s.sock.as_raw_fd(), &reply, &p.client); } } @@ -720,6 +893,8 @@ impl Dns { if let Some(stream) = stream { p.sock = stream; p.relayed = Some(Vec::new()); + p.tcp_send = None; + p.tcp_recv.clear(); p.sent = Instant::now(); true } else { @@ -727,6 +902,231 @@ impl Dns { } } + fn accept_tcp_clients(&mut self, listener: RawFd, server: u64) { + let container = self.servers.iter().find(|s| s.id == server).and_then(|s| s.container); + loop { + // SAFETY: sockaddr_in is plain data; accept4 fills it in. + let mut from: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: accept4 on a non-blocking TCP listener we own. + let fd = unsafe { libc::accept4(listener, (&mut from as *mut libc::sockaddr_in).cast(), &mut len, libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; + if fd < 0 { + break; + } + // SAFETY: fresh descriptor owned solely here. + let sock = unsafe { OwnedFd::from_raw_fd(fd) }; + if self.tcp_clients.len() >= MAX_TCP_CLIENTS { + continue; + } + let key = container.map_or_else(|| ClientKey::Ip(from.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); + self.tcp_clients.push(TcpClient { + id: server_id(), + server, + key, + sock, + recv: Vec::new(), + send: Vec::new(), + eof: false, + started: Instant::now(), + }); + } + } + + fn send_tcp_reply(&mut self, cid: u64, msg: &[u8]) { + let Ok(len) = u16::try_from(msg.len()) else { + self.drop_tcp_client(cid); + return; + }; + let Some(at) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + if self.tcp_clients[at].send.len() + 2 + msg.len() > MAX_TCP_SEND { + self.drop_tcp_client(cid); + return; + } + self.tcp_clients[at].send.extend_from_slice(&len.to_be_bytes()); + self.tcp_clients[at].send.extend_from_slice(msg); + self.flush_tcp_client(at); + } + + fn flush_tcp_client(&mut self, at: usize) { + let fd = self.tcp_clients[at].sock.as_raw_fd(); + while !self.tcp_clients[at].send.is_empty() { + let buf = &self.tcp_clients[at].send; + // SAFETY: writing a buffer we own to a socket we own. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) }; + if n > 0 { + self.tcp_clients[at].send.drain(..n as usize); + self.tcp_clients[at].started = Instant::now(); + continue; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + return; + } + let cid = self.tcp_clients[at].id; + self.drop_tcp_client(cid); + return; + } + let cid = self.tcp_clients[at].id; + if self.tcp_clients[at].eof && self.tcp_clients[at].send.is_empty() && !self.pending.iter().any(|p| p.tcp_client == Some(cid)) { + self.drop_tcp_client(cid); + } + } + + fn drop_tcp_client(&mut self, cid: u64) { + self.tcp_clients.retain(|c| c.id != cid); + } + + fn step_tcp_client(&mut self, at: usize, upstream: &[[u8; 4]]) { + let cid = self.tcp_clients[at].id; + let server_id_val = self.tcp_clients[at].server; + let key = self.tcp_clients[at].key; + if !self.tcp_clients[at].send.is_empty() { + self.flush_tcp_client(at); + } + let Some(at) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + if !self.tcp_clients[at].send.is_empty() { + return; + } + let fd = self.tcp_clients[at].sock.as_raw_fd(); + let mut buf = [0u8; 4096]; + while !self.tcp_clients[at].eof { + // SAFETY: reading into a buffer we own from a non-blocking socket we own. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + self.tcp_clients[at].started = Instant::now(); + self.tcp_clients[at].recv.extend_from_slice(&buf[..n as usize]); + if self.tcp_clients[at].recv.len() > MAX_RELAYED { + self.drop_tcp_client(cid); + return; + } + continue; + } + if n == 0 { + self.tcp_clients[at].eof = true; + break; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + break; + } + self.drop_tcp_client(cid); + return; + } + let Some(server) = self.servers.iter().position(|s| s.id == server_id_val) else { + self.drop_tcp_client(cid); + return; + }; + loop { + let Some(pos) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + let Some(raw) = framed_reply(&self.tcp_clients[pos].recv) else { + if self.tcp_clients[pos].eof { + self.tcp_clients[pos].recv.clear(); + } + break; + }; + let query = raw.to_vec(); + let consumed = 2 + query.len(); + self.tcp_clients[pos].recv.drain(..consumed); + if query.len() < 12 || parse_question(&query).is_none() { + self.drop_tcp_client(cid); + return; + } + match self.answer(server, &query) { + Some(reply) => self.send_tcp_reply(cid, &reply), + None => { + // SAFETY: zeroed sockaddr_in placeholder; TCP replies use `cid`. + let placeholder: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + self.forward_with(server, &query, placeholder, Some(cid), key, upstream); + } + } + } + if let Some(pos) = self.tcp_clients.iter().position(|c| c.id == cid) { + self.flush_tcp_client(pos); + } + } + + fn step_tcp_upstream(&mut self, at: usize) { + let fd = self.pending[at].sock.as_raw_fd(); + while self.pending[at].tcp_send.as_ref().is_some_and(|b| !b.is_empty()) { + let buf = self.pending[at].tcp_send.as_ref().expect("checked"); + // SAFETY: writing a buffer we own to a non-blocking TCP socket we own. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) }; + if n > 0 { + if let Some(b) = &mut self.pending[at].tcp_send { + b.drain(..n as usize); + } + continue; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if matches!(err.raw_os_error(), Some(libc::EAGAIN | libc::EINPROGRESS)) || err.kind() == io::ErrorKind::WouldBlock { + return; + } + self.hand_over(at); + return; + } + let mut buf = [0u8; 4096]; + let mut eof = false; + loop { + // SAFETY: reading into a buffer we own from a non-blocking TCP socket we own. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + self.pending[at].tcp_recv.extend_from_slice(&buf[..n as usize]); + if self.pending[at].tcp_recv.len() > MAX_RELAYED { + self.hand_over(at); + return; + } + continue; + } + if n == 0 { + eof = true; + break; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + break; + } + self.hand_over(at); + return; + } + if let Some(reply) = framed_reply(&self.pending[at].tcp_recv) { + let mut msg = reply.to_vec(); + let p = &self.pending[at]; + if msg.len() >= 12 && u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(&msg, p) { + if matches!(msg[3] & 0x0f, 2 | 5) { + if self.pending[at].own.is_some() && self.ask_next_own(at) { + return; + } + if self.pending[at].own.is_none() && self.ask_next_upstream(at) { + return; + } + } + if self.pending[at].own.is_none() && self.pending[at].may_relay && answer_has_fake_ip(&msg) { + self.prefer_relay = true; + if self.relay(at) { + return; + } + } + self.answered(at, &mut msg); + } else { + self.hand_over(at); + } + } else if eof { + self.hand_over(at); + } + } + /// Reads the host's reply to query `at` as it arrives. fn read_relayed(&mut self, at: usize) { let fd = self.pending[at].sock.as_raw_fd(); @@ -809,14 +1209,25 @@ impl Dns { } else if now.duration_since(p.sent) >= OWN_WAIT { self.hand_over(at); } - } else if p.may_relay && now.duration_since(p.sent) >= FALLBACK_AFTER { - self.relay(at); + } else if (p.upstream_at + 1 < p.upstreams.len() || p.may_relay) && now.duration_since(p.sent) >= FALLBACK_AFTER { + if !self.ask_next_upstream(at) { + self.relay(at); + } } else if now.duration_since(p.sent) >= FORWARD_TIMEOUT { // An upstream that never answered must not leave the // client to hit its own timeout with no reply at all. self.fail(at); } } + let pending = &self.pending; + self.tcp_clients.retain(|c| { + let has_pending = pending.iter().any(|p| p.tcp_client == Some(c.id)); + if c.eof && c.send.is_empty() && !has_pending { + return false; + } + let limit = if has_pending { OWN_DEADLINE } else { FORWARD_TIMEOUT }; + now.duration_since(c.started) < limit + }); } /// Milliseconds until `on_timer` has something to do; -1 for never. @@ -828,7 +1239,7 @@ impl Dns { .map(|p| { let due = if p.own.is_some() { left(p.sent, OWN_WAIT).min(left(p.started, OWN_DEADLINE)) - } else if p.may_relay { + } else if p.upstream_at + 1 < p.upstreams.len() || p.may_relay { left(p.sent, FALLBACK_AFTER).min(left(p.sent, FORWARD_TIMEOUT)) } else { // Even with no relay left, the query must be answered @@ -837,6 +1248,10 @@ impl Dns { }; wait_ms(due) }) + .chain(self.tcp_clients.iter().map(|c| { + let limit = if self.pending.iter().any(|p| p.tcp_client == Some(c.id)) { OWN_DEADLINE } else { FORWARD_TIMEOUT }; + wait_ms(left(c.started, limit)) + })) .min() .unwrap_or(-1) } @@ -893,29 +1308,71 @@ fn ask(dest: [u8; 4], msg: &[u8]) -> Option { Some(sock) } +/// Dials `dest`:53 over UDP (`!tcp`) or non-blocking TCP (`tcp`). +fn ask_dest(dest: [u8; 4], msg: &[u8], tcp: bool) -> Option<(OwnedFd, Option>)> { + if tcp { ask_tcp(dest, msg).map(|(s, rem)| (s, Some(rem))) } else { ask(dest, msg).map(|s| (s, None)) } +} + +/// A non-blocking TCP socket connecting to `dest`:53 with framed `msg` queued +/// (and sent immediately when `connect` completes synchronously). +fn ask_tcp(dest: [u8; 4], msg: &[u8]) -> Option<(OwnedFd, Vec)> { + let len = u16::try_from(msg.len()).ok()?.to_be_bytes(); + let fd = sys::check( + unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) } as _, + "dns tcp socket", + ) + .ok()?; + // SAFETY: `fd` is fresh and ours. + let sock = unsafe { OwnedFd::from_raw_fd(fd as RawFd) }; + let to = sockaddr(dest, 53); + // SAFETY: connecting a socket we own to a valid sockaddr_in. + let rc = unsafe { libc::connect(sock.as_raw_fd(), (&to as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) }; + if rc != 0 && io::Error::last_os_error().raw_os_error() != Some(libc::EINPROGRESS) { + return None; + } + let mut frame = Vec::with_capacity(2 + msg.len()); + frame.extend_from_slice(&len); + frame.extend_from_slice(msg); + if rc == 0 { + // SAFETY: writing a buffer we own on a connected non-blocking socket. + let n = unsafe { libc::write(sock.as_raw_fd(), frame.as_ptr().cast(), frame.len()) }; + if n > 0 { + frame.drain(..n as usize); + } + } + Some((sock, frame)) +} + /// The reply in `u16 len | reply`, once all of it is there. fn framed_reply(got: &[u8]) -> Option<&[u8]> { let len = u16::from_be_bytes([*got.first()?, *got.get(1)?]) as usize; got.get(2..2 + len) } -/// The embedded DNS's socket in a container's network namespace, which -/// the calling thread is in: on a free high port of 127.0.0.11, with -/// 127.0.0.11:53 redirected to it, as Docker does, so that a DNS server of -/// the container's own (dnsmasq, Pi-hole, CoreDNS, AdGuard) can bind -/// 0.0.0.0:53 while the container's lookups still reach this one. Where the -/// redirect can't be made (a kernel without nf_nat), port 53 itself. -fn embedded_socket() -> io::Result { +/// The embedded DNS's sockets (UDP and TCP) in a container's network +/// namespace, which the calling thread is in: on free high ports of +/// 127.0.0.11, with 127.0.0.11:53 (UDP and TCP) redirected to them, as Docker +/// does, so that a DNS server of the container's own (dnsmasq, Pi-hole, +/// CoreDNS, AdGuard) can bind 0.0.0.0:53 while the container's lookups still +/// reach this one. Where the redirect can't be made (a kernel without nf_nat), +/// port 53 itself. +fn embedded_socket() -> io::Result<(OwnedFd, Option)> { let sock = bound(EMBEDDED, 0)?; - match local_port(&sock).and_then(|port| super::netlink::redirect_embedded_dns(EMBEDDED, port)) { - Ok(()) => Ok(sock), + let (tcp, tcp_port) = match tcp_bound(EMBEDDED, 0).and_then(|t| local_port(&t).map(|p| (t, p))) { + Ok((t, p)) => (Some(t), Some(p)), + Err(_) => (None, None), + }; + let redirected = local_port(&sock).and_then(|up| super::netlink::redirect_embedded_dns(EMBEDDED, up, tcp_port)); + match redirected { + Ok(()) => Ok((sock, tcp)), Err(e) => { static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) { eprintln!("kiri-init: dns: no redirect to the embedded DNS ({e}); it takes port 53 in each container"); } - drop(sock); - bound(EMBEDDED, 53) + drop((sock, tcp)); + let udp53 = bound(EMBEDDED, 53)?; + Ok((udp53, tcp_bound(EMBEDDED, 53).ok())) } } } @@ -952,6 +1409,28 @@ fn bound(ip: [u8; 4], port: u16) -> io::Result { Ok(sock) } +/// A non-blocking TCP listening socket bound to `ip`:`port` (0: a free one). +fn tcp_bound(ip: [u8; 4], port: u16) -> io::Result { + // SAFETY: plain socket creation; owned immediately. + let fd = sys::check( + unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) } as _, + "dns tcp listen socket", + )?; + // SAFETY: `fd` is fresh and ours. + let sock = unsafe { OwnedFd::from_raw_fd(fd as RawFd) }; + let one: libc::c_int = 1; + // SAFETY: valid integer option on a socket we own. + let _ = unsafe { libc::setsockopt(sock.as_raw_fd(), libc::SOL_SOCKET, libc::SO_REUSEADDR, (&one as *const libc::c_int).cast(), std::mem::size_of::() as u32) }; + let addr = sockaddr(ip, port); + // SAFETY: bind and listen on a socket we own with a sockaddr_in of its size. + sys::check( + unsafe { libc::bind(sock.as_raw_fd(), (&addr as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) } as _, + "dns tcp bind", + )?; + sys::check(unsafe { libc::listen(sock.as_raw_fd(), 64) } as _, "dns tcp listen")?; + Ok(sock) +} + fn response_matches(msg: &[u8], pending: &Pending) -> bool { msg.get(2).is_some_and(|flags| flags & 0x80 != 0) && msg.get(12..12 + pending.question.len()).is_some_and(|question| question == pending.question) } @@ -1953,17 +2432,243 @@ mod tests { key: super::ClientKey::Ip([0; 4]), server: 0, client: unsafe { std::mem::zeroed() }, + tcp_client: None, id: 7, question: b"\x03www\x07example\x03com\x00\x00\x01\x00\x01".to_vec(), sent: Instant::now(), query: Vec::new(), own: None, + upstreams: Vec::new(), + upstream_at: 0, started: Instant::now(), may_relay: false, relayed: None, + tcp_send: None, + tcp_recv: Vec::new(), } } + #[test] + fn host_upstreams_fall_back_when_stub_refuses_and_tcp_dns_answers_local_and_forwarded() { + use std::io::{Read, Write}; + use std::os::fd::AsRawFd; + + // 1. UDP upstream fallback: a refusing loopback stub (127.0.0.68) + // hands over to the secondary upstream (127.0.0.69:53) (#330). + let stub_refused = [127, 0, 0, 68]; + let fallback_ip = [127, 0, 0, 69]; + let fallback_udp = std::net::UdpSocket::from(super::bound(fallback_ip, 53).unwrap()); + let fallback_tcp = std::net::TcpListener::from(super::tcp_bound(fallback_ip, 53).unwrap()); + fallback_tcp.set_nonblocking(false).unwrap(); + let (client_udp, from) = client(); + let mut dns = Dns::default(); + let sid = super::server_id(); + let tcp_listener = super::tcp_bound([127, 0, 0, 1], 0).unwrap(); + let tcp_port = super::local_port(&tcp_listener).unwrap(); + dns.servers.push(Server { id: sid, bridges: vec!["kiri0".into()], sock: udp_socket().unwrap(), container: None }); + dns.tcp_servers.push((sid, tcp_listener)); + dns.register("kiri0", ["svc"].iter(), [172, 17, 0, 9]); + + let q = query("example.com", 1); + dns.forward(0, &q, from, &[stub_refused, fallback_ip]); + assert_eq!(dns.pending.len(), 1); + let fd0 = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd0); + dns.on_readable(fd0, &[stub_refused, fallback_ip]); + assert_eq!(dns.pending.len(), 1, "handed over to fallback upstream"); + assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), fallback_ip); + let mut buf = [0u8; 512]; + wait_readable(fallback_udp.as_raw_fd()); + let (n, peer_addr) = fallback_udp.recv_from(&mut buf).unwrap(); + buf[2] |= 0x80; + fallback_udp.send_to(&buf[..n], peer_addr).unwrap(); + let fd1 = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd1); + dns.on_readable(fd1, &[stub_refused, fallback_ip]); + assert_eq!(told(&client_udp, 1000), Some((u16::from_be_bytes([q[0], q[1]]), 0))); + + // 2. TCP DNS listener: local network name (`svc`) and forwarded large + // upstream reply (>512 bytes, as after TC=1 in `bun install`, #330). + let upstream_worker = std::thread::spawn(move || { + let (mut s, _) = fallback_tcp.accept().unwrap(); + let mut len = [0u8; 2]; + s.read_exact(&mut len).unwrap(); + let mut uq = vec![0u8; u16::from_be_bytes(len) as usize]; + s.read_exact(&mut uq).unwrap(); + let mut reply = uq; + reply[2] = 0x81; + reply[3] = 0x80; + reply[6..8].copy_from_slice(&40u16.to_be_bytes()); + for i in 0..40u8 { + reply.extend_from_slice(&[0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 104, 16, 0, i]); + } + assert!(reply.len() > 600); + s.write_all(&(reply.len() as u16).to_be_bytes()).unwrap(); + s.write_all(&reply).unwrap(); + }); + + let client_worker = std::thread::spawn(move || { + let mut c = std::net::TcpStream::connect(("127.0.0.1", tcp_port)).unwrap(); + // First query: local container name `svc` -> 172.17.0.9. + let q1 = query("svc", 1); + c.write_all(&(q1.len() as u16).to_be_bytes()).unwrap(); + c.write_all(&q1).unwrap(); + let mut rlen = [0u8; 2]; + c.read_exact(&mut rlen).unwrap(); + let mut r1 = vec![0u8; u16::from_be_bytes(rlen) as usize]; + c.read_exact(&mut r1).unwrap(); + assert_eq!(&r1[r1.len() - 4..], &[172, 17, 0, 9]); + + // Second query on the same TCP stream: external large response via fallback_tcp. + let mut q2 = query("registry.npmjs.org", 1); + q2[0..2].copy_from_slice(&0x4242u16.to_be_bytes()); + c.write_all(&(q2.len() as u16).to_be_bytes()).unwrap(); + c.write_all(&q2).unwrap(); + c.read_exact(&mut rlen).unwrap(); + let mut r2 = vec![0u8; u16::from_be_bytes(rlen) as usize]; + c.read_exact(&mut r2).unwrap(); + assert!(r2.len() > 600); + assert_eq!(&r2[0..2], &[0x42, 0x42]); + assert_eq!(u16::from_be_bytes([r2[6], r2[7]]), 40); + }); + + let deadline = Instant::now() + std::time::Duration::from_secs(5); + while !client_worker.is_finished() && Instant::now() < deadline { + let mut fds = Vec::new(); + dns.interest(&mut fds); + let rc = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, 20) }; + if rc > 0 { + for pfd in fds { + if pfd.revents != 0 && dns.owns(pfd.fd) { + dns.on_readable(pfd.fd, &[stub_refused, fallback_ip]); + } + } + } + dns.on_timer(); + } + client_worker.join().unwrap(); + upstream_worker.join().unwrap(); + } + + #[test] + fn multiple_timed_out_queries_on_a_closed_tcp_client_never_panic_and_tcp_interest_respects_eof_and_backpressure() { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::time::Duration; + + let mut dns = Dns::default(); + let sid = super::server_id(); + dns.servers.push(Server { id: sid, bridges: vec!["kiri0".into()], sock: udp_socket().unwrap(), container: Some(77) }); + + // 1. >=3 timed-out/failing queries on a closed/reset TCP client: + // when `flush_tcp_client` drops the broken client on the first EPIPE, + // `drop_tcp_client` must not mutate `self.pending` while `on_timer` or + // `forward_with` walks `self.pending` by index. + for sweep_in_forward in [false, true] { + let mut fds = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds.as_mut_ptr()) }, 0); + let (server_end, client_end) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + drop(client_end); // close peer immediately so writes fail with EPIPE + let cid = super::server_id(); + dns.tcp_clients.push(super::TcpClient { + id: cid, + server: sid, + key: super::ClientKey::Container(77), + sock: server_end, + recv: Vec::new(), + send: Vec::new(), + eof: false, + started: Instant::now(), + }); + for qid in [1u16, 2, 3, 4] { + let mut p = pending(); + p.id = qid; + p.server = sid; + p.key = super::ClientKey::Container(77); + p.tcp_client = Some(cid); + p.sent = Instant::now() - super::FORWARD_TIMEOUT - Duration::from_secs(1); + dns.pending.push(p); + } + if sweep_in_forward { + let q = query("example.com", 1); + let placeholder: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + dns.forward_with(0, &q, placeholder, Some(cid), super::ClientKey::Container(77), &[]); + } else { + dns.on_timer(); + } + assert!(dns.pending.is_empty(), "all 4 expired TCP queries failed cleanly without index panic"); + assert!(dns.tcp_clients.is_empty(), "broken TCP client was dropped"); + } + + // 2. EOF clears trailing incomplete frame, suppresses POLLIN in interest(), + // and reaps the client once pending queries finish; non-empty send buffer + // polls POLLOUT without POLLIN and drops the client if MAX_TCP_SEND is exceeded. + let mut fds = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds.as_mut_ptr()) }, 0); + let (server_end, client_end) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + let cid = super::server_id(); + let sock_fd = server_end.as_raw_fd(); + dns.tcp_clients.push(super::TcpClient { + id: cid, + server: sid, + key: super::ClientKey::Container(77), + sock: server_end, + recv: vec![0, 20, 1, 2], // incomplete frame + send: vec![1, 2, 3], + eof: false, + started: Instant::now() - Duration::from_secs(3), + }); + let mut pollfds = Vec::new(); + dns.interest(&mut pollfds); + let c_pfd = pollfds.iter().find(|p| p.fd == sock_fd).expect("polled for POLLOUT"); + assert_eq!(c_pfd.events, libc::POLLOUT, "no POLLIN while send buffer is non-empty"); + + // Shut down client write half so read returns 0 (EOF) while a pending query is in flight. + unsafe { libc::shutdown(client_end.as_raw_fd(), libc::SHUT_WR) }; + let mut p = pending(); + p.server = sid; + p.key = super::ClientKey::Container(77); + p.tcp_client = Some(cid); + dns.pending.push(p); + + // Drain send buffer and step client to hit EOF. + dns.step_tcp_client(0, &[]); + let mut drain = [0u8; 16]; + let _ = unsafe { libc::read(client_end.as_raw_fd(), drain.as_mut_ptr().cast(), drain.len()) }; + dns.step_tcp_client(0, &[]); + assert_eq!(dns.tcp_clients.len(), 1, "kept while pending query is in flight"); + assert!(dns.tcp_clients[0].eof, "marked eof"); + assert!(dns.tcp_clients[0].recv.is_empty(), "incomplete frame cleared on eof"); + + pollfds.clear(); + dns.interest(&mut pollfds); + assert!(pollfds.iter().all(|p| p.fd != sock_fd), "half-closed idle TCP client is not polled for POLLIN"); + + // Exceeding MAX_TCP_SEND drops the client; or once pending finishes, eof client is reaped. + dns.pending.clear(); + dns.on_timer(); + assert!(dns.tcp_clients.is_empty(), "reaped once eof, send empty, and no pending query"); + + // Verify MAX_TCP_SEND cap and that unregister(Ip) never drops ClientKey::Container clients. + let mut fds2 = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds2.as_mut_ptr()) }, 0); + let (s2, _c2) = unsafe { (OwnedFd::from_raw_fd(fds2[0]), OwnedFd::from_raw_fd(fds2[1])) }; + let cid2 = super::server_id(); + dns.tcp_clients.push(super::TcpClient { + id: cid2, + server: sid, + key: super::ClientKey::Container(77), + sock: s2, + recv: Vec::new(), + send: vec![0u8; super::MAX_TCP_SEND - 10], + eof: false, + started: Instant::now(), + }); + dns.unregister("kiri0", [172, 17, 0, 2]); + assert_eq!(dns.tcp_clients.len(), 1, "unregistering an IP never drops a Container TCP client"); + dns.send_tcp_reply(cid2, &[0u8; 32]); + assert!(dns.tcp_clients.is_empty(), "client exceeding MAX_TCP_SEND is dropped"); + } + /// The default bridge moved off a subnet the host took (#489): its /// bridge is made again with another gateway, and the gateway's /// listener follows it rather than staying on the old address. diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index bbf35c10c..f37f6490e 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -474,9 +474,12 @@ pub fn local_resolver(servers: &[[u8; 4]]) -> bool { !servers.is_empty() && local_resolver_among(servers, &local_addrs()) } -/// `local_resolver`, given this machine's addresses. +/// `local_resolver`, given this machine's addresses. Loopback stubs +/// (`127.0.0.53`, systemd-resolved) and Tailscale's MagicDNS (`100.100.100.100`) +/// live in the host's network namespace too, so bridged containers reach them +/// through the agent at the bridge gateway rather than naming them directly. pub fn local_resolver_among(servers: &[[u8; 4]], local: &[[u8; 4]]) -> bool { - servers.iter().any(|s| local.contains(s)) + servers.iter().any(|s| s[0] == 127 || *s == [100, 100, 100, 100] || local.contains(s)) } /// The IPv4 address of interface `name`, if it has one: a bridge's gateway. diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 7468d421f..4a7b325a9 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -1046,21 +1046,22 @@ const EMBEDDED_DNS_TABLE: &str = "kiri_dns"; /// ```text /// table ip kiri_dns { /// chain output { type nat hook output priority -100; -/// ip daddr 127.0.0.11 udp dport 53 dnat to 127.0.0.11: } +/// ip daddr 127.0.0.11 udp dport 53 dnat to 127.0.0.11: +/// ip daddr 127.0.0.11 tcp dport 53 dnat to 127.0.0.11: } /// } /// ``` /// -/// The embedded DNS listens on 127.0.0.11:`port`, a free high port, so port -/// 53 stays free for a DNS server of the container's own (dnsmasq, Pi-hole, -/// CoreDNS bind 0.0.0.0:53), while the container's lookups at 127.0.0.11:53 -/// still reach Kiri's. Replies are mapped back to port 53 by conntrack. TCP -/// is not redirected: the embedded DNS answers over UDP only. -pub fn redirect_embedded_dns(addr: [u8; 4], port: u16) -> io::Result<()> { +/// The embedded DNS listens on 127.0.0.11's free high ports, so port 53 (UDP +/// and TCP) stays free for a DNS server of the container's own (dnsmasq, +/// Pi-hole, CoreDNS bind 0.0.0.0:53), while the container's lookups at +/// 127.0.0.11:53 still reach Kiri's. Replies are mapped back to port 53 by +/// conntrack. +pub fn redirect_embedded_dns(addr: [u8; 4], udp_port: u16, tcp_port: Option) -> io::Result<()> { let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; - nl.request(&mut embedded_dns_batch(addr, port)) + nl.request(&mut embedded_dns_batch(addr, udp_port, tcp_port)) } -fn embedded_dns_batch(addr: [u8; 4], port: u16) -> Vec { +fn embedded_dns_batch(addr: [u8; 4], udp_port: u16, tcp_port: Option) -> Vec { let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); let mut table = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); @@ -1076,10 +1077,15 @@ fn embedded_dns_batch(addr: [u8; 4], port: u16) -> Vec { // that took 15-30 ms of every container start. let mut flush = nft(NFT_MSG_DELRULE, NLM_F_ACK); flush.attr_str(1, EMBEDDED_DNS_TABLE).attr_str(2, "output"); - let rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: port }, None, None); + let udp_rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: udp_port }, None, None); + let mut out = vec![begin, table, chain, flush, udp_rule]; + if let Some(tp) = tcp_port { + out.push(dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: false, host_ip: addr, host_port: 53, to_ip: addr, to_port: tp }, None, None)); + } let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); - vec![begin, table, chain, flush, rule, end] + out.push(end); + out } const NLM_F_DUMP: u16 = 0x300; @@ -1433,16 +1439,16 @@ mod tests { /// The embedded DNS's redirect in a container's namespace: its own /// table (an engine inside the container replaces `kiri`), one output - /// nat chain emptied first, one rule that sends UDP for 127.0.0.11:53 to - /// the server's port. + /// nat chain emptied first, and UDP/TCP rules that send 127.0.0.11:53 to + /// the server's ports. #[test] fn the_embedded_dns_redirect_is_one_rule_in_a_table_of_its_own() { - let mut msgs = embedded_dns_batch([127, 0, 0, 11], 40123); + let mut msgs = embedded_dns_batch([127, 0, 0, 11], 40123, Some(40124)); let types: Vec = msgs.iter().map(|m| u16::from_ne_bytes([m.buf[4], m.buf[5]])).collect(); let t = |m: u16| (NFNL_SUBSYS_NFTABLES << 8) | m; // No DELTABLE: unregistering a hook waits for an RCU grace period. - assert_eq!(types, [NFNL_MSG_BATCH_BEGIN, t(NFT_MSG_NEWTABLE), t(NFT_MSG_NEWCHAIN), t(NFT_MSG_DELRULE), t(NFT_MSG_NEWRULE), NFNL_MSG_BATCH_END]); - for m in &msgs[1..5] { + assert_eq!(types, [NFNL_MSG_BATCH_BEGIN, t(NFT_MSG_NEWTABLE), t(NFT_MSG_NEWCHAIN), t(NFT_MSG_DELRULE), t(NFT_MSG_NEWRULE), t(NFT_MSG_NEWRULE), NFNL_MSG_BATCH_END]); + for m in &msgs[1..6] { assert_eq!(get(&attrs(&m.buf[20..]), 1), b"kiri_dns\0"); } assert_eq!(get(&attrs(&msgs[3].buf[20..]), 2), b"output\0", "the chain's rules, no handle: all of them"); @@ -1450,9 +1456,13 @@ mod tests { let hook = attrs(get(&chain, 4)); assert_eq!((be32(get(&hook, 1)), be32(get(&hook, 2)) as i32), (3, -100), "the output hook, at nat priority"); assert_eq!(get(&chain, 7), b"nat\0"); - let rule = msgs[4].finish(1).to_vec(); - let has = |needle: &[u8]| rule.windows(needle.len()).any(|w| w == needle); - assert!(has(&[127, 0, 0, 11]) && has(&53u16.to_be_bytes()) && has(&40123u16.to_be_bytes()) && has(b"nat\0")); + let udp_rule = msgs[4].finish(1).to_vec(); + let tcp_rule = msgs[5].finish(1).to_vec(); + let has = |rule: &[u8], needle: &[u8]| rule.windows(needle.len()).any(|w| w == needle); + assert!(has(&udp_rule, &[127, 0, 0, 11]) && has(&udp_rule, &53u16.to_be_bytes()) && has(&udp_rule, &40123u16.to_be_bytes()) && has(&udp_rule, b"nat\0")); + assert!(has(&tcp_rule, &[127, 0, 0, 11]) && has(&tcp_rule, &53u16.to_be_bytes()) && has(&tcp_rule, &40124u16.to_be_bytes()) && has(&tcp_rule, b"nat\0")); + let udp_only = embedded_dns_batch([127, 0, 0, 11], 40123, None); + assert_eq!(udp_only.len(), 6, "UDP redirect proceeds alone when TCP bind fails"); } /// The table is replaced with messages every kernel since 3.13 knows: diff --git a/crates/kiri-init/src/linux/transport.rs b/crates/kiri-init/src/linux/transport.rs index e8c101210..bccda6900 100644 --- a/crates/kiri-init/src/linux/transport.rs +++ b/crates/kiri-init/src/linux/transport.rs @@ -115,34 +115,71 @@ pub fn dial_within(port: u32, timeout: std::time::Duration) -> io::Result Vec<[u8; 4]> { - let parse = |path: &str| nameservers(&std::fs::read_to_string(path).unwrap_or_default()); - let direct = parse("/etc/resolv.conf"); - if direct.is_empty() { parse("/run/systemd/resolve/resolv.conf") } else { direct } + let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); + host_dns_from(&read("/etc/resolv.conf"), &read("/run/systemd/resolve/resolv.conf")) } -/// A resolv.conf's IPv4 nameservers but loopback ones (127.0.0.0/8). An -/// address of this machine's on another interface, or on `lo` outside -/// 127/8 (WSL's 10.255.255.254), is kept: `net::local_resolver` tells it. -fn nameservers(text: &str) -> Vec<[u8; 4]> { - text.lines() - .filter_map(|l| l.strip_prefix("nameserver")) +fn host_dns_from(resolv_conf: &str, systemd_resolv_conf: &str) -> Vec<[u8; 4]> { + let mut out = nameservers(resolv_conf, true); + if out.iter().all(|ip| ip[0] == 127) { + for ip in nameservers(systemd_resolv_conf, false) { + if !out.contains(&ip) { + out.push(ip); + } + } + } + out +} + +/// A resolv.conf's IPv4 nameservers, keeping loopback ones (`127.0.0.0/8`) +/// only when `allow_loopback` is set. An address of this machine's on another +/// interface, or on `lo` outside 127/8 (WSL's 10.255.255.254), is always +/// kept: `net::local_resolver` tells it. +fn nameservers(text: &str, allow_loopback: bool) -> Vec<[u8; 4]> { + let mut out = Vec::new(); + for ip in text + .lines() + .filter_map(|l| l.trim().strip_prefix("nameserver")) + .filter(|rest| rest.starts_with([' ', '\t'])) .filter_map(|ip| ip.trim().parse::().ok()) - .filter(|ip| !ip.is_loopback()) + .filter(|ip| allow_loopback || !ip.is_loopback()) .map(|ip| ip.octets()) - .collect() + { + if !out.contains(&ip) { + out.push(ip); + } + } + out } #[cfg(test)] mod tests { #[test] - fn host_resolvers_skip_loopback_ones_but_keep_wsls() { - // systemd-resolved's stub: its upstreams are read instead. - assert!(super::nameservers("nameserver 127.0.0.53\noptions edns0 trust-ad\n").is_empty()); + fn host_resolvers_keep_loopback_stub_with_systemd_fallbacks_and_keep_wsls() { + // systemd-resolved's stub alone (no /run/systemd/resolve/resolv.conf): + // kept so the host-netns agent forwards container lookups to 127.0.0.53. + assert_eq!(super::host_dns_from("nameserver 127.0.0.53\noptions edns0 trust-ad\n", ""), [[127, 0, 0, 53]]); + // Stub with systemd-resolved's upstream file: stub first (split-DNS), + // then non-loopback upstreams as fallbacks if nothing listens on the stub. + assert_eq!( + super::host_dns_from("nameserver 127.0.0.53\n", "nameserver 127.0.0.53\nnameserver 168.63.129.16\n"), + [[127, 0, 0, 53], [168, 63, 129, 16]] + ); + // Empty /etc/resolv.conf falls back to systemd-resolved's upstreams. + assert_eq!(super::host_dns_from("", "nameserver 10.0.2.3\n"), [[10, 0, 2, 3]]); + // Non-loopback /etc/resolv.conf is used as-is without mixing in stale systemd files. + assert_eq!( + super::host_dns_from("nameserver 192.168.5.2\nnameserver fe80::1\n", "nameserver 10.0.2.3\n"), + [[192, 168, 5, 2]] + ); // WSL 2's forwarder is on `lo` but outside 127/8: kept, and then // asked through the agent (net::local_resolver). - assert_eq!(super::nameservers("# generated by WSL\nnameserver 10.255.255.254\n"), [[10, 255, 255, 254]]); - assert_eq!(super::nameservers("nameserver 192.168.5.2\nnameserver fe80::1\n"), [[192, 168, 5, 2]]); + assert_eq!(super::host_dns_from("# generated by WSL\nnameserver 10.255.255.254\n", ""), [[10, 255, 255, 254]]); } } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 6982f00ac..bdde75039 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -287,7 +287,7 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea return image_save(engine, &names, w); } ("POST", "/containers/create") => { - if let Some(made) = super::builder::create_for_buildx(engine, req.query("name")) { + if let Some(made) = super::builder::create_for_buildx(engine, req) { return reply(w, made, 201); } return reply(w, create_for(req, engine, caller.wsl_distro()), 201); diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index b0b7f5efe..6ad10a4f2 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -193,9 +193,11 @@ fn ensure_image(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result Value { - json!({ +/// buildkitd flag), without a restart policy, since it starts on demand, +/// keeping network, DNS and environment options when buildx creates the +/// builder container (`--driver-opt network=host`, `env.*`, #209). +fn create_body_from(requested: Option<&Value>) -> Value { + let mut body = json!({ "Image": IMAGE, "Cmd": ["--allow-insecure-entitlement=network.host"], "Labels": {LABEL: "1"}, @@ -204,13 +206,32 @@ fn create_body() -> Value { "Mounts": [{"Type": "volume", "Source": volume_name(), "Target": "/var/lib/buildkit"}], "RestartPolicy": {"Name": "no"}, }, - }) + }); + if let Some(req) = requested { + if let Some(env) = req.get("Env").filter(|v| v.is_array()) { + body["Env"] = env.clone(); + } + let host = &req["HostConfig"]; + if let Some(mode) = host["NetworkMode"].as_str().filter(|m| !m.is_empty() && *m != "default") { + body["HostConfig"]["NetworkMode"] = json!(mode); + } + for key in ["Dns", "DnsSearch", "DnsOptions", "ExtraHosts"] { + if let Some(val) = host.get(key).filter(|v| v.is_array()) { + body["HostConfig"][key] = val.clone(); + } + } + } + body } fn create(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result { + create_with(engine, None, say) +} + +fn create_with(engine: &Engine, requested: Option<&Value>, say: &mut dyn FnMut(&str)) -> Result { ensure_image(engine, say)?; let name = container_name(); - let req = Request::internal("POST", "/containers/create", &[("name", &name)], create_body().to_string().into_bytes()); + let req = Request::internal("POST", "/containers/create", &[("name", &name)], create_body_from(requested).to_string().into_bytes()); let made = api::create(&req, engine)?; crate::diag::info!("builder created", name = name); let id = made["Id"].as_str().unwrap_or_default().to_owned(); @@ -257,28 +278,36 @@ fn start_with( } /// What the builder's registry tables come from: daemon.json's settings, -/// and the registries the store's images came from that those settings -/// reach without verified TLS (a network entry covers a registry only once -/// an image from it is pulled). +/// the registries mirrored from Kiri's store, those reached without verified +/// TLS, and whether the builder runs on the host network. #[derive(Debug, PartialEq)] struct Registries { config: std::sync::Arc, + mirrored: Vec, unverified: Vec, + host_net: bool, } impl Registries { - fn now(names: &[String]) -> Registries { + fn now(names: &[String], host_net: bool) -> Registries { let config = super::daemon_json::current(); + let mut mirrored = names.to_vec(); + mirrored.sort(); + mirrored.dedup(); let unverified = super::mirror::unverified(&config, names); - Registries { config, unverified } + Registries { config, mirrored, unverified, host_net } } } +fn builder_host_net(engine: &Engine, id: &str) -> bool { + engine.with(id, |c| c.spec.network_mode == "host").unwrap_or(false) +} + /// [`Registries`] as the builder's config last had them, so a hand edit, or -/// an image pulled from a registry inside a listed network, reaches a -/// running builder at the next build. `None` until this daemon has written -/// the file: a builder found running then (left from before the daemon -/// started) may have anything, and is treated as stale. +/// an image pulled from a new registry, reaches a running builder at the next +/// build. `None` until this daemon has written the file: a builder found +/// running then (left from before the daemon started) may have anything, and +/// is treated as stale. static WRITTEN: std::sync::Mutex>> = std::sync::Mutex::new(None); /// Whether a running builder's registry settings are not today's. @@ -290,8 +319,9 @@ fn is_stale(written: Option<&Registries>, current: &Registries) -> bool { /// start. [`WRITTEN`] says so only once the file is in place. fn write_config(engine: &Engine, id: &str) -> Result<(), Error> { let names = super::mirror::registry_names(engine); - let current = Registries::now(&names); - let toml = config_toml(cache_limit(), &super::mirror::config(engine, ¤t.config, &names)); + let host_net = builder_host_net(engine, id); + let current = Registries::now(&names, host_net); + let toml = config_toml(cache_limit(), &super::mirror::config_for(engine, ¤t.config, &names, host_net)); let archive = tar(&[("buildkit/", None), ("buildkit/buildkitd.toml", Some(toml.as_bytes()))]); let written = copy_in(engine, id, "/etc", &mut io::Cursor::new(archive)); *WRITTEN.lock().unwrap_or_else(|e| e.into_inner()) = written.is_ok().then(|| std::sync::Arc::new(current)); @@ -391,10 +421,10 @@ enum Step { const STOP_THEN_WRITE: [Step; 3] = [Step::Resume, Step::Stop, Step::Write]; /// Whether the config the builder runs with is not today's: daemon.json -/// edited by hand, or a registry in a listed network pulled from, since it -/// was written. +/// edited by hand, or a new registry pulled into the store since it was written. fn stale_now(engine: &Engine) -> bool { - is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine))) + let host_net = find(engine).is_some_and(|(id, _)| builder_host_net(engine, &id)); + is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine), host_net)) } /// Whether a builder is restarted with today's config now: only one that is @@ -522,15 +552,23 @@ fn hide_amd64_qemu(engine: &Engine, id: &str) { /// ls`, `inspect`, the window's Builds view) makes and pulls nothing, so a /// fresh Kiri has no builder, image or cache volume until the first build. /// None for any other name, or when the builder exists (the usual 409). -pub fn create_for_buildx(engine: &Engine, name: Option<&str>) -> Option> { - if name.map(|n| n.trim_start_matches('/')) != Some(container_name().as_str()) { +pub fn create_for_buildx(engine: &Engine, req: &Request) -> Option> { + if req.query("name").map(|n| n.trim_start_matches('/')) != Some(container_name().as_str()) { return None; } + let requested = if req.body.is_empty() { + None + } else { + match serde_json::from_slice::(&req.body) { + Ok(v) => Some(v), + Err(e) => return Some(Err(Error::BadRequest(format!("invalid JSON: {e}")))), + } + }; let _g = ENSURE.lock().unwrap_or_else(|e| e.into_inner()); if find(engine).is_some() { return None; } - Some(create(engine, &mut |_| {}).map(|id| json!({"Id": id, "Warnings": []}))) + Some(create_with(engine, requested.as_ref(), &mut |_| {}).map(|id| json!({"Id": id, "Warnings": []}))) } /// Claims the builder for a build or prune after checking whether it must @@ -1012,9 +1050,12 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu }; // `host-gateway` was parsed as the Mac's address; on WSL 2 with the Windows // host relay active it's 192.168.65.254, and on a plain Linux host it's the - // bridge gateway, as `docker run` gives (kiri-init maps it there). + // bridge gateway, or 127.0.0.1 for `--network host`, as `docker run` gives + // (kiri-init maps it there). let host = if crate::hostrelay::wsl_host_active() { crate::hostrelay::WSL_HOST_ADDR_STR.to_owned() + } else if cfg!(target_os = "linux") && o.network == "host" { + "127.0.0.1".to_owned() } else { super::mirror::host_addr(engine) }; @@ -1353,7 +1394,12 @@ mod tests { /// its recorded config is not advanced. #[test] fn a_builder_whose_config_is_unknown_or_old_is_stale() { - let r = |c: kiri_image::RegistryConfig, unverified: &[&str]| Registries { config: std::sync::Arc::new(c), unverified: unverified.iter().map(|s| s.to_string()).collect() }; + let r = |c: kiri_image::RegistryConfig, unverified: &[&str]| Registries { + config: std::sync::Arc::new(c), + mirrored: vec!["docker.io".into()], + unverified: unverified.iter().map(|s| s.to_string()).collect(), + host_net: false, + }; let none = r(kiri_image::RegistryConfig::default(), &[]); let some = r(kiri_image::RegistryConfig { insecure: vec![kiri_image::Insecure::parse("registry.lan:5000").unwrap()], ..Default::default() }, &[]); assert!(is_stale(None, &none), "never written by this daemon"); @@ -1361,19 +1407,84 @@ mod tests { assert!(!is_stale(Some(&some), &some)); } - /// An image pulled from a registry inside a listed network, after the - /// builder started, makes it stale: its config has no table for it. + /// An image pulled from a new registry after the builder started makes it + /// stale so `buildkitd.toml` gets Kiri's mirror table (and unverified flags + /// when inside a listed network) for that registry; pulling again from an + /// already-mirrored registry changes nothing. #[test] fn a_registry_pulled_from_inside_a_listed_network_makes_the_builder_stale() { let c = std::sync::Arc::new(kiri_image::RegistryConfig { insecure: vec![kiri_image::Insecure::parse("10.0.0.0/8").unwrap()], ..Default::default() }); - let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::>(); - let before = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io"])) }; - let after = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io", "ghcr.io", "10.1.2.3:5000"])) }; + let make = |n: &[&str], host_net: bool| { + let mut mirrored: Vec = n.iter().map(|s| s.to_string()).collect(); + let unverified = super::super::mirror::unverified(&c, &mirrored); + mirrored.sort(); + mirrored.dedup(); + Registries { config: c.clone(), mirrored, unverified, host_net } + }; + let before = make(&["docker.io", "ghcr.io"], false); + let after = make(&["docker.io", "ghcr.io", "10.1.2.3:5000"], false); assert_eq!(after.unverified, ["10.1.2.3:5000"]); assert!(is_stale(Some(&before), &after)); - // A registry outside the list changes nothing. - let other = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io", "ghcr.io"])) }; - assert!(!is_stale(Some(&before), &other)); + // Pulling another image from an already-mirrored registry changes nothing. + let same = make(&["ghcr.io", "docker.io"], false); + assert!(!is_stale(Some(&before), &same)); + // Switching the builder to `--driver-opt network=host` marks its mirror config stale. + assert!(is_stale(Some(&before), &make(&["docker.io", "ghcr.io"], true))); + } + + #[test] + fn create_for_buildx_preserves_host_network_and_dns_options() { + use std::io::Write as _; + let def = create_body_from(None); + assert!(def["HostConfig"].get("NetworkMode").is_none()); + + let asked = json!({ + "Image": "moby/buildkit:buildx-stable-1", + "Env": ["HTTP_PROXY=http://10.0.0.1:3128"], + "HostConfig": { + "NetworkMode": "host", + "Dns": ["10.0.0.53"], + "DnsSearch": ["corp.example"], + "DnsOptions": ["ndots:2"], + "ExtraHosts": ["reg.corp:10.0.0.9"], + "RestartPolicy": {"Name": "always"}, + } + }); + let merged = create_body_from(Some(&asked)); + assert_eq!(merged["HostConfig"]["NetworkMode"], "host"); + assert_eq!(merged["HostConfig"]["Dns"], json!(["10.0.0.53"])); + assert_eq!(merged["HostConfig"]["DnsSearch"], json!(["corp.example"])); + assert_eq!(merged["HostConfig"]["DnsOptions"], json!(["ndots:2"])); + assert_eq!(merged["HostConfig"]["ExtraHosts"], json!(["reg.corp:10.0.0.9"])); + assert_eq!(merged["Env"], json!(["HTTP_PROXY=http://10.0.0.1:3128"])); + assert_eq!(merged["HostConfig"]["RestartPolicy"]["Name"], "no", "managed builder starts on demand"); + + // Full create_for_buildx round-trip against Engine::boot with IMAGE pre-seeded. + let dir = std::env::temp_dir().join(format!("kiri-builder-hostnet-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let cfg = json!({"created": "2026-11-16T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["buildkitd"]}}); + let mut w = store.ingest().unwrap(); + w.write_all(&serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + store.put_image(kiri_image::archive::from_config(IMAGE.into(), &digest, &cfg, Vec::new())).unwrap(); + let engine = Engine::boot(store).unwrap(); + + let other = Request::internal("POST", "/containers/create", &[("name", "not-builder")], serde_json::to_vec(&asked).unwrap()); + assert!(create_for_buildx(&engine, &other).is_none()); + + let name = container_name(); + let bad = Request::internal("POST", "/containers/create", &[("name", &name)], b"{not-json".to_vec()); + assert!(matches!(create_for_buildx(&engine, &bad), Some(Err(Error::BadRequest(_))))); + + let create_req = Request::internal("POST", "/containers/create", &[("name", &name)], serde_json::to_vec(&asked).unwrap()); + let created = create_for_buildx(&engine, &create_req).expect("intercepted").expect("created"); + let id = created["Id"].as_str().unwrap(); + assert!(builder_host_net(&engine, id), "builder container kept HostConfig.NetworkMode = host"); + assert!(create_for_buildx(&engine, &create_req).is_none(), "existing builder falls through to 409"); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); } /// A builder on an old config is restarted only when it is up and diff --git a/crates/kiri/src/daemon/dns.rs b/crates/kiri/src/daemon/dns.rs index afb5cebf0..3c7ee5e34 100644 --- a/crates/kiri/src/daemon/dns.rs +++ b/crates/kiri/src/daemon/dns.rs @@ -122,21 +122,25 @@ fn relay_one(stream: &kiri_vmm::VsockStream) { if conn.read_exact(&mut len).is_err() { return; } - let mut query = vec![0u8; u16::from_be_bytes(len) as usize]; - if conn.read_exact(&mut query).is_err() || !is_query(&query) { + let qlen = usize::from(u16::from_be_bytes(len)); + if !(12..=4096).contains(&qlen) { + return; + } + let mut qbuf = [0u8; 4096]; + let query = &mut qbuf[..qlen]; + if conn.read_exact(query).is_err() || !is_query(query) { return; } static SAID: AtomicBool = AtomicBool::new(false); if !SAID.swap(true, Ordering::Relaxed) { crate::diag::warn!("the VM's DNS at its gateway did not answer; container lookups go through the Mac"); } - let name = question_name(&query).unwrap_or_default(); + let name = question_name(query).unwrap_or_default(); let servers = mac_resolvers(&name, Path::new("/etc/resolv.conf"), Path::new("/etc/resolver")); - let reply = relay_query(&query, &servers).unwrap_or_else(|| servfail(&query)); - let mut out = Vec::with_capacity(2 + reply.len()); - out.extend_from_slice(&(reply.len().min(u16::MAX as usize) as u16).to_be_bytes()); - out.extend_from_slice(&reply[..reply.len().min(u16::MAX as usize)]); - let _ = conn.write_all(&out); + let reply = relay_query(query, &servers).unwrap_or_else(|| servfail(query)); + let rlen = reply.len().min(usize::from(u16::MAX)); + let hdr = (rlen as u16).to_be_bytes(); + let _ = conn.write_all(&hdr).and_then(|()| conn.write_all(&reply[..rlen])); } /// Whether `q` is a standard DNS query with one well-formed question: the @@ -183,6 +187,11 @@ fn relay_query(query: &[u8], servers: &[SocketAddr]) -> Option> { let Ok(n) = sock.recv(&mut buf) else { break }; let r = &buf[..n]; if n >= 12 && r[..2] == query[..2] && r[2] & 0x80 != 0 { + if r[2] & 0x02 != 0 + && let Some(full) = relay_tcp(query, *server, until.saturating_duration_since(Instant::now())) + { + return Some(full); + } return Some(r.to_vec()); } } @@ -190,6 +199,29 @@ fn relay_query(query: &[u8], servers: &[SocketAddr]) -> Option> { None } +/// Retries a truncated (`TC=1`) UDP reply over TCP so large responses arrive whole. +fn relay_tcp(query: &[u8], server: SocketAddr, wait: Duration) -> Option> { + if wait.is_zero() { + return None; + } + let mut stream = std::net::TcpStream::connect_timeout(&server, wait).ok()?; + let _ = stream.set_read_timeout(Some(wait)); + let _ = stream.set_write_timeout(Some(wait)); + let len = u16::try_from(query.len()).ok()?.to_be_bytes(); + stream.write_all(&len).ok()?; + stream.write_all(query).ok()?; + let mut rlen = [0u8; 2]; + stream.read_exact(&mut rlen).ok()?; + let n = usize::from(u16::from_be_bytes(rlen)); + if !(12..=65_535).contains(&n) { + return None; + } + let mut buf = vec![0u8; 65_535]; + stream.read_exact(&mut buf[..n]).ok()?; + buf.truncate(n); + (buf[..2] == query[..2] && buf[2] & 0x80 != 0).then_some(buf) +} + /// SERVFAIL for `query`: no resolver on the Mac answered either. fn servfail(query: &[u8]) -> Vec { let end = question_end(query).unwrap_or(12).min(query.len()); @@ -352,6 +384,39 @@ mod tests { assert_eq!(super::question_name(&q).as_deref(), Some("registry-1.docker.io")); } + #[test] + fn a_truncated_udp_reply_is_retried_over_tcp() { + use std::io::{Read, Write}; + let udp = UdpSocket::bind("127.0.0.1:0").unwrap(); + let addr = udp.local_addr().unwrap(); + let tcp = std::net::TcpListener::bind(addr).unwrap(); + let udp_srv = std::thread::spawn(move || { + let mut buf = [0u8; 512]; + let (n, from) = udp.recv_from(&mut buf).unwrap(); + buf[2] |= 0x82; // QR=1, TC=1 + udp.send_to(&buf[..n], from).unwrap(); + }); + let tcp_srv = std::thread::spawn(move || { + let (mut s, _) = tcp.accept().unwrap(); + let mut len = [0u8; 2]; + s.read_exact(&mut len).unwrap(); + let mut q = vec![0u8; u16::from_be_bytes(len) as usize]; + s.read_exact(&mut q).unwrap(); + q[2] = 0x81; + q[3] = 0x80; + q[6..8].copy_from_slice(&1u16.to_be_bytes()); + q.extend_from_slice(&[0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 104, 16, 1, 2]); + s.write_all(&(q.len() as u16).to_be_bytes()).unwrap(); + s.write_all(&q).unwrap(); + }); + let q = query("registry.npmjs.org", 1); + let r = super::relay_query(&q, &[addr]).expect("retried over TCP"); + udp_srv.join().unwrap(); + tcp_srv.join().unwrap(); + assert_eq!(r[2] & 0x02, 0, "full TCP reply has TC=0"); + assert_eq!(&r[r.len() - 4..], &[104, 16, 1, 2]); + } + #[test] fn only_standard_queries_are_relayed() { let q = query("registry-1.docker.io", 1); diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index 623c4e551..16b24f66c 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -234,11 +234,15 @@ pub fn unverified(c: &kiri_image::RegistryConfig, names: &[String]) -> Vec String { +/// `names` ([`registry_names`]), with `host_net` selecting `127.0.0.1` on +/// Linux when the builder runs in the host network namespace (`--driver-opt +/// network=host`), where the loopback listener is always up even before `kiri0` +/// exists. +pub fn config_for(engine: &Engine, c: &kiri_image::RegistryConfig, names: &[String], host_net: bool) -> String { let mut tables: Vec<(String, Table)> = Vec::new(); if let Some(port) = LISTENING.get().copied().flatten() { - let host = format!("{}:{port}", mirror_host(&engine.lock_net())); + let addr = if cfg!(target_os = "linux") && host_net { "127.0.0.1".to_owned() } else { mirror_host(&engine.lock_net()) }; + let host = format!("{addr}:{port}"); let token = token(); for name in names { add_mirror(&mut tables, name, format!("{host}/{token}/{name}")); @@ -354,8 +358,8 @@ fn answer(conn: TcpStream, engine: &Engine) -> io::Result<()> { return head(&mut w, "405 Method Not Allowed", "", 0); } match lookup(&engine.store, target.split('?').next().unwrap_or_default(), &token()) { - Some(Found::Manifest(bytes, digest)) => { - head(&mut w, "200 OK", &format!("Content-Type: application/vnd.oci.image.manifest.v1+json\r\nDocker-Content-Digest: {digest}\r\n"), bytes.len() as u64)?; + Some(Found::Manifest(bytes, media_type, digest)) => { + head(&mut w, "200 OK", &format!("Content-Type: {media_type}\r\nDocker-Content-Digest: {digest}\r\n"), bytes.len() as u64)?; if method == "GET" { w.write_all(&bytes)?; } @@ -373,18 +377,50 @@ fn answer(conn: TcpStream, engine: &Engine) -> io::Result<()> { w.flush() } +const OCI_MANIFEST: &str = "application/vnd.oci.image.manifest.v1+json"; +const OCI_INDEX: &str = "application/vnd.oci.image.index.v1+json"; +const MAX_MANIFEST: u64 = 4 << 20; + #[derive(Debug)] enum Found { - Manifest(Vec, String), + Manifest(Vec, String, String), Blob(std::path::PathBuf, String), } +/// Content-Type for raw manifest or index JSON `bytes`. +fn manifest_media_type(bytes: &[u8]) -> String { + if let Ok(v) = serde_json::from_slice::(bytes) { + if let Some(mt) = v["mediaType"].as_str().map(str::trim).filter(|m| !m.is_empty() && !m.contains(['\r', '\n'])) { + return mt.to_owned(); + } + if v.get("manifests").is_some() { + return OCI_INDEX.to_owned(); + } + } + OCI_MANIFEST.to_owned() +} + +/// Reads a raw upstream manifest or multi-arch index blob saved during `pull`, +/// verifying that its bytes hash to `digest`. +fn stored_manifest(store: &kiri_image::Store, digest: &str) -> Option<(Vec, String)> { + let path = store.blob_path(digest).ok()?; + let len = std::fs::metadata(&path).ok()?.len(); + if len > MAX_MANIFEST { + return None; + } + let bytes = std::fs::read(path).ok()?; + (kiri_image::store::sha256_digest(&bytes) == digest).then(|| { + let media_type = manifest_media_type(&bytes); + (bytes, media_type) + }) +} + /// An image's manifest as Kiri serves it, and its digest. fn manifest(store: &kiri_image::Store, i: &Image) -> Option<(Vec, String)> { let config_size = std::fs::metadata(store.blob_path(&i.config_digest).ok()?).ok()?.len(); let m = json!({ "schemaVersion": 2, - "mediaType": "application/vnd.oci.image.manifest.v1+json", + "mediaType": OCI_MANIFEST, "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": i.config_digest, "size": config_size}, "layers": i.layers.iter().map(|l| json!({"mediaType": l.media_type, "digest": l.digest, "size": l.size})).collect::>(), }); @@ -421,7 +457,16 @@ fn lookup(store: &kiri_image::Store, path: &str, token: &str) -> Option { let in_repo = |i: &&Image| Reference::parse(&i.name).is_ok_and(|n| n.registry == registry && n.repository == repo); if is_manifest { if reference.starts_with("sha256:") { - return images.iter().filter(in_repo).find_map(|i| manifest(store, i).filter(|(_, d)| *d == reference)).map(|(b, d)| Found::Manifest(b, d)); + // Serve the exact raw manifest or multi-arch index bytes saved + // during `docker pull` when an image in this repository owns that + // digest, so digest-pinned builds (`FROM repo:tag@sha256:…` or + // `FROM repo@sha256:…`) verify cleanly from Kiri's store (#288, #330). + if images.iter().filter(in_repo).any(|i| i.digest == reference || i.index_digest.as_deref() == Some(reference.as_str())) + && let Some((b, mt)) = stored_manifest(store, &reference) + { + return Some(Found::Manifest(b, mt, reference)); + } + return images.iter().filter(in_repo).find_map(|i| manifest(store, i).filter(|(_, d)| *d == reference)).map(|(b, d)| Found::Manifest(b, OCI_MANIFEST.to_owned(), d)); } let wanted = Reference::parse(&format!("{registry}/{repo}:{reference}")).ok()?.short(); // A tag a registry published is the registry's to answer: Kiri holds @@ -431,10 +476,10 @@ fn lookup(store: &kiri_image::Store, path: &str, token: &str) -> Option { // mirror and pull the platform it asked for. let i = images.iter().find(|i| i.name == wanted && serve_tag(i))?; let (b, d) = manifest(store, i)?; - return Some(Found::Manifest(b, d)); + return Some(Found::Manifest(b, OCI_MANIFEST.to_owned(), d)); } // Only blobs of that repository's images. - let owned = images.iter().filter(in_repo).any(|i| i.config_digest == reference || i.layers.iter().any(|l| l.digest == reference)); + let owned = images.iter().filter(in_repo).any(|i| i.referenced_digests().any(|d| d == reference)); let path = store.blob_path(&reference).ok()?; (owned && path.is_file()).then_some(Found::Blob(path, reference)) } @@ -602,7 +647,7 @@ mod tests { assert!(lookup(&store, "/v2/tok/docker.io/library/alpine/manifests/3.20", "tok").is_none()); assert!(matches!( lookup(&store, &format!("/v2/tok/docker.io/library/alpine/manifests/{pulled_manifest_digest}"), "tok"), - Some(Found::Manifest(_, d)) if d == pulled_manifest_digest + Some(Found::Manifest(_, _, d)) if d == pulled_manifest_digest )); assert!(matches!( lookup(&store, &format!("/v2/tok/docker.io/library/alpine/blobs/{layer_digest}"), "tok"), @@ -620,7 +665,7 @@ mod tests { store.put_image(pulled.tagged("mybase:dev".into())).unwrap(); assert!(matches!( lookup(&store, "/v2/tok/docker.io/library/mybase/manifests/dev", "tok"), - Some(Found::Manifest(_, d)) if d == pulled_manifest_digest + Some(Found::Manifest(_, _, d)) if d == pulled_manifest_digest )); assert!(matches!( lookup(&store, &format!("/v2/tok/docker.io/library/mybase/blobs/{layer_digest}"), "tok"), @@ -628,12 +673,55 @@ mod tests { )); // 3. Built, loaded or committed here: served by tag until pushed to a registry. - let local = kiri_image::archive::from_config("localhost:5000/myapp:dev".into(), &cfg_digest, &cfg, layers); + let local = kiri_image::archive::from_config("localhost:5000/myapp:dev".into(), &cfg_digest, &cfg, layers.clone()); store.put_image(local).unwrap(); assert!(matches!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok"), Some(Found::Manifest(..)))); store.set_pushed("localhost:5000/myapp:dev", &cfg_digest, &format!("sha256:{}", "c".repeat(64))).unwrap(); assert!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok").is_none()); + // 4. Digest-pinned multi-arch pull (`docker pull oven/bun:1-alpine@sha256:`): + // raw index and platform manifest bytes are served verbatim with their + // upstream Content-Type so BuildKit's SHA-256 verification succeeds (#288, #330). + let raw_manifest = format!( + "{{\n \"schemaVersion\": 2,\n \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n \"config\": {{\"mediaType\": \"application/vnd.docker.container.image.v1+json\", \"size\": 42, \"digest\": \"{cfg_digest}\"}},\n \"layers\": [{{\"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\", \"size\": {layer_size}, \"digest\": \"{layer_digest}\"}}]\n}}" + ); + let (raw_man_digest, _) = write_blob(raw_manifest.as_bytes()); + let raw_index = format!( + "{{\n \"schemaVersion\": 2,\n \"mediaType\": \"application/vnd.oci.image.index.v1+json\",\n \"manifests\": [\n {{\"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\", \"size\": {}, \"digest\": \"{raw_man_digest}\", \"platform\": {{\"architecture\": \"amd64\", \"os\": \"linux\"}}}},\n {{\"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\", \"size\": 999, \"digest\": \"sha256:{}\", \"platform\": {{\"architecture\": \"arm64\", \"os\": \"linux\"}}}}\n ]\n}}", + raw_manifest.len(), + "e".repeat(64) + ); + let (raw_idx_digest, _) = write_blob(raw_index.as_bytes()); + let pinned = Image { + name: format!("oven/bun@{raw_idx_digest}"), + digest: raw_man_digest.clone(), + index_digest: Some(raw_idx_digest.clone()), + ..kiri_image::archive::from_config(format!("oven/bun@{raw_idx_digest}"), &cfg_digest, &cfg, layers) + }; + store.put_image(pinned).unwrap(); + match lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/{raw_idx_digest}"), "tok") { + Some(Found::Manifest(b, mt, d)) => { + assert_eq!(b, raw_index.as_bytes(), "exact upstream index bytes"); + assert_eq!(kiri_image::store::sha256_digest(&b), raw_idx_digest); + assert_eq!(mt, "application/vnd.oci.image.index.v1+json"); + assert_eq!(d, raw_idx_digest); + } + other => panic!("expected raw index manifest, got {other:?}"), + } + match lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/{raw_man_digest}"), "tok") { + Some(Found::Manifest(b, mt, d)) => { + assert_eq!(b, raw_manifest.as_bytes(), "exact upstream platform manifest bytes"); + assert_eq!(kiri_image::store::sha256_digest(&b), raw_man_digest); + assert_eq!(mt, "application/vnd.docker.distribution.manifest.v2+json"); + assert_eq!(d, raw_man_digest); + } + other => panic!("expected raw platform manifest, got {other:?}"), + } + // Unpulled platform digest returns None (404) so BuildKit falls back to the registry. + assert!(lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/sha256:{}", "e".repeat(64)), "tok").is_none()); + // Cross-repo isolation holds for raw manifests too. + assert!(lookup(&store, &format!("/v2/tok/docker.io/library/other/manifests/{raw_idx_digest}"), "tok").is_none()); + let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 261ea9355..3004fd522 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 +### Build: serve digest-pinned local bases, relay default-bridge stub DNS, and support host-network builds (unreleased) +- Fixes: #209 Windows: docker build hangs when a RUN step needs network (BuildKit has no usable DNS); #288 BuildKit fails to resolve digest-pinned FROM image already pulled into Kiri's image store; #330 Linux: containers have no DNS on the default bridge; Compose/BuildKit builds can't resolve a digest-pinned base; bun install gets ConnectionRefused +- Caused: none known +- Caused by: - +- Check: `dns-default-bridge-stub`, `build-pinned-digest`, `build-host-network-dns` + ### #640, #218, #761 Windows: forward published UDP and host-IP/LAN TCP ports to WSL 2, and write `kiri diag report --out` on the Windows filesystem (unreleased) - Fixes: #640 [Windows] Published UDP Ports Are Not Forwarding Packets to Containers; #218 Windows: publishing a port on a host IP (-p IP:port:port) fails with 'Address not available (os error 99)'; 0.0.0.0 is loopback-only; #761 `kiri diag report --out ` on Windows wrote inside the WSL rootfs instead of the Windows path - Caused: none known diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 76848ec5c..f06ddac3d 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -450,7 +450,41 @@ lt = "application/vnd.docker.distribution.manifest.list.v2+json" put(f"{u}/manifests/multi", lt, json.dumps({"schemaVersion": 2, "mediaType": lt, "manifests": ms}).encode()) '\'' 5055' t build-platform-pulled-tag "resolved-other-platform" "$MULTI_PUSH && here=\$(docker version --format '{{.Server.Arch}}') && { [ \"\$here\" = amd64 ] && other=arm64 || other=amd64; } && docker pull -q kiri-mirror-only:multi >/dev/null && lhere=\$(docker image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:multi) && printf 'FROM kiri-mirror-only:multi\\nCOPY Dockerfile /df\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache --platform linux/\$other -t kiri-mirror-only:built /bins >/dev/null 2>&1 && lbuilt=\$(docker image inspect -f '{{index .RootFS.Layers 0}}' kiri-mirror-only:built) && pbuilt=\$(docker image inspect -f '{{.Architecture}} {{index .Config.Labels \"plat\"}}' kiri-mirror-only:built) && [ \"\$pbuilt\" = \"\$other from-\$other\" ] && [ \"\$lbuilt\" != \"\$lhere\" ] && echo resolved-other-platform || echo \"here=\$here got=\$pbuilt lhere=\$lhere lbuilt=\$lbuilt\"" -t build-local-tag "local-still-served" "here=\$(docker version --format '{{.Server.Arch}}') && docker tag kiri-mirror-only:multi kiri-local-only:1 && printf 'FROM kiri-local-only:1\\nCOPY Dockerfile /df2\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache -t kiri-local-only:built /bins >/dev/null 2>&1 && [ \"\$(docker image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-local-only:built)\" = \"from-\$here\" ] && echo local-still-served; docker rmi kiri-mirror-only:multi kiri-mirror-only:built kiri-local-only:1 kiri-local-only:built >/dev/null 2>&1" +t build-local-tag "local-still-served" "here=\$(docker version --format '{{.Server.Arch}}') && docker tag kiri-mirror-only:multi kiri-local-only:1 && printf 'FROM kiri-local-only:1\\nCOPY Dockerfile /df2\\n' > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache -t kiri-local-only:built /bins >/dev/null 2>&1 && [ \"\$(docker image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-local-only:built)\" = \"from-\$here\" ] && echo local-still-served" +# A digest-pinned FROM (`FROM repo@sha256:…` and `FROM repo:tag@sha256:…`) +# builds from Kiri's store mirror using the exact raw index and manifest bytes +# saved at pull time, even after the upstream mirror is removed (#288, #330). +t build-pinned-digest "pinned-index-and-tag-ok" "here=\$(docker version --format '{{.Server.Arch}}') && gw=\$(docker inspect kiri-reg-http --format '{{.NetworkSettings.IPAddress}}'):5000 && rd=\$(docker image inspect -f '{{index .RepoDigests 0}}' kiri-mirror-only:multi) && d=\${rd#*@} && /opt/kiri/kiri registry mirror remove http://\$gw >/dev/null 2>&1 && printf \"FROM kiri-mirror-only@\$d\\nCOPY Dockerfile /df3\\n\" > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache -t kiri-mirror-only:pin1 /bins >/dev/null 2>&1 && printf \"FROM kiri-mirror-only:multi@\$d\\nCOPY Dockerfile /df4\\n\" > /bins/Dockerfile && DOCKER_BUILDKIT=0 docker build -q --no-cache -t kiri-mirror-only:pin2 /bins >/dev/null 2>&1 && [ \"\$(docker image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-mirror-only:pin1)\" = \"from-\$here\" ] && [ \"\$(docker image inspect -f '{{index .Config.Labels \"plat\"}}' kiri-mirror-only:pin2)\" = \"from-\$here\" ] && echo pinned-index-and-tag-ok; docker rmi kiri-mirror-only:multi kiri-mirror-only:built kiri-mirror-only:pin1 kiri-mirror-only:pin2 kiri-local-only:built >/dev/null 2>&1" +# When the host's /etc/resolv.conf names only 127.0.0.53 (systemd-resolved's +# stub, with no /run/systemd/resolve/resolv.conf), default-bridge containers, +# standard build steps, and --network=host build steps all resolve through the +# agent at the bridge gateway over UDP and TCP (#209, #330). +STUB53='python3 -c '\'' +import socket, struct, threading +def ans(q): + i = 12 + while i < len(q) and q[i]: i += 1 + q[i] + end = i + 5 + qt = struct.unpack("!H", q[end-4:end-2])[0] if end <= len(q) else 0 + if qt == 1: + return q[:2] + b"\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00" + q[12:end] + b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04\x0a\x35\x35\x35" + return q[:2] + b"\x81\x80\x00\x01\x00\x00\x00\x00\x00\x00" + q[12:end] +u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); u.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); u.bind(("127.0.0.53", 53)) +t = socket.socket(socket.AF_INET, socket.SOCK_STREAM); t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); t.bind(("127.0.0.53", 53)); t.listen(16) +def ul(): + while True: + d, a = u.recvfrom(2048); u.sendto(ans(d), a) +def tl(): + while True: + c, _ = t.accept() + with c: + h = c.recv(2) + if len(h) == 2: + 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\"" # 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 diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 613c3a1ed..c517afba8 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -303,3 +303,6 @@ crates/kiri/src/hostrelay.rs #550 on Windows (WSL 2), host.docker.internal resol crates/kiri-win/src/ports.rs #640 WSL 2's localhostForwarding only forwards loopback TCP, so published UDP container ports and non-loopback Windows host-IP or 0.0.0.0 LAN TCP bindings were unreachable on Windows (#218) crates/kiri/src/daemon/ports.rs #218 publishing a container port on a Windows host interface IP (-p IP:port:port) failed inside WSL 2 with EADDRNOTAVAIL (os error 99) instead of binding WSL's eth0 address for kiri-win to forward crates/kiri/src/wsl.rs #761 running kiri.exe diag report [--out PATH] on Windows wrote the report file inside the WSL Linux rootfs instead of the Windows filesystem +dns-default-bridge-stub #330 on a Linux host whose /etc/resolv.conf names only 127.0.0.53 (systemd-resolved), default-bridge containers got 1.1.1.1 instead of querying the host stub through the bridge gateway over UDP and TCP +build-pinned-digest #288 a digest-pinned FROM image (@sha256:...) already pulled into Kiri's store was re-serialized instead of served with its upstream manifest and index bytes, failing BuildKit's digest check (#330) +build-host-network-dns #209 build steps under docker build and docker build --network=host (or a host-network builder) could not resolve names through a loopback stub resolver on the host (#330) From 4a1dc2780bb1cca71ff0053520dd00c4c5890748 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:24:37 +0100 Subject: [PATCH 068/157] CLI: kiri --help lists only commands compiled for this OS (#743) (#860) --- crates/kiri/src/main.rs | 422 ++++++++++++++++++++++++++++++++-------- docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + 3 files changed, 349 insertions(+), 80 deletions(-) diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index fced5e890..eec075d2d 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -86,31 +86,175 @@ mod tools; #[cfg(any(target_os = "macos", target_os = "linux"))] mod update; -const USAGE: &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 daemon - kiri bridge [--socket PATH] (WSL2: the end of kiri-win.exe) - kiri ui [--start] [--view containers|images|volumes|networks] - kiri setup [--use] [--no-agent] | kiri setup --uninstall - kiri build-with [docker|kiri] which builder docker build uses - kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports - kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors - kiri scan [--json] [--history] known vulnerabilities in an image, found by Grype - kiri update [--check] update Kiri (with a container: docker's update) - kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N] - kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out) - kiri PORT [NAME] share a local port on the internet (same as kiri share PORT) - kiri share PORT|CONTAINER [--name N] | share login | logout | status - kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] - kiri usb [list] | attach DEVICE | detach DEVICE USB devices for containers, beta (Mac: pass through to the VM) - kiri machine create NAME [--distro D] | list | shell NAME | stop | delete NAME - kiri import [orbstack | desktop-linux] [--list | [--force] [image|volume|container NAME]] - kiri bench [--runs N] [--image IMAGE] [--network none|bridge] - kiri boot [--console] [--pings N] - kiri raw run [--rm] [-e KEY=VALUE]... IMAGE [COMMAND...] (its own guest, no daemon) - kiri raw pull | raw images | raw rmi ..."; +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)", + #[cfg(unix)] + " kiri daemon", + #[cfg(target_os = "linux")] + " kiri bridge [--socket PATH] (WSL2: the end of kiri-win.exe)", + #[cfg(any(target_os = "macos", target_os = "linux"))] + " kiri ui [--start] [--view containers|images|volumes|networks|builds]", + #[cfg(target_os = "macos")] + " kiri setup [--use] [--no-agent] | kiri setup --uninstall", + #[cfg(unix)] + " kiri build-with [docker|kiri] which builder docker build uses", + " kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports", + " kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors", + " kiri scan [--json] [--history] known vulnerabilities in an image, found by Grype", + #[cfg(target_os = "macos")] + " kiri update [--check] update Kiri (with a container: docker's update)", + #[cfg(target_os = "linux")] + " kiri update --check check for a newer Kiri (with a container: docker's update)", + " kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N]", + " kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out)", + " kiri PORT [NAME] share a local port on the internet (same as kiri share PORT)", + " kiri share PORT|CONTAINER [--name N] | share login | logout | status", + " kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N]", + " kiri usb [list] | attach DEVICE | detach DEVICE USB devices for containers, beta (Mac: pass through to the VM)", + " kiri machine create NAME [--distro D] | list | shell NAME | stop | delete NAME", + #[cfg(target_os = "macos")] + " kiri import [orbstack | desktop-linux] [--list | [--force] [image|volume|container NAME]]", + #[cfg(target_os = "macos")] + " kiri bench [--runs N] [--image IMAGE] [--network none|bridge]", + #[cfg(target_os = "macos")] + " kiri boot [--console] [--pings N]", + #[cfg(unix)] + " kiri raw run [--rm] [-e KEY=VALUE]... IMAGE [COMMAND...] (its own guest, no daemon)", + #[cfg(unix)] + " kiri raw pull | raw images | raw rmi ...", +]; + +fn usage() -> String { + USAGE_LINES.join("\n") +} + +#[derive(Debug, PartialEq, Eq)] +enum Command<'a> { + #[cfg(unix)] + Daemon(&'a [String]), + #[cfg(target_os = "linux")] + Bridge(&'a [String]), + #[cfg(target_os = "linux")] + HostRelay, + #[cfg(target_os = "linux")] + HostAccess(&'a [String]), + #[cfg(unix)] + RawRun(&'a [String]), + #[cfg(unix)] + RawPull(&'a [String]), + #[cfg(unix)] + RawImages(&'a [String]), + #[cfg(unix)] + RawRmi(&'a [String]), + #[cfg(target_os = "macos")] + Bench(&'a [String]), + #[cfg(target_os = "macos")] + Boot(&'a [String]), + #[cfg(target_os = "macos")] + Setup(&'a [String]), + #[cfg(any(unix, windows))] + Share(&'a [String]), + #[cfg(unix)] + Start, + #[cfg(windows)] + Start(&'a [String]), + #[cfg(unix)] + BuildWith(&'a [String]), + #[cfg(unix)] + Domains(&'a [String]), + #[cfg(unix)] + Registry(&'a [String]), + #[cfg(unix)] + Scan(&'a [String]), + #[cfg(unix)] + K8s(&'a [String]), + #[cfg(unix)] + Machine(&'a [String]), + #[cfg(unix)] + Usb(&'a [String]), + #[cfg(target_os = "macos")] + Import(&'a [String]), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Update(&'a [String]), + #[cfg(unix)] + Diag(&'a [String]), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Ui(&'a [String]), + #[cfg(any(unix, windows))] + Docker(&'a [String]), + #[cfg(windows)] + Wsl(&'a [String]), +} + +impl<'a> Command<'a> { + fn parse(args: &'a [String]) -> Option> { + match args.first().map(String::as_str) { + #[cfg(unix)] + Some("daemon") => Some(Command::Daemon(&args[1..])), + #[cfg(target_os = "linux")] + Some("bridge") => Some(Command::Bridge(&args[1..])), + #[cfg(target_os = "linux")] + Some("hostrelay") => Some(Command::HostRelay), + #[cfg(target_os = "linux")] + Some("host-access") => Some(Command::HostAccess(&args[1..])), + #[cfg(unix)] + Some("raw") => match args.get(1).map(String::as_str) { + Some("run") => Some(Command::RawRun(&args[2..])), + Some("pull") => Some(Command::RawPull(&args[2..])), + Some("images") => Some(Command::RawImages(&args[2..])), + Some("rmi") => Some(Command::RawRmi(&args[2..])), + _ => None, + }, + #[cfg(target_os = "macos")] + Some("bench") => Some(Command::Bench(&args[1..])), + #[cfg(target_os = "macos")] + Some("boot") => Some(Command::Boot(&args[1..])), + #[cfg(target_os = "macos")] + Some("setup") => Some(Command::Setup(&args[1..])), + #[cfg(any(unix, windows))] + Some("share") => Some(Command::Share(&args[1..])), + // `kiri 3000`: share a port straight away. + #[cfg(any(unix, windows))] + Some(a) if share::is_shorthand(a) => Some(Command::Share(args)), + // Bare: the window's Start (`kiri start NAME` is docker's start). + #[cfg(unix)] + Some("start") if args.len() == 1 => Some(Command::Start), + // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. + #[cfg(windows)] + Some("start") if args.len() == 1 => Some(Command::Start(args)), + #[cfg(unix)] + Some("build-with") => Some(Command::BuildWith(&args[1..])), + #[cfg(unix)] + Some("domains") => Some(Command::Domains(&args[1..])), + #[cfg(unix)] + Some("registry") => Some(Command::Registry(&args[1..])), + #[cfg(unix)] + Some("scan") => Some(Command::Scan(&args[1..])), + #[cfg(unix)] + Some("k8s") => Some(Command::K8s(&args[1..])), + #[cfg(unix)] + Some("machine") => Some(Command::Machine(&args[1..])), + #[cfg(unix)] + Some("usb") => Some(Command::Usb(&args[1..])), + #[cfg(target_os = "macos")] + Some("import") => Some(Command::Import(&args[1..])), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Some("update") if !docker::is_container_update(&args[1..]) => Some(Command::Update(&args[1..])), + #[cfg(unix)] + Some("diag") => Some(Command::Diag(&args[1..])), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Some("ui") => Some(Command::Ui(args)), + #[cfg(any(unix, windows))] + Some(c) if docker::handles(c) => Some(Command::Docker(args)), + // Windows: the engine's commands, by the `kiri` in WSL. + #[cfg(windows)] + Some(c) if wsl::COMMANDS.contains(&c) => Some(Command::Wsl(args)), + _ => None, + } + } +} fn main() -> ExitCode { flavor::init(); @@ -127,91 +271,82 @@ fn main() -> ExitCode { None if setup::launched_from_app() => diag::Part::Ui, _ => diag::Part::Cli, }); - let result: std::io::Result<()> = match args.first().map(String::as_str) { + let result: std::io::Result<()> = match Command::parse(&args) { #[cfg(unix)] - Some("daemon") => daemon::run(&args[1..]), + Some(Command::Daemon(rest)) => daemon::run(rest), #[cfg(target_os = "linux")] - Some("bridge") => bridge::run(&args[1..]), + Some(Command::Bridge(rest)) => bridge::run(rest), #[cfg(target_os = "linux")] - Some("hostrelay") => hostrelay::run(), + Some(Command::HostRelay) => hostrelay::run(), // Linux hosts: what the window's onboarding needs root for (through pkexec). #[cfg(target_os = "linux")] - Some("host-access") => match hostaccess::run(&args[1..]) { + Some(Command::HostAccess(rest)) => match hostaccess::run(rest) { Ok(code) => return ExitCode::from(code), Err(e) => Err(e), }, #[cfg(unix)] - Some("raw") => match args.get(1).map(String::as_str) { - Some("run") => run::run(&args[2..]), - Some("pull") => images::pull(&args[2..]), - Some("images") => images::list(&args[2..]), - Some("rmi") => images::remove(&args[2..]), - _ => { - eprintln!("{USAGE}"); - return ExitCode::FAILURE; - } - }, + Some(Command::RawRun(rest)) => run::run(rest), + #[cfg(unix)] + Some(Command::RawPull(rest)) => images::pull(rest), + #[cfg(unix)] + Some(Command::RawImages(rest)) => images::list(rest), + #[cfg(unix)] + Some(Command::RawRmi(rest)) => images::remove(rest), #[cfg(target_os = "macos")] - Some("bench") => bench::run(&args[1..]), + Some(Command::Bench(rest)) => bench::run(rest), #[cfg(target_os = "macos")] - Some("boot") => boot::run(&args[1..]), + Some(Command::Boot(rest)) => boot::run(rest), #[cfg(target_os = "macos")] - Some("setup") => setup::run(&args[1..]), - #[cfg(any(unix, windows))] - Some("share") => share::run(&args[1..]), - // `kiri 3000`: share a port straight away. + Some(Command::Setup(rest)) => setup::run(rest), #[cfg(any(unix, windows))] - Some(a) if share::is_shorthand(a) => share::run(&args), - // Bare: the window's Start (`kiri start NAME` is docker's start). + Some(Command::Share(rest)) => share::run(rest), #[cfg(unix)] - Some("start") if args.len() == 1 => engine_start(), - // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. + Some(Command::Start) => engine_start(), #[cfg(windows)] - Some("start") if args.len() == 1 => wsl::run(&args), + Some(Command::Start(all)) => wsl::run(all), #[cfg(unix)] - Some("build-with") => buildwith::cli(&args[1..]), + Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] - Some("domains") => domains_cli::run(&args[1..]), + Some(Command::Domains(rest)) => domains_cli::run(rest), #[cfg(unix)] - Some("registry") => registry_cli::run(&args[1..]), + Some(Command::Registry(rest)) => registry_cli::run(rest), #[cfg(unix)] - Some("scan") => scan_cli::run(&args[1..]), + Some(Command::Scan(rest)) => scan_cli::run(rest), #[cfg(unix)] - Some("k8s") => k8s::run(&args[1..]), + Some(Command::K8s(rest)) => k8s::run(rest), #[cfg(unix)] - Some("machine") => machine::run(&args[1..]), + Some(Command::Machine(rest)) => machine::run(rest), #[cfg(unix)] - Some("usb") => usb::run(&args[1..]), + Some(Command::Usb(rest)) => usb::run(rest), #[cfg(target_os = "macos")] - Some("import") => import::run(&args[1..]), + Some(Command::Import(rest)) => import::run(rest), #[cfg(any(target_os = "macos", target_os = "linux"))] - Some("update") if !docker::is_container_update(&args[1..]) => update::run(&args[1..]), + Some(Command::Update(rest)) => update::run(rest), #[cfg(unix)] - Some("diag") => diag::run(&args[1..]), - // Opening Kiri.app: set up on first launch, then the window. - #[cfg(target_os = "macos")] - None if setup::launched_from_app() => { - setup::first_launch(); - ui::run(true, None) - } + Some(Command::Diag(rest)) => diag::run(rest), #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some("ui") => ui::run( - args.iter().any(|a| a == "--start"), - args.iter().position(|a| a == "--view").and_then(|i| args.get(i + 1)).cloned(), + Some(Command::Ui(all)) => ui::run( + all.iter().any(|a| a == "--start"), + all.iter().position(|a| a == "--view").and_then(|i| all.get(i + 1)).cloned(), ), // The static engine has no window: the package's own build of it. #[cfg(all(target_os = "linux", not(feature = "window")))] - Some("ui") => window(&args), + Some(Command::Ui(all)) => window(all), #[cfg(any(unix, windows))] - Some(c) if docker::handles(c) => { + Some(Command::Docker(all)) => { engine_version_check(); - docker::run(&args) + docker::run(all) } - // Windows: the engine's commands, by the `kiri` in WSL. #[cfg(windows)] - Some(c) if wsl::COMMANDS.contains(&c) => wsl::run(&args), - _ => { - eprintln!("{USAGE}"); + Some(Command::Wsl(all)) => wsl::run(all), + // Opening Kiri.app: set up on first launch, then the window. + #[cfg(target_os = "macos")] + None if args.is_empty() && setup::launched_from_app() => { + setup::first_launch(); + ui::run(true, None) + } + None => { + eprintln!("{}", usage()); return ExitCode::FAILURE; } }; @@ -294,11 +429,138 @@ fn engine_version_check() { #[cfg(test)] mod tests { - use super::USAGE; + use super::{Command, usage}; + + fn parse(words: &[&str]) -> Option> { + let args: Vec = words.iter().map(|s| (*s).to_owned()).collect(); + Command::parse(&args)?; + Some(args) + } + + fn advertised_subcommands(help: &str) -> Vec<&str> { + help.lines() + .filter_map(|line| line.strip_prefix("usage: ").unwrap_or(line).trim_start().strip_prefix("kiri ")) + .filter_map(|rest| rest.split_whitespace().next()) + .collect() + } #[test] fn usage_lists_scan_command() { - assert!(USAGE.contains("kiri scan [--json] [--history] ")); - assert!(!USAGE.ends_with('\n')); + let help = usage(); + assert!(help.contains("kiri scan [--json] [--history] ")); + assert!(!help.ends_with('\n')); + } + + #[test] + fn usage_lists_only_commands_for_this_os() { + let help = usage(); + let cmds = advertised_subcommands(&help); + for common in ["COMMAND", "start", "domains", "registry", "scan", "diag", "PORT", "share", "k8s", "usb", "machine"] { + assert!(cmds.contains(&common), "help missing `{common}`:\n{help}"); + } + #[cfg(unix)] + { + for unix_cmd in ["daemon", "ui", "build-with", "update", "raw"] { + assert!(cmds.contains(&unix_cmd), "unix help missing `{unix_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri ui [--start] [--view containers|images|volumes|networks|builds]"), + "unix help missing `kiri ui` views (including builds):\n{help}" + ); + } + #[cfg(target_os = "macos")] + { + for mac_cmd in ["setup", "update", "import", "bench", "boot"] { + assert!(cmds.contains(&mac_cmd), "macOS help missing `{mac_cmd}`:\n{help}"); + } + assert!(help.contains("kiri update [--check]"), "macOS help missing `kiri update [--check]`:\n{help}"); + assert!(!cmds.contains(&"bridge"), "macOS help must not list Linux-only `bridge`:\n{help}"); + } + #[cfg(target_os = "linux")] + { + assert!(cmds.contains(&"bridge"), "Linux help missing `bridge`:\n{help}"); + assert!(cmds.contains(&"update"), "Linux help missing `update`:\n{help}"); + assert!(help.contains("kiri update --check"), "Linux help missing `kiri update --check`:\n{help}"); + assert!(!help.contains("kiri update [--check]"), "Linux help must not list macOS `kiri update [--check]`:\n{help}"); + for mac_cmd in ["setup", "import", "bench", "boot"] { + assert!(!cmds.contains(&mac_cmd), "Linux help must not list macOS-only `{mac_cmd}`:\n{help}"); + } + } + #[cfg(windows)] + { + for unix_or_mac in ["daemon", "bridge", "ui", "setup", "build-with", "update", "import", "bench", "boot", "raw"] { + assert!(!cmds.contains(&unix_or_mac), "Windows help must not list `{unix_or_mac}`:\n{help}"); + } + } + } + + #[test] + fn every_advertised_command_dispatches_in_main() { + let help = usage(); + let mut count = 0; + for line in help.lines() { + let Some(rest) = line.strip_prefix("usage: ").unwrap_or(line).trim_start().strip_prefix("kiri ") else { + continue; + }; + let mut words = rest.split_whitespace(); + let subcmd = words.next().expect("subcommand after `kiri `"); + count += 1; + match subcmd { + "COMMAND" => { + let args = ["run".to_owned()]; + assert!(matches!(Command::parse(&args), Some(Command::Docker(_)))); + } + "PORT" => { + let args = ["3000".to_owned()]; + assert!(matches!(Command::parse(&args), Some(Command::Share(_)))); + } + "raw" => { + for part in rest.split('|') { + let mut p = part.split_whitespace(); + if p.next() == Some("raw") { + let verb = p.next().expect("verb after `raw`"); + let args = ["raw".to_owned(), verb.to_owned()]; + let parsed = Command::parse(&args); + assert!( + parsed.is_some() && !matches!(parsed, Some(Command::Docker(_))), + "`kiri raw {verb}` advertised in usage has no dispatch arm in main" + ); + } + } + } + other => { + let args = [other.to_owned()]; + let parsed = Command::parse(&args); + assert!( + parsed.is_some() && !matches!(parsed, Some(Command::Docker(_))), + "`kiri {other}` advertised in usage has no dispatch arm in main" + ); + } + } + } + assert!(count > 0); + assert!(parse(&["--help"]).is_none()); + assert!(parse(&["-h"]).is_none()); + #[cfg(any(target_os = "macos", target_os = "linux"))] + for args in [ + vec!["update".to_owned()], + vec!["update".to_owned(), "--check".to_owned()], + vec!["update".to_owned(), "--help".to_owned()], + vec!["update".to_owned(), "-h".to_owned()], + ] { + assert!(matches!(Command::parse(&args), Some(Command::Update(_))), "expected Command::Update for {args:?}"); + } + let container_update = ["update".to_owned(), "--memory".to_owned(), "256m".to_owned(), "web".to_owned()]; + assert!(matches!(Command::parse(&container_update), Some(Command::Docker(_)))); + #[cfg(target_os = "macos")] + assert!(parse(&["bridge"]).is_none()); + #[cfg(target_os = "linux")] + for mac_cmd in ["setup", "import", "bench", "boot"] { + assert!(parse(&[mac_cmd]).is_none(), "`kiri {mac_cmd}` should not dispatch on Linux"); + } + #[cfg(windows)] + for unix_cmd in ["daemon", "bridge", "ui", "setup", "build-with", "import", "bench", "boot", "raw"] { + assert!(parse(&[unix_cmd]).is_none(), "`kiri {unix_cmd}` should not dispatch on Windows"); + } } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 3004fd522..d63fcaab2 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 +### #743 CLI: `kiri --help` lists only commands compiled for this OS (unreleased) +- Fixes: #743 Linux: `kiri --help` lists macOS-only commands (`setup`, `update`, `import`, `bench`, `boot`) that immediately fail +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/main.rs` + ### Build: serve digest-pinned local bases, relay default-bridge stub DNS, and support host-network builds (unreleased) - Fixes: #209 Windows: docker build hangs when a RUN step needs network (BuildKit has no usable DNS); #288 BuildKit fails to resolve digest-pinned FROM image already pulled into Kiri's image store; #330 Linux: containers have no DNS on the default bridge; Compose/BuildKit builds can't resolve a digest-pinned base; bun install gets ConnectionRefused - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index c517afba8..5ba34a9d4 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -306,3 +306,4 @@ crates/kiri/src/wsl.rs #761 running kiri.exe diag report [--out PATH] on Windows dns-default-bridge-stub #330 on a Linux host whose /etc/resolv.conf names only 127.0.0.53 (systemd-resolved), default-bridge containers got 1.1.1.1 instead of querying the host stub through the bridge gateway over UDP and TCP build-pinned-digest #288 a digest-pinned FROM image (@sha256:...) already pulled into Kiri's store was re-serialized instead of served with its upstream manifest and index bytes, failing BuildKit's digest check (#330) build-host-network-dns #209 build steps under docker build and docker build --network=host (or a host-network builder) could not resolve names through a loopback stub resolver on the host (#330) +crates/kiri/src/main.rs #743 kiri --help listed commands not compiled for the current OS (such as macOS-only setup, import, bench and boot on Linux, or Linux-only bridge on macOS) From 5ba1870e0c8a4916373c594ca8c203a851428899 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:08:14 +0100 Subject: [PATCH 069/157] CLI: kiri update --help prints usage without checking for updates (#840) (#865) Co-authored-by: takealook97 --- crates/kiri/src/update.rs | 66 +++++++++++++++++++++++++++++++++++---- docs/fix-registry.md | 6 ++++ tests/regressions.tsv | 1 + 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 38eda56ba..d0da46d31 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -416,12 +416,24 @@ fn has_cpu(head: &[u8], want: u32) -> bool { } } +#[cfg(target_os = "macos")] +const USAGE: &str = "usage: kiri update [--check]"; +#[cfg(target_os = "linux")] +const USAGE: &str = "usage: kiri update --check"; + pub fn run(args: &[String]) -> io::Result<()> { - if crate::flavor::dev() { + run_with_lookup(args, crate::flavor::dev(), env!("CARGO_PKG_VERSION"), &mut io::stdout(), latest) +} + +fn run_with_lookup(args: &[String], dev: bool, current: &str, out: &mut dyn Write, lookup: impl FnOnce() -> io::Result) -> io::Result<()> { + if args.iter().any(|a| a == "-h" || a == "--help") { + return writeln!(out, "{USAGE}"); + } + if dev { return Err(io::Error::other(format!("{} doesn't update itself: rebuild it with `cargo xtask app-dev`", crate::flavor::APP))); } - let release = latest()?; - run_release(args, &release, env!("CARGO_PKG_VERSION"), &mut io::stdout()) + let release = lookup()?; + run_release(args, &release, current, out) } fn run_release(args: &[String], release: &Release, current: &str, out: &mut dyn Write) -> io::Result<()> { @@ -466,11 +478,10 @@ mod tests { use std::io::{self, Read, Write}; use std::net::TcpListener; - use super::{Release, bundle_version, has_cpu, latest_from, newer, run_release, runs_here}; + use super::{Release, USAGE, bundle_version, has_cpu, latest_from, newer, run_with_lookup, runs_here}; fn run_with(args: &[String], url: &str, current: &str, out: &mut dyn Write) -> io::Result<()> { - let release = latest_from(url)?; - run_release(args, &release, current, out) + run_with_lookup(args, false, current, out, || latest_from(url)) } fn serve_feed(status: &'static str, body: &'static str) -> String { @@ -488,6 +499,43 @@ mod tests { format!("http://{addr}/latest.json") } + #[test] + fn help_skips_release_lookup() { + #[cfg(target_os = "macos")] + assert_eq!(USAGE, "usage: kiri update [--check]"); + #[cfg(target_os = "linux")] + assert_eq!(USAGE, "usage: kiri update --check"); + + for dev in [false, true] { + for (args, help) in [ + (&["--help"][..], true), + (&["-h"], true), + (&["--check", "--help"], true), + (&[], false), + (&["--check"], false), + ] { + let args = args.iter().map(|a| (*a).to_owned()).collect::>(); + let mut out = Vec::new(); + let mut looked_up = false; + let result = run_with_lookup(&args, dev, "0.2.0", &mut out, || { + looked_up = true; + Err(io::Error::other("feed unavailable")) + }); + if help { + assert!(!looked_up, "help must not look up release for {args:?} (dev={dev})"); + result.unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), format!("{USAGE}\n")); + } else if dev { + assert!(!looked_up, "dev guard must not look up release for {args:?}"); + assert!(result.unwrap_err().to_string().contains("doesn't update itself")); + } else { + assert!(looked_up, "expected release lookup for {args:?}"); + assert_eq!(result.unwrap_err().to_string(), "feed unavailable"); + } + } + } + } + #[test] fn compares_versions() { assert!(newer("0.2.0", "0.1.9")); @@ -556,6 +604,10 @@ mod tests { assert!(text.starts_with(&format!("Kiri 99.0.0 is available (this is {})\n", env!("CARGO_PKG_VERSION"))), "got {text:?}"); if cfg!(target_os = "linux") { assert!(text.contains("download the new .deb or .rpm from https://runkiri.com/releases/ and install it as before\n"), "got {text:?}"); + let url = serve_feed("200 OK", r#"{"version":"99.0.0","url":"https://runkiri.com/download","sha256":""}"#); + let mut bare_out = Vec::new(); + run_with(&[], &url, env!("CARGO_PKG_VERSION"), &mut bare_out).unwrap(); + assert_eq!(String::from_utf8(bare_out).unwrap(), text); } } @@ -575,6 +627,8 @@ mod tests { assert!(crate::docker::is_container_update(&a(&["--memory", "128m", "c1"]))); assert!(crate::docker::is_container_update(&a(&["--cpus", "2", "my-ctr"]))); assert!(!crate::docker::is_container_update(&a(&["--check"]))); + assert!(!crate::docker::is_container_update(&a(&["--help"]))); + assert!(!crate::docker::is_container_update(&a(&["-h"]))); assert!(!crate::docker::is_container_update(&a(&[]))); } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index d63fcaab2..d4fa5fa18 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 +### #840 CLI: `kiri update --help` prints usage without checking for updates (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/update.rs` + ### #743 CLI: `kiri --help` lists only commands compiled for this OS (unreleased) - Fixes: #743 Linux: `kiri --help` lists macOS-only commands (`setup`, `update`, `import`, `bench`, `boot`) that immediately fail - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 5ba34a9d4..d6b9900a9 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -307,3 +307,4 @@ dns-default-bridge-stub #330 on a Linux host whose /etc/resolv.conf names only 1 build-pinned-digest #288 a digest-pinned FROM image (@sha256:...) already pulled into Kiri's store was re-serialized instead of served with its upstream manifest and index bytes, failing BuildKit's digest check (#330) build-host-network-dns #209 build steps under docker build and docker build --network=host (or a host-network builder) could not resolve names through a loopback stub resolver on the host (#330) crates/kiri/src/main.rs #743 kiri --help listed commands not compiled for the current OS (such as macOS-only setup, import, bench and boot on Linux, or Linux-only bridge on macOS) +crates/kiri/src/update.rs #840 kiri update --help and kiri update -h entered the updater and tried the release feed (or failed the dev-build check) instead of printing OS-appropriate usage offline From a8ed284a9b8134026bc6110179f7932bdbbc6e60 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:55 +0100 Subject: [PATCH 070/157] Volumes: refuse volume rm --force when a container still uses the volume (#773) (#866) Co-authored-by: Randy Fay --- crates/kiri/src/daemon/api.rs | 97 ++++++++++++++++++++++++++++ crates/kiri/src/daemon/engine.rs | 104 ++++++++++++++++++++++++++++++- docs/fix-registry.md | 6 ++ tests/e2e.sh | 45 +++++++++++++ tests/regressions.tsv | 2 + 5 files changed, 252 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index bdde75039..171ad04aa 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -4161,6 +4161,9 @@ mod tests { engine.volume_ensure_with("free", json!({}), Default::default()).unwrap(); listed_user(&engine, "used", &image); assert!(matches!(engine.volume_remove("used", false), Err(Error::Conflict(m)) if m.contains("volume is in use"))); + // Force doesn't remove a volume in use either, as in Docker (#773). + assert!(matches!(engine.volume_remove("used", true), Err(Error::Conflict(m)) if m.contains("volume is in use"))); + assert!(engine.volume_get("used").is_some(), "the volume in use is kept"); engine.volume_remove("free", false).unwrap(); assert!(engine.volume_get("free").is_none()); assert!(matches!(image_remove(&engine, "used:1", false), Err(Error::Conflict(m)) if m.contains("is using its referenced image"))); @@ -4200,6 +4203,100 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + fn delete_volume_http(engine: &Arc, target: &str) -> (u16, String) { + use std::io::{Read, Write}; + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.write_all(format!("DELETE /volumes/{target} HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + let mut raw = String::new(); + client.read_to_string(&mut raw).unwrap(); + served.join().unwrap().unwrap(); + let (head, body) = raw.split_once("\r\n\r\n").unwrap_or((&raw, "")); + let code = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0); + (code, body.to_owned()) + } + + fn create_mounted(engine: &Engine, name: &str, image: &kiri_image::Image, body: Value) -> String { + let m = mounts(&body, engine, image).unwrap(); + let volumes_from = strings(&body["HostConfig"]["VolumesFrom"]).unwrap_or_default(); + let spec: super::super::engine::Spec = serde_json::from_value(json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": m.volumes, "anon_volumes": m.anon, + "mounts": m.guest, "mount_info": m.info, "volumes_from": volumes_from, + })).unwrap(); + engine.create(Some(name.into()), spec, image).unwrap() + } + + /// `DELETE /volumes/{name}` matches Docker's exact status codes and errors: + /// 404/204 for missing volumes (without/with `force`), and 409 Conflict for + /// volumes in use via `-v`, `--mount type=volume`, or `--volumes-from` + /// across created/running/stopped containers regardless of `force` (#773). + #[test] + fn delete_volume_http_status_and_in_use_match_docker() { + let (root, engine) = engine_in("vol-http", false); + let image = test_image("vol:1"); + engine.store.put_image(image.clone()).unwrap(); + + // Missing volume: 404 without force (or force=0/false), 204 with force=1/true. + for path in ["missing", "missing?force=0", "missing?force=false"] { + let (code, body) = delete_volume_http(&engine, path); + assert_eq!(code, 404, "{path}: {body}"); + assert!(body.contains("get missing: no such volume"), "{path}: {body}"); + } + for path in ["missing?force=1", "missing?force=true"] { + let (code, body) = delete_volume_http(&engine, path); + assert_eq!(code, 204, "{path}: {body}"); + assert!(body.is_empty(), "{path}: {body}"); + } + + // `-v` bind-style named volume on created and exited container. + let c_bind = create_mounted(&engine, "c-bind", &image, json!({"HostConfig": {"Binds": ["v-bind:/d"]}})); + for target in ["v-bind", "v-bind?force=1", "v-bind?force=true"] { + let (code, body) = delete_volume_http(&engine, target); + assert_eq!(code, 409, "{target}: {body}"); + assert!(body.contains("remove v-bind: volume is in use - [c-bind]"), "{target}: {body}"); + assert!(engine.volume_get("v-bind").is_some()); + } + engine.set_status(&c_bind, super::super::engine::Status::Exited); + assert_eq!(delete_volume_http(&engine, "v-bind?force=1").0, 409); + + // `--mount type=volume` on running container. + let c_mount = create_mounted( + &engine, + "c-mount", + &image, + json!({"HostConfig": {"Mounts": [{"Type": "volume", "Source": "v-mount", "Target": "/d"}]}}), + ); + engine.set_status(&c_mount, super::super::engine::Status::Running); + let (code, body) = delete_volume_http(&engine, "v-mount?force=1"); + assert_eq!(code, 409, "{body}"); + assert!(body.contains("remove v-mount: volume is in use - [c-mount]"), "{body}"); + + // `--volumes-from` retains the volume even after the source container is removed. + let c_vfrom = create_mounted(&engine, "c-vfrom", &image, json!({"HostConfig": {"VolumesFrom": ["c-bind"]}})); + engine.remove(&c_bind, false, false).unwrap(); + let (code, body) = delete_volume_http(&engine, "v-bind?force=1"); + assert_eq!(code, 409, "{body}"); + assert!(body.contains("remove v-bind: volume is in use - [c-vfrom]"), "{body}"); + assert!(engine.volume_get("v-bind").is_some()); + + // Removing holders frees the volumes for removal. + engine.remove(&c_vfrom, false, false).unwrap(); + engine.set_status(&c_mount, super::super::engine::Status::Exited); + engine.remove(&c_mount, false, false).unwrap(); + assert_eq!(delete_volume_http(&engine, "v-bind?force=1").0, 204); + assert_eq!(delete_volume_http(&engine, "v-mount").0, 204); + assert!(engine.volume_get("v-bind").is_none()); + assert!(engine.volume_get("v-mount").is_none()); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// `--volumes-from` entries: the container and its mode, as Docker parses them. #[test] fn volumes_from_takes_a_container_and_a_mode() { diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 35a8ae1b2..c0bf695ba 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -5298,10 +5298,18 @@ impl Engine { pub fn volume_remove(&self, name: &str, force: bool) -> Result<(), Error> { if self.volume_get(name).is_none() { + // Docker Engine returns 204 No Content for `DELETE /volumes/{name}?force=1` + // when the volume does not exist, and 404 Not Found without `force`. + if force { + return Ok(()); + } return Err(Error::NotFound(format!("get {name}: no such volume"))); } - let users = self.volume_users(name); - if !users.is_empty() && !force { + // A volume a container uses is refused even with `force`, as in Docker: + // `force` only ignores a missing volume and the damaged-list refusal below. + let mut users = self.volume_users(name); + if !users.is_empty() { + users.sort(); return Err(Error::Conflict(format!("remove {name}: volume is in use - [{}]", users.join(", ")))); } if !force && let Some(why) = self.refusal(&format!("Volume {name} was not removed, because the container list may be missing a container that uses it; `docker volume rm --force` removes it anyway")) { @@ -7239,6 +7247,13 @@ pub fn boot_without_vm(root: &std::path::Path) -> Arc { engine } +#[cfg(test)] +impl Engine { + pub(super) fn set_status(&self, id: &str, status: Status) { + self.lock().containers.get_mut(id).unwrap().status = status; + } +} + #[cfg(test)] mod records_tests { use super::*; @@ -9037,3 +9052,88 @@ mod exit_log_tests { let _ = std::fs::remove_dir_all(dir); } } + +#[cfg(test)] +mod volume_remove_tests { + use super::*; + + fn test_image() -> Image { + Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + } + } + + fn container_with_volumes(engine: &Engine, image: &Image, name: &str, volumes: Vec, anon_volumes: Vec) -> String { + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": volumes, "anon_volumes": anon_volumes, + })) + .unwrap(); + engine.create(Some(name.into()), spec, image).unwrap() + } + + #[test] + fn volume_remove_refuses_users_across_states_and_force_ignores_missing() { + let dir = std::env::temp_dir().join(format!("kiri-vol-rm-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = boot_without_vm(&dir); + let image = test_image(); + + // Missing volume: 404 without force, 204 (Ok) with force. + assert!(matches!(engine.volume_remove("missing", false), Err(Error::NotFound(m)) if m == "get missing: no such volume")); + engine.volume_remove("missing", true).unwrap(); + + // Volume in use: refused with or without force across Created, Running, Exited. + engine.volume_ensure("used", serde_json::json!({}), false).unwrap(); + engine.volume_ensure("anon-used", serde_json::json!({}), true).unwrap(); + let holder = container_with_volumes(&engine, &image, "holder", vec!["used".into()], Vec::new()); + let anon_holder = container_with_volumes(&engine, &image, "anon-holder", Vec::new(), vec!["anon-used".into()]); + + for status in [Status::Created, Status::Running, Status::Exited] { + engine.lock().containers.get_mut(&holder).unwrap().status = status; + for force in [false, true] { + assert!( + matches!(engine.volume_remove("used", force), Err(Error::Conflict(m)) if m == "remove used: volume is in use - [holder]"), + "status={status:?} force={force}" + ); + assert!(engine.volume_get("used").is_some()); + } + } + + // Multiple holders are sorted deterministically in the conflict message. + let holder2 = container_with_volumes(&engine, &image, "alpha-holder", vec!["used".into()], Vec::new()); + assert!(matches!( + engine.volume_remove("used", true), + Err(Error::Conflict(m)) if m == "remove used: volume is in use - [alpha-holder, holder]" + )); + + // Anonymous volume in use is also refused even with force. + assert!(matches!( + engine.volume_remove("anon-used", true), + Err(Error::Conflict(m)) if m == "remove anon-used: volume is in use - [anon-holder]" + )); + + // Once containers are gone, force and non-force removal succeed. + engine.remove(&holder, false, false).unwrap(); + engine.remove(&holder2, false, false).unwrap(); + engine.remove(&anon_holder, false, false).unwrap(); + engine.volume_remove("used", true).unwrap(); + engine.volume_remove("anon-used", false).unwrap(); + assert!(engine.volume_get("used").is_none()); + assert!(engine.volume_get("anon-used").is_none()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index d4fa5fa18..1867f3beb 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 +### #773 Volumes: `docker volume rm --force` refuses volumes in use and succeeds when missing, as Docker does (unreleased) +- Fixes: #773 `docker volume rm --force` removes a volume that a container still uses +- Caused: none known +- Caused by: - +- Check: `vol-rm-force-in-use`, `vol-rm-force-missing` + ### #840 CLI: `kiri update --help` prints usage without checking for updates (unreleased) - Fixes: no issue - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 32a8c3e6b..c62b8503d 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1111,6 +1111,51 @@ t vol-in-use "in use" bash -c "$D run -d --name vu -v tvol:/v alpine sleep 30 >/ $D rm -f vu >/dev/null t vol-rm "tvol" $D volume rm tvol thtml tempty t vol-create "made-vol" $D volume create made-vol +# `docker volume rm -f` refuses volumes in use by running, stopped or created +# containers (-v, --mount, --volumes-from) with 409 and keeps their data, and +# returns 204 when the volume does not exist (#773). +t vol-rm-force-in-use "409 kept 409 kept 409 kept 409 kept data=important gone" bash -c " + $D rm -f vf-run vf-stop vf-creat vf-from >/dev/null 2>&1 + $D volume rm -f vforce-used vforce-from >/dev/null 2>&1 + $D run --rm -v vforce-used:/d alpine sh -c 'echo important > /d/file' + $D run -d --name vf-run -v vforce-used:/d alpine sleep 60 >/dev/null + o1=\$($D volume rm -f vforce-used 2>&1); c1=\$? + s1=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-used?force=1') + k1=\$($D volume ls -q --filter name='^vforce-used\$' | sed 's/.*/kept/') + $D rm -f vf-run >/dev/null + $D run --name vf-stop --mount type=volume,source=vforce-used,target=/d alpine true >/dev/null + o2=\$($D volume rm -f vforce-used 2>&1); c2=\$? + s2=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-used?force=1') + k2=\$($D volume ls -q --filter name='^vforce-used\$' | sed 's/.*/kept/') + $D create --name vf-from --volumes-from vf-stop alpine true >/dev/null + $D rm vf-stop >/dev/null + o3=\$($D volume rm -f vforce-used 2>&1); c3=\$? + s3=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-used?force=1') + k3=\$($D volume ls -q --filter name='^vforce-used\$' | sed 's/.*/kept/') + $D create --name vf-creat --mount type=volume,source=vforce-from,target=/d alpine true >/dev/null + o4=\$($D volume rm -f vforce-from 2>&1); c4=\$? + s4=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-from?force=1') + k4=\$($D volume ls -q --filter name='^vforce-from\$' | sed 's/.*/kept/') + $D rm -f vf-from vf-creat >/dev/null + data=\$($D run --rm -v vforce-used:/d alpine cat /d/file) + $D volume rm -f vforce-used vforce-from >/dev/null + gone=\$($D volume ls -q --filter name='^vforce-used\$') + [ -z \"\$gone\" ] && gone=gone + grep -q 'in use' <<<\"\$o1\" && grep -q 'vf-run' <<<\"\$o1\" && + grep -q 'in use' <<<\"\$o2\" && grep -q 'vf-stop' <<<\"\$o2\" && + grep -q 'in use' <<<\"\$o3\" && grep -q 'vf-from' <<<\"\$o3\" && + grep -q 'in use' <<<\"\$o4\" && grep -q 'vf-creat' <<<\"\$o4\" && + [ \"\$c1\" != 0 ] && [ \"\$c2\" != 0 ] && [ \"\$c3\" != 0 ] && [ \"\$c4\" != 0 ] && + echo \"\$s1 \$k1 \$s2 \$k2 \$s3 \$k3 \$s4 \$k4 data=\$data \$gone\" +" +t vol-rm-force-missing "rm=1 rm_f=0 404 204" bash -c " + $D volume rm -f vforce-missing >/dev/null 2>&1 || true + $D volume rm vforce-missing >/dev/null 2>&1; rm_no=\$? + $D volume rm -f vforce-missing >/dev/null 2>&1; rm_f=\$? + s_no=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-missing') + s_f=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket $(printf %q "$SOCK") -X DELETE 'http://d/volumes/vforce-missing?force=1') + echo \"rm=\$rm_no rm_f=\$rm_f \$s_no \$s_f\" +" t tmpfs "size=10240k" $D run --rm --tmpfs /scratch:size=10m alpine sh -c 'mount | grep scratch' t tmpfs-mount "tmpfs on /t" $D run --rm --mount type=tmpfs,target=/t alpine sh -c 'mount | grep " /t "' # `--volumes-from` lends another container's volumes and binds at the same diff --git a/tests/regressions.tsv b/tests/regressions.tsv index d6b9900a9..ddd64fbbf 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -308,3 +308,5 @@ build-pinned-digest #288 a digest-pinned FROM image (@sha256:...) already pulled build-host-network-dns #209 build steps under docker build and docker build --network=host (or a host-network builder) could not resolve names through a loopback stub resolver on the host (#330) crates/kiri/src/main.rs #743 kiri --help listed commands not compiled for the current OS (such as macOS-only setup, import, bench and boot on Linux, or Linux-only bridge on macOS) crates/kiri/src/update.rs #840 kiri update --help and kiri update -h entered the updater and tried the release feed (or failed the dev-build check) instead of printing OS-appropriate usage offline +vol-rm-force-in-use #773 docker volume rm --force (and DELETE /volumes/{name}?force=1) removed a volume still used by a container instead of returning 409 Conflict and keeping its data +vol-rm-force-missing #773 DELETE /volumes/{name}?force=1 (and docker volume rm -f) returned 404 Not Found for a missing volume instead of 204 No Content as Docker does From 1b9a232560f84ce1878f5ca806f72b27dbcfa716 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:28:23 +0100 Subject: [PATCH 071/157] Images: validate reference grammar on load and escape buildkitd.toml strings (#746) (#867) Co-authored-by: Chukwuebuka (Gaus Octavio) <56232734+Chukwuebuka-2003@users.noreply.github.com> --- crates/kiri-image/src/archive.rs | 90 ++++++++++++++++++++---------- crates/kiri-image/src/reference.rs | 69 ++++++++++++++++++++--- crates/kiri/src/daemon/mirror.rs | 81 ++++++++++++++++++++++----- docs/fix-registry.md | 6 ++ tests/regressions.tsv | 2 + 5 files changed, 196 insertions(+), 52 deletions(-) diff --git a/crates/kiri-image/src/archive.rs b/crates/kiri-image/src/archive.rs index f23e74f51..5f76861d1 100644 --- a/crates/kiri-image/src/archive.rs +++ b/crates/kiri-image/src/archive.rs @@ -51,44 +51,49 @@ pub fn load(store: &Store, archive: impl Read) -> io::Result> { } files.insert(path, (digest, size)); } - let manifest = manifest.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "not an image archive: no manifest.json"))?; - let entries: Vec = serde_json::from_slice(&manifest).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("manifest.json: {e}")))?; - let lookup = |p: &str| files.get(p.trim_start_matches("./")).cloned().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("archive is missing {p}"))); - let mut loaded = Vec::new(); - for m in &entries { - let (config_digest, _) = lookup(m["Config"].as_str().unwrap_or_default())?; - let config: Value = serde_json::from_slice(&store.read_config(&config_digest)?) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("image config: {e}")))?; - let mut layers = Vec::new(); - for l in m["Layers"].as_array().into_iter().flatten() { - let (digest, size) = lookup(l.as_str().unwrap_or_default())?; - let media_type = media_type_of(&store.blob_path(&digest)?)?; - layers.push(Layer { digest, size, media_type: media_type.to_owned() }); + let read = (|| -> io::Result> { + let manifest = manifest.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "not an image archive: no manifest.json"))?; + let entries: Vec = serde_json::from_slice(&manifest).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("manifest.json: {e}")))?; + let lookup = |p: &str| files.get(p.trim_start_matches("./")).cloned().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("archive is missing {p}"))); + let mut loaded = Vec::new(); + for m in &entries { + let (config_digest, _) = lookup(m["Config"].as_str().unwrap_or_default())?; + let config: Value = serde_json::from_slice(&store.read_config(&config_digest)?) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("image config: {e}")))?; + let mut layers = Vec::new(); + for l in m["Layers"].as_array().into_iter().flatten() { + let (digest, size) = lookup(l.as_str().unwrap_or_default())?; + let media_type = media_type_of(&store.blob_path(&digest)?)?; + layers.push(Layer { digest, size, media_type: media_type.to_owned() }); + } + let mut names = Vec::new(); + for t in m["RepoTags"].as_array().into_iter().flatten().filter_map(Value::as_str) { + let r = Reference::parse(t).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; + if t.contains('@') || r.is_digest() { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("invalid repo tag: {t}"))); + } + names.push(r.short()); + } + // An untagged image is known by its id. + let names = if names.is_empty() { vec![config_digest.clone()] } else { names }; + for name in names { + loaded.push(from_config(name, &config_digest, &config, layers.clone())); + } } - let names: Vec = m["RepoTags"] - .as_array() - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(|t| Reference::parse(t).map(|r| r.short()).unwrap_or_else(|_| t.to_owned())) - .collect(); - // An untagged image is known by its id. - let names = if names.is_empty() { vec![config_digest.clone()] } else { names }; - for name in names { - let image = from_config(name, &config_digest, &config, layers.clone()); + for image in &loaded { store.put_image(image.clone())?; - loaded.push(image); } - } - // Files no image uses (OCI index blobs and the like) do not stay. - let used = |d: &str| loaded.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d)); + Ok(loaded) + })(); + // Files no image uses (OCI index blobs, or all of a refused archive) do not stay. + let used = |d: &str| read.as_ref().is_ok_and(|loaded| loaded.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d))); // The images are recorded: what they name is safe, and what nothing // names goes unless another image or writer has it now. drop(pins); for d in ingested.iter().filter(|d| !used(d)) { store.remove_if_unused(d)?; } - Ok(loaded) + read } /// Holds every blob `images` name ([`Store::pin`]) and checks each is @@ -395,4 +400,31 @@ mod tests { assert_eq!(tagged("localhost:5000/app"), "localhost:5000/app:latest"); assert_eq!(tagged("app:1"), "app:1"); } + + #[test] + fn rejects_invalid_repo_tags_and_cleans_up_blobs() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let add = |b: &mut tar::Builder>, name: &str, data: &[u8]| { + let mut h = tar::Header::new_ustar(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, name, data).unwrap(); + }; + let config = br#"{"architecture":"amd64","os":"linux","config":{},"rootfs":{"type":"layers","diff_ids":[]}}"#; + let digest_tag = format!("alpine@sha256:{}", "a".repeat(64)); + for bad_tag in ["evil\".com/x:1", digest_tag.as_str()] { + let manifest = json!([{"Config": "cfg.json", "RepoTags": [bad_tag], "Layers": []}]); + let mut b = tar::Builder::new(Vec::new()); + add(&mut b, "cfg.json", config); + add(&mut b, "manifest.json", &serde_json::to_vec(&manifest).unwrap()); + let bytes = b.into_inner().unwrap(); + + assert!(load(&store, bytes.as_slice()).is_err(), "{bad_tag}"); + assert!(store.images().unwrap().is_empty(), "{bad_tag}"); + assert_eq!(std::fs::read_dir(dir.join("blobs/sha256")).unwrap().count(), 0, "{bad_tag}"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/kiri-image/src/reference.rs b/crates/kiri-image/src/reference.rs index 9eb7e5b87..1f4d81ca1 100644 --- a/crates/kiri-image/src/reference.rs +++ b/crates/kiri-image/src/reference.rs @@ -33,6 +33,11 @@ impl Reference { if input.is_empty() || input.chars().any(char::is_whitespace) { return Err(bad()); } + let valid_tag = |t: &str| { + t.as_bytes().first().is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_') + && t.len() <= 128 + && t.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + }; let (name, reference) = if let Some((name, digest)) = input.split_once('@') { if crate::store::digest_hex(digest).is_err() { return Err(bad()); @@ -41,8 +46,7 @@ impl Reference { // in Docker, but it must still be a valid one. let name = match name.rfind(':') { Some(i) if !name[i..].contains('/') => { - let tag = &name[i + 1..]; - if tag.is_empty() || !tag.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) { + if !valid_tag(&name[i + 1..]) { return Err(bad()); } &name[..i] @@ -52,13 +56,17 @@ impl Reference { (name, digest.to_owned()) } else { // A colon after the last slash is a tag; one before it is a port. - match input.rfind(':') { - Some(i) if !input[i..].contains('/') => (&input[..i], input[i + 1..].to_owned()), - _ => (input, "latest".to_owned()), + let (name, tag) = match input.rfind(':') { + Some(i) if !input[i..].contains('/') => (&input[..i], &input[i + 1..]), + _ => (input, "latest"), + }; + if !valid_tag(tag) { + return Err(bad()); } + (name, tag.to_owned()) }; // Repository names are lowercase; tags may use any case. - if name.is_empty() || reference.is_empty() || name.chars().any(|c| c.is_ascii_uppercase()) { + if name.is_empty() || name.chars().any(|c| c.is_ascii_uppercase()) { return Err(bad()); } // The first component is a registry only if it looks like a host. @@ -73,7 +81,18 @@ impl Reference { } else { repository }; - if repository.split('/').any(str::is_empty) { + // A reference names a registry on the network and a path in a store, and + // is written into buildkitd.toml, log lines and other programs' arguments. + // Only a real host[:port], clean repository path segments and a valid tag + // or digest are accepted: a quote or a backslash in a name a `docker load` + // archive supplies would close a string wherever it is written. + let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); + let valid_seg = |s: &str| { + s.as_bytes().first().is_some_and(|&b| alnum(b)) + && s.as_bytes().last().is_some_and(|&b| alnum(b)) + && s.bytes().all(|b| alnum(b) || b".-_".contains(&b)) + }; + if crate::config::canonical(®istry).is_none() || repository.is_empty() || !repository.split('/').all(valid_seg) { return Err(bad()); } Ok(Reference { registry, repository, reference }) @@ -151,8 +170,13 @@ mod tests { assert_eq!(r("bitnami/redis:7"), s("docker.io", "bitnami/redis", "7")); assert_eq!(r("ghcr.io/o/r:v1"), s("ghcr.io", "o/r", "v1")); assert_eq!(r("localhost:5000/app"), s("localhost:5000", "app", "latest")); + assert_eq!(r("[::1]:5000/app:1"), s("[::1]:5000", "app", "1")); + assert_eq!(r("[::1]:5000/app"), s("[::1]:5000", "app", "latest")); + assert_eq!(r("localhost:5000/my_app-1.2/sub.repo:v1.0_build-2"), s("localhost:5000", "my_app-1.2/sub.repo", "v1.0_build-2")); + assert_eq!(r("localhost:5000/a__b--c.d:_tag-1.0"), s("localhost:5000", "a__b--c.d", "_tag-1.0")); let d = format!("sha256:{}", "a".repeat(64)); assert_eq!(r(&format!("alpine@{d}")), s("docker.io", "library/alpine", &d)); + assert_eq!(r(&format!("[::1]:5000/my_app-1.2/sub.repo:v1.0_build-2@{d}")), s("[::1]:5000", "my_app-1.2/sub.repo", &d)); } #[test] @@ -183,7 +207,36 @@ mod tests { fn rejects_garbage() { let non_hex = format!("alpine@sha256:{}", "g".repeat(64)); let traversal = format!("alpine@sha256:{}", "../".repeat(21) + "ab"); - for s in ["", "a b", "alpine:", "alpine@sha256:short", "/x", "Alpine", &non_hex, &traversal] { + for s in [ + "", + "a b", + "alpine:", + "alpine:1:2", + "ghcr.io/o/r:1:2", + "alpine@sha256:short", + "/x", + "Alpine", + "evil\".com/x:1", + "evil\\com/x:1", + "host/x:ta\"g", + "host/x?y:1", + "h#x/y:1", + "docker.io/a/../b:1", + "docker.io/./a:1", + "alpine:..", + "alpine:.x", + "alpine:-x", + "-bad/app:1", + "bad-/app:1", + "_bad/app:1", + "bad_/app:1", + "docker.io/.bad:1", + "docker.io/bad.:1", + "[not-ipv6]:5000/app:1", + "host:99999/app:1", + &non_hex, + &traversal, + ] { assert!(Reference::parse(s).is_err(), "{s}"); } } diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index 16b24f66c..791d0aec2 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -233,6 +233,47 @@ pub fn unverified(c: &kiri_image::RegistryConfig, names: &[String]) -> Vec String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\u{:04X}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +fn format_tables(tables: &[(String, Table)]) -> String { + let mut out = String::new(); + for (registry, t) in tables { + out.push_str(&format!("[registry.{}]\n", quoted(registry))); + if !t.mirrors.is_empty() { + let list = t.mirrors.iter().map(|m| quoted(m)).collect::>().join(", "); + out.push_str(&format!(" mirrors = [{list}]\n")); + } + if let Some(http) = t.http { + out.push_str(&format!(" http = {http}\n")); + } + if t.insecure { + out.push_str(" insecure = true\n"); + } + } + out +} + /// buildkitd.toml's registry tables, for `c` (daemon.json's settings) and /// `names` ([`registry_names`]), with `host_net` selecting `127.0.0.1` on /// Linux when the builder runs in the host network namespace (`--driver-opt @@ -250,21 +291,7 @@ pub fn config_for(engine: &Engine, c: &kiri_image::RegistryConfig, names: &[Stri table(&mut tables, &host).http = Some(true); } registries(&mut tables, c, names); - let mut out = String::new(); - for (registry, t) in tables { - out.push_str(&format!("[registry.\"{registry}\"]\n")); - if !t.mirrors.is_empty() { - let list = t.mirrors.iter().map(|m| format!("\"{m}\"")).collect::>().join(", "); - out.push_str(&format!(" mirrors = [{list}]\n")); - } - if let Some(http) = t.http { - out.push_str(&format!(" http = {http}\n")); - } - if t.insecure { - out.push_str(" insecure = true\n"); - } - } - out + format_tables(&tables) } /// daemon.json's part of buildkitd.toml, so a build reaches each registry @@ -755,4 +782,28 @@ mod tests { assert_eq!(std::fs::read_to_string(&p).unwrap(), "0123456789abcdef0123456789abcdef"); let _ = std::fs::remove_file(&p); } + + /// A registry name from an image reaches buildkitd.toml. A quote, a + /// backslash or a newline in it must not close the string or inject a + /// table: buildkitd refuses the whole file, and every build fails until + /// the image is removed (#746). + #[test] + fn names_are_quoted_for_toml() { + assert_eq!(super::quoted("registry.corp"), "\"registry.corp\""); + assert_eq!(super::quoted("evil\".com"), "\"evil\\\".com\""); + assert_eq!(super::quoted("a\\b"), "\"a\\\\b\""); + assert_eq!(super::quoted("a\nb\rc\td"), "\"a\\nb\\rc\\td\""); + assert_eq!(super::quoted("a\u{7}b\u{7f}c"), "\"a\\u0007b\\u007Fc\""); + let mut tables = Vec::new(); + add_mirror(&mut tables, "evil\"].com\n[worker.oci]", "127.0.0.1:47391/tok/evil\"].com\n[worker.oci]".into()); + let toml = super::format_tables(&tables); + assert_eq!( + toml, + "[registry.\"evil\\\"].com\\n[worker.oci]\"]\n mirrors = [\"127.0.0.1:47391/tok/evil\\\"].com\\n[worker.oci]\"]\n" + ); + // A name that could have carried one is not a reference any more. + for bad in ["evil\".com/x:1", "evil\\com/x:1", "host/x:ta\"g", "host/x?y:1", "h#x/y:1"] { + assert!(kiri_image::Reference::parse(bad).is_err(), "{bad:?}"); + } + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 1867f3beb..800872ee4 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 +### #746 Images: validate image reference characters and TOML-escape `buildkitd.toml` registry tables (unreleased) +- Fixes: #746 A loaded image whose name has a quote in it breaks buildkitd.toml, and every build after it +- Caused: none known +- Caused by: - +- Check: `crates/kiri-image/src/reference.rs`, `crates/kiri/src/daemon/mirror.rs` + ### #773 Volumes: `docker volume rm --force` refuses volumes in use and succeeds when missing, as Docker does (unreleased) - Fixes: #773 `docker volume rm --force` removes a volume that a container still uses - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index ddd64fbbf..116332d93 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -310,3 +310,5 @@ crates/kiri/src/main.rs #743 kiri --help listed commands not compiled for the cu crates/kiri/src/update.rs #840 kiri update --help and kiri update -h entered the updater and tried the release feed (or failed the dev-build check) instead of printing OS-appropriate usage offline vol-rm-force-in-use #773 docker volume rm --force (and DELETE /volumes/{name}?force=1) removed a volume still used by a container instead of returning 409 Conflict and keeping its data vol-rm-force-missing #773 DELETE /volumes/{name}?force=1 (and docker volume rm -f) returned 404 Not Found for a missing volume instead of 204 No Content as Docker does +crates/kiri-image/src/reference.rs #746 Reference::parse and archive::load accepted quotes, backslashes, queries and fragments in image names, storing unparseable or hostile RepoTags from docker load +crates/kiri/src/daemon/mirror.rs #746 registry and mirror names were written into buildkitd.toml without TOML string escaping, so a quote or backslash broke buildkitd startup on every build From bc556024ff0fb1d152226db38a21cf02fabeb282 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:48:08 +0100 Subject: [PATCH 072/157] HTTP: drain chunked trailers, handle Expect: 100-continue, and reject conflicting framing (#745, #134) (#868) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Chukwuebuka (Gaus Octavio) <56232734+Chukwuebuka-2003@users.noreply.github.com> Co-authored-by: Ersin KOÇ --- crates/kiri/src/daemon/api.rs | 159 ++++++- crates/kiri/src/daemon/builder.rs | 6 + crates/kiri/src/daemon/http.rs | 718 +++++++++++++++++++++++++++--- crates/kiri/src/daemon/storage.rs | 10 +- docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + 6 files changed, 835 insertions(+), 65 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 171ad04aa..8dc92271b 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -826,9 +826,11 @@ fn image_import(req: &Request, engine: &Engine, w: &mut UnixStream, r: &mut BufR http::end(w)?; } Err(e) => { - // The CLI is still sending the archive: read it out, or it gets - // a broken pipe instead of the message. - let _ = io::copy(&mut body, &mut io::sink()); + // The CLI may still be sending the archive: read it out unless it + // is still waiting on an unsent `100 Continue`. + if !req.needs_continue() { + let _ = io::copy(&mut body, &mut io::sink()); + } error_closing(w, e)?; } } @@ -3839,6 +3841,15 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: if req.flag("noOverwriteDirNonDir") { flags |= copy_flags::NO_OVERWRITE_DIR_NON_DIR; } + // Resolve the container and open the guest copy session before reading the + // body so missing containers fail with 404 without emitting `100 Continue`. + let stream = match engine.copy(id, kiri_proto::copy_op::IN, &path, flags) { + Ok(s) => s, + Err(e) => { + error_closing(w, e)?; + return Ok(Next::Close); + } + }; // Docker takes the archive plain or compressed; the guest unpacks tar. use std::io::Read; let mut body = http::Body::new(req, r); @@ -3852,13 +3863,6 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: return Ok(Next::Close); } }; - let stream = match engine.copy(id, kiri_proto::copy_op::IN, &path, flags) { - Ok(s) => s, - Err(e) => { - error_closing(w, e)?; - return Ok(Next::Close); - } - }; let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); if let Err(e) = send_chunks(&mut archive, &mut to_guest) { // The body broke off or isn't valid gzip: dropping the stream ends @@ -5138,6 +5142,141 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// End-to-end check through `serve`: TE+CL smuggling returns 400 and closes + /// without running a smuggled request; chunked trailers leave keep-alive + /// intact; `Expect: 100-continue` gets `100 Continue` before body upload. + #[test] + fn serve_handles_chunked_trailers_expect_continue_and_rejects_smuggling() { + use std::io::{Read, Write}; + let (root, engine) = engine_in("http-framing", false); + + // 1. Conflicting framing, malformed header lines (obs-fold, space before ':'), + // and bare-LF chunk size lines -> 400 Bad Request, Connection: close, no second reply. + for smuggle in [ + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\n Transfer-Encoding: chunked\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding : chunked\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\n{}\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client.write_all(smuggle).unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.starts_with("HTTP/1.1 400 Bad Request\r\n"), "{got}"); + assert!(got.contains("Connection: close\r\n"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 1, "{got}"); + } + + // 2. Chunked request with trailers followed by GET /_ping on the same connection. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all( + b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\nX-Checksum: 1\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n", + ) + .unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.contains("HTTP/1.1 200 OK\r\n") && got.ends_with("OK"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 2, "{got}"); + } + + // 3. Buffered Expect: 100-continue sends 100 Continue before reading body, then answers normally. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all(b"POST /auth HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 2\r\nConnection: close\r\n\r\n") + .unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"{}").unwrap(); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let rest = String::from_utf8_lossy(&rest); + assert!(rest.starts_with("HTTP/1.1 400 ") || rest.starts_with("HTTP/1.1 200 "), "{rest}"); + } + + // 4. Streamed 404 (PUT /archive on missing container) and early 400 (bad import repo) + // with Expect: 100-continue must NOT emit 100 Continue and must close cleanly. + for (req_head, want_status) in [ + ("PUT /containers/no-such-container/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n", "HTTP/1.1 404 Not Found\r\n"), + ("POST /images/create?fromSrc=-&repo=INVALID_UPPERCASE HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n", "HTTP/1.1 400 Bad Request\r\n"), + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client.write_all(req_head.as_bytes()).unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.starts_with(want_status), "expected {want_status:?} for {req_head:?}, got: {got}"); + assert!(got.contains("Connection: close\r\n"), "{got}"); + assert!(!got.contains("100 Continue"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 1, "{got}"); + } + + // 5. Valid streamed upload (POST /images/create?fromSrc=-) with Expect: 100-continue + // DOES emit 100 Continue before reading the body, then completes with 200 OK. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all(b"POST /images/create?fromSrc=- HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nTransfer-Encoding: chunked\r\n\r\n") + .unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + // Two 512-byte zero blocks form a valid empty tar archive. + let empty_tar = [0u8; 1024]; + write!(client, "{:x}\r\n", empty_tar.len()).unwrap(); + client.write_all(&empty_tar).unwrap(); + client.write_all(b"\r\n0\r\nX-Digest: ok\r\n\r\n").unwrap(); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let rest = String::from_utf8_lossy(&rest); + assert!(rest.starts_with("HTTP/1.1 200 OK\r\n"), "{rest}"); + assert!(rest.contains("sha256:"), "{rest}"); + } + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// `docker save | gzip | docker load` loads, as on Docker (issue 528): /// the body goes through the same detection as `docker cp` uploads. /// Each archive is sent to `POST /images/load` as the CLI sends it. diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index 6ad10a4f2..60b38c553 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -1065,6 +1065,12 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu *h = format!("{}={host}", &h[..h.len() - mac.len()]); } } + // Emit `100 Continue` before the streamed 200 OK header when the build will + // read its context from the request body, so `send_context` never writes + // an interim response after `200 OK`. + if o.remote.is_none() { + http::send_continue(req, r)?; + } // The context may be left partly unread: the connection closes after. http::begin_stream_with(w, 200, "application/json", http::CLOSE)?; let probe = w.try_clone()?; diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index fe471746f..27659e6b4 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -18,9 +18,20 @@ pub const MIN_API_VERSION: (u32, u32) = (1, 24); /// Largest request body read into memory (container create, etc.). Archives /// and image loads are streamed with [`Body`] instead, at any size. const MAX_BODY: usize = 8 << 20; +/// Cap on upfront buffer reservation for buffered request bodies so headers or +/// a chunk size line alone never pre-allocate [`MAX_BODY`] before bytes arrive. +const INITIAL_BODY_CAP: usize = 64 << 10; /// The request line and headers together may not exceed this: an endless /// header line must not grow memory without bound. const MAX_HEAD: u64 = 64 << 10; +/// Maximum size of a single chunk-size line (hex length plus optional `;ext`). +const MAX_CHUNK_LINE: u64 = 1024; +/// Maximum total bytes in a chunked body's trailer section (including its +/// terminating blank line), so an endless trailer cannot exhaust memory or +/// hold a connection open forever. +const MAX_TRAILERS: u64 = 8 << 10; +/// Maximum number of trailer header lines before the terminating blank line. +const MAX_TRAILER_LINES: usize = 128; /// Most of a streamed body its handler left unread that is read out so the /// connection can serve the next request; past this it closes. Go's /// net/http server, so Docker's, reads out as much. @@ -46,6 +57,9 @@ pub struct Request { /// Sent as HTTP/1.0: its connection closes after the response unless it /// asks to keep it. http10: bool, + /// Whether `HTTP/1.1 100 Continue` still needs to be sent before reading a + /// streamed body (RFC 9110 §10.1.1). Cleared once written. + needs_continue: Cell, /// How much of a streamed body has been read, through [`Body`]. streamed: Cell, } @@ -93,11 +107,23 @@ impl Request { has("close") || (self.http10 && !has("keep-alive")) } + fn expects_continue(&self) -> bool { + self.headers + .iter() + .filter(|(k, _)| k.eq_ignore_ascii_case("expect")) + .any(|(_, v)| v.split(',').any(|t| t.trim().eq_ignore_ascii_case("100-continue"))) + } + /// A request the daemon makes of itself (the managed builder's /// container create), so it goes through the same code as a client's. pub fn internal(method: &str, path: &str, query: &[(&str, &str)], body: Vec) -> Request { let query = query.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); - Request { method: method.to_owned(), path: path.to_owned(), api_version: None, query, headers: Vec::new(), body, http10: false, streamed: Cell::new(Streamed::No) } + Request { method: method.to_owned(), path: path.to_owned(), api_version: None, query, headers: Vec::new(), body, http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) } + } + + /// Whether a streamed body is still waiting for `HTTP/1.1 100 Continue`. + pub fn needs_continue(&self) -> bool { + self.needs_continue.get() } #[cfg(test)] @@ -113,6 +139,7 @@ impl Request { pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) -> bool) -> io::Result> { SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); CLOSING.with(|c| c.set(false)); + PENDING_CONTINUE.with(|c| c.set(false)); // The request line and headers are read through a cap, so a client // cannot exhaust memory with an endless line. The body is read after. let (method, path, api_version, query, headers, http10) = { @@ -157,55 +184,241 @@ pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) - loop { line.clear(); if head.read_line(&mut line)? == 0 { - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "headers too large or cut short")); + let kind = if head.limit() == 0 { io::ErrorKind::InvalidData } else { io::ErrorKind::UnexpectedEof }; + return Err(io::Error::new(kind, "headers too large or cut short")); } - let l = line.trim_end(); + let Some(l) = line.strip_suffix('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) else { + let kind = if head.limit() == 0 { io::ErrorKind::InvalidData } else { io::ErrorKind::UnexpectedEof }; + return Err(io::Error::new(kind, "headers too large or cut short")); + }; if l.is_empty() { break; } - if let Some((k, v)) = l.split_once(':') { - headers.push((k.trim().to_owned(), v.trim().to_owned())); + // RFC 9112 §5.1 / §5.2: reject obs-fold (leading whitespace), + // lines without ':', empty or non-token field-names (including + // whitespace before ':'), and control characters in values. + if l.starts_with([' ', '\t']) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); + } + let Some((k, v)) = l.split_once(':') else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); + }; + if k.is_empty() || !k.bytes().all(is_tchar) || v.bytes().any(is_ctl) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); } + headers.push((k.to_owned(), v.trim_matches([' ', '\t']).to_owned())); } (method, path, api_version, query, headers, http10) }; let streamed = stream(&method, &path); - let mut req = Request { method, path, api_version, query, headers, body: Vec::new(), http10, streamed: Cell::new(Streamed::No) }; + let mut req = Request { method, path, api_version, query, headers, body: Vec::new(), http10, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) }; + let body_framing = framing(&req)?; + if !streamed && matches!(body_framing, Framing::Length(len) if len > MAX_BODY as u64) { + return Ok(Some(too_large(req))); + } + let wants_continue = !req.http10 && req.expects_continue() && !matches!(body_framing, Framing::None); if streamed { - req.streamed.set(Streamed::Unread); + // Defer `100 Continue` until the handler actually reads the streamed + // body (RFC 9110 §10.1.1), so early 4xx rejections close without + // asking the client to upload a multi-GB archive. + req.needs_continue.set(wants_continue); + req.streamed.set(if matches!(body_framing, Framing::None) { Streamed::Done } else { Streamed::Unread }); return Ok(Some(req)); } - if req.header("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) { - let mut line = String::new(); - loop { - line.clear(); - // A chunk-size line is short hex (plus an optional ;extension). - (&mut *r).take(64).read_line(&mut line)?; - let size = line.trim().split(';').next().unwrap_or(""); - let n = usize::from_str_radix(size, 16) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; - if n > MAX_BODY || req.body.len().checked_add(n).is_none_or(|t| t > MAX_BODY) { - return Ok(Some(too_large(req))); - } - let start = req.body.len(); - req.body.resize(start + n, 0); - r.read_exact(&mut req.body[start..])?; - let mut crlf = [0u8; 2]; - r.read_exact(&mut crlf)?; + // RFC 9110 §10.1.1: an HTTP/1.1 client sending `Expect: 100-continue` + // waits for `100 Continue` before transmitting the body (as .NET's + // HttpClient and curl do on large uploads). HTTP/1.0 requests, bodiless + // requests, and already-rejected requests must not get a 100 response. + if wants_continue { + let w = r.get_mut(); + w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; + w.flush()?; + } + match body_framing { + Framing::None => {} + Framing::Chunked => loop { + let n = read_chunk_len(r)?; + // A zero chunk has no data and no CRLF of its own: its line's + // CRLF is already read, and the trailer section follows + // (RFC 9112 §7.1.2). if n == 0 { + read_trailers(r)?; break; } + if n > MAX_BODY as u64 || req.body.len().checked_add(n as usize).is_none_or(|t| t > MAX_BODY) { + return Ok(Some(too_large(req))); + } + let want = n as usize; + req.body.reserve(want.min(INITIAL_BODY_CAP)); + let got = (&mut *r).take(n).read_to_end(&mut req.body)?; + if got != want { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } + read_chunk_crlf(r)?; + }, + Framing::Length(len) => { + let want = len as usize; + req.body = Vec::with_capacity(want.min(INITIAL_BODY_CAP)); + let got = (&mut *r).take(len).read_to_end(&mut req.body)?; + if got != want { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } } - } else if let Some(len) = req.header("content-length").and_then(|v| v.parse::().ok()) { - if len > MAX_BODY { - return Ok(Some(too_large(req))); - } - req.body.resize(len, 0); - r.read_exact(&mut req.body)?; } Ok(Some(req)) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Framing { + None, + Chunked, + Length(u64), +} + +/// Validates and determines request body framing per RFC 9112 §6.1 & §6.3. +/// Rejects conflicting `Transfer-Encoding` + `Content-Length` headers, +/// unsupported transfer codings, and malformed or conflicting `Content-Length` +/// values with `InvalidData` so the connection answers 400 and closes. +fn framing(req: &Request) -> io::Result { + let mut has_te = false; + let mut te = Vec::new(); + for (_, raw) in req.headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding")) { + has_te = true; + for part in raw.split(',') { + let s = part.trim(); + if !s.is_empty() { + te.push(s); + } + } + } + let has_cl = req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-length")); + if has_te { + if has_cl { + return Err(io::Error::new(io::ErrorKind::InvalidData, "conflicting transfer-encoding and content-length")); + } + if req.http10 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "transfer-encoding is not valid in HTTP/1.0")); + } + if te.len() == 1 && te[0].eq_ignore_ascii_case("chunked") { + return Ok(Framing::Chunked); + } + return Err(io::Error::new(io::ErrorKind::InvalidData, "unsupported transfer-encoding")); + } + let mut len: Option = None; + for (_, raw) in req.headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case("content-length")) { + for part in raw.split(',') { + let s = part.trim(); + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad content-length")); + } + let n = s.parse::().map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad content-length"))?; + if let Some(prev) = len && prev != n { + return Err(io::Error::new(io::ErrorKind::InvalidData, "conflicting content-length")); + } + len = Some(n); + } + } + Ok(match len { + None | Some(0) => Framing::None, + Some(n) => Framing::Length(n), + }) +} + +fn read_chunk_len(r: &mut BufReader) -> io::Result { + let mut line = Vec::new(); + let mut lim = (&mut *r).take(MAX_CHUNK_LINE); + if lim.read_until(b'\n', &mut line)? == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } + let Some(raw) = line.strip_suffix(b"\n") else { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "chunk size line too large") + } else { + (io::ErrorKind::UnexpectedEof, "request body cut short") + }; + return Err(io::Error::new(kind, msg)); + }; + let Some(raw) = raw.strip_suffix(b"\r") else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk size line")); + }; + // A chunk size may carry extensions after a semicolon (RFC 9112 §7.1.1); + // reject control characters (including NUL and bare CR) in any extension. + let (size, ext) = match raw.iter().position(|&b| b == b';') { + Some(i) => (&raw[..i], Some(&raw[i + 1..])), + None => (raw, None), + }; + if let Some(ext) = ext && ext.iter().any(|&b| is_ctl(b)) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk extension")); + } + let size = &size[..size.iter().rposition(|b| !matches!(b, b' ' | b'\t')).map_or(0, |i| i + 1)]; + if size.is_empty() || !size.iter().all(|b| b.is_ascii_hexdigit()) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk size")); + } + let s = std::str::from_utf8(size).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + u64::from_str_radix(s, 16).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size")) +} + +fn read_chunk_crlf(r: &mut BufReader) -> io::Result<()> { + let mut crlf = [0u8; 2]; + r.read_exact(&mut crlf)?; + if crlf != *b"\r\n" { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk delimiter")); + } + Ok(()) +} + +fn is_tchar(b: u8) -> bool { + b.is_ascii_alphanumeric() + || matches!(b, b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~') +} + +/// Control characters disallowed in HTTP field values and chunk extensions: +/// C0 controls except HTAB (`0x09`), plus DEL (`0x7F`). +fn is_ctl(b: u8) -> bool { + (b < 0x20 && b != b'\t') || b == 0x7f +} + +/// Reads out a chunked body's trailer section: trailer header lines until the +/// terminating blank line (RFC 9112 §7.1.2). Bounded in total bytes and line +/// count so an endless trailer section cannot exhaust memory or hang. +fn read_trailers(r: &mut BufReader) -> io::Result<()> { + let mut lim = (&mut *r).take(MAX_TRAILERS); + let mut line = Vec::new(); + let mut count = 0usize; + loop { + line.clear(); + if lim.read_until(b'\n', &mut line)? == 0 { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "trailers too large") + } else { + (io::ErrorKind::UnexpectedEof, "trailers cut short") + }; + return Err(io::Error::new(kind, msg)); + } + let Some(raw) = line.strip_suffix(b"\n") else { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "trailers too large") + } else { + (io::ErrorKind::UnexpectedEof, "trailers cut short") + }; + return Err(io::Error::new(kind, msg)); + }; + let Some(raw) = raw.strip_suffix(b"\r") else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad trailer line")); + }; + if raw.is_empty() { + return Ok(()); + } + count += 1; + if count > MAX_TRAILER_LINES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "too many trailer headers")); + } + if !raw.iter().position(|&b| b == b':').is_some_and(|i| i > 0 && raw[..i].iter().all(|&b| is_tchar(b)) && !raw[i + 1..].iter().any(|&b| is_ctl(b))) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad trailer header")); + } + } +} + /// A request whose body is past [`MAX_BODY`]: what was read of it is dropped /// and the rest stays unread, for the connection's [`close`] to read out. fn too_large(mut req: Request) -> Request { @@ -237,17 +450,32 @@ pub fn refuse_bad_request(w: &mut UnixStream, r: &mut BufReader, mes sent } +/// Sends `HTTP/1.1 100 Continue` if this request is still waiting on one, +/// clearing the pending flag so it is emitted at most once. Handlers that +/// stream a final response header before reading [`Body`] (such as `POST /build`) +/// call this right before starting the response. +pub fn send_continue(req: &Request, r: &mut BufReader) -> io::Result<()> { + if req.needs_continue.get() { + let w = r.get_mut(); + w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; + w.flush()?; + req.needs_continue.set(false); + PENDING_CONTINUE.with(|c| c.set(false)); + } + Ok(()) +} + /// After a streamed request's response: whether the connection can serve /// the client's next request. A body its handler left unread (a pull sent /// with one, as docker-modem sends its options) is read out first, up to /// [`MAX_UNREAD`], or its bytes would be taken for the next request's head. -/// One read partly, too large, or held back for a `100 Continue` the daemon -/// never sends cannot be; the connection closes. +/// One read partly, too large, or waiting on an unsent `100 Continue` cannot +/// be; the connection closes. pub fn finish_body(req: &Request, r: &mut BufReader) -> bool { match req.streamed.get() { Streamed::No | Streamed::Done => true, Streamed::Started | Streamed::TooLarge => false, - Streamed::Unread if req.header("expect").is_some_and(|v| v.eq_ignore_ascii_case("100-continue")) => false, + Streamed::Unread if req.needs_continue.get() => false, Streamed::Unread => { let mut body = Body::new(req, r); io::copy(&mut (&mut body).take(MAX_UNREAD), &mut io::sink()).is_ok() && body.read(&mut [0; 1]).is_ok_and(|n| n == 0) @@ -303,38 +531,64 @@ pub struct Body<'a> { /// Bytes left in the body (or in the current chunk). left: u64, done: bool, + bad: Option, /// The request's record of how far its body was read. progress: &'a Cell, + /// Whether `100 Continue` still needs to be written on first read. + needs_continue: &'a Cell, } impl<'a> Body<'a> { pub fn new(req: &'a Request, r: &'a mut BufReader) -> Body<'a> { - let chunked = req.header("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")); - let left = if chunked { 0 } else { req.header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0) }; - let done = !chunked && left == 0; - req.streamed.set(if done { Streamed::Done } else { Streamed::Started }); - Body { r, chunked, left, done, progress: &req.streamed } + match framing(req) { + Ok(Framing::None) => { + req.streamed.set(Streamed::Done); + Body { r, chunked: false, left: 0, done: true, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Ok(Framing::Chunked) => { + Body { r, chunked: true, left: 0, done: false, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Ok(Framing::Length(n)) => { + Body { r, chunked: false, left: n, done: false, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Err(e) => { + req.streamed.set(Streamed::Started); + Body { r, chunked: false, left: 0, done: false, bad: Some(e.kind()), progress: &req.streamed, needs_continue: &req.needs_continue } + } + } } } impl Read for Body<'_> { fn read(&mut self, buf: &mut [u8]) -> io::Result { + if let Some(kind) = self.bad { + return Err(io::Error::new(kind, "bad request framing")); + } if self.done || buf.is_empty() { return Ok(0); } + self.progress.set(Streamed::Started); + if self.needs_continue.get() { + let w = self.r.get_mut(); + if let Err(e) = w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n").and_then(|()| w.flush()) { + self.bad = Some(e.kind()); + return Err(e); + } + self.needs_continue.set(false); + PENDING_CONTINUE.with(|c| c.set(false)); + } if self.chunked && self.left == 0 { - let mut line = String::new(); - self.r.read_line(&mut line)?; - // A chunk size may carry extensions after a semicolon. - let size = line.trim().split(';').next().unwrap_or(""); - self.left = u64::from_str_radix(size, 16).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + self.left = match read_chunk_len(self.r) { + Ok(n) => n, + Err(e) => { + self.bad = Some(e.kind()); + return Err(e); + } + }; if self.left == 0 { - // Trailers, then the blank line. - loop { - line.clear(); - if self.r.read_line(&mut line)? == 0 || line.trim().is_empty() { - break; - } + if let Err(e) = read_trailers(self.r) { + self.bad = Some(e.kind()); + return Err(e); } self.done = true; self.progress.set(Streamed::Done); @@ -344,13 +598,16 @@ impl Read for Body<'_> { let want = buf.len().min(self.left.min(usize::MAX as u64) as usize); let n = self.r.read(&mut buf[..want])?; if n == 0 { + self.bad = Some(io::ErrorKind::UnexpectedEof); return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); } self.left -= n as u64; if self.left == 0 { if self.chunked { - let mut crlf = [0u8; 2]; - self.r.read_exact(&mut crlf)?; + if let Err(e) = read_chunk_crlf(self.r) { + self.bad = Some(e.kind()); + return Err(e); + } } else { self.done = true; self.progress.set(Streamed::Done); @@ -476,6 +733,9 @@ thread_local! { /// Whether the connection closes after the request being answered: its /// response then says so (`Connection: close`), as Docker's does. static CLOSING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether the streamed request being answered still has an unsent + /// `100 Continue`: answering before reading the body closes the connection. + static PENDING_CONTINUE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Notes the request being answered: a failure status written for it is @@ -484,6 +744,7 @@ thread_local! { pub fn serving(req: &Request) { SERVING.with(|s| *s.borrow_mut() = (req.method.clone(), req.path.clone())); CLOSING.with(|c| c.set(req.wants_close())); + PENDING_CONTINUE.with(|c| c.set(req.needs_continue.get())); } /// Engine API failures in the log: 5xx as errors, 4xx as warnings, except @@ -504,7 +765,7 @@ fn head(w: &mut impl Write, status: u16, extra: &str) -> io::Result<()> { note_failure(status); } // A response that names its own Connection (an upgrade, `CLOSE`) keeps it. - let closing = if CLOSING.with(std::cell::Cell::get) && !extra.contains("Connection:") { CLOSE } else { "" }; + let closing = if (CLOSING.with(std::cell::Cell::get) || PENDING_CONTINUE.with(std::cell::Cell::get)) && !extra.contains("Connection:") { CLOSE } else { "" }; write!( w, "HTTP/1.1 {status} {}\r\nApi-Version: {API_VERSION}\r\nDocker-Experimental: false\r\nOstype: linux\r\nServer: Kiri/{} (linux)\r\n{extra}{closing}\r\n", @@ -627,7 +888,7 @@ mod tests { fn with_connection(value: Option<&str>) -> Request { let headers = value.map(|v| vec![("connection".to_owned(), v.to_owned())]).unwrap_or_default(); - Request { method: "POST".to_owned(), path: "/containers/x/start".to_owned(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, streamed: Cell::new(Streamed::No) } + Request { method: "POST".to_owned(), path: "/containers/x/start".to_owned(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) } } /// A request as `read_request` reads it off the wire. @@ -856,7 +1117,7 @@ mod tests { #[test] fn upgrades_only_when_asked() { let reply = |headers: Vec<(String, String)>| { - let req = Request { method: "POST".into(), path: "/exec/x/start".into(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, streamed: Cell::new(Streamed::No) }; + let req = Request { method: "POST".into(), path: "/exec/x/start".into(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) }; let mut out = Vec::new(); upgrade_if_asked(&req, &mut out).unwrap(); String::from_utf8(out).unwrap() @@ -871,4 +1132,353 @@ mod tests { assert!(plain.contains("Content-Type: application/vnd.docker.raw-stream\r\n"), "{plain}"); assert!(!plain.contains("Upgrade"), "{plain}"); } + + fn sock(bytes: &[u8]) -> BufReader { + let (mut a, b) = UnixStream::pair().unwrap(); + let data = bytes.to_vec(); + // Write on a helper thread so payloads larger than macOS's 8 KiB + // UnixStream socket buffer never deadlock before the reader starts. + std::thread::spawn(move || { + let _ = a.write_all(&data); + }); + BufReader::new(b) + } + + /// Chunked bodies (both buffered and streamed) consume their full trailer + /// section and closing blank line (RFC 9112 §7.1.2) so pipelined keep-alive + /// requests start at the exact next request line (#745). + #[test] + fn chunked_trailers_preserve_keep_alive_boundaries() { + let head = "POST /containers/create HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n"; + let ping = "GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"; + for tail in [ + "\r\n", + "X-Checksum: 1\r\n\r\n", + "X-Checksum: deadbeef\r\nX-Signature: sig-v1\r\nX-Time: 12:34:56\r\n\r\n", + ] { + let raw = format!("{head}{tail}{ping}"); + let mut r = sock(raw.as_bytes()); + let first = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!(first.body, b"{}", "{tail:?}"); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping"), "{tail:?}"); + } + + // Chunk extensions + multiple chunks + multi-line trailers on both + // buffered and streamed endpoints, plus a zero-length chunked body. + let streamed_raw = concat!( + "PUT /containers/abc/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n", + "5;ext=1\r\nhello\r\n", + "6\r\n world\r\n", + "0;last=yes\r\n", + "X-Checksum: sha256:abc\r\n", + "X-Trailer-Two: ok\r\n", + "\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n", + ); + let mut r = sock(streamed_raw.as_bytes()); + let first = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + let mut data = Vec::new(); + Body::new(&first, &mut r).read_to_end(&mut data).unwrap(); + assert_eq!(data, b"hello world"); + assert!(finish_body(&first, &mut r)); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping")); + + let empty_chunked = "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\r\nX-Empty: 1\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"; + let mut r = sock(empty_chunked.as_bytes()); + let first = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + let mut data = Vec::new(); + Body::new(&first, &mut r).read_to_end(&mut data).unwrap(); + assert!(data.is_empty()); + assert!(finish_body(&first, &mut r)); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping")); + } + + /// Trailer sections and chunk framing are bounded and validated in both + /// buffered and streamed paths so endless, oversized, truncated, or + /// malformed trailers and chunk delimiters fail cleanly (#745). + #[test] + fn chunked_trailers_and_delimiters_are_bounded_and_validated() { + let prefix = "POST /containers/create HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n"; + + // Single giant trailer line past MAX_TRAILERS -> InvalidData. + let giant = format!("{prefix}X-Big: {}\r\n\r\n", "a".repeat(MAX_TRAILERS as usize + 64)); + assert_eq!(read_request(&mut sock(giant.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Many trailer lines summing past MAX_TRAILERS -> InvalidData. + let mut many_bytes = String::from(prefix); + for i in 0..100 { + many_bytes.push_str(&format!("X-Pad-{i:03}: {}\r\n", "b".repeat(100))); + } + many_bytes.push_str("\r\n"); + assert_eq!(read_request(&mut sock(many_bytes.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Exceeding MAX_TRAILER_LINES even while well under MAX_TRAILERS -> InvalidData. + let mut many_lines = String::from(prefix); + for i in 0..=MAX_TRAILER_LINES { + many_lines.push_str(&format!("X-{i}: 1\r\n")); + } + many_lines.push_str("\r\n"); + assert!(many_lines.len() < MAX_TRAILERS as usize + prefix.len()); + assert_eq!(read_request(&mut sock(many_lines.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Same oversized-trailer rejection on the streamed Body path. + let streamed_big = format!( + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Big: {}\r\n\r\n", + "z".repeat(MAX_TRAILERS as usize + 16), + ); + let mut r = sock(streamed_big.as_bytes()); + let req = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::InvalidData); + assert!(!finish_body(&req, &mut r)); + + // Truncated trailers hit UnexpectedEof and prevent keep-alive reuse. + for cut_raw in [ + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Incomplete: 1", + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Incomplete: 1\r\n", + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n", + ] { + let mut r = sock(cut_raw.as_bytes()); + let req = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::UnexpectedEof, "{cut_raw:?}"); + assert!(!finish_body(&req, &mut r)); + } + + // Malformed trailer headers, bad chunk delimiters, funky-chunk bare LF + // lines, control characters in chunk extensions/trailers, and invalid sizes. + let huge_ext = format!( + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0;{}\r\n\r\n", + "e".repeat(MAX_CHUNK_LINE as usize + 16), + ); + for bad in [ + format!("{prefix}GET /_ping HTTP/1.1\r\n\r\n"), + format!("{prefix}: missing-name\r\n\r\n"), + format!("{prefix}X-T: 1\n\r\n"), + format!("{prefix}\n"), + format!("{prefix}X-T: a\rb\r\n\r\n"), + format!("{prefix}X-T: a\0b\r\n\r\n"), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhelloXX0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n+5\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n 5\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=1\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=a\rb\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext\r\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\0x\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x01\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x1f\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x7f\r\nhello\r\n0\r\n\r\n".to_owned(), + huge_ext, + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered: {bad:?}"); + let mut r = sock(bad.as_bytes()); + let req = read_request(&mut r, |_, _| true).unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed: {bad:?}"); + } + + // HTAB in chunk extensions remains valid per RFC 9112 §7.1.1. + let htab_ext = "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\t1\r\nhello\r\n0\r\n\r\n"; + let req = read_request(&mut sock(htab_ext.as_bytes()), |_, _| false).unwrap().unwrap(); + assert_eq!(req.body, b"hello"); + + // Truncated buffered Content-Length and chunked bodies return UnexpectedEof. + for short in [ + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 10\r\n\r\nabc", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 8388608\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel", + ] { + assert_eq!(read_request(&mut sock(short.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::UnexpectedEof, "{short:?}"); + } + } + + /// RFC 9112 §5.1 / §5.2: malformed header lines (obs-fold leading whitespace, + /// missing ':', whitespace before ':', empty or non-token field names, and + /// control characters in values) are rejected with InvalidData. + #[test] + fn rejects_malformed_header_lines() { + for bad in [ + "POST /x HTTP/1.1\r\nHost: d\r\n Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\n\tTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding : chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding\t: chunked\r\n\r\n0\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nNoColonHeader\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n \r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad Name: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad(Name): value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad\0Name: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\rb\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\0b\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\x7fb\r\n\r\n", + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered: {bad:?}"); + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| true).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed: {bad:?}"); + } + + // Valid headers with OWS tabs/spaces around values and empty values pass. + let ok = parsed("GET /_ping HTTP/1.1\r\nHost: d\r\nX-Empty:\r\nX-Tab: \tval \t\r\n\r\n"); + assert_eq!(ok.header("X-Empty"), Some("")); + assert_eq!(ok.header("X-Tab"), Some("val")); + } + + /// HTTP/1.1 requests with `Expect: 100-continue` receive `HTTP/1.1 100 Continue` + /// eagerly for buffered bodies and lazily on first `Body` read for streamed + /// routes (so early 4xx rejections never ask the client to upload), while + /// HTTP/1.0, bodiless, and oversized requests never receive 100 Continue (#134). + #[test] + fn expect_100_continue_handshakes_before_reading_body() { + use std::sync::mpsc; + use std::time::Duration; + + // 1. Buffered Content-Length: client waits for 100 Continue before writing body. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let t = std::thread::spawn(move || { + let mut r = BufReader::new(server); + let first = read_request(&mut r, |_, _| false).unwrap().unwrap(); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + (first.body, second.method, second.path) + }); + client.write_all(b"POST /containers/create HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 11\r\n\r\n").unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"{\"a\":12345}GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + drop(client); + let (body, m, p) = t.join().unwrap(); + assert_eq!(body, b"{\"a\":12345}"); + assert_eq!((m.as_str(), p.as_str()), ("GET", "/_ping")); + } + + // 2. Streamed chunked upload (as .NET/curl send for PUT /archive) with trailers: + // read_request does NOT emit 100 Continue; Body::read emits it lazily. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let (head_done_tx, head_done_rx) = mpsc::channel(); + let (go_read_tx, go_read_rx) = mpsc::channel(); + let t = std::thread::spawn(move || { + let mut r = BufReader::new(server); + let req = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + assert!(req.needs_continue()); + head_done_tx.send(()).unwrap(); + go_read_rx.recv().unwrap(); + let mut data = Vec::new(); + Body::new(&req, &mut r).read_to_end(&mut data).unwrap(); + assert!(!req.needs_continue()); + assert!(finish_body(&req, &mut r)); + let next = read_request(&mut r, |_, _| false).unwrap().unwrap(); + (data, next.path) + }); + client.write_all(b"PUT /containers/c/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-Continue\r\nTransfer-Encoding: chunked\r\n\r\n").unwrap(); + head_done_rx.recv().unwrap(); + // Confirm nothing was written before the handler reads Body. + client.set_nonblocking(true).unwrap(); + let mut peek = [0u8; 1]; + assert_eq!(client.read(&mut peek).unwrap_err().kind(), io::ErrorKind::WouldBlock); + client.set_nonblocking(false).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + go_read_tx.send(()).unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"7\r\ntarball\r\n0\r\nX-Hash: abc\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + drop(client); + let (data, next_path) = t.join().unwrap(); + assert_eq!(data, b"tarball"); + assert_eq!(next_path, "/_ping"); + } + + // 3. Streamed unread body with Expect: 100-continue does NOT emit 100 Continue; + // answering adds Connection: close and finish_body closes the connection. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let t = std::thread::spawn(move || { + let mut w = server.try_clone().unwrap(); + let mut r = BufReader::new(server); + let req = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + assert!(req.needs_continue()); + serving(&req); + error(&mut w, 404, "No such container").unwrap(); + assert!(!finish_body(&req, &mut r)); + close(&w, &mut r); + }); + client.write_all(b"PUT /containers/missing/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n").unwrap(); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + drop(client); + t.join().unwrap(); + let reply = String::from_utf8_lossy(&reply); + assert!(reply.starts_with("HTTP/1.1 404 Not Found\r\n"), "{reply}"); + assert!(reply.contains("Connection: close\r\n"), "{reply}"); + assert!(!reply.contains("100 Continue"), "{reply}"); + } + + // 4. Oversized buffered body, HTTP/1.0, and bodiless requests must NOT send 100 Continue. + for (raw, check_too_large) in [ + (format!("POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: {}\r\n\r\n", MAX_BODY + 1), true), + ("POST /x HTTP/1.0\r\nExpect: 100-continue\r\nContent-Length: 2\r\n\r\n{}".to_owned(), false), + ("GET /_ping HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\n\r\n".to_owned(), false), + ("POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 0\r\n\r\n".to_owned(), false), + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + client.write_all(raw.as_bytes()).unwrap(); + client.shutdown(std::net::Shutdown::Write).unwrap(); + let req = read_request(&mut BufReader::new(server), |_, _| false).unwrap().unwrap(); + assert_eq!(req.too_large(), check_too_large, "{raw:?}"); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + assert!(reply.is_empty(), "unexpected 100 Continue for {raw:?}: {:?}", String::from_utf8_lossy(&reply)); + } + } + + /// Ambiguous Transfer-Encoding + Content-Length combinations and malformed + /// or conflicting Content-Length headers are rejected with InvalidData so + /// the server responds 400 Bad Request and closes the connection (#134). + #[test] + fn rejects_ambiguous_transfer_encoding_and_content_length_framing() { + for bad in [ + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: \r\nContent-Length: 5\r\n\r\nhello", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked, chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: gzip, chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: identity\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: \r\n\r\n", + "POST /x HTTP/1.0\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4\r\nContent-Length: 8\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4, 8\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 99999999999999999999999999999\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: -1\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: +4\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: abc\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: \r\n\r\n", + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered accepted: {bad:?}"); + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| true).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed accepted: {bad:?}"); + } + + // TE+CL with Expect: 100-continue must reject without sending 100 Continue. + let (mut client, server) = UnixStream::pair().unwrap(); + client.write_all(b"POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n").unwrap(); + client.shutdown(std::net::Shutdown::Write).unwrap(); + assert_eq!(read_request(&mut BufReader::new(server), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + assert!(reply.is_empty()); + + // Identical duplicate Content-Length values remain valid per RFC 9112 §6.3. + for dup in [ + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4, 4\r\n\r\nabcd", + ] { + let req = read_request(&mut sock(dup.as_bytes()), |_, _| false).unwrap().unwrap(); + assert_eq!(req.body, b"abcd", "{dup:?}"); + } + } } diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index 93418540e..e4b65a804 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -695,7 +695,15 @@ pub fn serve_unavailable(stream: UnixStream, missing: &Path) -> io::Result<()> { let mut w = stream.try_clone()?; let mut r = BufReader::new(stream); let unavailable = chosen::Unavailable(missing.to_owned()).to_string(); - while let Some(req) = http::read_request(&mut r, |_, _| false)? { + loop { + let req = match http::read_request(&mut r, |_, _| false) { + Ok(Some(req)) => req, + Ok(None) => break, + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + return http::refuse_bad_request(&mut w, &mut r, &e.to_string()).or(Ok(())); + } + Err(e) => return Err(e), + }; if req.too_large() { return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 800872ee4..23592ac98 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 +### #745, #134 HTTP: drain bounded chunked trailers, handle `Expect: 100-continue`, and reject conflicting request framing (unreleased) +- Fixes: #745 Chunked HTTP/1.1 request bodies with trailers corrupt subsequent requests on keep-alive connections; #134 Handle `Expect: 100-continue` before reading request bodies and reject ambiguous `Transfer-Encoding` + `Content-Length` framing per RFC 9112 +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/daemon/http.rs` + ### #746 Images: validate image reference characters and TOML-escape `buildkitd.toml` registry tables (unreleased) - Fixes: #746 A loaded image whose name has a quote in it breaks buildkitd.toml, and every build after it - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 116332d93..ed4823f12 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -312,3 +312,4 @@ vol-rm-force-in-use #773 docker volume rm --force (and DELETE /volumes/{name}?fo vol-rm-force-missing #773 DELETE /volumes/{name}?force=1 (and docker volume rm -f) returned 404 Not Found for a missing volume instead of 204 No Content as Docker does crates/kiri-image/src/reference.rs #746 Reference::parse and archive::load accepted quotes, backslashes, queries and fragments in image names, storing unparseable or hostile RepoTags from docker load crates/kiri/src/daemon/mirror.rs #746 registry and mirror names were written into buildkitd.toml without TOML string escaping, so a quote or backslash broke buildkitd startup on every build +crates/kiri/src/daemon/http.rs #745 chunked request bodies left trailer headers on keep-alive connections, Expect: 100-continue never sent 100 Continue before reading bodies, and conflicting Transfer-Encoding + Content-Length headers were not rejected with 400 Bad Request (#134) From a0215cf17eedf4afc2b47efdc6f158bcab5e247c Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:05:04 +0100 Subject: [PATCH 073/157] Localization: Ukrainian Share button verb and wording fixes (#645) (#870) Co-authored-by: Tusko --- crates/kiri/src/ui/lang/uk.json | 52 ++++++++++++++++----------------- docs/fix-registry.md | 6 ++++ 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 43b7f5f05..ffd03722d 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -73,7 +73,7 @@ "Always send crash reports": "Завжди надсилати звіти про збої", "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR приймає токен, а не пароль: ім’я користувача — {user}, а токен видає {cmd}. Він діє 12 годин.", "Anchore, open source": "Anchore, відкритий код", - "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "Від ({use}) для {build} вибрано інший збирач. Виберіть Kiri знову, щоб збирати в Kiri.", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "Відтоді для {build} вибрано інший збирач ({use}). Виберіть Kiri знову, щоб збирати в Kiri.", "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "Адресу 127.0.0.1:53 зайняла інша програма, тому Kiri не може відповідати за .kiri.local; контейнери лишаються на .kiri.localhost", "Answers on /run/kiri/docker.sock": "Відповідає на /run/kiri/docker.sock", "Anyone who can reach the port signs in as root.": "Будь-хто, хто може під’єднатися до порту, входить як root.", @@ -351,8 +351,8 @@ "From ubuntu.com, through Microsoft's WSL list.": "З ubuntu.com через список WSL від Microsoft.", "Generate": "Згенерувати", "Getting a link…": "Отримання посилання…", - "GitHub opened in your browser. Approve there and you're signed in straight away.": "GitHub відкрито в браузері. Підтвердьте там — і ви одразу ввійдете.", - "GitHub opened in your browser. Approve there and {what} is shared straight away.": "GitHub відкрито в браузері. Підтвердьте там — і {what} одразу стане доступним.", + "GitHub opened in your browser. Approve there and you're signed in straight away.": "GitHub відкрито в браузері. Підтвердьте там, і ви одразу ввійдете.", + "GitHub opened in your browser. Approve there and {what} is shared straight away.": "GitHub відкрито в браузері. Підтвердьте там, і {what} одразу стане доступним.", "GitHub's page asks you to let Kiri read your packages. Check that it shows this code:": "Сторінка GitHub попросить дозволити Kiri читати ваші пакети. Перевірте, що на ній цей код:", "Give it back to this computer": "Повернути цьому комп’ютеру", "Give the VM more memory": "Виділити ВМ більше пам’яті", @@ -477,7 +477,7 @@ "Kiri quit unexpectedly last time": "Минулого разу Kiri несподівано завершив роботу", "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri запускає Grype тут, на вашому Mac, для образу зі сховища Kiri. Образ нікуди не вивантажується.", "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri запускає Linux-контейнери всередині WSL у власному Linux. Обидва варіанти запускають ті самі контейнери з однаковою швидкістю; вони відрізняються розміром і тим, що ви отримуєте на додачу.", - "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri запускає Linux-контейнери у Windows без Docker Desktop. Для цього потрібна підсистема Windows для Linux (WSL) — власний спосіб Microsoft запускати Linux, якого на цьому ПК ще немає.", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri запускає Linux-контейнери у Windows без Docker Desktop. Для цього потрібна підсистема Windows для Linux (WSL), власний спосіб Microsoft запускати Linux, якого на цьому ПК ще немає.", "Kiri sets itself up for your Windows account only.": "Kiri налаштовується лише для вашого облікового запису Windows.", "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Kiri налаштує свій збирач після запуску рушія, і відтоді збірки виконуватимуться в ньому.", "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri входить у Docker Hub за допомогою команди docker, але її не встановлено. Установіть її і спробуйте ще раз.", @@ -810,7 +810,7 @@ "Reading what {name} has…": "Читання даних {name}…", "Ready": "Готовий", "Recent crashes": "Нещодавні збої", - "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Нещодавні журнали, звіти про збої та версії в одному файлі з вилученими особистими даними — на випадок, якщо щось піде не так.", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Нещодавні журнали, звіти про збої та версії в одному файлі з вилученими особистими даними, на випадок, якщо щось піде не так.", "Recent pulls": "Нещодавно отримані", "Recommended": "Рекомендовано", "Reconnecting": "Перепідключення", @@ -967,9 +967,9 @@ "Setup steps": "Кроки встановлення", "Setup time": "Час установлення", "Severity": "Критичність", - "Share": "Спільний доступ", + "Share": "Поділитися", "Share again": "Поділитися знову", - "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "«Спільний доступ» дає контейнеру або сервісу Kubernetes публічне посилання https через захищений тунель до Kiri Cloud.", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "«Поділитися» дає контейнеру або сервісу Kubernetes публічне посилання https через захищений тунель до Kiri Cloud.", "Share pod {name}?": "Поділитися подом {name}?", "Share service {name}": "Поділитися сервісом {name}", "Share this pod on a port…": "Поділитися цим подом на порту…", @@ -1146,7 +1146,7 @@ "The engine isn't here: reinstall the kiri package": "Рушій не знайдено: перевстановіть пакет kiri", "The engine still runs Kiri {version}": "Рушій досі працює на Kiri {version}", "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Рушій досі працює на {version}. Перезапуск зупинить запущені контейнери, а ті, що мають політику перезапуску, запустяться знову.", - "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "Перше сканування завантажує Grype і його базу даних — близько 230 МБ (3 ГБ у розпакованому вигляді).", + "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "Перше сканування завантажує Grype і його базу даних: близько 230 МБ (3 ГБ у розпакованому вигляді).", "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Повна Ubuntu зі списку WSL від Microsoft. Kiri працює в ній, і ви теж можете відкривати її як свій Linux.", "The image's own way to start without it.": "Власний спосіб образу запуститися без цього.", "The kiri share there stops.": "kiri share там зупиниться.", @@ -1154,7 +1154,7 @@ "The last {n} seconds": "Останні {n} с", "The link ends when the pod does.": "Посилання перестає працювати разом із подом.", "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "Максимум, який може зайняти ВМ. Вона використовує пам’ять, лише коли та потрібна контейнерам, а решту повертає {os}.", - "The name comes from the Igbo word ntakịrị, “small”.": "Назва походить від слова ntakịrị мовою ігбо — «маленький».", + "The name comes from the Igbo word ntakịrị, “small”.": "Назва походить від слова ntakịrị мовою ігбо, що означає «маленький».", "The part that runs your containers, inside {linux}.": "Частина, що запускає ваші контейнери всередині {linux}.", "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "Порт API-сервера на цьому {host}, від 1024 до 65535 (типово 6443). Якщо під час запуску кластера він зайнятий, береться наступний вільний. Збереження перезапускає кластер і оновлює контекст {context}.", "The profile {profile} asks for a code from your MFA device {device}.": "Профіль {profile} запитує код із вашого MFA-пристрою {device}.", @@ -1278,14 +1278,14 @@ "What's new": "Що нового", "What's new in Kiri {version}": "Що нового в Kiri {version}", "What's new in {version}": "Що нового у {version}", - "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Коли в якійсь частині Kiri стається збій, трасування стека й останні 200 рядків журналу перед ним надсилаються в Kiri Cloud разом із версіями Kiri та системи, моделлю комп’ютера й випадковим ID цього встановлення. Ніколи — ваш обліковий запис Kiri Cloud і нічого зсередини ваших контейнерів. Шлях до домашньої теки, імена образів і контейнерів, токени й паролі вилучаються.", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Коли в якійсь частині Kiri стається збій, трасування стека й останні 200 рядків журналу перед ним надсилаються в Kiri Cloud разом із версіями Kiri та системи, моделлю комп’ютера й випадковим ID цього встановлення. Ваш обліковий запис Kiri Cloud і вміст контейнерів не надсилаються ніколи. Шлях до домашньої теки, імена образів і контейнерів, токени й паролі вилучаються.", "When the pod restarts, it gets a new name and the link ends.": "Під час перезапуску под отримує нове ім’я, і посилання перестає працювати.", "Where should your containers run?": "Де запускати контейнери?", "Which steps": "Які кроки", "Window": "Вікно", "Windows Subsystem for Linux": "Підсистема Windows для Linux", "Windows asks for an administrator's approval once.": "Windows один раз запитає дозвіл адміністратора.", - "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows передає USB-пристрої у WSL, де працюють контейнери Kiri, через usbipd-win — інструмент, рекомендований Microsoft.", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows передає USB-пристрої у WSL, де працюють контейнери Kiri, через usbipd-win, інструмент, який рекомендує Microsoft.", "Windows is asking": "Windows запитує", "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows увімкне платформу віртуальних машин під час завантаження. Потім Kiri сам відкриється знову й продовжить із кроку 2. Спершу збережіть свою роботу.", "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "Коли це завершиться, Windows знадобиться один перезапуск. Kiri запитає перед перезапуском, щоб ви встигли зберегти роботу.", @@ -1680,7 +1680,7 @@ "✓ Installed": "✓ Установлено", "Waiting to come back": "Чекає на повернення", "Stop waiting": "Не чекати", - "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "Kiri знову підключить його, коли воно повернеться. Перестаньте чекати, щоб залишити його на цьому комп'ютері.", + "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "Kiri знову під’єднає його, коли він повернеться. Натисніть «Не чекати», щоб залишити його на цьому комп’ютері.", "Fit the whole project": "Показати весь проєкт", "Find a service": "Знайти сервіс", "docker compose up failed": "docker compose up завершився з помилкою", @@ -1694,7 +1694,7 @@ "Saved, not started yet": "Збережено, ще не запускався", "image": "образ", "Overwrite their changes": "Перезаписати їхні зміни", - "Recreating…": "Створюється знову…", + "Recreating…": "Перестворюється…", "Service": "Сервіс", "{n} need it": "Потрібен сервісам: {n}", "CHANGES": "ЗМІНЕНО", @@ -1718,7 +1718,7 @@ "Overwrite their changes?": "Перезаписати їхні зміни?", "No Compose projects yet": "Проєктів Compose поки немає", "Saved, not applied": "Збережено, але не застосовано", - "New service, built from its folder.": "Новий сервіс, збирається зі своєї папки.", + "New service, built from its folder.": "Новий сервіс, збирається зі своєї теки.", "The compose file isn't on this computer: {error}": "Compose-файлу немає на цьому комп’ютері: {error}", "Saved, matches what runs": "Збережено, збігається із запущеним", "Line {n}.": "Рядок {n}.", @@ -1731,12 +1731,12 @@ "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "Проєкт з назвою {name} уже працює з {dir}. Відкрийте його або дайте цьому файлу власний рядок name:.", "{n} needs it": "Потрібен {n} сервісу", "File": "Файл", - "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "Kiri не може показати план із прихованим {name}. «{apply}» запустить docker compose up.", + "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "Kiri не може показати план, поки {name} приховано. «{apply}» запустить docker compose up.", "REMOVED": "ВИДАЛЕНО", "The file changed outside Kiri. Apply writes your edits over it, and those changes are lost.": "Файл змінено поза Kiri. Застосування запише ваші правки поверх нього, і ті зміни буде втрачено.", "The other Apply of {name} finished. Your edit isn't applied yet.": "Інше застосування {name} завершилося. Вашу правку ще не застосовано.", "The file changed outside Kiri.": "Файл змінено поза Kiri.", - "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "Kiri не може перевірити цей файл із прихованою {name}. Compose його приймає, тож «Застосувати» усе одно працює.", + "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "Kiri не може перевірити цей файл, поки {name} приховано. Compose його приймає, тож «Застосувати» усе одно працює.", "Compose rejects this file with its real values. Kiri can't show why with secrets hidden.": "Compose відхиляє цей файл зі справжніми значеннями. Kiri не може показати чому, поки секрети приховано.", "docker compose took longer than {secs} seconds": "docker compose працював довше {secs} с", "Discard": "Відкинути", @@ -1770,29 +1770,29 @@ "The compose file is gone from its folder.": "Compose-файлу більше немає в його теці.", "Zoom in": "Збільшити", "The image name from {name} isn't valid": "Назва образу з {name} недійсна", - "Kiri can't show this service's details with its secrets hidden": "Kiri не може показати подробиці цієї служби з прихованими секретами", + "Kiri can't show this service's details with its secrets hidden": "Kiri не може показати подробиці цього сервісу, поки його секрети приховано", "The file changed outside Kiri": "Файл змінено поза Kiri", "Recreate": "Перестворити", "Applied {name}, but {svc} stopped": "{name} застосовано, але {svc} зупинився", "Web": "Веб", "See its logs": "Переглянути його журнали", "Remove from the list": "Прибрати зі списку", - "Compose rejects this file. A required variable may not be set: {name}.": "Compose відхиляє цей файл. Можливо, обовʼязкову змінну не задано: {name}.", + "Compose rejects this file. A required variable may not be set: {name}.": "Compose відхиляє цей файл. Можливо, не задано обов’язкову змінну: {name}.", "environment": "середовище", "Search": "Пошук", - "Couldn't save the compose file: {error}": "Не вдалося зберегти Compose-файл: {error}", + "Couldn't save the compose file: {error}": "Не вдалося зберегти compose-файл: {error}", "Compose files": "Compose-файли", "Scheduler": "Планувальник", - "Kiri has nothing to put back": "Kiri нічого повертати", + "Kiri has nothing to put back": "Kiri немає чого повертати", "Put back the file as it was before Apply saved over it": "Повернути файл до стану перед тим, як «Застосувати» його перезаписало", "Kiri can't check this file's variables, so it manages this project by name. Apply changes from a terminal.": "Kiri не може перевірити змінні цього файлу, тому керує цим проєктом за назвою. Застосовуйте зміни з термінала.", "Edited, not applied": "Змінено, не застосовано", - "This file isn't a compose file: it has no services": "Цей файл не Compose-файл: у ньому немає сервісів", - "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri не знаходить docker CLI. Перезапустіть Kiri, щоб він налаштував його знову.", + "This file isn't a compose file: it has no services": "Цей файл не є compose-файлом: у ньому немає сервісів", + "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri не може знайти docker CLI. Перезапустіть Kiri, щоб налаштувати його знову.", "Fit": "За розміром", "Compose rejects this file: YAML error in an included file, line {n}": "Compose відхиляє цей файл: помилка YAML у включеному файлі, рядок {n}", "Open a compose file…": "Відкрити compose-файл…", - "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "Назва цього файлу використовує {vars}. Kiri використовує назву папки, {name}, щоб ніколи не класти секрет у назву.", + "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "Назва цього файлу використовує {vars}. Kiri використовує назву теки, {name}, щоб ніколи не класти секрет у назву.", "Kiri doesn't know that action": "Kiri не знає такої дії", "Kiri can't find this project's compose file.": "Kiri не може знайти compose-файл цього проєкту.", "ports": "порти", @@ -1810,7 +1810,7 @@ "Showing the file as edited, not applied yet.": "Показано змінений файл, ще не застосований.", "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "Поки нічого: файл збігається із запущеним. Змініть його, і тут з’явиться, що станеться з кожним сервісом.", "Kiri can't read the compose file: {error}": "Kiri не може прочитати compose-файл: {error}", - "Pick a .yaml or .yml compose file": "Виберіть Compose-файл .yaml або .yml", + "Pick a .yaml or .yml compose file": "Виберіть compose-файл .yaml або .yml", "Applied {name}, but {svcs} stopped": "{name} застосовано, але зупинилися: {svcs}", "Compose rejects this file: YAML error in {file}, line {n}": "Compose відхиляє цей файл: помилка YAML у {file}, рядок {n}", "What Apply does": "Що зробить «Застосувати»", @@ -1820,13 +1820,13 @@ "Couldn't read env file {file}: it isn't a local regular file": "Не вдалося прочитати env-файл {file}: це не звичайний локальний файл", "Keep editing": "Продовжити редагування", "The compose file is read-only, so Kiri can't save it. Make it writable, then Apply again.": "Compose-файл лише для читання, тому Kiri не може його зберегти. Дозвольте запис і застосуйте знову.", - "There's no Compose project {name} on Kiri": "У Kiri немає Compose-проєкту {name}", + "There's no Compose project {name} on Kiri": "У Kiri немає проєкту Compose {name}", "The compose file is back, and differs from your edits.": "Compose-файл повернувся і відрізняється від ваших змін.", "{n} more": "ще {n}", "Unchanged": "Без змін", "Saved, but line {n} has an error": "Збережено, але в рядку {n} помилка", "Actual size": "Фактичний розмір", - "Show in compose file": "Показати у файлі Compose", + "Show in compose file": "Показати в compose-файлі", "Open project": "Відкрити проєкт", "not started": "не запускався", "Apply the compose file to create it": "Застосуйте compose-файл, щоб створити його", diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 23592ac98..baf71c104 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 +### #645 Localization: Ukrainian's Share is a button, and other wording fixes (unreleased) +- Fixes: no issue +- Caused: none known +- Caused by: - +- Check: none + ### #745, #134 HTTP: drain bounded chunked trailers, handle `Expect: 100-continue`, and reject conflicting request framing (unreleased) - Fixes: #745 Chunked HTTP/1.1 request bodies with trailers corrupt subsequent requests on keep-alive connections; #134 Handle `Expect: 100-continue` before reading request bodies and reject ambiguous `Transfer-Encoding` + `Content-Length` framing per RFC 9112 - Caused: none known From ea8a341e7718ab4985ecee9c5e77afdb1a6d6810 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:16:44 +0100 Subject: [PATCH 074/157] UI & Diagnostics: add Windows bind-watch toggle, fix narrow socket layout, and remove macOS copy on Linux/Windows (#487) (#871) --- crates/kiri-win/src/engine.rs | 2 + crates/kiri-win/src/main.rs | 47 ++++++++++++ crates/kiri-win/src/relay.rs | 8 ++- crates/kiri-win/src/serve.rs | 5 +- crates/kiri/src/daemon/http.rs | 21 ++++-- crates/kiri/src/daemon/storage.rs | 22 ++++++ crates/kiri/src/diag/report.rs | 62 ++++++++++++---- crates/kiri/src/ui/index.html | 49 ++++++++----- crates/kiri/src/ui/lang/am.json | 16 ++++- crates/kiri/src/ui/lang/ar.json | 16 ++++- crates/kiri/src/ui/lang/bg.json | 16 ++++- crates/kiri/src/ui/lang/bn.json | 16 ++++- crates/kiri/src/ui/lang/ca.json | 16 ++++- crates/kiri/src/ui/lang/ckb.json | 16 ++++- crates/kiri/src/ui/lang/cs.json | 16 ++++- crates/kiri/src/ui/lang/de.json | 16 ++++- crates/kiri/src/ui/lang/el.json | 16 ++++- crates/kiri/src/ui/lang/es.json | 16 ++++- crates/kiri/src/ui/lang/fa.json | 16 ++++- crates/kiri/src/ui/lang/fi.json | 16 ++++- crates/kiri/src/ui/lang/fr.json | 16 ++++- crates/kiri/src/ui/lang/hi.json | 16 ++++- crates/kiri/src/ui/lang/hu.json | 16 ++++- crates/kiri/src/ui/lang/id.json | 16 ++++- crates/kiri/src/ui/lang/it.json | 16 ++++- crates/kiri/src/ui/lang/ja.json | 16 ++++- crates/kiri/src/ui/lang/kk.json | 16 ++++- crates/kiri/src/ui/lang/ko.json | 16 ++++- crates/kiri/src/ui/lang/lo.json | 16 ++++- crates/kiri/src/ui/lang/lt.json | 16 ++++- crates/kiri/src/ui/lang/nb.json | 16 ++++- crates/kiri/src/ui/lang/pl.json | 16 ++++- crates/kiri/src/ui/lang/pt-BR.json | 16 ++++- crates/kiri/src/ui/lang/ro.json | 16 ++++- crates/kiri/src/ui/lang/ru.json | 16 ++++- crates/kiri/src/ui/lang/sl.json | 16 ++++- crates/kiri/src/ui/lang/sq.json | 16 ++++- crates/kiri/src/ui/lang/ta.json | 16 ++++- crates/kiri/src/ui/lang/te.json | 16 ++++- crates/kiri/src/ui/lang/th.json | 16 ++++- crates/kiri/src/ui/lang/tr.json | 16 ++++- crates/kiri/src/ui/lang/uk.json | 16 ++++- crates/kiri/src/ui/lang/vi.json | 16 ++++- crates/kiri/src/ui/lang/zh-Hans.json | 16 ++++- crates/kiri/src/ui/lang/zh-Hant.json | 16 ++++- crates/kiri/src/ui/mod.rs | 6 +- docs/fix-registry.md | 6 ++ tests/regressions.tsv | 1 + tests/ui/dockersock-narrow.js | 102 +++++++++++++++++++++++++++ tests/ui/watch-bind-mounts.js | 69 ++++++++++++++++++ 50 files changed, 910 insertions(+), 82 deletions(-) create mode 100644 tests/ui/dockersock-narrow.js create mode 100644 tests/ui/watch-bind-mounts.js diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index aade5b9db..bd8ed7243 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -1001,9 +1001,11 @@ fn set_pref(name: &str, value: Value) { let on = value.as_bool().unwrap_or(false); if crate::watch::save_enabled(on).is_err() { emit(notice("error", &trf("Could not save the setting to {path}", &[("path", &"%LOCALAPPDATA%\\Kiri\\settings.json")]))); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); return; } crate::watch::set_enabled(crate::watch::is_enabled()); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); return; } if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton" | "startAtLogin" | "stopOnQuit") { diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index 034f69a1e..fae8222a3 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -124,6 +124,23 @@ mod ports; // Settings → Storage: custom WSL distro location in %LOCALAPPDATA%\Kiri\storage.json. #[cfg(any(windows, test))] mod storage; + +#[cfg(any(windows, test))] +pub(crate) fn format_try_wait(res: std::io::Result>) -> Option { + match res { + Ok(None) => None, + Ok(Some(status)) => Some(format!("{status}")), + Err(e) => Some(format!("{e}")), + } +} + +#[cfg(any(windows, test))] +pub(crate) fn format_wait_status(res: std::io::Result) -> String { + match res { + Ok(status) => format!("{status}"), + Err(e) => format!("{e}"), + } +} // Settings → Import from Docker Desktop: the Mac's and Linux's own // crates/kiri/src/import.rs, through the docker CLI's contexts. #[cfg(windows)] @@ -251,3 +268,33 @@ fn main() -> std::process::ExitCode { eprintln!("kiri-win runs on Windows only"); std::process::ExitCode::FAILURE } + +#[cfg(test)] +mod exit_status_tests { + #[test] + fn formats_exit_status_with_display_instead_of_nested_debug() { + let run = |code: i32| { + #[cfg(windows)] + let mut cmd = { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", &format!("exit {code}")]); + c + }; + #[cfg(not(windows))] + let mut cmd = { + let mut c = std::process::Command::new("sh"); + c.args(["-c", &format!("exit {code}")]); + c + }; + cmd.status().unwrap() + }; + let status = run(15); + let waited = super::format_wait_status(Ok(status)); + assert!(!waited.contains("Ok(") && !waited.contains("ExitStatus("), "nested Debug leaked: {waited}"); + assert!(waited.contains("15"), "{waited}"); + let polled = super::format_try_wait(Ok(Some(status))).unwrap(); + assert_eq!(polled, waited); + assert_eq!(super::format_try_wait(Ok(None)), None); + assert_eq!(super::format_wait_status(Err(std::io::Error::other("wait failed"))), "wait failed"); + } +} diff --git a/crates/kiri-win/src/relay.rs b/crates/kiri-win/src/relay.rs index 522a2bf6c..91641759c 100644 --- a/crates/kiri-win/src/relay.rs +++ b/crates/kiri-win/src/relay.rs @@ -155,8 +155,12 @@ fn start(distro: Option, kiri: String) -> io::Result> { ); r.dead.store(true, Ordering::SeqCst); r.changed.notify_all(); - let status = child.wait(); - log_once(format!("host relay ended: {end:?}, {status:?}")); + let end = match end { + Ok(()) => "closed".to_owned(), + Err(e) => format!("{e}"), + }; + let status = crate::format_wait_status(child.wait()); + log_once(format!("host relay ended: {end}, {status}")); }); Ok(relay) } diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 8c29923f9..9b958e8b7 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -1451,10 +1451,7 @@ impl Process for Wsl { } fn exited(&mut self) -> Option { - match self.0.try_wait() { - Ok(None) => None, - status => Some(format!("{status:?}")), - } + crate::format_try_wait(self.0.try_wait()) } } diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index 27659e6b4..c833ed0d2 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -752,14 +752,27 @@ pub fn serving(req: &Request) { fn note_failure(status: u16) { SERVING.with(|s| { let (method, path) = &*s.borrow(); - match status { - 404 => crate::diag::debug!("request failed", method = method, path = path, status = status), - 400..=499 => crate::diag::warn!("request failed", method = method, path = path, status = status), - _ => crate::diag::error!("request failed", method = method, path = path, status = status), + if method.is_empty() && path.is_empty() { + match status { + 404 => crate::diag::debug!("request failed", status = status), + 400..=499 => crate::diag::warn!("request failed", status = status), + _ => crate::diag::error!("request failed", status = status), + } + } else { + match status { + 404 => crate::diag::debug!("request failed", method = method, path = path, status = status), + 400..=499 => crate::diag::warn!("request failed", method = method, path = path, status = status), + _ => crate::diag::error!("request failed", method = method, path = path, status = status), + } } }); } +#[cfg(test)] +pub fn current_serving() -> (String, String) { + SERVING.with(|s| s.borrow().clone()) +} + fn head(w: &mut impl Write, status: u16, extra: &str) -> io::Result<()> { if status >= 400 { note_failure(status); diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index e4b65a804..c4c8fa7dd 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -707,6 +707,7 @@ pub fn serve_unavailable(stream: UnixStream, missing: &Path) -> io::Result<()> { if req.too_large() { return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); } + http::serving(&req); match (req.method.as_str(), req.path.as_str()) { ("GET" | "HEAD", "/_ping") => http::respond(&mut w, 200, "text/plain; charset=utf-8", if req.method == "HEAD" { b"" } else { b"OK" })?, ("GET", "/version") => http::json(&mut w, 200, &super::api::version().to_string())?, @@ -999,4 +1000,25 @@ mod tests { assert!(!gone.exists()); let _ = std::fs::remove_dir_all(&d); } + + /// Requests refused with 503 while storage is unavailable record their + /// HTTP method and path on the connection thread so failure logs carry + /// `method=GET path=/containers/json status=503` instead of empty fields. + #[test] + fn serve_unavailable_populates_method_and_path_on_503() { + use std::io::{Read, Write}; + let d = scratch("unavailable-503"); + let gone = d.join("Volumes/External/kiri"); + let (mut client, server) = UnixStream::pair().unwrap(); + client + .write_all(b"GET /v1.47/containers/json HTTP/1.1\r\nHost: docker\r\nConnection: close\r\n\r\n") + .unwrap(); + serve_unavailable(server, &gone).unwrap(); + assert_eq!(http::current_serving(), ("GET".to_owned(), "/containers/json".to_owned())); + let mut resp = String::new(); + client.read_to_string(&mut resp).unwrap(); + assert!(resp.starts_with("HTTP/1.1 503 "), "{resp}"); + assert!(resp.contains("Connection: close\r\n"), "{resp}"); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index d12fc2dd4..ac33614b7 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -62,7 +62,9 @@ const CRASHES: usize = 5; /// Log lines a crash upload carries: its part's last ones before it. const CRASH_LOG_LINES: usize = 200; const CRASH_BUDGET: usize = 48 << 10; +#[cfg(any(target_os = "macos", test))] const MAC_REPORTS: usize = 3; +#[cfg(any(target_os = "macos", test))] const MAC_REPORT_BUDGET: usize = 24 << 10; pub fn run(args: &[String]) -> io::Result<()> { @@ -388,9 +390,35 @@ fn crash_name(name: &str) -> Option<(u64, Part)> { Some((secs, part)) } -/// The report's text, redacted. `home` holds `Library/Logs/DiagnosticReports`; -/// `state` is `~/.kiri`. +#[cfg(any(target_os = "macos", test))] +fn append_macos_crash_reports(s: &mut String, home: &Path) { + // What macOS wrote down itself: crashes our hook can't see (a signal, a + // hang the system killed, an abort inside a framework). + let reports = home.join("Library/Logs/DiagnosticReports"); + let month = SystemTime::now() - Duration::from_secs(30 * 86_400); + let ips: Vec<_> = newest(&reports, |n| n.to_ascii_lowercase().starts_with("kiri") && n.ends_with(".ips")).into_iter().filter(|(_, t)| *t >= month).collect(); + let _ = writeln!(s, "\n==== macOS crash reports ({}, last 30 days: {}) ====", reports.display(), ips.len()); + for (path, _) in ips.iter().take(MAC_REPORTS) { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap_or_default()).into_owned(); + let _ = writeln!(s, "--- {} ---", path.file_name().unwrap_or_default().to_string_lossy()); + s.push_str(&first_bytes(&text, MAC_REPORT_BUDGET)); + s.push('\n'); + } +} + +/// The report's text, redacted. `home` holds `Library/Logs/DiagnosticReports` +/// on macOS; `state` is `~/.kiri`. pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) -> String { + #[cfg(target_os = "macos")] + return assemble_inner(home, state, facts, redactor, true); + #[cfg(not(target_os = "macos"))] + { + let _ = home; + assemble_inner(home, state, facts, redactor, false) + } +} + +fn assemble_inner(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor, include_macos_reports: bool) -> String { let mut s = String::new(); let _ = writeln!(s, "Kiri diagnostics report"); let _ = writeln!(s, "Created: {}", time::rfc3339(facts.created)); @@ -445,18 +473,12 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - s.push_str(&first_bytes(&text, CRASH_BUDGET)); } - // What macOS wrote down itself: crashes our hook can't see (a signal, a - // hang the system killed, an abort inside a framework). - let reports = home.join("Library/Logs/DiagnosticReports"); - let month = SystemTime::now() - Duration::from_secs(30 * 86_400); - let ips: Vec<_> = newest(&reports, |n| n.to_ascii_lowercase().starts_with("kiri") && n.ends_with(".ips")).into_iter().filter(|(_, t)| *t >= month).collect(); - let _ = writeln!(s, "\n==== macOS crash reports ({}, last 30 days: {}) ====", reports.display(), ips.len()); - for (path, _) in ips.iter().take(MAC_REPORTS) { - let text = String::from_utf8_lossy(&std::fs::read(path).unwrap_or_default()).into_owned(); - let _ = writeln!(s, "--- {} ---", path.file_name().unwrap_or_default().to_string_lossy()); - s.push_str(&first_bytes(&text, MAC_REPORT_BUDGET)); - s.push('\n'); + #[cfg(any(target_os = "macos", test))] + if include_macos_reports { + append_macos_crash_reports(&mut s, home); } + #[cfg(not(any(target_os = "macos", test)))] + let _ = (home, include_macos_reports); redactor.apply(&s) } @@ -955,7 +977,8 @@ mod tests { std::fs::write(reports.join("kiri-2026-10-28-094107.ips"), format!("{{\"app_name\":\"kiri\",\"crashReporterKey\":\"ABCD-1234\"}}\n{{\"procPath\":\"{h}/Applications/Kiri.app\"}}")).unwrap(); std::fs::write(reports.join("Safari-2026-10-28-094107.ips"), "not ours").unwrap(); let facts = Facts { engine: "not running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: Some("web nginx:alpine Up 2 hours\n".into()), vm_network: None }; - let text = assemble(&home, &state, &facts, &Redactor::new(Some(h.clone()), Vec::new())); + let redactor = Redactor::new(Some(h.clone()), Vec::new()); + let text = assemble(&home, &state, &facts, &redactor); assert!(text.starts_with("Kiri diagnostics report\nCreated: 2026-10-24T00:00:00"), "{text}"); assert!(text.contains("Engine: not running") && text.contains("Crash reports: not sent automatically")); @@ -967,7 +990,16 @@ mod tests { assert!(text.contains("==== Containers (names, images and status only) ====\nweb nginx:alpine Up 2 hours\n")); assert!(text.contains("2 in all") && text.contains("--- 1792800000-daemon.txt ---") && text.contains("boom with Bearer [redacted]")); assert!(text.find("1792800000-daemon").unwrap() < text.find("1792700000-ui").unwrap(), "newest crash first"); - assert!(text.contains("--- kiri-2026-10-28-094107.ips ---") && text.contains("~/Applications/Kiri.app") && !text.contains("Safari")); + let mac_text = assemble_inner(&home, &state, &facts, &redactor, true); + assert!(mac_text.contains("--- kiri-2026-10-28-094107.ips ---") && mac_text.contains("~/Applications/Kiri.app") && !mac_text.contains("Safari")); + assert!(!mac_text.contains("ABCD-1234") && !mac_text.contains(&h), "{mac_text}"); + let non_mac_text = assemble_inner(&home, &state, &facts, &redactor, false); + assert!(!non_mac_text.contains("macOS crash reports") && !non_mac_text.contains("DiagnosticReports") && !non_mac_text.contains(".ips"), "{non_mac_text}"); + if cfg!(target_os = "macos") { + assert!(text.contains("==== macOS crash reports") && text.contains("--- kiri-2026-10-28-094107.ips ---"), "{text}"); + } else { + assert!(!text.contains("macOS crash reports") && !text.contains("DiagnosticReports") && !text.contains(".ips"), "{text}"); + } assert!(!text.contains("ABCD-1234") && !text.contains(&h), "{text}"); assert!(text.len() < MAX_BODY); let _ = std::fs::remove_dir_all(&home); diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 682eb3702..5f4464939 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -1091,7 +1091,7 @@ .linkbtn { background: none; border: 0; padding: 0; color: var(--blue-light); font: inherit; cursor: pointer; } .pref { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 20px; align-items: center; padding-bottom: 18px; border-bottom: 1px solid var(--line); } .pref .t { font-weight: 600; } -.pref .d { color: var(--muted); font-size: var(--fs); grid-column: 1; } +.pref .d { color: var(--muted); font-size: var(--fs); grid-column: 1; min-width: 0; } .pref select { grid-row: 1 / span 2; grid-column: 2; height: 32px; width: 240px; padding: 0 10px; border-radius: 7px; border: 1px solid var(--line); background: var(--panel); color: var(--text); font: var(--fs) var(--ui-font); } /* Every other ${cpuText(d.cpus)} -

${tr("Memory")}${tr("The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.", { os: OS })} +
${tr("Memory")}${LINUX ? tr("The most containers and the engine may take. Unused memory stays free on Linux.") : tr("The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.", { os: OS })}
${gb(d.memory_mib)}
${hasDisk ? `
${tr("Disk image size")}${tr("The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.", { os: OS })}
${diskGb(diskVal)}
` : ""} ${r.overridden ? `

${hasDisk ? tr("KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.") : tr("KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.")}

` : ""} -
${r.awake ? (hasDisk ? tr("Running now with {cpus}, up to {mem}, and a {disk} disk.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib), disk: diskGb(r.running_disk_gb ?? r.disk_gb) }) : tr("Running now with {cpus} and up to {mem}.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib) })) : tr("The VM is asleep; it starts with these next time.")} +
${r.awake ? (hasDisk ? tr("Running now with {cpus}, up to {mem}, and a {disk} disk.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib), disk: diskGb(r.running_disk_gb ?? r.disk_gb) }) : tr("Running now with {cpus} and up to {mem}.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib) })) : LINUX ? tr("The engine is off; it starts with these next time.") : tr("The VM is asleep; it starts with these next time.")} - ${pending ? `` : ""} + ${pending ? `` : ""}
${pending ? `

${esc(r.restart_note || tr("Restarting stops the running containers; start them again afterwards."))}

` : ""}
`; @@ -4558,12 +4559,18 @@

${tr("Use {app} for docker?", { app: esc(app) })}

function wslPane() { const list = ui.res?.wsl_distros; - if (!WIN && !Array.isArray(list)) return ""; - if (!Array.isArray(list)) return `

${tr("WSL integration")}

${tr("Loading…")}

`; - if (!list.length) return `

${tr("WSL integration")}

${tr("No other WSL distros installed.")}

`; - const rows = list.map((w) => `
${esc(w.name)}${tr("docker, Compose and Docker-socket tools reach Kiri")} -
`).join(""); - return `

${tr("WSL integration")}

${rows}
`; + const hasWatch = prefs.watchBindMounts != null || ui.res?.watch_bind_mounts != null; + if (!WIN && !Array.isArray(list) && !hasWatch) return ""; + const watchOn = !!(prefs.watchBindMounts ?? ui.res?.watch_bind_mounts); + const watchRow = `
${tr("Windows bind-mount file events")}${tr("Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.", { path: 'C:\\' })} +
`; + const distros = Array.isArray(list) + ? (list.length + ? list.map((w) => `
${esc(w.name)}${tr("docker, Compose and Docker-socket tools reach Kiri")} +
`).join("") + : `

${tr("No other WSL distros installed.")}

`) + : WIN ? `

${tr("Loading…")}

` : ""; + return `

${tr("WSL integration")}

${watchRow}${distros}
`; } /* Settings → Storage: where Kiri keeps images, containers, and volumes. */ @@ -8161,10 +8168,10 @@

${tr("Logs")}

const item = (t, d) => `
${dgIcon("check")}${t}${d}
`; scrim.innerHTML = ``; } +/* Settings → Builds: cache limit and idle sleep (/kiri/builder). */ +function builderSettingsPrefs() { + const s = ui.bset; + if (!s || s.error) return ""; + const cacheVal = Math.min(128, Math.max(2, Number(ui.bsetDraft?.cache_gb ?? s.cache_gb ?? s.default_cache_gb ?? 20))); + const idleVal = Number(ui.bsetDraft?.idle_secs ?? s.idle_secs ?? 300); + const idleOpts = [[300, tr("5 min")], [600, tr("10 min")], [1800, tr("30 min")], [0, tr("Never")]]; + return `
${tr("Build cache limit")} + ${tr("Oldest cached layers are pruned automatically once BuildKit's cache passes this size.")} +
${diskGb(cacheVal)}
+
${tr("Stop builder when idle")} + ${tr("Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.")} +
${idleOpts.map(([v, l]) => ``).join("")}
+ ${s.overridden ? `

${tr("KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.")}

` : ""}`; +} + /* Settings → Builds: Docker's builder or Kiri's for plain `docker build`, at once. */ function buildsPane() { const b = ui.bw; @@ -4413,6 +4429,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

${note} ${builderPref()} + ${builderSettingsPrefs()}

${tr("{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.", { cmd: cmd("kiri build") })}

`; } @@ -4465,16 +4482,30 @@

${tr("Use {app} for docker?", { app: esc(app) })}

return sockRow + cliRow; } +function vmNetRow() { + const v = ui.vmnet; + if (!v || v.supported === false) return ""; + const nat = v.shared_nat !== false; + const desc = nat + ? tr("macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.") + : tr("Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart."); + const envNote = v.env ? ` ${tr("KIRI_SHARED_NAT is set in the environment and takes precedence.")}` : ""; + return `
${tr("Outbound VM traffic")} + ${desc}${envNote} +
`; +} + function networkPane() { - const p = ui.proxy, sock = dockerSockRows(); - if (!p) return `

${tr("Network")}

${sock}

${tr("Loading…")}

`; - if (p.error) return `

${tr("Network")}

${sock}

${tr("Start Kiri to change its network settings. ({error})", { error: esc(p.error) })}

`; + const p = ui.proxy, sock = dockerSockRows(), vmnet = vmNetRow(); + if (!p) return `

${tr("Network")}

${sock}${vmnet}

${tr("Loading…")}

`; + if (p.error) return `

${tr("Network")}

${sock}${vmnet}

${tr("Start Kiri to change its network settings. ({error})", { error: esc(p.error) })}

`; const d = ui.pxDraft, eff = p.effective; const seg = [["system", tr("{os} settings", { os: OS })], ["custom", tr("Custom")], ["none", tr("None")]].map(([v, l]) => ``).join(""); const now = eff.https || eff.http ? (eff.no_proxy.length ? tr("In use: {proxy}, except {hosts}.", { proxy: `${esc(eff.https || eff.http)}`, hosts: `${esc(eff.no_proxy.join(", "))}` }) : tr("In use: {proxy}.", { proxy: `${esc(eff.https || eff.http)}` })) : tr("No proxy is in use."); const field = (k, label, ph) => ``; return `

${tr("Network")}

${sock} + ${vmnet}
${tr("Proxy")}${tr("For pulling and pushing images.")} ${d.mode === p.settings.mode ? now : ""}
${seg}
${d.mode === "system" && eff.pac ? `

${tr("{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.", { os: OS })}

` : ""} @@ -4546,7 +4577,7 @@

${tr("Use {app} for docker?", { app: esc(app) })}

${cpuText(d.cpus)}
${tr("Memory")}${LINUX ? tr("The most containers and the engine may take. Unused memory stays free on Linux.") : tr("The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.", { os: OS })}
${gb(d.memory_mib)}
- ${hasDisk ? `
${tr("Disk image size")}${tr("The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.", { os: OS })} + ${hasDisk ? `
${tr("Disk image size")}${tr("The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.", { os: OS, storage: `` })}
${diskGb(diskVal)}
` : ""} ${r.overridden ? `

${hasDisk ? tr("KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.") : tr("KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.")}

` : ""}
${r.awake ? (hasDisk ? tr("Running now with {cpus}, up to {mem}, and a {disk} disk.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib), disk: diskGb(r.running_disk_gb ?? r.disk_gb) }) : tr("Running now with {cpus} and up to {mem}.", { cpus: cpuText(r.running_cpus), mem: gb(r.running_memory_mib) })) : LINUX ? tr("The engine is off; it starts with these next time.") : tr("The VM is asleep; it starts with these next time.")} @@ -4608,6 +4639,94 @@

${tr("Storage location unavailable")}

`; } +function storageDiskRow(s, moving) { + if (LINUX) { + return `
${tr("VM disk space")} + ${tr("Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.")}
`; + } + const vhdx = 'ext4.vhdx'; + const diskHost = s.disk_host, diskInUse = s.disk_in_use, reclaimable = s.reclaimable; + const btnLbl = WIN ? tr("Compact disk…") : tr("Reclaim space"); + const busyLbl = WIN ? tr("Compacting…") : tr("Reclaiming…"); + let d = ""; + if (ui.stReclaiming) { + d = WIN + ? tr("Compacting {vhdx} and restarting the engine…", { vhdx }) + : diskHost != null && diskInUse != null + ? tr("{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…", { host: size(diskHost), os: OS, inUse: size(diskInUse) }) + : tr("Trimming unused blocks inside the VM disk…"); + } else if (ui.stReclaimed) { + const r = ui.stReclaimed, after = r.after ?? diskHost, inUse = r.in_use ?? diskInUse, freed = r.reclaimed || 0; + const freedHtml = `${tr("Freed {size}", { size: size(freed) })}`; + if (freed > 0) { + d = after != null && inUse != null + ? (WIN + ? tr("{host} on Windows ({vhdx}), {inUse} in use · {freed}.", { host: size(after), vhdx, inUse: size(inUse), freed: freedHtml }) + : tr("{host} on {os}, {inUse} in use inside the VM · {freed}.", { host: size(after), os: OS, inUse: size(inUse), freed: freedHtml })) + : freedHtml; + } else { + d = after != null && inUse != null + ? (WIN + ? tr("{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.", { host: size(after), vhdx, inUse: size(inUse) }) + : tr("{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.", { host: size(after), os: OS, inUse: size(inUse) })) + : tr("Nothing to reclaim."); + } + } else if (diskHost != null && diskInUse != null && reclaimable > 0) { + const can = `${tr("{size} can be given back", { size: size(reclaimable) })}`; + d = WIN + ? tr("{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.", { host: size(diskHost), vhdx, inUse: size(diskInUse), can }) + : tr("{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.", { host: size(diskHost), os: OS, inUse: size(diskInUse), can }); + } else if (diskHost != null && diskInUse != null) { + d = WIN + ? tr("{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.", { host: size(diskHost), vhdx, inUse: size(diskInUse) }) + : tr("{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.", { host: size(diskHost), os: OS, inUse: size(diskInUse) }); + } else if (diskHost != null) { + d = WIN + ? tr("{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.", { host: size(diskHost), vhdx }) + : tr("{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.", { host: size(diskHost), os: OS }); + } else { + d = WIN + ? tr("Returns unused space in {vhdx} to Windows. Compacting restarts the engine.", { vhdx }) + : tr("Returns unused blocks in the VM disk to {os} without stopping containers.", { os: OS }); + } + const dis = moving || (diskHost != null && diskInUse != null && !(reclaimable > 0)); + const ctl = ui.stReclaiming + ? `${busyLbl}` + : ``; + return `
${tr("VM disk space")}${d}${ctl}
`; +} + +function storagePruneRow(moving) { + const stoppedN = ui.containers.filter((c) => c.State !== "running").length; + const danglingImgs = ui.images.filter((i) => !(i.RepoTags || []).some((t) => t && t !== ":" && !t.startsWith("sha256:"))); + const danglingSize = danglingImgs.reduce((a, i) => a + (i.Size || 0), 0); + const hasCache = !!ui.builderVolume; + const hasUnused = stoppedN > 0 || danglingImgs.length > 0 || hasCache; + let d = ""; + if (ui.stPruning) { + d = tr("Cleaning up stopped containers, untagged images, and build cache…"); + } else if (hasUnused) { + const parts = []; + if (stoppedN > 0) parts.push(trn(stoppedN, "{n} stopped container", "{n} stopped containers")); + if (danglingImgs.length > 0) { + const cnt = trn(danglingImgs.length, "{n} untagged image", "{n} untagged images"); + parts.push(danglingSize > 0 ? tr("{count} ({size})", { count: cnt, size: size(danglingSize) }) : cnt); + } + if (hasCache) parts.push(tr("build cache")); + d = `${parts.join(" · ")}.`; + } else if (ui.stPruned && ui.stPruned.freed > 0) { + d = tr("No stopped containers, untagged images or build cache · {freed}.", { + freed: `${tr("Freed {size}", { size: size(ui.stPruned.freed) })}`, + }); + } else { + d = tr("No stopped containers, untagged images or build cache."); + } + const ctl = ui.stPruning + ? `${tr("Cleaning up…")}` + : ``; + return `
${tr("Unused Docker data")}${d}${ctl}
`; +} + function storagePane() { const s = ui.storage; if (!s) return `

${tr("Storage")}

${tr("Loading…")}

`; @@ -4648,6 +4767,8 @@

${tr("Storage location unavailable")}

${progressBox} ${errBox} ${oldRow} + ${!unavail ? storageDiskRow(s, moving) : ""} + ${!unavail ? storagePruneRow(moving) : ""}

${tr("Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.")}

`; } @@ -4740,6 +4861,8 @@

${tr("Storage location unavailable")}

${tr("Stop the engine when Kiri quits")}${tr("Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.")}
+ ${ui.shellPath && ui.shellPath.supported !== false ? `
${tr("Command-line tools in shell")}${tr("Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.", { bin: '~/.kiri/bin', zshrc: '.zshrc', zprofile: '.zprofile', docker: 'docker', kubectl: 'kubectl', kiri: 'kiri' })} +
` : ""} `; const portsPref = routerPortsPref(); // On Linux: kiri.localhost only, for now; nothing to switch. @@ -4770,6 +4893,7 @@

${tr("Storage location unavailable")}

`; const a = about; const mib = (b) => (b ? `${(b / 1073741824).toFixed(1)} GB` : "—"); + const canUninstall = a?.can_uninstall ?? (!WIN && !LINUX); const aboutPane = `

${tr("Storage location unavailable")}

${tr("Website")}
runkiri.com
${tr("Made by")}
Canestack Labs
-

${tr("The name comes from the Igbo word ntakịrị, “small”.")}

`; +

${tr("The name comes from the Igbo word ntakịrị, “small”.")}

+ ${canUninstall ? `
${tr("Uninstall Kiri")} + ${tr("Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).", { cmd: 'kiri setup --uninstall' })} +
` : ""}
`; const html = `
${tab("appearance", "textaa", tr("Appearance"))}${tab("resources", "stack", tr("Resources"))}${tab("storage", "harddrive", tr("Storage"))}${tab("network", "globe", tr("Network"))}${tab("builds", "hammer", tr("Builds"))}${tab("registries", "lock", tr("Registries"))}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", tr("Import"))}${tab("domains", "network", tr("Domains"))}${tab("diagnostics", "bug", tr("Diagnostics"))}${tab("about", "info", tr("About"))}
${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "storage" ? storagePane() : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}
`; // The container lists arrive every few seconds; rebuilding an unchanged page @@ -4829,6 +4956,22 @@

${tr("Storage location unavailable")}

// A list left open over a page that's gone (another view) closes; over the page drawn again, it stays. if (langPopState.close) $("pref-lang-btn")?.setAttribute("aria-expanded", "true"); $("pref-mono")?.addEventListener("change", (ev) => setPref("mono", ev.target.value)); + $("bld-cache")?.addEventListener("input", (ev) => { + const v = +ev.target.value; + ui.bsetDraft = { ...(ui.bsetDraft || {}), cache_gb: v }; + ev.target.style.setProperty("--fill", rangeFill(v, +ev.target.min, +ev.target.max)); + $("bld-cache-v").textContent = diskGb(v); + }); + $("bld-cache")?.addEventListener("change", (ev) => { + const v = +ev.target.value; + ui.bsetDraft = { ...(ui.bsetDraft || {}), cache_gb: v }; + if (ui.bset) ui.bset = { ...ui.bset, cache_gb: v }; + send("setbuildersettings", { value: { cache_gb: v, idle_secs: ui.bsetDraft?.idle_secs ?? ui.bset?.idle_secs ?? 300 } }); + }); + $("k8s-ver")?.addEventListener("change", (ev) => { + const v = ev.target.value, c = k8s.config || {}; + if (v !== (c.version || "")) k8sDo("set", { lan: !!c.lan, tls_san: c.tls_san || [], version: v || "default" }); + }); } /* i18n */ void [tr("Blue"), tr("Purple"), tr("Orange"), tr("Teal"), tr("Pink"), tr("Green"), tr("Small"), tr("Medium"), tr("Large")]; @@ -4842,7 +4985,7 @@

${tr("Storage location unavailable")}

if (view === "compose") { cmp.open = null; cmp.asked = 0; cmpAsk(); } if (view === "usb") usbPoll(); if (view === "share") { send("shares"); send("shareusage"); shPoll(); } - if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("storage"); send("dockersock"); send("proxy"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } + if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("storage"); send("dockersock"); send("proxy"); send("vmnet"); send("buildersettings"); send("shellpath"); send("registryconfig"); send("routerports"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); } render(); // From the top, as a container's or pod's page opens: leaving a page scrolled // down (a long Terminal or Logs tab) otherwise opened the next view below its rows. @@ -8377,6 +8520,13 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "onboarding": onboarding(e); break; case "buildask": buildAsk(e.engine); break; case "buildwith": ui.bw = e; if (ui.view === "settings") render(); break; + case "buildersettings": + ui.bset = e; + if (!e.error) ui.bsetDraft = { cache_gb: e.cache_gb ?? e.default_cache_gb ?? 20, idle_secs: e.idle_secs ?? 300 }; + if (ui.view === "settings") render(); + break; + case "vmnet": ui.vmnet = e; if (ui.view === "settings") render(); break; + case "shellpath": ui.shellPath = e; ui.shellPathBusy = false; if (ui.view === "settings") render(); break; case "dockersock": ui.dockersock = e; ui.sockTaking = false; if (ui.view === "settings") render(); break; case "status": ui.status = e; @@ -8470,9 +8620,33 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r const wasUnavail = ui.storage?.state === "unavailable"; ui.storage = e; if (e.state === "moving") ui.stErr = ""; + if (e.reclaimable > 0) ui.stReclaimed = null; if (ui.view === "settings" || e.state === "unavailable" || wasUnavail) render(); break; } + case "storagereclaimed": + ui.stReclaiming = false; + if (e.error) { + toast("error", tr("Couldn't reclaim disk space: {error}", { error: e.error })); + } else { + ui.stReclaimed = e; + if (ui.storage && e.after != null) { + ui.storage = { ...ui.storage, disk_host: e.after, ...(e.in_use != null ? { disk_in_use: e.in_use } : {}), reclaimable: 0 }; + } + toast("ok", e.reclaimed > 0 ? tr("Reclaimed {size} on {os}", { size: size(e.reclaimed), os: OS }) : tr("Nothing to reclaim")); + } + if (ui.view === "settings") render(); + break; + case "storagepruned": + ui.stPruning = false; + if (e.error) { + toast("error", tr("Couldn't clean up unused Docker data: {error}", { error: e.error })); + } else { + ui.stPruned = e; + toast("ok", e.freed > 0 ? tr("Cleaned up {size} of unused Docker data", { size: size(e.freed) }) : tr("Cleaned up unused Docker data")); + } + if (ui.view === "settings") render(); + break; case "storagecheck": if (e.error) { ui.stErr = e.error; if (ui.view === "settings") render(); else toast("error", e.error); } else { ui.stErr = ""; storageConfirm(e); } @@ -8576,8 +8750,18 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-g]"))) projectAsk(el.dataset.project, el.dataset.g); else if ((el = t("[data-group]"))) toggleGroup(el); else if (composeClick(t)) {} - else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "storage") send("storage"); if (prefs.tab === "network") { send("proxy"); send("dockersock"); } if (prefs.tab === "builds") send("buildwith"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } + else if ((el = t("[data-stab]"))) { prefs.tab = el.dataset.stab; if (prefs.tab === "about") send("about"); if (prefs.tab === "storage") send("storage"); if (prefs.tab === "network") { send("proxy"); send("dockersock"); send("vmnet"); } if (prefs.tab === "builds") { send("buildwith"); send("buildersettings"); } if (prefs.tab === "appearance") send("shellpath"); if (prefs.tab === "registries") { send("logins"); send("registryconfig"); } if (prefs.tab === "diagnostics") diagOpen(); render(); } else if (t("[data-stpick]")) { ui.stErr = ""; send("storagepick"); } + else if (t("[data-streclaim]")) { + if (WIN) { + confirmRemove(tr("Compact WSL disk?"), tr("Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.", { vhdx: 'ext4.vhdx' }), tr("Compact disk"), () => { ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); }, "primary"); + } else { + ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); + } + } + else if (t("[data-stprune]")) { + confirmRemove(tr("Clean up unused Docker data?"), tr("Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept."), tr("Clean up"), () => { ui.stPruning = true; ui.stPruned = null; send("storageprune"); render(); }); + } else if (t("[data-streset]")) { if (ui.storage?.state === "unavailable") { confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => send("storagereset"), "primary"); @@ -8599,6 +8783,35 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-theme-pick]"))) setPref("theme", el.dataset.themePick); else if ((el = t("[data-accent]"))) setPref("accent", el.dataset.accent); else if (t("[data-buildprune]")) { ui.bwPruning = true; send("buildprune"); render(); } + else if ((el = t("[data-bldidle]"))) { + const secs = +el.dataset.bldidle; + if (ui.bset && !ui.bset.error && secs !== Number(ui.bsetDraft?.idle_secs ?? ui.bset.idle_secs)) { + ui.bsetDraft = { ...(ui.bsetDraft || {}), idle_secs: secs }; + ui.bset = { ...ui.bset, idle_secs: secs }; + send("setbuildersettings", { value: { idle_secs: secs } }); + render(); + } + } + else if ((el = t("[data-vmnat]"))) { + const shared_nat = el.dataset.vmnat === "1"; + if (ui.vmnet && !ui.vmnet.env && !!ui.vmnet.shared_nat !== shared_nat) { + ui.vmnet = { ...ui.vmnet, shared_nat }; + send("setvmnet", { value: { shared_nat } }); + render(); + } + } + else if ((el = t("[data-shellpath]"))) { + const enabled = el.dataset.shellpath === "1"; + if (ui.shellPath && !ui.shellPathBusy && !!ui.shellPath.enabled !== enabled) { + ui.shellPath = { ...ui.shellPath, enabled }; + ui.shellPathBusy = true; + send("setshellpath", { value: { enabled } }); + render(); + } + } + else if (t("[data-uninstall]")) { + confirmRemove(tr("Uninstall Kiri?"), tr("Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it."), tr("Uninstall Kiri"), () => send("uninstall")); + } else if ((el = t("[data-bw]"))) { const v = el.dataset.bw; if (ui.bw && !ui.bw.error && (v !== ui.bw.with || (v === "kiri" && !ui.bw.taken))) { ui.bw = { ...ui.bw, with: v }; send("buildwith", { value: v }); render(); } } else if ((el = t("[data-domains]"))) { if (!!+el.dataset.domains !== !!ui.domainsOn) send("domains", { value: !!+el.dataset.domains }); } else if ((el = t("[data-open-site]"))) send("open", { name: el.dataset.openSite }); @@ -8742,7 +8955,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r awake for it then anyway). Nothing here starts the cluster but Start. */ const K8S_VIEWS = new Set(["pods", "services"]); const k8s = { state: null, ready: false, pods: [], services: [], icon: null, asked: 0, sig: "", detail: null, svc: null, partial: "", - op: "", opAt: 0, opLine: "", context: "", config: null, sanDraft: null, port: null, wantPort: 6443, portDraft: null }; + op: "", opAt: 0, opLine: "", context: "", config: null, sanDraft: null, port: null, wantPort: 6443, portDraft: null, argsDraft: null, defaultVer: "", manifestsDir: "" }; empty.pods = { title: "No pods", body: "Pods you create with kubectl show up here, grouped by namespace.", art: "pods" }; empty.services = { title: "No services", body: "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.", art: "services" }; /* i18n */ void [tr("No pods"), tr("Pods you create with kubectl show up here, grouped by namespace."), tr("No services"), tr("Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.")]; @@ -8818,6 +9031,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r Object.assign(k8s, { state: e.state, ready: !!e.ready, error: e.error || "", context: e.context || k8s.context, config: e.config || k8s.config }); if ("port" in e) k8s.port = e.port; if (e.want_port) k8s.wantPort = e.want_port; + if (e.default_version) k8s.defaultVer = e.default_version; + if (e.manifests_dir) k8s.manifestsDir = e.manifests_dir; if (e.ready) { Object.assign(k8s, { pods: e.pods || [], services: e.services || [], icon: e.icon }); kGone(); } k8sCounts(); k8sSide(); @@ -8835,7 +9050,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (k8sShown()) { const el = $("k8s-step"); if (el) el.textContent = k8s.opLine; else render(); } break; } - k8s.op = ""; k8s.opLine = ""; k8s.opAt = 0; k8s.sanDraft = null; k8s.portDraft = null; + k8s.op = ""; k8s.opLine = ""; k8s.opAt = 0; k8s.sanDraft = null; k8s.portDraft = null; k8s.argsDraft = null; if (e.port) k8s.port = e.port; if (e.want_port) k8s.wantPort = e.want_port; if (e.state === "error") toast("error", tr("Kubernetes: {error}", { error: e.error })); @@ -8953,6 +9168,29 @@

${tr("Network")}

${tr("Additional certificate names")}${tr("IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.", { host: tr(HOST) })}
+

${tr("Cluster")}

+ ${(() => { + const defVer = k8s.defaultVer || "v1.37.1-k3s1"; + const savedVer = cfg.version || ""; + const presets = ["v1.37.1-k3s1", "v1.36.0-k3s1", "v1.35.0-k3s1", "v1.34.1-k3s1", "v1.33.1-k3s1", "v1.32.1-k3s1", "v1.31.4-k3s1"]; + const list = [defVer, ...presets.filter((v) => v !== defVer)]; + if (savedVer && !list.includes(savedVer)) list.push(savedVer); + const optsHtml = list.map((v, i) => { + const val = i === 0 ? "" : v; + const lbl = i === 0 ? `${v} (${tr("default")})` : v; + return ``; + }).join(""); + const savedArgs = (cfg.k3s_args || []).join(" "); + const argsDraft = k8s.argsDraft ?? savedArgs; + const mdir = k8s.manifestsDir || (WIN ? "%LOCALAPPDATA%\\Kiri\\k8s-manifests" : "~/.kiri/k8s-manifests"); + return `
${tr("k3s version")}${tr("Image version for the cluster node ({cmd}). Applies when recreated.", { cmd: 'kiri k8s set --version' })} +
+
${tr("Extra server flags")}${tr("Passed to {srv} ({flag}), separated by spaces.", { srv: 'k3s server', flag: '--k3s-arg' })} +
+
+
${tr("Startup manifests")}${tr("YAML files in {path} are applied whenever the cluster starts.", { path: `${esc(mdir)}` })} +
`; + })()}
${tr("Delete cluster")}${tr("Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.", { volume: 'kiri-k8s', context: `${esc(k8sContext())}`, cmd: 'kiri k8s delete' })}
`; @@ -9463,6 +9701,8 @@

${tr("Labels")}

else k8sDo("set", { lan: !!c.lan, tls_san: c.tls_san || [], port }); } else if (t("[data-k8ssan]")) { const c = k8s.config || {}; k8sDo("set", { lan: !!c.lan, tls_san: ($("k8s-san")?.value || "").split(",").map((x) => x.trim()).filter(Boolean) }); } + else if (t("[data-k8sargs]")) { const c = k8s.config || {}; const list = ($("k8s-args")?.value || "").trim().split(/\s+/).filter(Boolean); k8sDo("set", { lan: !!c.lan, tls_san: c.tls_san || [], k3s_args: list }); } + else if (t("[data-k8smanifests]")) send("k8s", { action: "manifests" }); else if (t("[data-k8sdelete]")) deleteCluster(); else if (t("[data-klogreload]")) podLogs(true); else if (t("[data-klogclear]")) { klogEl.textContent = ""; klogCount(); } @@ -9477,6 +9717,12 @@

${tr("Labels")}

if (b) b.disabled = !!k8s.op || ev.target.value === String(k8s.wantPort); return; } + if (ev.target.id === "k8s-args") { + k8s.argsDraft = ev.target.value; + const b = document.querySelector("[data-k8sargs]"); + if (b) b.disabled = !!k8s.op || ev.target.value === (k8s.config?.k3s_args || []).join(" "); + return; + } if (ev.target.id !== "k8s-san") return; k8s.sanDraft = ev.target.value; const b = document.querySelector("[data-k8ssan]"); diff --git a/crates/kiri/src/ui/k8s.rs b/crates/kiri/src/ui/k8s.rs index 47f8c0d11..d20c690d7 100644 --- a/crates/kiri/src/ui/k8s.rs +++ b/crates/kiri/src/ui/k8s.rs @@ -55,7 +55,7 @@ pub fn handle(action: &str, value: &Value) { "start" => op("start", vec!["start".into()]), "stop" => op("stop", vec!["stop".into()]), "deletecluster" => op("deletecluster", vec!["delete".into()]), - // Settings → Kubernetes → Network: saved, and the node recreated with them. + // Settings → Kubernetes: saved, and the node recreated with them. "set" => { let sans: Vec<&str> = value["tls_san"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); let lan = if value["lan"] == true { "on" } else { "off" }; @@ -63,8 +63,28 @@ pub fn handle(action: &str, value: &Value) { if let Some(port) = value["port"].as_u64() { args.extend(["--port".into(), port.to_string()]); } + if let Some(ver) = value.get("version") { + let raw = ver.as_str().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("default"); + args.extend(["--version".into(), raw.to_owned()]); + } + if let Some(kargs) = value.get("k3s_args").and_then(Value::as_array) { + let list: Vec = kargs.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect(); + if list.is_empty() { + args.push("--clear-k3s-args".into()); + } else { + for a in list { + args.extend(["--k3s-arg".into(), a]); + } + } + } op("set", args); } + "manifests" => { + if let Ok(dir) = crate::k8s::manifests_dir() { + let _ = std::fs::create_dir_all(&dir); + super::open(&dir); + } + } "delete" => delete(arg("ns"), arg("pod")), "logs" => logs(arg("ns"), arg("pod"), arg("container"), value["previous"] == true), "logsstop" => stop_logs(), @@ -233,6 +253,10 @@ fn read_lists() -> Value { v["op"] = json!(current_op()); v["context"] = json!(crate::flavor::CONTEXT.get()); v["config"] = json!(crate::k8s::config()); + v["default_version"] = json!(crate::k8s::DEFAULT_VERSION); + if let Ok(dir) = crate::k8s::manifests_dir() { + v["manifests_dir"] = json!(dir); + } v } diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index d504c22fc..3def09c72 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -1854,7 +1854,6 @@ "Disk image size": "የዲስክ ምስል መጠን", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS፣ KIRI_MEMORY_MIB ወይም KIRI_DISK_GB ለዴሞኑ ተቀናብሯል፣ ከእነዚህም ቅድሚያ ይወስዳል።", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "አሁን በ{cpus}፣ እስከ {mem} እና በ{disk} ዲስክ እየሠራ ነው።", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፤ በፍጹም አይቀንስም። ዳግም ሲጀመር ተግባራዊ ይሆናል።", "No other WSL distros installed.": "ሌሎች የWSL ስርጭቶች አልተጫኑም።", "WSL integration": "የWSL ውህደት", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ዝጋ፦ መስኮቱ የሚጠቀመው ማህደረ ትውስታ ይለቀቃል። እንደገና ለመክፈት ትንሽ ጊዜ ይወስዳል፣ የተከፈቱ ተርሚናሎችም ይዘጋሉ።", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri እና ይህ PC", "Kiri and this computer": "Kiri እና ይህ ኮምፒውተር", "Versions, {os}, whether the engine runs, how many containers and images": "ስሪቶች፣ {os}፣ ሞተሩ እየሠራ እንደሆነ፣ ስንት ኮንቴይነሮች እና ኢሜጆች", - "Saved. The engine uses these from its next start": "ተቀምጧል። ሞተሩ እነዚህን ከሚቀጥለው ጅምሩ ጀምሮ ይጠቀማል" + "Saved. The engine uses these from its next start": "ተቀምጧል። ሞተሩ እነዚህን ከሚቀጥለው ጅምሩ ጀምሮ ይጠቀማል", + "5 min": "5 ደቂቃ", + "10 min": "10 ደቂቃ", + "30 min": "30 ደቂቃ", + "Never": "በፍጹም", + "Build cache limit": "የቢልድ ካሽ ገደብ", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "የBuildKit ካሽ ከዚህ መጠን ሲያልፍ በጣም የቆዩት የካሽ ንብርብሮች በራስ-ሰር ይጸዳሉ።", + "Stop builder when idle": "ሥራ ሲፈታ ቢልደሩን አቁም", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "በቢልዶች መካከል BuildKitን ያቆማል ስለዚህ ሥራ ሲፈታ ምንም ማህደረ ትውስታ አይጠቀምም፤ ቀጣዩ ቢልድ ከአንድ ሰከንድ ባነሰ ጊዜ ውስጥ ያነቃዋል።", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB ወይም KIRI_BUILDER_IDLE_SECS ለዴሞኑ ተቀናብሯል፣ ከእነዚህም ቅድሚያ ይወስዳል።", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT፦ በጣም ፈጣኑ። Cloudflare WARP ወይም የድርጅት ፋየርዎል የኮንቴይነር HTTPSን የሚያግድ ከሆነ ወደ አስተናጋጅ ቅብብል ይቀይሩ። VMው ዳግም ሲጀመር ተግባራዊ ይሆናል።", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "አስተናጋጅ ቅብብል፦ ግንኙነቶች በVirtualization.framework NAT ምትክ በmacOS ላይ ካለው Kiri ይወጣሉ። VMው ዳግም ሲጀመር ተግባራዊ ይሆናል።", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT በአካባቢው ተቀናብሯል እና ቅድሚያ ይወስዳል።", + "Outbound VM traffic": "ወጪ የVM ትራፊክ", + "macOS NAT": "macOS NAT", + "Host relay": "አስተናጋጅ ቅብብል", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "የVM ዲስክ ሊያድግ የሚችለው ከፍተኛ መጠን። በ{os} ላይ ቦታ የሚያዝበት ውሂብ ሲጻፍ ብቻ ነው፣ ጥቅም ላይ ያልዋለ ቦታ ደግሞ በ{storage} ውስጥ መመለስ ይቻላል። ዳግም ሲጀመር ተግባራዊ ይሆናል።", + "Settings → Storage": "ቅንብሮች → ማከማቻ", + "VM disk space": "የVM ዲስክ ቦታ", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "ቀጥተኛ Linux የአስተናጋጁን የፋይል ሥርዓት በቀጥታ ይጠቀማል — የተሰረዙ ኢሜጆች እና ቮልዩሞች ወዲያውኑ ቦታ ይለቃሉ።", + "Compact disk…": "ዲስክ አጥብ…", + "Reclaim space": "ቦታ አስመልስ", + "Compacting…": "በማጠብ ላይ…", + "Reclaiming…": "ቦታ በማስመለስ ላይ…", + "Compacting {vhdx} and restarting the engine…": "{vhdx}ን በማጠብ እና ሞተሩን ዳግም በማስጀመር ላይ…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "በ{os} ላይ {host}፣ በVM ውስጥ {inUse} በጥቅም ላይ · ጥቅም ላይ ያልዋሉ ብሎኮችን በመቁረጥ ላይ…", + "Trimming unused blocks inside the VM disk…": "በVM ዲስክ ውስጥ ጥቅም ላይ ያልዋሉ ብሎኮችን በመቁረጥ ላይ…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "በWindows ላይ {host} ({vhdx})፣ {inUse} በጥቅም ላይ · {freed}።", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "በ{os} ላይ {host}፣ በVM ውስጥ {inUse} በጥቅም ላይ · {freed}።", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "በWindows ላይ {host} ({vhdx})፣ {inUse} በጥቅም ላይ · የሚመለስ ነገር የለም።", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "በ{os} ላይ {host}፣ በVM ውስጥ {inUse} በጥቅም ላይ · የሚመለስ ነገር የለም።", + "Nothing to reclaim.": "የሚመለስ ነገር የለም።", + "{size} can be given back": "{size} መመለስ ይቻላል", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "በWindows ላይ {host} ({vhdx})፣ {inUse} በጥቅም ላይ · {can}። ማጠብ ሞተሩን ዳግም ያስጀምረዋል።", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "በ{os} ላይ {host}፣ በVM ውስጥ {inUse} በጥቅም ላይ · ኮንቴይነሮችን ሳያቆሙ {can}።", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "በWindows ላይ {host} ({vhdx})። ማጠብ ጥቅም ላይ ያልዋለ ቦታን ይመልሳል እና ሞተሩን ዳግም ያስጀምረዋል።", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "በ{os} ላይ {host}። ቦታ ማስመለስ ኮንቴይነሮችን ሳያቆም በVM ዲስክ ውስጥ ጥቅም ላይ ያልዋሉ ብሎኮችን ይቆርጣል።", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "በ{vhdx} ውስጥ ጥቅም ላይ ያልዋለ ቦታን ለWindows ይመልሳል። ማጠብ ሞተሩን ዳግም ያስጀምረዋል።", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "ኮንቴይነሮችን ሳያቆም በVM ዲስክ ውስጥ ጥቅም ላይ ያልዋሉ ብሎኮችን ለ{os} ይመልሳል።", + "Cleaning up stopped containers, untagged images, and build cache…": "የቆሙ ኮንቴይነሮችን፣ ታግ የሌላቸው ኢሜጆችን እና የቢልድ ካሹን በማጽዳት ላይ…", + "{count} ({size})": "{count} ({size})", + "build cache": "የቢልድ ካሽ", + "No stopped containers, untagged images or build cache · {freed}.": "የቆሙ ኮንቴይነሮች፣ ታግ የሌላቸው ኢሜጆች ወይም የቢልድ ካሽ የሉም · {freed}።", + "No stopped containers, untagged images or build cache.": "የቆሙ ኮንቴይነሮች፣ ታግ የሌላቸው ኢሜጆች ወይም የቢልድ ካሽ የሉም።", + "Cleaning up…": "በማጽዳት ላይ…", + "Clean up…": "አጽዳ…", + "Unused Docker data": "ጥቅም ላይ ያልዋለ የDocker ውሂብ", + "Command-line tools in shell": "በሼል ውስጥ የትዕዛዝ መስመር መሣሪያዎች", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{docker}፣ {kubectl} እና {kiri} በአዲስ ተርሚናሎች ውስጥ እንዲሠሩ {bin}ን ወደ {zshrc} እና {zprofile} ያክሉ።", + "Uninstall Kiri": "Kiriን አራግፍ", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "ሞተሩን ያቆማል፣ የKiriን የጀርባ አገልግሎት፣ የCLI ሊንኮችን እና የሼል ፕሮፋይል ግቤቶችን ያስወግዳል፣ እንዲሁም የቀድሞ የDocker አውድዎን ይመልሳል ({cmd})።", + "Uninstall Kiri…": "Kiriን አራግፍ…", + "Couldn't reclaim disk space: {error}": "የዲስክ ቦታን ማስመለስ አልተቻለም፦ {error}", + "Reclaimed {size} on {os}": "በ{os} ላይ {size} ተመልሷል", + "Nothing to reclaim": "የሚመለስ ነገር የለም", + "Couldn't clean up unused Docker data: {error}": "ጥቅም ላይ ያልዋለ የDocker ውሂብን ማጽዳት አልተቻለም፦ {error}", + "Cleaned up {size} of unused Docker data": "{size} ጥቅም ላይ ያልዋለ የDocker ውሂብ ጸድቷል", + "Cleaned up unused Docker data": "ጥቅም ላይ ያልዋለ የDocker ውሂብ ጸድቷል", + "Compact WSL disk?": "የWSL ዲስክ ይጠበብ?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx}ን ማጠብ ጥቅም ላይ ያልዋለ ቦታን ለWindows ይመልሳል እንዲሁም የKiriን ሞተር እና እየሠሩ ያሉ ኮንቴይነሮችን ለአጭር ጊዜ ዳግም ያስጀምራል።", + "Compact disk": "ዲስክ አጥብ", + "Clean up unused Docker data?": "ጥቅም ላይ ያልዋለ የDocker ውሂብ ይጽዳ?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "የቆሙ ኮንቴይነሮችን፣ ታግ የሌላቸው ኢሜጆችን እና የBuildKit የቢልድ ካሽን ያስወግዳል። እየሠሩ ያሉ ኮንቴይነሮች እና ታግ ያላቸው ኢሜጆች ይጠበቃሉ።", + "Clean up": "አጽዳ", + "Uninstall Kiri?": "Kiri ይራገፍ?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "ሞተሩን ያቆማል፣ የKiriን የጀርባ አገልግሎት፣ የCLI ሊንኮችን እና የሼል ፕሮፋይል ግቤቶችን ያስወግዳል፣ እንዲሁም የቀድሞ የDocker አውድዎን ይመልሳል። ኢሜጆችዎ እና ቮልዩሞችዎ እስኪሰርዙት ድረስ በKiri የውሂብ አቃፊ ውስጥ ይቆያሉ።", + "Cluster": "ክላስተር", + "default": "ነባሪ", + "k3s version": "የk3s ስሪት", + "Image version for the cluster node ({cmd}). Applies when recreated.": "ለክላስተር ኖዱ የኢሜጅ ስሪት ({cmd})። እንደገና ሲፈጠር ተግባራዊ ይሆናል።", + "Extra server flags": "ተጨማሪ የሰርቨር ፍላጎች", + "Passed to {srv} ({flag}), separated by spaces.": "በክፍተት ተለይተው ወደ {srv} ({flag}) ይተላለፋሉ።", + "Startup manifests": "የጅማሬ ማኒፌስቶች", + "YAML files in {path} are applied whenever the cluster starts.": "በ{path} ውስጥ ያሉ የYAML ፋይሎች ክላስተሩ በጀመረ ቁጥር ይተገበራሉ።", + "Open folder": "አቃፊ ክፈት", + "{n} untagged image": "{n} ታግ የሌለው ኢሜጅ", + "{n} untagged images": "{n} ታግ የሌላቸው ኢሜጆች", + "Uninstall Kiri from Windows Settings → Apps": "Kiriን ከWindows ቅንብሮች → መተግበሪያዎች ያራግፉ", + "Builder settings saved": "የቢልደር ቅንብሮች ተቀምጠዋል", + "Could not save builder settings: {error}": "የቢልደር ቅንብሮችን ማስቀመጥ አልተቻለም፦ {error}", + "Disk reclaim is already running": "የዲስክ ቦታ ማስመለስ አስቀድሞ እየሠራ ነው", + "Outbound VM traffic setting saved. Restart the VM to apply.": "የወጪ VM ትራፊክ ቅንብር ተቀምጧል። ለመተግበር VMውን ዳግም ያስጀምሩ።", + "Could not save VM networking setting: {error}": "የVM ኔትዎርክ ቅንብርን ማስቀመጥ አልተቻለም፦ {error}", + "Added Kiri command-line tools to shell profiles": "የKiri የትዕዛዝ መስመር መሣሪያዎች ወደ ሼል ፕሮፋይሎች ታክለዋል", + "Removed Kiri command-line tools from shell profiles": "የKiri የትዕዛዝ መስመር መሣሪያዎች ከሼል ፕሮፋይሎች ተወግደዋል", + "Could not update shell profiles: {error}": "የሼል ፕሮፋይሎችን ማዘመን አልተቻለም፦ {error}", + "Uninstalling Kiri…": "Kiriን በማራገፍ ላይ…", + "Could not uninstall Kiri: {error}": "Kiriን ማራገፍ አልተቻለም፦ {error}", + "Uninstall Kiri using your system package manager": "የሥርዓትዎን የጥቅል አስተዳዳሪ በመጠቀም Kiriን ያራግፉ" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index f7f285436..d72f5a2e7 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -1854,7 +1854,6 @@ "Disk image size": "حجم صورة القرص", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "المتغير KIRI_CPUS أو KIRI_MEMORY_MIB أو KIRI_DISK_GB معيّن للخدمة الخلفية، وله الأولوية على هذه الإعدادات.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "يعمل الآن بـ {cpus} وبحد أقصى {mem} وقرص بحجم {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ولا يتقلص الحجم أبداً. يُطبّق عند إعادة التشغيل.", "No other WSL distros installed.": "لا توجد توزيعات WSL أخرى مثبّتة.", "WSL integration": "تكامل WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "إغلاق: تُحرَّر الذاكرة التي تستخدمها النافذة. تستغرق لحظة لتُفتح مجددًا، وتُنهى الطرفيات المفتوحة.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri وهذا الكمبيوتر", "Kiri and this computer": "Kiri وهذا الكمبيوتر", "Versions, {os}, whether the engine runs, how many containers and images": "الإصدارات، {os}، هل يعمل المحرّك، وعدد الحاويات والصور", - "Saved. The engine uses these from its next start": "تم الحفظ. يستخدمها المحرّك عند بدئه القادم" + "Saved. The engine uses these from its next start": "تم الحفظ. يستخدمها المحرّك عند بدئه القادم", + "5 min": "5 د", + "10 min": "10 د", + "30 min": "30 د", + "Never": "أبداً", + "Build cache limit": "حدّ ذاكرة البناء المؤقتة", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "تُقلَّم أقدم الطبقات المخزّنة تلقائياً بمجرد تجاوز ذاكرة BuildKit المؤقتة هذا الحجم.", + "Stop builder when idle": "إيقاف أداة البناء عند الخمول", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "يوقف BuildKit بين عمليات البناء كي لا يستهلك ذاكرة أثناء الخمول؛ توقظه عملية البناء التالية في أقل من ثانية.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "المتغير KIRI_BUILD_CACHE_GB أو KIRI_BUILDER_IDLE_SECS معيّن للخدمة الخلفية، وله الأولوية على هذه الإعدادات.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: الأسرع. انتقل إلى ترحيل المضيف إذا كان Cloudflare WARP أو جدار حماية مؤسسي يحجب HTTPS للحاويات. يُطبَّق عند إعادة تشغيل الجهاز الافتراضي.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "ترحيل المضيف: تخرج الاتصالات من Kiri على macOS بدلاً من Virtualization.framework NAT. يُطبَّق عند إعادة تشغيل الجهاز الافتراضي.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "المتغير KIRI_SHARED_NAT معيّن في البيئة وله الأولوية.", + "Outbound VM traffic": "حركة الجهاز الافتراضي الصادرة", + "macOS NAT": "macOS NAT", + "Host relay": "ترحيل المضيف", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "أقصى حجم قد ينمو إليه قرص الجهاز الافتراضي. لا تُستهلك المساحة على {os} إلا عند كتابة البيانات، ويمكن استرداد المساحة غير المستخدمة من {storage}. يُطبَّق عند إعادة التشغيل.", + "Settings → Storage": "الإعدادات ← التخزين", + "VM disk space": "مساحة قرص الجهاز الافتراضي", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "يستخدم Linux الأصلي نظام ملفات المضيف مباشرةً — الصور ووحدات التخزين المحذوفة تحرّر المساحة فوراً.", + "Compact disk…": "ضغط القرص…", + "Reclaim space": "استرداد المساحة", + "Compacting…": "جارٍ الضغط…", + "Reclaiming…": "جارٍ الاسترداد…", + "Compacting {vhdx} and restarting the engine…": "جارٍ ضغط {vhdx} وإعادة تشغيل المحرّك…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} على {os}، {inUse} قيد الاستخدام داخل الجهاز الافتراضي · جارٍ تقليم الكتل غير المستخدمة…", + "Trimming unused blocks inside the VM disk…": "جارٍ تقليم الكتل غير المستخدمة داخل قرص الجهاز الافتراضي…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} على Windows ({vhdx})، {inUse} قيد الاستخدام · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} على {os}، {inUse} قيد الاستخدام داخل الجهاز الافتراضي · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} على Windows ({vhdx})، {inUse} قيد الاستخدام · لا شيء لاسترداده.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} على {os}، {inUse} قيد الاستخدام داخل الجهاز الافتراضي · لا شيء لاسترداده.", + "Nothing to reclaim.": "لا شيء لاسترداده.", + "{size} can be given back": "يمكن استرداد {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} على Windows ({vhdx})، {inUse} قيد الاستخدام · {can}. الضغط يعيد تشغيل المحرّك.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} على {os}، {inUse} قيد الاستخدام داخل الجهاز الافتراضي · {can} دون إيقاف الحاويات.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} على Windows ({vhdx}). الضغط يعيد المساحة غير المستخدمة ويعيد تشغيل المحرّك.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} على {os}. الاسترداد يقلّم الكتل غير المستخدمة في قرص الجهاز الافتراضي دون إيقاف الحاويات.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "يعيد المساحة غير المستخدمة في {vhdx} إلى Windows. الضغط يعيد تشغيل المحرّك.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "يعيد الكتل غير المستخدمة في قرص الجهاز الافتراضي إلى {os} دون إيقاف الحاويات.", + "Cleaning up stopped containers, untagged images, and build cache…": "جارٍ تنظيف الحاويات المتوقفة والصور بلا وسم وذاكرة البناء المؤقتة…", + "{count} ({size})": "{count} ({size})", + "build cache": "ذاكرة البناء المؤقتة", + "No stopped containers, untagged images or build cache · {freed}.": "لا حاويات متوقفة ولا صور بلا وسم ولا ذاكرة بناء مؤقتة · {freed}.", + "No stopped containers, untagged images or build cache.": "لا حاويات متوقفة ولا صور بلا وسم ولا ذاكرة بناء مؤقتة.", + "Cleaning up…": "جارٍ التنظيف…", + "Clean up…": "تنظيف…", + "Unused Docker data": "بيانات Docker غير المستخدمة", + "Command-line tools in shell": "أدوات سطر الأوامر في الصدفة", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "أضِف {bin} إلى {zshrc} و{zprofile} لكي تعمل {docker} و{kubectl} و{kiri} في النوافذ الطرفية الجديدة.", + "Uninstall Kiri": "إزالة تثبيت Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "يوقف المحرّك، ويزيل خدمة Kiri الخلفية وروابط سطر الأوامر وإدخالات ملفات الصدفة، ويستعيد سياق Docker السابق ({cmd}).", + "Uninstall Kiri…": "إزالة تثبيت Kiri…", + "Couldn't reclaim disk space: {error}": "تعذر استرداد مساحة القرص: {error}", + "Reclaimed {size} on {os}": "تم استرداد {size} على {os}", + "Nothing to reclaim": "لا شيء لاسترداده", + "Couldn't clean up unused Docker data: {error}": "تعذر تنظيف بيانات Docker غير المستخدمة: {error}", + "Cleaned up {size} of unused Docker data": "تم تنظيف {size} من بيانات Docker غير المستخدمة", + "Cleaned up unused Docker data": "تم تنظيف بيانات Docker غير المستخدمة", + "Compact WSL disk?": "ضغط قرص WSL؟", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "يُعيد ضغط {vhdx} المساحة غير المستخدمة إلى Windows ويعيد تشغيل محرّك Kiri والحاويات الجارية لبرهة.", + "Compact disk": "ضغط القرص", + "Clean up unused Docker data?": "تنظيف بيانات Docker غير المستخدمة؟", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "يزيل الحاويات المتوقفة والصور بلا وسم وذاكرة BuildKit المؤقتة للبناء. تبقى الحاويات الجارية والصور الموسومة.", + "Clean up": "تنظيف", + "Uninstall Kiri?": "إزالة تثبيت Kiri؟", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "يوقف المحرّك، ويزيل خدمة Kiri الخلفية وروابط سطر الأوامر وإدخالات ملفات الصدفة، ويستعيد سياق Docker السابق. تبقى صورك ووحدات التخزين في مجلد بيانات Kiri حتى تحذفه.", + "Cluster": "العنقود", + "default": "افتراضي", + "k3s version": "إصدار k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "إصدار الصورة لعقدة العنقود ({cmd}). يُطبَّق عند إعادة الإنشاء.", + "Extra server flags": "خيارات إضافية للخادم", + "Passed to {srv} ({flag}), separated by spaces.": "تُمرَّر إلى {srv} ({flag}) مفصولةً بمسافات.", + "Startup manifests": "ملفات بيان بدء التشغيل", + "YAML files in {path} are applied whenever the cluster starts.": "تُطبَّق ملفات YAML الموجودة في {path} كلما بدأ تشغيل العنقود.", + "Open folder": "فتح المجلد", + "{n} untagged image": "{n} صورة بلا وسم", + "{n} untagged images": "{n} من الصور بلا وسم", + "Uninstall Kiri from Windows Settings → Apps": "أزِل تثبيت Kiri من إعدادات Windows ← التطبيقات", + "Builder settings saved": "تم حفظ إعدادات أداة البناء", + "Could not save builder settings: {error}": "تعذر حفظ إعدادات أداة البناء: {error}", + "Disk reclaim is already running": "استرداد مساحة القرص قيد التشغيل بالفعل", + "Outbound VM traffic setting saved. Restart the VM to apply.": "تم حفظ إعداد حركة الجهاز الافتراضي الصادرة. أعد تشغيل الجهاز الافتراضي للتطبيق.", + "Could not save VM networking setting: {error}": "تعذر حفظ إعداد شبكة الجهاز الافتراضي: {error}", + "Added Kiri command-line tools to shell profiles": "تمت إضافة أدوات سطر أوامر Kiri إلى ملفات تعريف الصدفة", + "Removed Kiri command-line tools from shell profiles": "تمت إزالة أدوات سطر أوامر Kiri من ملفات تعريف الصدفة", + "Could not update shell profiles: {error}": "تعذر تحديث ملفات تعريف الصدفة: {error}", + "Uninstalling Kiri…": "جارٍ إزالة تثبيت Kiri…", + "Could not uninstall Kiri: {error}": "تعذرت إزالة تثبيت Kiri: {error}", + "Uninstall Kiri using your system package manager": "أزِل تثبيت Kiri باستخدام مدير الحزم في نظامك" } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 70a96fb2a..675f26431 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -1854,7 +1854,6 @@ "Disk image size": "Размер на дисковия образ", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "За демона е зададена KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB и тя има предимство пред тези настройки.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Работи в момента с {cpus}, до {mem} и диск {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни; размерът никога не се свива. Прилага се при рестартиране.", "No other WSL distros installed.": "Няма други инсталирани WSL дистрибуции.", "WSL integration": "Интеграция с WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Затваряне: паметта, която прозорецът използва, се освобождава. Отварянето му отново отнема миг, а отворените терминали се затварят.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri и този PC", "Kiri and this computer": "Kiri и този компютър", "Versions, {os}, whether the engine runs, how many containers and images": "Версии, {os}, дали двигателят работи, колко контейнера и образа има", - "Saved. The engine uses these from its next start": "Запазено. Двигателят ги използва от следващото си стартиране" + "Saved. The engine uses these from its next start": "Запазено. Двигателят ги използва от следващото си стартиране", + "5 min": "5 мин", + "10 min": "10 мин", + "30 min": "30 мин", + "Never": "Никога", + "Build cache limit": "Лимит на кеша за изграждане", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Най-старите кеширани слоеве се изчистват автоматично, когато кешът на BuildKit надхвърли този размер.", + "Stop builder when idle": "Спиране на билдъра при неактивност", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Спира BuildKit между изгражданията, за да не заема памет при престой; следващото изграждане го събужда за под секунда.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "За демона е зададена KIRI_BUILD_CACHE_GB или KIRI_BUILDER_IDLE_SECS и тя има предимство пред тези настройки.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: най-бърз. Превключете към Реле през хоста, ако Cloudflare WARP или корпоративна защитна стена блокира HTTPS на контейнерите. Прилага се при рестартиране на ВМ.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Реле през хоста: връзките излизат от Kiri в macOS вместо през NAT на Virtualization.framework. Прилага се при рестартиране на ВМ.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT е зададена в средата и има предимство.", + "Outbound VM traffic": "Изходящ трафик на ВМ", + "macOS NAT": "macOS NAT", + "Host relay": "Реле през хоста", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Максимумът, до който може да порасне дискът на виртуалната машина. Пространство на {os} се заема само при запис на данни, а неизползваното място може да се освободи в {storage}. Прилага се при рестартиране.", + "Settings → Storage": "Настройки → Съхранение", + "VM disk space": "Дисково пространство на ВМ", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Директният Linux използва файловата система на хоста — изтритите образи и томове освобождават място веднага.", + "Compact disk…": "Уплътняване…", + "Reclaim space": "Освобождаване", + "Compacting…": "Уплътняване…", + "Reclaiming…": "Освобождаване…", + "Compacting {vhdx} and restarting the engine…": "Уплътняване на {vhdx} и рестартиране на двигателя…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} в {os}, {inUse} използвани във виртуалната машина · изрязване на неизползваните блокове…", + "Trimming unused blocks inside the VM disk…": "Изрязване на неизползваните блокове в диска на виртуалната машина…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} в Windows ({vhdx}), {inUse} използвани · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} в {os}, {inUse} използвани във виртуалната машина · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} в Windows ({vhdx}), {inUse} използвани · няма какво да се освободи.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} в {os}, {inUse} използвани във виртуалната машина · няма какво да се освободи.", + "Nothing to reclaim.": "Няма какво да се освободи.", + "{size} can be given back": "{size} могат да се върнат", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} в Windows ({vhdx}), {inUse} използвани · {can}. Уплътняването рестартира двигателя.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} в {os}, {inUse} използвани във виртуалната машина · {can} без спиране на контейнерите.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} в Windows ({vhdx}). Уплътняването връща неизползваното място и рестартира двигателя.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} в {os}. Освобождаването изрязва неизползваните блокове в диска на виртуалната машина без спиране на контейнерите.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Връща неизползваното място в {vhdx} на Windows. Уплътняването рестартира двигателя.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Връща неизползваните блокове в диска на виртуалната машина към {os} без спиране на контейнерите.", + "Cleaning up stopped containers, untagged images, and build cache…": "Изчистване на спрени контейнери, образи без етикет и кеш за изграждане…", + "{count} ({size})": "{count} ({size})", + "build cache": "кеш за изграждане", + "No stopped containers, untagged images or build cache · {freed}.": "Няма спрени контейнери, образи без етикет или кеш за изграждане · {freed}.", + "No stopped containers, untagged images or build cache.": "Няма спрени контейнери, образи без етикет или кеш за изграждане.", + "Cleaning up…": "Изчистване…", + "Clean up…": "Изчистване…", + "Unused Docker data": "Неизползвани данни на Docker", + "Command-line tools in shell": "Инструменти за командния ред в обвивката", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Добавете {bin} към {zshrc} и {zprofile}, за да работят {docker}, {kubectl} и {kiri} в новите терминали.", + "Uninstall Kiri": "Деинсталиране на Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Спира двигателя, премахва фоновата услуга на Kiri, CLI връзките и записите в профилите на обвивката и възстановява предишния ви Docker контекст ({cmd}).", + "Uninstall Kiri…": "Деинсталиране на Kiri…", + "Couldn't reclaim disk space: {error}": "Неуспешно освобождаване на дисково пространство: {error}", + "Reclaimed {size} on {os}": "Освободени {size} в {os}", + "Nothing to reclaim": "Няма какво да се освободи", + "Couldn't clean up unused Docker data: {error}": "Неуспешно изчистване на неизползваните данни на Docker: {error}", + "Cleaned up {size} of unused Docker data": "Изчистени {size} неизползвани данни на Docker", + "Cleaned up unused Docker data": "Неизползваните данни на Docker са изчистени", + "Compact WSL disk?": "Уплътняване на WSL диска?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Уплътняването на {vhdx} връща неизползваното място на Windows и за кратко рестартира двигателя на Kiri и работещите контейнери.", + "Compact disk": "Уплътни диска", + "Clean up unused Docker data?": "Изчистване на неизползваните данни на Docker?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Премахва спрените контейнери, образите без етикет и кеша за изграждане на BuildKit. Работещите контейнери и образите с етикет се запазват.", + "Clean up": "Изчисти", + "Uninstall Kiri?": "Деинсталиране на Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Спира двигателя, премахва фоновата услуга на Kiri, CLI връзките и записите в профилите на обвивката и възстановява предишния ви Docker контекст. Вашите образи и томове остават в папката с данни на Kiri, докато не я изтриете.", + "Cluster": "Клъстер", + "default": "по подразбиране", + "k3s version": "Версия на k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Версия на образа за възела на клъстера ({cmd}). Прилага се при пресъздаване.", + "Extra server flags": "Допълнителни флагове на сървъра", + "Passed to {srv} ({flag}), separated by spaces.": "Подават се на {srv} ({flag}), разделени с интервали.", + "Startup manifests": "Стартови манифести", + "YAML files in {path} are applied whenever the cluster starts.": "YAML файловете в {path} се прилагат при всяко стартиране на клъстера.", + "Open folder": "Отваряне на папка", + "{n} untagged image": "{n} образ без етикет", + "{n} untagged images": "{n} образа без етикет", + "Uninstall Kiri from Windows Settings → Apps": "Деинсталирайте Kiri от Настройки на Windows → Приложения", + "Builder settings saved": "Настройките на билдъра са запазени", + "Could not save builder settings: {error}": "Неуспешно запазване на настройките на билдъра: {error}", + "Disk reclaim is already running": "Освобождаването на дисково пространство вече се изпълнява", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Настройката за изходящ трафик на ВМ е запазена. Рестартирайте виртуалната машина за прилагане.", + "Could not save VM networking setting: {error}": "Неуспешно запазване на мрежовата настройка на ВМ: {error}", + "Added Kiri command-line tools to shell profiles": "Инструментите за командния ред на Kiri са добавени в профилите на обвивката", + "Removed Kiri command-line tools from shell profiles": "Инструментите за командния ред на Kiri са премахнати от профилите на обвивката", + "Could not update shell profiles: {error}": "Неуспешно обновяване на профилите на обвивката: {error}", + "Uninstalling Kiri…": "Деинсталиране на Kiri…", + "Could not uninstall Kiri: {error}": "Неуспешно деинсталиране на Kiri: {error}", + "Uninstall Kiri using your system package manager": "Деинсталирайте Kiri чрез пакетния мениджър на системата си" } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index cfcf0cead..695d4cc4b 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -1854,7 +1854,6 @@ "Disk image size": "ডিস্ক ইমেজের আকার", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "ডেমনের জন্য KIRI_CPUS, KIRI_MEMORY_MIB বা KIRI_DISK_GB সেট করা আছে, এবং সেগুলো এগুলোর চেয়ে অগ্রাধিকার পায়।", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "এখন {cpus}, সর্বোচ্চ {mem} ও {disk} ডিস্ক নিয়ে চলছে।", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়; এটি কখনো ছোট হয় না। রিস্টার্ট করলে প্রয়োগ হয়।", "No other WSL distros installed.": "অন্য কোনো WSL ডিস্ট্রো ইনস্টল করা নেই।", "WSL integration": "WSL ইন্টিগ্রেশন", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "বন্ধ করুন: উইন্ডোর ব্যবহৃত মেমরি মুক্ত হয়। আবার খুলতে একটু সময় লাগে, এবং খোলা টার্মিনালগুলো বন্ধ হয়ে যায়।", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri ও এই PC", "Kiri and this computer": "Kiri ও এই কম্পিউটার", "Versions, {os}, whether the engine runs, how many containers and images": "ভার্সন, {os}, ইঞ্জিন চলছে কি না, কতগুলো কন্টেইনার ও ইমেজ", - "Saved. The engine uses these from its next start": "সেভ হয়েছে। ইঞ্জিন পরের বার চালু হওয়া থেকে এগুলো ব্যবহার করবে" + "Saved. The engine uses these from its next start": "সেভ হয়েছে। ইঞ্জিন পরের বার চালু হওয়া থেকে এগুলো ব্যবহার করবে", + "5 min": "5 মিনিট", + "10 min": "10 মিনিট", + "30 min": "30 মিনিট", + "Never": "কখনো না", + "Build cache limit": "বিল্ড ক্যাশ সীমা", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit-এর ক্যাশ এই আকার পেরোলেই সবচেয়ে পুরোনো ক্যাশড লেয়ারগুলো স্বয়ংক্রিয়ভাবে ছাঁটাই হয়।", + "Stop builder when idle": "অলস থাকলে বিল্ডার থামান", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "দুই বিল্ডের মাঝে BuildKit থামিয়ে রাখে যাতে অলস অবস্থায় কোনো মেমরি খরচ না হয়; পরের বিল্ড এক সেকেন্ডেরও কম সময়ে এটিকে জাগিয়ে তোলে।", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "ডেমনের জন্য KIRI_BUILD_CACHE_GB বা KIRI_BUILDER_IDLE_SECS সেট করা আছে, এবং তা এগুলোর চেয়ে অগ্রাধিকার পায়।", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: সবচেয়ে দ্রুত। Cloudflare WARP বা কর্পোরেট ফায়ারওয়াল কন্টেইনারের HTTPS ব্লক করলে হোস্ট রিলে-তে বদলান। VM রিস্টার্ট করলে প্রয়োগ হয়।", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "হোস্ট রিলে: Virtualization.framework NAT-এর বদলে macOS-এ Kiri থেকে সংযোগ বের হয়। VM রিস্টার্ট করলে প্রয়োগ হয়।", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "এনভায়রনমেন্টে KIRI_SHARED_NAT সেট করা আছে এবং সেটি অগ্রাধিকার পায়।", + "Outbound VM traffic": "বহির্গামী VM ট্রাফিক", + "macOS NAT": "macOS NAT", + "Host relay": "হোস্ট রিলে", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM ডিস্ক সর্বোচ্চ যতটা বড় হতে পারে। ডেটা লেখা হলেই কেবল {os}-এ জায়গা ব্যবহার হয়, আর অব্যবহৃত জায়গা {storage} থেকে পুনরুদ্ধার করা যায়। রিস্টার্ট করলে প্রয়োগ হয়।", + "Settings → Storage": "সেটিংস → স্টোরেজ", + "VM disk space": "VM ডিস্কের জায়গা", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "নেটিভ Linux সরাসরি আপনার হোস্ট ফাইলসিস্টেম ব্যবহার করে — ইমেজ ও ভলিউম মুছলে সঙ্গে সঙ্গে জায়গা খালি হয়।", + "Compact disk…": "ডিস্ক কমপ্যাক্ট…", + "Reclaim space": "জায়গা ফেরত নিন", + "Compacting…": "কমপ্যাক্ট হচ্ছে…", + "Reclaiming…": "পুনরুদ্ধার হচ্ছে…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} কমপ্যাক্ট করা হচ্ছে ও ইঞ্জিন রিস্টার্ট হচ্ছে…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os}-এ {host}, VM-এর ভেতরে {inUse} ব্যবহৃত হচ্ছে · অব্যবহৃত ব্লক ছাঁটাই হচ্ছে…", + "Trimming unused blocks inside the VM disk…": "VM ডিস্কের ভেতরে অব্যবহৃত ব্লক ছাঁটাই হচ্ছে…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows-এ {host} ({vhdx}), {inUse} ব্যবহৃত হচ্ছে · {freed}।", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os}-এ {host}, VM-এর ভেতরে {inUse} ব্যবহৃত হচ্ছে · {freed}।", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows-এ {host} ({vhdx}), {inUse} ব্যবহৃত হচ্ছে · ফেরত নেওয়ার কিছু নেই।", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os}-এ {host}, VM-এর ভেতরে {inUse} ব্যবহৃত হচ্ছে · ফেরত নেওয়ার কিছু নেই।", + "Nothing to reclaim.": "ফেরত নেওয়ার কিছু নেই।", + "{size} can be given back": "{size} ফেরত দেওয়া যাবে", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows-এ {host} ({vhdx}), {inUse} ব্যবহৃত হচ্ছে · {can}। কমপ্যাক্ট করলে ইঞ্জিন রিস্টার্ট হয়।", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os}-এ {host}, VM-এর ভেতরে {inUse} ব্যবহৃত হচ্ছে · কন্টেইনার বন্ধ না করেই {can}।", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows-এ {host} ({vhdx})। কমপ্যাক্ট করলে অব্যবহৃত জায়গা ফিরে আসে ও ইঞ্জিন রিস্টার্ট হয়।", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os}-এ {host}। পুনরুদ্ধার করলে কন্টেইনার বন্ধ না করেই VM ডিস্কের অব্যবহৃত ব্লক ছাঁটাই হয়।", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx}-এর অব্যবহৃত জায়গা Windows-কে ফিরিয়ে দেয়। কমপ্যাক্ট করলে ইঞ্জিন রিস্টার্ট হয়।", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "কন্টেইনার বন্ধ না করেই VM ডিস্কের অব্যবহৃত ব্লক {os}-কে ফিরিয়ে দেয়।", + "Cleaning up stopped containers, untagged images, and build cache…": "থেমে থাকা কন্টেইনার, ট্যাগহীন ইমেজ ও বিল্ড ক্যাশ পরিষ্কার করা হচ্ছে…", + "{count} ({size})": "{count} ({size})", + "build cache": "বিল্ড ক্যাশ", + "No stopped containers, untagged images or build cache · {freed}.": "কোনো থেমে থাকা কন্টেইনার, ট্যাগহীন ইমেজ বা বিল্ড ক্যাশ নেই · {freed}।", + "No stopped containers, untagged images or build cache.": "কোনো থেমে থাকা কন্টেইনার, ট্যাগহীন ইমেজ বা বিল্ড ক্যাশ নেই।", + "Cleaning up…": "পরিষ্কার হচ্ছে…", + "Clean up…": "পরিষ্কার করুন…", + "Unused Docker data": "অব্যবহৃত Docker ডেটা", + "Command-line tools in shell": "শেলে কমান্ড-লাইন টুল", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{zshrc} ও {zprofile}-এ {bin} যোগ করুন যাতে নতুন টার্মিনালে {docker}, {kubectl} ও {kiri} কাজ করে।", + "Uninstall Kiri": "Kiri আনইনস্টল করুন", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "ইঞ্জিন থামায়, Kiri-র ব্যাকগ্রাউন্ড সার্ভিস, CLI লিংক ও শেল প্রোফাইল এন্ট্রি সরায় এবং আপনার আগের Docker কনটেক্সট ফিরিয়ে আনে ({cmd})।", + "Uninstall Kiri…": "Kiri আনইনস্টল করুন…", + "Couldn't reclaim disk space: {error}": "ডিস্কের জায়গা ফেরত নেওয়া যায়নি: {error}", + "Reclaimed {size} on {os}": "{os}-এ {size} পুনরুদ্ধার হয়েছে", + "Nothing to reclaim": "ফেরত নেওয়ার কিছু নেই", + "Couldn't clean up unused Docker data: {error}": "অব্যবহৃত Docker ডেটা পরিষ্কার করা যায়নি: {error}", + "Cleaned up {size} of unused Docker data": "{size} অব্যবহৃত Docker ডেটা পরিষ্কার করা হয়েছে", + "Cleaned up unused Docker data": "অব্যবহৃত Docker ডেটা পরিষ্কার করা হয়েছে", + "Compact WSL disk?": "WSL ডিস্ক কমপ্যাক্ট করবেন?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} কমপ্যাক্ট করলে অব্যবহৃত জায়গা Windows-কে ফিরিয়ে দেওয়া হয় এবং অল্প সময়ের জন্য Kiri-র ইঞ্জিন ও চলমান কন্টেইনারগুলো রিস্টার্ট হয়।", + "Compact disk": "ডিস্ক কমপ্যাক্ট করুন", + "Clean up unused Docker data?": "অব্যবহৃত Docker ডেটা পরিষ্কার করবেন?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "থেমে থাকা কন্টেইনার, ট্যাগহীন ইমেজ এবং BuildKit-এর বিল্ড ক্যাশ সরিয়ে দেয়। চলমান কন্টেইনার ও ট্যাগযুক্ত ইমেজ থেকে যায়।", + "Clean up": "পরিষ্কার করুন", + "Uninstall Kiri?": "Kiri আনইনস্টল করবেন?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "ইঞ্জিন থামায়, Kiri-র ব্যাকগ্রাউন্ড সার্ভিস, CLI লিংক ও শেল প্রোফাইল এন্ট্রি সরায় এবং আপনার আগের Docker কনটেক্সট ফিরিয়ে আনে। আপনি না মোছা পর্যন্ত আপনার ইমেজ ও ভলিউমগুলো Kiri-র ডেটা ফোল্ডারে থেকে যায়।", + "Cluster": "ক্লাস্টার", + "default": "ডিফল্ট", + "k3s version": "k3s সংস্করণ", + "Image version for the cluster node ({cmd}). Applies when recreated.": "ক্লাস্টার নোডের ইমেজ সংস্করণ ({cmd})। নতুন করে তৈরি করলে প্রয়োগ হয়।", + "Extra server flags": "অতিরিক্ত সার্ভার ফ্ল্যাগ", + "Passed to {srv} ({flag}), separated by spaces.": "স্পেস দিয়ে আলাদা করে {srv} ({flag})-এ পাঠানো হয়।", + "Startup manifests": "স্টার্টআপ ম্যানিফেস্ট", + "YAML files in {path} are applied whenever the cluster starts.": "ক্লাস্টার প্রতিবার চালু হলে {path}-এ থাকা YAML ফাইলগুলো প্রয়োগ হয়।", + "Open folder": "ফোল্ডার খুলুন", + "{n} untagged image": "{n}টি ট্যাগহীন ইমেজ", + "{n} untagged images": "{n}টি ট্যাগহীন ইমেজ", + "Uninstall Kiri from Windows Settings → Apps": "Windows সেটিংস → অ্যাপস থেকে Kiri আনইনস্টল করুন", + "Builder settings saved": "বিল্ডার সেটিংস সেভ হয়েছে", + "Could not save builder settings: {error}": "বিল্ডার সেটিংস সেভ করা যায়নি: {error}", + "Disk reclaim is already running": "ডিস্কের জায়গা পুনরুদ্ধার ইতিমধ্যেই চলছে", + "Outbound VM traffic setting saved. Restart the VM to apply.": "বহির্গামী VM ট্রাফিক সেটিং সেভ হয়েছে। প্রয়োগ করতে VM রিস্টার্ট করুন।", + "Could not save VM networking setting: {error}": "VM নেটওয়ার্ক সেটিং সেভ করা যায়নি: {error}", + "Added Kiri command-line tools to shell profiles": "শেল প্রোফাইলে Kiri কমান্ড-লাইন টুল যোগ করা হয়েছে", + "Removed Kiri command-line tools from shell profiles": "শেল প্রোফাইল থেকে Kiri কমান্ড-লাইন টুল সরানো হয়েছে", + "Could not update shell profiles: {error}": "শেল প্রোফাইল আপডেট করা যায়নি: {error}", + "Uninstalling Kiri…": "Kiri আনইনস্টল হচ্ছে…", + "Could not uninstall Kiri: {error}": "Kiri আনইনস্টল করা যায়নি: {error}", + "Uninstall Kiri using your system package manager": "আপনার সিস্টেমের প্যাকেজ ম্যানেজার দিয়ে Kiri আনইনস্টল করুন" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 31c1795f6..34cb18bea 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -1854,7 +1854,6 @@ "Disk image size": "Mida de la imatge de disc", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB estan definits per al dimoni i tenen prioritat sobre aquests valors.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ara s'executa amb {cpus}, fins a {mem} i un disc de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades; no s'encongeix mai. S'aplica en reiniciar.", "No other WSL distros installed.": "No hi ha cap altra distribució de WSL instal·lada.", "WSL integration": "Integració amb WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tanca: s’allibera la memòria que fa servir la finestra. Tarda un moment a tornar-se a obrir, i els terminals oberts es tanquen.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri i aquest PC", "Kiri and this computer": "Kiri i aquest ordinador", "Versions, {os}, whether the engine runs, how many containers and images": "Versions, {os}, si el motor s'executa, quants contenidors i imatges", - "Saved. The engine uses these from its next start": "Desat. El motor els fa servir a partir del proper inici" + "Saved. The engine uses these from its next start": "Desat. El motor els fa servir a partir del proper inici", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Mai", + "Build cache limit": "Límit de la memòria cau de build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Les capes en memòria cau més antigues es netegen automàticament quan la cau de BuildKit supera aquesta mida.", + "Stop builder when idle": "Atura el builder quan estigui inactiu", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Atura BuildKit entre builds perquè no consumeixi memòria quan està inactiu; el següent build el desperta en menys d'un segon.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB o KIRI_BUILDER_IDLE_SECS estan definits per al dimoni i tenen prioritat sobre aquests valors.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT de macOS: el més ràpid. Canvia a Relé de l'amfitrió si Cloudflare WARP o un tallafoc corporatiu bloqueja l'HTTPS dels contenidors. S'aplica en reiniciar la VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relé de l'amfitrió: les connexions surten de Kiri a macOS en lloc del NAT de Virtualization.framework. S'aplica en reiniciar la VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT està definit a l'entorn i té prioritat.", + "Outbound VM traffic": "Trànsit de sortida de la VM", + "macOS NAT": "NAT de macOS", + "Host relay": "Relé de l'amfitrió", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "El màxim que pot créixer el disc de la VM. Només ocupa espai a {os} a mesura que s'escriuen dades, i l'espai sense ús es pot recuperar a {storage}. S'aplica en reiniciar.", + "Settings → Storage": "Configuració → Emmagatzematge", + "VM disk space": "Espai de disc de la VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux natiu fa servir directament el sistema de fitxers de l'amfitrió — les imatges i els volums suprimits alliberen espai immediatament.", + "Compact disk…": "Compacta el disc…", + "Reclaim space": "Recupera espai", + "Compacting…": "S'està compactant…", + "Reclaiming…": "S'està recuperant…", + "Compacting {vhdx} and restarting the engine…": "S'està compactant {vhdx} i reiniciant el motor…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} a {os}, {inUse} en ús dins la VM · s'estan retallant els blocs sense ús…", + "Trimming unused blocks inside the VM disk…": "S'estan retallant els blocs sense ús dins el disc de la VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} a Windows ({vhdx}), {inUse} en ús · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} a {os}, {inUse} en ús dins la VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} a Windows ({vhdx}), {inUse} en ús · res per recuperar.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} a {os}, {inUse} en ús dins la VM · res per recuperar.", + "Nothing to reclaim.": "Res per recuperar.", + "{size} can be given back": "es poden recuperar {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} a Windows ({vhdx}), {inUse} en ús · {can}. Compactar reinicia el motor.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} a {os}, {inUse} en ús dins la VM · {can} sense aturar els contenidors.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} a Windows ({vhdx}). Compactar retorna l'espai sense ús i reinicia el motor.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} a {os}. Recuperar retalla els blocs sense ús del disc de la VM sense aturar els contenidors.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Retorna l'espai sense ús de {vhdx} a Windows. Compactar reinicia el motor.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Retorna els blocs sense ús del disc de la VM a {os} sense aturar els contenidors.", + "Cleaning up stopped containers, untagged images, and build cache…": "S'estan netejant els contenidors aturats, les imatges sense etiqueta i la memòria cau de build…", + "{count} ({size})": "{count} ({size})", + "build cache": "memòria cau de build", + "No stopped containers, untagged images or build cache · {freed}.": "Cap contenidor aturat, imatge sense etiqueta ni memòria cau de build · {freed}.", + "No stopped containers, untagged images or build cache.": "Cap contenidor aturat, imatge sense etiqueta ni memòria cau de build.", + "Cleaning up…": "S'està netejant…", + "Clean up…": "Neteja…", + "Unused Docker data": "Dades de Docker sense ús", + "Command-line tools in shell": "Eines de línia d'ordres a l'intèrpret", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Afegeix {bin} a {zshrc} i {zprofile} perquè {docker}, {kubectl} i {kiri} funcionin als terminals nous.", + "Uninstall Kiri": "Desinstal·la Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Atura el motor, elimina el servei en segon pla de Kiri, els enllaços de CLI i les entrades dels perfils de l'intèrpret, i restaura el context de Docker anterior ({cmd}).", + "Uninstall Kiri…": "Desinstal·la Kiri…", + "Couldn't reclaim disk space: {error}": "No s'ha pogut recuperar espai de disc: {error}", + "Reclaimed {size} on {os}": "S'han recuperat {size} a {os}", + "Nothing to reclaim": "Res per recuperar", + "Couldn't clean up unused Docker data: {error}": "No s'han pogut netejar les dades de Docker sense ús: {error}", + "Cleaned up {size} of unused Docker data": "S'han netejat {size} de dades de Docker sense ús", + "Cleaned up unused Docker data": "S'han netejat les dades de Docker sense ús", + "Compact WSL disk?": "Vols compactar el disc de WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Compactar {vhdx} retorna l'espai sense ús a Windows i reinicia breument el motor de Kiri i els contenidors en execució.", + "Compact disk": "Compacta el disc", + "Clean up unused Docker data?": "Vols netejar les dades de Docker sense ús?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Elimina els contenidors aturats, les imatges sense etiqueta i la memòria cau de build de BuildKit. Es conserven els contenidors en execució i les imatges amb etiqueta.", + "Clean up": "Neteja", + "Uninstall Kiri?": "Vols desinstal·lar Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Atura el motor, elimina el servei en segon pla de Kiri, els enllaços de CLI i les entrades dels perfils de l'intèrpret, i restaura el context de Docker anterior. Les imatges i els volums es queden a la carpeta de dades de Kiri fins que la suprimeixis.", + "Cluster": "Clúster", + "default": "per defecte", + "k3s version": "Versió de k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versió de la imatge per al node del clúster ({cmd}). S'aplica en tornar-lo a crear.", + "Extra server flags": "Paràmetres addicionals del servidor", + "Passed to {srv} ({flag}), separated by spaces.": "Es passen a {srv} ({flag}), separats per espais.", + "Startup manifests": "Manifestos d'inici", + "YAML files in {path} are applied whenever the cluster starts.": "Els fitxers YAML de {path} s'apliquen cada vegada que s'inicia el clúster.", + "Open folder": "Obre la carpeta", + "{n} untagged image": "{n} imatge sense etiqueta", + "{n} untagged images": "{n} imatges sense etiqueta", + "Uninstall Kiri from Windows Settings → Apps": "Desinstal·la Kiri des de Configuració de Windows → Aplicacions", + "Builder settings saved": "S'ha desat la configuració del builder", + "Could not save builder settings: {error}": "No s'ha pogut desar la configuració del builder: {error}", + "Disk reclaim is already running": "La recuperació d'espai de disc ja s'està executant", + "Outbound VM traffic setting saved. Restart the VM to apply.": "S'ha desat la configuració del trànsit de sortida de la VM. Reinicia la VM per aplicar-ho.", + "Could not save VM networking setting: {error}": "No s'ha pogut desar la configuració de xarxa de la VM: {error}", + "Added Kiri command-line tools to shell profiles": "S'han afegit les eines de línia d'ordres de Kiri als perfils de l'intèrpret", + "Removed Kiri command-line tools from shell profiles": "S'han eliminat les eines de línia d'ordres de Kiri dels perfils de l'intèrpret", + "Could not update shell profiles: {error}": "No s'han pogut actualitzar els perfils de l'intèrpret: {error}", + "Uninstalling Kiri…": "S'està desinstal·lant Kiri…", + "Could not uninstall Kiri: {error}": "No s'ha pogut desinstal·lar Kiri: {error}", + "Uninstall Kiri using your system package manager": "Desinstal·la Kiri amb el gestor de paquets del sistema" } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index 96180800f..abcc03323 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -1854,7 +1854,6 @@ "Disk image size": "قەبارەی وێنەی دیسک", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یان KIRI_DISK_GB بۆ daemon دانراوە، و لەسەر ئەمانە پێشەنگی هەیە.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ئێستا بە {cpus}، تا {mem} و دیسکی {disk} کاردەکات.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت؛ هەرگیز بچووک نابێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت.", "No other WSL distros installed.": "هیچ دابەشکراوێکی دیکەی WSL دانەمەزراوە.", "WSL integration": "ئاوێتەکردنی WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "داخستن: ئەو بیرگەیەی پەنجەرەکە بەکاری دەهێنێت ئازاد دەکرێت. کردنەوەی دووبارەی کەمێک کات دەبات، و تێرمیناڵە کراوەکان کۆتاییان دێت.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri و ئەم کۆمپیوتەرە", "Kiri and this computer": "Kiri و ئەم کۆمپیوتەرە", "Versions, {os}, whether the engine runs, how many containers and images": "وەشانەکان، {os}، ئایا بزوێنەر کاردەکات، چەند کۆنتەینەر و ئیمەیج", - "Saved. The engine uses these from its next start": "پاشەکەوت کرا. بزوێنەر لە دەستپێکردنی داهاتوویەوە بەکاریان دەهێنێت" + "Saved. The engine uses these from its next start": "پاشەکەوت کرا. بزوێنەر لە دەستپێکردنی داهاتوویەوە بەکاریان دەهێنێت", + "5 min": "5 خولەک", + "10 min": "10 خولەک", + "30 min": "30 خولەک", + "Never": "هەرگیز", + "Build cache limit": "سنووری کاشی دروستکردن", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "کۆنترین چینە کاشکراوەکان خۆکارانە پاک دەکرێنەوە کاتێک کاشی BuildKit لەم قەبارەیە تێدەپەڕێت.", + "Stop builder when idle": "وەستاندنی دروستکەر لە کاتی بێکاریدا", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "لە نێوان دروستکردنەکاندا BuildKit دەوەستێنێت بۆ ئەوەی لە کاتی بێکاریدا هیچ بیرگەیەک بەکارنەهێنێت؛ دروستکردنی داهاتوو لە کەمتر لە چرکەیەکدا بەخەبەری دەهێنێتەوە.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB یان KIRI_BUILDER_IDLE_SECS بۆ daemon دانراوە، و لەسەر ئەمانە پێشەنگی هەیە.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: خێراترین. بیگۆڕە بۆ گەیاندنی خانەخوێ ئەگەر Cloudflare WARP یان دیواری ئاگرینی دامەزراوەیی ڕێگری لە HTTPS ی کۆنتەینەر بکات. لە کاتی دەستپێکردنەوەی VM جێبەجێ دەبێت.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "گەیاندنی خانەخوێ: پەیوەندییەکان لە Kiri لەسەر macOS دەردەچن لەبری Virtualization.framework NAT. لە کاتی دەستپێکردنەوەی VM جێبەجێ دەبێت.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT لە ژینگەکەدا دانراوە و پێشەنگی هەیە.", + "Outbound VM traffic": "ترافیکی دەرچووی VM", + "macOS NAT": "macOS NAT", + "Host relay": "گەیاندنی خانەخوێ", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "زۆرترین قەبارە کە دیسکی VM دەتوانێت بۆی گەورە ببێت. تەنها کاتێک داتا دەنووسرێت جێگا لەسەر {os} بەکاردەهێنێت، و جێگای بەکارنەهاتوو دەتوانرێت لە {storage} وەربگیرێتەوە. لە کاتی دەستپێکردنەوەدا جێبەجێ دەبێت.", + "Settings → Storage": "ڕێکخستنەکان ← کۆگاکردن", + "VM disk space": "جێگای دیسکی VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux ی ڕەسەن ڕاستەوخۆ سیستەمی پەڕگەی خانەخوێکەت بەکاردەهێنێت — ئیمەیج و ڤۆلیوومە سڕاوەکان دەستبەجێ جێگا ئازاد دەکەن.", + "Compact disk…": "پەستاندنی دیسک…", + "Reclaim space": "وەرگرتنەوەی جێگا", + "Compacting…": "پەستاندن…", + "Reclaiming…": "وەرگرتنەوە…", + "Compacting {vhdx} and restarting the engine…": "پەستاندنی {vhdx} و دەستپێکردنەوەی بزوێنەرەکە…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} لەسەر {os}، {inUse} لە ناو VM لە بەکارهێناندایە · بڕینی بلۆکە بەکارنەهاتووەکان…", + "Trimming unused blocks inside the VM disk…": "بڕینی بلۆکە بەکارنەهاتووەکان لە ناو دیسکی VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} لەسەر Windows ({vhdx})، {inUse} لە بەکارهێناندایە · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} لەسەر {os}، {inUse} لە ناو VM لە بەکارهێناندایە · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} لەسەر Windows ({vhdx})، {inUse} لە بەکارهێناندایە · هیچ شتێک نییە بۆ وەرگرتنەوە.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} لەسەر {os}، {inUse} لە ناو VM لە بەکارهێناندایە · هیچ شتێک نییە بۆ وەرگرتنەوە.", + "Nothing to reclaim.": "هیچ شتێک نییە بۆ وەرگرتنەوە.", + "{size} can be given back": "دەکرێت {size} بگەڕێنرێتەوە", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} لەسەر Windows ({vhdx})، {inUse} لە بەکارهێناندایە · {can}. پەستاندن بزوێنەرەکە دەستپێدەکاتەوە.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} لەسەر {os}، {inUse} لە ناو VM لە بەکارهێناندایە · بەبێ وەستاندنی کۆنتەینەرەکان {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} لەسەر Windows ({vhdx}). پەستاندن جێگای بەکارنەهاتوو دەگەڕێنێتەوە و بزوێنەرەکە دەستپێدەکاتەوە.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} لەسەر {os}. وەرگرتنەوە بەبێ وەستاندنی کۆنتەینەرەکان بلۆکە بەکارنەهاتووەکانی ناو دیسکی VM دەبڕێت.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "جێگای بەکارنەهاتووی ناو {vhdx} دەگەڕێنێتەوە بۆ Windows. پەستاندن بزوێنەرەکە دەستپێدەکاتەوە.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "بەبێ وەستاندنی کۆنتەینەرەکان بلۆکە بەکارنەهاتووەکانی دیسکی VM دەگەڕێنێتەوە بۆ {os}.", + "Cleaning up stopped containers, untagged images, and build cache…": "پاککردنەوەی کۆنتەینەرە وەستاوەکان، ئیمەیجە بێتاگەکان، و کاشی دروستکردن…", + "{count} ({size})": "{count} ({size})", + "build cache": "کاشی دروستکردن", + "No stopped containers, untagged images or build cache · {freed}.": "هیچ کۆنتەینەرێکی وەستاو، ئیمەیجێکی بێتاگ یان کاشی دروستکردن نییە · {freed}.", + "No stopped containers, untagged images or build cache.": "هیچ کۆنتەینەرێکی وەستاو، ئیمەیجێکی بێتاگ یان کاشی دروستکردن نییە.", + "Cleaning up…": "پاککردنەوە…", + "Clean up…": "پاککردنەوە…", + "Unused Docker data": "داتای بەکارنەهاتووی Docker", + "Command-line tools in shell": "ئامرازەکانی هێڵی فەرمان لە شێڵدا", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{bin} زیاد بکە بۆ {zshrc} و {zprofile} بۆ ئەوەی {docker}، {kubectl} و {kiri} لە تێرمیناڵە نوێیەکاندا کار بکەن.", + "Uninstall Kiri": "سڕینەوەی Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "بزوێنەرەکە دەوەستێنێت، ڕاژەی پاشبنەمای Kiri، بەستەرەکانی CLI و تۆمارەکانی پرۆفایلی شێڵ لادەبات، و کۆنتێکستی پێشووی Docker دەگەڕێنێتەوە ({cmd}).", + "Uninstall Kiri…": "سڕینەوەی Kiri…", + "Couldn't reclaim disk space: {error}": "نەتوانرا جێگای دیسک وەربگیرێتەوە: {error}", + "Reclaimed {size} on {os}": "{size} لەسەر {os} وەرگیرایەوە", + "Nothing to reclaim": "هیچ شتێک نییە بۆ وەرگرتنەوە", + "Couldn't clean up unused Docker data: {error}": "نەتوانرا داتای بەکارنەهاتووی Docker پاک بکرێتەوە: {error}", + "Cleaned up {size} of unused Docker data": "{size} لە داتای بەکارنەهاتووی Docker پاککرایەوە", + "Cleaned up unused Docker data": "داتای بەکارنەهاتووی Docker پاککرایەوە", + "Compact WSL disk?": "پەستاندنی دیسکی WSL؟", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "پەستاندنی {vhdx} جێگای بەکارنەهاتوو دەگەڕێنێتەوە بۆ Windows و بۆ ماوەیەکی کورت بزوێنەری Kiri و کۆنتەینەرە کاراکان دەستپێدەکاتەوە.", + "Compact disk": "پەستاندنی دیسک", + "Clean up unused Docker data?": "پاککردنەوەی داتای بەکارنەهاتووی Docker؟", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "کۆنتەینەرە وەستاوەکان، ئیمەیجە بێتاگەکان، و کاشی دروستکردنی BuildKit لادەبات. کۆنتەینەرە کاراکان و ئیمەیجە تاگدارەکان دەمێننەوە.", + "Clean up": "پاککردنەوە", + "Uninstall Kiri?": "سڕینەوەی Kiri؟", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "بزوێنەرەکە دەوەستێنێت، ڕاژەی پاشبنەمای Kiri، بەستەرەکانی CLI و تۆمارەکانی پرۆفایلی شێڵ لادەبات، و کۆنتێکستی پێشووی Docker دەگەڕێنێتەوە. ئیمەیج و ڤۆلیوومەکانت لە بوخچەی داتای Kiri دەمێننەوە هەتا خۆت دەیسڕیتەوە.", + "Cluster": "کلەستەر", + "default": "بنەڕەتی", + "k3s version": "وەشانی k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "وەشانی ئیمەیج بۆ گرێی کلەستەرەکە ({cmd}). لە کاتی دروستکردنەوەدا جێبەجێ دەبێت.", + "Extra server flags": "ئاڵا زیادەکانی ڕاژەکار", + "Passed to {srv} ({flag}), separated by spaces.": "دەنێردرێت بۆ {srv} ({flag})، بە بۆشایی جیاکراوەتەوە.", + "Startup manifests": "مانیفێستەکانی دەستپێکردن", + "YAML files in {path} are applied whenever the cluster starts.": "پەڕگەکانی YAML لە {path} هەر کاتێک کلەستەرەکە دەستپێبکات جێبەجێ دەکرێن.", + "Open folder": "کردنەوەی بوخچە", + "{n} untagged image": "{n} ئیمەیجی بێتاگ", + "{n} untagged images": "{n} ئیمەیجی بێتاگ", + "Uninstall Kiri from Windows Settings → Apps": "Kiri لە ڕێکخستنەکانی Windows ← ئەپەکان بسڕەوە", + "Builder settings saved": "ڕێکخستنەکانی دروستکەر پاشەکەوت کران", + "Could not save builder settings: {error}": "نەتوانرا ڕێکخستنەکانی دروستکەر پاشەکەوت بکرێن: {error}", + "Disk reclaim is already running": "وەرگرتنەوەی جێگای دیسک پێشتر لە کاردایە", + "Outbound VM traffic setting saved. Restart the VM to apply.": "ڕێکخستنی ترافیکی دەرچووی VM پاشەکەوت کرا. بۆ جێبەجێکردن VM دەستپێبکەرەوە.", + "Could not save VM networking setting: {error}": "نەتوانرا ڕێکخستنی تۆڕی VM پاشەکەوت بکرێت: {error}", + "Added Kiri command-line tools to shell profiles": "ئامرازەکانی هێڵی فەرمانی Kiri زیادکران بۆ پرۆفایلەکانی شێڵ", + "Removed Kiri command-line tools from shell profiles": "ئامرازەکانی هێڵی فەرمانی Kiri لە پرۆفایلەکانی شێڵ لابران", + "Could not update shell profiles: {error}": "نەتوانرا پرۆفایلەکانی شێڵ نوێ بکرێنەوە: {error}", + "Uninstalling Kiri…": "سڕینەوەی Kiri…", + "Could not uninstall Kiri: {error}": "نەتوانرا Kiri بسڕدرێتەوە: {error}", + "Uninstall Kiri using your system package manager": "Kiri بە بەڕێوەبەری پاکێجی سیستەمەکەت بسڕەوە" } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index 14275e25c..6dfd5f055 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -1854,7 +1854,6 @@ "Disk image size": "Velikost obrazu disku", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Pro démona je nastaveno KIRI_CPUS, KIRI_MEMORY_MIB nebo KIRI_DISK_GB a to má přednost před těmito hodnotami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Teď běží s {cpus}, až {mem} a diskem {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat; nikdy se nezmenšuje. Použije se po restartu.", "No other WSL distros installed.": "Nejsou nainstalovány žádné další distribuce WSL.", "WSL integration": "Integrace s WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zavřít: paměť, kterou okno používá, se uvolní. Znovu se otevře až po chvilce a otevřené terminály se ukončí.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri a toto PC", "Kiri and this computer": "Kiri a tento počítač", "Versions, {os}, whether the engine runs, how many containers and images": "Verze, {os}, zda běží engine, kolik je kontejnerů a obrazů", - "Saved. The engine uses these from its next start": "Uloženo. Engine je použije od příštího spuštění" + "Saved. The engine uses these from its next start": "Uloženo. Engine je použije od příštího spuštění", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nikdy", + "Build cache limit": "Limit mezipaměti sestavení", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Nejstarší vrstvy v mezipaměti se automaticky promažou, jakmile mezipaměť BuildKitu překročí tuto velikost.", + "Stop builder when idle": "Zastavit builder při nečinnosti", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Mezi sestaveními BuildKit zastaví, takže při nečinnosti nezabírá žádnou paměť; další sestavení ho probudí za méně než sekundu.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Pro démona je nastaveno KIRI_BUILD_CACHE_GB nebo KIRI_BUILDER_IDLE_SECS a to má přednost před těmito hodnotami.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: nejrychlejší. Přepněte na Přes hostitele, pokud Cloudflare WARP nebo firemní firewall blokuje HTTPS kontejnerů. Projeví se po restartu VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Přes hostitele: spojení odcházejí z Kiri v macOS místo přes NAT Virtualization.framework. Projeví se po restartu VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "V prostředí je nastaveno KIRI_SHARED_NAT a má přednost.", + "Outbound VM traffic": "Odchozí provoz VM", + "macOS NAT": "macOS NAT", + "Host relay": "Přes hostitele", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Nejvíc, na kolik může disk virtuálního počítače vyrůst. Místo v systému {os} zabírá až při zápisu dat a nevyužité místo lze uvolnit v {storage}. Použije se po restartu.", + "Settings → Storage": "Nastavení → Úložiště", + "VM disk space": "Místo na disku VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Nativní Linux používá přímo souborový systém hostitele — smazané obrazy a svazky uvolní místo okamžitě.", + "Compact disk…": "Zkomprimovat disk…", + "Reclaim space": "Uvolnit místo", + "Compacting…": "Komprimace…", + "Reclaiming…": "Uvolňování…", + "Compacting {vhdx} and restarting the engine…": "Komprimace {vhdx} a restartování enginu…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} v systému {os}, ve VM využito {inUse} · ořezávání nevyužitých bloků…", + "Trimming unused blocks inside the VM disk…": "Ořezávání nevyužitých bloků na disku VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} ve Windows ({vhdx}), využito {inUse} · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} v systému {os}, ve VM využito {inUse} · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} ve Windows ({vhdx}), využito {inUse} · není co uvolnit.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} v systému {os}, ve VM využito {inUse} · není co uvolnit.", + "Nothing to reclaim.": "Není co uvolnit.", + "{size} can be given back": "{size} lze vrátit", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} ve Windows ({vhdx}), využito {inUse} · {can}. Komprimace restartuje engine.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} v systému {os}, ve VM využito {inUse} · {can} bez zastavení kontejnerů.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} ve Windows ({vhdx}). Komprimace vrátí nevyužité místo a restartuje engine.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} v systému {os}. Uvolnění ořízne nevyužité bloky na disku VM bez zastavení kontejnerů.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Vrátí nevyužité místo v {vhdx} systému Windows. Komprimace restartuje engine.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Vrátí nevyužité bloky na disku VM systému {os} bez zastavení kontejnerů.", + "Cleaning up stopped containers, untagged images, and build cache…": "Čištění zastavených kontejnerů, obrazů bez značky a mezipaměti sestavení…", + "{count} ({size})": "{count} ({size})", + "build cache": "mezipaměť sestavení", + "No stopped containers, untagged images or build cache · {freed}.": "Žádné zastavené kontejnery, obrazy bez značky ani mezipaměť sestavení · {freed}.", + "No stopped containers, untagged images or build cache.": "Žádné zastavené kontejnery, obrazy bez značky ani mezipaměť sestavení.", + "Cleaning up…": "Čištění…", + "Clean up…": "Vyčistit…", + "Unused Docker data": "Nepoužívaná data Dockeru", + "Command-line tools in shell": "Nástroje příkazové řádky v shellu", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Přidejte {bin} do {zshrc} a {zprofile}, aby {docker}, {kubectl} a {kiri} fungovaly v nových terminálech.", + "Uninstall Kiri": "Odinstalovat Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Zastaví engine, odebere službu Kiri na pozadí, odkazy CLI a záznamy v profilech shellu a obnoví předchozí kontext Dockeru ({cmd}).", + "Uninstall Kiri…": "Odinstalovat Kiri…", + "Couldn't reclaim disk space: {error}": "Místo na disku se nepodařilo uvolnit: {error}", + "Reclaimed {size} on {os}": "V systému {os} uvolněno {size}", + "Nothing to reclaim": "Není co uvolnit", + "Couldn't clean up unused Docker data: {error}": "Nepoužívaná data Dockeru se nepodařilo vyčistit: {error}", + "Cleaned up {size} of unused Docker data": "Vyčištěno {size} nepoužívaných dat Dockeru", + "Cleaned up unused Docker data": "Nepoužívaná data Dockeru vyčištěna", + "Compact WSL disk?": "Zkomprimovat disk WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Komprimace {vhdx} vrátí nevyužité místo systému Windows a krátce restartuje engine Kiri i běžící kontejnery.", + "Compact disk": "Zkomprimovat disk", + "Clean up unused Docker data?": "Vyčistit nepoužívaná data Dockeru?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Odebere zastavené kontejnery, obrazy bez značky a mezipaměť sestavení BuildKitu. Běžící kontejnery a označené obrazy zůstanou zachovány.", + "Clean up": "Vyčistit", + "Uninstall Kiri?": "Odinstalovat Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Zastaví engine, odebere službu Kiri na pozadí, odkazy CLI a záznamy v profilech shellu a obnoví předchozí kontext Dockeru. Vaše obrazy a svazky zůstanou ve složce dat Kiri, dokud ji nesmažete.", + "Cluster": "Cluster", + "default": "výchozí", + "k3s version": "Verze k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Verze obrazu pro uzel clusteru ({cmd}). Projeví se při novém vytvoření.", + "Extra server flags": "Další příznaky serveru", + "Passed to {srv} ({flag}), separated by spaces.": "Předávají se do {srv} ({flag}), oddělené mezerami.", + "Startup manifests": "Startovací manifesty", + "YAML files in {path} are applied whenever the cluster starts.": "Soubory YAML v {path} se použijí při každém spuštění clusteru.", + "Open folder": "Otevřít složku", + "{n} untagged image": "{n} obraz bez značky", + "{n} untagged images": "obrazy bez značky: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Odinstalujte Kiri v Nastavení Windows → Aplikace", + "Builder settings saved": "Nastavení builderu uloženo", + "Could not save builder settings: {error}": "Nastavení builderu se nepodařilo uložit: {error}", + "Disk reclaim is already running": "Uvolňování místa na disku už běží", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Nastavení odchozího provozu VM uloženo. Pro použití restartujte virtuální počítač.", + "Could not save VM networking setting: {error}": "Nastavení sítě VM se nepodařilo uložit: {error}", + "Added Kiri command-line tools to shell profiles": "Nástroje příkazové řádky Kiri přidány do profilů shellu", + "Removed Kiri command-line tools from shell profiles": "Nástroje příkazové řádky Kiri odebrány z profilů shellu", + "Could not update shell profiles: {error}": "Profily shellu se nepodařilo aktualizovat: {error}", + "Uninstalling Kiri…": "Odinstalovávání Kiri…", + "Could not uninstall Kiri: {error}": "Kiri se nepodařilo odinstalovat: {error}", + "Uninstall Kiri using your system package manager": "Odinstalujte Kiri pomocí správce balíčků vašeho systému" } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index 65dddc397..a9e47500c 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -1854,7 +1854,6 @@ "Disk image size": "Größe des Festplattenimages", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB oder KIRI_DISK_GB ist für den Daemon gesetzt und hat Vorrang vor diesen Werten.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Läuft jetzt mit {cpus}, bis zu {mem} und einer {disk}-Festplatte.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt; die Größe schrumpft nie. Gilt nach einem Neustart.", "No other WSL distros installed.": "Keine weiteren WSL-Distributionen installiert.", "WSL integration": "WSL-Integration", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Schließen: Der Speicher des Fensters wird freigegeben. Es braucht einen Moment, um wieder zu öffnen, und offene Terminals werden beendet.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri und dieser PC", "Kiri and this computer": "Kiri und dieser Computer", "Versions, {os}, whether the engine runs, how many containers and images": "Versionen, {os}, ob die Engine läuft, wie viele Container und Images", - "Saved. The engine uses these from its next start": "Gespeichert. Die Engine nutzt sie ab dem nächsten Start" + "Saved. The engine uses these from its next start": "Gespeichert. Die Engine nutzt sie ab dem nächsten Start", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nie", + "Build cache limit": "Build-Cache-Limit", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Die ältesten gecachten Layer werden automatisch bereinigt, sobald der Cache von BuildKit diese Größe überschreitet.", + "Stop builder when idle": "Builder bei Leerlauf stoppen", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Stoppt BuildKit zwischen Builds, damit es im Leerlauf keinen Speicher belegt; der nächste Build weckt es in unter einer Sekunde.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB oder KIRI_BUILDER_IDLE_SECS ist für den Daemon gesetzt und hat Vorrang vor diesen Werten.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: am schnellsten. Wechsle zu Host-Relay, wenn Cloudflare WARP oder eine Firmen-Firewall Container-HTTPS blockiert. Gilt nach VM-Neustart.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Host-Relay: Verbindungen gehen über Kiri auf macOS raus statt über das NAT von Virtualization.framework. Gilt nach VM-Neustart.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT ist in der Umgebung gesetzt und hat Vorrang.", + "Outbound VM traffic": "Ausgehender VM-Traffic", + "macOS NAT": "macOS NAT", + "Host relay": "Host-Relay", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Die maximale Größe der VM-Festplatte. Speicherplatz auf {os} wird erst beim Schreiben von Daten belegt, und ungenutzter Platz lässt sich unter {storage} zurückholen. Gilt nach einem Neustart.", + "Settings → Storage": "Einstellungen → Speicher", + "VM disk space": "VM-Festplattenplatz", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Natives Linux nutzt das Dateisystem des Hosts direkt — gelöschte Images und Volumes geben Speicherplatz sofort frei.", + "Compact disk…": "Komprimieren…", + "Reclaim space": "Freigeben", + "Compacting…": "Komprimiere…", + "Reclaiming…": "Gebe frei…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} wird komprimiert und die Engine neu gestartet…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} auf {os}, {inUse} in der VM belegt · ungenutzte Blöcke werden freigegeben…", + "Trimming unused blocks inside the VM disk…": "Ungenutzte Blöcke in der VM-Festplatte werden freigegeben…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} auf Windows ({vhdx}), {inUse} belegt · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} auf {os}, {inUse} in der VM belegt · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} auf Windows ({vhdx}), {inUse} belegt · nichts freizugeben.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} auf {os}, {inUse} in der VM belegt · nichts freizugeben.", + "Nothing to reclaim.": "Nichts freizugeben.", + "{size} can be given back": "{size} können zurückgegeben werden", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} auf Windows ({vhdx}), {inUse} belegt · {can}. Komprimieren startet die Engine neu.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} auf {os}, {inUse} in der VM belegt · {can}, ohne Container zu stoppen.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} auf Windows ({vhdx}). Komprimieren gibt ungenutzten Platz zurück und startet die Engine neu.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} auf {os}. Freigeben gibt ungenutzte Blöcke in der VM-Festplatte zurück, ohne Container zu stoppen.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Gibt ungenutzten Speicherplatz in {vhdx} an Windows zurück. Komprimieren startet die Engine neu.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Gibt ungenutzte Blöcke der VM-Festplatte an {os} zurück, ohne Container zu stoppen.", + "Cleaning up stopped containers, untagged images, and build cache…": "Gestoppte Container, Images ohne Tag und Build-Cache werden bereinigt…", + "{count} ({size})": "{count} ({size})", + "build cache": "Build-Cache", + "No stopped containers, untagged images or build cache · {freed}.": "Keine gestoppten Container, Images ohne Tag oder Build-Cache · {freed}.", + "No stopped containers, untagged images or build cache.": "Keine gestoppten Container, Images ohne Tag oder Build-Cache.", + "Cleaning up…": "Bereinige…", + "Clean up…": "Bereinigen…", + "Unused Docker data": "Unbenutzte Docker-Daten", + "Command-line tools in shell": "Befehlszeilentools in der Shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Füge {bin} zu {zshrc} und {zprofile} hinzu, damit {docker}, {kubectl} und {kiri} in neuen Terminals funktionieren.", + "Uninstall Kiri": "Kiri deinstallieren", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Stoppt die Engine, entfernt Kiris Hintergrunddienst, CLI-Links und Einträge in Shell-Profilen und stellt deinen vorherigen Docker-Kontext wieder her ({cmd}).", + "Uninstall Kiri…": "Kiri deinstallieren…", + "Couldn't reclaim disk space: {error}": "Speicherplatz konnte nicht freigegeben werden: {error}", + "Reclaimed {size} on {os}": "{size} auf {os} freigegeben", + "Nothing to reclaim": "Nichts freizugeben", + "Couldn't clean up unused Docker data: {error}": "Unbenutzte Docker-Daten konnten nicht bereinigt werden: {error}", + "Cleaned up {size} of unused Docker data": "{size} an unbenutzten Docker-Daten bereinigt", + "Cleaned up unused Docker data": "Unbenutzte Docker-Daten bereinigt", + "Compact WSL disk?": "WSL-Festplatte komprimieren?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Das Komprimieren von {vhdx} gibt ungenutzten Speicherplatz an Windows zurück und startet Kiris Engine sowie laufende Container kurz neu.", + "Compact disk": "Festplatte komprimieren", + "Clean up unused Docker data?": "Unbenutzte Docker-Daten bereinigen?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Entfernt gestoppte Container, Images ohne Tag und den Build-Cache von BuildKit. Laufende Container und Images mit Tag bleiben erhalten.", + "Clean up": "Bereinigen", + "Uninstall Kiri?": "Kiri deinstallieren?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Stoppt die Engine, entfernt Kiris Hintergrunddienst, CLI-Links und Einträge in Shell-Profilen und stellt deinen vorherigen Docker-Kontext wieder her. Deine Images und Volumes bleiben im Datenordner von Kiri, bis du ihn löschst.", + "Cluster": "Cluster", + "default": "Standard", + "k3s version": "k3s-Version", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Image-Version für den Cluster-Knoten ({cmd}). Gilt beim Neuerstellen.", + "Extra server flags": "Zusätzliche Server-Flags", + "Passed to {srv} ({flag}), separated by spaces.": "Werden durch Leerzeichen getrennt an {srv} ({flag}) übergeben.", + "Startup manifests": "Start-Manifeste", + "YAML files in {path} are applied whenever the cluster starts.": "YAML-Dateien in {path} werden bei jedem Start des Clusters angewendet.", + "Open folder": "Ordner öffnen", + "{n} untagged image": "{n} Image ohne Tag", + "{n} untagged images": "{n} Images ohne Tag", + "Uninstall Kiri from Windows Settings → Apps": "Kiri über Windows-Einstellungen → Apps deinstallieren", + "Builder settings saved": "Builder-Einstellungen gespeichert", + "Could not save builder settings: {error}": "Builder-Einstellungen konnten nicht gespeichert werden: {error}", + "Disk reclaim is already running": "Speicherfreigabe läuft bereits", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Einstellung für ausgehenden VM-Traffic gespeichert. VM neu starten zum Übernehmen.", + "Could not save VM networking setting: {error}": "VM-Netzwerkeinstellung konnte nicht gespeichert werden: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri-Befehlszeilentools zu Shell-Profilen hinzugefügt", + "Removed Kiri command-line tools from shell profiles": "Kiri-Befehlszeilentools aus Shell-Profilen entfernt", + "Could not update shell profiles: {error}": "Shell-Profile konnten nicht aktualisiert werden: {error}", + "Uninstalling Kiri…": "Kiri wird deinstalliert…", + "Could not uninstall Kiri: {error}": "Kiri konnte nicht deinstalliert werden: {error}", + "Uninstall Kiri using your system package manager": "Deinstalliere Kiri über die Paketverwaltung deines Systems" } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 184d47076..7460781a6 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -1854,7 +1854,6 @@ "Disk image size": "Μέγεθος εικόνας δίσκου", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Το KIRI_CPUS, το KIRI_MEMORY_MIB ή το KIRI_DISK_GB έχει οριστεί για τον daemon και υπερισχύει αυτών.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Εκτελείται τώρα με {cpus}, έως {mem} και δίσκο {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα και δεν μικραίνει ποτέ. Εφαρμόζεται κατά την επανεκκίνηση.", "No other WSL distros installed.": "Δεν υπάρχουν άλλες εγκατεστημένες διανομές WSL.", "WSL integration": "Ενσωμάτωση WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Κλείσιμο: η μνήμη που χρησιμοποιεί το παράθυρο ελευθερώνεται. Χρειάζεται μια στιγμή για να ανοίξει ξανά, και τα ανοιχτά τερματικά τερματίζονται.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Το Kiri και αυτό το PC", "Kiri and this computer": "Το Kiri και αυτός ο υπολογιστής", "Versions, {os}, whether the engine runs, how many containers and images": "Εκδόσεις, {os}, αν εκτελείται η μηχανή, πόσα κοντέινερ και εικόνες", - "Saved. The engine uses these from its next start": "Αποθηκεύτηκε. Η μηχανή τα χρησιμοποιεί από την επόμενη εκκίνησή της" + "Saved. The engine uses these from its next start": "Αποθηκεύτηκε. Η μηχανή τα χρησιμοποιεί από την επόμενη εκκίνησή της", + "5 min": "5 λ", + "10 min": "10 λ", + "30 min": "30 λ", + "Never": "Ποτέ", + "Build cache limit": "Όριο κρυφής μνήμης δόμησης", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Τα παλαιότερα επίπεδα κρυφής μνήμης εκκαθαρίζονται αυτόματα μόλις η κρυφή μνήμη του BuildKit ξεπεράσει αυτό το μέγεθος.", + "Stop builder when idle": "Διακοπή builder σε αδράνεια", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Σταματά το BuildKit μεταξύ των δομήσεων ώστε να μη δεσμεύει μνήμη σε αδράνεια· η επόμενη δόμηση το ξυπνά σε λιγότερο από ένα δευτερόλεπτο.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Το KIRI_BUILD_CACHE_GB ή το KIRI_BUILDER_IDLE_SECS έχει οριστεί για τον daemon και υπερισχύει αυτών.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: το ταχύτερο. Αλλάξτε σε Αναμετάδοση host αν το Cloudflare WARP ή ένα εταιρικό τείχος προστασίας μπλοκάρει το HTTPS των κοντέινερ. Ισχύει μετά από επανεκκίνηση της VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Αναμετάδοση host: οι συνδέσεις εξέρχονται από το Kiri στο macOS αντί για το NAT του Virtualization.framework. Ισχύει μετά από επανεκκίνηση της VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Το KIRI_SHARED_NAT έχει οριστεί στο περιβάλλον και υπερισχύει.", + "Outbound VM traffic": "Εξερχόμενη κίνηση VM", + "macOS NAT": "macOS NAT", + "Host relay": "Αναμετάδοση host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Το μέγιστο μέγεθος στο οποίο μπορεί να μεγαλώσει ο δίσκος της VM. Καταλαμβάνει χώρο στο {os} μόνο καθώς γράφονται δεδομένα, ενώ ο αχρησιμοποίητος χώρος μπορεί να ανακτηθεί στις {storage}. Εφαρμόζεται κατά την επανεκκίνηση.", + "Settings → Storage": "Ρυθμίσεις → Αποθηκευτικός χώρος", + "VM disk space": "Χώρος δίσκου VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Το εγγενές Linux χρησιμοποιεί απευθείας το σύστημα αρχείων του κεντρικού υπολογιστή — οι διαγραμμένες εικόνες και οι τόμοι ελευθερώνουν χώρο αμέσως.", + "Compact disk…": "Συμπύκνωση δίσκου…", + "Reclaim space": "Ανάκτηση χώρου", + "Compacting…": "Συμπύκνωση…", + "Reclaiming…": "Ανάκτηση…", + "Compacting {vhdx} and restarting the engine…": "Συμπύκνωση του {vhdx} και επανεκκίνηση της μηχανής…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} στο {os}, {inUse} σε χρήση εντός της VM · περικοπή αχρησιμοποίητων μπλοκ…", + "Trimming unused blocks inside the VM disk…": "Περικοπή αχρησιμοποίητων μπλοκ στον δίσκο της VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} στα Windows ({vhdx}), {inUse} σε χρήση · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} στο {os}, {inUse} σε χρήση εντός της VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} στα Windows ({vhdx}), {inUse} σε χρήση · τίποτα για ανάκτηση.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} στο {os}, {inUse} σε χρήση εντός της VM · τίποτα για ανάκτηση.", + "Nothing to reclaim.": "Τίποτα για ανάκτηση.", + "{size} can be given back": "μπορούν να επιστραφούν {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} στα Windows ({vhdx}), {inUse} σε χρήση · {can}. Η συμπύκνωση επανεκκινεί τη μηχανή.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} στο {os}, {inUse} σε χρήση εντός της VM · {can} χωρίς διακοπή των κοντέινερ.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} στα Windows ({vhdx}). Η συμπύκνωση επιστρέφει τον αχρησιμοποίητο χώρο και επανεκκινεί τη μηχανή.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} στο {os}. Η ανάκτηση περικόπτει τα αχρησιμοποίητα μπλοκ στον δίσκο της VM χωρίς διακοπή των κοντέινερ.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Επιστρέφει τον αχρησιμοποίητο χώρο του {vhdx} στα Windows. Η συμπύκνωση επανεκκινεί τη μηχανή.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Επιστρέφει τα αχρησιμοποίητα μπλοκ του δίσκου της VM στο {os} χωρίς διακοπή των κοντέινερ.", + "Cleaning up stopped containers, untagged images, and build cache…": "Εκκαθάριση σταματημένων κοντέινερ, εικόνων χωρίς ετικέτα και κρυφής μνήμης δόμησης…", + "{count} ({size})": "{count} ({size})", + "build cache": "κρυφή μνήμη δόμησης", + "No stopped containers, untagged images or build cache · {freed}.": "Κανένα σταματημένο κοντέινερ, εικόνα χωρίς ετικέτα ή κρυφή μνήμη δόμησης · {freed}.", + "No stopped containers, untagged images or build cache.": "Κανένα σταματημένο κοντέινερ, εικόνα χωρίς ετικέτα ή κρυφή μνήμη δόμησης.", + "Cleaning up…": "Εκκαθάριση…", + "Clean up…": "Εκκαθάριση…", + "Unused Docker data": "Αχρησιμοποίητα δεδομένα Docker", + "Command-line tools in shell": "Εργαλεία γραμμής εντολών στο κέλυφος", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Προσθέστε το {bin} στα {zshrc} και {zprofile} ώστε τα {docker}, {kubectl} και {kiri} να λειτουργούν σε νέα τερματικά.", + "Uninstall Kiri": "Απεγκατάσταση Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Σταματά τη μηχανή, αφαιρεί την υπηρεσία παρασκηνίου του Kiri, τους συνδέσμους CLI και τις καταχωρίσεις προφίλ κελύφους, και επαναφέρει το προηγούμενο περιβάλλον Docker ({cmd}).", + "Uninstall Kiri…": "Απεγκατάσταση Kiri…", + "Couldn't reclaim disk space: {error}": "Δεν ήταν δυνατή η ανάκτηση χώρου στον δίσκο: {error}", + "Reclaimed {size} on {os}": "Ανακτήθηκαν {size} στο {os}", + "Nothing to reclaim": "Τίποτα για ανάκτηση", + "Couldn't clean up unused Docker data: {error}": "Δεν ήταν δυνατή η εκκαθάριση των αχρησιμοποίητων δεδομένων Docker: {error}", + "Cleaned up {size} of unused Docker data": "Εκκαθαρίστηκαν {size} αχρησιμοποίητων δεδομένων Docker", + "Cleaned up unused Docker data": "Εκκαθαρίστηκαν τα αχρησιμοποίητα δεδομένα Docker", + "Compact WSL disk?": "Συμπύκνωση δίσκου WSL;", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Η συμπύκνωση του {vhdx} επιστρέφει τον αχρησιμοποίητο χώρο στα Windows και επανεκκινεί για λίγο τη μηχανή του Kiri και τα ενεργά κοντέινερ.", + "Compact disk": "Συμπύκνωση δίσκου", + "Clean up unused Docker data?": "Εκκαθάριση αχρησιμοποίητων δεδομένων Docker;", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Αφαιρεί τα σταματημένα κοντέινερ, τις εικόνες χωρίς ετικέτα και την κρυφή μνήμη δόμησης του BuildKit. Τα ενεργά κοντέινερ και οι εικόνες με ετικέτα διατηρούνται.", + "Clean up": "Εκκαθάριση", + "Uninstall Kiri?": "Απεγκατάσταση του Kiri;", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Σταματά τη μηχανή, αφαιρεί την υπηρεσία παρασκηνίου του Kiri, τους συνδέσμους CLI και τις καταχωρίσεις προφίλ κελύφους, και επαναφέρει το προηγούμενο περιβάλλον Docker. Οι εικόνες και οι τόμοι σας παραμένουν στον φάκελο δεδομένων του Kiri μέχρι να τον διαγράψετε.", + "Cluster": "Cluster", + "default": "προεπιλογή", + "k3s version": "Έκδοση k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Έκδοση εικόνας για τον κόμβο του cluster ({cmd}). Εφαρμόζεται κατά την εκ νέου δημιουργία.", + "Extra server flags": "Επιπλέον σημαίες διακομιστή", + "Passed to {srv} ({flag}), separated by spaces.": "Περνούν στο {srv} ({flag}), χωρισμένες με κενά.", + "Startup manifests": "Δηλώσεις εκκίνησης", + "YAML files in {path} are applied whenever the cluster starts.": "Τα αρχεία YAML στο {path} εφαρμόζονται κάθε φορά που ξεκινά το cluster.", + "Open folder": "Άνοιγμα φακέλου", + "{n} untagged image": "{n} εικόνα χωρίς ετικέτα", + "{n} untagged images": "{n} εικόνες χωρίς ετικέτα", + "Uninstall Kiri from Windows Settings → Apps": "Απεγκαταστήστε το Kiri από τις Ρυθμίσεις Windows → Εφαρμογές", + "Builder settings saved": "Οι ρυθμίσεις του builder αποθηκεύτηκαν", + "Could not save builder settings: {error}": "Δεν ήταν δυνατή η αποθήκευση των ρυθμίσεων του builder: {error}", + "Disk reclaim is already running": "Η ανάκτηση χώρου δίσκου εκτελείται ήδη", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Η ρύθμιση εξερχόμενης κίνησης VM αποθηκεύτηκε. Επανεκκινήστε τη VM για εφαρμογή.", + "Could not save VM networking setting: {error}": "Δεν ήταν δυνατή η αποθήκευση της ρύθμισης δικτύου VM: {error}", + "Added Kiri command-line tools to shell profiles": "Προστέθηκαν τα εργαλεία γραμμής εντολών του Kiri στα προφίλ κελύφους", + "Removed Kiri command-line tools from shell profiles": "Αφαιρέθηκαν τα εργαλεία γραμμής εντολών του Kiri από τα προφίλ κελύφους", + "Could not update shell profiles: {error}": "Δεν ήταν δυνατή η ενημέρωση των προφίλ κελύφους: {error}", + "Uninstalling Kiri…": "Απεγκατάσταση Kiri…", + "Could not uninstall Kiri: {error}": "Δεν ήταν δυνατή η απεγκατάσταση του Kiri: {error}", + "Uninstall Kiri using your system package manager": "Απεγκαταστήστε το Kiri μέσω του διαχειριστή πακέτων του συστήματός σας" } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index b3aa3ddc4..d46419ef0 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -1854,7 +1854,6 @@ "Disk image size": "Tamaño de la imagen de disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB está definida para el daemon y tiene prioridad sobre estos valores.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marcha ahora con {cpus}, hasta {mem} y un disco de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos; nunca se reduce. Se aplica al reiniciar.", "No other WSL distros installed.": "No hay otras distribuciones de WSL instaladas.", "WSL integration": "Integración con WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Cerrar: se libera la memoria que usa la ventana. Tarda un momento en volver a abrirse y los terminales abiertos se cierran.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri y este PC", "Kiri and this computer": "Kiri y este equipo", "Versions, {os}, whether the engine runs, how many containers and images": "Versiones, {os}, si el motor está en marcha, cuántos contenedores e imágenes", - "Saved. The engine uses these from its next start": "Guardado. El motor los usa a partir de su próximo inicio" + "Saved. The engine uses these from its next start": "Guardado. El motor los usa a partir de su próximo inicio", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nunca", + "Build cache limit": "Límite de caché de build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Las capas en caché más antiguas se purgan automáticamente cuando la caché de BuildKit supera este tamaño.", + "Stop builder when idle": "Detener builder en reposo", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Detiene BuildKit entre builds para que no use memoria mientras está inactivo; el siguiente build lo reactiva en menos de un segundo.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB o KIRI_BUILDER_IDLE_SECS está definida para el daemon y tiene prioridad sobre estos valores.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT de macOS: el más rápido. Cambia a Relé del host si Cloudflare WARP o un firewall corporativo bloquea el HTTPS de los contenedores. Se aplica al reiniciar la VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relé del host: las conexiones salen desde Kiri en macOS en lugar del NAT de Virtualization.framework. Se aplica al reiniciar la VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT está definida en el entorno y tiene prioridad.", + "Outbound VM traffic": "Tráfico saliente de la VM", + "macOS NAT": "NAT de macOS", + "Host relay": "Relé del host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Lo máximo que puede crecer el disco de la VM. Solo ocupa espacio en {os} a medida que se escriben datos, y el espacio sin uso puede recuperarse en {storage}. Se aplica al reiniciar.", + "Settings → Storage": "Ajustes → Almacenamiento", + "VM disk space": "Espacio en disco de la VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux nativo usa directamente el sistema de archivos del host — las imágenes y volúmenes eliminados liberan espacio al instante.", + "Compact disk…": "Compactar disco…", + "Reclaim space": "Recuperar espacio", + "Compacting…": "Compactando…", + "Reclaiming…": "Recuperando…", + "Compacting {vhdx} and restarting the engine…": "Compactando {vhdx} y reiniciando el motor…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} en {os}, {inUse} en uso dentro de la VM · recortando bloques sin uso…", + "Trimming unused blocks inside the VM disk…": "Recortando bloques sin uso dentro del disco de la VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} en Windows ({vhdx}), {inUse} en uso · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} en {os}, {inUse} en uso dentro de la VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} en Windows ({vhdx}), {inUse} en uso · nada que recuperar.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} en {os}, {inUse} en uso dentro de la VM · nada que recuperar.", + "Nothing to reclaim.": "Nada que recuperar.", + "{size} can be given back": "se pueden recuperar {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} en Windows ({vhdx}), {inUse} en uso · {can}. Compactar reinicia el motor.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} en {os}, {inUse} en uso dentro de la VM · {can} sin detener los contenedores.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} en Windows ({vhdx}). Compactar devuelve el espacio sin uso y reinicia el motor.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} en {os}. Recuperar recorta los bloques sin uso del disco de la VM sin detener los contenedores.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Devuelve a Windows el espacio sin uso de {vhdx}. Compactar reinicia el motor.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Devuelve a {os} los bloques sin uso del disco de la VM sin detener los contenedores.", + "Cleaning up stopped containers, untagged images, and build cache…": "Limpiando contenedores detenidos, imágenes sin tag y caché de build…", + "{count} ({size})": "{count} ({size})", + "build cache": "caché de build", + "No stopped containers, untagged images or build cache · {freed}.": "Sin contenedores detenidos, imágenes sin tag ni caché de build · {freed}.", + "No stopped containers, untagged images or build cache.": "Sin contenedores detenidos, imágenes sin tag ni caché de build.", + "Cleaning up…": "Limpiando…", + "Clean up…": "Limpiar…", + "Unused Docker data": "Datos de Docker sin uso", + "Command-line tools in shell": "Herramientas de línea de comandos en la shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Añade {bin} a {zshrc} y {zprofile} para que {docker}, {kubectl} y {kiri} funcionen en las terminales nuevas.", + "Uninstall Kiri": "Desinstalar Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Detiene el motor, elimina el servicio en segundo plano de Kiri, los enlaces de CLI y las entradas en los perfiles de la shell, y restaura tu contexto de Docker anterior ({cmd}).", + "Uninstall Kiri…": "Desinstalar Kiri…", + "Couldn't reclaim disk space: {error}": "No se pudo recuperar espacio en disco: {error}", + "Reclaimed {size} on {os}": "Se recuperaron {size} en {os}", + "Nothing to reclaim": "Nada que recuperar", + "Couldn't clean up unused Docker data: {error}": "No se pudieron limpiar los datos de Docker sin uso: {error}", + "Cleaned up {size} of unused Docker data": "Se limpiaron {size} de datos de Docker sin uso", + "Cleaned up unused Docker data": "Se limpiaron los datos de Docker sin uso", + "Compact WSL disk?": "¿Compactar disco de WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Compactar {vhdx} devuelve el espacio sin uso a Windows y reinicia brevemente el motor de Kiri y los contenedores en ejecución.", + "Compact disk": "Compactar disco", + "Clean up unused Docker data?": "¿Limpiar datos de Docker sin uso?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Elimina los contenedores detenidos, las imágenes sin tag y la caché de build de BuildKit. Se conservan los contenedores en ejecución y las imágenes con tag.", + "Clean up": "Limpiar", + "Uninstall Kiri?": "¿Desinstalar Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Detiene el motor, elimina el servicio en segundo plano de Kiri, los enlaces de CLI y las entradas en los perfiles de la shell, y restaura tu contexto de Docker anterior. Tus imágenes y volúmenes permanecen en la carpeta de datos de Kiri hasta que la elimines.", + "Cluster": "Clúster", + "default": "por defecto", + "k3s version": "Versión de k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versión de la imagen del nodo del clúster ({cmd}). Se aplica al recrearlo.", + "Extra server flags": "Opciones adicionales del servidor", + "Passed to {srv} ({flag}), separated by spaces.": "Se pasan a {srv} ({flag}), separadas por espacios.", + "Startup manifests": "Manifiestos de inicio", + "YAML files in {path} are applied whenever the cluster starts.": "Los archivos YAML en {path} se aplican cada vez que se inicia el clúster.", + "Open folder": "Abrir carpeta", + "{n} untagged image": "{n} imagen sin tag", + "{n} untagged images": "{n} imágenes sin tag", + "Uninstall Kiri from Windows Settings → Apps": "Desinstala Kiri desde Configuración de Windows → Aplicaciones", + "Builder settings saved": "Ajustes del builder guardados", + "Could not save builder settings: {error}": "No se pudieron guardar los ajustes del builder: {error}", + "Disk reclaim is already running": "La recuperación de espacio en disco ya está en curso", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Ajuste de tráfico saliente de la VM guardado. Reinicia la VM para aplicarlo.", + "Could not save VM networking setting: {error}": "No se pudo guardar el ajuste de red de la VM: {error}", + "Added Kiri command-line tools to shell profiles": "Herramientas de línea de comandos de Kiri añadidas a los perfiles de la shell", + "Removed Kiri command-line tools from shell profiles": "Herramientas de línea de comandos de Kiri eliminadas de los perfiles de la shell", + "Could not update shell profiles: {error}": "No se pudieron actualizar los perfiles de la shell: {error}", + "Uninstalling Kiri…": "Desinstalando Kiri…", + "Could not uninstall Kiri: {error}": "No se pudo desinstalar Kiri: {error}", + "Uninstall Kiri using your system package manager": "Desinstala Kiri con el gestor de paquetes de tu sistema" } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index ecd7d8df9..542e95e8a 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -1854,7 +1854,6 @@ "Disk image size": "اندازهٔ تصویر دیسک", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS، KIRI_MEMORY_MIB یا KIRI_DISK_GB برای سرویس پس‌زمینه تنظیم شده و بر این تنظیمات اولویت دارد.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "اکنون با {cpus}، حداکثر {mem} و دیسک {disk} در حال اجراست.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و هرگز کوچک نمی‌شود. پس از راه‌اندازی مجدد اعمال می‌شود.", "No other WSL distros installed.": "توزیع WSL دیگری نصب نشده است.", "WSL integration": "یکپارچه‌سازی WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "بستن: حافظه‌ای که پنجره مصرف می‌کند آزاد می‌شود. باز شدن دوباره‌اش کمی طول می‌کشد و ترمینال‌های باز بسته می‌شوند.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri و این رایانه", "Kiri and this computer": "Kiri و این رایانه", "Versions, {os}, whether the engine runs, how many containers and images": "نسخه‌ها، {os}، اجرا بودن یا نبودن موتور، تعداد کانتینرها و ایمیج‌ها", - "Saved. The engine uses these from its next start": "ذخیره شد. موتور از شروع بعدی از آن‌ها استفاده می‌کند" + "Saved. The engine uses these from its next start": "ذخیره شد. موتور از شروع بعدی از آن‌ها استفاده می‌کند", + "5 min": "5 دقیقه", + "10 min": "10 دقیقه", + "30 min": "30 دقیقه", + "Never": "هرگز", + "Build cache limit": "محدودیت حافظهٔ پنهان ساخت", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "به محض اینکه حافظهٔ پنهان BuildKit از این اندازه بگذرد، قدیمی‌ترین لایه‌های کش‌شده به‌طور خودکار پاک‌سازی می‌شوند.", + "Stop builder when idle": "توقف سازنده هنگام بیکاری", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "BuildKit را بین ساخت‌ها متوقف می‌کند تا در زمان بیکاری حافظه‌ای مصرف نکند؛ ساخت بعدی در کمتر از یک ثانیه بیدارش می‌کند.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB یا KIRI_BUILDER_IDLE_SECS برای سرویس پس‌زمینه تنظیم شده و بر این تنظیمات اولویت دارد.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: سریع‌ترین. اگر Cloudflare WARP یا فایروال سازمانی، HTTPS کانتینرها را مسدود می‌کند به رلهٔ میزبان تغییر دهید. پس از راه‌اندازی مجدد ماشین مجازی اعمال می‌شود.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "رلهٔ میزبان: اتصال‌ها به‌جای NAT در Virtualization.framework از Kiri روی macOS خارج می‌شوند. پس از راه‌اندازی مجدد ماشین مجازی اعمال می‌شود.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT در محیط تنظیم شده و اولویت دارد.", + "Outbound VM traffic": "ترافیک خروجی ماشین مجازی", + "macOS NAT": "macOS NAT", + "Host relay": "رلهٔ میزبان", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "بیشترین اندازه‌ای که دیسک ماشین مجازی می‌تواند بزرگ شود. فضا در {os} فقط هنگام نوشتن داده‌ها مصرف می‌شود و فضای استفاده‌نشده را می‌توان در {storage} بازپس گرفت. پس از راه‌اندازی مجدد اعمال می‌شود.", + "Settings → Storage": "تنظیمات ← فضای ذخیره‌سازی", + "VM disk space": "فضای دیسک ماشین مجازی", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux بومی مستقیماً از فایل‌سیستم میزبان استفاده می‌کند — ایمیج‌ها و والیوم‌های حذف‌شده بلافاصله فضا را آزاد می‌کنند.", + "Compact disk…": "فشرده‌سازی دیسک…", + "Reclaim space": "بازپس‌گیری فضا", + "Compacting…": "در حال فشرده‌سازی…", + "Reclaiming…": "در حال بازپس‌گیری…", + "Compacting {vhdx} and restarting the engine…": "در حال فشرده‌سازی {vhdx} و راه‌اندازی مجدد موتور…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} در {os}، {inUse} در حال استفاده داخل ماشین مجازی · در حال آزادسازی بلوک‌های استفاده‌نشده…", + "Trimming unused blocks inside the VM disk…": "در حال آزادسازی بلوک‌های استفاده‌نشده در دیسک ماشین مجازی…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} در Windows ({vhdx})، {inUse} در حال استفاده · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} در {os}، {inUse} در حال استفاده داخل ماشین مجازی · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} در Windows ({vhdx})، {inUse} در حال استفاده · چیزی برای بازپس‌گیری نیست.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} در {os}، {inUse} در حال استفاده داخل ماشین مجازی · چیزی برای بازپس‌گیری نیست.", + "Nothing to reclaim.": "چیزی برای بازپس‌گیری نیست.", + "{size} can be given back": "{size} قابل بازگرداندن است", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} در Windows ({vhdx})، {inUse} در حال استفاده · {can}. فشرده‌سازی موتور را دوباره راه‌اندازی می‌کند.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} در {os}، {inUse} در حال استفاده داخل ماشین مجازی · بدون توقف کانتینرها {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} در Windows ({vhdx}). فشرده‌سازی فضای استفاده‌نشده را برمی‌گرداند و موتور را دوباره راه‌اندازی می‌کند.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} در {os}. بازپس‌گیری بدون توقف کانتینرها بلوک‌های استفاده‌نشدهٔ دیسک ماشین مجازی را آزاد می‌کند.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "فضای استفاده‌نشدهٔ {vhdx} را به Windows برمی‌گرداند. فشرده‌سازی موتور را دوباره راه‌اندازی می‌کند.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "بلوک‌های استفاده‌نشدهٔ دیسک ماشین مجازی را بدون توقف کانتینرها به {os} برمی‌گرداند.", + "Cleaning up stopped containers, untagged images, and build cache…": "در حال پاک‌سازی کانتینرهای متوقف، ایمیج‌های بدون تگ و حافظهٔ پنهان ساخت…", + "{count} ({size})": "{count} ({size})", + "build cache": "حافظهٔ پنهان ساخت", + "No stopped containers, untagged images or build cache · {freed}.": "هیچ کانتینر متوقف، ایمیج بدون تگ یا حافظهٔ پنهان ساختی وجود ندارد · {freed}.", + "No stopped containers, untagged images or build cache.": "هیچ کانتینر متوقف، ایمیج بدون تگ یا حافظهٔ پنهان ساختی وجود ندارد.", + "Cleaning up…": "در حال پاک‌سازی…", + "Clean up…": "پاک‌سازی…", + "Unused Docker data": "داده‌های استفاده‌نشدهٔ Docker", + "Command-line tools in shell": "ابزارهای خط فرمان در شل", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{bin} را به {zshrc} و {zprofile} اضافه کنید تا {docker}، {kubectl} و {kiri} در ترمینال‌های جدید کار کنند.", + "Uninstall Kiri": "حذف نصب Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "موتور را متوقف می‌کند، سرویس پس‌زمینهٔ Kiri، پیوندهای CLI و ورودی‌های پروفایل شل را برمی‌دارد و کانتکست قبلی Docker شما را بازمی‌گرداند ({cmd}).", + "Uninstall Kiri…": "حذف نصب Kiri…", + "Couldn't reclaim disk space: {error}": "بازپس‌گیری فضای دیسک ممکن نشد: {error}", + "Reclaimed {size} on {os}": "{size} در {os} بازپس گرفته شد", + "Nothing to reclaim": "چیزی برای بازپس‌گیری نیست", + "Couldn't clean up unused Docker data: {error}": "پاک‌سازی داده‌های استفاده‌نشدهٔ Docker ممکن نشد: {error}", + "Cleaned up {size} of unused Docker data": "{size} از داده‌های استفاده‌نشدهٔ Docker پاک‌سازی شد", + "Cleaned up unused Docker data": "داده‌های استفاده‌نشدهٔ Docker پاک‌سازی شد", + "Compact WSL disk?": "دیسک WSL فشرده شود؟", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "فشرده‌سازی {vhdx} فضای استفاده‌نشده را به Windows برمی‌گرداند و موتور Kiri و کانتینرهای در حال اجرا را برای لحظه‌ای دوباره راه‌اندازی می‌کند.", + "Compact disk": "فشرده‌سازی دیسک", + "Clean up unused Docker data?": "داده‌های استفاده‌نشدهٔ Docker پاک‌سازی شوند؟", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "کانتینرهای متوقف، ایمیج‌های بدون تگ و حافظهٔ پنهان ساخت BuildKit را حذف می‌کند. کانتینرهای در حال اجرا و ایمیج‌های تگ‌دار حفظ می‌شوند.", + "Clean up": "پاک‌سازی", + "Uninstall Kiri?": "Kiri حذف نصب شود؟", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "موتور را متوقف می‌کند، سرویس پس‌زمینهٔ Kiri، پیوندهای CLI و ورودی‌های پروفایل شل را برمی‌دارد و کانتکست قبلی Docker شما را بازمی‌گرداند. ایمیج‌ها و والیوم‌های شما تا زمانی که خودتان پوشهٔ دادهٔ Kiri را حذف کنید در آن باقی می‌مانند.", + "Cluster": "کلاستر", + "default": "پیش‌فرض", + "k3s version": "نسخهٔ k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "نسخهٔ ایمیج برای گره کلاستر ({cmd}). هنگام ساخت مجدد اعمال می‌شود.", + "Extra server flags": "پرچم‌های اضافی سرور", + "Passed to {srv} ({flag}), separated by spaces.": "با فاصله از هم جدا شده و به {srv} ({flag}) داده می‌شوند.", + "Startup manifests": "مانیفست‌های آغازین", + "YAML files in {path} are applied whenever the cluster starts.": "فایل‌های YAML در {path} هر بار که کلاستر راه‌اندازی می‌شود اعمال می‌شوند.", + "Open folder": "باز کردن پوشه", + "{n} untagged image": "{n} ایمیج بدون تگ", + "{n} untagged images": "{n} ایمیج بدون تگ", + "Uninstall Kiri from Windows Settings → Apps": "Kiri را از تنظیمات Windows ← برنامه‌ها حذف نصب کنید", + "Builder settings saved": "تنظیمات سازنده ذخیره شد", + "Could not save builder settings: {error}": "ذخیرهٔ تنظیمات سازنده ممکن نشد: {error}", + "Disk reclaim is already running": "بازپس‌گیری فضای دیسک هم‌اکنون در حال اجراست", + "Outbound VM traffic setting saved. Restart the VM to apply.": "تنظیم ترافیک خروجی ماشین مجازی ذخیره شد. برای اعمال، ماشین مجازی را دوباره راه‌اندازی کنید.", + "Could not save VM networking setting: {error}": "ذخیرهٔ تنظیم شبکهٔ ماشین مجازی ممکن نشد: {error}", + "Added Kiri command-line tools to shell profiles": "ابزارهای خط فرمان Kiri به پروفایل‌های شل اضافه شدند", + "Removed Kiri command-line tools from shell profiles": "ابزارهای خط فرمان Kiri از پروفایل‌های شل حذف شدند", + "Could not update shell profiles: {error}": "به‌روزرسانی پروفایل‌های شل ممکن نشد: {error}", + "Uninstalling Kiri…": "در حال حذف نصب Kiri…", + "Could not uninstall Kiri: {error}": "حذف نصب Kiri ممکن نشد: {error}", + "Uninstall Kiri using your system package manager": "Kiri را با مدیر بستهٔ سیستم خود حذف نصب کنید" } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index 4e79517fc..9038fe400 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -1854,7 +1854,6 @@ "Disk image size": "Levykuvan koko", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemonille on asetettu KIRI_CPUS, KIRI_MEMORY_MIB tai KIRI_DISK_GB, ja ne menevät näiden edelle.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Käynnissä nyt: {cpus}, muistia enintään {mem}, levy {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, eikä levy koskaan pienene. Tulee voimaan uudelleenkäynnistyksessä.", "No other WSL distros installed.": "Muita WSL-jakeluita ei ole asennettu.", "WSL integration": "WSL-integraatio", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Sulje: ikkunan käyttämä muisti vapautetaan. Uudelleen avautuminen kestää hetken, ja avoimet päätteet suljetaan.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri ja tämä PC", "Kiri and this computer": "Kiri ja tämä tietokone", "Versions, {os}, whether the engine runs, how many containers and images": "Versiot, {os}, onko moottori käynnissä, konttien ja levykuvien määrä", - "Saved. The engine uses these from its next start": "Tallennettu. Moottori käyttää näitä seuraavasta käynnistyksestä alkaen" + "Saved. The engine uses these from its next start": "Tallennettu. Moottori käyttää näitä seuraavasta käynnistyksestä alkaen", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Ei koskaan", + "Build cache limit": "Koontivälimuistin raja", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Vanhimmat välimuistissa olevat tasot siivotaan automaattisesti, kun BuildKitin välimuisti ylittää tämän koon.", + "Stop builder when idle": "Pysäytä koontipalvelu jouten ollessa", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Pysäyttää BuildKitin koontien välillä, jotta se ei vie muistia jouten ollessaan; seuraava koonti herättää sen alle sekunnissa.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Daemonille on asetettu KIRI_BUILD_CACHE_GB tai KIRI_BUILDER_IDLE_SECS, ja se menee näiden edelle.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: nopein. Vaihda tilaan Isäntävälitys, jos Cloudflare WARP tai yrityksen palomuuri estää konttien HTTPS-liikenteen. Tulee voimaan virtuaalikoneen uudelleenkäynnistyksessä.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Isäntävälitys: yhteydet lähtevät Kiristä macOS:ssä Virtualization.frameworkin NATin sijaan. Tulee voimaan virtuaalikoneen uudelleenkäynnistyksessä.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT on asetettu ympäristössä ja menee edelle.", + "Outbound VM traffic": "Virtuaalikoneen lähtevä liikenne", + "macOS NAT": "macOS NAT", + "Host relay": "Isäntävälitys", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Enimmäiskoko, johon virtuaalikoneen levy voi kasvaa. Tilaa kuluu järjestelmästä {os} vain dataa kirjoitettaessa, ja käyttämätön tila voidaan vapauttaa kohdassa {storage}. Tulee voimaan uudelleenkäynnistyksessä.", + "Settings → Storage": "Asetukset → Tallennustila", + "VM disk space": "Virtuaalikoneen levytila", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Natiivi Linux käyttää isäntäjärjestelmän tiedostojärjestelmää suoraan — poistetut levykuvat ja taltiot vapauttavat tilaa heti.", + "Compact disk…": "Tiivistä levy…", + "Reclaim space": "Vapauta tilaa", + "Compacting…": "Tiivistetään…", + "Reclaiming…": "Vapautetaan…", + "Compacting {vhdx} and restarting the engine…": "Tiivistetään {vhdx} ja käynnistetään moottori uudelleen…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} järjestelmässä {os}, {inUse} käytössä virtuaalikoneessa · vapautetaan käyttämättömiä lohkoja…", + "Trimming unused blocks inside the VM disk…": "Vapautetaan käyttämättömiä lohkoja virtuaalikoneen levyllä…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} Windowsissa ({vhdx}), {inUse} käytössä · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} järjestelmässä {os}, {inUse} käytössä virtuaalikoneessa · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} Windowsissa ({vhdx}), {inUse} käytössä · ei vapautettavaa.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} järjestelmässä {os}, {inUse} käytössä virtuaalikoneessa · ei vapautettavaa.", + "Nothing to reclaim.": "Ei vapautettavaa.", + "{size} can be given back": "{size} voidaan palauttaa", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} Windowsissa ({vhdx}), {inUse} käytössä · {can}. Tiivistäminen käynnistää moottorin uudelleen.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} järjestelmässä {os}, {inUse} käytössä virtuaalikoneessa · {can} pysäyttämättä kontteja.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} Windowsissa ({vhdx}). Tiivistäminen palauttaa käyttämättömän tilan ja käynnistää moottorin uudelleen.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} järjestelmässä {os}. Vapautus trimmaa käyttämättömät lohkot virtuaalikoneen levyltä pysäyttämättä kontteja.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Palauttaa tiedoston {vhdx} käyttämättömän tilan Windowsille. Tiivistäminen käynnistää moottorin uudelleen.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Palauttaa virtuaalikoneen levyn käyttämättömät lohkot järjestelmälle {os} pysäyttämättä kontteja.", + "Cleaning up stopped containers, untagged images, and build cache…": "Siivotaan pysäytettyjä kontteja, nimeämättömiä levykuvia ja koontivälimuistia…", + "{count} ({size})": "{count} ({size})", + "build cache": "koontivälimuisti", + "No stopped containers, untagged images or build cache · {freed}.": "Ei pysäytettyjä kontteja, nimeämättömiä levykuvia eikä koontivälimuistia · {freed}.", + "No stopped containers, untagged images or build cache.": "Ei pysäytettyjä kontteja, nimeämättömiä levykuvia eikä koontivälimuistia.", + "Cleaning up…": "Siivotaan…", + "Clean up…": "Siivoa…", + "Unused Docker data": "Käyttämätön Docker-data", + "Command-line tools in shell": "Komentorivityökalut komentotulkissa", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Lisää {bin} tiedostoihin {zshrc} ja {zprofile}, jotta {docker}, {kubectl} ja {kiri} toimivat uusissa päätteissä.", + "Uninstall Kiri": "Poista Kirin asennus", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Pysäyttää moottorin, poistaa Kirin taustapalvelun, CLI-linkit ja komentotulkin profiilimerkinnät sekä palauttaa aiemman Docker-kontekstin ({cmd}).", + "Uninstall Kiri…": "Poista Kirin asennus…", + "Couldn't reclaim disk space: {error}": "Levytilaa ei voitu vapauttaa: {error}", + "Reclaimed {size} on {os}": "Vapautettiin {size} järjestelmässä {os}", + "Nothing to reclaim": "Ei vapautettavaa", + "Couldn't clean up unused Docker data: {error}": "Käyttämätöntä Docker-dataa ei voitu siivota: {error}", + "Cleaned up {size} of unused Docker data": "Siivottiin {size} käyttämätöntä Docker-dataa", + "Cleaned up unused Docker data": "Käyttämätön Docker-data siivottu", + "Compact WSL disk?": "Tiivistetäänkö WSL-levy?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Tiedoston {vhdx} tiivistäminen palauttaa käyttämättömän tilan Windowsille ja käynnistää hetkeksi uudelleen Kirin moottorin ja käynnissä olevat kontit.", + "Compact disk": "Tiivistä levy", + "Clean up unused Docker data?": "Siivotaanko käyttämätön Docker-data?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Poistaa pysäytetyt kontit, nimeämättömät levykuvat ja BuildKitin koontivälimuistin. Käynnissä olevat kontit ja nimetyt levykuvat säilytetään.", + "Clean up": "Siivoa", + "Uninstall Kiri?": "Poistetaanko Kirin asennus?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Pysäyttää moottorin, poistaa Kirin taustapalvelun, CLI-linkit ja komentotulkin profiilimerkinnät sekä palauttaa aiemman Docker-kontekstin. Levykuvat ja taltiot säilyvät Kirin datakansiossa, kunnes poistat sen.", + "Cluster": "Klusteri", + "default": "oletus", + "k3s version": "k3s-versio", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Klusterisolmun levykuvaversio ({cmd}). Tulee voimaan uudelleenluonnissa.", + "Extra server flags": "Palvelimen lisävalitsimet", + "Passed to {srv} ({flag}), separated by spaces.": "Välitetään komennolle {srv} ({flag}) välilyönnein erotettuina.", + "Startup manifests": "Käynnistysmanifestit", + "YAML files in {path} are applied whenever the cluster starts.": "Kansion {path} YAML-tiedostot otetaan käyttöön aina klusterin käynnistyessä.", + "Open folder": "Avaa kansio", + "{n} untagged image": "{n} nimeämätön levykuva", + "{n} untagged images": "{n} nimeämätöntä levykuvaa", + "Uninstall Kiri from Windows Settings → Apps": "Poista Kirin asennus kohdasta Windowsin asetukset → Sovellukset", + "Builder settings saved": "Koontipalvelun asetukset tallennettu", + "Could not save builder settings: {error}": "Koontipalvelun asetuksia ei voitu tallentaa: {error}", + "Disk reclaim is already running": "Levytilan vapautus on jo käynnissä", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Virtuaalikoneen lähtevän liikenteen asetus tallennettu. Ota käyttöön käynnistämällä virtuaalikone uudelleen.", + "Could not save VM networking setting: {error}": "Virtuaalikoneen verkkoasetusta ei voitu tallentaa: {error}", + "Added Kiri command-line tools to shell profiles": "Kirin komentorivityökalut lisättiin komentotulkin profiileihin", + "Removed Kiri command-line tools from shell profiles": "Kirin komentorivityökalut poistettiin komentotulkin profiileista", + "Could not update shell profiles: {error}": "Komentotulkin profiileja ei voitu päivittää: {error}", + "Uninstalling Kiri…": "Poistetaan Kirin asennusta…", + "Could not uninstall Kiri: {error}": "Kirin asennusta ei voitu poistaa: {error}", + "Uninstall Kiri using your system package manager": "Poista Kirin asennus järjestelmän paketinhallinnalla" } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 75aff8ef2..3e0b0eeb2 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -1854,7 +1854,6 @@ "Disk image size": "Taille de l’image disque", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB est défini pour le démon et prime sur ces réglages.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "En marche avec {cpus}, jusqu’à {mem} et un disque de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites ; il ne rétrécit jamais. Appliqué au redémarrage.", "No other WSL distros installed.": "Aucune autre distribution WSL installée.", "WSL integration": "Intégration WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fermer : la mémoire utilisée par la fenêtre est libérée. Elle met un instant à se rouvrir, et les terminaux ouverts se ferment.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri et ce PC", "Kiri and this computer": "Kiri et cet ordinateur", "Versions, {os}, whether the engine runs, how many containers and images": "Versions, {os}, état du moteur, nombre de conteneurs et d’images", - "Saved. The engine uses these from its next start": "Enregistré. Le moteur les utilise dès son prochain démarrage" + "Saved. The engine uses these from its next start": "Enregistré. Le moteur les utilise dès son prochain démarrage", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Jamais", + "Build cache limit": "Limite du cache de build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Les couches en cache les plus anciennes sont purgées automatiquement dès que le cache de BuildKit dépasse cette taille.", + "Stop builder when idle": "Arrêter le builder au repos", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Arrête BuildKit entre les builds pour qu’il n’utilise aucune mémoire au repos ; le build suivant le réveille en moins d’une seconde.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB ou KIRI_BUILDER_IDLE_SECS est défini pour le démon et prime sur ces réglages.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS : le plus rapide. Passez sur Relais hôte si Cloudflare WARP ou un pare-feu d’entreprise bloque le HTTPS des conteneurs. Appliqué au redémarrage de la VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relais hôte : les connexions sortent depuis Kiri sur macOS au lieu du NAT de Virtualization.framework. Appliqué au redémarrage de la VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT est défini dans l’environnement et prime sur ce réglage.", + "Outbound VM traffic": "Trafic sortant de la VM", + "macOS NAT": "NAT macOS", + "Host relay": "Relais hôte", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "La taille maximale du disque de la VM. L’espace sur {os} n’est utilisé qu’à mesure que des données sont écrites, et l’espace inutilisé peut être récupéré dans {storage}. Appliqué au redémarrage.", + "Settings → Storage": "Paramètres → Stockage", + "VM disk space": "Espace disque de la VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux natif utilise directement le système de fichiers hôte — les images et volumes supprimés libèrent l’espace immédiatement.", + "Compact disk…": "Compacter le disque…", + "Reclaim space": "Récupérer l’espace", + "Compacting…": "Compactage…", + "Reclaiming…": "Récupération…", + "Compacting {vhdx} and restarting the engine…": "Compactage de {vhdx} et redémarrage du moteur…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} sur {os}, {inUse} utilisés dans la VM · nettoyage des blocs inutilisés…", + "Trimming unused blocks inside the VM disk…": "Nettoyage des blocs inutilisés dans le disque de la VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} sur Windows ({vhdx}), {inUse} utilisés · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} sur {os}, {inUse} utilisés dans la VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} sur Windows ({vhdx}), {inUse} utilisés · rien à récupérer.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} sur {os}, {inUse} utilisés dans la VM · rien à récupérer.", + "Nothing to reclaim.": "Rien à récupérer.", + "{size} can be given back": "{size} peuvent être rendus", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} sur Windows ({vhdx}), {inUse} utilisés · {can}. Le compactage redémarre le moteur.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} sur {os}, {inUse} utilisés dans la VM · {can} sans arrêter les conteneurs.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} sur Windows ({vhdx}). Le compactage rend l’espace inutilisé et redémarre le moteur.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} sur {os}. La récupération libère les blocs inutilisés du disque de la VM sans arrêter les conteneurs.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Rend à Windows l’espace inutilisé dans {vhdx}. Le compactage redémarre le moteur.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Rend à {os} les blocs inutilisés du disque de la VM sans arrêter les conteneurs.", + "Cleaning up stopped containers, untagged images, and build cache…": "Nettoyage des conteneurs arrêtés, des images sans tag et du cache de build…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache de build", + "No stopped containers, untagged images or build cache · {freed}.": "Aucun conteneur arrêté, image sans tag ni cache de build · {freed}.", + "No stopped containers, untagged images or build cache.": "Aucun conteneur arrêté, image sans tag ni cache de build.", + "Cleaning up…": "Nettoyage…", + "Clean up…": "Nettoyer…", + "Unused Docker data": "Données Docker inutilisées", + "Command-line tools in shell": "Outils en ligne de commande dans le shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Ajoute {bin} à {zshrc} et {zprofile} pour que {docker}, {kubectl} et {kiri} fonctionnent dans les nouveaux terminaux.", + "Uninstall Kiri": "Désinstaller Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Arrête le moteur, supprime le service d’arrière-plan de Kiri, les liens CLI et les entrées du profil shell, puis restaure votre contexte Docker précédent ({cmd}).", + "Uninstall Kiri…": "Désinstaller Kiri…", + "Couldn't reclaim disk space: {error}": "Impossible de récupérer de l’espace disque : {error}", + "Reclaimed {size} on {os}": "{size} récupérés sur {os}", + "Nothing to reclaim": "Rien à récupérer", + "Couldn't clean up unused Docker data: {error}": "Impossible de nettoyer les données Docker inutilisées : {error}", + "Cleaned up {size} of unused Docker data": "{size} de données Docker inutilisées nettoyés", + "Cleaned up unused Docker data": "Données Docker inutilisées nettoyées", + "Compact WSL disk?": "Compacter le disque WSL ?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Le compactage de {vhdx} rend l’espace inutilisé à Windows et redémarre brièvement le moteur de Kiri ainsi que les conteneurs en marche.", + "Compact disk": "Compacter le disque", + "Clean up unused Docker data?": "Nettoyer les données Docker inutilisées ?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Supprime les conteneurs arrêtés, les images sans tag et le cache de build de BuildKit. Les conteneurs en marche et les images avec tag sont conservés.", + "Clean up": "Nettoyer", + "Uninstall Kiri?": "Désinstaller Kiri ?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Arrête le moteur, supprime le service d’arrière-plan de Kiri, les liens CLI et les entrées du profil shell, puis restaure votre contexte Docker précédent. Vos images et volumes restent dans le dossier de données de Kiri jusqu’à ce que vous le supprimiez.", + "Cluster": "Cluster", + "default": "par défaut", + "k3s version": "Version de k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Version de l’image du nœud du cluster ({cmd}). Appliquée à la recréation.", + "Extra server flags": "Options supplémentaires du serveur", + "Passed to {srv} ({flag}), separated by spaces.": "Passées à {srv} ({flag}), séparées par des espaces.", + "Startup manifests": "Manifestes de démarrage", + "YAML files in {path} are applied whenever the cluster starts.": "Les fichiers YAML dans {path} sont appliqués à chaque démarrage du cluster.", + "Open folder": "Ouvrir le dossier", + "{n} untagged image": "{n} image sans tag", + "{n} untagged images": "{n} images sans tag", + "Uninstall Kiri from Windows Settings → Apps": "Désinstallez Kiri depuis Paramètres Windows → Applications", + "Builder settings saved": "Paramètres du builder enregistrés", + "Could not save builder settings: {error}": "Impossible d’enregistrer les paramètres du builder : {error}", + "Disk reclaim is already running": "La récupération d’espace disque est déjà en cours", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Paramètre de trafic sortant de la VM enregistré. Redémarrez la VM pour l’appliquer.", + "Could not save VM networking setting: {error}": "Impossible d’enregistrer le paramètre réseau de la VM : {error}", + "Added Kiri command-line tools to shell profiles": "Outils en ligne de commande Kiri ajoutés aux profils shell", + "Removed Kiri command-line tools from shell profiles": "Outils en ligne de commande Kiri retirés des profils shell", + "Could not update shell profiles: {error}": "Impossible de mettre à jour les profils shell : {error}", + "Uninstalling Kiri…": "Désinstallation de Kiri…", + "Could not uninstall Kiri: {error}": "Impossible de désinstaller Kiri : {error}", + "Uninstall Kiri using your system package manager": "Désinstallez Kiri avec le gestionnaire de paquets de votre système" } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 395522897..13912178b 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -1854,7 +1854,6 @@ "Disk image size": "डिस्क इमेज का आकार", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "डेमन के लिए KIRI_CPUS, KIRI_MEMORY_MIB या KIRI_DISK_GB सेट है, और वह इनसे ऊपर लागू होता है।", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "अभी {cpus}, अधिकतम {mem} और {disk} डिस्क के साथ चल रहा है।", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है; यह कभी छोटा नहीं होता। रीस्टार्ट पर लागू होता है।", "No other WSL distros installed.": "कोई अन्य WSL डिस्ट्रो इंस्टॉल नहीं है।", "WSL integration": "WSL एकीकरण", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "बंद करें: विंडो की इस्तेमाल की गई मेमोरी खाली हो जाती है। फिर से खुलने में थोड़ा समय लगता है, और खुले टर्मिनल बंद हो जाते हैं।", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri और यह PC", "Kiri and this computer": "Kiri और यह कंप्यूटर", "Versions, {os}, whether the engine runs, how many containers and images": "वर्शन, {os}, इंजन चल रहा है या नहीं, कितने कंटेनर और इमेज", - "Saved. The engine uses these from its next start": "सेव किया गया। इंजन अगली बार शुरू होने से इनका उपयोग करता है" + "Saved. The engine uses these from its next start": "सेव किया गया। इंजन अगली बार शुरू होने से इनका उपयोग करता है", + "5 min": "5 मिनट", + "10 min": "10 मिनट", + "30 min": "30 मिनट", + "Never": "कभी नहीं", + "Build cache limit": "बिल्ड कैश सीमा", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit का कैश इस आकार से पार होते ही सबसे पुरानी कैश्ड लेयर अपने-आप हटा दी जाती हैं।", + "Stop builder when idle": "खाली रहने पर बिल्डर रोकें", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "बिल्ड के बीच BuildKit को रोक देता है ताकि खाली रहने पर मेमोरी न लगे; अगला बिल्ड इसे एक सेकंड से कम में जगा देता है।", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "डेमन के लिए KIRI_BUILD_CACHE_GB या KIRI_BUILDER_IDLE_SECS सेट है, और वह इनसे ऊपर लागू होता है।", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: सबसे तेज़। अगर Cloudflare WARP या कॉर्पोरेट फ़ायरवॉल कंटेनर HTTPS को रोकता है, तो होस्ट रिले पर बदलें। VM रीस्टार्ट पर लागू होता है।", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "होस्ट रिले: कनेक्शन Virtualization.framework NAT के बजाय macOS पर Kiri से बाहर जाते हैं। VM रीस्टार्ट पर लागू होता है।", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "एनवायरनमेंट में KIRI_SHARED_NAT सेट है और वह इससे ऊपर लागू होता है।", + "Outbound VM traffic": "बाहर जाने वाला VM ट्रैफ़िक", + "macOS NAT": "macOS NAT", + "Host relay": "होस्ट रिले", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM डिस्क अधिकतम इतना बढ़ सकता है। {os} पर जगह तभी इस्तेमाल होती है जब डेटा लिखा जाता है, और खाली जगह {storage} में वापस पाई जा सकती है। रीस्टार्ट पर लागू होता है।", + "Settings → Storage": "सेटिंग्स → स्टोरेज", + "VM disk space": "VM डिस्क स्पेस", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "नेटिव Linux सीधे आपके होस्ट फ़ाइलसिस्टम का उपयोग करता है — हटाई गई इमेज और वॉल्यूम तुरंत जगह खाली कर देते हैं।", + "Compact disk…": "डिस्क कॉम्पैक्ट करें…", + "Reclaim space": "जगह वापस पाएँ", + "Compacting…": "कॉम्पैक्ट हो रहा है…", + "Reclaiming…": "वापस पा रहे हैं…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} कॉम्पैक्ट हो रहा है और इंजन रीस्टार्ट हो रहा है…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} पर {host}, VM के अंदर {inUse} उपयोग में · अप्रयुक्त ब्लॉक ट्रिम हो रहे हैं…", + "Trimming unused blocks inside the VM disk…": "VM डिस्क के अंदर अप्रयुक्त ब्लॉक ट्रिम हो रहे हैं…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows पर {host} ({vhdx}), {inUse} उपयोग में · {freed}।", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} पर {host}, VM के अंदर {inUse} उपयोग में · {freed}।", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows पर {host} ({vhdx}), {inUse} उपयोग में · वापस पाने के लिए कुछ नहीं।", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} पर {host}, VM के अंदर {inUse} उपयोग में · वापस पाने के लिए कुछ नहीं।", + "Nothing to reclaim.": "वापस पाने के लिए कुछ नहीं।", + "{size} can be given back": "{size} वापस मिल सकता है", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows पर {host} ({vhdx}), {inUse} उपयोग में · {can}। कॉम्पैक्ट करने से इंजन रीस्टार्ट होता है।", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} पर {host}, VM के अंदर {inUse} उपयोग में · कंटेनर रोके बिना {can}।", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows पर {host} ({vhdx})। कॉम्पैक्ट करने से खाली जगह वापस मिलती है और इंजन रीस्टार्ट होता है।", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} पर {host}। जगह वापस पाने से कंटेनर रोके बिना VM डिस्क के अप्रयुक्त ब्लॉक ट्रिम होते हैं।", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} की खाली जगह Windows को लौटाता है। कॉम्पैक्ट करने से इंजन रीस्टार्ट होता है।", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "कंटेनर रोके बिना VM डिस्क के अप्रयुक्त ब्लॉक {os} को लौटाता है।", + "Cleaning up stopped containers, untagged images, and build cache…": "रुके कंटेनर, बिना टैग वाली इमेज और बिल्ड कैश साफ़ हो रहे हैं…", + "{count} ({size})": "{count} ({size})", + "build cache": "बिल्ड कैश", + "No stopped containers, untagged images or build cache · {freed}.": "कोई रुका कंटेनर, बिना टैग वाली इमेज या बिल्ड कैश नहीं · {freed}।", + "No stopped containers, untagged images or build cache.": "कोई रुका कंटेनर, बिना टैग वाली इमेज या बिल्ड कैश नहीं।", + "Cleaning up…": "साफ़ हो रहा है…", + "Clean up…": "साफ़ करें…", + "Unused Docker data": "अप्रयुक्त Docker डेटा", + "Command-line tools in shell": "शेल में कमांड-लाइन टूल", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{zshrc} और {zprofile} में {bin} जोड़ें ताकि नए टर्मिनल में {docker}, {kubectl} और {kiri} काम करें।", + "Uninstall Kiri": "Kiri अनइंस्टॉल करें", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "इंजन को रोकता है, Kiri की बैकग्राउंड सर्विस, CLI लिंक और शेल प्रोफ़ाइल एंट्री हटाता है, और आपका पिछला Docker कॉन्टेक्स्ट लौटाता है ({cmd})।", + "Uninstall Kiri…": "Kiri अनइंस्टॉल करें…", + "Couldn't reclaim disk space: {error}": "डिस्क स्पेस वापस नहीं पा सके: {error}", + "Reclaimed {size} on {os}": "{os} पर {size} वापस पाया गया", + "Nothing to reclaim": "वापस पाने के लिए कुछ नहीं", + "Couldn't clean up unused Docker data: {error}": "अप्रयुक्त Docker डेटा साफ़ नहीं कर सके: {error}", + "Cleaned up {size} of unused Docker data": "{size} अप्रयुक्त Docker डेटा साफ़ किया गया", + "Cleaned up unused Docker data": "अप्रयुक्त Docker डेटा साफ़ किया गया", + "Compact WSL disk?": "WSL डिस्क कॉम्पैक्ट करें?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} को कॉम्पैक्ट करने से खाली जगह Windows को वापस मिलती है और Kiri का इंजन व चलते कंटेनर थोड़ी देर के लिए रीस्टार्ट होते हैं।", + "Compact disk": "डिस्क कॉम्पैक्ट करें", + "Clean up unused Docker data?": "अप्रयुक्त Docker डेटा साफ़ करें?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "रुके कंटेनर, बिना टैग वाली इमेज और BuildKit का बिल्ड कैश हटाता है। चलते कंटेनर और टैग वाली इमेज सुरक्षित रहती हैं।", + "Clean up": "साफ़ करें", + "Uninstall Kiri?": "Kiri अनइंस्टॉल करें?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "इंजन को रोकता है, Kiri की बैकग्राउंड सर्विस, CLI लिंक और शेल प्रोफ़ाइल एंट्री हटाता है, और आपका पिछला Docker कॉन्टेक्स्ट लौटाता है। आपकी इमेज और वॉल्यूम तब तक Kiri के डेटा फ़ोल्डर में रहते हैं जब तक आप उसे हटाते नहीं।", + "Cluster": "क्लस्टर", + "default": "डिफ़ॉल्ट", + "k3s version": "k3s वर्शन", + "Image version for the cluster node ({cmd}). Applies when recreated.": "क्लस्टर नोड के लिए इमेज वर्शन ({cmd})। दोबारा बनने पर लागू होता है।", + "Extra server flags": "अतिरिक्त सर्वर फ़्लैग", + "Passed to {srv} ({flag}), separated by spaces.": "स्पेस से अलग करके {srv} ({flag}) को पास किए जाते हैं।", + "Startup manifests": "स्टार्टअप मैनिफ़ेस्ट", + "YAML files in {path} are applied whenever the cluster starts.": "जब भी क्लस्टर शुरू होता है, {path} में मौजूद YAML फ़ाइलें लागू होती हैं।", + "Open folder": "फ़ोल्डर खोलें", + "{n} untagged image": "{n} बिना टैग वाली इमेज", + "{n} untagged images": "{n} बिना टैग वाली इमेज", + "Uninstall Kiri from Windows Settings → Apps": "Windows सेटिंग्स → ऐप्स से Kiri अनइंस्टॉल करें", + "Builder settings saved": "बिल्डर सेटिंग्स सेव की गईं", + "Could not save builder settings: {error}": "बिल्डर सेटिंग्स सेव नहीं कर सके: {error}", + "Disk reclaim is already running": "डिस्क स्पेस वापस पाने की प्रक्रिया पहले से चल रही है", + "Outbound VM traffic setting saved. Restart the VM to apply.": "बाहर जाने वाले VM ट्रैफ़िक की सेटिंग सेव की गई। लागू करने के लिए VM रीस्टार्ट करें।", + "Could not save VM networking setting: {error}": "VM नेटवर्किंग सेटिंग सेव नहीं कर सके: {error}", + "Added Kiri command-line tools to shell profiles": "शेल प्रोफ़ाइल में Kiri कमांड-लाइन टूल जोड़े गए", + "Removed Kiri command-line tools from shell profiles": "शेल प्रोफ़ाइल से Kiri कमांड-लाइन टूल हटाए गए", + "Could not update shell profiles: {error}": "शेल प्रोफ़ाइल अपडेट नहीं कर सके: {error}", + "Uninstalling Kiri…": "Kiri अनइंस्टॉल हो रहा है…", + "Could not uninstall Kiri: {error}": "Kiri अनइंस्टॉल नहीं कर सके: {error}", + "Uninstall Kiri using your system package manager": "अपने सिस्टम पैकेज मैनेजर से Kiri अनइंस्टॉल करें" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index 018218f62..c61dff354 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -1854,7 +1854,6 @@ "Disk image size": "Lemezkép mérete", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "A démonnál be van állítva a KIRI_CPUS, a KIRI_MEMORY_MIB vagy a KIRI_DISK_GB, és ez felülírja ezeket.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Most így fut: {cpus}, legfeljebb {mem} memória és {disk} lemez.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), és soha nem zsugorodik. Újraindításkor lép életbe.", "No other WSL distros installed.": "Nincs más WSL-disztribúció telepítve.", "WSL integration": "WSL-integráció", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Bezárás: az ablak által használt memória felszabadul. Újbóli megnyitása egy pillanatig tart, a nyitott terminálok pedig bezárulnak.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "A Kiri és ez a PC", "Kiri and this computer": "A Kiri és ez a számítógép", "Versions, {os}, whether the engine runs, how many containers and images": "Verziók, {os}, fut-e a motor, hány konténer és image van", - "Saved. The engine uses these from its next start": "Mentve. A motor a következő indításától használja ezeket" + "Saved. The engine uses these from its next start": "Mentve. A motor a következő indításától használja ezeket", + "5 min": "5 perc", + "10 min": "10 perc", + "30 min": "30 perc", + "Never": "Soha", + "Build cache limit": "Build-gyorsítótár korlátja", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "A legrégebbi gyorsítótárazott rétegek automatikusan törlődnek, amint a BuildKit gyorsítótára meghaladja ezt a méretet.", + "Stop builder when idle": "Builder leállítása tétlenségkor", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "A buildek között leállítja a BuildKitet, így tétlenül nem fogyaszt memóriát; a következő build egy másodperc alatt felébreszti.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "A démonnál be van állítva a KIRI_BUILD_CACHE_GB vagy a KIRI_BUILDER_IDLE_SECS, és ez felülírja ezeket.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: a leggyorsabb. Válts a Gazdagép-relé módra, ha a Cloudflare WARP vagy egy vállalati tűzfal blokkolja a konténerek HTTPS-forgalmát. A virtuális gép újraindításakor lép életbe.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Gazdagép-relé: a kapcsolatok a Virtualization.framework NAT helyett a macOS-en futó Kiriből indulnak. A virtuális gép újraindításakor lép életbe.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "A környezetben be van állítva a KIRI_SHARED_NAT, és ez felülírja ezt.", + "Outbound VM traffic": "Kimenő VM-forgalom", + "macOS NAT": "macOS NAT", + "Host relay": "Gazdagép-relé", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "A virtuális gép lemezének maximális mérete. A tárhely csak adatok írásakor foglalódik el a rendszeren ({os}), a nem használt hely pedig visszanyerhető itt: {storage}. Újraindításkor lép életbe.", + "Settings → Storage": "Beállítások → Tárhely", + "VM disk space": "Virtuális gép lemezterülete", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "A natív Linux közvetlenül a gazdagép fájlrendszerét használja — a törölt image-ek és kötetek azonnal felszabadítják a helyet.", + "Compact disk…": "Lemez tömörítése…", + "Reclaim space": "Hely visszanyerése", + "Compacting…": "Tömörítés…", + "Reclaiming…": "Visszanyerés…", + "Compacting {vhdx} and restarting the engine…": "A(z) {vhdx} tömörítése és a motor újraindítása…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} a rendszeren ({os}), {inUse} használatban a virtuális gépen belül · nem használt blokkok felszabadítása…", + "Trimming unused blocks inside the VM disk…": "Nem használt blokkok felszabadítása a virtuális gép lemezén…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} Windowson ({vhdx}), {inUse} használatban · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} a rendszeren ({os}), {inUse} használatban a virtuális gépen belül · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} Windowson ({vhdx}), {inUse} használatban · nincs visszanyerhető hely.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} a rendszeren ({os}), {inUse} használatban a virtuális gépen belül · nincs visszanyerhető hely.", + "Nothing to reclaim.": "Nincs visszanyerhető hely.", + "{size} can be given back": "{size} visszaadható", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} Windowson ({vhdx}), {inUse} használatban · {can}. A tömörítés újraindítja a motort.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} a rendszeren ({os}), {inUse} használatban a virtuális gépen belül · {can} a konténerek leállítása nélkül.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} Windowson ({vhdx}). A tömörítés visszaadja a nem használt helyet, és újraindítja a motort.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} a rendszeren ({os}). A visszanyerés a konténerek leállítása nélkül szabadítja fel a nem használt blokkokat a virtuális gép lemezén.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Visszaadja a Windowsnak a(z) {vhdx} nem használt területét. A tömörítés újraindítja a motort.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "A konténerek leállítása nélkül visszaadja a rendszernek ({os}) a virtuális gép lemezének nem használt blokkjait.", + "Cleaning up stopped containers, untagged images, and build cache…": "Leállított konténerek, címke nélküli image-ek és a build-gyorsítótár tisztítása…", + "{count} ({size})": "{count} ({size})", + "build cache": "build-gyorsítótár", + "No stopped containers, untagged images or build cache · {freed}.": "Nincs leállított konténer, címke nélküli image vagy build-gyorsítótár · {freed}.", + "No stopped containers, untagged images or build cache.": "Nincs leállított konténer, címke nélküli image vagy build-gyorsítótár.", + "Cleaning up…": "Tisztítás…", + "Clean up…": "Tisztítás…", + "Unused Docker data": "Nem használt Docker-adatok", + "Command-line tools in shell": "Parancssori eszközök a shellben", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Hozzáadja a(z) {bin} elérési utat a(z) {zshrc} és {zprofile} fájlokhoz, hogy a {docker}, a {kubectl} és a {kiri} működjön az új terminálokban.", + "Uninstall Kiri": "A Kiri eltávolítása", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Leállítja a motort, eltávolítja a Kiri háttérszolgáltatását, a CLI-hivatkozásokat és a shell-profilbejegyzéseket, valamint visszaállítja az előző Docker-kontextust ({cmd}).", + "Uninstall Kiri…": "A Kiri eltávolítása…", + "Couldn't reclaim disk space: {error}": "Nem sikerült visszanyerni a lemezterületet: {error}", + "Reclaimed {size} on {os}": "{size} visszanyerve itt: {os}", + "Nothing to reclaim": "Nincs visszanyerhető hely", + "Couldn't clean up unused Docker data: {error}": "Nem sikerült megtisztítani a nem használt Docker-adatokat: {error}", + "Cleaned up {size} of unused Docker data": "{size} nem használt Docker-adat törölve", + "Cleaned up unused Docker data": "Nem használt Docker-adatok törölve", + "Compact WSL disk?": "Tömöríted a WSL-lemezt?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "A(z) {vhdx} tömörítése visszaadja a nem használt helyet a Windowsnak, és rövid időre újraindítja a Kiri motorját és a futó konténereket.", + "Compact disk": "Lemez tömörítése", + "Clean up unused Docker data?": "Törlöd a nem használt Docker-adatokat?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Eltávolítja a leállított konténereket, a címke nélküli image-eket és a BuildKit build-gyorsítótárát. A futó konténerek és a címkézett image-ek megmaradnak.", + "Clean up": "Tisztítás", + "Uninstall Kiri?": "Eltávolítod a Kirit?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Leállítja a motort, eltávolítja a Kiri háttérszolgáltatását, a CLI-hivatkozásokat és a shell-profilbejegyzéseket, valamint visszaállítja az előző Docker-kontextust. Az image-ek és a kötetek a Kiri adatmappájában maradnak, amíg nem törlöd azt.", + "Cluster": "Fürt", + "default": "alapértelmezett", + "k3s version": "k3s-verzió", + "Image version for the cluster node ({cmd}). Applies when recreated.": "A fürtcsomópont image-verziója ({cmd}). Újralétrehozáskor lép életbe.", + "Extra server flags": "További szerverkapcsolók", + "Passed to {srv} ({flag}), separated by spaces.": "Szóközökkel elválasztva átadva ennek: {srv} ({flag}).", + "Startup manifests": "Indítási manifesztumok", + "YAML files in {path} are applied whenever the cluster starts.": "A(z) {path} alatti YAML-fájlok a fürt minden indításakor alkalmazva lesznek.", + "Open folder": "Mappa megnyitása", + "{n} untagged image": "{n} címke nélküli image", + "{n} untagged images": "{n} címke nélküli image", + "Uninstall Kiri from Windows Settings → Apps": "Távolítsd el a Kirit a Windows Gépház → Alkalmazások alatt", + "Builder settings saved": "Builder-beállítások mentve", + "Could not save builder settings: {error}": "Nem sikerült menteni a builder beállításait: {error}", + "Disk reclaim is already running": "A lemezterület visszanyerése már folyamatban van", + "Outbound VM traffic setting saved. Restart the VM to apply.": "A kimenő VM-forgalom beállítása mentve. Az alkalmazáshoz indítsd újra a virtuális gépet.", + "Could not save VM networking setting: {error}": "Nem sikerült menteni a virtuális gép hálózati beállítását: {error}", + "Added Kiri command-line tools to shell profiles": "A Kiri parancssori eszközei hozzáadva a shell-profilokhoz", + "Removed Kiri command-line tools from shell profiles": "A Kiri parancssori eszközei eltávolítva a shell-profilokból", + "Could not update shell profiles: {error}": "Nem sikerült frissíteni a shell-profilokat: {error}", + "Uninstalling Kiri…": "A Kiri eltávolítása…", + "Could not uninstall Kiri: {error}": "Nem sikerült eltávolítani a Kirit: {error}", + "Uninstall Kiri using your system package manager": "Távolítsd el a Kirit a rendszer csomagkezelőjével" } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index a34f676bd..3be9fae91 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -1854,7 +1854,6 @@ "Disk image size": "Ukuran image disk", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB, atau KIRI_DISK_GB diatur untuk daemon, dan lebih diutamakan daripada pengaturan ini.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Berjalan sekarang dengan {cpus}, hingga {mem}, dan disk {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis; ukurannya tidak pernah menyusut. Berlaku setelah mulai ulang.", "No other WSL distros installed.": "Tidak ada distro WSL lain yang terinstal.", "WSL integration": "Integrasi WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Tutup: memori yang dipakai jendela dibebaskan. Perlu sesaat untuk membukanya lagi, dan terminal yang terbuka ditutup.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri dan PC ini", "Kiri and this computer": "Kiri dan komputer ini", "Versions, {os}, whether the engine runs, how many containers and images": "Versi, {os}, apakah engine berjalan, berapa banyak kontainer dan image", - "Saved. The engine uses these from its next start": "Disimpan. Engine memakainya mulai start berikutnya" + "Saved. The engine uses these from its next start": "Disimpan. Engine memakainya mulai start berikutnya", + "5 min": "5 mnt", + "10 min": "10 mnt", + "30 min": "30 mnt", + "Never": "Tidak pernah", + "Build cache limit": "Batas cache build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Layer cache terlama akan dipangkas otomatis setelah cache BuildKit melewati ukuran ini.", + "Stop builder when idle": "Hentikan builder saat menganggur", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Menghentikan BuildKit di sela-sela build agar tidak memakai memori saat menganggur; build berikutnya membangunkannya dalam kurang dari satu detik.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB atau KIRI_BUILDER_IDLE_SECS diatur untuk daemon, dan lebih diutamakan daripada pengaturan ini.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: paling cepat. Beralih ke Relai host jika Cloudflare WARP atau firewall kantor memblokir HTTPS kontainer. Berlaku setelah restart VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relai host: koneksi keluar dari Kiri di macOS alih-alih NAT Virtualization.framework. Berlaku setelah restart VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT diatur di environment dan lebih diutamakan.", + "Outbound VM traffic": "Trafik keluar VM", + "macOS NAT": "NAT macOS", + "Host relay": "Relai host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Batas maksimum pertumbuhan disk VM. Ruang di {os} hanya terpakai saat data ditulis, dan ruang tak terpakai bisa diklaim kembali di {storage}. Berlaku setelah mulai ulang.", + "Settings → Storage": "Pengaturan → Penyimpanan", + "VM disk space": "Ruang disk VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux native memakai filesystem host secara langsung — image dan volume yang dihapus langsung membebaskan ruang.", + "Compact disk…": "Padatkan disk…", + "Reclaim space": "Klaim ruang", + "Compacting…": "Memadatkan…", + "Reclaiming…": "Mengklaim…", + "Compacting {vhdx} and restarting the engine…": "Memadatkan {vhdx} dan me-restart engine…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} di {os}, {inUse} terpakai di dalam VM · memangkas blok tak terpakai…", + "Trimming unused blocks inside the VM disk…": "Memangkas blok tak terpakai di dalam disk VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} di Windows ({vhdx}), {inUse} terpakai · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} di {os}, {inUse} terpakai di dalam VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} di Windows ({vhdx}), {inUse} terpakai · tidak ada yang bisa diklaim.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} di {os}, {inUse} terpakai di dalam VM · tidak ada yang bisa diklaim.", + "Nothing to reclaim.": "Tidak ada yang bisa diklaim.", + "{size} can be given back": "{size} bisa dikembalikan", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} di Windows ({vhdx}), {inUse} terpakai · {can}. Memadatkan akan me-restart engine.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} di {os}, {inUse} terpakai di dalam VM · {can} tanpa menghentikan kontainer.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} di Windows ({vhdx}). Memadatkan akan mengembalikan ruang tak terpakai dan me-restart engine.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} di {os}. Mengklaim ruang memangkas blok tak terpakai di disk VM tanpa menghentikan kontainer.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Mengembalikan ruang tak terpakai di {vhdx} ke Windows. Memadatkan akan me-restart engine.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Mengembalikan blok tak terpakai di disk VM ke {os} tanpa menghentikan kontainer.", + "Cleaning up stopped containers, untagged images, and build cache…": "Membersihkan kontainer berhenti, image tanpa tag, dan cache build…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache build", + "No stopped containers, untagged images or build cache · {freed}.": "Tidak ada kontainer berhenti, image tanpa tag, atau cache build · {freed}.", + "No stopped containers, untagged images or build cache.": "Tidak ada kontainer berhenti, image tanpa tag, atau cache build.", + "Cleaning up…": "Membersihkan…", + "Clean up…": "Bersihkan…", + "Unused Docker data": "Data Docker tak terpakai", + "Command-line tools in shell": "Alat baris perintah di shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Tambahkan {bin} ke {zshrc} dan {zprofile} agar {docker}, {kubectl}, dan {kiri} berfungsi di terminal baru.", + "Uninstall Kiri": "Hapus instalasi Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Menghentikan engine, menghapus layanan latar belakang Kiri, tautan CLI, dan entri profil shell, lalu memulihkan konteks Docker sebelumnya ({cmd}).", + "Uninstall Kiri…": "Hapus instalasi Kiri…", + "Couldn't reclaim disk space: {error}": "Tidak bisa mengklaim ruang disk: {error}", + "Reclaimed {size} on {os}": "Berhasil mengklaim {size} di {os}", + "Nothing to reclaim": "Tidak ada yang bisa diklaim", + "Couldn't clean up unused Docker data: {error}": "Tidak bisa membersihkan data Docker tak terpakai: {error}", + "Cleaned up {size} of unused Docker data": "Membersihkan {size} data Docker tak terpakai", + "Cleaned up unused Docker data": "Data Docker tak terpakai dibersihkan", + "Compact WSL disk?": "Padatkan disk WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Memadatkan {vhdx} mengembalikan ruang tak terpakai ke Windows dan me-restart sebentar engine Kiri serta kontainer yang berjalan.", + "Compact disk": "Padatkan disk", + "Clean up unused Docker data?": "Bersihkan data Docker tak terpakai?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Menghapus kontainer berhenti, image tanpa tag, dan cache build BuildKit. Kontainer yang berjalan dan image dengan tag tetap disimpan.", + "Clean up": "Bersihkan", + "Uninstall Kiri?": "Hapus instalasi Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Menghentikan engine, menghapus layanan latar belakang Kiri, tautan CLI, dan entri profil shell, lalu memulihkan konteks Docker sebelumnya. Image dan volume Anda tetap ada di folder data Kiri sampai Anda menghapusnya.", + "Cluster": "Cluster", + "default": "bawaan", + "k3s version": "Versi k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versi image untuk node cluster ({cmd}). Berlaku saat dibuat ulang.", + "Extra server flags": "Flag server tambahan", + "Passed to {srv} ({flag}), separated by spaces.": "Diteruskan ke {srv} ({flag}), dipisahkan dengan spasi.", + "Startup manifests": "Manifes saat mulai", + "YAML files in {path} are applied whenever the cluster starts.": "File YAML di {path} diterapkan setiap kali cluster dimulai.", + "Open folder": "Buka folder", + "{n} untagged image": "{n} image tanpa tag", + "{n} untagged images": "{n} image tanpa tag", + "Uninstall Kiri from Windows Settings → Apps": "Hapus instalasi Kiri dari Pengaturan Windows → Aplikasi", + "Builder settings saved": "Pengaturan builder disimpan", + "Could not save builder settings: {error}": "Tidak bisa menyimpan pengaturan builder: {error}", + "Disk reclaim is already running": "Klaim ruang disk sudah berjalan", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Pengaturan trafik keluar VM disimpan. Restart VM untuk menerapkan.", + "Could not save VM networking setting: {error}": "Tidak bisa menyimpan pengaturan jaringan VM: {error}", + "Added Kiri command-line tools to shell profiles": "Alat baris perintah Kiri ditambahkan ke profil shell", + "Removed Kiri command-line tools from shell profiles": "Alat baris perintah Kiri dihapus dari profil shell", + "Could not update shell profiles: {error}": "Tidak bisa memperbarui profil shell: {error}", + "Uninstalling Kiri…": "Menghapus instalasi Kiri…", + "Could not uninstall Kiri: {error}": "Tidak bisa menghapus instalasi Kiri: {error}", + "Uninstall Kiri using your system package manager": "Hapus instalasi Kiri menggunakan manajer paket sistem Anda" } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 541c2f004..ccdda15f9 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -1854,7 +1854,6 @@ "Disk image size": "Dimensione immagine disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB o KIRI_DISK_GB è impostata per il daemon e ha la precedenza su questi valori.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Ora in esecuzione con {cpus}, fino a {mem} e un disco da {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati; non si riduce mai. Si applica al riavvio.", "No other WSL distros installed.": "Nessun’altra distribuzione WSL installata.", "WSL integration": "Integrazione WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Chiudi: la memoria usata dalla finestra viene liberata. Ci vuole un attimo per riaprirla e i terminali aperti si chiudono.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri e questo PC", "Kiri and this computer": "Kiri e questo computer", "Versions, {os}, whether the engine runs, how many containers and images": "Versioni, {os}, se il motore è in esecuzione, quanti container e immagini", - "Saved. The engine uses these from its next start": "Salvato. Il motore li usa dal prossimo avvio" + "Saved. The engine uses these from its next start": "Salvato. Il motore li usa dal prossimo avvio", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Mai", + "Build cache limit": "Limite cache di build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "I layer in cache più vecchi vengono rimossi automaticamente quando la cache di BuildKit supera questa dimensione.", + "Stop builder when idle": "Ferma il builder se inattivo", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Ferma BuildKit tra una build e l’altra così non usa memoria quando è inattivo; la build successiva lo riattiva in meno di un secondo.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB o KIRI_BUILDER_IDLE_SECS è impostata per il daemon e ha la precedenza su questi valori.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: il più veloce. Passa a Relay host se Cloudflare WARP o un firewall aziendale blocca HTTPS dei container. Si applica al riavvio della VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relay host: le connessioni escono da Kiri su macOS invece che dal NAT di Virtualization.framework. Si applica al riavvio della VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT è impostata nell’ambiente e ha la precedenza.", + "Outbound VM traffic": "Traffico in uscita della VM", + "macOS NAT": "NAT macOS", + "Host relay": "Relay host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "La dimensione massima a cui può crescere il disco della VM. Lo spazio su {os} viene usato solo man mano che si scrivono dati, e lo spazio inutilizzato può essere recuperato in {storage}. Si applica al riavvio.", + "Settings → Storage": "Impostazioni → Archiviazione", + "VM disk space": "Spazio su disco della VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux nativo usa direttamente il filesystem dell’host — le immagini e i volumi eliminati liberano spazio immediatamente.", + "Compact disk…": "Compatta disco…", + "Reclaim space": "Recupera spazio", + "Compacting…": "Compattazione…", + "Reclaiming…": "Recupero…", + "Compacting {vhdx} and restarting the engine…": "Compattazione di {vhdx} e riavvio del motore…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} su {os}, {inUse} in uso nella VM · pulizia dei blocchi inutilizzati…", + "Trimming unused blocks inside the VM disk…": "Pulizia dei blocchi inutilizzati nel disco della VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} su Windows ({vhdx}), {inUse} in uso · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} su {os}, {inUse} in uso nella VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} su Windows ({vhdx}), {inUse} in uso · niente da recuperare.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} su {os}, {inUse} in uso nella VM · niente da recuperare.", + "Nothing to reclaim.": "Niente da recuperare.", + "{size} can be given back": "{size} possono essere restituiti", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} su Windows ({vhdx}), {inUse} in uso · {can}. La compattazione riavvia il motore.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} su {os}, {inUse} in uso nella VM · {can} senza fermare i container.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} su Windows ({vhdx}). La compattazione restituisce lo spazio inutilizzato e riavvia il motore.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} su {os}. Il recupero libera i blocchi inutilizzati nel disco della VM senza fermare i container.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Restituisce a Windows lo spazio inutilizzato in {vhdx}. La compattazione riavvia il motore.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Restituisce a {os} i blocchi inutilizzati nel disco della VM senza fermare i container.", + "Cleaning up stopped containers, untagged images, and build cache…": "Pulizia dei container fermi, delle immagini senza tag e della cache di build…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache di build", + "No stopped containers, untagged images or build cache · {freed}.": "Nessun container fermo, immagine senza tag o cache di build · {freed}.", + "No stopped containers, untagged images or build cache.": "Nessun container fermo, immagine senza tag o cache di build.", + "Cleaning up…": "Pulizia…", + "Clean up…": "Pulisci…", + "Unused Docker data": "Dati Docker inutilizzati", + "Command-line tools in shell": "Strumenti da riga di comando nella shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Aggiungi {bin} a {zshrc} e {zprofile} affinché {docker}, {kubectl} e {kiri} funzionino nei nuovi terminali.", + "Uninstall Kiri": "Disinstalla Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Ferma il motore, rimuove il servizio in background di Kiri, i collegamenti CLI e le voci dei profili shell, e ripristina il contesto Docker precedente ({cmd}).", + "Uninstall Kiri…": "Disinstalla Kiri…", + "Couldn't reclaim disk space: {error}": "Impossibile recuperare spazio su disco: {error}", + "Reclaimed {size} on {os}": "Recuperati {size} su {os}", + "Nothing to reclaim": "Niente da recuperare", + "Couldn't clean up unused Docker data: {error}": "Impossibile pulire i dati Docker inutilizzati: {error}", + "Cleaned up {size} of unused Docker data": "Rimossi {size} di dati Docker inutilizzati", + "Cleaned up unused Docker data": "Dati Docker inutilizzati rimossi", + "Compact WSL disk?": "Compattare il disco WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "La compattazione di {vhdx} restituisce lo spazio inutilizzato a Windows e riavvia brevemente il motore di Kiri e i container in esecuzione.", + "Compact disk": "Compatta disco", + "Clean up unused Docker data?": "Pulire i dati Docker inutilizzati?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Rimuove i container fermi, le immagini senza tag e la cache di build di BuildKit. I container in esecuzione e le immagini con tag vengono mantenuti.", + "Clean up": "Pulisci", + "Uninstall Kiri?": "Disinstallare Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Ferma il motore, rimuove il servizio in background di Kiri, i collegamenti CLI e le voci dei profili shell, e ripristina il contesto Docker precedente. Immagini e volumi restano nella cartella dati di Kiri finché non la elimini.", + "Cluster": "Cluster", + "default": "predefinita", + "k3s version": "Versione di k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versione dell’immagine per il nodo del cluster ({cmd}). Si applica quando viene ricreato.", + "Extra server flags": "Flag aggiuntivi del server", + "Passed to {srv} ({flag}), separated by spaces.": "Passati a {srv} ({flag}), separati da spazi.", + "Startup manifests": "Manifest di avvio", + "YAML files in {path} are applied whenever the cluster starts.": "I file YAML in {path} vengono applicati a ogni avvio del cluster.", + "Open folder": "Apri cartella", + "{n} untagged image": "{n} immagine senza tag", + "{n} untagged images": "{n} immagini senza tag", + "Uninstall Kiri from Windows Settings → Apps": "Disinstalla Kiri da Impostazioni di Windows → App", + "Builder settings saved": "Impostazioni del builder salvate", + "Could not save builder settings: {error}": "Impossibile salvare le impostazioni del builder: {error}", + "Disk reclaim is already running": "Il recupero dello spazio su disco è già in corso", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Impostazione del traffico in uscita della VM salvata. Riavvia la VM per applicarla.", + "Could not save VM networking setting: {error}": "Impossibile salvare l’impostazione di rete della VM: {error}", + "Added Kiri command-line tools to shell profiles": "Strumenti da riga di comando di Kiri aggiunti ai profili shell", + "Removed Kiri command-line tools from shell profiles": "Strumenti da riga di comando di Kiri rimossi dai profili shell", + "Could not update shell profiles: {error}": "Impossibile aggiornare i profili shell: {error}", + "Uninstalling Kiri…": "Disinstallazione di Kiri…", + "Could not uninstall Kiri: {error}": "Impossibile disinstallare Kiri: {error}", + "Uninstall Kiri using your system package manager": "Disinstalla Kiri usando il gestore di pacchetti del sistema" } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index a83dbf061..dae93c701 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -1854,7 +1854,6 @@ "Disk image size": "ディスクイメージのサイズ", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "デーモンに KIRI_CPUS、KIRI_MEMORY_MIB、または KIRI_DISK_GB が設定されており、こちらの設定より優先されます。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "現在 {cpus}、最大 {mem}、{disk} ディスクで実行中です。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、縮小することはありません。再起動時に適用されます。", "No other WSL distros installed.": "他の WSL ディストリビューションはインストールされていません。", "WSL integration": "WSL 統合", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "閉じる:ウインドウが使うメモリを解放します。再び開くまでに少し時間がかかり、開いているターミナルは終了します。", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri とこの PC", "Kiri and this computer": "Kiri とこのコンピュータ", "Versions, {os}, whether the engine runs, how many containers and images": "バージョン、{os}、エンジンの実行状況、コンテナとイメージの数", - "Saved. The engine uses these from its next start": "保存しました。エンジンは次回の起動時からこの設定を使用します" + "Saved. The engine uses these from its next start": "保存しました。エンジンは次回の起動時からこの設定を使用します", + "5 min": "5 分", + "10 min": "10 分", + "30 min": "30 分", + "Never": "しない", + "Build cache limit": "ビルドキャッシュの上限", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit のキャッシュがこのサイズを超えると、古いキャッシュレイヤーから自動的に削除されます。", + "Stop builder when idle": "アイドル時にビルダーを停止", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "ビルドの合間に BuildKit を停止して待機中のメモリ使用をゼロにします。次のビルド時に 1 秒未満で復帰します。", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "デーモンに KIRI_BUILD_CACHE_GB または KIRI_BUILDER_IDLE_SECS が設定されており、こちらの設定より優先されます。", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT:最速です。Cloudflare WARP や社内ファイアウォールでコンテナの HTTPS がブロックされる場合はホストリレーに切り替えてください。VM の再起動時に適用されます。", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "ホストリレー:Virtualization.framework の NAT ではなく macOS 上の Kiri から通信します。VM の再起動時に適用されます。", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "環境変数 KIRI_SHARED_NAT が設定されており、優先されます。", + "Outbound VM traffic": "VM の外向き通信", + "macOS NAT": "macOS NAT", + "Host relay": "ホストリレー", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM ディスクが拡張できる上限です。{os} 上の容量はデータが書き込まれた分だけ使用され、未使用の領域は {storage} で回収できます。再起動時に適用されます。", + "Settings → Storage": "設定 → ストレージ", + "VM disk space": "VM ディスク領域", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "ネイティブ Linux はホストのファイルシステムを直接使用するため、削除したイメージやボリュームの領域はすぐに解放されます。", + "Compact disk…": "ディスクを圧縮…", + "Reclaim space": "領域を回収", + "Compacting…": "圧縮中…", + "Reclaiming…": "回収中…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} を圧縮してエンジンを再起動しています…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} 上で {host}、VM 内で {inUse} 使用中 · 未使用ブロックをトリムしています…", + "Trimming unused blocks inside the VM disk…": "VM ディスク内の未使用ブロックをトリムしています…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows 上で {host}({vhdx})、{inUse} 使用中 · {freed}。", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} 上で {host}、VM 内で {inUse} 使用中 · {freed}。", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows 上で {host}({vhdx})、{inUse} 使用中 · 回収できる領域はありません。", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} 上で {host}、VM 内で {inUse} 使用中 · 回収できる領域はありません。", + "Nothing to reclaim.": "回収できる領域はありません。", + "{size} can be given back": "{size} を返せます", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows 上で {host}({vhdx})、{inUse} 使用中 · {can}。圧縮するとエンジンが再起動します。", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} 上で {host}、VM 内で {inUse} 使用中 · コンテナを止めずに {can}。", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows 上で {host}({vhdx})。圧縮すると未使用領域を返却し、エンジンを再起動します。", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} 上で {host}。コンテナを止めずに VM ディスク内の未使用ブロックをトリムします。", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} の未使用領域を Windows に返します。圧縮するとエンジンが再起動します。", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "コンテナを止めずに VM ディスク内の未使用ブロックを {os} に返します。", + "Cleaning up stopped containers, untagged images, and build cache…": "停止中のコンテナ、タグなしイメージ、ビルドキャッシュをクリーンアップしています…", + "{count} ({size})": "{count}({size})", + "build cache": "ビルドキャッシュ", + "No stopped containers, untagged images or build cache · {freed}.": "停止中のコンテナ、タグなしイメージ、ビルドキャッシュはありません · {freed}。", + "No stopped containers, untagged images or build cache.": "停止中のコンテナ、タグなしイメージ、ビルドキャッシュはありません。", + "Cleaning up…": "クリーンアップ中…", + "Clean up…": "クリーンアップ…", + "Unused Docker data": "未使用の Docker データ", + "Command-line tools in shell": "シェルのコマンドラインツール", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "{zshrc} と {zprofile} に {bin} を追加し、新しいターミナルで {docker}、{kubectl}、{kiri} を使えるようにします。", + "Uninstall Kiri": "Kiri をアンインストール", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "エンジンを停止し、Kiri のバックグラウンドサービス、CLI リンク、シェルプロファイルの設定を削除して、以前の Docker コンテキストを復元します({cmd})。", + "Uninstall Kiri…": "Kiri をアンインストール…", + "Couldn't reclaim disk space: {error}": "ディスク領域を回収できませんでした:{error}", + "Reclaimed {size} on {os}": "{os} で {size} を回収しました", + "Nothing to reclaim": "回収できる領域はありません", + "Couldn't clean up unused Docker data: {error}": "未使用の Docker データをクリーンアップできませんでした:{error}", + "Cleaned up {size} of unused Docker data": "未使用の Docker データを {size} クリーンアップしました", + "Cleaned up unused Docker data": "未使用の Docker データをクリーンアップしました", + "Compact WSL disk?": "WSL ディスクを圧縮しますか?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} を圧縮すると未使用領域が Windows に返され、Kiri のエンジンと実行中のコンテナが一時的に再起動します。", + "Compact disk": "ディスクを圧縮", + "Clean up unused Docker data?": "未使用の Docker データをクリーンアップしますか?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "停止中のコンテナ、タグなしイメージ、BuildKit のビルドキャッシュを削除します。実行中のコンテナとタグ付きイメージは保持されます。", + "Clean up": "クリーンアップ", + "Uninstall Kiri?": "Kiri をアンインストールしますか?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "エンジンを停止し、Kiri のバックグラウンドサービス、CLI リンク、シェルプロファイルの設定を削除して、以前の Docker コンテキストを復元します。イメージとボリュームは、Kiri のデータフォルダーを削除するまで残ります。", + "Cluster": "クラスタ", + "default": "デフォルト", + "k3s version": "k3s のバージョン", + "Image version for the cluster node ({cmd}). Applies when recreated.": "クラスタノードのイメージバージョン({cmd})。再作成時に適用されます。", + "Extra server flags": "追加のサーバフラグ", + "Passed to {srv} ({flag}), separated by spaces.": "スペース区切りで {srv}({flag})に渡されます。", + "Startup manifests": "起動マニフェスト", + "YAML files in {path} are applied whenever the cluster starts.": "{path} 内の YAML ファイルはクラスタの起動時に毎回適用されます。", + "Open folder": "フォルダーを開く", + "{n} untagged image": "タグなしイメージ {n} 個", + "{n} untagged images": "タグなしイメージ {n} 個", + "Uninstall Kiri from Windows Settings → Apps": "Windows の設定 → アプリから Kiri をアンインストールしてください", + "Builder settings saved": "ビルダー設定を保存しました", + "Could not save builder settings: {error}": "ビルダー設定を保存できませんでした:{error}", + "Disk reclaim is already running": "ディスク領域の回収はすでに実行中です", + "Outbound VM traffic setting saved. Restart the VM to apply.": "VM の外向き通信設定を保存しました。VM を再起動すると適用されます。", + "Could not save VM networking setting: {error}": "VM のネットワーク設定を保存できませんでした:{error}", + "Added Kiri command-line tools to shell profiles": "Kiri のコマンドラインツールをシェルプロファイルに追加しました", + "Removed Kiri command-line tools from shell profiles": "Kiri のコマンドラインツールをシェルプロファイルから削除しました", + "Could not update shell profiles: {error}": "シェルプロファイルを更新できませんでした:{error}", + "Uninstalling Kiri…": "Kiri をアンインストールしています…", + "Could not uninstall Kiri: {error}": "Kiri をアンインストールできませんでした:{error}", + "Uninstall Kiri using your system package manager": "システムのパッケージマネージャーで Kiri をアンインストールしてください" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 6622bfb1c..3f4882ae2 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -1854,7 +1854,6 @@ "Disk image size": "Диск кескінінің өлшемі", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Демон үшін KIRI_CPUS, KIRI_MEMORY_MIB немесе KIRI_DISK_GB орнатылған және ол осы баптаулардан басым.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Қазір {cpus}, {mem} дейінгі жад және {disk} дискімен жұмыс істеп тұр.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады; ол ешқашан кішіреймейді. Қайта іске қосқанда қолданылады.", "No other WSL distros installed.": "Басқа WSL дистрибутивтері орнатылмаған.", "WSL integration": "WSL интеграциясы", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Жабу: терезе пайдаланатын жад босатылады. Қайта ашылуына біраз уақыт кетеді, ал ашық терминалдар жабылады.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri және осы ДК", "Kiri and this computer": "Kiri және осы компьютер", "Versions, {os}, whether the engine runs, how many containers and images": "Нұсқалар, {os}, қозғалтқыштың жұмыс істеп тұрғаны, контейнерлер мен образдар саны", - "Saved. The engine uses these from its next start": "Сақталды. Қозғалтқыш оларды келесі іске қосылғанда пайдаланады" + "Saved. The engine uses these from its next start": "Сақталды. Қозғалтқыш оларды келесі іске қосылғанда пайдаланады", + "5 min": "5 мин", + "10 min": "10 мин", + "30 min": "30 мин", + "Never": "Ешқашан", + "Build cache limit": "Құрастыру кэшінің шегі", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit кэші осы өлшемнен асқанда ең ескі кэштелген қабаттар автоматты түрде тазартылады.", + "Stop builder when idle": "Бос тұрғанда құрастырушыны тоқтату", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Бос кезде жад жұмсамауы үшін құрастырулар арасында BuildKit-ті тоқтатады; келесі құрастыру оны бір секундқа жеткізбей оятады.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Демон үшін KIRI_BUILD_CACHE_GB немесе KIRI_BUILDER_IDLE_SECS орнатылған және ол осы баптаулардан басым.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: ең жылдамы. Егер Cloudflare WARP немесе корпоративтік желіаралық қалқан контейнерлердің HTTPS трафигін бұғаттаса, Хост релесі режиміне ауысыңыз. Виртуалды машинаны қайта іске қосқанда қолданылады.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Хост релесі: қосылымдар Virtualization.framework NAT орнына macOS жүйесіндегі Kiri арқылы шығады. Виртуалды машинаны қайта іске қосқанда қолданылады.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Ортада KIRI_SHARED_NAT орнатылған және ол басымдыққа ие.", + "Outbound VM traffic": "Виртуалды машинаның шығыс трафигі", + "macOS NAT": "macOS NAT", + "Host relay": "Хост релесі", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Виртуалды машина дискі өсе алатын ең үлкен өлшем. {os} жүйесінде орын тек деректер жазылғанда ғана алынады, ал пайдаланылмайтын орынды {storage} бөлімінде қайтаруға болады. Қайта іске қосқанда қолданылады.", + "Settings → Storage": "Параметрлер → Сақтау орны", + "VM disk space": "Виртуалды машинаның диск орны", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Жергілікті Linux хосттың файлдық жүйесін тікелей пайдаланады — жойылған образдар мен томдар орынды бірден босатады.", + "Compact disk…": "Дискіні тығыздау…", + "Reclaim space": "Орынды қайтару", + "Compacting…": "Тығыздалуда…", + "Reclaiming…": "Қайтарылуда…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} тығыздалуда және қозғалтқыш қайта іске қосылуда…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} жүйесінде {host}, виртуалды машина ішінде {inUse} пайдаланылуда · пайдаланылмайтын блоктар босатылуда…", + "Trimming unused blocks inside the VM disk…": "Виртуалды машина дискісіндегі пайдаланылмайтын блоктар босатылуда…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows жүйесінде {host} ({vhdx}), {inUse} пайдаланылуда · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} жүйесінде {host}, виртуалды машина ішінде {inUse} пайдаланылуда · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows жүйесінде {host} ({vhdx}), {inUse} пайдаланылуда · қайтаратын ештеңе жоқ.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} жүйесінде {host}, виртуалды машина ішінде {inUse} пайдаланылуда · қайтаратын ештеңе жоқ.", + "Nothing to reclaim.": "Қайтаратын ештеңе жоқ.", + "{size} can be given back": "{size} қайтаруға болады", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows жүйесінде {host} ({vhdx}), {inUse} пайдаланылуда · {can}. Тығыздау қозғалтқышты қайта іске қосады.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} жүйесінде {host}, виртуалды машина ішінде {inUse} пайдаланылуда · контейнерлерді тоқтатпай {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows жүйесінде {host} ({vhdx}). Тығыздау пайдаланылмайтын орынды қайтарады және қозғалтқышты қайта іске қосады.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} жүйесінде {host}. Орынды қайтару контейнерлерді тоқтатпай виртуалды машина дискісіндегі бос блоктарды босатады.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} ішіндегі пайдаланылмайтын орынды Windows жүйесіне қайтарады. Тығыздау қозғалтқышты қайта іске қосады.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Контейнерлерді тоқтатпай виртуалды машина дискісіндегі пайдаланылмайтын блоктарды {os} жүйесіне қайтарады.", + "Cleaning up stopped containers, untagged images, and build cache…": "Тоқтатылған контейнерлер, тегсіз образдар және құрастыру кэші тазартылуда…", + "{count} ({size})": "{count} ({size})", + "build cache": "құрастыру кэші", + "No stopped containers, untagged images or build cache · {freed}.": "Тоқтатылған контейнерлер, тегсіз образдар немесе құрастыру кэші жоқ · {freed}.", + "No stopped containers, untagged images or build cache.": "Тоқтатылған контейнерлер, тегсіз образдар немесе құрастыру кэші жоқ.", + "Cleaning up…": "Тазартылуда…", + "Clean up…": "Тазарту…", + "Unused Docker data": "Пайдаланылмайтын Docker деректері", + "Command-line tools in shell": "Shell ішіндегі пәрмен жолы құралдары", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Жаңа терминалдарда {docker}, {kubectl} және {kiri} жұмыс істеуі үшін {bin} жолын {zshrc} мен {zprofile} файлдарына қосыңыз.", + "Uninstall Kiri": "Kiri-ді өшіру", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Қозғалтқышты тоқтатады, Kiri фондық қызметін, CLI сілтемелерін және shell профилі жазбаларын жояды, сондай-ақ алдыңғы Docker контекстін қалпына келтіреді ({cmd}).", + "Uninstall Kiri…": "Kiri-ді өшіру…", + "Couldn't reclaim disk space: {error}": "Диск орнын қайтару мүмкін болмады: {error}", + "Reclaimed {size} on {os}": "{os} жүйесінде {size} қайтарылды", + "Nothing to reclaim": "Қайтаратын ештеңе жоқ", + "Couldn't clean up unused Docker data: {error}": "Пайдаланылмайтын Docker деректерін тазарту мүмкін болмады: {error}", + "Cleaned up {size} of unused Docker data": "{size} пайдаланылмайтын Docker деректері тазартылды", + "Cleaned up unused Docker data": "Пайдаланылмайтын Docker деректері тазартылды", + "Compact WSL disk?": "WSL дискісін тығыздау керек пе?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} файлын тығыздау пайдаланылмайтын орынды Windows жүйесіне қайтарады және Kiri қозғалтқышы мен жұмыс істеп тұрған контейнерлерді қысқа уақытқа қайта іске қосады.", + "Compact disk": "Дискіні тығыздау", + "Clean up unused Docker data?": "Пайдаланылмайтын Docker деректерін тазарту керек пе?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Тоқтатылған контейнерлерді, тегсіз образдарды және BuildKit құрастыру кэшін жояды. Жұмыс істеп тұрған контейнерлер мен тегі бар образдар сақталады.", + "Clean up": "Тазарту", + "Uninstall Kiri?": "Kiri-ді өшіру керек пе?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Қозғалтқышты тоқтатады, Kiri фондық қызметін, CLI сілтемелерін және shell профилі жазбаларын жояды, сондай-ақ алдыңғы Docker контекстін қалпына келтіреді. Образдар мен томдар Kiri деректер қалтасын өзіңіз жойғанша сонда қалады.", + "Cluster": "Кластер", + "default": "әдепкі", + "k3s version": "k3s нұсқасы", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Кластер түйініне арналған образ нұсқасы ({cmd}). Қайта жасалғанда қолданылады.", + "Extra server flags": "Сервердің қосымша жалаушалары", + "Passed to {srv} ({flag}), separated by spaces.": "Бос орын арқылы бөлініп, {srv} ({flag}) пәрменіне беріледі.", + "Startup manifests": "Іске қосу манифесттері", + "YAML files in {path} are applied whenever the cluster starts.": "{path} ішіндегі YAML файлдары кластер іске қосылған сайын қолданылады.", + "Open folder": "Қалтаны ашу", + "{n} untagged image": "{n} тегсіз образ", + "{n} untagged images": "{n} тегсіз образ", + "Uninstall Kiri from Windows Settings → Apps": "Kiri-ді Windows Параметрлер → Қолданбалар бөлімінен өшіріңіз", + "Builder settings saved": "Құрастырушы параметрлері сақталды", + "Could not save builder settings: {error}": "Құрастырушы параметрлерін сақтау мүмкін болмады: {error}", + "Disk reclaim is already running": "Диск орнын қайтару әлдеқашан орындалып жатыр", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Виртуалды машинаның шығыс трафигі параметрі сақталды. Қолдану үшін виртуалды машинаны қайта іске қосыңыз.", + "Could not save VM networking setting: {error}": "Виртуалды машинаның желі параметрін сақтау мүмкін болмады: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri пәрмен жолы құралдары shell профильдеріне қосылды", + "Removed Kiri command-line tools from shell profiles": "Kiri пәрмен жолы құралдары shell профильдерінен алынды", + "Could not update shell profiles: {error}": "Shell профильдерін жаңарту мүмкін болмады: {error}", + "Uninstalling Kiri…": "Kiri өшірілуде…", + "Could not uninstall Kiri: {error}": "Kiri-ді өшіру мүмкін болмады: {error}", + "Uninstall Kiri using your system package manager": "Kiri-ді жүйенің пакет менеджері арқылы өшіріңіз" } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 7f610e4f9..40e624847 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -1854,7 +1854,6 @@ "Disk image size": "디스크 이미지 크기", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "데몬에 KIRI_CPUS, KIRI_MEMORY_MIB 또는 KIRI_DISK_GB가 설정되어 있어 이 값보다 우선합니다.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "지금 {cpus}, 최대 {mem}, {disk} 디스크로 실행 중입니다.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며 줄어들지 않습니다. 재시작 시 적용됩니다.", "No other WSL distros installed.": "설치된 다른 WSL 배포판이 없습니다.", "WSL integration": "WSL 통합", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "닫기: 창이 쓰는 메모리를 해제합니다. 다시 여는 데 잠시 걸리며, 열려 있는 터미널은 종료됩니다.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri와 이 PC", "Kiri and this computer": "Kiri와 이 컴퓨터", "Versions, {os}, whether the engine runs, how many containers and images": "버전, {os}, 엔진 실행 여부, 컨테이너와 이미지 개수", - "Saved. The engine uses these from its next start": "저장했습니다. 엔진은 다음 시작부터 이 값을 사용합니다" + "Saved. The engine uses these from its next start": "저장했습니다. 엔진은 다음 시작부터 이 값을 사용합니다", + "5 min": "5분", + "10 min": "10분", + "30 min": "30분", + "Never": "안 함", + "Build cache limit": "빌드 캐시 한도", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit 캐시가 이 크기를 넘으면 가장 오래된 캐시 레이어부터 자동으로 정리됩니다.", + "Stop builder when idle": "유휴 시 빌더 중지", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "유휴 상태에서 메모리를 쓰지 않도록 빌드 사이에 BuildKit을 중지합니다. 다음 빌드 시 1초 안에 다시 깨어납니다.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "데몬에 KIRI_BUILD_CACHE_GB 또는 KIRI_BUILDER_IDLE_SECS가 설정되어 있어 이 값보다 우선합니다.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: 가장 빠릅니다. Cloudflare WARP나 사내 방화벽이 컨테이너 HTTPS를 차단하면 호스트 릴레이로 전환하세요. VM 다시 시작 시 적용됩니다.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "호스트 릴레이: 연결이 Virtualization.framework NAT 대신 macOS의 Kiri를 통해 나갑니다. VM 다시 시작 시 적용됩니다.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "환경 변수에 KIRI_SHARED_NAT이 설정되어 있어 우선 적용됩니다.", + "Outbound VM traffic": "VM 외부 통신", + "macOS NAT": "macOS NAT", + "Host relay": "호스트 릴레이", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM 디스크가 커질 수 있는 최대 크기입니다. {os}의 공간은 데이터를 쓸 때만 사용되며, 사용하지 않는 공간은 {storage}에서 회수할 수 있습니다. 재시작 시 적용됩니다.", + "Settings → Storage": "설정 → 저장 장치", + "VM disk space": "VM 디스크 공간", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "네이티브 Linux는 호스트 파일시스템을 직접 사용하므로 이미지나 볼륨을 삭제하면 공간이 즉시 확보됩니다.", + "Compact disk…": "디스크 압축…", + "Reclaim space": "공간 회수", + "Compacting…": "압축 중…", + "Reclaiming…": "회수 중…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} 압축 및 엔진 다시 시작 중…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os}에서 {host}, VM 내부 {inUse} 사용 중 · 미사용 블록 정리 중…", + "Trimming unused blocks inside the VM disk…": "VM 디스크 내부의 미사용 블록 정리 중…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows에서 {host}({vhdx}), {inUse} 사용 중 · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os}에서 {host}, VM 내부 {inUse} 사용 중 · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows에서 {host}({vhdx}), {inUse} 사용 중 · 회수할 공간 없음.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os}에서 {host}, VM 내부 {inUse} 사용 중 · 회수할 공간 없음.", + "Nothing to reclaim.": "회수할 공간이 없습니다.", + "{size} can be given back": "{size} 반환 가능", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows에서 {host}({vhdx}), {inUse} 사용 중 · {can}. 압축하면 엔진을 다시 시작합니다.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os}에서 {host}, VM 내부 {inUse} 사용 중 · 컨테이너를 멈추지 않고 {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows에서 {host}({vhdx}). 압축하면 사용하지 않는 공간을 반환하고 엔진을 다시 시작합니다.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os}에서 {host}. 공간을 회수하면 컨테이너를 멈추지 않고 VM 디스크의 미사용 블록을 정리합니다.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx}의 미사용 공간을 Windows에 반환합니다. 압축하면 엔진을 다시 시작합니다.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "컨테이너를 멈추지 않고 VM 디스크의 미사용 블록을 {os}에 반환합니다.", + "Cleaning up stopped containers, untagged images, and build cache…": "중지된 컨테이너, 태그 없는 이미지, 빌드 캐시 정리 중…", + "{count} ({size})": "{count}({size})", + "build cache": "빌드 캐시", + "No stopped containers, untagged images or build cache · {freed}.": "중지된 컨테이너, 태그 없는 이미지, 빌드 캐시 없음 · {freed}.", + "No stopped containers, untagged images or build cache.": "중지된 컨테이너, 태그 없는 이미지, 빌드 캐시가 없습니다.", + "Cleaning up…": "정리 중…", + "Clean up…": "정리…", + "Unused Docker data": "사용하지 않는 Docker 데이터", + "Command-line tools in shell": "셸의 명령줄 도구", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "새 터미널에서 {docker}, {kubectl}, {kiri}가 작동하도록 {zshrc}와 {zprofile}에 {bin}을(를) 추가합니다.", + "Uninstall Kiri": "Kiri 제거", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "엔진을 중지하고 Kiri의 백그라운드 서비스, CLI 링크, 셸 프로필 항목을 제거한 뒤 이전 Docker 컨텍스트를 복원합니다({cmd}).", + "Uninstall Kiri…": "Kiri 제거…", + "Couldn't reclaim disk space: {error}": "디스크 공간을 회수할 수 없습니다: {error}", + "Reclaimed {size} on {os}": "{os}에서 {size} 회수됨", + "Nothing to reclaim": "회수할 공간 없음", + "Couldn't clean up unused Docker data: {error}": "사용하지 않는 Docker 데이터를 정리할 수 없습니다: {error}", + "Cleaned up {size} of unused Docker data": "사용하지 않는 Docker 데이터 {size} 정리됨", + "Cleaned up unused Docker data": "사용하지 않는 Docker 데이터 정리됨", + "Compact WSL disk?": "WSL 디스크를 압축할까요?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx}을(를) 압축하면 사용하지 않는 공간을 Windows에 반환하며 Kiri 엔진과 실행 중인 컨테이너가 잠시 다시 시작됩니다.", + "Compact disk": "디스크 압축", + "Clean up unused Docker data?": "사용하지 않는 Docker 데이터를 정리할까요?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "중지된 컨테이너, 태그 없는 이미지, BuildKit 빌드 캐시를 제거합니다. 실행 중인 컨테이너와 태그된 이미지는 유지됩니다.", + "Clean up": "정리", + "Uninstall Kiri?": "Kiri를 제거할까요?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "엔진을 중지하고 Kiri의 백그라운드 서비스, CLI 링크, 셸 프로필 항목을 제거한 뒤 이전 Docker 컨텍스트를 복원합니다. 이미지와 볼륨은 Kiri 데이터 폴더를 직접 삭제할 때까지 유지됩니다.", + "Cluster": "클러스터", + "default": "기본값", + "k3s version": "k3s 버전", + "Image version for the cluster node ({cmd}). Applies when recreated.": "클러스터 노드의 이미지 버전입니다({cmd}). 재생성할 때 적용됩니다.", + "Extra server flags": "추가 서버 플래그", + "Passed to {srv} ({flag}), separated by spaces.": "공백으로 구분하여 {srv}({flag})에 전달됩니다.", + "Startup manifests": "시작 매니페스트", + "YAML files in {path} are applied whenever the cluster starts.": "클러스터가 시작될 때마다 {path}의 YAML 파일이 적용됩니다.", + "Open folder": "폴더 열기", + "{n} untagged image": "태그 없는 이미지 {n}개", + "{n} untagged images": "태그 없는 이미지 {n}개", + "Uninstall Kiri from Windows Settings → Apps": "Windows 설정 → 앱에서 Kiri를 제거하세요", + "Builder settings saved": "빌더 설정 저장됨", + "Could not save builder settings: {error}": "빌더 설정을 저장할 수 없습니다: {error}", + "Disk reclaim is already running": "디스크 공간 회수가 이미 실행 중입니다", + "Outbound VM traffic setting saved. Restart the VM to apply.": "VM 외부 통신 설정을 저장했습니다. 적용하려면 VM을 다시 시작하세요.", + "Could not save VM networking setting: {error}": "VM 네트워크 설정을 저장할 수 없습니다: {error}", + "Added Kiri command-line tools to shell profiles": "셸 프로필에 Kiri 명령줄 도구를 추가했습니다", + "Removed Kiri command-line tools from shell profiles": "셸 프로필에서 Kiri 명령줄 도구를 제거했습니다", + "Could not update shell profiles: {error}": "셸 프로필을 업데이트할 수 없습니다: {error}", + "Uninstalling Kiri…": "Kiri 제거 중…", + "Could not uninstall Kiri: {error}": "Kiri를 제거할 수 없습니다: {error}", + "Uninstall Kiri using your system package manager": "시스템 패키지 관리자로 Kiri를 제거하세요" } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 508fd95a0..b11c41b6a 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -1854,7 +1854,6 @@ "Disk image size": "ຂະໜາດອິມເມຈດິສກ໌", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ຫຼື KIRI_DISK_GB ຖືກຕັ້ງໄວ້ສຳລັບ daemon, ແລະ ມັນມີຜົນເໜືອກວ່າຄ່າເຫຼົ່ານີ້.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ຕອນນີ້ແລ່ນດ້ວຍ {cpus}, ສູງສຸດ {mem} ແລະ ດິສກ໌ {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ບໍ່ເຄີຍຫົດລົງ. ມີຜົນເມື່ອເລີ່ມໃໝ່.", "No other WSL distros installed.": "ບໍ່ມີ WSL distro ອື່ນຕິດຕັ້ງຢู่.", "WSL integration": "ການເຊື່ອມໂຍງ WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ປິດ: ໜ່ວຍຄວາມຈຳທີ່ໜ້າຕ່າງໃຊ້ຈະຖືກປ່ອຍຄືນ. ການເປີດຄືນຈະໃຊ້ເວລາໜ້ອຍໜຶ່ງ ແລະ ເທີມິນອນທີ່ເປີດຢູ່ຈະຖືກປິດ.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri ແລະ PC ນີ້", "Kiri and this computer": "Kiri ແລະ ຄອມພິວເຕີນີ້", "Versions, {os}, whether the engine runs, how many containers and images": "ເວີຊັນ, {os}, ເອນຈິນແລ່ນຢູ່ຫຼືບໍ່, ຈຳນວນຄອນເທນເນີ ແລະ ອິມເມຈ", - "Saved. The engine uses these from its next start": "ບັນທຶກແລ້ວ. ເອນຈິນຈະໃຊ້ຄ່າເຫຼົ່ານີ້ຕັ້ງແຕ່ການເລີ່ມຄັ້ງຕໍ່ໄປ" + "Saved. The engine uses these from its next start": "ບັນທຶກແລ້ວ. ເອນຈິນຈະໃຊ້ຄ່າເຫຼົ່ານີ້ຕັ້ງແຕ່ການເລີ່ມຄັ້ງຕໍ່ໄປ", + "5 min": "5 ນາທີ", + "10 min": "10 ນາທີ", + "30 min": "30 ນາທີ", + "Never": "ບໍ່ເຄີຍ", + "Build cache limit": "ຂີດຈຳກັດແຄດການບິວ", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "ເລເຍີແຄດທີ່ເກົ່າທີ່ສຸດຈະຖືກລຶບອັດຕະໂນມັດເມື່ອແຄດຂອງ BuildKit ເກີນຂະໜາດນີ້.", + "Stop builder when idle": "ຢຸດຕົວບິວເມື່ອວ່າງ", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "ຢຸດ BuildKit ລະຫວ່າງການບິວ ເພື່ອບໍ່ໃຫ້ໃຊ້ໜ່ວຍຄວາມຈຳເມື່ອວ່າງ; ການບິວຄັ້ງຕໍ່ໄປຈະປຸກມັນພາຍໃນບໍ່ເຖິງໜຶ່ງວິນາທີ.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB ຫຼື KIRI_BUILDER_IDLE_SECS ຖືກຕັ້ງໄວ້ສຳລັບ daemon, ແລະ ມັນມີຜົນເໜືອກວ່າຄ່າເຫຼົ່ານີ້.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: ໄວທີ່ສຸດ. ປ່ຽນເປັນ ຣີເລໂຮສ ຖ້າ Cloudflare WARP ຫຼື ໄຟວໍອົງກອນບລັອກ HTTPS ຂອງຄອນເທນເນີ. ມີຜົນເມື່ອເລີ່ມ VM ໃໝ່.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "ຣີເລໂຮສ: ການເຊື່ອມຕໍ່ອອກຈາກ Kiri ເທິງ macOS ແທນ NAT ຂອງ Virtualization.framework. ມີຜົນເມື່ອເລີ່ມ VM ໃໝ່.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT ຖືກຕັ້ງໄວ້ໃນສະພາບແວດລ້ອມ ແລະ ມີຜົນເໜືອກວ່າ.", + "Outbound VM traffic": "ທຣາຟຟິກຂາອອກຂອງ VM", + "macOS NAT": "macOS NAT", + "Host relay": "ຣີເລໂຮສ", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "ຂະໜາດສູງສຸດທີ່ດິສກ໌ VM ສາມາດຂະຫຍາຍໄດ້. ພື້ນທີ່ໃນ {os} ຈະຖືກໃຊ້ສະເພາະເມື່ອມີການຂຽນຂໍ້ມູນ ແລະ ພື້ນທີ່ທີ່ບໍ່ໄດ້ໃຊ້ສາມາດຂໍຄືນໄດ້ໃນ {storage}. ມີຜົນເມື່ອເລີ່ມໃໝ່.", + "Settings → Storage": "ການຕັ້ງຄ່າ → ບ່ອນເກັບຂໍ້ມູນ", + "VM disk space": "ພື້ນທີ່ດິສກ໌ VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux ແບບ native ໃຊ້ລະບົບໄຟລ໌ຂອງໂຮສໂດຍກົງ — ອິມເມຈ ແລະ ວອລຸ່ມທີ່ຖືກລຶບຈະຄືນພື້ນທີ່ທັນທີ.", + "Compact disk…": "ບີບອັດດິສກ໌…", + "Reclaim space": "ຂໍພື້ນທີ່ຄືນ", + "Compacting…": "ກຳລັງບີບອັດ…", + "Reclaiming…": "ກຳລັງຂໍຄືນ…", + "Compacting {vhdx} and restarting the engine…": "ກຳລັງບີບອັດ {vhdx} ແລະ ເລີ່ມເອນຈິນໃໝ່…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} ເທິງ {os}, ໃຊ້ຢູ່ {inUse} ພາຍໃນ VM · ກຳລັງຕັດບລັອກທີ່ບໍ່ໄດ້ໃຊ້ອອກ…", + "Trimming unused blocks inside the VM disk…": "ກຳລັງຕັດບລັອກທີ່ບໍ່ໄດ້ໃຊ້ພາຍໃນດິສກ໌ VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} ເທິງ Windows ({vhdx}), ໃຊ້ຢູ່ {inUse} · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} ເທິງ {os}, ໃຊ້ຢູ່ {inUse} ພາຍໃນ VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} ເທິງ Windows ({vhdx}), ໃຊ້ຢູ່ {inUse} · ບໍ່ມີພື້ນທີ່ໃຫ້ຂໍຄືນ.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} ເທິງ {os}, ໃຊ້ຢູ່ {inUse} ພາຍໃນ VM · ບໍ່ມີພື້ນທີ່ໃຫ້ຂໍຄືນ.", + "Nothing to reclaim.": "ບໍ່ມີພື້ນທີ່ໃຫ້ຂໍຄືນ.", + "{size} can be given back": "ສົ່ງຄືນໄດ້ {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} ເທິງ Windows ({vhdx}), ໃຊ້ຢູ່ {inUse} · {can}. ການບີບອັດຈະເລີ່ມເອນຈິນໃໝ່.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} ເທິງ {os}, ໃຊ້ຢູ່ {inUse} ພາຍໃນ VM · {can} ໂດຍບໍ່ຕ້ອງຢຸດຄອນເທນເນີ.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} ເທິງ Windows ({vhdx}). ການບີບອັດຈະສົ່ງພື້ນທີ່ທີ່ບໍ່ໄດ້ໃຊ້ຄືນ ແລະ ເລີ່ມເອນຈິນໃໝ່.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} ເທິງ {os}. ການຂໍພື້ນທີ່ຄືນຈະຕັດບລັອກທີ່ບໍ່ໄດ້ໃຊ້ໃນດິສກ໌ VM ໂດຍບໍ່ຕ້ອງຢຸດຄອນເທນເນີ.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "ສົ່ງພື້ນທີ່ທີ່ບໍ່ໄດ້ໃຊ້ໃນ {vhdx} ຄືນໃຫ້ Windows. ການບີບອັດຈະເລີ່ມເອນຈິນໃໝ່.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "ສົ່ງບລັອກທີ່ບໍ່ໄດ້ໃຊ້ໃນດິສກ໌ VM ຄືນໃຫ້ {os} ໂດຍບໍ່ຕ້ອງຢຸດຄອນເທນເນີ.", + "Cleaning up stopped containers, untagged images, and build cache…": "ກຳລັງລ້າງຄອນເທນເນີທີ່ຢຸດແລ້ວ, ອິມເມຈທີ່ບໍ່ມີແທັກ ແລະ ແຄດການບິວ…", + "{count} ({size})": "{count} ({size})", + "build cache": "ແຄດການບິວ", + "No stopped containers, untagged images or build cache · {freed}.": "ບໍ່ມີຄອນເທນເນີທີ່ຢຸດແລ້ວ, ອິມເມຈທີ່ບໍ່ມີແທັກ ຫຼື ແຄດການບິວ · {freed}.", + "No stopped containers, untagged images or build cache.": "ບໍ່ມີຄອນເທນເນີທີ່ຢຸດແລ້ວ, ອິມເມຈທີ່ບໍ່ມີແທັກ ຫຼື ແຄດການບິວ.", + "Cleaning up…": "ກຳລັງລ້າງຂໍ້ມູນ…", + "Clean up…": "ລ້າງຂໍ້ມູນ…", + "Unused Docker data": "ຂໍ້ມູນ Docker ທີ່ບໍ່ໄດ້ໃຊ້", + "Command-line tools in shell": "ເຄື່ອງມືແຖວຄຳສັ່ງໃນ shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "ເພີ່ມ {bin} ໃສ່ {zshrc} ແລະ {zprofile} ເພື່ອໃຫ້ {docker}, {kubectl} ແລະ {kiri} ໃຊ້ໄດ້ໃນເທີມິນອນໃໝ່.", + "Uninstall Kiri": "ຖອນການຕິດຕັ້ງ Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "ຢຸດເອນຈິນ, ລຶບບໍລິການເບື້ອງຫຼັງຂອງ Kiri, ລິ້ງ CLI ແລະ ລາຍການໂປຣໄຟລ໌ shell, ແລ້ວກູ້ຄືນ context Docker ກ່ອນໜ້າຂອງທ່ານ ({cmd}).", + "Uninstall Kiri…": "ຖອນການຕິດຕັ້ງ Kiri…", + "Couldn't reclaim disk space: {error}": "ຂໍພື້ນທີ່ດິສກ໌ຄືນບໍ່ໄດ້: {error}", + "Reclaimed {size} on {os}": "ຂໍພື້ນທີ່ຄືນແລ້ວ {size} ເທິງ {os}", + "Nothing to reclaim": "ບໍ່ມີພື້ນທີ່ໃຫ້ຂໍຄືນ", + "Couldn't clean up unused Docker data: {error}": "ລ້າງຂໍ້ມູນ Docker ທີ່ບໍ່ໄດ້ໃຊ້ບໍ່ໄດ້: {error}", + "Cleaned up {size} of unused Docker data": "ລ້າງຂໍ້ມູນ Docker ທີ່ບໍ່ໄດ້ໃຊ້ແລ້ວ {size}", + "Cleaned up unused Docker data": "ລ້າງຂໍ້ມູນ Docker ທີ່ບໍ່ໄດ້ໃຊ້ແລ້ວ", + "Compact WSL disk?": "ບີບອັດດິສກ໌ WSL ບໍ?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "ການບີບອັດ {vhdx} ຈະສົ່ງພື້ນທີ່ທີ່ບໍ່ໄດ້ໃຊ້ຄືນໃຫ້ Windows ແລະ ເລີ່ມເອນຈິນ Kiri ກັບຄອນເທນເນີທີ່ແລ່ນຢູ່ໃໝ່ຊົ່ວຄາວ.", + "Compact disk": "ບີບອັດດິສກ໌", + "Clean up unused Docker data?": "ລ້າງຂໍ້ມູນ Docker ທີ່ບໍ່ໄດ້ໃຊ້ບໍ?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "ລຶບຄອນເທນເນີທີ່ຢຸດແລ້ວ, ອິມເມຈທີ່ບໍ່ມີແທັກ ແລະ ແຄດການບິວຂອງ BuildKit. ຄອນເທນເນີທີ່ແລ່ນຢູ່ ແລະ ອິມເມຈທີ່ມີແທັກຈະຖືກເກັບໄວ້.", + "Clean up": "ລ້າງຂໍ້ມູນ", + "Uninstall Kiri?": "ຖອນການຕິດຕັ້ງ Kiri ບໍ?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "ຢຸດເອນຈິນ, ລຶບບໍລິການເບື້ອງຫຼັງຂອງ Kiri, ລິ້ງ CLI ແລະ ລາຍການໂປຣໄຟລ໌ shell, ແລ້ວກູ້ຄືນ context Docker ກ່ອນໜ້າຂອງທ່ານ. ອິມເມຈ ແລະ ວອລຸ່ມຂອງທ່ານຍັງຢູ່ໃນໂຟນເດີຂໍ້ມູນຂອງ Kiri ຈົນກວ່າທ່ານຈະລຶບມັນ.", + "Cluster": "ຄລັສເຕີ", + "default": "ຄ່າເລີ່ມຕົ້ນ", + "k3s version": "ເວີຊັນ k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "ເວີຊັນອິມເມຈສຳລັບ node ຂອງຄລັສເຕີ ({cmd}). ມີຜົນເມື່ອສ້າງໃໝ່.", + "Extra server flags": "ແຟລັກເຊີບເວີເພີ່ມເຕີມ", + "Passed to {srv} ({flag}), separated by spaces.": "ສົ່ງຕໍ່ໃຫ້ {srv} ({flag}), ຂັ້ນດ້ວຍຍະຫວ່າງ.", + "Startup manifests": "Manifest ເມື່ອເລີ່ມລະບົບ", + "YAML files in {path} are applied whenever the cluster starts.": "ໄຟລ໌ YAML ໃນ {path} ຈະຖືກນຳໃຊ້ທຸກຄັ້ງທີ່ຄລັສເຕີເລີ່ມຕົ້ນ.", + "Open folder": "ເປີດໂຟນເດີ", + "{n} untagged image": "{n} ອິມເມຈທີ່ບໍ່ມີແທັກ", + "{n} untagged images": "{n} ອິມເມຈທີ່ບໍ່ມີແທັກ", + "Uninstall Kiri from Windows Settings → Apps": "ຖອນການຕິດຕັ້ງ Kiri ຈາກ ການຕັ້ງຄ່າ Windows → ແອັບ", + "Builder settings saved": "ບັນທຶກການຕັ້ງຄ່າຕົວບິວແລ້ວ", + "Could not save builder settings: {error}": "ບັນທຶກການຕັ້ງຄ່າຕົວບິວບໍ່ໄດ້: {error}", + "Disk reclaim is already running": "ການຂໍພື້ນທີ່ດິສກ໌ຄືນກຳລັງເຮັດວຽກຢູ່ແລ້ວ", + "Outbound VM traffic setting saved. Restart the VM to apply.": "ບັນທຶກການຕັ້ງຄ່າທຣາຟຟິກຂາອອກຂອງ VM ແລ້ວ. ເລີ່ມ VM ໃໝ່ເພື່ອນຳໃຊ້.", + "Could not save VM networking setting: {error}": "ບັນທຶກການຕັ້ງຄ່າເຄືອຂ່າຍ VM ບໍ່ໄດ້: {error}", + "Added Kiri command-line tools to shell profiles": "ເພີ່ມເຄື່ອງມືແຖວຄຳສັ່ງ Kiri ເຂົ້າໂປຣໄຟລ໌ shell ແລ້ວ", + "Removed Kiri command-line tools from shell profiles": "ລຶບເຄື່ອງມືແຖວຄຳສັ່ງ Kiri ອອກຈາກໂປຣໄຟລ໌ shell ແລ້ວ", + "Could not update shell profiles: {error}": "ອັບເດດໂປຣໄຟລ໌ shell ບໍ່ໄດ້: {error}", + "Uninstalling Kiri…": "ກຳລັງຖອນການຕິດຕັ້ງ Kiri…", + "Could not uninstall Kiri: {error}": "ຖອນການຕິດຕັ້ງ Kiri ບໍ່ໄດ້: {error}", + "Uninstall Kiri using your system package manager": "ຖອນການຕິດຕັ້ງ Kiri ໂດຍໃຊ້ຕົວຈັດການແພັກເກັດຂອງລະບົບທ່ານ" } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 8d1486c84..5567563bb 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -1854,7 +1854,6 @@ "Disk image size": "Disko atvaizdo dydis", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Tarnybai nustatytas KIRI_CPUS, KIRI_MEMORY_MIB arba KIRI_DISK_GB, ir jie turi pirmenybę prieš šiuos nustatymus.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Dabar veikia su {cpus}, iki {mem} ir {disk} disku.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis; diskas niekada nesumažėja. Pritaikoma paleidus iš naujo.", "No other WSL distros installed.": "Kitų WSL distribucijų neįdiegta.", "WSL integration": "WSL integracija", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Uždaryti: lango naudojama atmintis atlaisvinama. Vėl atsidaryti užtrunka akimirką, o atviri terminalai užbaigiami.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri ir šis PK", "Kiri and this computer": "Kiri ir šis kompiuteris", "Versions, {os}, whether the engine runs, how many containers and images": "Versijos, {os}, ar veikia variklis, kiek yra konteinerių ir atvaizdų", - "Saved. The engine uses these from its next start": "Įrašyta. Variklis juos naudos nuo kito paleidimo" + "Saved. The engine uses these from its next start": "Įrašyta. Variklis juos naudos nuo kito paleidimo", + "5 min": "5 min.", + "10 min": "10 min.", + "30 min": "30 min.", + "Never": "Niekada", + "Build cache limit": "Kūrimo talpyklos riba", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Seniausi talpykloje esantys sluoksniai automatiškai išvalomi, kai BuildKit talpykla viršija šį dydį.", + "Stop builder when idle": "Stabdyti kūrimo įrankį, kai nenaudojamas", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Sustabdo BuildKit tarp kūrimų, kad nenaudojamas neužimtų atminties; kitas kūrimas jį pažadina greičiau nei per sekundę.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Tarnybai nustatytas KIRI_BUILD_CACHE_GB arba KIRI_BUILDER_IDLE_SECS, ir jie turi pirmenybę prieš šiuos nustatymus.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: greičiausias. Perjunkite į Šeimininko relė, jei Cloudflare WARP arba įmonės užkarda blokuoja konteinerių HTTPS. Pritaikoma paleidus VM iš naujo.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Šeimininko relė: ryšiai išeina iš Kiri macOS sistemoje, o ne per Virtualization.framework NAT. Pritaikoma paleidus VM iš naujo.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Aplinkoje nustatytas KIRI_SHARED_NAT ir jis turi pirmenybę.", + "Outbound VM traffic": "Išeinantis VM srautas", + "macOS NAT": "macOS NAT", + "Host relay": "Šeimininko relė", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Didžiausias dydis, iki kurio gali išaugti VM diskas. Vieta {os} naudojama tik rašant duomenis, o nenaudojamą vietą galima susigrąžinti skiltyje {storage}. Pritaikoma paleidus iš naujo.", + "Settings → Storage": "Nustatymai → Saugykla", + "VM disk space": "VM disko vieta", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Savasis Linux tiesiogiai naudoja pagrindinio kompiuterio failų sistemą — ištrinti atvaizdai ir tomai iš karto atlaisvina vietą.", + "Compact disk…": "Suglaudinti diską…", + "Reclaim space": "Susigrąžinti vietą", + "Compacting…": "Glaudinama…", + "Reclaiming…": "Susigrąžinama…", + "Compacting {vhdx} and restarting the engine…": "Glaudinamas {vhdx} ir iš naujo paleidžiamas variklis…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} sistemoje {os}, {inUse} naudojama VM viduje · atlaisvinami nenaudojami blokai…", + "Trimming unused blocks inside the VM disk…": "VM diske atlaisvinami nenaudojami blokai…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} Windows sistemoje ({vhdx}), naudojama {inUse} · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} sistemoje {os}, {inUse} naudojama VM viduje · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} Windows sistemoje ({vhdx}), naudojama {inUse} · nėra ką susigrąžinti.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} sistemoje {os}, {inUse} naudojama VM viduje · nėra ką susigrąžinti.", + "Nothing to reclaim.": "Nėra ką susigrąžinti.", + "{size} can be given back": "galima grąžinti {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} Windows sistemoje ({vhdx}), naudojama {inUse} · {can}. Glaudinimas paleidžia variklį iš naujo.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} sistemoje {os}, {inUse} naudojama VM viduje · {can} nestabdant konteinerių.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} Windows sistemoje ({vhdx}). Glaudinimas grąžina nenaudojamą vietą ir paleidžia variklį iš naujo.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} sistemoje {os}. Vietos susigrąžinimas atlaisvina nenaudojamus VM disko blokus nestabdant konteinerių.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Grąžina Windows sistemai nenaudojamą vietą iš {vhdx}. Glaudinimas paleidžia variklį iš naujo.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Grąžina {os} nenaudojamus VM disko blokus nestabdant konteinerių.", + "Cleaning up stopped containers, untagged images, and build cache…": "Valomi sustabdyti konteineriai, nepažymėti atvaizdai ir kūrimo talpykla…", + "{count} ({size})": "{count} ({size})", + "build cache": "kūrimo talpykla", + "No stopped containers, untagged images or build cache · {freed}.": "Nėra sustabdytų konteinerių, nepažymėtų atvaizdų ar kūrimo talpyklos · {freed}.", + "No stopped containers, untagged images or build cache.": "Nėra sustabdytų konteinerių, nepažymėtų atvaizdų ar kūrimo talpyklos.", + "Cleaning up…": "Valoma…", + "Clean up…": "Išvalyti…", + "Unused Docker data": "Nenaudojami Docker duomenys", + "Command-line tools in shell": "Komandinės eilutės įrankiai apvalkale", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Pridėkite {bin} prie {zshrc} ir {zprofile}, kad {docker}, {kubectl} ir {kiri} veiktų naujuose terminaluose.", + "Uninstall Kiri": "Pašalinti Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Sustabdo variklį, pašalina Kiri foninę tarnybą, CLI nuorodas ir apvalkalo profilio įrašus bei atkuria ankstesnį Docker kontekstą ({cmd}).", + "Uninstall Kiri…": "Pašalinti Kiri…", + "Couldn't reclaim disk space: {error}": "Nepavyko susigrąžinti disko vietos: {error}", + "Reclaimed {size} on {os}": "Susigrąžinta {size} sistemoje {os}", + "Nothing to reclaim": "Nėra ką susigrąžinti", + "Couldn't clean up unused Docker data: {error}": "Nepavyko išvalyti nenaudojamų Docker duomenų: {error}", + "Cleaned up {size} of unused Docker data": "Išvalyta {size} nenaudojamų Docker duomenų", + "Cleaned up unused Docker data": "Nenaudojami Docker duomenys išvalyti", + "Compact WSL disk?": "Suglaudinti WSL diską?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Suglaudinus {vhdx}, nenaudojama vieta grąžinama Windows sistemai, o Kiri variklis ir veikiantys konteineriai trumpam paleidžiami iš naujo.", + "Compact disk": "Suglaudinti diską", + "Clean up unused Docker data?": "Išvalyti nenaudojamus Docker duomenis?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Pašalina sustabdytus konteinerius, nepažymėtus atvaizdus ir BuildKit kūrimo talpyklą. Veikiantys konteineriai ir pažymėti atvaizdai paliekami.", + "Clean up": "Išvalyti", + "Uninstall Kiri?": "Pašalinti Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Sustabdo variklį, pašalina Kiri foninę tarnybą, CLI nuorodas ir apvalkalo profilio įrašus bei atkuria ankstesnį Docker kontekstą. Jūsų atvaizdai ir tomai lieka Kiri duomenų aplanke, kol jį ištrinsite.", + "Cluster": "Klasteris", + "default": "numatytoji", + "k3s version": "k3s versija", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Klasterio mazgo atvaizdo versija ({cmd}). Pritaikoma sukūrus iš naujo.", + "Extra server flags": "Papildomi serverio parametrai", + "Passed to {srv} ({flag}), separated by spaces.": "Perduodami {srv} ({flag}), atskirti tarpais.", + "Startup manifests": "Paleisties manifestai", + "YAML files in {path} are applied whenever the cluster starts.": "YAML failai iš {path} pritaikomi kaskart paleidžiant klasterį.", + "Open folder": "Atidaryti aplanką", + "{n} untagged image": "{n} nepažymėtas atvaizdas", + "{n} untagged images": "Nepažymėtų atvaizdų: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Pašalinkite Kiri per Windows Nustatymai → Programos", + "Builder settings saved": "Kūrimo įrankio nustatymai įrašyti", + "Could not save builder settings: {error}": "Nepavyko įrašyti kūrimo įrankio nustatymų: {error}", + "Disk reclaim is already running": "Disko vietos susigrąžinimas jau vykdomas", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Išeinančio VM srauto nustatymas įrašytas. Paleiskite VM iš naujo, kad būtų pritaikyta.", + "Could not save VM networking setting: {error}": "Nepavyko įrašyti VM tinklo nustatymo: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri komandinės eilutės įrankiai pridėti prie apvalkalo profilių", + "Removed Kiri command-line tools from shell profiles": "Kiri komandinės eilutės įrankiai pašalinti iš apvalkalo profilių", + "Could not update shell profiles: {error}": "Nepavyko atnaujinti apvalkalo profilių: {error}", + "Uninstalling Kiri…": "Šalinamas Kiri…", + "Could not uninstall Kiri: {error}": "Nepavyko pašalinti Kiri: {error}", + "Uninstall Kiri using your system package manager": "Pašalinkite Kiri naudodami sistemos paketų tvarkyklę" } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 6aeb45e52..b818dba77 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -1854,7 +1854,6 @@ "Disk image size": "Størrelse på diskbilde", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB eller KIRI_DISK_GB er satt for daemonen og har forrang foran disse.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Kjører nå med {cpus}, opptil {mem} og en disk på {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives; den krymper aldri. Gjelder ved omstart.", "No other WSL distros installed.": "Ingen andre WSL-distribusjoner er installert.", "WSL integration": "WSL-integrering", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Lukk: minnet vinduet bruker, frigjøres. Det tar et øyeblikk å åpne det igjen, og åpne terminaler avsluttes.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri og denne PC-en", "Kiri and this computer": "Kiri og denne datamaskinen", "Versions, {os}, whether the engine runs, how many containers and images": "Versjoner, {os}, om motoren kjører, hvor mange containere og bilder", - "Saved. The engine uses these from its next start": "Lagret. Motoren bruker disse fra neste start" + "Saved. The engine uses these from its next start": "Lagret. Motoren bruker disse fra neste start", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Aldri", + "Build cache limit": "Grense for byggebuffer", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "De eldste bufrede lagene ryddes automatisk når BuildKits buffer passerer denne størrelsen.", + "Stop builder when idle": "Stopp bygger ved inaktivitet", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Stopper BuildKit mellom bygg slik at den ikke bruker minne i hvile; neste bygg vekker den på under et sekund.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB eller KIRI_BUILDER_IDLE_SECS er satt for daemonen og har forrang foran disse.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: raskest. Bytt til Vertsrelé hvis Cloudflare WARP eller en bedriftsbrannmur blokkerer HTTPS fra containere. Gjelder ved omstart av VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Vertsrelé: tilkoblinger går ut fra Kiri på macOS i stedet for Virtualization.framework NAT. Gjelder ved omstart av VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT er satt i miljøet og har forrang.", + "Outbound VM traffic": "Utgående VM-trafikk", + "macOS NAT": "macOS NAT", + "Host relay": "Vertsrelé", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Det meste VM-disken kan vokse til. Plass på {os} brukes bare etter hvert som data skrives, og ubrukt plass kan frigjøres i {storage}. Gjelder ved omstart.", + "Settings → Storage": "Innstillinger → Lagring", + "VM disk space": "VM-diskplass", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Direkte på Linux brukes vertens filsystem — slettede bilder og volumer frigjør plass umiddelbart.", + "Compact disk…": "Komprimer disk…", + "Reclaim space": "Frigjør plass", + "Compacting…": "Komprimerer…", + "Reclaiming…": "Frigjør…", + "Compacting {vhdx} and restarting the engine…": "Komprimerer {vhdx} og starter motoren på nytt…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} på {os}, {inUse} i bruk inne i VM-en · trimmer ubrukte blokker…", + "Trimming unused blocks inside the VM disk…": "Trimmer ubrukte blokker inne i VM-disken…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} på Windows ({vhdx}), {inUse} i bruk · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} på {os}, {inUse} i bruk inne i VM-en · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} på Windows ({vhdx}), {inUse} i bruk · ingenting å frigjøre.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} på {os}, {inUse} i bruk inne i VM-en · ingenting å frigjøre.", + "Nothing to reclaim.": "Ingenting å frigjøre.", + "{size} can be given back": "{size} kan gis tilbake", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} på Windows ({vhdx}), {inUse} i bruk · {can}. Komprimering starter motoren på nytt.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} på {os}, {inUse} i bruk inne i VM-en · {can} uten å stoppe containere.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} på Windows ({vhdx}). Komprimering gir tilbake ubrukt plass og starter motoren på nytt.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} på {os}. Frigjøring trimmer ubrukte blokker i VM-disken uten å stoppe containere.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Gir ubrukt plass i {vhdx} tilbake til Windows. Komprimering starter motoren på nytt.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Gir ubrukte blokker i VM-disken tilbake til {os} uten å stoppe containere.", + "Cleaning up stopped containers, untagged images, and build cache…": "Rydder opp i stoppede containere, bilder uten tagg og byggebuffer…", + "{count} ({size})": "{count} ({size})", + "build cache": "byggebuffer", + "No stopped containers, untagged images or build cache · {freed}.": "Ingen stoppede containere, bilder uten tagg eller byggebuffer · {freed}.", + "No stopped containers, untagged images or build cache.": "Ingen stoppede containere, bilder uten tagg eller byggebuffer.", + "Cleaning up…": "Rydder opp…", + "Clean up…": "Rydd opp…", + "Unused Docker data": "Ubrukte Docker-data", + "Command-line tools in shell": "Kommandolinjeverktøy i skallet", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Legg til {bin} i {zshrc} og {zprofile} slik at {docker}, {kubectl} og {kiri} fungerer i nye terminaler.", + "Uninstall Kiri": "Avinstaller Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Stopper motoren, fjerner Kiris bakgrunnstjeneste, CLI-lenker og oppføringer i skallprofiler, og gjenoppretter forrige Docker-kontekst ({cmd}).", + "Uninstall Kiri…": "Avinstaller Kiri…", + "Couldn't reclaim disk space: {error}": "Kunne ikke frigjøre diskplass: {error}", + "Reclaimed {size} on {os}": "Frigjorde {size} på {os}", + "Nothing to reclaim": "Ingenting å frigjøre", + "Couldn't clean up unused Docker data: {error}": "Kunne ikke rydde opp i ubrukte Docker-data: {error}", + "Cleaned up {size} of unused Docker data": "Ryddet opp {size} ubrukte Docker-data", + "Cleaned up unused Docker data": "Ryddet opp ubrukte Docker-data", + "Compact WSL disk?": "Komprimere WSL-disk?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Komprimering av {vhdx} gir ubrukt plass tilbake til Windows og starter Kiris motor og kjørende containere kort på nytt.", + "Compact disk": "Komprimer disk", + "Clean up unused Docker data?": "Rydde opp i ubrukte Docker-data?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Fjerner stoppede containere, bilder uten tagg og BuildKits byggebuffer. Kjørende containere og bilder med tagg beholdes.", + "Clean up": "Rydd opp", + "Uninstall Kiri?": "Avinstallere Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Stopper motoren, fjerner Kiris bakgrunnstjeneste, CLI-lenker og oppføringer i skallprofiler, og gjenoppretter forrige Docker-kontekst. Bilder og volumer blir liggende i Kiris datamappe til du sletter den.", + "Cluster": "Klynge", + "default": "standard", + "k3s version": "k3s-versjon", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Bildeversjon for klyngenoden ({cmd}). Gjelder når den opprettes på nytt.", + "Extra server flags": "Ekstra serverflagg", + "Passed to {srv} ({flag}), separated by spaces.": "Sendes til {srv} ({flag}), atskilt med mellomrom.", + "Startup manifests": "Oppstartsmanifester", + "YAML files in {path} are applied whenever the cluster starts.": "YAML-filer i {path} brukes hver gang klyngen starter.", + "Open folder": "Åpne mappe", + "{n} untagged image": "{n} bilde uten tagg", + "{n} untagged images": "{n} bilder uten tagg", + "Uninstall Kiri from Windows Settings → Apps": "Avinstaller Kiri fra Windows-innstillinger → Apper", + "Builder settings saved": "Byggerinnstillinger lagret", + "Could not save builder settings: {error}": "Kunne ikke lagre byggerinnstillinger: {error}", + "Disk reclaim is already running": "Frigjøring av diskplass kjører allerede", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Innstilling for utgående VM-trafikk lagret. Start VM-en på nytt for å bruke den.", + "Could not save VM networking setting: {error}": "Kunne ikke lagre nettverksinnstilling for VM: {error}", + "Added Kiri command-line tools to shell profiles": "La til Kiris kommandolinjeverktøy i skallprofiler", + "Removed Kiri command-line tools from shell profiles": "Fjernet Kiris kommandolinjeverktøy fra skallprofiler", + "Could not update shell profiles: {error}": "Kunne ikke oppdatere skallprofiler: {error}", + "Uninstalling Kiri…": "Avinstallerer Kiri…", + "Could not uninstall Kiri: {error}": "Kunne ikke avinstallere Kiri: {error}", + "Uninstall Kiri using your system package manager": "Avinstaller Kiri med systemets pakkebehandler" } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index 65de0acbc..b003d8126 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -1854,7 +1854,6 @@ "Disk image size": "Rozmiar obrazu dysku", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Dla demona ustawiono KIRI_CPUS, KIRI_MEMORY_MIB lub KIRI_DISK_GB i to one mają pierwszeństwo przed tymi ustawieniami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Działa teraz z {cpus}, maks. {mem} i dyskiem {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych; dysk nigdy się nie zmniejsza. Działa po restarcie.", "No other WSL distros installed.": "Brak innych zainstalowanych dystrybucji WSL.", "WSL integration": "Integracja z WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zamknij: pamięć używana przez okno zostaje zwolniona. Ponowne otwarcie zajmuje chwilę, a otwarte terminale zostają zakończone.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri i ten PC", "Kiri and this computer": "Kiri i ten komputer", "Versions, {os}, whether the engine runs, how many containers and images": "Wersje, {os}, czy silnik działa, liczba kontenerów i obrazów", - "Saved. The engine uses these from its next start": "Zapisano. Silnik użyje tego od następnego uruchomienia" + "Saved. The engine uses these from its next start": "Zapisano. Silnik użyje tego od następnego uruchomienia", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nigdy", + "Build cache limit": "Limit pamięci podręcznej buildów", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Najstarsze warstwy w pamięci podręcznej są automatycznie usuwane, gdy pamięć podręczna BuildKit przekroczy ten rozmiar.", + "Stop builder when idle": "Zatrzymuj builder w bezczynności", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Zatrzymuje BuildKit między buildami, aby nie zużywał pamięci w spoczynku; kolejny build wybudza go w mniej niż sekundę.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Dla demona ustawiono KIRI_BUILD_CACHE_GB lub KIRI_BUILDER_IDLE_SECS i to one mają pierwszeństwo przed tymi ustawieniami.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: najszybszy. Przełącz na Przekaźnik hosta, jeśli Cloudflare WARP lub zapora firmowa blokuje ruch HTTPS kontenerów. Działa po restarcie maszyny wirtualnej.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Przekaźnik hosta: połączenia wychodzą z Kiri w systemie macOS zamiast przez NAT Virtualization.framework. Działa po restarcie maszyny wirtualnej.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "W środowisku ustawiono KIRI_SHARED_NAT i ma ono pierwszeństwo.", + "Outbound VM traffic": "Ruch wychodzący z VM", + "macOS NAT": "NAT macOS", + "Host relay": "Przekaźnik hosta", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Maksymalny rozmiar, do jakiego może urosnąć dysk maszyny wirtualnej. Miejsce w systemie {os} jest zajmowane dopiero przy zapisie danych, a nieużywane miejsce można odzyskać w sekcji {storage}. Działa po restarcie.", + "Settings → Storage": "Ustawienia → Pamięć masowa", + "VM disk space": "Miejsce na dysku VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Natywny Linux korzysta bezpośrednio z systemu plików hosta — usunięte obrazy i woluminy od razu zwalniają miejsce.", + "Compact disk…": "Kompaktuj dysk…", + "Reclaim space": "Odzyskaj miejsce", + "Compacting…": "Kompaktowanie…", + "Reclaiming…": "Odzyskiwanie…", + "Compacting {vhdx} and restarting the engine…": "Kompaktowanie {vhdx} i ponowne uruchamianie silnika…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} w systemie {os}, {inUse} w użyciu w VM · zwalnianie nieużywanych bloków…", + "Trimming unused blocks inside the VM disk…": "Zwalnianie nieużywanych bloków na dysku maszyny wirtualnej…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} w Windows ({vhdx}), {inUse} w użyciu · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} w systemie {os}, {inUse} w użyciu w VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} w Windows ({vhdx}), {inUse} w użyciu · nic do odzyskania.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} w systemie {os}, {inUse} w użyciu w VM · nic do odzyskania.", + "Nothing to reclaim.": "Nic do odzyskania.", + "{size} can be given back": "można zwrócić {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} w Windows ({vhdx}), {inUse} w użyciu · {can}. Kompaktowanie ponownie uruchamia silnik.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} w systemie {os}, {inUse} w użyciu w VM · {can} bez zatrzymywania kontenerów.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} w Windows ({vhdx}). Kompaktowanie zwraca nieużywane miejsce i ponownie uruchamia silnik.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} w systemie {os}. Odzyskiwanie zwalnia nieużywane bloki na dysku VM bez zatrzymywania kontenerów.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Zwraca systemowi Windows nieużywane miejsce w pliku {vhdx}. Kompaktowanie ponownie uruchamia silnik.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Zwraca systemowi {os} nieużywane bloki dysku VM bez zatrzymywania kontenerów.", + "Cleaning up stopped containers, untagged images, and build cache…": "Czyszczenie zatrzymanych kontenerów, nieoznaczonych obrazów i pamięci podręcznej buildów…", + "{count} ({size})": "{count} ({size})", + "build cache": "pamięć podręczna buildów", + "No stopped containers, untagged images or build cache · {freed}.": "Brak zatrzymanych kontenerów, nieoznaczonych obrazów i pamięci podręcznej buildów · {freed}.", + "No stopped containers, untagged images or build cache.": "Brak zatrzymanych kontenerów, nieoznaczonych obrazów i pamięci podręcznej buildów.", + "Cleaning up…": "Czyszczenie…", + "Clean up…": "Wyczyść…", + "Unused Docker data": "Nieużywane dane Dockera", + "Command-line tools in shell": "Narzędzia wiersza poleceń w powłoce", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Dodaj {bin} do {zshrc} i {zprofile}, aby polecenia {docker}, {kubectl} i {kiri} działały w nowych terminalach.", + "Uninstall Kiri": "Odinstaluj Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Zatrzymuje silnik, usuwa usługę Kiri działającą w tle, dowiązania CLI oraz wpisy w profilach powłoki i przywraca poprzedni kontekst Dockera ({cmd}).", + "Uninstall Kiri…": "Odinstaluj Kiri…", + "Couldn't reclaim disk space: {error}": "Nie udało się odzyskać miejsca na dysku: {error}", + "Reclaimed {size} on {os}": "Odzyskano {size} w systemie {os}", + "Nothing to reclaim": "Nic do odzyskania", + "Couldn't clean up unused Docker data: {error}": "Nie udało się wyczyścić nieużywanych danych Dockera: {error}", + "Cleaned up {size} of unused Docker data": "Wyczyszczono {size} nieużywanych danych Dockera", + "Cleaned up unused Docker data": "Wyczyszczono nieużywane dane Dockera", + "Compact WSL disk?": "Skompaktować dysk WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Kompaktowanie pliku {vhdx} zwraca nieużywane miejsce systemowi Windows oraz na chwilę ponownie uruchamia silnik Kiri i działające kontenery.", + "Compact disk": "Kompaktuj dysk", + "Clean up unused Docker data?": "Wyczyścić nieużywane dane Dockera?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Usuwa zatrzymane kontenery, nieoznaczone obrazy oraz pamięć podręczną buildów BuildKit. Działające kontenery i oznaczone obrazy zostają zachowane.", + "Clean up": "Wyczyść", + "Uninstall Kiri?": "Odinstalować Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Zatrzymuje silnik, usuwa usługę Kiri działającą w tle, dowiązania CLI oraz wpisy w profilach powłoki i przywraca poprzedni kontekst Dockera. Obrazy i woluminy pozostają w folderze danych Kiri, dopóki go nie usuniesz.", + "Cluster": "Klaster", + "default": "domyślna", + "k3s version": "Wersja k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Wersja obrazu węzła klastra ({cmd}). Działa po odtworzeniu.", + "Extra server flags": "Dodatkowe flagi serwera", + "Passed to {srv} ({flag}), separated by spaces.": "Przekazywane do {srv} ({flag}), rozdzielone spacjami.", + "Startup manifests": "Manifesty startowe", + "YAML files in {path} are applied whenever the cluster starts.": "Pliki YAML z katalogu {path} są stosowane przy każdym uruchomieniu klastra.", + "Open folder": "Otwórz folder", + "{n} untagged image": "{n} nieoznaczony obraz", + "{n} untagged images": "Nieoznaczone obrazy: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Odinstaluj Kiri w Ustawieniach systemu Windows → Aplikacje", + "Builder settings saved": "Zapisano ustawienia buildera", + "Could not save builder settings: {error}": "Nie udało się zapisać ustawień buildera: {error}", + "Disk reclaim is already running": "Odzyskiwanie miejsca na dysku już trwa", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Zapisano ustawienie ruchu wychodzącego z VM. Uruchom ponownie maszynę wirtualną, aby zastosować.", + "Could not save VM networking setting: {error}": "Nie udało się zapisać ustawienia sieci maszyny wirtualnej: {error}", + "Added Kiri command-line tools to shell profiles": "Dodano narzędzia wiersza poleceń Kiri do profili powłoki", + "Removed Kiri command-line tools from shell profiles": "Usunięto narzędzia wiersza poleceń Kiri z profili powłoki", + "Could not update shell profiles: {error}": "Nie udało się zaktualizować profili powłoki: {error}", + "Uninstalling Kiri…": "Odinstalowywanie Kiri…", + "Could not uninstall Kiri: {error}": "Nie udało się odinstalować Kiri: {error}", + "Uninstall Kiri using your system package manager": "Odinstaluj Kiri za pomocą systemowego menedżera pakietów" } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 210253502..948d083eb 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -1854,7 +1854,6 @@ "Disk image size": "Tamanho da imagem de disco", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ou KIRI_DISK_GB está definido para o daemon e tem prioridade sobre estes.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rodando agora com {cpus}, até {mem} e disco de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados; ele nunca encolhe. Aplica ao reiniciar.", "No other WSL distros installed.": "Nenhuma outra distribuição do WSL instalada.", "WSL integration": "Integração com o WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Fechar: a memória usada pela janela é liberada. Leva um momento para abrir de novo, e os terminais abertos são encerrados.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "O Kiri e este PC", "Kiri and this computer": "O Kiri e este computador", "Versions, {os}, whether the engine runs, how many containers and images": "Versões, {os}, se a engine está rodando, quantos contêineres e imagens", - "Saved. The engine uses these from its next start": "Salvo. A engine usa isso a partir da próxima inicialização" + "Saved. The engine uses these from its next start": "Salvo. A engine usa isso a partir da próxima inicialização", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nunca", + "Build cache limit": "Limite do cache de build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "As camadas em cache mais antigas são removidas automaticamente quando o cache do BuildKit ultrapassa esse tamanho.", + "Stop builder when idle": "Parar builder quando ocioso", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Para o BuildKit entre builds para não usar memória enquanto ocioso; o próximo build o desperta em menos de um segundo.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB ou KIRI_BUILDER_IDLE_SECS está definido para o daemon e tem prioridade sobre estes.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT do macOS: mais rápido. Mude para Relay do host se o Cloudflare WARP ou um firewall corporativo bloquear HTTPS dos contêineres. Aplica ao reiniciar a VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Relay do host: as conexões saem pelo Kiri no macOS em vez do NAT do Virtualization.framework. Aplica ao reiniciar a VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT está definido no ambiente e tem prioridade.", + "Outbound VM traffic": "Tráfego de saída da VM", + "macOS NAT": "NAT do macOS", + "Host relay": "Relay do host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "O máximo que o disco da VM pode crescer. O espaço no {os} só é usado conforme os dados são gravados, e o espaço não usado pode ser recuperado em {storage}. Aplica ao reiniciar.", + "Settings → Storage": "Configurações → Armazenamento", + "VM disk space": "Espaço em disco da VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "O Linux nativo usa diretamente o sistema de arquivos do host — imagens e volumes excluídos liberam espaço imediatamente.", + "Compact disk…": "Compactar disco…", + "Reclaim space": "Recuperar espaço", + "Compacting…": "Compactando…", + "Reclaiming…": "Recuperando…", + "Compacting {vhdx} and restarting the engine…": "Compactando {vhdx} e reiniciando o engine…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} no {os}, {inUse} em uso na VM · liberando blocos não usados…", + "Trimming unused blocks inside the VM disk…": "Liberando blocos não usados no disco da VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} no Windows ({vhdx}), {inUse} em uso · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} no {os}, {inUse} em uso na VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} no Windows ({vhdx}), {inUse} em uso · nada a recuperar.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} no {os}, {inUse} em uso na VM · nada a recuperar.", + "Nothing to reclaim.": "Nada a recuperar.", + "{size} can be given back": "{size} podem ser devolvidos", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} no Windows ({vhdx}), {inUse} em uso · {can}. Compactar reinicia o engine.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} no {os}, {inUse} em uso na VM · {can} sem parar contêineres.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} no Windows ({vhdx}). Compactar devolve o espaço não usado e reinicia o engine.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} no {os}. Recuperar libera blocos não usados no disco da VM sem parar contêineres.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Devolve o espaço não usado em {vhdx} ao Windows. Compactar reinicia o engine.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Devolve blocos não usados no disco da VM ao {os} sem parar contêineres.", + "Cleaning up stopped containers, untagged images, and build cache…": "Limpando contêineres parados, imagens sem tag e cache de build…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache de build", + "No stopped containers, untagged images or build cache · {freed}.": "Nenhum contêiner parado, imagem sem tag ou cache de build · {freed}.", + "No stopped containers, untagged images or build cache.": "Nenhum contêiner parado, imagem sem tag ou cache de build.", + "Cleaning up…": "Limpando…", + "Clean up…": "Limpar…", + "Unused Docker data": "Dados não usados do Docker", + "Command-line tools in shell": "Ferramentas de linha de comando no shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Adicione {bin} ao {zshrc} e ao {zprofile} para que {docker}, {kubectl} e {kiri} funcionem em novos terminais.", + "Uninstall Kiri": "Desinstalar o Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Para o engine, remove o serviço em segundo plano do Kiri, os links da CLI e as entradas de perfil do shell, e restaura seu contexto anterior do Docker ({cmd}).", + "Uninstall Kiri…": "Desinstalar o Kiri…", + "Couldn't reclaim disk space: {error}": "Não foi possível recuperar espaço em disco: {error}", + "Reclaimed {size} on {os}": "{size} recuperados no {os}", + "Nothing to reclaim": "Nada a recuperar", + "Couldn't clean up unused Docker data: {error}": "Não foi possível limpar os dados não usados do Docker: {error}", + "Cleaned up {size} of unused Docker data": "{size} de dados não usados do Docker limpos", + "Cleaned up unused Docker data": "Dados não usados do Docker limpos", + "Compact WSL disk?": "Compactar disco do WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Compactar {vhdx} devolve o espaço não usado ao Windows e reinicia brevemente o engine do Kiri e os contêineres em execução.", + "Compact disk": "Compactar disco", + "Clean up unused Docker data?": "Limpar dados não usados do Docker?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Remove contêineres parados, imagens sem tag e o cache de build do BuildKit. Contêineres em execução e imagens com tag são mantidos.", + "Clean up": "Limpar", + "Uninstall Kiri?": "Desinstalar o Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Para o engine, remove o serviço em segundo plano do Kiri, os links da CLI e as entradas de perfil do shell, e restaura seu contexto anterior do Docker. Suas imagens e volumes permanecem na pasta de dados do Kiri até que você a exclua.", + "Cluster": "Cluster", + "default": "padrão", + "k3s version": "Versão do k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versão da imagem do nó do cluster ({cmd}). Aplica ao recriar.", + "Extra server flags": "Flags extras do servidor", + "Passed to {srv} ({flag}), separated by spaces.": "Passadas para {srv} ({flag}), separadas por espaços.", + "Startup manifests": "Manifestos de inicialização", + "YAML files in {path} are applied whenever the cluster starts.": "Arquivos YAML em {path} são aplicados sempre que o cluster inicia.", + "Open folder": "Abrir pasta", + "{n} untagged image": "{n} imagem sem tag", + "{n} untagged images": "{n} imagens sem tag", + "Uninstall Kiri from Windows Settings → Apps": "Desinstale o Kiri em Configurações do Windows → Aplicativos", + "Builder settings saved": "Configurações do builder salvas", + "Could not save builder settings: {error}": "Não foi possível salvar as configurações do builder: {error}", + "Disk reclaim is already running": "A recuperação de disco já está em execução", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Configuração de tráfego de saída da VM salva. Reinicie a VM para aplicar.", + "Could not save VM networking setting: {error}": "Não foi possível salvar a configuração de rede da VM: {error}", + "Added Kiri command-line tools to shell profiles": "Ferramentas de linha de comando do Kiri adicionadas aos perfis do shell", + "Removed Kiri command-line tools from shell profiles": "Ferramentas de linha de comando do Kiri removidas dos perfis do shell", + "Could not update shell profiles: {error}": "Não foi possível atualizar os perfis do shell: {error}", + "Uninstalling Kiri…": "Desinstalando o Kiri…", + "Could not uninstall Kiri: {error}": "Não foi possível desinstalar o Kiri: {error}", + "Uninstall Kiri using your system package manager": "Desinstale o Kiri usando o gerenciador de pacotes do sistema" } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index 7353dd7fa..cab8bdfc5 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -1854,7 +1854,6 @@ "Disk image size": "Dimensiunea imaginii de disc", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB sau KIRI_DISK_GB este setat pentru daemon și are prioritate față de acestea.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Rulează acum cu {cpus}, până la {mem} și un disc de {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date; nu se micșorează niciodată. Se aplică la repornire.", "No other WSL distros installed.": "Nu sunt instalate alte distribuții WSL.", "WSL integration": "Integrare WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Închide: memoria folosită de fereastră este eliberată. Redeschiderea durează o clipă, iar terminalele deschise se închid.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri și acest PC", "Kiri and this computer": "Kiri și acest computer", "Versions, {os}, whether the engine runs, how many containers and images": "Versiuni, {os}, dacă motorul rulează, câte containere și imagini", - "Saved. The engine uses these from its next start": "Salvat. Motorul le folosește de la următoarea pornire" + "Saved. The engine uses these from its next start": "Salvat. Motorul le folosește de la următoarea pornire", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Niciodată", + "Build cache limit": "Limită cache de build", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Cele mai vechi straturi din cache sunt curățate automat când cache-ul BuildKit depășește această dimensiune.", + "Stop builder when idle": "Oprește builderul când e inactiv", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Oprește BuildKit între build-uri ca să nu consume memorie cât e inactiv; următorul build îl trezește în sub o secundă.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB sau KIRI_BUILDER_IDLE_SECS este setat pentru daemon și are prioritate față de acestea.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: cel mai rapid. Comută pe Releu gazdă dacă Cloudflare WARP sau un firewall corporativ blochează HTTPS-ul din containere. Se aplică la repornirea VM-ului.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Releu gazdă: conexiunile ies din Kiri pe macOS în loc de NAT-ul Virtualization.framework. Se aplică la repornirea VM-ului.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT este setat în mediu și are prioritate.", + "Outbound VM traffic": "Trafic de ieșire VM", + "macOS NAT": "NAT macOS", + "Host relay": "Releu gazdă", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Maximul la care poate crește discul VM-ului. Spațiul pe {os} este folosit doar pe măsură ce se scriu date, iar spațiul nefolosit poate fi recuperat în {storage}. Se aplică la repornire.", + "Settings → Storage": "Setări → Stocare", + "VM disk space": "Spațiu pe discul VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux nativ folosește direct sistemul de fișiere gazdă — imaginile și volumele șterse eliberează spațiul imediat.", + "Compact disk…": "Compactează discul…", + "Reclaim space": "Recuperează spațiu", + "Compacting…": "Se compactează…", + "Reclaiming…": "Se recuperează…", + "Compacting {vhdx} and restarting the engine…": "Se compactează {vhdx} și se repornește motorul…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} pe {os}, {inUse} în uz în VM · se eliberează blocurile nefolosite…", + "Trimming unused blocks inside the VM disk…": "Se eliberează blocurile nefolosite din discul VM-ului…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} pe Windows ({vhdx}), {inUse} în uz · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} pe {os}, {inUse} în uz în VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} pe Windows ({vhdx}), {inUse} în uz · nimic de recuperat.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} pe {os}, {inUse} în uz în VM · nimic de recuperat.", + "Nothing to reclaim.": "Nimic de recuperat.", + "{size} can be given back": "se pot elibera {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} pe Windows ({vhdx}), {inUse} în uz · {can}. Compactarea repornește motorul.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} pe {os}, {inUse} în uz în VM · {can} fără a opri containerele.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} pe Windows ({vhdx}). Compactarea returnează spațiul nefolosit și repornește motorul.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} pe {os}. Recuperarea eliberează blocurile nefolosite din discul VM-ului fără a opri containerele.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Returnează spațiul nefolosit din {vhdx} către Windows. Compactarea repornește motorul.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Returnează blocurile nefolosite din discul VM-ului către {os} fără a opri containerele.", + "Cleaning up stopped containers, untagged images, and build cache…": "Se curăță containerele oprite, imaginile fără etichetă și cache-ul de build…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache de build", + "No stopped containers, untagged images or build cache · {freed}.": "Niciun container oprit, imagine fără etichetă sau cache de build · {freed}.", + "No stopped containers, untagged images or build cache.": "Niciun container oprit, imagine fără etichetă sau cache de build.", + "Cleaning up…": "Se curăță…", + "Clean up…": "Curăță…", + "Unused Docker data": "Date Docker nefolosite", + "Command-line tools in shell": "Instrumente în linia de comandă în shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Adaugă {bin} în {zshrc} și {zprofile} pentru ca {docker}, {kubectl} și {kiri} să funcționeze în terminalele noi.", + "Uninstall Kiri": "Dezinstalează Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Oprește motorul, elimină serviciul de fundal Kiri, linkurile CLI și intrările din profilurile shell, și restaurează contextul Docker anterior ({cmd}).", + "Uninstall Kiri…": "Dezinstalează Kiri…", + "Couldn't reclaim disk space: {error}": "Nu s-a putut recupera spațiul pe disc: {error}", + "Reclaimed {size} on {os}": "S-au recuperat {size} pe {os}", + "Nothing to reclaim": "Nimic de recuperat", + "Couldn't clean up unused Docker data: {error}": "Nu s-au putut curăța datele Docker nefolosite: {error}", + "Cleaned up {size} of unused Docker data": "S-au curățat {size} de date Docker nefolosite", + "Cleaned up unused Docker data": "S-au curățat datele Docker nefolosite", + "Compact WSL disk?": "Compactezi discul WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Compactarea fișierului {vhdx} returnează spațiul nefolosit către Windows și repornește scurt motorul Kiri și containerele care rulează.", + "Compact disk": "Compactează discul", + "Clean up unused Docker data?": "Cureți datele Docker nefolosite?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Elimină containerele oprite, imaginile fără etichetă și cache-ul de build BuildKit. Containerele active și imaginile cu etichetă sunt păstrate.", + "Clean up": "Curăță", + "Uninstall Kiri?": "Dezinstalezi Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Oprește motorul, elimină serviciul de fundal Kiri, linkurile CLI și intrările din profilurile shell, și restaurează contextul Docker anterior. Imaginile și volumele rămân în dosarul de date Kiri până când îl ștergi.", + "Cluster": "Cluster", + "default": "implicit", + "k3s version": "Versiune k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versiunea imaginii pentru nodul clusterului ({cmd}). Se aplică la recreare.", + "Extra server flags": "Argumente suplimentare server", + "Passed to {srv} ({flag}), separated by spaces.": "Transmise către {srv} ({flag}), separate prin spații.", + "Startup manifests": "Manifeste la pornire", + "YAML files in {path} are applied whenever the cluster starts.": "Fișierele YAML din {path} sunt aplicate ori de câte ori pornește clusterul.", + "Open folder": "Deschide dosarul", + "{n} untagged image": "{n} imagine fără etichetă", + "{n} untagged images": "Imagini fără etichetă: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Dezinstalează Kiri din Setări Windows → Aplicații", + "Builder settings saved": "Setările builderului au fost salvate", + "Could not save builder settings: {error}": "Nu s-au putut salva setările builderului: {error}", + "Disk reclaim is already running": "Recuperarea spațiului pe disc rulează deja", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Setarea pentru traficul de ieșire VM a fost salvată. Repornește VM-ul pentru a aplica.", + "Could not save VM networking setting: {error}": "Nu s-a putut salva setarea de rețea a VM-ului: {error}", + "Added Kiri command-line tools to shell profiles": "Instrumentele în linia de comandă Kiri au fost adăugate în profilurile shell", + "Removed Kiri command-line tools from shell profiles": "Instrumentele în linia de comandă Kiri au fost eliminate din profilurile shell", + "Could not update shell profiles: {error}": "Nu s-au putut actualiza profilurile shell: {error}", + "Uninstalling Kiri…": "Se dezinstalează Kiri…", + "Could not uninstall Kiri: {error}": "Nu s-a putut dezinstala Kiri: {error}", + "Uninstall Kiri using your system package manager": "Dezinstalează Kiri folosind gestionarul de pachete al sistemului" } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index 5f4ea176d..fcc1248af 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -1854,7 +1854,6 @@ "Disk image size": "Размер образа диска", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задана переменная KIRI_CPUS, KIRI_MEMORY_MIB или KIRI_DISK_GB, и она имеет приоритет над этими настройками.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Сейчас работает с {cpus}, до {mem} памяти и диском {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных; размер никогда не уменьшается. Применяется после перезапуска.", "No other WSL distros installed.": "Другие дистрибутивы WSL не установлены.", "WSL integration": "Интеграция с WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрыть: память, которую занимает окно, освобождается. Повторное открытие занимает мгновение, а открытые терминалы закрываются.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri и этот ПК", "Kiri and this computer": "Kiri и этот компьютер", "Versions, {os}, whether the engine runs, how many containers and images": "Версии, {os}, работает ли движок, количество контейнеров и образов", - "Saved. The engine uses these from its next start": "Сохранено. Движок применит эти настройки при следующем запуске" + "Saved. The engine uses these from its next start": "Сохранено. Движок применит эти настройки при следующем запуске", + "5 min": "5 мин", + "10 min": "10 мин", + "30 min": "30 мин", + "Never": "Никогда", + "Build cache limit": "Лимит кеша сборки", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Самые старые закешированные слои удаляются автоматически, когда кеш BuildKit превышает этот размер.", + "Stop builder when idle": "Останавливать сборщик при простое", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Останавливает BuildKit между сборками, чтобы он не занимал память в простое; следующая сборка запускает его менее чем за секунду.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Для демона задана переменная KIRI_BUILD_CACHE_GB или KIRI_BUILDER_IDLE_SECS, и она имеет приоритет над этими настройками.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: самый быстрый вариант. Переключитесь на «Ретранслятор хоста», если Cloudflare WARP или корпоративный межсетевой экран блокирует HTTPS в контейнерах. Применяется после перезапуска ВМ.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Ретранслятор хоста: соединения выходят через Kiri в macOS вместо NAT из Virtualization.framework. Применяется после перезапуска ВМ.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "В окружении задана переменная KIRI_SHARED_NAT, и она имеет приоритет.", + "Outbound VM traffic": "Исходящий трафик ВМ", + "macOS NAT": "NAT macOS", + "Host relay": "Ретранслятор хоста", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Максимум, до которого может вырасти диск ВМ. Место на {os} занимается только по мере записи данных, а неиспользуемое место можно вернуть в разделе {storage}. Применяется после перезапуска.", + "Settings → Storage": "Настройки → Накопитель", + "VM disk space": "Место на диске ВМ", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "В Linux напрямую используется файловая система хоста — удаление образов и томов освобождает место сразу.", + "Compact disk…": "Сжать диск…", + "Reclaim space": "Вернуть место", + "Compacting…": "Сжатие…", + "Reclaiming…": "Освобождение…", + "Compacting {vhdx} and restarting the engine…": "Сжатие {vhdx} и перезапуск движка…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} в {os}, {inUse} занято внутри ВМ · освобождение неиспользуемых блоков…", + "Trimming unused blocks inside the VM disk…": "Освобождение неиспользуемых блоков диска ВМ…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} в Windows ({vhdx}), {inUse} занято · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} в {os}, {inUse} занято внутри ВМ · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} в Windows ({vhdx}), {inUse} занято · освобождать нечего.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} в {os}, {inUse} занято внутри ВМ · освобождать нечего.", + "Nothing to reclaim.": "Освобождать нечего.", + "{size} can be given back": "можно вернуть {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} в Windows ({vhdx}), {inUse} занято · {can}. Сжатие перезапустит движок.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} в {os}, {inUse} занято внутри ВМ · {can} без остановки контейнеров.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} в Windows ({vhdx}). Сжатие возвращает неиспользуемое место и перезапускает движок.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} в {os}. Освобождение очищает неиспользуемые блоки диска ВМ без остановки контейнеров.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Возвращает неиспользуемое место в {vhdx} системе Windows. Сжатие перезапустит движок.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Возвращает неиспользуемые блоки диска ВМ системе {os} без остановки контейнеров.", + "Cleaning up stopped containers, untagged images, and build cache…": "Очистка остановленных контейнеров, образов без тегов и кеша сборки…", + "{count} ({size})": "{count} ({size})", + "build cache": "кеш сборки", + "No stopped containers, untagged images or build cache · {freed}.": "Нет остановленных контейнеров, образов без тегов и кеша сборки · {freed}.", + "No stopped containers, untagged images or build cache.": "Нет остановленных контейнеров, образов без тегов и кеша сборки.", + "Cleaning up…": "Очистка…", + "Clean up…": "Очистить…", + "Unused Docker data": "Неиспользуемые данные Docker", + "Command-line tools in shell": "Инструменты командной строки в оболочке", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Добавить {bin} в {zshrc} и {zprofile}, чтобы {docker}, {kubectl} и {kiri} работали в новых окнах терминала.", + "Uninstall Kiri": "Удалить Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Останавливает движок, удаляет фоновую службу Kiri, ссылки CLI и записи в профилях оболочки, а также восстанавливает прежний контекст Docker ({cmd}).", + "Uninstall Kiri…": "Удалить Kiri…", + "Couldn't reclaim disk space: {error}": "Не удалось освободить место на диске: {error}", + "Reclaimed {size} on {os}": "Освобождено {size} в {os}", + "Nothing to reclaim": "Освобождать нечего", + "Couldn't clean up unused Docker data: {error}": "Не удалось очистить неиспользуемые данные Docker: {error}", + "Cleaned up {size} of unused Docker data": "Очищено неиспользуемых данных Docker: {size}", + "Cleaned up unused Docker data": "Неиспользуемые данные Docker очищены", + "Compact WSL disk?": "Сжать диск WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Сжатие {vhdx} возвращает неиспользуемое место в Windows и ненадолго перезапускает движок Kiri и запущенные контейнеры.", + "Compact disk": "Сжать диск", + "Clean up unused Docker data?": "Очистить неиспользуемые данные Docker?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Удаляет остановленные контейнеры, образы без тегов и кеш сборки BuildKit. Запущенные контейнеры и образы с тегами сохраняются.", + "Clean up": "Очистить", + "Uninstall Kiri?": "Удалить Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Останавливает движок, удаляет фоновую службу Kiri, ссылки CLI и записи в профилях оболочки, а также восстанавливает прежний контекст Docker. Ваши образы и тома останутся в папке данных Kiri, пока вы её не удалите.", + "Cluster": "Кластер", + "default": "по умолчанию", + "k3s version": "Версия k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Версия образа узла кластера ({cmd}). Применяется при пересоздании.", + "Extra server flags": "Дополнительные флаги сервера", + "Passed to {srv} ({flag}), separated by spaces.": "Передаются в {srv} ({flag}), разделяются пробелами.", + "Startup manifests": "Манифесты автозапуска", + "YAML files in {path} are applied whenever the cluster starts.": "YAML-файлы из {path} применяются при каждом запуске кластера.", + "Open folder": "Открыть папку", + "{n} untagged image": "{n} образ без тега", + "{n} untagged images": "образов без тегов: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Удалите Kiri в разделе Параметры Windows → Приложения", + "Builder settings saved": "Настройки сборщика сохранены", + "Could not save builder settings: {error}": "Не удалось сохранить настройки сборщика: {error}", + "Disk reclaim is already running": "Освобождение места на диске уже выполняется", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Настройка исходящего трафика ВМ сохранена. Перезапустите ВМ, чтобы применить её.", + "Could not save VM networking setting: {error}": "Не удалось сохранить сетевую настройку ВМ: {error}", + "Added Kiri command-line tools to shell profiles": "Инструменты командной строки Kiri добавлены в профили оболочки", + "Removed Kiri command-line tools from shell profiles": "Инструменты командной строки Kiri удалены из профилей оболочки", + "Could not update shell profiles: {error}": "Не удалось обновить профили оболочки: {error}", + "Uninstalling Kiri…": "Удаление Kiri…", + "Could not uninstall Kiri: {error}": "Не удалось удалить Kiri: {error}", + "Uninstall Kiri using your system package manager": "Удалите Kiri с помощью системного пакетного менеджера" } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index 400bc703f..79b032c8b 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -1854,7 +1854,6 @@ "Disk image size": "Velikost slike diska", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Za demon je nastavljen KIRI_CPUS, KIRI_MEMORY_MIB ali KIRI_DISK_GB, ki ima prednost pred temi nastavitvami.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Zdaj teče s {cpus}, največ {mem} in diskom {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov; disk se nikoli ne skrči. Uveljavi se ob ponovnem zagonu.", "No other WSL distros installed.": "Nameščene ni nobene druge distribucije WSL.", "WSL integration": "Integracija z WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Zapri: pomnilnik, ki ga uporablja okno, se sprosti. Ponovno odpiranje traja trenutek, odprti terminali pa se končajo.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri in ta PC", "Kiri and this computer": "Kiri in ta računalnik", "Versions, {os}, whether the engine runs, how many containers and images": "Različice, {os}, ali pogon teče, koliko je kontejnerjev in slik", - "Saved. The engine uses these from its next start": "Shranjeno. Pogon jih uporablja od naslednjega zagona" + "Saved. The engine uses these from its next start": "Shranjeno. Pogon jih uporablja od naslednjega zagona", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Nikoli", + "Build cache limit": "Omejitev predpomnilnika gradenj", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Najstarejši predpomnjeni sloji se samodejno odstranijo, ko predpomnilnik BuildKita preseže to velikost.", + "Stop builder when idle": "Ustavi gradilnik ob nedejavnosti", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Med gradnjami ustavi BuildKit, da ob nedejavnosti ne porablja pomnilnika; naslednja gradnja ga prebudi v manj kot sekundi.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Za demon je nastavljen KIRI_BUILD_CACHE_GB ali KIRI_BUILDER_IDLE_SECS, ki ima prednost pred temi nastavitvami.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: najhitrejše. Preklopite na Posrednik gostitelja, če Cloudflare WARP ali požarni zid podjetja blokira HTTPS kontejnerjev. Uveljavi se ob ponovnem zagonu VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Posrednik gostitelja: povezave gredo prek Kirija v macOS namesto prek NAT-a ogrodja Virtualization.framework. Uveljavi se ob ponovnem zagonu VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "V okolju je nastavljen KIRI_SHARED_NAT, ki ima prednost.", + "Outbound VM traffic": "Odhodni promet VM", + "macOS NAT": "macOS NAT", + "Host relay": "Posrednik gostitelja", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Največja velikost, do katere lahko zraste disk navideznega računalnika. Prostor v sistemu {os} se porablja šele ob zapisovanju podatkov, neuporabljeni prostor pa lahko sprostite v {storage}. Uveljavi se ob ponovnem zagonu.", + "Settings → Storage": "Nastavitve → Shramba", + "VM disk space": "Prostor na disku VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Domorodni Linux uporablja datotečni sistem gostitelja neposredno — izbrisane slike in nosilci takoj sprostijo prostor.", + "Compact disk…": "Strni disk …", + "Reclaim space": "Sprosti prostor", + "Compacting…": "Strnjevanje …", + "Reclaiming…": "Sproščanje …", + "Compacting {vhdx} and restarting the engine…": "Strnjevanje {vhdx} in ponovni zagon pogona …", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} v sistemu {os}, {inUse} v uporabi v VM · sproščanje neuporabljenih blokov …", + "Trimming unused blocks inside the VM disk…": "Sproščanje neuporabljenih blokov na disku VM …", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} v sistemu Windows ({vhdx}), {inUse} v uporabi · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} v sistemu {os}, {inUse} v uporabi v VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} v sistemu Windows ({vhdx}), {inUse} v uporabi · ničesar ni mogoče sprostiti.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} v sistemu {os}, {inUse} v uporabi v VM · ničesar ni mogoče sprostiti.", + "Nothing to reclaim.": "Ničesar ni mogoče sprostiti.", + "{size} can be given back": "vrniti je mogoče {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} v sistemu Windows ({vhdx}), {inUse} v uporabi · {can}. Strnjevanje znova zažene pogon.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} v sistemu {os}, {inUse} v uporabi v VM · {can} brez ustavljanja kontejnerjev.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} v sistemu Windows ({vhdx}). Strnjevanje vrne neuporabljeni prostor in znova zažene pogon.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} v sistemu {os}. Sproščanje počisti neuporabljene bloke na disku VM brez ustavljanja kontejnerjev.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Vrne neuporabljeni prostor v {vhdx} sistemu Windows. Strnjevanje znova zažene pogon.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Vrne neuporabljene bloke na disku VM sistemu {os} brez ustavljanja kontejnerjev.", + "Cleaning up stopped containers, untagged images, and build cache…": "Čiščenje ustavljenih kontejnerjev, slik brez oznake in predpomnilnika gradenj …", + "{count} ({size})": "{count} ({size})", + "build cache": "predpomnilnik gradenj", + "No stopped containers, untagged images or build cache · {freed}.": "Ni ustavljenih kontejnerjev, slik brez oznake ali predpomnilnika gradenj · {freed}.", + "No stopped containers, untagged images or build cache.": "Ni ustavljenih kontejnerjev, slik brez oznake ali predpomnilnika gradenj.", + "Cleaning up…": "Čiščenje …", + "Clean up…": "Počisti …", + "Unused Docker data": "Neuporabljeni podatki Dockerja", + "Command-line tools in shell": "Orodja ukazne vrstice v lupini", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Dodajte {bin} v {zshrc} in {zprofile}, da bodo {docker}, {kubectl} in {kiri} delovali v novih terminalih.", + "Uninstall Kiri": "Odstrani Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Ustavi pogon, odstrani Kirijevo storitev v ozadju, povezave CLI in vnose v profilih lupine ter obnovi prejšnji kontekst Dockerja ({cmd}).", + "Uninstall Kiri…": "Odstrani Kiri …", + "Couldn't reclaim disk space: {error}": "Prostora na disku ni bilo mogoče sprostiti: {error}", + "Reclaimed {size} on {os}": "Sproščeno {size} v sistemu {os}", + "Nothing to reclaim": "Ničesar ni mogoče sprostiti", + "Couldn't clean up unused Docker data: {error}": "Neuporabljenih podatkov Dockerja ni bilo mogoče počistiti: {error}", + "Cleaned up {size} of unused Docker data": "Počiščeno {size} neuporabljenih podatkov Dockerja", + "Cleaned up unused Docker data": "Neuporabljeni podatki Dockerja so počiščeni", + "Compact WSL disk?": "Strnim disk WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Strnjevanje {vhdx} vrne neuporabljeni prostor sistemu Windows ter za kratek čas znova zažene Kirijev pogon in delujoče kontejnerje.", + "Compact disk": "Strni disk", + "Clean up unused Docker data?": "Počistim neuporabljene podatke Dockerja?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Odstrani ustavljene kontejnerje, slike brez oznake in predpomnilnik gradenj BuildKita. Delujoči kontejnerji in označene slike se ohranijo.", + "Clean up": "Počisti", + "Uninstall Kiri?": "Odstranim Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Ustavi pogon, odstrani Kirijevo storitev v ozadju, povezave CLI in vnose v profilih lupine ter obnovi prejšnji kontekst Dockerja. Vaše slike in nosilci ostanejo v Kirijevi podatkovni mapi, dokler je ne izbrišete.", + "Cluster": "Gruča", + "default": "privzeto", + "k3s version": "Različica k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Različica slike za vozlišče gruče ({cmd}). Uveljavi se ob ponovni ustvaritvi.", + "Extra server flags": "Dodatne zastavice strežnika", + "Passed to {srv} ({flag}), separated by spaces.": "Posredovane ukazu {srv} ({flag}), ločene s presledki.", + "Startup manifests": "Zagonski manifesti", + "YAML files in {path} are applied whenever the cluster starts.": "Datoteke YAML v mapi {path} se uveljavijo ob vsakem zagonu gruče.", + "Open folder": "Odpri mapo", + "{n} untagged image": "{n} slika brez oznake", + "{n} untagged images": "Slike brez oznake: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Odstranite Kiri v Nastavitve sistema Windows → Aplikacije", + "Builder settings saved": "Nastavitve gradilnika shranjene", + "Could not save builder settings: {error}": "Nastavitev gradilnika ni bilo mogoče shraniti: {error}", + "Disk reclaim is already running": "Sproščanje prostora na disku že poteka", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Nastavitev odhodnega prometa VM je shranjena. Za uveljavitev znova zaženite VM.", + "Could not save VM networking setting: {error}": "Omrežne nastavitve VM ni bilo mogoče shraniti: {error}", + "Added Kiri command-line tools to shell profiles": "Orodja ukazne vrstice Kiri dodana v profile lupine", + "Removed Kiri command-line tools from shell profiles": "Orodja ukazne vrstice Kiri odstranjena iz profilov lupine", + "Could not update shell profiles: {error}": "Profilov lupine ni bilo mogoče posodobiti: {error}", + "Uninstalling Kiri…": "Odstranjevanje Kirija …", + "Could not uninstall Kiri: {error}": "Kirija ni bilo mogoče odstraniti: {error}", + "Uninstall Kiri using your system package manager": "Odstranite Kiri z upraviteljem paketov svojega sistema" } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index 8796f0225..dfded937e 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -1854,7 +1854,6 @@ "Disk image size": "Madhësia e imazhit të diskut", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB ose KIRI_DISK_GB është vendosur për daemon-in dhe ka përparësi ndaj këtyre.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Tani në punë me {cpus}, deri në {mem} dhe disk {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna; nuk tkurret kurrë. Zbatohet pas rinisjes.", "No other WSL distros installed.": "Nuk ka shpërndarje të tjera WSL të instaluara.", "WSL integration": "Integrimi me WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Mbyll: memoria që përdor dritarja lirohet. Rihapja zgjat një çast dhe terminalet e hapura mbyllen.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri dhe ky PC", "Kiri and this computer": "Kiri dhe ky kompjuter", "Versions, {os}, whether the engine runs, how many containers and images": "Versionet, {os}, nëse motori është në punë, sa kontejnerë dhe imazhe", - "Saved. The engine uses these from its next start": "U ruajt. Motori i përdor që nga nisja e tij e ardhshme" + "Saved. The engine uses these from its next start": "U ruajt. Motori i përdor që nga nisja e tij e ardhshme", + "5 min": "5 min", + "10 min": "10 min", + "30 min": "30 min", + "Never": "Kurrë", + "Build cache limit": "Kufiri i cache-it të ndërtimit", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Shtresat më të vjetra në cache pastrohen automatikisht kur cache-i i BuildKit e kalon këtë madhësi.", + "Stop builder when idle": "Ndalo ndërtuesin kur është joaktiv", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Ndalon BuildKit midis ndërtimeve që të mos përdorë memorie kur është joaktiv; ndërtimi tjetër e zgjon në më pak se një sekondë.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB ose KIRI_BUILDER_IDLE_SECS është vendosur për daemon-in dhe ka përparësi ndaj këtyre.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT i macOS: më i shpejti. Kaloni te Releja e hostit nëse Cloudflare WARP ose një firewall korporativ bllokon HTTPS-në e kontejnerëve. Zbatohet pas rinisjes së VM-së.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Releja e hostit: lidhjet dalin nga Kiri në macOS në vend të NAT-it të Virtualization.framework. Zbatohet pas rinisjes së VM-së.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT është vendosur në mjedis dhe ka përparësi.", + "Outbound VM traffic": "Trafiku dalës i VM-së", + "macOS NAT": "NAT i macOS", + "Host relay": "Releja e hostit", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Maksimumi deri ku mund të rritet disku i VM-së. Hapësira në {os} përdoret vetëm kur shkruhen të dhëna, dhe hapësira e papërdorur mund të rikuperohet te {storage}. Zbatohet pas rinisjes.", + "Settings → Storage": "Cilësimet → Hapësira ruajtëse", + "VM disk space": "Hapësira e diskut të VM-së", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux-i vendas përdor drejtpërdrejt sistemin e skedarëve të hostit — imazhet dhe vëllimet e fshira lirojnë hapësirën menjëherë.", + "Compact disk…": "Ngjesh diskun…", + "Reclaim space": "Rikupero hapësirën", + "Compacting…": "Po ngjeshet…", + "Reclaiming…": "Po rikuperohet…", + "Compacting {vhdx} and restarting the engine…": "Po ngjeshet {vhdx} dhe po riniset motori…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} në {os}, {inUse} në përdorim brenda VM-së · po lirohen blloqet e papërdorura…", + "Trimming unused blocks inside the VM disk…": "Po lirohen blloqet e papërdorura brenda diskut të VM-së…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} në Windows ({vhdx}), {inUse} në përdorim · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} në {os}, {inUse} në përdorim brenda VM-së · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} në Windows ({vhdx}), {inUse} në përdorim · asgjë për të rikuperuar.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} në {os}, {inUse} në përdorim brenda VM-së · asgjë për të rikuperuar.", + "Nothing to reclaim.": "Asgjë për të rikuperuar.", + "{size} can be given back": "{size} mund të kthehen", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} në Windows ({vhdx}), {inUse} në përdorim · {can}. Ngjeshja rinis motorin.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} në {os}, {inUse} në përdorim brenda VM-së · {can} pa ndalur kontejnerët.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} në Windows ({vhdx}). Ngjeshja kthen hapësirën e papërdorur dhe rinis motorin.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} në {os}. Rikuperimi liron blloqet e papërdorura në diskun e VM-së pa ndalur kontejnerët.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Kthen hapësirën e papërdorur në {vhdx} te Windows. Ngjeshja rinis motorin.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Kthen blloqet e papërdorura në diskun e VM-së te {os} pa ndalur kontejnerët.", + "Cleaning up stopped containers, untagged images, and build cache…": "Po pastrohen kontejnerët e ndalur, imazhet pa etiketë dhe cache-i i ndërtimit…", + "{count} ({size})": "{count} ({size})", + "build cache": "cache i ndërtimit", + "No stopped containers, untagged images or build cache · {freed}.": "Asnjë kontejner i ndalur, imazh pa etiketë ose cache ndërtimi · {freed}.", + "No stopped containers, untagged images or build cache.": "Asnjë kontejner i ndalur, imazh pa etiketë ose cache ndërtimi.", + "Cleaning up…": "Po pastrohet…", + "Clean up…": "Pastro…", + "Unused Docker data": "Të dhëna të papërdorura të Docker", + "Command-line tools in shell": "Mjetet e rreshtit të komandave në shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Shto {bin} te {zshrc} dhe {zprofile} që {docker}, {kubectl} dhe {kiri} të punojnë në terminalet e reja.", + "Uninstall Kiri": "Çinstalo Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Ndalon motorin, heq shërbimin në sfond të Kiri, lidhjet CLI dhe hyrjet në profilet e shell-it, dhe rikthen kontekstin e mëparshëm të Docker ({cmd}).", + "Uninstall Kiri…": "Çinstalo Kiri…", + "Couldn't reclaim disk space: {error}": "Hapësira e diskut nuk u rikuperua dot: {error}", + "Reclaimed {size} on {os}": "U rikuperua {size} në {os}", + "Nothing to reclaim": "Asgjë për të rikuperuar", + "Couldn't clean up unused Docker data: {error}": "Të dhënat e papërdorura të Docker nuk u pastruan dot: {error}", + "Cleaned up {size} of unused Docker data": "U pastrua {size} të dhëna të papërdorura të Docker", + "Cleaned up unused Docker data": "Të dhënat e papërdorura të Docker u pastruan", + "Compact WSL disk?": "Të ngjeshet disku WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Ngjeshja e {vhdx} ia kthen hapësirën e papërdorur Windows-it dhe rinis shkurtimisht motorin e Kiri dhe kontejnerët në punë.", + "Compact disk": "Ngjesh diskun", + "Clean up unused Docker data?": "Të pastrohen të dhënat e papërdorura të Docker?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Heq kontejnerët e ndalur, imazhet pa etiketë dhe cache-in e ndërtimit të BuildKit. Kontejnerët në punë dhe imazhet me etiketë ruhen.", + "Clean up": "Pastro", + "Uninstall Kiri?": "Të çinstalohet Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Ndalon motorin, heq shërbimin në sfond të Kiri, lidhjet CLI dhe hyrjet në profilet e shell-it, dhe rikthen kontekstin e mëparshëm të Docker. Imazhet dhe vëllimet tuaja mbeten në dosjen e të dhënave të Kiri derisa ta fshini atë.", + "Cluster": "Klasteri", + "default": "parazgjedhje", + "k3s version": "Versioni i k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Versioni i imazhit për nyjën e klasterit ({cmd}). Zbatohet kur rikrijohet.", + "Extra server flags": "Opsione shtesë të serverit", + "Passed to {srv} ({flag}), separated by spaces.": "I kalohen {srv} ({flag}), të ndara me hapësira.", + "Startup manifests": "Manifestet e nisjes", + "YAML files in {path} are applied whenever the cluster starts.": "Skedarët YAML në {path} zbatohen sa herë që niset klasteri.", + "Open folder": "Hap dosjen", + "{n} untagged image": "{n} imazh pa etiketë", + "{n} untagged images": "{n} imazhe pa etiketë", + "Uninstall Kiri from Windows Settings → Apps": "Çinstaloni Kiri nga Cilësimet e Windows → Aplikacionet", + "Builder settings saved": "Cilësimet e ndërtuesit u ruajtën", + "Could not save builder settings: {error}": "Cilësimet e ndërtuesit nuk u ruajtën: {error}", + "Disk reclaim is already running": "Rikuperimi i diskut është tashmë në punë", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Cilësimi i trafikut dalës të VM-së u ruajt. Rinisni VM-në për ta zbatuar.", + "Could not save VM networking setting: {error}": "Cilësimi i rrjetit të VM-së nuk u ruajt: {error}", + "Added Kiri command-line tools to shell profiles": "Mjetet e rreshtit të komandave të Kiri u shtuan në profilet e shell-it", + "Removed Kiri command-line tools from shell profiles": "Mjetet e rreshtit të komandave të Kiri u hoqën nga profilet e shell-it", + "Could not update shell profiles: {error}": "Profilet e shell-it nuk u përditësuan dot: {error}", + "Uninstalling Kiri…": "Po çinstalohet Kiri…", + "Could not uninstall Kiri: {error}": "Kiri nuk u çinstalua dot: {error}", + "Uninstall Kiri using your system package manager": "Çinstaloni Kiri duke përdorur menaxherin e paketave të sistemit" } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index f579083d6..dfc556569 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -1854,7 +1854,6 @@ "Disk image size": "வட்டுப் பட அளவு", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "டீமனுக்கு KIRI_CPUS, KIRI_MEMORY_MIB அல்லது KIRI_DISK_GB அமைக்கப்பட்டுள்ளது, அது இவற்றை விட முன்னுரிமை பெறும்.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "இப்போது {cpus}, அதிகபட்சம் {mem} மற்றும் {disk} வட்டுடன் இயங்குகிறது.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; இது ஒருபோதும் சுருங்காது. மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", "No other WSL distros installed.": "வேறு எந்த WSL விநியோகங்களும் நிறுவப்படவில்லை.", "WSL integration": "WSL ஒருங்கிணைப்பு", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "மூடு: சாளரம் பயன்படுத்தும் நினைவகம் விடுவிக்கப்படும். மீண்டும் திறக்கச் சற்று நேரமாகும், திறந்திருக்கும் டெர்மினல்கள் முடிவடையும்.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri-யும் இந்த PC-யும்", "Kiri and this computer": "Kiri-யும் இந்தக் கணினியும்", "Versions, {os}, whether the engine runs, how many containers and images": "பதிப்புகள், {os}, இன்ஜின் இயங்குகிறதா, எத்தனை கன்டெய்னர்கள், இமேஜ்கள்", - "Saved. The engine uses these from its next start": "சேமிக்கப்பட்டது. இன்ஜின் அடுத்த தொடக்கத்திலிருந்து இவற்றைப் பயன்படுத்தும்" + "Saved. The engine uses these from its next start": "சேமிக்கப்பட்டது. இன்ஜின் அடுத்த தொடக்கத்திலிருந்து இவற்றைப் பயன்படுத்தும்", + "5 min": "5 நிமி", + "10 min": "10 நிமி", + "30 min": "30 நிமி", + "Never": "ஒருபோதுமில்லை", + "Build cache limit": "பில்ட் கேஷ் வரம்பு", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit-இன் கேஷ் இந்த அளவைத் தாண்டியதும் பழைய கேஷ் லேயர்கள் தானாக அகற்றப்படும்.", + "Stop builder when idle": "சும்மா இருக்கும்போது பில்டரை நிறுத்து", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "பில்ட்களுக்கு இடையில் சும்மா இருக்கும்போது நினைவகத்தைப் பயன்படுத்தாதபடி BuildKit-ஐ நிறுத்தும்; அடுத்த பில்ட் ஒரு வினாடிக்குள் அதை எழுப்பிவிடும்.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "டீமனுக்கு KIRI_BUILD_CACHE_GB அல்லது KIRI_BUILDER_IDLE_SECS அமைக்கப்பட்டுள்ளது, அது இவற்றை விட முன்னுரிமை பெறும்.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: மிக வேகமானது. Cloudflare WARP அல்லது நிறுவன ஃபயர்வால் கன்டெய்னர் HTTPS-ஐத் தடுத்தால் ஹோஸ்ட் ரிலே-க்கு மாற்றவும். VM மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "ஹோஸ்ட் ரிலே: இணைப்புகள் Virtualization.framework NAT-க்குப் பதிலாக macOS-இல் உள்ள Kiri வழியாகச் செல்லும். VM மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "சூழலில் KIRI_SHARED_NAT அமைக்கப்பட்டுள்ளது, அது முன்னுரிமை பெறும்.", + "Outbound VM traffic": "வெளிச்செல்லும் VM போக்குவரத்து", + "macOS NAT": "macOS NAT", + "Host relay": "ஹோஸ்ட் ரிலே", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM வட்டு அதிகபட்சம் வளரக்கூடிய அளவு. தரவு எழுதப்படும்போது மட்டுமே {os}-இல் இடம் பயன்படுத்தப்படும்; பயன்படுத்தப்படாத இடத்தை {storage}-இல் மீட்டெடுக்கலாம். மறுதொடக்கத்தில் நடைமுறைக்கு வரும்.", + "Settings → Storage": "அமைப்புகள் → சேமிப்பகம்", + "VM disk space": "VM வட்டு இடம்", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "நேட்டிவ் Linux நேரடியாக ஹோஸ்ட் கோப்பு முறைமையைப் பயன்படுத்துகிறது — நீக்கப்பட்ட இமேஜ்களும் வால்யூம்களும் உடனடியாக இடத்தை விடுவிக்கும்.", + "Compact disk…": "வட்டைச் சுருக்கு…", + "Reclaim space": "இடத்தை மீட்டெடு", + "Compacting…": "சுருக்குகிறது…", + "Reclaiming…": "மீட்டெடுக்கிறது…", + "Compacting {vhdx} and restarting the engine…": "{vhdx}-ஐச் சுருக்கி இன்ஜினை மறுதொடக்குகிறது…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os}-இல் {host}, VM-க்குள் {inUse} பயன்பாட்டில் · பயன்படுத்தப்படாத தொகுதிகளை விடுவிக்கிறது…", + "Trimming unused blocks inside the VM disk…": "VM வட்டுக்குள் பயன்படுத்தப்படாத தொகுதிகளை விடுவிக்கிறது…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows-இல் {host} ({vhdx}), {inUse} பயன்பாட்டில் · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os}-இல் {host}, VM-க்குள் {inUse} பயன்பாட்டில் · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows-இல் {host} ({vhdx}), {inUse} பயன்பாட்டில் · மீட்டெடுக்க எதுவுமில்லை.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os}-இல் {host}, VM-க்குள் {inUse} பயன்பாட்டில் · மீட்டெடுக்க எதுவுமில்லை.", + "Nothing to reclaim.": "மீட்டெடுக்க எதுவுமில்லை.", + "{size} can be given back": "{size} திருப்பித் தரலாம்", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows-இல் {host} ({vhdx}), {inUse} பயன்பாட்டில் · {can}. சுருக்குவது இன்ஜினை மறுதொடக்கும்.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os}-இல் {host}, VM-க்குள் {inUse} பயன்பாட்டில் · கன்டெய்னர்களை நிறுத்தாமல் {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows-இல் {host} ({vhdx}). சுருக்குவது பயன்படுத்தப்படாத இடத்தைத் திருப்பித் தந்து இன்ஜினை மறுதொடக்கும்.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os}-இல் {host}. மீட்டெடுப்பு கன்டெய்னர்களை நிறுத்தாமல் VM வட்டில் பயன்படுத்தப்படாத தொகுதிகளை விடுவிக்கும்.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx}-இல் பயன்படுத்தப்படாத இடத்தை Windows-க்குத் திருப்பித் தரும். சுருக்குவது இன்ஜினை மறுதொடக்கும்.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "கன்டெய்னர்களை நிறுத்தாமல் VM வட்டில் பயன்படுத்தப்படாத தொகுதிகளை {os}-க்குத் திருப்பித் தரும்.", + "Cleaning up stopped containers, untagged images, and build cache…": "நிறுத்தப்பட்ட கன்டெய்னர்கள், டேக் இல்லாத இமேஜ்கள், பில்ட் கேஷ் ஆகியவற்றைச் சுத்தம் செய்கிறது…", + "{count} ({size})": "{count} ({size})", + "build cache": "பில்ட் கேஷ்", + "No stopped containers, untagged images or build cache · {freed}.": "நிறுத்தப்பட்ட கன்டெய்னர்கள், டேக் இல்லாத இமேஜ்கள் அல்லது பில்ட் கேஷ் இல்லை · {freed}.", + "No stopped containers, untagged images or build cache.": "நிறுத்தப்பட்ட கன்டெய்னர்கள், டேக் இல்லாத இமேஜ்கள் அல்லது பில்ட் கேஷ் இல்லை.", + "Cleaning up…": "சுத்தம் செய்கிறது…", + "Clean up…": "சுத்தம் செய்…", + "Unused Docker data": "பயன்படுத்தப்படாத Docker தரவு", + "Command-line tools in shell": "ஷெல்லில் கட்டளை-வரி கருவிகள்", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "புதிய டெர்மினல்களில் {docker}, {kubectl}, {kiri} வேலை செய்ய {zshrc} மற்றும் {zprofile}-இல் {bin}-ஐச் சேர்க்கவும்.", + "Uninstall Kiri": "Kiri-ஐ நிறுவல் நீக்கு", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "இன்ஜினை நிறுத்தி, Kiri-யின் பின்னணி சேவை, CLI இணைப்புகள், ஷெல் சுயவிவரப் பதிவுகளை அகற்றி, முந்தைய Docker சூழலை ({cmd}) மீட்டமைக்கும்.", + "Uninstall Kiri…": "Kiri-ஐ நிறுவல் நீக்கு…", + "Couldn't reclaim disk space: {error}": "வட்டு இடத்தை மீட்டெடுக்க முடியவில்லை: {error}", + "Reclaimed {size} on {os}": "{os}-இல் {size} மீட்டெடுக்கப்பட்டது", + "Nothing to reclaim": "மீட்டெடுக்க எதுவுமில்லை", + "Couldn't clean up unused Docker data: {error}": "பயன்படுத்தப்படாத Docker தரவைச் சுத்தம் செய்ய முடியவில்லை: {error}", + "Cleaned up {size} of unused Docker data": "{size} பயன்படுத்தப்படாத Docker தரவு சுத்தம் செய்யப்பட்டது", + "Cleaned up unused Docker data": "பயன்படுத்தப்படாத Docker தரவு சுத்தம் செய்யப்பட்டது", + "Compact WSL disk?": "WSL வட்டைச் சுருக்கவா?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx}-ஐச் சுருக்குவது பயன்படுத்தப்படாத இடத்தை Windows-க்குத் திருப்பித் தரும், மேலும் Kiri இன்ஜினையும் இயங்கும் கன்டெய்னர்களையும் சிறிது நேரம் மறுதொடக்கும்.", + "Compact disk": "வட்டைச் சுருக்கு", + "Clean up unused Docker data?": "பயன்படுத்தப்படாத Docker தரவைச் சுத்தம் செய்யவா?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "நிறுத்தப்பட்ட கன்டெய்னர்கள், டேக் இல்லாத இமேஜ்கள், BuildKit பில்ட் கேஷ் ஆகியவற்றை அகற்றும். இயங்கும் கன்டெய்னர்களும் டேக் உள்ள இமேஜ்களும் பாதுகாக்கப்படும்.", + "Clean up": "சுத்தம் செய்", + "Uninstall Kiri?": "Kiri-ஐ நிறுவல் நீக்கவா?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "இன்ஜினை நிறுத்தி, Kiri-யின் பின்னணி சேவை, CLI இணைப்புகள், ஷெல் சுயவிவரப் பதிவுகளை அகற்றி, முந்தைய Docker சூழலை மீட்டமைக்கும். உங்கள் இமேஜ்களும் வால்யூம்களும் Kiri தரவுக் கோப்புறையை நீங்கள் நீக்கும் வரை அங்கேயே இருக்கும்.", + "Cluster": "க்ளஸ்டர்", + "default": "இயல்புநிலை", + "k3s version": "k3s பதிப்பு", + "Image version for the cluster node ({cmd}). Applies when recreated.": "க்ளஸ்டர் முனைக்கான இமேஜ் பதிப்பு ({cmd}). மீண்டும் உருவாக்கும்போது பொருந்தும்.", + "Extra server flags": "கூடுதல் சர்வர் கொடிகள்", + "Passed to {srv} ({flag}), separated by spaces.": "இடைவெளியால் பிரிக்கப்பட்டு {srv}-க்கு ({flag}) அனுப்பப்படும்.", + "Startup manifests": "தொடக்க மேனிஃபெஸ்ட்கள்", + "YAML files in {path} are applied whenever the cluster starts.": "க்ளஸ்டர் தொடங்கும்போதெல்லாம் {path}-இல் உள்ள YAML கோப்புகள் பயன்படுத்தப்படும்.", + "Open folder": "கோப்புறையைத் திற", + "{n} untagged image": "டேக் இல்லாத {n} இமேஜ்", + "{n} untagged images": "டேக் இல்லாத {n} இமேஜ்கள்", + "Uninstall Kiri from Windows Settings → Apps": "Windows அமைப்புகள் → பயன்பாடுகள் வழியாக Kiri-ஐ நிறுவல் நீக்கவும்", + "Builder settings saved": "பில்டர் அமைப்புகள் சேமிக்கப்பட்டன", + "Could not save builder settings: {error}": "பில்டர் அமைப்புகளைச் சேமிக்க முடியவில்லை: {error}", + "Disk reclaim is already running": "வட்டு இட மீட்டெடுப்பு ஏற்கனவே நடைபெறுகிறது", + "Outbound VM traffic setting saved. Restart the VM to apply.": "வெளிச்செல்லும் VM போக்குவரத்து அமைப்பு சேமிக்கப்பட்டது. பொருத்த VM-ஐ மறுதொடக்கவும்.", + "Could not save VM networking setting: {error}": "VM நெட்வொர்க் அமைப்பைச் சேமிக்க முடியவில்லை: {error}", + "Added Kiri command-line tools to shell profiles": "ஷெல் சுயவிவரங்களில் Kiri கட்டளை-வரி கருவிகள் சேர்க்கப்பட்டன", + "Removed Kiri command-line tools from shell profiles": "ஷெல் சுயவிவரங்களிலிருந்து Kiri கட்டளை-வரி கருவிகள் அகற்றப்பட்டன", + "Could not update shell profiles: {error}": "ஷெல் சுயவிவரங்களைப் புதுப்பிக்க முடியவில்லை: {error}", + "Uninstalling Kiri…": "Kiri நிறுவல் நீக்கப்படுகிறது…", + "Could not uninstall Kiri: {error}": "Kiri-ஐ நிறுவல் நீக்க முடியவில்லை: {error}", + "Uninstall Kiri using your system package manager": "உங்கள் கணினி தொகுப்பு மேலாளரைப் பயன்படுத்தி Kiri-ஐ நிறுவல் நீக்கவும்" } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 6554d317c..fbe229378 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -1854,7 +1854,6 @@ "Disk image size": "డిస్క్ ఇమేజ్ పరిమాణం", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "డెమన్‌కు KIRI_CPUS, KIRI_MEMORY_MIB లేదా KIRI_DISK_GB సెట్ చేయబడింది, అది వీటి కంటే ప్రాధాన్యం పొందుతుంది.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ఇప్పుడు {cpus}, గరిష్టంగా {mem}, {disk} డిస్క్‌తో రన్ అవుతోంది.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది; ఇది ఎప్పుడూ తగ్గదు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది.", "No other WSL distros installed.": "ఇతర WSL డిస్ట్రోలు ఏవీ ఇన్‌స్టాల్ చేయబడలేదు.", "WSL integration": "WSL ఇంటిగ్రేషన్", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "మూసివేయి: విండో వాడే మెమరీ విడుదల అవుతుంది. మళ్లీ తెరవడానికి కొంత సమయం పడుతుంది, తెరిచి ఉన్న టెర్మినల్స్ ముగుస్తాయి.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri, ఈ PC", "Kiri and this computer": "Kiri, ఈ కంప్యూటర్", "Versions, {os}, whether the engine runs, how many containers and images": "వెర్షన్‌లు, {os}, ఇంజిన్ రన్ అవుతోందా, ఎన్ని కంటైనర్‌లు, ఇమేజ్‌లు", - "Saved. The engine uses these from its next start": "సేవ్ అయింది. ఇంజిన్ తదుపరి ప్రారంభం నుండి వీటిని వాడుతుంది" + "Saved. The engine uses these from its next start": "సేవ్ అయింది. ఇంజిన్ తదుపరి ప్రారంభం నుండి వీటిని వాడుతుంది", + "5 min": "5 నిమి", + "10 min": "10 నిమి", + "30 min": "30 నిమి", + "Never": "ఎప్పుడూ వద్దు", + "Build cache limit": "బిల్డ్ కాష్ పరిమితి", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit కాష్ ఈ పరిమాణాన్ని దాటినప్పుడు పాత కాష్ లేయర్‌లు స్వయంచాలకంగా తొలగించబడతాయి.", + "Stop builder when idle": "ఖాళీగా ఉన్నప్పుడు బిల్డర్‌ను ఆపు", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "ఖాళీగా ఉన్నప్పుడు మెమరీ వాడకుండా బిల్డ్‌ల మధ్య BuildKitని ఆపుతుంది; తదుపరి బిల్డ్ దాన్ని ఒక సెకనులోపు మేల్కొలుపుతుంది.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "డెమన్‌కు KIRI_BUILD_CACHE_GB లేదా KIRI_BUILDER_IDLE_SECS సెట్ చేయబడింది, అది వీటి కంటే ప్రాధాన్యం పొందుతుంది.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: అత్యంత వేగవంతమైనది. Cloudflare WARP లేదా కార్పొరేట్ ఫైర్‌వాల్ కంటైనర్ HTTPSని అడ్డుకుంటే హోస్ట్ రిలేకి మార్చండి. VM రీస్టార్ట్ తర్వాత వర్తిస్తుంది.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "హోస్ట్ రిలే: కనెక్షన్‌లు Virtualization.framework NATకి బదులు macOSలోని Kiri నుండి బయటకు వెళ్తాయి. VM రీస్టార్ట్ తర్వాత వర్తిస్తుంది.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "ఎన్విరాన్‌మెంట్‌లో KIRI_SHARED_NAT సెట్ చేయబడింది, దానికి ప్రాధాన్యం ఉంటుంది.", + "Outbound VM traffic": "VM అవుట్‌బౌండ్ ట్రాఫిక్", + "macOS NAT": "macOS NAT", + "Host relay": "హోస్ట్ రిలే", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM డిస్క్ పెరగగల గరిష్ట పరిమాణం. డేటా రాసినప్పుడు మాత్రమే {os}లో స్థలం వాడబడుతుంది, మరియు వాడని స్థలాన్ని {storage}లో తిరిగి పొందవచ్చు. రీస్టార్ట్ చేసినప్పుడు వర్తిస్తుంది.", + "Settings → Storage": "సెట్టింగ్‌లు → స్టోరేజ్", + "VM disk space": "VM డిస్క్ స్థలం", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "నేటివ్ Linux నేరుగా హోస్ట్ ఫైల్‌సిస్టమ్‌ను వాడుతుంది — తొలగించిన ఇమేజ్‌లు, వాల్యూమ్‌లు వెంటనే స్థలాన్ని ఖాళీ చేస్తాయి.", + "Compact disk…": "డిస్క్ కుదించు…", + "Reclaim space": "స్థలం తిరిగి పొందు", + "Compacting…": "కుదిస్తోంది…", + "Reclaiming…": "తిరిగి పొందుతోంది…", + "Compacting {vhdx} and restarting the engine…": "{vhdx}ని కుదించి ఇంజిన్‌ను రీస్టార్ట్ చేస్తోంది…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os}లో {host}, VM లోపల {inUse} వాడుకలో · వాడని బ్లాక్‌లను ట్రిమ్ చేస్తోంది…", + "Trimming unused blocks inside the VM disk…": "VM డిస్క్ లోపల వాడని బ్లాక్‌లను ట్రిమ్ చేస్తోంది…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windowsలో {host} ({vhdx}), {inUse} వాడుకలో · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os}లో {host}, VM లోపల {inUse} వాడుకలో · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windowsలో {host} ({vhdx}), {inUse} వాడుకలో · తిరిగి పొందడానికి ఏమీ లేదు.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os}లో {host}, VM లోపల {inUse} వాడుకలో · తిరిగి పొందడానికి ఏమీ లేదు.", + "Nothing to reclaim.": "తిరిగి పొందడానికి ఏమీ లేదు.", + "{size} can be given back": "{size} తిరిగి ఇవ్వవచ్చు", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windowsలో {host} ({vhdx}), {inUse} వాడుకలో · {can}. కుదించడం వల్ల ఇంజిన్ రీస్టార్ట్ అవుతుంది.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os}లో {host}, VM లోపల {inUse} వాడుకలో · కంటైనర్‌లను ఆపకుండా {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windowsలో {host} ({vhdx}). కుదించడం వాడని స్థలాన్ని తిరిగి ఇచ్చి ఇంజిన్‌ను రీస్టార్ట్ చేస్తుంది.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os}లో {host}. కంటైనర్‌లను ఆపకుండా VM డిస్క్‌లోని వాడని బ్లాక్‌లను ట్రిమ్ చేస్తుంది.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx}లోని వాడని స్థలాన్ని Windowsకు తిరిగి ఇస్తుంది. కుదించడం వల్ల ఇంజిన్ రీస్టార్ట్ అవుతుంది.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "కంటైనర్‌లను ఆపకుండా VM డిస్క్‌లోని వాడని బ్లాక్‌లను {os}కు తిరిగి ఇస్తుంది.", + "Cleaning up stopped containers, untagged images, and build cache…": "ఆగిన కంటైనర్‌లు, ట్యాగ్ లేని ఇమేజ్‌లు, బిల్డ్ కాష్‌ను శుభ్రం చేస్తోంది…", + "{count} ({size})": "{count} ({size})", + "build cache": "బిల్డ్ కాష్", + "No stopped containers, untagged images or build cache · {freed}.": "ఆగిన కంటైనర్‌లు, ట్యాగ్ లేని ఇమేజ్‌లు లేదా బిల్డ్ కాష్ లేవు · {freed}.", + "No stopped containers, untagged images or build cache.": "ఆగిన కంటైనర్‌లు, ట్యాగ్ లేని ఇమేజ్‌లు లేదా బిల్డ్ కాష్ లేవు.", + "Cleaning up…": "శుభ్రం చేస్తోంది…", + "Clean up…": "శుభ్రం చేయి…", + "Unused Docker data": "వాడని Docker డేటా", + "Command-line tools in shell": "షెల్‌లో కమాండ్-లైన్ టూల్స్", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "కొత్త టెర్మినల్స్‌లో {docker}, {kubectl}, {kiri} పనిచేయడానికి {zshrc}, {zprofile}లకు {bin}ని జోడించండి.", + "Uninstall Kiri": "Kiriని అన్‌ఇన్‌స్టాల్ చేయి", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "ఇంజిన్‌ను ఆపి, Kiri బ్యాక్‌గ్రౌండ్ సర్వీస్, CLI లింక్‌లు, షెల్ ప్రొఫైల్ ఎంట్రీలను తొలగించి, మీ మునుపటి Docker కాంటెక్స్ట్ ({cmd})ని పునరుద్ధరిస్తుంది.", + "Uninstall Kiri…": "Kiriని అన్‌ఇన్‌స్టాల్ చేయి…", + "Couldn't reclaim disk space: {error}": "డిస్క్ స్థలాన్ని తిరిగి పొందలేకపోయాం: {error}", + "Reclaimed {size} on {os}": "{os}లో {size} తిరిగి పొందబడింది", + "Nothing to reclaim": "తిరిగి పొందడానికి ఏమీ లేదు", + "Couldn't clean up unused Docker data: {error}": "వాడని Docker డేటాను శుభ్రం చేయలేకపోయాం: {error}", + "Cleaned up {size} of unused Docker data": "{size} వాడని Docker డేటా శుభ్రం చేయబడింది", + "Cleaned up unused Docker data": "వాడని Docker డేటా శుభ్రం చేయబడింది", + "Compact WSL disk?": "WSL డిస్క్‌ను కుదించాలా?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx}ని కుదించడం వాడని స్థలాన్ని Windowsకు తిరిగి ఇస్తుంది మరియు Kiri ఇంజిన్‌తో పాటు రన్ అవుతున్న కంటైనర్‌లను కాసేపు రీస్టార్ట్ చేస్తుంది.", + "Compact disk": "డిస్క్ కుదించు", + "Clean up unused Docker data?": "వాడని Docker డేటాను శుభ్రం చేయాలా?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "ఆగిన కంటైనర్‌లు, ట్యాగ్ లేని ఇమేజ్‌లు, BuildKit బిల్డ్ కాష్‌ను తొలగిస్తుంది. రన్ అవుతున్న కంటైనర్‌లు, ట్యాగ్ ఉన్న ఇమేజ్‌లు అలాగే ఉంటాయి.", + "Clean up": "శుభ్రం చేయి", + "Uninstall Kiri?": "Kiriని అన్‌ఇన్‌స్టాల్ చేయాలా?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "ఇంజిన్‌ను ఆపి, Kiri బ్యాక్‌గ్రౌండ్ సర్వీస్, CLI లింక్‌లు, షెల్ ప్రొఫైల్ ఎంట్రీలను తొలగించి, మీ మునుపటి Docker కాంటెక్స్ట్‌ను పునరుద్ధరిస్తుంది. మీరు తొలగించే వరకు మీ ఇమేజ్‌లు, వాల్యూమ్‌లు Kiri డేటా ఫోల్డర్‌లోనే ఉంటాయి.", + "Cluster": "క్లస్టర్", + "default": "డిఫాల్ట్", + "k3s version": "k3s వెర్షన్", + "Image version for the cluster node ({cmd}). Applies when recreated.": "క్లస్టర్ నోడ్ ఇమేజ్ వెర్షన్ ({cmd}). మళ్లీ సృష్టించినప్పుడు వర్తిస్తుంది.", + "Extra server flags": "అదనపు సర్వర్ ఫ్లాగ్‌లు", + "Passed to {srv} ({flag}), separated by spaces.": "స్పేస్‌లతో వేరు చేసి {srv} ({flag})కు పంపబడతాయి.", + "Startup manifests": "స్టార్టప్ మానిఫెస్ట్‌లు", + "YAML files in {path} are applied whenever the cluster starts.": "క్లస్టర్ ప్రారంభమైన ప్రతిసారీ {path}లోని YAML ఫైల్‌లు వర్తింపజేయబడతాయి.", + "Open folder": "ఫోల్డర్ తెరువు", + "{n} untagged image": "ట్యాగ్ లేని {n} ఇమేజ్", + "{n} untagged images": "ట్యాగ్ లేని {n} ఇమేజ్‌లు", + "Uninstall Kiri from Windows Settings → Apps": "Windows సెట్టింగ్‌లు → యాప్‌ల నుండి Kiriని అన్‌ఇన్‌స్టాల్ చేయండి", + "Builder settings saved": "బిల్డర్ సెట్టింగ్‌లు సేవ్ అయ్యాయి", + "Could not save builder settings: {error}": "బిల్డర్ సెట్టింగ్‌లు సేవ్ చేయలేకపోయాం: {error}", + "Disk reclaim is already running": "డిస్క్ స్థలం తిరిగి పొందే ప్రక్రియ ఇప్పటికే నడుస్తోంది", + "Outbound VM traffic setting saved. Restart the VM to apply.": "VM అవుట్‌బౌండ్ ట్రాఫిక్ సెట్టింగ్ సేవ్ అయింది. వర్తింపజేయడానికి VMని రీస్టార్ట్ చేయండి.", + "Could not save VM networking setting: {error}": "VM నెట్‌వర్క్ సెట్టింగ్ సేవ్ చేయలేకపోయాం: {error}", + "Added Kiri command-line tools to shell profiles": "షెల్ ప్రొఫైల్‌లకు Kiri కమాండ్-లైన్ టూల్స్ జోడించబడ్డాయి", + "Removed Kiri command-line tools from shell profiles": "షెల్ ప్రొఫైల్‌ల నుండి Kiri కమాండ్-లైన్ టూల్స్ తొలగించబడ్డాయి", + "Could not update shell profiles: {error}": "షెల్ ప్రొఫైల్‌లను అప్‌డేట్ చేయలేకపోయాం: {error}", + "Uninstalling Kiri…": "Kiri అన్‌ఇన్‌స్టాల్ అవుతోంది…", + "Could not uninstall Kiri: {error}": "Kiriని అన్‌ఇన్‌స్టాల్ చేయలేకపోయాం: {error}", + "Uninstall Kiri using your system package manager": "మీ సిస్టమ్ ప్యాకేజీ మేనేజర్‌తో Kiriని అన్‌ఇన్‌స్టాల్ చేయండి" } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index 1a3d8a5ee..f0ff9933f 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -1854,7 +1854,6 @@ "Disk image size": "ขนาดอิมเมจดิสก์", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "มีการตั้งค่า KIRI_CPUS, KIRI_MEMORY_MIB หรือ KIRI_DISK_GB ให้ daemon ซึ่งมีลำดับความสำคัญเหนือค่าเหล่านี้", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "ขณะนี้ทำงานด้วย {cpus} สูงสุด {mem} และดิสก์ {disk}", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และจะไม่หดเล็กลง มีผลเมื่อรีสตาร์ท", "No other WSL distros installed.": "ไม่มีดิสโทร WSL อื่นติดตั้งอยู่", "WSL integration": "การผสานรวม WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "ปิด: คืนหน่วยความจำที่หน้าต่างใช้ การเปิดอีกครั้งจะใช้เวลาสักครู่ และเทอร์มินัลที่เปิดอยู่จะถูกปิด", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri และ PC เครื่องนี้", "Kiri and this computer": "Kiri และคอมพิวเตอร์เครื่องนี้", "Versions, {os}, whether the engine runs, how many containers and images": "เวอร์ชัน {os} เอนจินทำงานอยู่หรือไม่ จำนวนคอนเทนเนอร์และอิมเมจ", - "Saved. The engine uses these from its next start": "บันทึกแล้ว เอนจินจะใช้ค่าเหล่านี้ตั้งแต่เริ่มครั้งถัดไป" + "Saved. The engine uses these from its next start": "บันทึกแล้ว เอนจินจะใช้ค่าเหล่านี้ตั้งแต่เริ่มครั้งถัดไป", + "5 min": "5 นาที", + "10 min": "10 นาที", + "30 min": "30 นาที", + "Never": "ไม่เลย", + "Build cache limit": "ขีดจำกัดแคชบิลด์", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "เลเยอร์แคชที่เก่าที่สุดจะถูกล้างอัตโนมัติเมื่อแคชของ BuildKit เกินขนาดนี้", + "Stop builder when idle": "หยุดบิลเดอร์เมื่อว่าง", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "หยุด BuildKit ระหว่างการบิลด์เพื่อไม่ให้ใช้หน่วยความจำขณะว่าง และปลุกกลับมาในการบิลด์ถัดไปภายในไม่ถึงวินาที", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "มีการตั้งค่า KIRI_BUILD_CACHE_GB หรือ KIRI_BUILDER_IDLE_SECS ให้ daemon ซึ่งมีลำดับความสำคัญเหนือค่าเหล่านี้", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: เร็วที่สุด สลับเป็นรีเลย์ผ่านโฮสต์หาก Cloudflare WARP หรือไฟร์วอลล์องค์กรบล็อก HTTPS ของคอนเทนเนอร์ มีผลเมื่อรีสตาร์ท VM", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "รีเลย์ผ่านโฮสต์: การเชื่อมต่อจะออกจาก Kiri บน macOS แทน NAT ของ Virtualization.framework มีผลเมื่อรีสตาร์ท VM", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "มีการตั้งค่า KIRI_SHARED_NAT ในสภาพแวดล้อมและมีลำดับความสำคัญเหนือกว่า", + "Outbound VM traffic": "ทราฟฟิกขาออกของ VM", + "macOS NAT": "macOS NAT", + "Host relay": "รีเลย์ผ่านโฮสต์", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "ขนาดสูงสุดที่ดิสก์ของ VM ขยายได้ พื้นที่บน {os} จะถูกใช้เมื่อมีการเขียนข้อมูลเท่านั้น และขอคืนพื้นที่ที่ไม่ได้ใช้ได้ใน{storage} มีผลเมื่อรีสตาร์ท", + "Settings → Storage": "การตั้งค่า → พื้นที่จัดเก็บ", + "VM disk space": "พื้นที่ดิสก์ของ VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux แบบเนทีฟใช้ระบบไฟล์ของโฮสต์โดยตรง เมื่อลบอิมเมจและโวลุ่มจะได้พื้นที่คืนทันที", + "Compact disk…": "บีบอัดดิสก์…", + "Reclaim space": "ขอพื้นที่คืน", + "Compacting…": "กำลังบีบอัด…", + "Reclaiming…": "กำลังขอพื้นที่คืน…", + "Compacting {vhdx} and restarting the engine…": "กำลังบีบอัด {vhdx} และรีสตาร์ทเอนจิน…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} บน {os}, ใช้อยู่ {inUse} ใน VM · กำลังตัดบล็อกที่ไม่ได้ใช้…", + "Trimming unused blocks inside the VM disk…": "กำลังตัดบล็อกที่ไม่ได้ใช้ในดิสก์ของ VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} บน Windows ({vhdx}), ใช้อยู่ {inUse} · {freed}", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} บน {os}, ใช้อยู่ {inUse} ใน VM · {freed}", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} บน Windows ({vhdx}), ใช้อยู่ {inUse} · ไม่มีพื้นที่ให้ขอคืน", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} บน {os}, ใช้อยู่ {inUse} ใน VM · ไม่มีพื้นที่ให้ขอคืน", + "Nothing to reclaim.": "ไม่มีพื้นที่ให้ขอคืน", + "{size} can be given back": "คืนพื้นที่ได้ {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} บน Windows ({vhdx}), ใช้อยู่ {inUse} · {can} การบีบอัดจะรีสตาร์ทเอนจิน", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} บน {os}, ใช้อยู่ {inUse} ใน VM · {can} โดยไม่ต้องหยุดคอนเทนเนอร์", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} บน Windows ({vhdx}) การบีบอัดจะคืนพื้นที่ที่ไม่ได้ใช้และรีสตาร์ทเอนจิน", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} บน {os} การขอพื้นที่คืนจะตัดบล็อกที่ไม่ได้ใช้ในดิสก์ของ VM โดยไม่ต้องหยุดคอนเทนเนอร์", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "คืนพื้นที่ที่ไม่ได้ใช้ใน {vhdx} ให้ Windows การบีบอัดจะรีสตาร์ทเอนจิน", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "คืนบล็อกที่ไม่ได้ใช้ในดิสก์ของ VM ให้ {os} โดยไม่ต้องหยุดคอนเทนเนอร์", + "Cleaning up stopped containers, untagged images, and build cache…": "กำลังล้างคอนเทนเนอร์ที่หยุดอยู่ อิมเมจที่ไม่มีแท็ก และแคชบิลด์…", + "{count} ({size})": "{count} ({size})", + "build cache": "แคชบิลด์", + "No stopped containers, untagged images or build cache · {freed}.": "ไม่มีคอนเทนเนอร์ที่หยุดอยู่ อิมเมจที่ไม่มีแท็ก หรือแคชบิลด์ · {freed}", + "No stopped containers, untagged images or build cache.": "ไม่มีคอนเทนเนอร์ที่หยุดอยู่ อิมเมจที่ไม่มีแท็ก หรือแคชบิลด์", + "Cleaning up…": "กำลังล้าง…", + "Clean up…": "ล้างข้อมูล…", + "Unused Docker data": "ข้อมูล Docker ที่ไม่ได้ใช้", + "Command-line tools in shell": "เครื่องมือบรรทัดคำสั่งในเชลล์", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "เพิ่ม {bin} ลงใน {zshrc} และ {zprofile} เพื่อให้ใช้ {docker}, {kubectl} และ {kiri} ในเทอร์มินัลใหม่ได้", + "Uninstall Kiri": "ถอนการติดตั้ง Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "หยุดเอนจิน ลบบริการเบื้องหลังของ Kiri ลิงก์ CLI และรายการในโปรไฟล์เชลล์ แล้วคืนค่าบริบท Docker ก่อนหน้า ({cmd})", + "Uninstall Kiri…": "ถอนการติดตั้ง Kiri…", + "Couldn't reclaim disk space: {error}": "ขอพื้นที่ดิสก์คืนไม่ได้: {error}", + "Reclaimed {size} on {os}": "ได้พื้นที่คืน {size} บน {os}", + "Nothing to reclaim": "ไม่มีพื้นที่ให้ขอคืน", + "Couldn't clean up unused Docker data: {error}": "ล้างข้อมูล Docker ที่ไม่ได้ใช้ไม่สำเร็จ: {error}", + "Cleaned up {size} of unused Docker data": "ล้างข้อมูล Docker ที่ไม่ได้ใช้แล้ว {size}", + "Cleaned up unused Docker data": "ล้างข้อมูล Docker ที่ไม่ได้ใช้แล้ว", + "Compact WSL disk?": "บีบอัดดิสก์ WSL หรือไม่", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "การบีบอัด {vhdx} จะคืนพื้นที่ที่ไม่ได้ใช้ให้ Windows และรีสตาร์ทเอนจินของ Kiri รวมถึงคอนเทนเนอร์ที่กำลังทำงานชั่วครู่", + "Compact disk": "บีบอัดดิสก์", + "Clean up unused Docker data?": "ล้างข้อมูล Docker ที่ไม่ได้ใช้หรือไม่", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "ลบคอนเทนเนอร์ที่หยุดอยู่ อิมเมจที่ไม่มีแท็ก และแคชบิลด์ของ BuildKit ส่วนคอนเทนเนอร์ที่ทำงานอยู่และอิมเมจที่มีแท็กจะถูกเก็บไว้", + "Clean up": "ล้างข้อมูล", + "Uninstall Kiri?": "ถอนการติดตั้ง Kiri หรือไม่", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "หยุดเอนจิน ลบบริการเบื้องหลังของ Kiri ลิงก์ CLI และรายการในโปรไฟล์เชลล์ แล้วคืนค่าบริบท Docker ก่อนหน้า อิมเมจและโวลุ่มของคุณจะยังอยู่ในโฟลเดอร์ข้อมูลของ Kiri จนกว่าคุณจะลบออก", + "Cluster": "คลัสเตอร์", + "default": "ค่าเริ่มต้น", + "k3s version": "เวอร์ชัน k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "เวอร์ชันอิมเมจสำหรับโหนดคลัสเตอร์ ({cmd}) มีผลเมื่อสร้างใหม่", + "Extra server flags": "แฟล็กเพิ่มเติมของเซิร์ฟเวอร์", + "Passed to {srv} ({flag}), separated by spaces.": "ส่งต่อไปยัง {srv} ({flag}) คั่นด้วยช่องว่าง", + "Startup manifests": "Manifest เมื่อเริ่มต้น", + "YAML files in {path} are applied whenever the cluster starts.": "ไฟล์ YAML ใน {path} จะถูกนำไปใช้ทุกครั้งที่คลัสเตอร์เริ่มทำงาน", + "Open folder": "เปิดโฟลเดอร์", + "{n} untagged image": "อิมเมจที่ไม่มีแท็ก {n} รายการ", + "{n} untagged images": "อิมเมจที่ไม่มีแท็ก {n} รายการ", + "Uninstall Kiri from Windows Settings → Apps": "ถอนการติดตั้ง Kiri ได้ที่การตั้งค่า Windows → แอป", + "Builder settings saved": "บันทึกการตั้งค่าบิลเดอร์แล้ว", + "Could not save builder settings: {error}": "บันทึกการตั้งค่าบิลเดอร์ไม่ได้: {error}", + "Disk reclaim is already running": "กำลังขอพื้นที่ดิสก์คืนอยู่แล้ว", + "Outbound VM traffic setting saved. Restart the VM to apply.": "บันทึกการตั้งค่าทราฟฟิกขาออกของ VM แล้ว รีสตาร์ท VM เพื่อใช้งาน", + "Could not save VM networking setting: {error}": "บันทึกการตั้งค่าเครือข่ายของ VM ไม่ได้: {error}", + "Added Kiri command-line tools to shell profiles": "เพิ่มเครื่องมือบรรทัดคำสั่งของ Kiri ลงในโปรไฟล์เชลล์แล้ว", + "Removed Kiri command-line tools from shell profiles": "ลบเครื่องมือบรรทัดคำสั่งของ Kiri ออกจากโปรไฟล์เชลล์แล้ว", + "Could not update shell profiles: {error}": "อัปเดตโปรไฟล์เชลล์ไม่ได้: {error}", + "Uninstalling Kiri…": "กำลังถอนการติดตั้ง Kiri…", + "Could not uninstall Kiri: {error}": "ถอนการติดตั้ง Kiri ไม่ได้: {error}", + "Uninstall Kiri using your system package manager": "ถอนการติดตั้ง Kiri ด้วยตัวจัดการแพ็กเกจของระบบ" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index 1061bc455..3b298ccca 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -1854,7 +1854,6 @@ "Disk image size": "Disk görüntüsü boyutu", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_CPUS, KIRI_MEMORY_MIB veya KIRI_DISK_GB ayarlı ve bunlar buradakilerden önceliklidir.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Şu anda {cpus}, en fazla {mem} ve {disk} disk ile çalışıyor.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; asla küçülmez. Yeniden başlatmada uygulanır.", "No other WSL distros installed.": "Başka WSL dağıtımı kurulu değil.", "WSL integration": "WSL entegrasyonu", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Kapat: pencerenin kullandığı bellek boşaltılır. Yeniden açılması biraz sürer ve açık terminaller kapanır.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri ve bu PC", "Kiri and this computer": "Kiri ve bu bilgisayar", "Versions, {os}, whether the engine runs, how many containers and images": "Sürümler, {os}, motorun çalışıp çalışmadığı, kapsayıcı ve görüntü sayısı", - "Saved. The engine uses these from its next start": "Kaydedildi. Motor bunları bir sonraki başlatmada kullanır" + "Saved. The engine uses these from its next start": "Kaydedildi. Motor bunları bir sonraki başlatmada kullanır", + "5 min": "5 dk", + "10 min": "10 dk", + "30 min": "30 dk", + "Never": "Asla", + "Build cache limit": "Derleme önbelleği sınırı", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit önbelleği bu boyutu aştığında en eski önbellek katmanları otomatik olarak temizlenir.", + "Stop builder when idle": "Boştayken derleyiciyi durdur", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Boştayken bellek kullanmaması için derlemeler arasında BuildKit'i durdurur; sonraki derleme bir saniyeden kısa sürede uyandırır.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_BUILD_CACHE_GB veya KIRI_BUILDER_IDLE_SECS ayarlı ve bunlar buradakilerden önceliklidir.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: en hızlısı. Cloudflare WARP veya kurumsal bir güvenlik duvarı kapsayıcı HTTPS trafiğini engelliyorsa Ana makine aktarımı'na geçin. VM yeniden başlatıldığında uygulanır.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Ana makine aktarımı: bağlantılar Virtualization.framework NAT yerine macOS üzerindeki Kiri üzerinden çıkar. VM yeniden başlatıldığında uygulanır.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Ortamda KIRI_SHARED_NAT ayarlı ve önceliklidir.", + "Outbound VM traffic": "Giden VM trafiği", + "macOS NAT": "macOS NAT", + "Host relay": "Ana makine aktarımı", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; kullanılmayan alan {storage} bölümünden geri kazanılabilir. Yeniden başlatmada uygulanır.", + "Settings → Storage": "Ayarlar → Depolama", + "VM disk space": "VM disk alanı", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Yerel Linux doğrudan ana bilgisayar dosya sistemini kullanır — silinen görüntüler ve birimler alanı anında boşaltır.", + "Compact disk…": "Diski sıkıştır…", + "Reclaim space": "Alanı geri kazan", + "Compacting…": "Sıkıştırılıyor…", + "Reclaiming…": "Geri kazanılıyor…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} sıkıştırılıyor ve motor yeniden başlatılıyor…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · kullanılmayan bloklar kırpılıyor…", + "Trimming unused blocks inside the VM disk…": "VM diski içindeki kullanılmayan bloklar kırpılıyor…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · geri kazanılacak alan yok.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · geri kazanılacak alan yok.", + "Nothing to reclaim.": "Geri kazanılacak alan yok.", + "{size} can be given back": "{size} geri verilebilir", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · {can}. Sıkıştırma motoru yeniden başlatır.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · kapsayıcıları durdurmadan {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows üzerinde {host} ({vhdx}). Sıkıştırma kullanılmayan alanı geri verir ve motoru yeniden başlatır.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} üzerinde {host}. Geri kazanma, kapsayıcıları durdurmadan VM diskindeki kullanılmayan blokları kırpar.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} içindeki kullanılmayan alanı Windows'a geri verir. Sıkıştırma motoru yeniden başlatır.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "VM diskindeki kullanılmayan blokları kapsayıcıları durdurmadan {os} sistemine geri verir.", + "Cleaning up stopped containers, untagged images, and build cache…": "Durdurulmuş kapsayıcılar, etiketsiz görüntüler ve derleme önbelleği temizleniyor…", + "{count} ({size})": "{count} ({size})", + "build cache": "derleme önbelleği", + "No stopped containers, untagged images or build cache · {freed}.": "Durdurulmuş kapsayıcı, etiketsiz görüntü veya derleme önbelleği yok · {freed}.", + "No stopped containers, untagged images or build cache.": "Durdurulmuş kapsayıcı, etiketsiz görüntü veya derleme önbelleği yok.", + "Cleaning up…": "Temizleniyor…", + "Clean up…": "Temizle…", + "Unused Docker data": "Kullanılmayan Docker verileri", + "Command-line tools in shell": "Kabukta komut satırı araçları", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Yeni terminallerde {docker}, {kubectl} ve {kiri} komutlarının çalışması için {zshrc} ve {zprofile} dosyalarına {bin} ekleyin.", + "Uninstall Kiri": "Kiri'yi kaldır", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Motoru durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve kabuk profili kayıtlarını kaldırır ve önceki Docker bağlamınızı ({cmd}) geri yükler.", + "Uninstall Kiri…": "Kiri'yi kaldır…", + "Couldn't reclaim disk space: {error}": "Disk alanı geri kazanılamadı: {error}", + "Reclaimed {size} on {os}": "{os} üzerinde {size} geri kazanıldı", + "Nothing to reclaim": "Geri kazanılacak alan yok", + "Couldn't clean up unused Docker data: {error}": "Kullanılmayan Docker verileri temizlenemedi: {error}", + "Cleaned up {size} of unused Docker data": "{size} kullanılmayan Docker verisi temizlendi", + "Cleaned up unused Docker data": "Kullanılmayan Docker verileri temizlendi", + "Compact WSL disk?": "WSL diski sıkıştırılsın mı?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} dosyasını sıkıştırmak kullanılmayan alanı Windows'a geri verir ve Kiri motorunu ve çalışan kapsayıcıları kısa süreliğine yeniden başlatır.", + "Compact disk": "Diski sıkıştır", + "Clean up unused Docker data?": "Kullanılmayan Docker verileri temizlensin mi?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Durdurulmuş kapsayıcıları, etiketsiz görüntüleri ve BuildKit derleme önbelleğini kaldırır. Çalışan kapsayıcılar ve etiketli görüntüler korunur.", + "Clean up": "Temizle", + "Uninstall Kiri?": "Kiri kaldırılsın mı?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Motoru durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve kabuk profili kayıtlarını kaldırır ve önceki Docker bağlamınızı geri yükler. Görüntüleriniz ve birimleriniz siz silene kadar Kiri'nin veri klasöründe kalır.", + "Cluster": "Küme", + "default": "varsayılan", + "k3s version": "k3s sürümü", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Küme düğümü için görüntü sürümü ({cmd}). Yeniden oluşturulduğunda uygulanır.", + "Extra server flags": "Ek sunucu bayrakları", + "Passed to {srv} ({flag}), separated by spaces.": "Boşluklarla ayrılarak {srv} komutuna ({flag}) iletilir.", + "Startup manifests": "Başlangıç manifestleri", + "YAML files in {path} are applied whenever the cluster starts.": "{path} içindeki YAML dosyaları küme her başladığında uygulanır.", + "Open folder": "Klasörü aç", + "{n} untagged image": "{n} etiketsiz görüntü", + "{n} untagged images": "{n} etiketsiz görüntü", + "Uninstall Kiri from Windows Settings → Apps": "Kiri'yi Windows Ayarları → Uygulamalar'dan kaldırın", + "Builder settings saved": "Derleyici ayarları kaydedildi", + "Could not save builder settings: {error}": "Derleyici ayarları kaydedilemedi: {error}", + "Disk reclaim is already running": "Disk alanı geri kazanma işlemi zaten çalışıyor", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Giden VM trafiği ayarı kaydedildi. Uygulamak için VM'yi yeniden başlatın.", + "Could not save VM networking setting: {error}": "VM ağ ayarı kaydedilemedi: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri komut satırı araçları kabuk profillerine eklendi", + "Removed Kiri command-line tools from shell profiles": "Kiri komut satırı araçları kabuk profillerinden kaldırıldı", + "Could not update shell profiles: {error}": "Kabuk profilleri güncellenemedi: {error}", + "Uninstalling Kiri…": "Kiri kaldırılıyor…", + "Could not uninstall Kiri: {error}": "Kiri kaldırılamadı: {error}", + "Uninstall Kiri using your system package manager": "Kiri'yi sistem paket yöneticinizi kullanarak kaldırın" } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 12be3b461..493a9d528 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -1854,7 +1854,6 @@ "Disk image size": "Розмір образу диска", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Для демона задано змінну KIRI_CPUS, KIRI_MEMORY_MIB або KIRI_DISK_GB, і вона має пріоритет над цими налаштуваннями.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Зараз працює з {cpus}, до {mem} пам’яті та диском {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних; розмір ніколи не зменшується. Застосовується після перезапуску.", "No other WSL distros installed.": "Інших дистрибутивів WSL не встановлено.", "WSL integration": "Інтеграція з WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Закрити: пам’ять, яку займає вікно, звільняється. Повторне відкриття триває мить, а відкриті термінали закриваються.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri і цей ПК", "Kiri and this computer": "Kiri і цей комп’ютер", "Versions, {os}, whether the engine runs, how many containers and images": "Версії, {os}, чи працює рушій, кількість контейнерів і образів", - "Saved. The engine uses these from its next start": "Збережено. Рушій застосує це під час наступного запуску" + "Saved. The engine uses these from its next start": "Збережено. Рушій застосує це під час наступного запуску", + "5 min": "5 хв", + "10 min": "10 хв", + "30 min": "30 хв", + "Never": "Ніколи", + "Build cache limit": "Ліміт кешу збірки", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Найстаріші кешовані шари видаляються автоматично, коли кеш BuildKit перевищує цей розмір.", + "Stop builder when idle": "Зупиняти збирач під час простою", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Зупиняє BuildKit між збірками, щоб він не займав пам’ять під час простою; наступна збірка запускає його менш ніж за секунду.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Для демона задано змінну KIRI_BUILD_CACHE_GB або KIRI_BUILDER_IDLE_SECS, і вона має пріоритет над цими налаштуваннями.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "NAT macOS: найшвидший варіант. Перемкніться на «Ретранслятор хоста», якщо Cloudflare WARP або корпоративний брандмауер блокує HTTPS у контейнерах. Застосовується після перезапуску ВМ.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Ретранслятор хоста: з’єднання виходять через Kiri в macOS замість NAT із Virtualization.framework. Застосовується після перезапуску ВМ.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "У середовищі задано змінну KIRI_SHARED_NAT, і вона має пріоритет.", + "Outbound VM traffic": "Вихідний трафік ВМ", + "macOS NAT": "NAT macOS", + "Host relay": "Ретранслятор хоста", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Максимум, до якого може вирости диск ВМ. Місце на {os} займається лише під час запису даних, а невикористане місце можна повернути в розділі {storage}. Застосовується після перезапуску.", + "Settings → Storage": "Налаштування → Сховище", + "VM disk space": "Місце на диску ВМ", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Нативний Linux використовує файлову систему хоста напряму — видалені образи й томи одразу звільняють місце.", + "Compact disk…": "Стиснути диск…", + "Reclaim space": "Повернути місце", + "Compacting…": "Стиснення…", + "Reclaiming…": "Звільнення…", + "Compacting {vhdx} and restarting the engine…": "Стиснення {vhdx} і перезапуск рушія…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} у {os}, {inUse} зайнято всередині ВМ · звільнення невикористаних блоків…", + "Trimming unused blocks inside the VM disk…": "Звільнення невикористаних блоків диска ВМ…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} у Windows ({vhdx}), {inUse} зайнято · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} у {os}, {inUse} зайнято всередині ВМ · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} у Windows ({vhdx}), {inUse} зайнято · нічого повертати.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} у {os}, {inUse} зайнято всередині ВМ · нічого повертати.", + "Nothing to reclaim.": "Нічого повертати.", + "{size} can be given back": "можна повернути {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} у Windows ({vhdx}), {inUse} зайнято · {can}. Стиснення перезапустить рушій.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} у {os}, {inUse} зайнято всередині ВМ · {can} без зупинки контейнерів.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} у Windows ({vhdx}). Стиснення повертає невикористане місце й перезапускає рушій.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} у {os}. Повернення місця очищає невикористані блоки диска ВМ без зупинки контейнерів.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Повертає невикористане місце у {vhdx} системі Windows. Стиснення перезапустить рушій.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Повертає невикористані блоки диска ВМ системі {os} без зупинки контейнерів.", + "Cleaning up stopped containers, untagged images, and build cache…": "Очищення зупинених контейнерів, образів без тегів і кешу збірки…", + "{count} ({size})": "{count} ({size})", + "build cache": "кеш збірки", + "No stopped containers, untagged images or build cache · {freed}.": "Немає зупинених контейнерів, образів без тегів чи кешу збірки · {freed}.", + "No stopped containers, untagged images or build cache.": "Немає зупинених контейнерів, образів без тегів чи кешу збірки.", + "Cleaning up…": "Очищення…", + "Clean up…": "Очистити…", + "Unused Docker data": "Невикористані дані Docker", + "Command-line tools in shell": "Інструменти командного рядка в оболонці", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Додати {bin} до {zshrc} і {zprofile}, щоб {docker}, {kubectl} і {kiri} працювали в нових вікнах термінала.", + "Uninstall Kiri": "Видалити Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Зупиняє рушій, видаляє фонову службу Kiri, посилання CLI й записи в профілях оболонки та відновлює попередній контекст Docker ({cmd}).", + "Uninstall Kiri…": "Видалити Kiri…", + "Couldn't reclaim disk space: {error}": "Не вдалося повернути місце на диску: {error}", + "Reclaimed {size} on {os}": "Повернуто {size} у {os}", + "Nothing to reclaim": "Нічого повертати", + "Couldn't clean up unused Docker data: {error}": "Не вдалося очистити невикористані дані Docker: {error}", + "Cleaned up {size} of unused Docker data": "Очищено {size} невикористаних даних Docker", + "Cleaned up unused Docker data": "Невикористані дані Docker очищено", + "Compact WSL disk?": "Стиснути диск WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Стиснення {vhdx} повертає невикористане місце у Windows і ненадовго перезапускає рушій Kiri та запущені контейнери.", + "Compact disk": "Стиснути диск", + "Clean up unused Docker data?": "Очистити невикористані дані Docker?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Видаляє зупинені контейнери, образи без тегів і кеш збірки BuildKit. Запущені контейнери й образи з тегами зберігаються.", + "Clean up": "Очистити", + "Uninstall Kiri?": "Видалити Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Зупиняє рушій, видаляє фонову службу Kiri, посилання CLI й записи в профілях оболонки та відновлює попередній контекст Docker. Ваші образи й томи залишаться в теці даних Kiri, доки ви її не видалите.", + "Cluster": "Кластер", + "default": "типово", + "k3s version": "Версія k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Версія образу вузла кластера ({cmd}). Застосовується під час перестворення.", + "Extra server flags": "Додаткові прапорці сервера", + "Passed to {srv} ({flag}), separated by spaces.": "Передаються в {srv} ({flag}), розділені пробілами.", + "Startup manifests": "Маніфести запуску", + "YAML files in {path} are applied whenever the cluster starts.": "YAML-файли з {path} застосовуються щоразу під час запуску кластера.", + "Open folder": "Відкрити теку", + "{n} untagged image": "{n} образ без тегу", + "{n} untagged images": "образів без тегів: {n}", + "Uninstall Kiri from Windows Settings → Apps": "Видаліть Kiri в розділі Налаштування Windows → Програми", + "Builder settings saved": "Налаштування збирача збережено", + "Could not save builder settings: {error}": "Не вдалося зберегти налаштування збирача: {error}", + "Disk reclaim is already running": "Повернення місця на диску вже виконується", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Налаштування вихідного трафіку ВМ збережено. Перезапустіть ВМ, щоб застосувати.", + "Could not save VM networking setting: {error}": "Не вдалося зберегти мережеве налаштування ВМ: {error}", + "Added Kiri command-line tools to shell profiles": "Інструменти командного рядка Kiri додано до профілів оболонки", + "Removed Kiri command-line tools from shell profiles": "Інструменти командного рядка Kiri видалено з профілів оболонки", + "Could not update shell profiles: {error}": "Не вдалося оновити профілі оболонки: {error}", + "Uninstalling Kiri…": "Видалення Kiri…", + "Could not uninstall Kiri: {error}": "Не вдалося видалити Kiri: {error}", + "Uninstall Kiri using your system package manager": "Видаліть Kiri за допомогою системного менеджера пакунків" } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index c28c14e8c..aeae1c4e0 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -1854,7 +1854,6 @@ "Disk image size": "Kích thước ảnh đĩa", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "KIRI_CPUS, KIRI_MEMORY_MIB hoặc KIRI_DISK_GB đã được đặt cho daemon và được ưu tiên hơn các thiết lập này.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Đang chạy với {cpus}, tối đa {mem} và đĩa {disk}.", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu; đĩa không bao giờ thu nhỏ. Áp dụng khi khởi động lại.", "No other WSL distros installed.": "Chưa cài đặt bản phân phối WSL nào khác.", "WSL integration": "Tích hợp WSL", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Đóng: giải phóng bộ nhớ cửa sổ đang dùng. Mở lại sẽ mất một lúc, và các terminal đang mở sẽ bị đóng.", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri và PC này", "Kiri and this computer": "Kiri và máy tính này", "Versions, {os}, whether the engine runs, how many containers and images": "Phiên bản, {os}, engine có chạy không, số container và image", - "Saved. The engine uses these from its next start": "Đã lưu. Engine dùng các giá trị này từ lần khởi động tới" + "Saved. The engine uses these from its next start": "Đã lưu. Engine dùng các giá trị này từ lần khởi động tới", + "5 min": "5 phút", + "10 min": "10 phút", + "30 min": "30 phút", + "Never": "Không bao giờ", + "Build cache limit": "Giới hạn build cache", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Các layer cache cũ nhất sẽ tự động được dọn khi cache của BuildKit vượt quá dung lượng này.", + "Stop builder when idle": "Dừng builder khi nhàn rỗi", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Dừng BuildKit giữa các lần build để không tốn bộ nhớ khi nhàn rỗi; lần build tiếp theo đánh thức nó trong chưa đầy một giây.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "KIRI_BUILD_CACHE_GB hoặc KIRI_BUILDER_IDLE_SECS đã được đặt cho daemon và được ưu tiên hơn các thiết lập này.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: nhanh nhất. Chuyển sang Chuyển tiếp host nếu Cloudflare WARP hoặc tường lửa doanh nghiệp chặn HTTPS của container. Áp dụng khi khởi động lại VM.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Chuyển tiếp host: kết nối đi ra từ Kiri trên macOS thay vì NAT của Virtualization.framework. Áp dụng khi khởi động lại VM.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "KIRI_SHARED_NAT đã được đặt trong môi trường và được ưu tiên.", + "Outbound VM traffic": "Lưu lượng đi ra của VM", + "macOS NAT": "macOS NAT", + "Host relay": "Chuyển tiếp host", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Mức tối đa đĩa VM có thể mở rộng. Dung lượng trên {os} chỉ được dùng khi ghi dữ liệu, và dung lượng không dùng có thể thu hồi trong {storage}. Áp dụng khi khởi động lại.", + "Settings → Storage": "Cài đặt → Lưu trữ", + "VM disk space": "Dung lượng đĩa VM", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux gốc dùng trực tiếp hệ thống tệp của máy chủ — xóa image và volume sẽ giải phóng dung lượng ngay lập tức.", + "Compact disk…": "Nén đĩa…", + "Reclaim space": "Thu hồi dung lượng", + "Compacting…": "Đang nén…", + "Reclaiming…": "Đang thu hồi…", + "Compacting {vhdx} and restarting the engine…": "Đang nén {vhdx} và khởi động lại engine…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} trên {os}, đang dùng {inUse} trong VM · đang cắt các khối không dùng…", + "Trimming unused blocks inside the VM disk…": "Đang cắt các khối không dùng trong đĩa VM…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} trên Windows ({vhdx}), đang dùng {inUse} · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} trên {os}, đang dùng {inUse} trong VM · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} trên Windows ({vhdx}), đang dùng {inUse} · không có gì để thu hồi.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} trên {os}, đang dùng {inUse} trong VM · không có gì để thu hồi.", + "Nothing to reclaim.": "Không có gì để thu hồi.", + "{size} can be given back": "có thể hoàn trả {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} trên Windows ({vhdx}), đang dùng {inUse} · {can}. Nén đĩa sẽ khởi động lại engine.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} trên {os}, đang dùng {inUse} trong VM · {can} mà không cần dừng container.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} trên Windows ({vhdx}). Nén đĩa hoàn trả dung lượng không dùng và khởi động lại engine.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} trên {os}. Thu hồi sẽ cắt các khối không dùng trong đĩa VM mà không dừng container.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Hoàn trả dung lượng không dùng trong {vhdx} cho Windows. Nén đĩa sẽ khởi động lại engine.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Hoàn trả các khối không dùng trong đĩa VM cho {os} mà không dừng container.", + "Cleaning up stopped containers, untagged images, and build cache…": "Đang dọn các container đã dừng, image không có tag và build cache…", + "{count} ({size})": "{count} ({size})", + "build cache": "build cache", + "No stopped containers, untagged images or build cache · {freed}.": "Không có container đã dừng, image không có tag hay build cache · {freed}.", + "No stopped containers, untagged images or build cache.": "Không có container đã dừng, image không có tag hay build cache.", + "Cleaning up…": "Đang dọn…", + "Clean up…": "Dọn dẹp…", + "Unused Docker data": "Dữ liệu Docker không dùng", + "Command-line tools in shell": "Công cụ dòng lệnh trong shell", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Thêm {bin} vào {zshrc} và {zprofile} để {docker}, {kubectl} và {kiri} hoạt động trong các cửa sổ terminal mới.", + "Uninstall Kiri": "Gỡ cài đặt Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Dừng engine, gỡ dịch vụ chạy nền của Kiri, liên kết CLI và các mục trong hồ sơ shell, đồng thời khôi phục ngữ cảnh Docker trước đó ({cmd}).", + "Uninstall Kiri…": "Gỡ cài đặt Kiri…", + "Couldn't reclaim disk space: {error}": "Không thể thu hồi dung lượng đĩa: {error}", + "Reclaimed {size} on {os}": "Đã thu hồi {size} trên {os}", + "Nothing to reclaim": "Không có gì để thu hồi", + "Couldn't clean up unused Docker data: {error}": "Không thể dọn dữ liệu Docker không dùng: {error}", + "Cleaned up {size} of unused Docker data": "Đã dọn {size} dữ liệu Docker không dùng", + "Cleaned up unused Docker data": "Đã dọn dữ liệu Docker không dùng", + "Compact WSL disk?": "Nén đĩa WSL?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "Nén {vhdx} sẽ hoàn trả dung lượng không dùng cho Windows và khởi động lại nhanh engine của Kiri cùng các container đang chạy.", + "Compact disk": "Nén đĩa", + "Clean up unused Docker data?": "Dọn dữ liệu Docker không dùng?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Xóa các container đã dừng, image không có tag và build cache của BuildKit. Các container đang chạy và image có tag được giữ nguyên.", + "Clean up": "Dọn dẹp", + "Uninstall Kiri?": "Gỡ cài đặt Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Dừng engine, gỡ dịch vụ chạy nền của Kiri, liên kết CLI và các mục trong hồ sơ shell, đồng thời khôi phục ngữ cảnh Docker trước đó. Các image và volume của bạn vẫn nằm trong thư mục dữ liệu của Kiri cho đến khi bạn xóa nó.", + "Cluster": "Cluster", + "default": "mặc định", + "k3s version": "Phiên bản k3s", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Phiên bản image cho node của cluster ({cmd}). Áp dụng khi tạo lại.", + "Extra server flags": "Cờ máy chủ bổ sung", + "Passed to {srv} ({flag}), separated by spaces.": "Truyền cho {srv} ({flag}), phân tách bằng dấu cách.", + "Startup manifests": "Manifest khi khởi động", + "YAML files in {path} are applied whenever the cluster starts.": "Các tệp YAML trong {path} được áp dụng mỗi khi cluster khởi động.", + "Open folder": "Mở thư mục", + "{n} untagged image": "{n} image không có tag", + "{n} untagged images": "{n} image không có tag", + "Uninstall Kiri from Windows Settings → Apps": "Gỡ cài đặt Kiri trong Cài đặt Windows → Ứng dụng", + "Builder settings saved": "Đã lưu thiết lập builder", + "Could not save builder settings: {error}": "Không thể lưu thiết lập builder: {error}", + "Disk reclaim is already running": "Đang thu hồi dung lượng đĩa rồi", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Đã lưu thiết lập lưu lượng đi ra của VM. Hãy khởi động lại VM để áp dụng.", + "Could not save VM networking setting: {error}": "Không thể lưu thiết lập mạng của VM: {error}", + "Added Kiri command-line tools to shell profiles": "Đã thêm công cụ dòng lệnh Kiri vào hồ sơ shell", + "Removed Kiri command-line tools from shell profiles": "Đã gỡ công cụ dòng lệnh Kiri khỏi hồ sơ shell", + "Could not update shell profiles: {error}": "Không thể cập nhật hồ sơ shell: {error}", + "Uninstalling Kiri…": "Đang gỡ cài đặt Kiri…", + "Could not uninstall Kiri: {error}": "Không thể gỡ cài đặt Kiri: {error}", + "Uninstall Kiri using your system package manager": "Hãy gỡ cài đặt Kiri bằng trình quản lý gói của hệ thống" } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 03d15c292..d3ea11a00 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -1854,7 +1854,6 @@ "Disk image size": "磁盘镜像大小", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "守护进程设置了 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其优先级高于这里的设置。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "当前运行使用 {cpus}、内存最多 {mem}、{disk} 磁盘。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,且永不缩小。重启后生效。", "No other WSL distros installed.": "未安装其他 WSL 发行版。", "WSL integration": "WSL 集成", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "关闭:释放窗口占用的内存。重新打开需要片刻,已打开的终端会结束。", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri 和这台电脑", "Kiri and this computer": "Kiri 和这台电脑", "Versions, {os}, whether the engine runs, how many containers and images": "版本、{os}、引擎是否在运行、容器和镜像数量", - "Saved. The engine uses these from its next start": "已保存。引擎下次启动时生效" + "Saved. The engine uses these from its next start": "已保存。引擎下次启动时生效", + "5 min": "5 分钟", + "10 min": "10 分钟", + "30 min": "30 分钟", + "Never": "从不", + "Build cache limit": "构建缓存上限", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "当 BuildKit 的缓存超过此大小时,最旧的缓存层会自动清理。", + "Stop builder when idle": "空闲时停止构建器", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "在构建间隙停止 BuildKit,空闲时不占用内存;下次构建会在一秒内唤醒它。", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "守护进程设置了 KIRI_BUILD_CACHE_GB 或 KIRI_BUILDER_IDLE_SECS,其优先级高于这里的设置。", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT:最快。如果 Cloudflare WARP 或企业防火墙拦截容器 HTTPS,请切换到“宿主机中继”。重启虚拟机后生效。", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "宿主机中继:连接通过 macOS 上的 Kiri 发出,而不是通过 Virtualization.framework NAT。重启虚拟机后生效。", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "环境中设置了 KIRI_SHARED_NAT,优先生效。", + "Outbound VM traffic": "虚拟机出站流量", + "macOS NAT": "macOS NAT", + "Host relay": "宿主机中继", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "虚拟机磁盘最多可扩展到的大小。仅在写入数据时才会占用 {os} 上的空间,未使用的空间可在 {storage} 中回收。重启后生效。", + "Settings → Storage": "设置 → 存储", + "VM disk space": "虚拟机磁盘空间", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "原生 Linux 直接使用宿主机文件系统——删除镜像和卷会立即释放空间。", + "Compact disk…": "压缩磁盘…", + "Reclaim space": "回收空间", + "Compacting…": "正在压缩…", + "Reclaiming…": "正在回收…", + "Compacting {vhdx} and restarting the engine…": "正在压缩 {vhdx} 并重启引擎…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} 上占用 {host},虚拟机内已用 {inUse} · 正在回收未使用的块…", + "Trimming unused blocks inside the VM disk…": "正在回收虚拟机磁盘中未使用的块…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows 上占用 {host}({vhdx}),已用 {inUse} · {freed}。", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} 上占用 {host},虚拟机内已用 {inUse} · {freed}。", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows 上占用 {host}({vhdx}),已用 {inUse} · 无可回收空间。", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} 上占用 {host},虚拟机内已用 {inUse} · 无可回收空间。", + "Nothing to reclaim.": "无可回收空间。", + "{size} can be given back": "可归还 {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows 上占用 {host}({vhdx}),已用 {inUse} · {can}。压缩会重启引擎。", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} 上占用 {host},虚拟机内已用 {inUse} · {can},无需停止容器。", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows 上占用 {host}({vhdx})。压缩会归还未使用的空间并重启引擎。", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} 上占用 {host}。回收会清理虚拟机磁盘中未使用的块,无需停止容器。", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "将 {vhdx} 中未使用的空间归还给 Windows。压缩会重启引擎。", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "将虚拟机磁盘中未使用的块归还给 {os},无需停止容器。", + "Cleaning up stopped containers, untagged images, and build cache…": "正在清理已停止的容器、无标签镜像和构建缓存…", + "{count} ({size})": "{count}({size})", + "build cache": "构建缓存", + "No stopped containers, untagged images or build cache · {freed}.": "没有已停止的容器、无标签镜像或构建缓存 · {freed}。", + "No stopped containers, untagged images or build cache.": "没有已停止的容器、无标签镜像或构建缓存。", + "Cleaning up…": "正在清理…", + "Clean up…": "清理…", + "Unused Docker data": "未使用的 Docker 数据", + "Command-line tools in shell": "Shell 命令行工具", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "将 {bin} 添加到 {zshrc} 和 {zprofile},以便在新终端中使用 {docker}、{kubectl} 和 {kiri}。", + "Uninstall Kiri": "卸载 Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "停止引擎,移除 Kiri 的后台服务、CLI 链接和 Shell 配置项,并恢复之前的 Docker 上下文({cmd})。", + "Uninstall Kiri…": "卸载 Kiri…", + "Couldn't reclaim disk space: {error}": "无法回收磁盘空间:{error}", + "Reclaimed {size} on {os}": "已在 {os} 上回收 {size}", + "Nothing to reclaim": "无可回收空间", + "Couldn't clean up unused Docker data: {error}": "无法清理未使用的 Docker 数据:{error}", + "Cleaned up {size} of unused Docker data": "已清理 {size} 未使用的 Docker 数据", + "Cleaned up unused Docker data": "已清理未使用的 Docker 数据", + "Compact WSL disk?": "压缩 WSL 磁盘?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "压缩 {vhdx} 会将未使用的空间归还给 Windows,并短暂重启 Kiri 引擎和正在运行的容器。", + "Compact disk": "压缩磁盘", + "Clean up unused Docker data?": "清理未使用的 Docker 数据?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "移除已停止的容器、无标签镜像和 BuildKit 构建缓存。正在运行的容器和有标签的镜像会保留。", + "Clean up": "清理", + "Uninstall Kiri?": "卸载 Kiri?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "停止引擎,移除 Kiri 的后台服务、CLI 链接和 Shell 配置项,并恢复之前的 Docker 上下文。你的镜像和卷会保留在 Kiri 数据文件夹中,直到你手动删除该文件夹。", + "Cluster": "集群", + "default": "默认", + "k3s version": "k3s 版本", + "Image version for the cluster node ({cmd}). Applies when recreated.": "集群节点的镜像版本({cmd})。重建集群时生效。", + "Extra server flags": "额外服务器参数", + "Passed to {srv} ({flag}), separated by spaces.": "传递给 {srv}({flag}),以空格分隔。", + "Startup manifests": "启动清单", + "YAML files in {path} are applied whenever the cluster starts.": "每次集群启动时都会应用 {path} 中的 YAML 文件。", + "Open folder": "打开文件夹", + "{n} untagged image": "{n} 个无标签镜像", + "{n} untagged images": "{n} 个无标签镜像", + "Uninstall Kiri from Windows Settings → Apps": "请在“Windows 设置 → 应用”中卸载 Kiri", + "Builder settings saved": "构建器设置已保存", + "Could not save builder settings: {error}": "无法保存构建器设置:{error}", + "Disk reclaim is already running": "磁盘空间回收已在运行中", + "Outbound VM traffic setting saved. Restart the VM to apply.": "虚拟机出站流量设置已保存。重启虚拟机后生效。", + "Could not save VM networking setting: {error}": "无法保存虚拟机网络设置:{error}", + "Added Kiri command-line tools to shell profiles": "已将 Kiri 命令行工具添加到 Shell 配置文件", + "Removed Kiri command-line tools from shell profiles": "已从 Shell 配置文件移除 Kiri 命令行工具", + "Could not update shell profiles: {error}": "无法更新 Shell 配置文件:{error}", + "Uninstalling Kiri…": "正在卸载 Kiri…", + "Could not uninstall Kiri: {error}": "无法卸载 Kiri:{error}", + "Uninstall Kiri using your system package manager": "请使用系统包管理器卸载 Kiri" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 8867ed30f..4e12f1ccb 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -1854,7 +1854,6 @@ "Disk image size": "磁碟映像大小", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "常駐程式已設定 KIRI_CPUS、KIRI_MEMORY_MIB 或 KIRI_DISK_GB,其優先順序高於這裡的設定。", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "目前以 {cpus}、記憶體最多 {mem} 與 {disk} 磁碟執行。", - "The most the VM disk may grow to. Space is used on {os} only as data is written; it never shrinks. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,且永不縮小。重新啟動後生效。", "No other WSL distros installed.": "未安裝其他 WSL 發行版。", "WSL integration": "WSL 整合", "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "關閉:釋放視窗占用的記憶體。重新開啟需要片刻,已開啟的終端機會結束。", @@ -1946,5 +1945,93 @@ "Kiri and this PC": "Kiri 和這台電腦", "Kiri and this computer": "Kiri 和這台電腦", "Versions, {os}, whether the engine runs, how many containers and images": "版本、{os}、引擎是否正在執行、容器和映像檔數量", - "Saved. The engine uses these from its next start": "已儲存。引擎下次啟動時生效" + "Saved. The engine uses these from its next start": "已儲存。引擎下次啟動時生效", + "5 min": "5 分鐘", + "10 min": "10 分鐘", + "30 min": "30 分鐘", + "Never": "永不", + "Build cache limit": "建置快取上限", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "當 BuildKit 的快取超過此大小時,最舊的快取層會自動清理。", + "Stop builder when idle": "閒置時停止建置器", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "在建置之間停止 BuildKit,閒置時不佔用記憶體;下次建置會在不到一秒內喚醒它。", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "常駐程式已設定 KIRI_BUILD_CACHE_GB 或 KIRI_BUILDER_IDLE_SECS,其優先順序高於這裡的設定。", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT:最快。如果 Cloudflare WARP 或企業防火牆封鎖容器 HTTPS,請切換為「主機中繼」。重新啟動虛擬機器後生效。", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "主機中繼:連線會從 macOS 上的 Kiri 發出,而非透過 Virtualization.framework NAT。重新啟動虛擬機器後生效。", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "環境中已設定 KIRI_SHARED_NAT,且優先順序較高。", + "Outbound VM traffic": "虛擬機器對外流量", + "macOS NAT": "macOS NAT", + "Host relay": "主機中繼", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "虛擬機器磁碟最多可擴展的大小。僅在寫入資料時才會佔用 {os} 上的空間,未使用的空間可在 {storage} 中回收。重新啟動後生效。", + "Settings → Storage": "設定 → 儲存裝置", + "VM disk space": "虛擬機器磁碟空間", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "原生 Linux 直接使用主機檔案系統——刪除映像檔和磁碟區會立即釋放空間。", + "Compact disk…": "壓縮磁碟…", + "Reclaim space": "回收空間", + "Compacting…": "正在壓縮…", + "Reclaiming…": "正在回收…", + "Compacting {vhdx} and restarting the engine…": "正在壓縮 {vhdx} 並重新啟動引擎…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} 上佔用 {host},虛擬機器內已用 {inUse} · 正在回收未使用的區塊…", + "Trimming unused blocks inside the VM disk…": "正在回收虛擬機器磁碟中未使用的區塊…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows 上佔用 {host}({vhdx}),已用 {inUse} · {freed}。", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} 上佔用 {host},虛擬機器內已用 {inUse} · {freed}。", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows 上佔用 {host}({vhdx}),已用 {inUse} · 沒有可回收的空間。", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} 上佔用 {host},虛擬機器內已用 {inUse} · 沒有可回收的空間。", + "Nothing to reclaim.": "沒有可回收的空間。", + "{size} can be given back": "可歸還 {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows 上佔用 {host}({vhdx}),已用 {inUse} · {can}。壓縮會重新啟動引擎。", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} 上佔用 {host},虛擬機器內已用 {inUse} · {can},無需停止容器。", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows 上佔用 {host}({vhdx})。壓縮會歸還未使用的空間並重新啟動引擎。", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} 上佔用 {host}。回收會清理虛擬機器磁碟中未使用的區塊,無需停止容器。", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "將 {vhdx} 中未使用的空間歸還給 Windows。壓縮會重新啟動引擎。", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "將虛擬機器磁碟中未使用的區塊歸還給 {os},無需停止容器。", + "Cleaning up stopped containers, untagged images, and build cache…": "正在清理已停止的容器、無標籤映像檔與建置快取…", + "{count} ({size})": "{count}({size})", + "build cache": "建置快取", + "No stopped containers, untagged images or build cache · {freed}.": "沒有已停止的容器、無標籤映像檔或建置快取 · {freed}。", + "No stopped containers, untagged images or build cache.": "沒有已停止的容器、無標籤映像檔或建置快取。", + "Cleaning up…": "正在清理…", + "Clean up…": "清理…", + "Unused Docker data": "未使用的 Docker 資料", + "Command-line tools in shell": "Shell 命令列工具", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "將 {bin} 加入 {zshrc} 與 {zprofile},讓 {docker}、{kubectl} 與 {kiri} 可在新終端機中使用。", + "Uninstall Kiri": "解除安裝 Kiri", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "停止引擎,移除 Kiri 的背景服務、CLI 連結與 Shell 設定檔項目,並還原您先前的 Docker 環境({cmd})。", + "Uninstall Kiri…": "解除安裝 Kiri…", + "Couldn't reclaim disk space: {error}": "無法回收磁碟空間:{error}", + "Reclaimed {size} on {os}": "已在 {os} 上回收 {size}", + "Nothing to reclaim": "沒有可回收的空間", + "Couldn't clean up unused Docker data: {error}": "無法清理未使用的 Docker 資料:{error}", + "Cleaned up {size} of unused Docker data": "已清理 {size} 的未使用 Docker 資料", + "Cleaned up unused Docker data": "已清理未使用的 Docker 資料", + "Compact WSL disk?": "要壓縮 WSL 磁碟嗎?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "壓縮 {vhdx} 會將未使用的空間歸還給 Windows,並短暫重新啟動 Kiri 引擎與執行中的容器。", + "Compact disk": "壓縮磁碟", + "Clean up unused Docker data?": "要清理未使用的 Docker 資料嗎?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "移除已停止的容器、無標籤映像檔與 BuildKit 建置快取。執行中的容器與有標籤的映像檔會保留。", + "Clean up": "清理", + "Uninstall Kiri?": "要解除安裝 Kiri 嗎?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "停止引擎,移除 Kiri 的背景服務、CLI 連結與 Shell 設定檔項目,並還原您先前的 Docker 環境。您的映像檔與磁碟區會保留在 Kiri 資料夾中,直到您將其刪除。", + "Cluster": "叢集", + "default": "預設", + "k3s version": "k3s 版本", + "Image version for the cluster node ({cmd}). Applies when recreated.": "叢集節點的映像檔版本({cmd})。重建時套用。", + "Extra server flags": "額外伺服器旗標", + "Passed to {srv} ({flag}), separated by spaces.": "傳遞給 {srv}({flag}),以空格分隔。", + "Startup manifests": "啟動資訊清單", + "YAML files in {path} are applied whenever the cluster starts.": "每次叢集啟動時都會套用 {path} 中的 YAML 檔案。", + "Open folder": "開啟資料夾", + "{n} untagged image": "{n} 個無標籤映像檔", + "{n} untagged images": "{n} 個無標籤映像檔", + "Uninstall Kiri from Windows Settings → Apps": "請從「Windows 設定 → 應用程式」解除安裝 Kiri", + "Builder settings saved": "已儲存建置器設定", + "Could not save builder settings: {error}": "無法儲存建置器設定:{error}", + "Disk reclaim is already running": "磁碟空間回收已在執行中", + "Outbound VM traffic setting saved. Restart the VM to apply.": "已儲存虛擬機器對外流量設定。重新啟動虛擬機器以套用。", + "Could not save VM networking setting: {error}": "無法儲存虛擬機器網路設定:{error}", + "Added Kiri command-line tools to shell profiles": "已將 Kiri 命令列工具加入 Shell 設定檔", + "Removed Kiri command-line tools from shell profiles": "已從 Shell 設定檔移除 Kiri 命令列工具", + "Could not update shell profiles: {error}": "無法更新 Shell 設定檔:{error}", + "Uninstalling Kiri…": "正在解除安裝 Kiri…", + "Could not uninstall Kiri: {error}": "無法解除安裝 Kiri:{error}", + "Uninstall Kiri using your system package manager": "請使用系統套件管理員解除安裝 Kiri" } diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 84fca0069..fb5c74452 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -889,6 +889,153 @@ fn storage_remove_old() { } } +fn storage_reclaim(tx: Sender) { + match client::request("POST", "/kiri/storage/reclaim", None) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = "storagereclaimed".into(); + emit(v.to_string()); + storage_status(); + let _ = tx.send(Cmd::Refresh); + } + Ok(r) => { + emit(serde_json::json!({"type": "storagereclaimed", "error": r.error()}).to_string()); + storage_status(); + } + Err(e) => { + emit(serde_json::json!({"type": "storagereclaimed", "error": e.to_string()}).to_string()); + storage_status(); + } + } +} + +fn storage_prune(tx: Sender) { + let mut freed = 0u64; + let mut containers = 0usize; + let mut images = 0usize; + let mut err: Option = None; + for (endpoint, kind) in [("/containers/prune", "c"), ("/images/prune", "i"), ("/build/prune?all=1", "b")] { + match client::request("POST", endpoint, None) { + Ok(r) if r.ok() => { + let v = r.json(); + freed = freed.saturating_add(v["SpaceReclaimed"].as_u64().unwrap_or(0)); + if kind == "c" { + containers = v["ContainersDeleted"].as_array().map_or(0, Vec::len); + } else if kind == "i" { + images = v["ImagesDeleted"].as_array().map_or(0, Vec::len); + } + } + Ok(r) => { + err = Some(r.error()); + break; + } + Err(e) => { + err = Some(e.to_string()); + break; + } + } + } + let ev = match err { + Some(e) => serde_json::json!({"type": "storagepruned", "error": e}), + None => serde_json::json!({"type": "storagepruned", "freed": freed, "containers": containers, "images": images}), + }; + emit(ev.to_string()); + storage_status(); + let _ = tx.send(Cmd::Refresh); +} + +fn builder_settings(save: Option) { + if let Some(body) = save { + match client::request("POST", "/kiri/builder", Some(&body)) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = "buildersettings".into(); + emit(v.to_string()); + emit(notice("ok", &tr("Builder settings saved"))); + return; + } + Ok(r) => emit(notice("error", &trf("Could not save builder settings: {error}", &[("error", &r.error())]))), + Err(e) => emit(notice("error", &trf("Could not save builder settings: {error}", &[("error", &e)]))), + } + } + let mut v = client::get_background("/kiri/builder").unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})); + v["type"] = "buildersettings".into(); + emit(v.to_string()); +} + +#[cfg(target_os = "macos")] +fn vm_net(save: Option) { + if let Some(body) = save { + if let Some(enabled) = body["shared_nat"].as_bool() { + match crate::vm_cli::set_shared_nat(enabled) { + Ok(()) => emit(notice("ok", &tr("Outbound VM traffic setting saved. Restart the VM to apply."))), + Err(e) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), + } + } + } + let configured = crate::daemon::engine::vm_shared_nat_config(); + let env_override = crate::daemon::engine::shared_nat_env(); + let effective = env_override.or(configured).unwrap_or(true); + let info = client::get_background("/info").ok(); + let awake = info.as_ref().is_some_and(|i| i["KiriVmAwake"] == true); + let running_shared_nat = awake.then(|| info.as_ref().and_then(|i| i["KiriVmUplink"]["mode"].as_str()).is_none_or(|m| m != "host-egress")); + emit( + serde_json::json!({ + "type": "vmnet", + "supported": true, + "shared_nat": effective, + "configured": configured, + "env": env_override.is_some(), + "awake": awake, + "running_shared_nat": running_shared_nat, + }) + .to_string(), + ); +} + +#[cfg(not(target_os = "macos"))] +fn vm_net(_save: Option) { + emit(serde_json::json!({"type": "vmnet", "supported": false}).to_string()); +} + +#[cfg(target_os = "macos")] +fn shell_path(save: Option) { + if let Some(body) = save { + if let Some(enabled) = body["enabled"].as_bool() { + match crate::setup::set_shell_path(enabled) { + Ok(()) => emit(notice("ok", &if enabled { tr("Added Kiri command-line tools to shell profiles") } else { tr("Removed Kiri command-line tools from shell profiles") })), + Err(e) => emit(notice("error", &trf("Could not update shell profiles: {error}", &[("error", &e)]))), + } + } + } + emit(serde_json::json!({"type": "shellpath", "supported": true, "enabled": crate::setup::shell_path_enabled()}).to_string()); +} + +#[cfg(not(target_os = "macos"))] +fn shell_path(_save: Option) { + emit(serde_json::json!({"type": "shellpath", "supported": false}).to_string()); +} + +#[cfg(target_os = "macos")] +fn run_uninstall() { + match std::env::current_exe().and_then(|exe| { + std::process::Command::new(exe) + .args(["setup", "--uninstall"]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + }) { + Ok(_) => emit(notice("ok", &tr("Uninstalling Kiri…"))), + Err(e) => emit(notice("error", &trf("Could not uninstall Kiri: {error}", &[("error", &e)]))), + } +} + +#[cfg(not(target_os = "macos"))] +fn run_uninstall() { + emit(notice("error", &tr("Uninstall Kiri using your system package manager"))); +} + /// Reads (or saves, then reads) the VM's CPUs and memory for Settings. fn resources(save: Option) { let saved = save.map(|body| client::request("POST", "/kiri/resources", Some(&body))); @@ -1180,6 +1327,7 @@ fn about() { "memory": info["MemTotal"], "awake": info["KiriVmAwake"], "os": info["OperatingSystem"], + "can_uninstall": cfg!(target_os = "macos"), }) .to_string(), ); @@ -2464,6 +2612,51 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { std::thread::spawn(storage_remove_old); Ok(()) } + "storagereclaim" => { + let tx = tx.clone(); + std::thread::spawn(move || storage_reclaim(tx)); + Ok(()) + } + "storageprune" => { + let tx = tx.clone(); + std::thread::spawn(move || storage_prune(tx)); + Ok(()) + } + // Settings → Builds: cache limit and idle timeout (/kiri/builder). + "buildersettings" => { + std::thread::spawn(|| builder_settings(None)); + Ok(()) + } + "setbuildersettings" => { + let body = msg.value; + std::thread::spawn(move || builder_settings(Some(body))); + Ok(()) + } + // Settings → Network: macOS outbound VM traffic (vm.json shared_nat). + "vmnet" => { + std::thread::spawn(|| vm_net(None)); + Ok(()) + } + "setvmnet" => { + let body = msg.value; + std::thread::spawn(move || vm_net(Some(body))); + Ok(()) + } + // Settings → Appearance: macOS shell profile PATH (#556). + "shellpath" => { + std::thread::spawn(|| shell_path(None)); + Ok(()) + } + "setshellpath" => { + let body = msg.value; + std::thread::spawn(move || shell_path(Some(body))); + Ok(()) + } + // Settings → About: Uninstall Kiri (macOS). + "uninstall" => { + std::thread::spawn(run_uninstall); + Ok(()) + } // Settings → Resources. "resources" => { std::thread::spawn(|| resources(None)); diff --git a/crates/kiri/src/vm_cli.rs b/crates/kiri/src/vm_cli.rs index efc0c2a68..3bd920637 100644 --- a/crates/kiri/src/vm_cli.rs +++ b/crates/kiri/src/vm_cli.rs @@ -82,6 +82,13 @@ fn save_shared_nat(path: &Path, enabled: bool) -> io::Result { Ok(cfg) } +/// Saves `shared_nat` in `~/.kiri/vm.json` while preserving other keys (`cpus`, +/// `memory_mib`, `disk_gb`). Used by Settings → Network. +pub(crate) fn set_shared_nat(enabled: bool) -> io::Result<()> { + let path = engine::resources_path().ok_or_else(|| io::Error::other("HOME is not set"))?; + save_shared_nat(&path, enabled).map(|_| ()) +} + fn on_off(b: bool) -> &'static str { if b { "on" } else { "off" } } diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 1e224efba..17bd4fa15 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -15,7 +15,7 @@ use std::process::{Command, Stdio}; 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"]; +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. diff --git a/tests/ui/settings-reclaim-and-cli.js b/tests/ui/settings-reclaim-and-cli.js new file mode 100644 index 000000000..b2c990b28 --- /dev/null +++ b/tests/ui/settings-reclaim-and-cli.js @@ -0,0 +1,172 @@ +// Settings: VM disk space reclaim & Docker cleanup (#879), Builds cache/idle +// settings, macOS outbound VM traffic, Kubernetes cluster controls, shell PATH +// toggle (#556), and Uninstall Kiri confirmation dialog. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const last = (cmd) => sent.filter((m) => m.type === cmd).at(-1); + +t("Resources disk description links to Settings → Storage instead of saying never shrinks", () => { + kiri.on({ + type: "resources", cpus: 4, memory_mib: 8192, disk_gb: 64, + running_cpus: 4, running_memory_mib: 8192, running_disk_gb: 64, + awake: true, max_cpus: 12, max_memory_mib: 32768, min_disk_gb: 64, max_disk_gb: 1024, overridden: false, + }); + prefs.tab = "resources"; + show("settings"); + const pane = document.querySelector(".settings .panes"); + if (/never shrinks/i.test(pane.textContent)) throw new Error("still says never shrinks"); + const link = pane.querySelector("[data-stgoto]"); + if (!link) throw new Error("missing Settings → Storage link button"); + link.click(); + if (prefs.tab !== "storage") throw new Error("link did not switch to storage tab"); +}); + +t("Storage: VM disk space row reclaims online on macOS and disables when clean", () => { + kiri.on({ + type: "storage", + path: "/Users/me/.kiri/data", + default: "/Users/me/.kiri/data", + custom: false, env: false, state: "ok", + used: 29_400_000_000, free: 412_600_000_000, fs: "apfs", + disk_host: 29_400_000_000, disk_in_use: 17_300_000_000, disk_limit: 64 * 1073741824, reclaimable: 12_100_000_000, + moving: null, error: null, old: null, + }); + const pane = document.querySelector(".settings .pane"); + if (!pane.textContent.includes("VM disk space")) throw new Error("missing VM disk space row"); + if (!pane.textContent.includes("can be given back")) throw new Error("missing reclaimable summary"); + const btn = pane.querySelector("[data-streclaim]"); + if (!btn || btn.disabled) throw new Error("Reclaim space button missing or disabled"); + btn.click(); + if (!last("storagereclaim")) throw new Error("didn't send storagereclaim"); + if (!document.querySelector(".settings .pane .hspin")) throw new Error("missing busy spinner while reclaiming"); + + kiri.on({ type: "storagereclaimed", before: 29_400_000_000, after: 17_300_000_000, reclaimed: 12_100_000_000, in_use: 17_300_000_000, elapsed_ms: 800 }); + const afterPane = document.querySelector(".settings .pane"); + if (!afterPane.textContent.includes("Freed")) throw new Error("missing Freed summary after reclaim"); + const afterBtn = afterPane.querySelector("[data-streclaim]"); + if (!afterBtn?.disabled) throw new Error("Reclaim button should be disabled when nothing left to reclaim"); +}); + +t("Storage: Unused Docker data row confirms and sends storageprune", () => { + ui.containers.push({ Id: "stopped1", Names: ["/old-web"], Image: "nginx", State: "exited", Ports: [], Labels: {} }); + ui.images.push({ Id: "sha256:deadbeef", RepoTags: [":"], Size: 500_000_000, Created: Date.now() / 1000 - 100 }); + ui.builderVolume = { Name: "buildx_buildkit_kiri-build0_state" }; + render(); + const btn = document.querySelector("[data-stprune]"); + if (!btn || btn.disabled) throw new Error("Clean up… button missing or disabled"); + btn.click(); + const go = document.querySelector(".scrim [data-go]"); + if (!go) throw new Error("Clean up… didn't open confirmation dialog"); + go.click(); + if (!last("storageprune")) throw new Error("didn't send storageprune"); + ui.containers = []; + ui.images = []; + ui.builderVolume = null; + kiri.on({ type: "storagepruned", freed: 500_000_000, containers: 1, images: 1 }); + const pane = document.querySelector(".settings .pane"); + if (!pane.textContent.includes("No stopped containers")) throw new Error("missing clean summary"); + if (!pane.querySelector("[data-stprune]")?.disabled) throw new Error("Clean up… should be disabled when clean"); +}); + +t("Builds: Build cache limit slider and idle timeout wire /kiri/builder", () => { + document.querySelector('[data-stab="builds"]').click(); + if (!last("buildersettings")) throw new Error("opening Builds did not request buildersettings"); + kiri.on({ type: "buildwith", with: "kiri", ask: false, engine: null, taken: true, ready: true }); + kiri.on({ type: "buildersettings", cache_gb: 20, default_cache_gb: 20, idle_secs: 600, state: "running", overridden: false }); + const slider = document.getElementById("bld-cache"); + if (!slider || slider.value !== "20") throw new Error("missing or wrong #bld-cache"); + slider.value = "40"; + slider.dispatchEvent(new Event("input", { bubbles: true })); + if (document.getElementById("bld-cache-v").textContent !== "40 GB") throw new Error("slider label did not update"); + slider.dispatchEvent(new Event("change", { bubbles: true })); + const savedCache = last("setbuildersettings"); + if (!savedCache || savedCache.value?.cache_gb !== 40) throw new Error("bad setbuildersettings for cache: " + JSON.stringify(savedCache)); + + const idle30 = document.querySelector('[data-bldidle="1800"]'); + if (!idle30) throw new Error("missing 30 min idle button"); + idle30.click(); + const savedIdle = last("setbuildersettings"); + if (!savedIdle || savedIdle.value?.idle_secs !== 1800) throw new Error("bad setbuildersettings for idle: " + JSON.stringify(savedIdle)); + if (document.querySelector('[data-bldidle="1800"]').getAttribute("aria-pressed") !== "true") throw new Error("30 min button not pressed"); + + kiri.on({ type: "buildersettings", cache_gb: 40, default_cache_gb: 20, idle_secs: 1800, overridden: true }); + if (!document.querySelector(".settings .pane").textContent.includes("KIRI_BUILD_CACHE_GB")) throw new Error("missing env override note"); +}); + +t("Network: Outbound VM traffic toggles macOS NAT and Host relay", () => { + document.querySelector('[data-stab="network"]').click(); + if (!last("vmnet")) throw new Error("opening Network did not request vmnet"); + kiri.on({ type: "proxy", settings: { mode: "system", containers: false }, effective: { http: null, https: null, no_proxy: [], pac: false } }); + kiri.on({ type: "vmnet", supported: true, shared_nat: true, env: false, awake: true, running_shared_nat: true }); + const natOn = document.querySelector('[data-vmnat="1"]'); + const natOff = document.querySelector('[data-vmnat="0"]'); + if (!natOn || !natOff || natOn.getAttribute("aria-pressed") !== "true") throw new Error("Outbound VM traffic buttons wrong"); + natOff.click(); + const req = last("setvmnet"); + if (!req || req.value?.shared_nat !== false) throw new Error("bad setvmnet: " + JSON.stringify(req)); + if (document.querySelector('[data-vmnat="0"]').getAttribute("aria-pressed") !== "true") throw new Error("Host relay not pressed"); + + kiri.on({ type: "vmnet", supported: false }); + if (document.querySelector('[data-vmnat="0"]')) throw new Error("Outbound VM traffic should hide when unsupported"); +}); + +t("Kubernetes: Cluster section exposes k3s version, extra server flags, and startup manifests", () => { + kiri.on({ + type: "k8s", state: "running", ready: true, context: "kiri", port: 6443, want_port: 6443, + default_version: "v1.37.1-k3s1", manifests_dir: "/Users/me/.kiri/k8s-manifests", + config: { lan: false, tls_san: [], version: null, k3s_args: [] }, + pods: [], services: [], + }); + document.querySelector('[data-stab="kubernetes"]').click(); + const pane = document.querySelector(".settings .pane"); + if (!pane.textContent.includes("Cluster") || !pane.textContent.includes("k3s version")) throw new Error("missing Cluster section"); + if (!pane.textContent.includes("/Users/me/.kiri/k8s-manifests")) throw new Error("missing manifests dir"); + + const ver = document.getElementById("k8s-ver"); + if (!ver) throw new Error("missing #k8s-ver"); + ver.value = "v1.31.4-k3s1"; + ver.dispatchEvent(new Event("change", { bubbles: true })); + const setVer = sent.filter((m) => m.type === "k8s" && m.action === "set").at(-1); + if (!setVer || setVer.value?.version !== "v1.31.4-k3s1") throw new Error("bad k8s set version: " + JSON.stringify(setVer)); + + // Clear pending op so we can test k3s args and manifests. + kiri.on({ type: "k8sop", op: "set", state: "done", context: "kiri", port: 6443, want_port: 6443 }); + const argsInput = document.getElementById("k8s-args"); + const argsBtn = document.querySelector("[data-k8sargs]"); + if (!argsInput || !argsBtn?.disabled) throw new Error("k8s-args missing or save not initially disabled"); + argsInput.value = "--disable=servicelb --flannel-backend=none"; + argsInput.dispatchEvent(new Event("input", { bubbles: true })); + if (argsBtn.disabled) throw new Error("k8s-args save button did not enable"); + argsBtn.click(); + const setArgs = sent.filter((m) => m.type === "k8s" && m.action === "set").at(-1); + if (JSON.stringify(setArgs?.value?.k3s_args) !== JSON.stringify(["--disable=servicelb", "--flannel-backend=none"])) { + throw new Error("bad k8s set k3s_args: " + JSON.stringify(setArgs)); + } + + document.querySelector("[data-k8smanifests]").click(); + const man = sent.filter((m) => m.type === "k8s" && m.action === "manifests").at(-1); + if (!man) throw new Error("Open folder did not send k8s manifests action"); +}); + +t("Appearance & About: shell PATH toggle and Uninstall Kiri confirmation", () => { + document.querySelector('[data-stab="appearance"]').click(); + kiri.on({ type: "shellpath", supported: true, enabled: true }); + const shOff = document.querySelector('[data-shellpath="0"]'); + const shOn = document.querySelector('[data-shellpath="1"]'); + if (!shOff || !shOn || shOn.getAttribute("aria-pressed") !== "true") throw new Error("shellpath controls missing"); + shOff.click(); + const setSh = last("setshellpath"); + if (!setSh || setSh.value?.enabled !== false) throw new Error("bad setshellpath: " + JSON.stringify(setSh)); + + document.querySelector('[data-stab="about"]').click(); + kiri.on({ type: "about", app: "0.2.0", running: true, engine: "0.2.0", api: "1.47", kernel: "6.12", cpus: 4, memory: 8 * 1073741824, awake: true, can_uninstall: true }); + const unBtn = document.querySelector("[data-uninstall]"); + if (!unBtn) throw new Error("missing Uninstall Kiri… button"); + unBtn.click(); + const go = document.querySelector(".scrim [data-go]"); + if (!go) throw new Error("Uninstall Kiri… did not open confirmation dialog"); + go.click(); + if (!last("uninstall")) throw new Error("Confirming uninstall did not send uninstall"); +}); + +report(R); From 9d25641d5fd8ad65633edcaa32619e4481b9dd88 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:39:27 +0100 Subject: [PATCH 108/157] macOS: mount ~/Kiri NFS share with nobrowse so Finder hides < sidebar entry (#929) (#939) Co-authored-by: Jota Furtado --- crates/kiri/src/daemon/nfs.rs | 5 +++-- docs/fix-registry.md | 6 ++++++ tests/e2e.sh | 1 + tests/regressions.tsv | 1 + 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/daemon/nfs.rs b/crates/kiri/src/daemon/nfs.rs index 053e16414..a5714699f 100644 --- a/crates/kiri/src/daemon/nfs.rs +++ b/crates/kiri/src/daemon/nfs.rs @@ -126,8 +126,9 @@ pub fn mount(socket: &Path) -> io::Result { // ticotsord with socket paths: mount_nfs's local transport ("<>" is the // host). noac: attributes are never reused, so every read sees the // current file. soft: if the daemon is gone, Finder gets an error - // instead of hanging. - let opts = format!("vers=3,proto=ticotsord,port={socket},mountport={socket},rdonly,nolocks,soft,intr,timeo=10,retrans=2,noac"); + // instead of hanging. nobrowse: open ~/Kiri directly without Finder's + // automatic "<" entry for the Unix socket mount. + let opts = format!("vers=3,proto=ticotsord,port={socket},mountport={socket},rdonly,nobrowse,nolocks,soft,intr,timeo=10,retrans=2,noac"); let status = std::process::Command::new("/sbin/mount_nfs").args(["-o", &opts, "<>:/"]).arg(&dir).status()?; if !status.success() { return Err(io::Error::other(format!("mount_nfs failed: {status}"))); diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 71a64a640..05c7afbca 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 +### #929 macOS: hide the automatic `<` Finder entry for the Kiri NFS mount (unreleased) +- Fixes: #929 Kiri appears as `<` in the Finder sidebar on macOS +- Caused: none known +- Caused by: - +- Check: `finder-mount-nobrowse` + ### #473 Mac: bind unprivileged low ports (`<1024`) on loopback and allow disabling `VZNATNetworkDeviceAttachment` (`kiri vm set --shared-nat off`) for Cloudflare WARP and strict TLS firewalls (unreleased) - Fixes: #473 Port forwarding for ports `<1024` fails without root on macOS even when binding `127.0.0.1`, #383 Cloudflare WARP breaks container networking on macOS (`InternetSharing` conflict), #350 TLS 1.3 handshake hangs when corporate firewall drops non-DF packets from macOS `InternetSharing` NAT - Caused: none known diff --git a/tests/e2e.sh b/tests/e2e.sh index 02da5716f..a8e24d058 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1057,6 +1057,7 @@ needs finder t finder-symlink-is-link "link . Alpine Linux" bash -c "$D exec fsv needs finder t finder-no-proc-sys "hidden" bash -c "! ls $KFQ/fsv | grep -qxE 'proc|sys' && ! ls $KFQ/fsv/proc >/dev/null 2>&1 && ! ls $KFQ/fsv/sys >/dev/null 2>&1 && echo hidden" needs finder code finder-readonly 1 bash -c "echo x > $KFQ/fsv/tmp/written" t finder-mounted "nfs" bash -c "mount | grep -F \" on $KF \"" +t finder-mount-nobrowse ", nobrowse" bash -c 'mount | grep -F " on $1 "' _ "$KF" # A file rewritten in place (same path, same size) must never read stale. needs finder t finder-fresh "match match match" bash -c "for i in 1 2 3; do $D exec fsv sh -c 'head -c 100000 /dev/urandom > /tmp/same.bin'; a=\$($D exec fsv sha256sum /tmp/same.bin | cut -c1-64); b=\$($SHA $KFQ/fsv/tmp/same.bin | cut -c1-64); [ \"\$a\" = \"\$b\" ] && printf 'match '; done" needs finder t finder-new-file "late" bash -c "$D exec fsv sh -c 'echo late > /tmp/late.txt'; cat $KFQ/fsv/tmp/late.txt" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 211ad99a3..8db4a9530 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -350,3 +350,4 @@ crates/kiri/src/daemon/grpc.rs #734 docker build run from a Docker CLI inside a crates/kiri-image/src/store.rs #864 an image put under a name another image had dropped the old record without freeing its unreferenced blobs, and Store::pin updated PINNED without BLOB_LOCK bind-chown-chmod #382 chown on a macOS virtiofs bind mount returned 0 while leaving files owned by the caller so chmod by the new owner failed with EPERM, and warm bind-mount reads lacked close-to-open page/dir caching and BDI read-ahead (#415) crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350) +finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount From fd8f838814b07be84f17dc0aa971e51e987b43c2 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:48:26 +0100 Subject: [PATCH 109/157] Guest kernel: enable ext2/ext3 and FAT/vfat for loop-mounted disk images (#934) (#940) --- docs/fix-registry.md | 6 ++++++ guest/kernel/kiri.config | 10 ++++++++++ tests/e2e.sh | 21 +++++++++++++++++++++ tests/regressions.tsv | 1 + 4 files changed, 38 insertions(+) diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 05c7afbca..4b69d8e11 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 +### #934 Guest kernel: enable ext2/ext3 and FAT/vfat for loop-mounted disk images (unreleased) +- Fixes: #934 Guest kernel has no ext2 or FAT/vfat, so loop-mounted disk images can't be mounted (`pmbootstrap install`, SD-card/EFI images) +- Caused: none known +- Caused by: - +- Check: `guest-kernel-ext2-vfat` + ### #929 macOS: hide the automatic `<` Finder entry for the Kiri NFS mount (unreleased) - Fixes: #929 Kiri appears as `<` in the Finder sidebar on macOS - Caused: none known diff --git a/guest/kernel/kiri.config b/guest/kernel/kiri.config index de47daa8b..dfb9d00da 100644 --- a/guest/kernel/kiri.config +++ b/guest/kernel/kiri.config @@ -103,8 +103,18 @@ CONFIG_FILE_LOCKING=y CONFIG_INOTIFY_USER=y CONFIG_FANOTIFY=y CONFIG_EXT4_FS=y +CONFIG_EXT4_USE_FOR_EXT2=y CONFIG_EXT4_FS_POSIX_ACL=y CONFIG_EXT4_FS_SECURITY=y +# Loop-mounted boot, SD-card and EFI system partitions (#934). +CONFIG_FAT_FS=y +CONFIG_MSDOS_FS=y +CONFIG_VFAT_FS=y +CONFIG_NLS=y +CONFIG_NLS_DEFAULT="iso8859-1" +CONFIG_NLS_CODEPAGE_437=y +CONFIG_NLS_ISO8859_1=y +CONFIG_NLS_UTF8=y CONFIG_MISC_FILESYSTEMS=y CONFIG_EROFS_FS=y CONFIG_EROFS_FS_XATTR=y diff --git a/tests/e2e.sh b/tests/e2e.sh index a8e24d058..ccae589da 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1665,6 +1665,27 @@ os.close(os.open(\"/upper.lock\", os.O_CREAT | os.O_WRONLY, 0o644)) os.utime(\"/upper.lock\", (1700000001, 1700000001)) bu = sx(-100, b\"/upper.lock\", 0) print(\"btime-ok\" if b1 == b2 == b3 and b1[:3] == (0, (0, 0), (1700000000, 0)) and bu[:3] == (0, (0, 0), (1700000001, 0)) else (b1, b2, b3, bu))'); $D rmi kiri-test/btime:1 >/dev/null 2>&1; echo \"\$out\"" +# Guest kernel supports ext2/ext3 (via ext4) and FAT/vfat for loop-mounted boot +# and EFI/SD-card disk images (#934). +only mac t guest-kernel-ext2-vfat "fs=ext2,ext3,ext4,vfat ext2=hello-ext2 vfat=hello-vfat" bash -c "$D run --rm --privileged alpine:3.20 sh -c ' + set -e + fs=\$(awk \"{print \\\$NF}\" /proc/filesystems | grep -xE \"ext2|ext3|ext4|vfat\" | sort -u | paste -sd, -) + apk add -q --no-cache e2fsprogs dosfstools + dd if=/dev/zero of=/tmp/e2.img bs=1M count=4 status=none + mkfs.ext2 -q -F /tmp/e2.img + mkdir -p /mnt/e2 /mnt/vf + mount -t ext2 -o loop /tmp/e2.img /mnt/e2 + echo hello-ext2 > /mnt/e2/ok + e2=\$(cat /mnt/e2/ok) + umount /mnt/e2 + dd if=/dev/zero of=/tmp/vf.img bs=1M count=4 status=none + mkfs.vfat /tmp/vf.img >/dev/null + mount -t vfat -o loop /tmp/vf.img /mnt/vf + echo hello-vfat > /mnt/vf/ok + vf=\$(cat /mnt/vf/ok) + umount /mnt/vf + echo \"fs=\$fs ext2=\$e2 vfat=\$vf\" +'" # Images of 59 to 125 layers start, with their top and lowest layers in the # container (#253: from 60 the overlay's options did not fit in a page). The # 125-layer one is also the next check's. diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 8db4a9530..b60b4c23b 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -351,3 +351,4 @@ crates/kiri-image/src/store.rs #864 an image put under a name another image had bind-chown-chmod #382 chown on a macOS virtiofs bind mount returned 0 while leaving files owned by the caller so chmod by the new owner failed with EPERM, and warm bind-mount reads lacked close-to-open page/dir caching and BDI read-ahead (#415) crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350) finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount +guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount From 7e437bae7776bd857610e4336a9d9c47f81b7f2d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:04:54 +0100 Subject: [PATCH 110/157] Machine: use local image before pulling and allow exec on /tmp for --systemd (#935) (#941) --- crates/kiri/src/machine.rs | 378 +++++++++++++++++++++++++++++++++++-- docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + 3 files changed, 369 insertions(+), 16 deletions(-) diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index 5d722e9d9..6658934ae 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -93,22 +93,86 @@ fn home(user: &str) -> String { if user == "root" { "/root".to_owned() } else { format!("{HOMES}/{user}") } } -fn create(name: &str, pick: &str, systemd: bool) -> io::Result<()> { - if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') || name.starts_with('-') { - return Err(io::Error::other("a machine name is letters, digits and dashes")); +/// A parsed image reference for `kiri machine create`: the full reference +/// passed to `/images/{ref}/json` and `POST /containers/create`, plus the +/// `fromImage` and `tag` query values for `POST /images/create` when pulling. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MachineImage { + full: String, + from_image: String, + tag: String, +} + +impl MachineImage { + fn inspect_path(&self) -> String { + format!("/images/{}/json", percent_encode_image_ref(&self.full)) } + + fn pull_path(&self) -> String { + format!("/images/create?fromImage={}&tag={}", urlish(&self.from_image), urlish(&self.tag)) + } +} + +fn percent_encode_image_ref(reference: &str) -> String { + urlish(reference) +} + +fn parse_machine_image(pick: &str) -> MachineImage { let image = DISTROS.iter().find(|(d, _)| *d == pick).map_or(pick, |(_, i)| *i); + if let Some((repo, digest)) = image.split_once('@').filter(|(_, d)| d.starts_with("sha256:")) { + // Strip an optional `:tag` label before `@sha256:...` for `fromImage`, + // keeping any registry `:port` before the last `/`. + let from_image = match repo.rsplit_once(':') { + Some((r, t)) if !t.contains('/') && !t.is_empty() => r, + _ => repo, + }; + return MachineImage { + full: image.to_owned(), + from_image: from_image.to_owned(), + tag: digest.to_owned(), + }; + } let (repo, tag) = match image.rsplit_once(':') { - Some((r, t)) if !t.contains('/') => (r, t), + Some((r, t)) if !t.contains('/') && !t.is_empty() => (r, t), _ => (image, "latest"), }; - println!("pulling {repo}:{tag}…"); - let pulled = ok(client::request("POST", &format!("/images/create?fromImage={repo}&tag={tag}"), None))?; - if let Some(e) = String::from_utf8_lossy(&pulled.body).lines().filter_map(|l| serde_json::from_str::(l).ok()).find_map(|v| v["error"].as_str().map(str::to_owned)) { + MachineImage { + full: format!("{repo}:{tag}"), + from_image: repo.to_owned(), + tag: tag.to_owned(), + } +} + +/// Ensures `image` is present in the daemon's image store, matching +/// `docker run --pull=missing`: probes `GET /images/{ref}/json` first and only +/// pulls via `POST /images/create` on `404`. Returns `Ok(true)` if it pulled, +/// or `Ok(false)` if the image was already local. +fn ensure_machine_image_with(image: &MachineImage, mut req: F, mut on_pull: P) -> io::Result +where + F: FnMut(&str, &str, Option<&serde_json::Value>) -> io::Result, + P: FnMut(&str), +{ + let probe = req("GET", &image.inspect_path(), None)?; + if probe.status == 200 { + return Ok(false); + } + if probe.status != 404 { + return Err(io::Error::other(probe.error())); + } + on_pull(&image.full); + let pulled = ok(req("POST", &image.pull_path(), None))?; + if let Some(e) = String::from_utf8_lossy(&pulled.body) + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .find_map(|v| v["error"].as_str().map(str::to_owned)) + { return Err(io::Error::other(e)); } - let (user, uid, gid) = user(); - let home = home(&user); + Ok(true) +} + +fn create_body_for(name: &str, image: &str, user: &str, uid: u32, gid: u32, systemd: bool) -> serde_json::Value { + let home = home(user); // The host user, made once; every distro has one of these tools. An // image user that already has the uid (Ubuntu's `ubuntu` is 1000, the // first user's uid on most Linux hosts) is renamed to the host user. @@ -132,7 +196,7 @@ command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=nonint } ); let mut body = json!({ - "Image": format!("{repo}:{tag}"), + "Image": image, "Cmd": ["/bin/sh", "-c", init], "Hostname": name, "Labels": {LABEL: name}, @@ -143,21 +207,51 @@ command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=nonint }, }); if systemd { - // systemd needs its own cgroup tree, tmpfs /run and /tmp, and stops - // on SIGRTMIN+3. + // systemd needs its own cgroup tree, tmpfs /run and /tmp (with exec so + // scripts and helpers in /tmp and /run can run instead of inheriting + // Docker's default noexec tmpfs flag), and stops on SIGRTMIN+3. body["StopSignal"] = "SIGRTMIN+3".into(); body["Env"] = json!(["container=docker"]); body["HostConfig"]["Privileged"] = true.into(); - body["HostConfig"]["Tmpfs"] = json!({"/run": "", "/run/lock": "", "/tmp": ""}); + body["HostConfig"]["Tmpfs"] = json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"}); } - ok(client::request("POST", &format!("/containers/create?name={}", container(name)), Some(&body)))?; - ok(client::request("POST", &format!("/containers/{}/start", container(name)), None))?; + body +} + +fn create_with( + name: &str, + pick: &str, + systemd: bool, + (user, uid, gid): (&str, u32, u32), + mut req: Req, + mut exec: Exec, + on_pull: OnPull, +) -> io::Result +where + Req: FnMut(&str, &str, Option<&serde_json::Value>) -> io::Result, + Exec: FnMut(&str, &[&str]) -> io::Result<(i64, String)>, + OnPull: FnMut(&str), +{ + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') || name.starts_with('-') { + return Err(io::Error::other("a machine name is letters, digits and dashes")); + } + let image = parse_machine_image(pick); + ensure_machine_image_with(&image, &mut req, on_pull)?; + let body = create_body_for(name, &image.full, user, uid, gid, systemd); + ok(req("POST", &format!("/containers/create?name={}", container(name)), Some(&body)))?; + ok(req("POST", &format!("/containers/{}/start", container(name)), None))?; // The user is made by the machine's own first command: wait for it, or // a `machine shell` straight after was "unknown user" (seen on Fedora). let wait = format!("for i in $(seq 300); do id -u {user} >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1"); - if client::exec(&container(name), &["sh", "-c", &wait])?.0 != 0 { + if exec(&container(name), &["sh", "-c", &wait])?.0 != 0 { return Err(io::Error::other(format!("machine {name} is running, but the user {user} could not be added to it"))); } + Ok(image.full) +} + +fn create(name: &str, pick: &str, systemd: bool) -> io::Result<()> { + let (user, uid, gid) = user(); + let image = create_with(name, pick, systemd, (&user, uid, gid), client::request, client::exec, |img| println!("pulling {img}…"))?; println!("machine {name} ({image}) is running: kiri machine shell {name}"); Ok(()) } @@ -205,3 +299,255 @@ fn shell(name: &str, cmd: &[&str]) -> io::Result<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn resp(status: u16, body: &[u8]) -> client::Response { + client::Response { status, body: body.to_vec() } + } + + #[test] + fn parse_machine_image_handles_distros_tags_ports_and_digests() { + let digest = format!("sha256:{}", "a".repeat(64)); + let cases = [ + ("ubuntu", "ubuntu:24.04", "ubuntu", "24.04", "/images/ubuntu%3A24.04/json", "/images/create?fromImage=ubuntu&tag=24.04"), + ( + "opensuse", + "opensuse/tumbleweed:latest", + "opensuse/tumbleweed", + "latest", + "/images/opensuse%2Ftumbleweed%3Alatest/json", + "/images/create?fromImage=opensuse%2Ftumbleweed&tag=latest", + ), + ("pmb-copy", "pmb-copy:latest", "pmb-copy", "latest", "/images/pmb-copy%3Alatest/json", "/images/create?fromImage=pmb-copy&tag=latest"), + ("pmb-copy:latest", "pmb-copy:latest", "pmb-copy", "latest", "/images/pmb-copy%3Alatest/json", "/images/create?fromImage=pmb-copy&tag=latest"), + ( + "ghcr.io/org/devbox:1", + "ghcr.io/org/devbox:1", + "ghcr.io/org/devbox", + "1", + "/images/ghcr.io%2Forg%2Fdevbox%3A1/json", + "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1", + ), + ( + "localhost:5000/pmb:latest", + "localhost:5000/pmb:latest", + "localhost:5000/pmb", + "latest", + "/images/localhost%3A5000%2Fpmb%3Alatest/json", + "/images/create?fromImage=localhost%3A5000%2Fpmb&tag=latest", + ), + ( + "localhost:5000/pmb", + "localhost:5000/pmb:latest", + "localhost:5000/pmb", + "latest", + "/images/localhost%3A5000%2Fpmb%3Alatest/json", + "/images/create?fromImage=localhost%3A5000%2Fpmb&tag=latest", + ), + ]; + for (pick, full, from, tag, inspect, pull) in cases { + let parsed = parse_machine_image(pick); + assert_eq!(parsed.full, full, "{pick}"); + assert_eq!(parsed.from_image, from, "{pick}"); + assert_eq!(parsed.tag, tag, "{pick}"); + assert_eq!(parsed.inspect_path(), inspect, "{pick}"); + assert_eq!(parsed.pull_path(), pull, "{pick}"); + assert!(kiri_image::Reference::parse(&parsed.full).is_ok(), "{pick}"); + } + + // Digest references: bare repo@sha256:..., tag+digest, and registry:port@sha256:... + let digest_cases = [ + (format!("org/box@{digest}"), "org/box"), + (format!("ghcr.io/org/box:v1@{digest}"), "ghcr.io/org/box"), + (format!("localhost:5000/org/box@{digest}"), "localhost:5000/org/box"), + ]; + for (pick, expected_from) in digest_cases { + let parsed = parse_machine_image(&pick); + assert_eq!(parsed.full, pick); + assert_eq!(parsed.from_image, expected_from); + assert_eq!(parsed.tag, digest); + assert_eq!(parsed.inspect_path(), format!("/images/{}/json", urlish(&pick))); + assert_eq!(parsed.pull_path(), format!("/images/create?fromImage={}&tag={}", urlish(expected_from), urlish(&digest))); + assert!(kiri_image::Reference::parse(&parsed.full).is_ok(), "{pick}"); + // Matches daemon/api.rs `pull()` reconstruction for `sha256:` tags. + let daemon_pull_name = format!("{}@{}", parsed.from_image, parsed.tag); + assert!(kiri_image::Reference::parse(&daemon_pull_name).is_ok(), "{daemon_pull_name}"); + } + } + + #[test] + fn local_image_skips_pull_and_creates_container_immediately() { + let digest = format!("sha256:{}", "b".repeat(64)); + let digest_ref = format!("org/box@{digest}"); + let digest_inspect = format!("/images/{}/json", urlish(&digest_ref)); + for (pick, expected_image, expected_inspect) in [ + ("pmb-copy:latest", "pmb-copy:latest", "/images/pmb-copy%3Alatest/json"), + ("pmb-copy", "pmb-copy:latest", "/images/pmb-copy%3Alatest/json"), + ("ghcr.io/org/devbox:1", "ghcr.io/org/devbox:1", "/images/ghcr.io%2Forg%2Fdevbox%3A1/json"), + ("localhost:5000/pmb:latest", "localhost:5000/pmb:latest", "/images/localhost%3A5000%2Fpmb%3Alatest/json"), + (digest_ref.as_str(), digest_ref.as_str(), digest_inspect.as_str()), + ] { + let mut calls: Vec<(String, String, Option)> = Vec::new(); + let mut pulled_notices: Vec = Vec::new(); + let created_image = create_with( + "devbox", + pick, + true, + ("alice", 1000, 1000), + |method, path, body| { + calls.push((method.to_owned(), path.to_owned(), body.cloned())); + match (method, path) { + ("GET", p) if p == expected_inspect => Ok(resp(200, br#"{"Id":"sha256:local"}"#)), + ("POST", "/containers/create?name=machine-devbox") => Ok(resp(201, br#"{"Id":"c1"}"#)), + ("POST", "/containers/machine-devbox/start") => Ok(resp(204, b"")), + other => panic!("unexpected daemon call for {pick}: {other:?}"), + } + }, + |cname, _| { + assert_eq!(cname, "machine-devbox"); + Ok((0, String::new())) + }, + |img| pulled_notices.push(img.to_owned()), + ) + .unwrap(); + + assert_eq!(created_image, expected_image); + assert!(pulled_notices.is_empty(), "must not announce pulling when image is local: {pick}"); + assert!(!calls.iter().any(|(m, p, _)| m == "POST" && p.starts_with("/images/create")), "must skip /images/create: {calls:?}"); + assert_eq!(calls.len(), 3, "{calls:?}"); + assert_eq!((calls[0].0.as_str(), calls[0].1.as_str()), ("GET", expected_inspect)); + assert_eq!((calls[1].0.as_str(), calls[1].1.as_str()), ("POST", "/containers/create?name=machine-devbox")); + let create_body = calls[1].2.as_ref().unwrap(); + assert_eq!(create_body["Image"], expected_image); + assert_eq!(create_body["HostConfig"]["Tmpfs"], json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"})); + assert_eq!((calls[2].0.as_str(), calls[2].1.as_str()), ("POST", "/containers/machine-devbox/start")); + } + } + + #[test] + fn missing_image_pulls_on_404_and_surfaces_errors() { + // 1. 404 -> pulls via POST /images/create and creates container. + let image = parse_machine_image("ghcr.io/org/devbox:1"); + let mut calls = Vec::new(); + let mut pulled_notices = Vec::new(); + let pulled = ensure_machine_image_with( + &image, + |method, path, _| { + calls.push((method.to_owned(), path.to_owned())); + match (method, path) { + ("GET", "/images/ghcr.io%2Forg%2Fdevbox%3A1/json") => Ok(resp(404, br#"{"message":"No such image"}"#)), + ("POST", "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1") => { + Ok(resp(200, b"{\"status\":\"Pulling from org/devbox\"}\n{\"status\":\"Status: Downloaded newer image\"}\n")) + } + other => panic!("unexpected call: {other:?}"), + } + }, + |img| pulled_notices.push(img.to_owned()), + ) + .unwrap(); + assert!(pulled); + assert_eq!(pulled_notices, vec!["ghcr.io/org/devbox:1"]); + assert_eq!( + calls, + vec![ + ("GET".to_owned(), "/images/ghcr.io%2Forg%2Fdevbox%3A1/json".to_owned()), + ("POST".to_owned(), "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1".to_owned()), + ] + ); + + // 2. Pull stream JSON error is surfaced. + let err = ensure_machine_image_with( + &image, + |method, _, _| match method { + "GET" => Ok(resp(404, br#"{"message":"No such image"}"#)), + "POST" => Ok(resp(200, b"{\"status\":\"Pulling\"}\n{\"error\":\"pull access denied for ghcr.io/org/devbox\"}\n")), + _ => unreachable!(), + }, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "pull access denied for ghcr.io/org/devbox"); + + // 3. Non-2xx pull HTTP error is surfaced. + let err = ensure_machine_image_with( + &image, + |method, _, _| match method { + "GET" => Ok(resp(404, br#"{"message":"No such image"}"#)), + "POST" => Ok(resp(400, br#"{"message":"invalid image reference"}"#)), + _ => unreachable!(), + }, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "invalid image reference"); + + // 4. Transport error on GET fails immediately without pulling. + let mut pull_called = false; + let err = ensure_machine_image_with( + &image, + |method, _, _| { + assert_eq!(method, "GET"); + Err(io::Error::new(io::ErrorKind::ConnectionRefused, "daemon gone")) + }, + |_| pull_called = true, + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::ConnectionRefused); + assert!(!pull_called); + + // 5. Unexpected non-404 status on GET fails without attempting to pull. + let err = ensure_machine_image_with( + &image, + |method, _, _| { + assert_eq!(method, "GET"); + Ok(resp(500, br#"{"message":"image store unreadable"}"#)) + }, + |_| pull_called = true, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "image store unreadable"); + assert!(!pull_called); + } + + #[test] + fn systemd_create_body_sets_exec_tmpfs_and_systemd_options() { + let sd = create_body_for("dev", "ubuntu:24.04", "alice", 1000, 1000, true); + assert_eq!(sd["Image"], "ubuntu:24.04"); + assert_eq!(sd["Hostname"], "dev"); + assert_eq!(sd["Labels"], json!({LABEL: "dev"})); + assert_eq!(sd["StopSignal"], "SIGRTMIN+3"); + assert_eq!(sd["Env"], json!(["container=docker"])); + assert_eq!(sd["HostConfig"]["Privileged"], true); + assert_eq!(sd["HostConfig"]["Tmpfs"], json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"})); + assert_eq!(sd["HostConfig"]["Binds"], json!([format!("{HOMES}:{HOMES}")])); + assert_eq!(sd["HostConfig"]["CapAdd"], json!(["NET_ADMIN", "SYS_PTRACE"])); + assert!(sd["Cmd"][2].as_str().unwrap().contains("/lib/systemd/systemd")); + + let plain = create_body_for("dev", "ubuntu:24.04", "alice", 1000, 1000, false); + assert!(plain["StopSignal"].is_null()); + assert!(plain["Env"].is_null()); + assert!(plain["HostConfig"]["Privileged"].is_null()); + assert!(plain["HostConfig"]["Tmpfs"].is_null()); + assert!(plain["Cmd"][2].as_str().unwrap().contains("sleep 3600")); + } + + #[test] + fn create_with_rejects_invalid_names_before_talking_to_daemon() { + for bad in ["", "-leading", "bad_name!", "with space"] { + let err = create_with( + bad, + "ubuntu", + false, + ("alice", 1000, 1000), + |_, _, _| panic!("daemon must not be called for invalid name {bad:?}"), + |_, _| panic!("exec must not be called"), + |_| panic!("pull must not be called"), + ) + .unwrap_err(); + assert_eq!(err.to_string(), "a machine name is letters, digits and dashes"); + } + } +} diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 4b69d8e11..9c1aeaad5 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 +### #935 Machines: use local images before pulling and mount `--systemd` `/tmp` and `/run` with `exec` (unreleased) +- Fixes: #935 `kiri machine create`: `--systemd` machines get a `noexec` `/tmp`, and `--image` always pulls instead of using a local image +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/machine.rs` + ### #934 Guest kernel: enable ext2/ext3 and FAT/vfat for loop-mounted disk images (unreleased) - Fixes: #934 Guest kernel has no ext2 or FAT/vfat, so loop-mounted disk images can't be mounted (`pmbootstrap install`, SD-card/EFI images) - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index b60b4c23b..e8a9f5a91 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -352,3 +352,4 @@ bind-chown-chmod #382 chown on a macOS virtiofs bind mount returned 0 while leav crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350) finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount +crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec From c5459e6bc12e0142c27135e1d7f14979f6d971aa Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:13:49 +0100 Subject: [PATCH 111/157] WSL: bundle zoneinfo and self-repair empty /etc/localtime directories (#938) (#942) --- contrib/wsl/kiri-linux/kiri-start | 4 + crates/kiri-init/src/linux/agent.rs | 5 + crates/kiri-init/src/linux/container.rs | 16 +- crates/kiri-init/src/linux/localtime.rs | 363 +++++++++++++++ crates/kiri-init/src/linux/mod.rs | 1 + crates/kiri/src/daemon/api.rs | 105 ++++- crates/kiri/src/daemon/binds.rs | 10 + crates/kiri/src/daemon/localtime.rs | 574 ++++++++++++++++++++++++ crates/kiri/src/daemon/mod.rs | 8 + docs/fix-registry.md | 6 + scripts/kiri-linux.sh | 32 ++ tests/regressions.tsv | 3 + 12 files changed, 1119 insertions(+), 8 deletions(-) create mode 100644 crates/kiri-init/src/linux/localtime.rs create mode 100644 crates/kiri/src/daemon/localtime.rs diff --git a/contrib/wsl/kiri-linux/kiri-start b/contrib/wsl/kiri-linux/kiri-start index a9ef111b9..63d349d10 100644 --- a/contrib/wsl/kiri-linux/kiri-start +++ b/contrib/wsl/kiri-linux/kiri-start @@ -34,6 +34,10 @@ if [ -n "$ro_state" ]; then exit 2 fi mkdir -p "$HOME" /var/log +# Clear an empty /etc/localtime or /etc/timezone directory left by pre-fix +# `-v` bind mounts before the daemon starts and restores valid files (#938). +[ -d /etc/localtime ] && [ ! -L /etc/localtime ] && rmdir /etc/localtime 2>/dev/null || true +[ -d /etc/timezone ] && [ ! -L /etc/timezone ] && rmdir /etc/timezone 2>/dev/null || true # One at a time: the boot command, the bridge, kiri-win and `kiri` # (crates/kiri/src/wsl.rs) can each start it at once, and two would each # remove the socket and start a daemon. busybox flock has no time limit of diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 8ca12e04f..576f216fe 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -105,6 +105,11 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap = if host_process { if let Err(e) = net::host_uplink() { diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index fdf9d0e40..5f0bd87c5 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1754,7 +1754,21 @@ pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> { } // A missing source becomes a directory, as Docker does; one that is // there already (a file such as /etc/hostname, too) is used as it is. - if flags.contains(&"create") && fs::symlink_metadata(src).is_err() { + // Never create a directory at /etc/localtime or /etc/timezone (#938). + let norm = lexical_normalize(Path::new(src)); + if norm == Path::new("/etc/localtime") { + if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir()) + || (flags.contains(&"create") && fs::metadata(src).is_err()) + { + super::localtime::ensure_localtime()?; + } + } else if norm == Path::new("/etc/timezone") { + if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir()) + || (flags.contains(&"create") && fs::metadata(src).is_err()) + { + super::localtime::ensure_timezone()?; + } + } else if flags.contains(&"create") && fs::symlink_metadata(src).is_err() { fs::create_dir_all(src)?; } let mut loop_mount = None; diff --git a/crates/kiri-init/src/linux/localtime.rs b/crates/kiri-init/src/linux/localtime.rs new file mode 100644 index 000000000..b0b1e2197 --- /dev/null +++ b/crates/kiri-init/src/linux/localtime.rs @@ -0,0 +1,363 @@ +//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or +//! symlink rather than missing or an empty directory (#938). +//! +//! Runs in `kiri-init` on WSL startup (self-healing upgraded pre-0.2.3 Kiri WSL +//! distros where Alpine minirootfs lacked `tzdata`) and guards `parse_mounts` +//! so bind-mount source creation never turns `/etc/localtime` or `/etc/timezone` +//! into a directory. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes: +/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) + +/// POSIX TZ footer (`\nUTC0\n`, 6 B). +pub const UTC_TZIF2: [u8; 114] = [ + // V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes, + // isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4. + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // V2 header (44 bytes): identical counts + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // POSIX TZ footer (6 bytes): "\nUTC0\n" + b'\n', b'U', b'T', b'C', b'0', b'\n', +]; + +static TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +/// Strict validation for relative IANA zone names from `TZ`: non-empty, no +/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and +/// only ASCII `[A-Za-z0-9_+.-/]`. +pub fn valid_tz_name(tz: &str) -> bool { + if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') { + return false; + } + if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) { + return false; + } + tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..") +} + +fn join_confined(root: &Path, rel: &Path) -> Option { + use std::path::Component; + let mut stack: Vec = Vec::new(); + for c in rel.components() { + match c { + Component::Normal(p) => stack.push(p.to_owned()), + Component::CurDir | Component::RootDir | Component::Prefix(_) => {} + Component::ParentDir => { + stack.pop()?; + } + } + } + let mut out = root.to_path_buf(); + for s in stack { + out.push(s); + } + Some(out) +} + +fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool { + let Ok(canon_root) = fs::canonicalize(root) else { + return false; + }; + let mut cur = path.to_path_buf(); + for _ in 0..16 { + let Ok(meta) = fs::symlink_metadata(&cur) else { + return false; + }; + let ft = meta.file_type(); + if !ft.is_symlink() { + if !ft.is_file() || meta.len() == 0 { + return false; + } + let Ok(canon_target) = fs::canonicalize(&cur) else { + return false; + }; + if !canon_target.starts_with(&canon_root) { + return false; + } + return allowed_bases.iter().any(|base| { + fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb)) + }); + } + let Ok(target) = fs::read_link(&cur) else { + return false; + }; + let next = if target.is_absolute() { + if root != Path::new("/") && target.starts_with(root) { + let rel = target.strip_prefix(root).unwrap_or(&target); + join_confined(root, rel) + } else { + let rel = target.strip_prefix("/").unwrap_or(&target); + join_confined(root, rel) + } + } else { + let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else { + return false; + }; + let combined = parent_rel.join(target); + join_confined(root, &combined) + }; + let Some(n) = next else { + return false; + }; + cur = n; + } + false +} + +fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path) +} + +fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else { + return false; + }; + resolve_confined_file(root, &[zinfo.as_path()], &candidate) +} + +fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf { + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id())) +} + +fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + let write_res = (|| -> io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?; + f.write_all(bytes)?; + f.set_permissions(fs::Permissions::from_mode(0o644))?; + f.sync_all()?; + Ok(()) + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + symlink(target, &tmp)?; + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn write_timezone_if_missing(root: &Path, zone: &str) { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) if meta.file_type().is_dir() => { + if fs::remove_dir(&tz_path).is_err() { + return; + } + } + Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return, + Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return, + Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return, + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(_) => return, + } + let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()); +} + +/// Ensures `/etc/localtime` on `/` is a valid timezone file or symlink. +pub fn ensure_localtime() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_localtime_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/localtime` is a valid timezone file or symlink. +pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let localtime = root.join("etc/localtime"); + match fs::symlink_metadata(&localtime) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&localtime) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &localtime) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + localtime.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz)) + && zoneinfo_file_exists(root, tz) + { + atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?; + write_timezone_if_missing(root, tz); + return Ok(()); + } + + if zoneinfo_file_exists(root, "Etc/UTC") { + atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?; + write_timezone_if_missing(root, "Etc/UTC"); + return Ok(()); + } + + atomic_write_file(&localtime, &UTC_TZIF2)?; + write_timezone_if_missing(root, "UTC"); + Ok(()) +} + +/// Ensures `/etc/timezone` on `/` is a valid timezone name file. +pub fn ensure_timezone() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_timezone_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/timezone` is a valid timezone name file (never a +/// directory), refusing to delete a non-empty directory. +pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&tz_path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &tz_path) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + tz_path.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + let inferred = fs::read_link(root.join("etc/localtime")) + .ok() + .and_then(|p| p.to_str().map(str::to_owned)) + .and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned())) + .filter(|z| valid_tz_name(z)); + let zone = inferred + .as_deref() + .or_else(|| tz_env.filter(|tz| valid_tz_name(tz))) + .unwrap_or("UTC"); + atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_root(name: &str) -> PathBuf { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-init-localtime-{name}-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("etc")).unwrap(); + dir + } + + #[test] + fn repairs_empty_dir_and_refuses_non_empty_dir() { + let root = test_root("dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + let bytes = fs::read(<).unwrap(); + assert!(bytes.starts_with(b"TZif2")); + assert!(bytes.ends_with(b"\nUTC0\n")); + assert_eq!(bytes.len(), 114); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n"); + + fs::remove_file(<).unwrap(); + fs::create_dir(<).unwrap(); + fs::write(lt.join("keep"), b"x").unwrap(); + assert!(ensure_localtime_at(&root, None).is_err()); + assert_eq!(fs::read(lt.join("keep")).unwrap(), b"x"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn preserves_valid_and_validates_tz() { + let root = test_root("tz"); + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + + ensure_localtime_at(&root, Some("../etc/shadow")).unwrap(); + assert!(fs::symlink_metadata(root.join("etc/localtime")).unwrap().file_type().is_file()); + + fs::remove_file(root.join("etc/localtime")).unwrap(); + fs::remove_file(root.join("etc/timezone")).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n"); + + // Second call leaves valid symlink untouched. + ensure_localtime_at(&root, None).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index be54bd8c1..6df6e9879 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -11,6 +11,7 @@ mod fsview; mod hostopts; mod inroot; mod layers; +mod localtime; mod net; mod netlink; mod pid1; diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 42d4b34f1..86b61d2ee 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -2022,6 +2022,57 @@ fn volumes_from_mounts(guest: &[String], info: &[Value], ro: bool) -> Vec<(Strin .collect() } +/// Prepares a host bind-mount source path before adding it to a container spec. +/// On Linux/WSL, `/etc/localtime` and `/etc/timezone` are never created as +/// directories: if missing (for `-v`) or an empty directory (left by an earlier +/// version before #938), they are created/repaired as valid timezone files. +fn prepare_bind_source(src: &str, here: &str, create_missing: bool) -> Result<(), Error> { + let tz = std::env::var("TZ").ok(); + prepare_bind_source_at(std::path::Path::new("/"), src, here, create_missing, !cfg!(target_os = "macos"), tz.as_deref()) +} + +fn prepare_bind_source_at( + root: &std::path::Path, + src: &str, + here: &str, + create_missing: bool, + linux_tz_guard: bool, + tz_env: Option<&str>, +) -> Result<(), Error> { + let norm = lexical_path(here); + let p = if root == std::path::Path::new("/") { + std::path::PathBuf::from(here) + } else { + root.join(norm.trim_start_matches('/')) + }; + if linux_tz_guard && matches!(norm.as_str(), "/etc/localtime" | "/etc/timezone") { + let heal = || match norm.as_str() { + "/etc/localtime" => super::localtime::ensure_localtime_at(root, tz_env).map_err(Error::Io), + _ => super::localtime::ensure_timezone_at(root, tz_env).map_err(Error::Io), + }; + let is_dir = std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_dir()); + if is_dir { + return heal(); + } + if !super::localtime::is_valid_timezone_file_at(root, &p) { + if !create_missing && !std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_file()) { + return Err(Error::BadRequest(format!( + "invalid mount config for type \"bind\": bind source path does not exist: {src}" + ))); + } + return heal(); + } + return Ok(()); + } + if !p.exists() { + if !create_missing { + return Err(Error::BadRequest(format!("invalid mount config for type \"bind\": bind source path does not exist: {src}"))); + } + super::binds::make_source(&p).map_err(Error::Io)?; + } + Ok(()) +} + /// `-v`, `--mount`, `--tmpfs`, `--volumes-from`, `-v /path` and the image's /// VOLUME lines. #[cfg(test)] @@ -2097,13 +2148,7 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); return Ok(()); }; - let p = std::path::Path::new(&here); - if !p.exists() { - if !create_missing { - return Err(Error::BadRequest(format!("invalid mount config for type \"bind\": bind source path does not exist: {src}"))); - } - super::binds::make_source(p).map_err(Error::Io)?; - } + prepare_bind_source(src, &here, create_missing)?; // After a missing source was made, so its links are followed too. out.guest.push(format!("{}\t{dst}\t{}", guest_bind_source(src), flag(""))); out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); @@ -8061,4 +8106,50 @@ mod resources_disk_tests { bad_guest.join().unwrap(); assert_eq!(err.kind(), io::ErrorKind::InvalidData); } + + #[test] + fn bind_mount_preparation_never_creates_localtime_or_timezone_directory() { + let root = std::env::temp_dir().join(format!("kiri-api-localtime-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("etc")).unwrap(); + + // `--mount type=bind` (`create_missing = false`) refuses missing /etc/localtime without creating a directory. + let err = super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", false, true, None).unwrap_err(); + assert!(matches!(err, super::Error::BadRequest(ref m) if m.contains("bind source path does not exist")), "{err:?}"); + assert!(std::fs::symlink_metadata(root.join("etc/localtime")).is_err()); + + // `-v /etc/localtime:/etc/localtime:ro` (`create_missing = true`) creates a valid TZif2 file, never a directory. + super::prepare_bind_source_at(&root, "/etc/localtime", "/etc//localtime", true, true, None).unwrap(); + let lt = root.join("etc/localtime"); + assert!(std::fs::symlink_metadata(<).unwrap().file_type().is_file()); + let bytes = std::fs::read(<).unwrap(); + assert!(bytes.starts_with(b"TZif2") && bytes.ends_with(b"\nUTC0\n")); + + // Existing empty directory at /etc/localtime is repaired into a file for both `-v` and `--mount`. + std::fs::remove_file(<).unwrap(); + std::fs::create_dir(<).unwrap(); + super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/./localtime", false, true, None).unwrap(); + assert!(std::fs::symlink_metadata(<).unwrap().file_type().is_file()); + + // Non-empty directory at /etc/localtime is refused without deleting its contents. + std::fs::remove_file(<).unwrap(); + std::fs::create_dir(<).unwrap(); + std::fs::write(lt.join("keep"), b"keep").unwrap(); + assert!(super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", true, true, None).is_err()); + assert_eq!(std::fs::read(lt.join("keep")).unwrap(), b"keep"); + std::fs::remove_dir_all(<).unwrap(); + + // `-v /etc/timezone:/etc/timezone:ro` creates/repairs a regular file, never a directory. + let tz = root.join("etc/timezone"); + let _ = std::fs::remove_file(&tz); + super::prepare_bind_source_at(&root, "/etc/timezone", "/etc/timezone", true, true, Some("Asia/Shanghai")).unwrap(); + assert!(std::fs::symlink_metadata(&tz).unwrap().file_type().is_file()); + assert_eq!(std::fs::read_to_string(&tz).unwrap(), "Asia/Shanghai\n"); + + // Regular missing bind paths still become directories under `-v`. + super::prepare_bind_source_at(&root, "/srv/app", "/srv/app", true, true, None).unwrap(); + assert!(root.join("srv/app").is_dir()); + + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index 754d19e6a..ad4da7d36 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -535,6 +535,16 @@ fn engine_socket_with_alias(src: &str, own: &str, alias: Option<&str>, resolve: /// folders 0750 and shut out the user whose mount it is. Folders already /// there are left as they are. pub fn make_source(path: &Path) -> std::io::Result<()> { + #[cfg(target_os = "linux")] + if path.is_absolute() { + let norm = lexical_clean(&path.to_string_lossy()); + if norm == "/etc/localtime" { + return super::localtime::ensure_localtime(); + } + if norm == "/etc/timezone" { + return super::localtime::ensure_timezone(); + } + } use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; let missing: Vec<&Path> = path.ancestors().take_while(|a| std::fs::symlink_metadata(a).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)).collect(); if missing.is_empty() { diff --git a/crates/kiri/src/daemon/localtime.rs b/crates/kiri/src/daemon/localtime.rs new file mode 100644 index 000000000..34fac5300 --- /dev/null +++ b/crates/kiri/src/daemon/localtime.rs @@ -0,0 +1,574 @@ +//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or +//! symlink rather than missing or an empty directory (#938). +//! +//! Pre-0.2.3 Kiri WSL distros were built from Alpine minirootfs without +//! `tzdata`, so `/etc/localtime` did not exist and `-v /etc/localtime:...` +//! created an empty directory there. On WSL startup and before host bind mounts +//! of `/etc/localtime` or `/etc/timezone`, this module heals empty directories +//! (never non-empty directories) and creates either a symlink into +//! `/usr/share/zoneinfo` or a canonical RFC 8536 `TZif2` UTC binary. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes: +/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) + +/// POSIX TZ footer (`\nUTC0\n`, 6 B). +pub const UTC_TZIF2: [u8; 114] = [ + // V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes, + // isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4. + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // V2 header (44 bytes): identical counts + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // POSIX TZ footer (6 bytes): "\nUTC0\n" + b'\n', b'U', b'T', b'C', b'0', b'\n', +]; + +static TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +/// Strict validation for relative IANA zone names from `TZ` (e.g. +/// `"Asia/Shanghai"`, `"America/New_York"`, `"Etc/GMT+5"`): non-empty, no +/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and +/// only ASCII `[A-Za-z0-9_+.-/]`. +pub fn valid_tz_name(tz: &str) -> bool { + if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') { + return false; + } + if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) { + return false; + } + tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..") +} + +/// Checks whether `path` (interpreted within `root`) is a non-empty regular +/// file or a symlink whose target stays confined to `/usr/share/zoneinfo` +/// (or `/etc`) and resolves to a non-empty regular file. +pub fn is_valid_timezone_file_at(root: &Path, path: &Path) -> bool { + let Ok(meta) = fs::symlink_metadata(path) else { + return false; + }; + let ft = meta.file_type(); + if ft.is_file() { + return meta.len() > 0; + } + if ft.is_symlink() { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + return resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path); + } + false +} + +/// Lexically normalizes `rel` beneath `root`, returning `None` if `..` would +/// escape above `root`. +fn join_confined(root: &Path, rel: &Path) -> Option { + use std::path::Component; + let mut stack: Vec = Vec::new(); + for c in rel.components() { + match c { + Component::Normal(p) => stack.push(p.to_owned()), + Component::CurDir | Component::RootDir | Component::Prefix(_) => {} + Component::ParentDir => { + stack.pop()?; + } + } + } + let mut out = root.to_path_buf(); + for s in stack { + out.push(s); + } + Some(out) +} + +/// Resolves symlinks starting at `path` within `root` and returns true iff the +/// final target is a non-empty regular file whose canonical path sits inside +/// one of `allowed_bases`. +fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool { + let canon_root = fs::canonicalize(root).ok(); + let Some(canon_root_ref) = canon_root.as_deref() else { + return false; + }; + let mut cur = path.to_path_buf(); + for _ in 0..16 { + let Ok(meta) = fs::symlink_metadata(&cur) else { + return false; + }; + let ft = meta.file_type(); + if !ft.is_symlink() { + if !ft.is_file() || meta.len() == 0 { + return false; + } + let Ok(canon_target) = fs::canonicalize(&cur) else { + return false; + }; + if !canon_target.starts_with(canon_root_ref) { + return false; + } + return allowed_bases.iter().any(|base| { + fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb)) + }); + } + let Ok(target) = fs::read_link(&cur) else { + return false; + }; + let next = if target.is_absolute() { + if root != Path::new("/") && target.starts_with(root) { + let rel = target.strip_prefix(root).unwrap_or(&target); + join_confined(root, rel) + } else { + let rel = target.strip_prefix("/").unwrap_or(&target); + join_confined(root, rel) + } + } else { + let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else { + return false; + }; + let combined = parent_rel.join(target); + join_confined(root, &combined) + }; + let Some(n) = next else { + return false; + }; + cur = n; + } + false +} + +fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path) +} + +fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else { + return false; + }; + resolve_confined_file(root, &[zinfo.as_path()], &candidate) +} + +fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf { + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id())) +} + +fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + let write_res = (|| -> io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?; + f.write_all(bytes)?; + f.set_permissions(fs::Permissions::from_mode(0o644))?; + f.sync_all()?; + Ok(()) + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + symlink(target, &tmp)?; + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +/// Writes `\n` to `/etc/timezone` if it is missing (or an empty +/// directory). Never overwrites an existing valid file or non-empty directory. +fn write_timezone_if_missing(root: &Path, zone: &str) { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) if meta.file_type().is_dir() => { + // Only remove an empty directory; never remove_dir_all. + if fs::remove_dir(&tz_path).is_err() { + return; + } + } + Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return, + Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return, + Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return, + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(_) => return, + } + let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()); +} + +/// Ensures `/etc/localtime` on the live root (`/`) is a valid file or symlink. +pub fn ensure_localtime() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_localtime_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/localtime` is a valid timezone file or symlink: +/// 1. If `/etc/localtime` is a directory, removes it ONLY if empty +/// (`remove_dir`, never `remove_dir_all`). +/// 2. If it is already a non-empty regular file or a symlink resolving to a +/// regular file, leaves it untouched. +/// 3. If missing, empty file, or broken symlink: +/// - If `tz_env` is a valid relative zone name and +/// `/usr/share/zoneinfo/` is a regular file, symlinks +/// `/etc/localtime` -> `/usr/share/zoneinfo/` and writes `\n` to +/// `/etc/timezone` if missing. +/// - Else if `/usr/share/zoneinfo/Etc/UTC` is a regular file, symlinks +/// `/etc/localtime` -> `/usr/share/zoneinfo/Etc/UTC` and writes `Etc/UTC\n` +/// to `/etc/timezone` if missing. +/// - Else atomically writes canonical RFC 8536 `UTC_TZIF2` (`0644`) to +/// `/etc/localtime` and writes `UTC\n` to `/etc/timezone` if +/// missing. +pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let localtime = root.join("etc/localtime"); + match fs::symlink_metadata(&localtime) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + // ONLY removes an empty directory; non-empty directories return an error. + match fs::remove_dir(&localtime) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &localtime) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + localtime.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz)) + && zoneinfo_file_exists(root, tz) + { + atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?; + write_timezone_if_missing(root, tz); + return Ok(()); + } + + if zoneinfo_file_exists(root, "Etc/UTC") { + atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?; + write_timezone_if_missing(root, "Etc/UTC"); + return Ok(()); + } + + atomic_write_file(&localtime, &UTC_TZIF2)?; + write_timezone_if_missing(root, "UTC"); + Ok(()) +} + +/// Ensures `/etc/timezone` on the live root (`/`) is a valid file or symlink. +pub fn ensure_timezone() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_timezone_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/timezone` is a valid timezone name file (never a +/// directory), refusing to delete a non-empty directory. +pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&tz_path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &tz_path) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + tz_path.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + let inferred = fs::read_link(root.join("etc/localtime")) + .ok() + .and_then(|p| p.to_str().map(str::to_owned)) + .and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned())) + .filter(|z| valid_tz_name(z)); + let zone = inferred + .as_deref() + .or_else(|| tz_env.filter(|tz| valid_tz_name(tz))) + .unwrap_or("UTC"); + atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_root(name: &str) -> PathBuf { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-localtime-{name}-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("etc")).unwrap(); + dir + } + + /// Minimal RFC 8536 TZif2 parser check verifying header counts, v1/v2 data + /// block framing, UTC designation, and POSIX TZ footer. + fn assert_valid_utc_tzif2(bytes: &[u8]) { + assert_eq!(bytes.len(), 114, "canonical UTC TZif2 is 114 bytes"); + assert!(bytes.starts_with(b"TZif2"), "must start with TZif2 magic"); + assert!(bytes.ends_with(b"\nUTC0\n"), "must end with POSIX UTC0 footer"); + let be_u32 = |off: usize| u32::from_be_bytes(bytes[off..off + 4].try_into().unwrap()); + // Verify both v1 (offset 0) and v2 (offset 54) sections. + for base in [0usize, 54usize] { + assert_eq!(&bytes[base..base + 5], b"TZif2"); + assert_eq!(&bytes[base + 5..base + 20], &[0u8; 15]); + assert_eq!(be_u32(base + 20), 0, "isutcnt"); + assert_eq!(be_u32(base + 24), 0, "isstdcnt"); + assert_eq!(be_u32(base + 28), 0, "leapcnt"); + assert_eq!(be_u32(base + 32), 0, "timecnt"); + assert_eq!(be_u32(base + 36), 1, "typecnt"); + assert_eq!(be_u32(base + 40), 4, "charcnt"); + // Local time type record: utoff=0, isdst=0, desigidx=0 + assert_eq!(&bytes[base + 44..base + 50], &[0u8; 6]); + // Abbreviation string table: "UTC\0" + assert_eq!(&bytes[base + 50..base + 54], b"UTC\0"); + } + assert_eq!(&bytes[108..114], b"\nUTC0\n"); + } + + #[test] + fn repairs_empty_localtime_directory_into_valid_tzif2_file() { + let root = test_root("empty-dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_dir()); + + ensure_localtime_at(&root, None).unwrap(); + + let meta = fs::symlink_metadata(<).unwrap(); + assert!(meta.file_type().is_file(), "repaired /etc/localtime must be a regular file"); + assert_eq!(meta.permissions().mode() & 0o777, 0o644); + let bytes = fs::read(<).unwrap(); + assert_valid_utc_tzif2(&bytes); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn refuses_to_delete_non_empty_localtime_directory() { + let root = test_root("non-empty-dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + let keep = lt.join("sentinel.txt"); + fs::write(&keep, b"do-not-delete").unwrap(); + + let err = ensure_localtime_at(&root, None).expect_err("non-empty directory must not be removed"); + assert!(lt.is_dir(), "directory must remain intact after error ({err})"); + assert_eq!(fs::read(&keep).unwrap(), b"do-not-delete"); + + // Same safety invariant for /etc/timezone. + let tz = root.join("etc/timezone"); + fs::create_dir(&tz).unwrap(); + let keep_tz = tz.join("keep"); + fs::write(&keep_tz, b"safe").unwrap(); + assert!(ensure_timezone_at(&root, None).is_err()); + assert_eq!(fs::read(&keep_tz).unwrap(), b"safe"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn preserves_existing_valid_localtime_file_and_symlink() { + let root = test_root("preserve"); + let lt = root.join("etc/localtime"); + let custom = b"TZif2-custom-existing-file"; + fs::write(<, custom).unwrap(); + + // Even with TZ pointing to a valid zoneinfo file, existing valid file is untouched. + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_eq!(fs::read(<).unwrap(), custom); + assert!(!root.join("etc/timezone").exists(), "should not touch /etc/timezone when /etc/localtime is already valid"); + + // Valid symlink resolving inside root is also preserved untouched. + fs::remove_file(<).unwrap(); + let ny = root.join("usr/share/zoneinfo/America/New_York"); + fs::create_dir_all(ny.parent().unwrap()).unwrap(); + fs::write(&ny, &UTC_TZIF2).unwrap(); + symlink("/usr/share/zoneinfo/America/New_York", <).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(<).unwrap(), Path::new("/usr/share/zoneinfo/America/New_York")); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn links_valid_tz_env_and_rejects_path_traversal() { + let root = test_root("tz-env"); + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + let utc = root.join("usr/share/zoneinfo/Etc/UTC"); + fs::create_dir_all(utc.parent().unwrap()).unwrap(); + fs::write(&utc, &UTC_TZIF2).unwrap(); + + // Valid TZ links to /usr/share/zoneinfo/ and populates /etc/timezone. + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n"); + + // Reject path-traversal and invalid TZ strings; fall back to Etc/UTC. + for bad in [ + "../etc/shadow", + "/etc/passwd", + "Asia/../../etc/passwd", + "", + ".", + "..", + "Asia/", + "Asia//Shanghai", + "Asia\\Shanghai", + "Asia/Shanghai\0", + "Asia/Shanghai\n", + ":Asia/Shanghai", + ] { + assert!(!valid_tz_name(bad), "{bad:?} must be rejected"); + let _ = fs::remove_file(root.join("etc/localtime")); + let _ = fs::remove_file(root.join("etc/timezone")); + ensure_localtime_at(&root, Some(bad)).unwrap(); + assert_eq!( + fs::read_link(root.join("etc/localtime")).unwrap(), + Path::new("/usr/share/zoneinfo/Etc/UTC"), + "bad TZ {bad:?} must fall back to Etc/UTC" + ); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Etc/UTC\n"); + } + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn replaces_broken_symlink_and_empty_file() { + let root = test_root("broken-link"); + let lt = root.join("etc/localtime"); + + // Dangling symlink pointing to /usr/share/zoneinfo/Etc/UTC when root has no zoneinfo. + symlink("/usr/share/zoneinfo/Etc/UTC", <).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // Symlink pointing to a directory is treated as broken. + fs::remove_file(<).unwrap(); + fs::create_dir_all(root.join("usr/share/zoneinfo")).unwrap(); + symlink("/usr/share/zoneinfo", <).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // 0-byte regular file is repaired into a valid TZif2 file. + fs::write(<, b"").unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn ensures_timezone_file_and_infers_from_localtime_link() { + let root = test_root("timezone"); + let berlin = root.join("usr/share/zoneinfo/Europe/Berlin"); + fs::create_dir_all(berlin.parent().unwrap()).unwrap(); + fs::write(&berlin, &UTC_TZIF2).unwrap(); + symlink("/usr/share/zoneinfo/Europe/Berlin", root.join("etc/localtime")).unwrap(); + fs::create_dir(root.join("etc/timezone")).unwrap(); + + ensure_timezone_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(root.join("etc/timezone")).unwrap().file_type().is_file()); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Europe/Berlin\n"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn rejects_symlinks_escaping_zoneinfo_or_root() { + let root = test_root("confined"); + let zinfo = root.join("usr/share/zoneinfo"); + fs::create_dir_all(&zinfo).unwrap(); + fs::create_dir_all(root.join("var/secret")).unwrap(); + fs::write(root.join("var/secret/token"), b"secret").unwrap(); + + // A symlink inside zoneinfo escaping to /var/secret/token is rejected for TZ + // and falls back to writing UTC_TZIF2 instead of linking to the secret file. + symlink("../../../var/secret/token", zinfo.join("EvilZone")).unwrap(); + assert!(!super::zoneinfo_file_exists(&root, "EvilZone")); + ensure_localtime_at(&root, Some("EvilZone")).unwrap(); + let lt = root.join("etc/localtime"); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // An /etc/localtime symlink pointing outside /usr/share/zoneinfo and /etc is + // rejected by is_valid_timezone_file_at and replaced on ensure_localtime_at. + fs::remove_file(<).unwrap(); + symlink("/var/secret/token", <).unwrap(); + assert!(!is_valid_timezone_file_at(&root, <)); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index c11db2b63..2a5972969 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -23,6 +23,8 @@ mod hostetc; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] mod hostroots; mod hostopts; +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) mod localtime; mod mirror; mod http; mod logfile; @@ -217,6 +219,12 @@ pub fn run(_args: &[String]) -> io::Result<()> { } } let _ = BOUND_SOCKET.set(socket.clone()); + #[cfg(target_os = "linux")] + if rofs::is_wsl() + && let Err(e) = localtime::ensure_localtime() + { + diag::warn!("could not repair /etc/localtime", error = e); + } if let Some(ref msg) = rofs::check_daemon_storage(None) { diag::error!("storage filesystem is read-only", detail = msg); } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 9c1aeaad5..86a25b8ea 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 +### #938 Windows (WSL 2): bundle `zoneinfo`, self-heal `/etc/localtime`, and prevent bind mounts from creating timezone directories (unreleased) +- Fixes: #938 Windows: `/etc/localtime` is a directory in Kiri WSL, breaking common bind mounts +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/daemon/localtime.rs`, `crates/kiri-init/src/linux/localtime.rs`, `scripts/kiri-linux.sh` + ### #935 Machines: use local images before pulling and mount `--systemd` `/tmp` and `/run` with `exec` (unreleased) - Fixes: #935 `kiri machine create`: `--systemd` machines get a `noexec` `/tmp`, and `--image` always pulls instead of using a local image - Caused: none known diff --git a/scripts/kiri-linux.sh b/scripts/kiri-linux.sh index 30d5f8ed1..a78e63be6 100644 --- a/scripts/kiri-linux.sh +++ b/scripts/kiri-linux.sh @@ -19,9 +19,41 @@ mkdir -p "$cache" # The .part is this process's own: CI jobs on one machine share the cache. [ -f "$cache/$ALPINE" ] || { curl -fsSL --retry 3 -o "$cache/$ALPINE.$$.part" "$ALPINE_URL" && mv -f "$cache/$ALPINE.$$.part" "$cache/$ALPINE"; } || rm -f "$cache/$ALPINE.$$.part" echo "$ALPINE_SHA256 $cache/$ALPINE" | sha256sum -c - >/dev/null || { rm -f "$cache/$ALPINE"; echo "$ALPINE: SHA-256 mismatch" >&2; exit 1; } +write_utc_tzif() { + # Canonical RFC 8536 TZif2 binary for UTC (UTC0): v1 header+data (54 B), + # v2 header+data (54 B), POSIX TZ footer ("\nUTC0\n", 6 B). + for _ in 1 2; do + printf 'TZif2' + printf '\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000' + printf '\001\000\000\000\004\000\000\000\000\000\000UTC\000' + done + printf '\nUTC0\n' +} root=$(mktemp -d) trap 'rm -rf "$root"' EXIT tar --no-same-owner -xzf "$cache/$ALPINE" -C "$root" install -m 755 "$bin/kiri" "$bin/kiri-init" "$repo/contrib/wsl/kiri-linux/kiri-start" "$root/usr/local/bin/" install -m 644 "$repo/contrib/wsl/kiri-linux/wsl.conf" "$root/etc/wsl.conf" +# Bundle zoneinfo and /etc/localtime so WSL 2's Windows-to-Linux timezone sync +# finds /usr/share/zoneinfo and common `-v /etc/localtime:...` bind mounts +# never turn /etc/localtime into a directory (#938). +if [ -d /usr/share/zoneinfo ]; then + mkdir -p "$root/usr/share/zoneinfo" + cp -a /usr/share/zoneinfo/. "$root/usr/share/zoneinfo" +fi +if [ -L "$root/usr/share/zoneinfo/Etc/UTC" ] || [ ! -f "$root/usr/share/zoneinfo/Etc/UTC" ]; then + mkdir -p "$root/usr/share/zoneinfo/Etc" + rm -f "$root/usr/share/zoneinfo/Etc/UTC" + write_utc_tzif > "$root/usr/share/zoneinfo/Etc/UTC" + chmod 644 "$root/usr/share/zoneinfo/Etc/UTC" +fi +if [ -L "$root/usr/share/zoneinfo/UTC" ] || [ ! -f "$root/usr/share/zoneinfo/UTC" ]; then + rm -f "$root/usr/share/zoneinfo/UTC" + write_utc_tzif > "$root/usr/share/zoneinfo/UTC" + chmod 644 "$root/usr/share/zoneinfo/UTC" +fi +ln -snf /usr/share/zoneinfo/Etc/UTC "$root/etc/localtime" +rm -f "$root/etc/timezone" +printf 'Etc/UTC\n' > "$root/etc/timezone" +chmod 644 "$root/etc/timezone" tar -C "$root" --numeric-owner --owner=0 --group=0 -czf "$out" . diff --git a/tests/regressions.tsv b/tests/regressions.tsv index e8a9f5a91..ae404f5a5 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -353,3 +353,6 @@ crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed w finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec +crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation +crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone +scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs From d52422f8a0e2390acaaa58764ed1ab8e900aa08d Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:44:21 +0100 Subject: [PATCH 112/157] Networking: answer external AAAA with NODATA on IPv4-only networks and relay enterprise macOS VPNs (#932) (#943) --- crates/kiri-init/src/linux/agent.rs | 1 + crates/kiri-init/src/linux/container.rs | 1 + crates/kiri-init/src/linux/dns.rs | 85 ++++++- crates/kiri-init/src/linux/net.rs | 5 + crates/kiri/src/daemon/ports.rs | 301 ++++++++++++++++++++---- docs/fix-registry.md | 6 + tests/regressions.tsv | 1 + 7 files changed, 353 insertions(+), 47 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 576f216fe..253bec551 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -786,6 +786,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { + dns.set_bridge_ipv6(n.bridge, bridges.has_ipv6(n.bridge)); if is_user { if let Some(name) = kiri_proto::net_opts::values(n.opts, kiri_proto::net_opts::NETWORK).next() { dns.name_network(n.bridge, name); diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 5f0bd87c5..e3384058b 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -785,6 +785,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

>, + /// Bridges with IPv6 enabled: external `AAAA` queries on a server whose + /// bridges are all IPv4-only are answered `NODATA` locally (matching + /// Docker's libnetwork) instead of returning unreachable global IPv6 + /// addresses (#932). + ipv6_bridges: std::collections::HashSet, /// bridge → its Docker network's name: the order a container's server /// searches its networks in. networks: HashMap, @@ -340,6 +345,7 @@ impl Dns { /// The IPv6 address of the container that has `owner` on this network. pub fn register6(&mut self, bridge: &str, names: impl Iterator>, owner: [u8; 4], ip: [u8; 16]) { + self.ipv6_bridges.insert(bridge.to_owned()); let table = self.names6.entry(bridge.to_owned()).or_default(); for n in names { let list = table.entry(n.as_ref().to_ascii_lowercase()).or_default(); @@ -349,6 +355,25 @@ impl Dns { } } + /// Records whether `bridge` has IPv6 enabled, controlling whether external + /// `AAAA` queries on servers attached to it are forwarded upstream or + /// answered `NODATA` locally (#932). + pub fn set_bridge_ipv6(&mut self, bridge: &str, enabled: bool) { + if enabled { + self.ipv6_bridges.insert(bridge.to_owned()); + } else { + self.ipv6_bridges.remove(bridge); + } + } + + /// Whether any network served by `server` has IPv6 enabled. + fn server_has_ipv6(&self, server: usize) -> bool { + self.servers[server] + .bridges + .iter() + .any(|b| self.ipv6_bridges.contains(b) || self.names6.get(b).is_some_and(|m| !m.is_empty())) + } + /// `bridge` is Docker network `name` (`net_opts::NETWORK`). pub fn name_network(&mut self, bridge: &str, name: &str) { if self.networks.get(bridge).is_none_or(|n| n != name) { @@ -364,6 +389,7 @@ impl Dns { } self.names.remove(bridge); self.names6.remove(bridge); + self.ipv6_bridges.remove(bridge); self.networks.remove(bridge); self.refused.remove(bridge); self.forget_pending(); @@ -685,9 +711,19 @@ impl Dns { } } let own = self.own_servers(key).map(|v| v.len()); - let Some((_, _, end)) = parse_question(q) else { + let Some((_, qtype, end)) = parse_question(q) else { return; }; + // On IPv4-only networks (no bridge on this server has IPv6 enabled), + // return NOERROR/NODATA for external AAAA queries instead of forwarding + // upstream and returning unreachable global IPv6 records (matching + // Docker Engine's libnetwork resolver, #932). Containers with custom + // `--dns` servers keep forwarding unmodified. + if qtype == 28 && own.is_none() && !self.server_has_ipv6(server) { + let reply = nodata(id_of(q), rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &reply); + return; + } let (mut mine, mut mine_own) = (0, 0); for p in self.pending.iter().filter(|p| p.key == key) { mine += 1; @@ -1280,6 +1316,18 @@ fn rd(q: &[u8]) -> bool { q.get(2).is_some_and(|f| f & 0x01 != 0) } +/// A NOERROR reply with zero answers (NODATA) for a query with this `id`, RD +/// flag and `question` section. +fn nodata(id: u16, rd: bool, question: &[u8]) -> Vec { + let mut r = Vec::with_capacity(12 + question.len()); + r.extend_from_slice(&id.to_be_bytes()); + r.extend_from_slice(&[0x80 | u8::from(rd), 0x80]); // response, RD as asked, recursion available, NOERROR + r.extend_from_slice(&1u16.to_be_bytes()); + r.extend_from_slice(&[0; 6]); + r.extend_from_slice(question); + r +} + /// A SERVFAIL for a query with this `id`, RD flag and `question` section. fn servfail(id: u16, rd: bool, question: &[u8]) -> Vec { let mut r = Vec::with_capacity(12 + question.len()); @@ -2852,4 +2900,39 @@ mod tests { msg[rdata_off..].copy_from_slice(&[104, 16, 25, 34]); assert!(!super::answer_has_fake_ip(&msg), "real public IP is not a Fake-IP"); } + + #[test] + fn ipv4_only_server_answers_external_aaaa_with_nodata_while_ipv6_forwards() { + use std::net::UdpSocket; + use std::os::fd::AsRawFd; + + let mut dns = Dns::default(); + let gw = UdpSocket::bind("127.0.0.1:0").unwrap(); + gw.set_nonblocking(true).unwrap(); + let gw_addr = gw.local_addr().unwrap(); + dns.servers.push(super::Server { id: super::server_id(), bridges: vec!["kiri0".into()], sock: gw.into(), container: None }); + + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + + // 1. IPv4-only bridge: external AAAA gets immediate NOERROR/NODATA without upstream traffic. + let q_aaaa = query("registry-1.docker.io", 28); + client.send_to(&q_aaaa, gw_addr).unwrap(); + let srv_fd = dns.servers[0].sock.as_raw_fd(); + wait_readable(srv_fd); + dns.on_readable(srv_fd, &[[127, 0, 0, 71]]); + assert!(dns.pending.is_empty(), "IPv4-only server must not forward external AAAA upstream"); + let mut reply = [0u8; 512]; + let n = client.recv(&mut reply).unwrap(); + assert_eq!(reply[3] & 0x0f, 0, "NOERROR"); + assert_eq!(u16::from_be_bytes([reply[6], reply[7]]), 0, "zero answers (NODATA)"); + assert!(n >= q_aaaa.len()); + + // 2. Enabling IPv6 on the bridge allows external AAAA queries to forward upstream. + dns.set_bridge_ipv6("kiri0", true); + client.send_to(&q_aaaa, gw_addr).unwrap(); + wait_readable(srv_fd); + dns.on_readable(srv_fd, &[[127, 0, 0, 71]]); + assert_eq!(dns.pending.len(), 1, "IPv6-enabled bridge forwards external AAAA upstream"); + } } diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 973665b4f..86867bec2 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -941,6 +941,11 @@ enum BridgePlan { } impl Bridges { + /// Whether `name` currently exists with an IPv6 subnet configured. + pub fn has_ipv6(&self, name: &str) -> bool { + matches!(self.made.get(name), Some((.., Some(_)))) + } + fn plan(&self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, want6: Bridge6) -> BridgePlan { match self.made.get(name) { Some(&(i, g, p, b6)) if (g, p) == (gateway, prefix) => match (b6, want6) { diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index ffb2eb14d..a747061f3 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -1855,8 +1855,9 @@ pub fn is_tunnel_iface(name: &str) -> bool { .any(|prefix| name.strip_prefix(prefix).is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))) } -/// Collapses a set of IPv4 CIDRs, removing duplicates and any sub-prefix -/// already covered by a broader prefix in the set. +/// Collapses a set of IPv4 CIDRs, removing duplicates, sub-prefixes already +/// covered by a broader prefix, and merging aligned sibling halves (such as +/// OpenVPN `def1`'s `0.0.0.0/1` + `128.0.0.0/1` → `0.0.0.0/0`). pub fn collapse_cidrs(cidrs: impl IntoIterator) -> Vec<([u8; 4], u8)> { let mut list: Vec<([u8; 4], u8)> = cidrs .into_iter() @@ -1867,20 +1868,89 @@ pub fn collapse_cidrs(cidrs: impl IntoIterator) -> Vec<([u .collect(); list.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); list.dedup(); - let mut out: Vec<([u8; 4], u8)> = Vec::with_capacity(list.len()); + let mut disjoint: Vec<([u8; 4], u8)> = Vec::with_capacity(list.len()); for (net, prefix) in list { - if !out.iter().any(|&(broader_net, broader_prefix)| broader_prefix <= prefix && cidr_contains(broader_net, broader_prefix, net)) { - out.push((net, prefix)); + if !disjoint.iter().any(|&(broader_net, broader_prefix)| broader_prefix <= prefix && cidr_contains(broader_net, broader_prefix, net)) { + disjoint.push((net, prefix)); } } + disjoint.sort_by_key(|&(net, prefix)| (u32::from_be_bytes(net), prefix)); + let mut merged: Vec<(u32, u8)> = Vec::with_capacity(disjoint.len()); + for (net, prefix) in disjoint { + let mut cur = (u32::from_be_bytes(net), prefix); + while let Some(&(prev_net, prev_prefix)) = merged.last() { + if prev_prefix != cur.1 || prev_prefix == 0 { + break; + } + let parent_prefix = prev_prefix - 1; + let parent_mask = ipv4_mask(parent_prefix); + if (prev_net & parent_mask) == (cur.0 & parent_mask) { + merged.pop(); + cur = (prev_net & parent_mask, parent_prefix); + } else { + break; + } + } + merged.push(cur); + } + let mut out: Vec<([u8; 4], u8)> = merged.into_iter().map(|(net, prefix)| (net.to_be_bytes(), prefix)).collect(); + out.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); out } +/// An active (`IFF_UP | IFF_RUNNING`) macOS tunnel interface (`utun*`, +/// `ipsec*`, `ppp*`, `gpd*`, `feth*`) carrying a non-loopback, non-link-local +/// IPv4 address (distinguishing active VPN tunnels from macOS's dormant +/// IDS/iCloud `utun*` interfaces, which only carry `fe80::` link-local IPv6). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ActiveTunnel { + pub name: String, + pub ip: [u8; 4], + pub prefix: u8, + pub peer: Option<[u8; 4]>, + pub point_to_point: bool, +} + +fn is_routable_tunnel_ipv4(ip: [u8; 4]) -> bool { + ip[0] != 0 && ip[0] != 127 && !(ip[0] == 169 && ip[1] == 254) && ip[0] < 224 +} + +fn is_tunnel_route_skippable(dst: [u8; 4], prefix: u8) -> bool { + dst[0] == 127 + || (dst[0] == 169 && dst[1] == 254) + || dst[0] >= 224 + || (dst == [0, 0, 0, 0] && prefix == 32) +} + /// Parses a macOS `sysctl([CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0])` /// binary routing table buffer and returns the collapsed IPv4 CIDR prefixes /// whose outgoing interface is a tunnel (`is_tunnel_iface`), skipping /// loopback, link-local and multicast/reserved destinations. +#[cfg(test)] pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) -> Vec<([u8; 4], u8)> { + parse_macos_routes_with_tunnels(buf, ifname_of, &[]) +} + +/// Parses a macOS `NET_RT_DUMP` buffer together with active IPv4 tunnel +/// interfaces (`active_tunnels` from `getifaddrs`), returning the collapsed +/// IPv4 CIDR prefixes that must route through the host egress dialer (#932): +/// - Unscoped routes on any tunnel interface (`is_tunnel_iface`) are kept. +/// - `RTF_IFSCOPE` routes on non-tunnel interfaces and dormant tunnels +/// without an IPv4 address are ignored. +/// - On an active IPv4 tunnel, non-default `RTF_IFSCOPE` split routes are +/// kept, and an `RTF_IFSCOPE` default route (`0.0.0.0/0`) is promoted when +/// that tunnel has no explicit non-endpoint narrower routes (catching +/// macOS 15+ `includeAllNetworks` / built-in IKEv2 / IPSec / PPP full +/// tunnels without misclassifying split-tunnel OpenVPN/Tailscale/WireGuard). +/// - An active IPv4 tunnel with no explicit non-endpoint routes in the route +/// table contributes `0.0.0.0/0` when it is a `/32` (or `/0`) +/// point-to-point tunnel (NECP policy-routed VPN), or its own subnet when +/// it has a `1..=31` netmask. +pub fn parse_macos_routes_with_tunnels( + buf: &[u8], + ifname_of: impl Fn(u16) -> Option, + active_tunnels: &[ActiveTunnel], +) -> Vec<([u8; 4], u8)> { const RTM_HDR_LEN: usize = 92; const RTM_VERSION: u8 = 5; const RTF_UP: i32 = 0x1; @@ -1893,7 +1963,7 @@ pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) #[cfg(target_os = "macos")] const _: () = assert!(std::mem::size_of::() == RTM_HDR_LEN); - let mut entries: Vec<([u8; 4], u8, String)> = Vec::new(); + let mut entries: Vec<([u8; 4], u8, String, bool)> = Vec::new(); let mut off = 0; while off + RTM_HDR_LEN <= buf.len() { let msglen = u16::from_ne_bytes([buf[off], buf[off + 1]]) as usize; @@ -1910,9 +1980,10 @@ pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) let ifindex = u16::from_ne_bytes([msg[4], msg[5]]); let flags = i32::from_ne_bytes([msg[8], msg[9], msg[10], msg[11]]); let addrs = i32::from_ne_bytes([msg[12], msg[13], msg[14], msg[15]]); - if flags & RTF_UP == 0 || flags & (RTF_WASCLONED | RTF_LLINFO | RTF_IFSCOPE) != 0 || addrs & 0x1 == 0 { + if flags & RTF_UP == 0 || flags & (RTF_WASCLONED | RTF_LLINFO) != 0 || addrs & 0x1 == 0 { continue; } + let is_ifscope = flags & RTF_IFSCOPE != 0; let mut pos = RTM_HDR_LEN; let mut dst: Option<[u8; 4]> = None; let mut mask_prefix: Option = None; @@ -1957,43 +2028,75 @@ pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) mask_prefix.unwrap_or(0) }; let Some(ifname) = ifname_of(ifindex).filter(|s| !s.is_empty()) else { continue }; - entries.push((mask_ipv4(dst_ip, prefix), prefix, ifname)); + if !is_tunnel_iface(&ifname) { + continue; + } + let net = mask_ipv4(dst_ip, prefix); + if is_tunnel_route_skippable(net, prefix) { + continue; + } + entries.push((net, prefix, ifname, is_ifscope)); } + let is_active_tunnel = |name: &str| active_tunnels.iter().any(|t| t.name == name && is_tunnel_iface(&t.name) && is_routable_tunnel_ipv4(t.ip)); let mut routes = Vec::new(); - for (dst, prefix, ifname) in entries { - if !is_tunnel_iface(&ifname) { + for &(dst, prefix, ref ifname, is_ifscope) in &entries { + if !is_ifscope || (prefix > 0 && is_active_tunnel(ifname)) { + routes.push((dst, prefix)); + } + } + for t in active_tunnels { + if !is_tunnel_iface(&t.name) || !is_routable_tunnel_ipv4(t.ip) { continue; } - // Every tunnel route is kept, the default route too when a full - // tunnel VPN replaced the primary interface. Skip loopback, link-local, multicast/reserved and 0.0.0.0/32. - if dst[0] == 127 - || (dst[0] == 169 && dst[1] == 254) - || dst[0] >= 224 - || (dst == [0, 0, 0, 0] && prefix == 32) - { + let is_endpoint = |dst: [u8; 4], prefix: u8| prefix == 32 && (dst == t.ip || t.peer == Some(dst)); + let mut has_unscoped_default = false; + let mut has_ifscope_default = false; + let mut has_explicit_narrower = false; + for &(dst, prefix, ref ifname, is_ifscope) in &entries { + if ifname != &t.name { + continue; + } + if prefix == 0 { + if is_ifscope { + has_ifscope_default = true; + } else { + has_unscoped_default = true; + } + } else if !is_endpoint(dst, prefix) { + has_explicit_narrower = true; + } + } + if has_unscoped_default { continue; } - routes.push((dst, prefix)); + if has_ifscope_default && !has_explicit_narrower { + routes.push(([0, 0, 0, 0], 0)); + } else if !has_explicit_narrower { + if t.point_to_point && (t.prefix == 0 || t.prefix == 32) { + routes.push(([0, 0, 0, 0], 0)); + } else if (1..=31).contains(&t.prefix) { + let net = mask_ipv4(t.ip, t.prefix); + if !is_tunnel_route_skippable(net, t.prefix) { + routes.push((net, t.prefix)); + } + } + } } collapse_cidrs(routes) } -/// Whether `identifier` (and optional extension points blob/text) is a pure -/// packet-tunnel VPN extension whose routes live in the kernel routing table -/// on `utun*`, rather than a transparent proxy, content filter or DNS proxy. -fn is_pure_packet_tunnel_ext(identifier: &str, ext_points_haystack: &[u8]) -> bool { - if identifier.starts_with("io.tailscale.") || identifier.starts_with("com.wireguard.") { - return true; - } - let has_bytes = |needle: &[u8]| ext_points_haystack.windows(needle.len()).any(|w| w == needle); - let has_packet_tunnel = has_bytes(b"com.apple.networkextension.packet-tunnel"); - let has_filter_or_proxy = has_bytes(b"com.apple.networkextension.filter-data") - || has_bytes(b"com.apple.networkextension.filter-packet") - || has_bytes(b"com.apple.networkextension.app-proxy") - || has_bytes(b"com.apple.networkextension.dns-proxy") - || has_bytes(b"com.apple.networkextension.transparent-proxy"); - has_packet_tunnel && !has_filter_or_proxy +/// Whether `identifier` is a split-tunnel/mesh packet-tunnel extension known to +/// coexist cleanly with macOS `vmnet` NAT via standard unscoped kernel subnet +/// routes on `utun*` (Tailscale, WireGuard). All other activated third-party +/// `networkextension` SystemExtensions — including enterprise SASE / VPN +/// `com.apple.networkextension.packet-tunnel` extensions (GlobalProtect, +/// Zscaler, Netskope, Cisco Secure Client, Cloudflare WARP, FortiClient, +/// Jamf Trust, Twingate) whose tunnels use `RTF_IFSCOPE` routes or sub-1500 +/// MTUs that break `vmnet` PMTUD / TLS 1.3 ClientHello (#350, #932) — enable +/// host egress relay. +fn is_pure_packet_tunnel_ext(identifier: &str) -> bool { + identifier.starts_with("io.tailscale.") || identifier.starts_with("com.wireguard.") } fn is_network_ext_category(cat: &str) -> bool { @@ -2035,7 +2138,7 @@ fn has_active_network_extension_xml(xml: &str) -> bool { if !has_net_cat { continue; } - if is_pure_packet_tunnel_ext(id, dict.as_bytes()) { + if is_pure_packet_tunnel_ext(id) { continue; } return true; @@ -2125,7 +2228,6 @@ fn xml_key_string<'a>(dict: &'a str, key: &str) -> Option<&'a str> { #[derive(Debug)] enum BplistObj<'a> { Str(&'a str), - Data(&'a [u8]), Array(Vec), Dict(Vec<(usize, usize)>), Other, @@ -2186,7 +2288,8 @@ fn parse_bplist(buf: &[u8]) -> Option<(usize, Vec>)> { let obj = match kind { 0x4 => { let (len, start) = bplist_len(buf, obj_off + 1, low)?; - BplistObj::Data(buf.get(start..start.checked_add(len)?)?) + let _ = buf.get(start..start.checked_add(len)?)?; + BplistObj::Other } 0x5 => { let (len, start) = bplist_len(buf, obj_off + 1, low)?; @@ -2259,13 +2362,7 @@ fn has_active_network_extension_bplist(buf: &[u8]) -> bool { if !has_net_cat { continue; } - let launchd_data = get_dict_field(pairs, "additionalLaunchdPlistEntries") - .and_then(|didx| match objs.get(didx) { - Some(BplistObj::Data(d)) => Some(*d), - _ => None, - }) - .unwrap_or(&[]); - if is_pure_packet_tunnel_ext(id, launchd_data) { + if is_pure_packet_tunnel_ext(id) { continue; } return true; @@ -2362,6 +2459,86 @@ fn macos_ifname(index: u16) -> Option { Some(unsafe { std::ffi::CStr::from_ptr(ptr) }.to_string_lossy().into_owned()) } +#[cfg(target_os = "macos")] +fn macos_active_ipv4_tunnels() -> Vec { + let mut list: *mut libc::ifaddrs = std::ptr::null_mut(); + // SAFETY: getifaddrs allocates `list`, freed below. + if unsafe { libc::getifaddrs(&mut list) } != 0 { + return Vec::new(); + } + let mut out = Vec::new(); + let mut cur = list; + while !cur.is_null() { + // SAFETY: `cur` is a valid node from `getifaddrs`. + let ifa = unsafe { &*cur }; + cur = ifa.ifa_next; + if ifa.ifa_name.is_null() || ifa.ifa_addr.is_null() { + continue; + } + let flags = ifa.ifa_flags as i32; + if flags & (libc::IFF_UP | libc::IFF_RUNNING) != (libc::IFF_UP | libc::IFF_RUNNING) + || flags & libc::IFF_LOOPBACK != 0 + { + continue; + } + // SAFETY: `ifa_addr` is non-null. + if i32::from(unsafe { (*ifa.ifa_addr).sa_family }) != libc::AF_INET { + continue; + } + // SAFETY: `ifa_name` is NUL-terminated by `getifaddrs`. + let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned(); + if !is_tunnel_iface(&name) { + continue; + } + // SAFETY: `sa_family == AF_INET` guarantees a `sockaddr_in`. + let ip = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); + if !is_routable_tunnel_ipv4(ip) { + continue; + } + let prefix = if !ifa.ifa_netmask.is_null() { + // SAFETY: `ifa_netmask` is non-null; `sa_len` gives its valid byte length. + let sa_len = unsafe { (*ifa.ifa_netmask).sa_len } as usize; + let sa_family = i32::from(unsafe { (*ifa.ifa_netmask).sa_family }); + if sa_family == libc::AF_INET || sa_family == 0 { + let avail = sa_len.saturating_sub(4).min(4); + let mut mask = [0u8; 4]; + if avail > 0 { + // SAFETY: `4 + avail <= sa_len`, within the kernel-allocated sockaddr. + let bytes = unsafe { std::slice::from_raw_parts(ifa.ifa_netmask.cast::(), sa_len) }; + mask[..avail].copy_from_slice(&bytes[4..4 + avail]); + } + u32::from_be_bytes(mask).leading_ones() as u8 + } else { + 32 + } + } else { + 32 + }; + let point_to_point = flags & libc::IFF_POINTOPOINT != 0; + let peer = if point_to_point && !ifa.ifa_dstaddr.is_null() { + // SAFETY: `ifa_dstaddr` is non-null. + let sa_family = i32::from(unsafe { (*ifa.ifa_dstaddr).sa_family }); + let sa_len = unsafe { (*ifa.ifa_dstaddr).sa_len } as usize; + if sa_family == libc::AF_INET && sa_len >= 8 { + // SAFETY: `sa_family == AF_INET` and `sa_len >= 8` guarantees `sin_addr` is readable. + let bytes = unsafe { std::slice::from_raw_parts(ifa.ifa_dstaddr.cast::(), 8) }; + Some([bytes[4], bytes[5], bytes[6], bytes[7]]) + } else { + None + } + } else { + None + }; + let tunnel = ActiveTunnel { name, ip, prefix, peer, point_to_point }; + if !out.contains(&tunnel) { + out.push(tunnel); + } + } + // SAFETY: `list` came from `getifaddrs` and is freed once. + unsafe { libc::freeifaddrs(list) }; + out +} + pub fn current_egress_routes() -> Vec { let env_mode = std::env::var("KIRI_HOST_EGRESS").ok(); #[cfg(target_os = "macos")] @@ -2369,9 +2546,9 @@ pub fn current_egress_routes() -> Vec { let ext = std::fs::read("/Library/SystemExtensions/db.plist") .ok() .is_some_and(|b| has_active_network_extension(&b)); - let routes = dump_macos_route_table() - .map(|b| parse_macos_routes(&b, macos_ifname)) - .unwrap_or_default(); + let active_tunnels = macos_active_ipv4_tunnels(); + let dump = dump_macos_route_table().unwrap_or_default(); + let routes = parse_macos_routes_with_tunnels(&dump, macos_ifname, &active_tunnels); (ext, routes) }; #[cfg(not(target_os = "macos"))] @@ -4793,4 +4970,36 @@ tcp4 0 0 *.53 *.* LISTEN 1 assert_ne!(k1, k2); assert!(k1.starts_with("same-container:") && k2.starts_with("same-container:")); } + + #[test] + fn enterprise_packet_tunnel_and_ifscope_vpn_routes_trigger_host_egress() { + use super::{ActiveTunnel, collapse_cidrs, has_active_network_extension, parse_macos_routes_with_tunnels}; + + // 1. OpenVPN `def1` sibling halves `0.0.0.0/1` + `128.0.0.0/1` collapse to `0.0.0.0/0`. + assert_eq!(collapse_cidrs([([0, 0, 0, 0], 1), ([128, 0, 0, 0], 1)]), vec![([0, 0, 0, 0], 0)]); + + // 2. Enterprise packet-tunnel SystemExtensions (GlobalProtect, Cloudflare WARP, Zscaler) + // enable host egress relay, while Tailscale / WireGuard stay route-driven (#932). + let make_xml = |id: &str| format!( + "extensions\ + identifier{id}\ + stateactivated_enabled\ + categoriescom.apple.system_extension.network_extension\ + additionalLaunchdPlistEntriescom.apple.networkextension.packet-tunnel\ + " + ); + assert!(has_active_network_extension(make_xml("com.paloaltonetworks.GlobalProtect.client.extension").as_bytes())); + assert!(has_active_network_extension(make_xml("com.cloudflare.1dot1dot1dot1.macos.warp.extension").as_bytes())); + assert!(has_active_network_extension(make_xml("com.zscaler.zenith.tunnel").as_bytes())); + assert!(!has_active_network_extension(make_xml("io.tailscale.ipn.macsys.network-extension").as_bytes())); + assert!(!has_active_network_extension(make_xml("com.wireguard.macos.network-extension").as_bytes())); + + // 3. Active IPv4 point-to-point tunnel (`utun7`) with NECP policy routing or `RTF_IFSCOPE` + // default route promotes `0.0.0.0/0`, whereas a split-tunnel with an explicit subnet + // only routes its subnet, and dormant system `utun` without IPv4 contributes nothing. + let p2p = ActiveTunnel { name: "utun7".into(), ip: [10, 66, 0, 2], prefix: 32, peer: Some([10, 66, 0, 1]), point_to_point: true }; + assert_eq!(parse_macos_routes_with_tunnels(&[], |_| None, &[p2p]), vec![([0, 0, 0, 0], 0)]); + let sub = ActiveTunnel { name: "utun8".into(), ip: [100, 64, 1, 5], prefix: 10, peer: None, point_to_point: false }; + assert_eq!(parse_macos_routes_with_tunnels(&[], |_| None, &[sub]), vec![([100, 64, 0, 0], 10)]); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 86a25b8ea..da4faed42 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 +### #932 Networking: return `NODATA` for external `AAAA` queries on IPv4-only networks and relay enterprise macOS VPN tunnels through the host (unreleased) +- Fixes: #932 Containers and the Kubernetes node fail to reach Docker Hub with IPv6 `Network unreachable` and `TLS handshake timeout` under macOS VPN / packet-tunnel extensions +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/daemon/ports.rs`, `crates/kiri-init/src/linux/dns.rs` + ### #938 Windows (WSL 2): bundle `zoneinfo`, self-heal `/etc/localtime`, and prevent bind mounts from creating timezone directories (unreleased) - Fixes: #938 Windows: `/etc/localtime` is a directory in Kiri WSL, breaking common bind mounts - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index ae404f5a5..8578de440 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -356,3 +356,4 @@ crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instea crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs +crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded external AAAA queries returning unreachable IPv6 addresses, and enterprise macOS packet-tunnel / RTF_IFSCOPE VPNs bypassed host egress relay causing TLS handshake timeouts From 3422a34d772ec0903fc2f980157b9aa4b5c2e0b0 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:52:12 +0100 Subject: [PATCH 113/157] UI: show each volume's size asynchronously in Volumes view (#936) (#944) --- crates/kiri-win/src/client.rs | 4 +- crates/kiri-win/src/engine.rs | 41 +++++++++++ crates/kiri/src/daemon/engine.rs | 51 ++++++++++++- crates/kiri/src/daemon/ops.rs | 109 +++++++++++++++++++++++++++ crates/kiri/src/ui/index.html | 52 ++++++++++++- crates/kiri/src/ui/mod.rs | 38 ++++++++++ docs/fix-registry.md | 6 ++ tests/regressions.tsv | 1 + tests/ui/volumes-size.js | 122 +++++++++++++++++++++++++++++++ 9 files changed, 418 insertions(+), 6 deletions(-) create mode 100644 tests/ui/volumes-size.js diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index 76d4fdb5a..2ecc259ae 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -348,9 +348,9 @@ pub fn get_quick(path: &str) -> io::Result { } /// A GET marked as the window's own, which doesn't count as use (as the -/// Mac's `get_background`, for crates/kiri/src/builds.rs). +/// Mac's `get_background`, for crates/kiri/src/builds.rs), bounded by 120 s. pub fn get_background(path: &str) -> io::Result { - let r = request_with("GET", path, None, true)?; + let r = request_within("GET", path, None, true, Some(Duration::from_secs(120)))?; if !r.ok() { return Err(io::Error::other(r.error())); } diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index cfa5d7ff5..7d700aadf 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -1671,6 +1671,9 @@ pub fn on_message(msg: &str) { "storage" => { std::thread::spawn(crate::storage::emit_report); } + "volumesizes" => { + spawn_volume_sizes(); + } "storagepick" => { crate::app::pick_folder(&tr("Choose a storage folder"), |path| { if let Some(p) = path { @@ -1952,6 +1955,44 @@ fn builder_settings(save: Option) { emit(ev.to_string()); } +/// Volumes view: reads each volume's disk usage asynchronously without waking +/// a sleeping VM or touching WSL while stopped. Single-flight with coalesced +/// re-run so repeated UI messages never accumulate background threads. +fn spawn_volume_sizes() { + use std::sync::atomic::{AtomicBool, Ordering}; + static BUSY: AtomicBool = AtomicBool::new(false); + static RERUN: AtomicBool = AtomicBool::new(false); + + if BUSY.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + RERUN.store(true, Ordering::Release); + return; + } + std::thread::spawn(|| { + struct Guard<'a>(&'a AtomicBool); + impl Drop for Guard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } + } + let _guard = Guard(&BUSY); + loop { + RERUN.store(false, Ordering::Release); + let sizes = if crate::serve::is_stopped() { + json!({}) + } else { + client::get_background("/kiri/volumes/sizes") + .ok() + .and_then(|v| v.get("sizes").filter(|s| s.is_object()).cloned()) + .unwrap_or_else(|| json!({})) + }; + emit(json!({"type": "volumesizes", "sizes": sizes}).to_string()); + if !RERUN.swap(false, Ordering::AcqRel) { + break; + } + } + }); +} + /// The tray's commands. pub fn on_tray(cmd: &str) { match cmd { diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 9f765ba60..431bd6ee8 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -1735,6 +1735,17 @@ pub struct Engine { image_labels: Mutex>, /// The running VM's uplink status for `/info` and `kiri diag report` (#435). uplink: Mutex, + /// Short-lived cache of guest-measured volume sizes (`GET /kiri/volumes/sizes`), + /// invalidated on volume create/remove and container remove while leaving + /// `GET /system/df` live. + volume_sizes_cache: Mutex, +} + +#[derive(Default)] +struct VolumeSizesCache { + generation: u64, + measured_at: Option, + sizes: HashMap, } /// k3s's pod and service ranges, which `kiri k8s` leaves at their defaults. @@ -1869,6 +1880,7 @@ impl Engine { k8s_fwd: Mutex::new(HashMap::new()), image_labels: Mutex::new(HashMap::new()), uplink: Mutex::new(serde_json::Value::Null), + volume_sizes_cache: Mutex::default(), }); let _ = engine.me.set(Arc::downgrade(&engine)); engine.start_syncer(); @@ -2734,11 +2746,44 @@ impl Engine { } /// The VM's link while it runs, without waking it. - #[cfg(target_os = "macos")] pub fn awake_link(&self) -> Option> { self.awake() } + /// Cached guest volume disk usage if younger than `ttl`, plus the cache + /// generation so an in-flight measurement does not overwrite an invalidation. + pub(super) fn volume_sizes_cached(&self, ttl: Duration) -> (u64, Option>) { + let c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + let hit = c.measured_at.is_some_and(|at| at.elapsed() < ttl).then(|| c.sizes.clone()); + (c.generation, hit) + } + + /// Stores freshly measured volume sizes. When `expected_gen` is `Some(g)`, + /// skips writing if the cache was invalidated since generation `g`. + pub(super) fn cache_volume_sizes(&self, expected_gen: Option, sizes: HashMap) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + if expected_gen.is_some_and(|g| g != c.generation) { + return; + } + c.measured_at = Some(std::time::Instant::now()); + c.sizes = sizes; + } + + /// Drops cached volume sizes and advances the generation counter. + pub(super) fn invalidate_volume_sizes(&self) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + c.sizes.clear(); + } + + #[cfg(test)] + pub(super) fn set_volume_sizes_cache_at(&self, at: std::time::Instant, sizes: HashMap) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + c.measured_at = Some(at); + c.sizes = sizes; + } + /// Queries `(in_use, capacity)` of the guest data disk while the VM is /// awake without waking a sleeping VM. #[cfg(target_os = "macos")] @@ -5750,6 +5795,7 @@ impl Engine { self.delete_volume_data(&v); } } + self.invalidate_volume_sizes(); Ok(()) } @@ -5763,6 +5809,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure(name, labels, anonymous).map_err(Error::BadRequest)?; if new { + self.invalidate_volume_sizes(); self.emit_volume("create", name); } Ok(v) @@ -5774,6 +5821,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure_with(name, labels, false, options).map_err(Error::BadRequest)?; if new { + self.invalidate_volume_sizes(); self.emit_volume("create", name); } Ok(v) @@ -5838,6 +5886,7 @@ impl Engine { fn forget_volume(&self, name: &str) -> bool { let forgot = self.lock_volumes().forget(name); if forgot { + self.invalidate_volume_sizes(); self.emit_volume("destroy", name); } forgot diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index 39bc5c22d..6d2e92c9c 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -27,6 +27,7 @@ pub fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixS Some(match (m, p) { ("GET", "/events") => events(req, engine, w), ("GET", "/system/df") => reply(w, system_df(engine), 200), + ("GET", "/kiri/volumes/sizes") => reply(w, volume_sizes(engine), 200), ("POST", "/containers/prune") => reply(w, container_prune(req, engine), 200), ("POST", "/images/prune") => reply(w, image_prune(req, engine), 200), ("GET", "/images/search") => reply(w, search(req), 200), @@ -473,6 +474,9 @@ fn system_df(engine: &Engine) -> Result { let used: Vec = engine.each(|c| Some(c.spec.image_id.clone())); let measured = engine.vm().ok().and_then(|vm| vm.usage(std::time::Duration::from_secs(120))); let du = measured.as_deref().map(DiskUsage::parse); + if let Some(d) = &du { + engine.cache_volume_sizes(None, d.volumes.clone()); + } let layer_size = |l: &kiri_image::Layer| du.as_ref().and_then(|d| d.layers.get(l.digest.trim_start_matches("sha256:")).copied()).unwrap_or(l.size); // How many images use each layer, for each image's shared size. let mut users: HashMap<&str, usize> = HashMap::new(); @@ -549,6 +553,54 @@ fn system_df(engine: &Engine) -> Result { Ok(json!({"LayersSize": layers_size, "Images": image_rows, "Containers": containers, "Volumes": volumes, "BuildCache": super::builder::cache(engine)})) } +/// How long `GET /kiri/volumes/sizes` reuses guest-measured volume sizes so +/// tab switches do not re-walk the guest disk (`GET /system/df` stays live). +const VOLUME_SIZES_TTL: Duration = Duration::from_secs(30); + +fn volume_sizes_map(volumes: &[super::volumes::Volume], du: &HashMap) -> serde_json::Map { + let mut out = serde_json::Map::with_capacity(volumes.len()); + for v in volumes { + let size = match du.get(&v.name) { + Some(&b) => i64::try_from(b).unwrap_or(i64::MAX), + // A plain local volume never mounted yet has no directory in the + // guest and takes 0 bytes; one backed by driver options (NFS/bind/ + // tmpfs) is not measured on the guest data disk. + None if v.options.is_empty() => 0, + None => -1, + }; + out.insert(v.name.clone(), json!(size)); + } + out +} + +/// Each volume's size in bytes for the Volumes view (`GET /kiri/volumes/sizes`). +/// Uses a short cache invalidated on volume/container changes and never wakes +/// a sleeping or stopped VM. +fn volume_sizes(engine: &Engine) -> Result { + volume_sizes_with_ttl(engine, VOLUME_SIZES_TTL) +} + +fn volume_sizes_with_ttl(engine: &Engine, ttl: Duration) -> Result { + let volumes = engine.volume_list(); + if volumes.is_empty() { + return Ok(json!({"sizes": {}})); + } + let (generation, cached) = engine.volume_sizes_cached(ttl); + if let Some(du) = cached { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &du)})); + } + let Some(vm) = engine.awake_link() else { + return Ok(json!({"sizes": {}})); + }; + let Some(measured) = vm.usage(Duration::from_secs(120)) else { + return Ok(json!({"sizes": {}})); + }; + let du = DiskUsage::parse(&measured); + engine.cache_volume_sizes(Some(generation), du.volumes.clone()); + let current = engine.volume_list(); + Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes)})) +} + /// `docker history`: the config's history, newest first, with each /// layer-making step's size. fn history(engine: &Engine, name: &str) -> Result { @@ -806,6 +858,63 @@ mod disk_usage_tests { assert_eq!(du.volumes.get("data"), Some(&12288)); assert_eq!((du.layers.len(), du.containers.len(), du.volumes.len()), (1, 1, 1)); } + + #[test] + fn volume_sizes_never_wakes_asleep_vm_and_honors_cache_and_invalidation() { + use serde_json::json; + use std::collections::{BTreeMap, HashMap}; + use std::time::{Duration, Instant}; + + let root = std::env::temp_dir().join(format!("kiri-vol-sizes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + + engine.volume_ensure("pg_data", json!({}), false).unwrap(); + engine.volume_ensure("empty_vol", json!({}), false).unwrap(); + let mut nfs_opts = BTreeMap::new(); + nfs_opts.insert("type".into(), "nfs".into()); + nfs_opts.insert("device".into(), ":/export".into()); + engine.volume_ensure_with("nfs_vol", json!({}), nfs_opts).unwrap(); + + // With no awake VM and an empty cache, returns {} without attempting to boot a VM. + let unmeasured = super::volume_sizes(&engine).unwrap(); + assert_eq!(unmeasured, json!({"sizes": {}})); + assert!(!engine.is_awake()); + + // Populate cache as if an awake measurement just completed. + let mut measured = HashMap::new(); + measured.insert("pg_data".into(), 807_700_000u64); + let (gen_before, _) = engine.volume_sizes_cached(Duration::from_secs(30)); + engine.cache_volume_sizes(Some(gen_before), measured.clone()); + + let hit = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); + assert_eq!(hit, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); + + // Stale cache entry (> TTL) misses and still does not wake the VM. + engine.set_volume_sizes_cache_at(Instant::now() - Duration::from_secs(31), measured.clone()); + let expired = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); + assert_eq!(expired, json!({"sizes": {}})); + + // Creating a new volume invalidates the cache and bumps generation so + // an in-flight measurement from before creation cannot repopulate it. + engine.cache_volume_sizes(None, measured.clone()); + let (old_gen, cached) = engine.volume_sizes_cached(Duration::from_secs(30)); + assert!(cached.is_some()); + engine.volume_ensure("new_vol", json!({}), false).unwrap(); + assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none()); + engine.cache_volume_sizes(Some(old_gen), measured.clone()); + assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none(), "stale generation write ignored"); + + // Removing a volume also invalidates the cache. + engine.cache_volume_sizes(None, measured); + assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_some()); + engine.volume_remove("new_vol", false).unwrap(); + assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none()); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } } #[cfg(test)] diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 940b9bf1e..9b40ad076 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -2804,7 +2804,7 @@

Containers

({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); -const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, storage: null, stErr: "", stReclaiming: false, stReclaimed: null, stPruning: false, stPruned: null, bset: null, bsetDraft: null, vmnet: null, shellPath: null, shellPathBusy: false, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, +const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], volSizes: {}, volSizesLoading: false, volSizesAt: 0, volSizesKey: "", volSizesInFlight: 0, networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, storage: null, stErr: "", stReclaiming: false, stReclaimed: null, stPruning: false, stPruned: null, bset: null, bsetDraft: null, vmnet: null, shellPath: null, shellPathBusy: false, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, imp: { sources: null, source: null, inv: null, picked: { images: new Set(), volumes: new Set(), containers: new Set() }, steps: {}, running: false, summary: "" }, upd: null, engineStale: null, staleHidden: false, // The Builds view: the list, the picked build and its detail, and how its steps show. @@ -4982,6 +4982,7 @@

${tr("Storage location unavailable")}

needClose(); ui.view = view; ui.filter = ""; $("gq").value = ""; if (view === "builds") send("builds"); + if (view === "volumes") requestVolumeSizes(); if (view === "compose") { cmp.open = null; cmp.asked = 0; cmpAsk(); } if (view === "usb") usbPoll(); if (view === "share") { send("shares"); send("shareusage"); shPoll(); } @@ -6508,13 +6509,47 @@

${tr("Ports for {name}", { name: esc(name) })}

${d.tab === "security" ? scanView(i, { own: tr("this image") }) : layersView(d.layers, null, { own: tr("Added in this image"), base: tr("From its base image") })}`; } +const VOL_SIZES_TTL = 30000; +function volumeListKey() { + return kept("volumes").map((v) => v.Name).sort().join("\0"); +} +function requestVolumeSizes(force = false) { + if (ui.vm === "stopped" || !kept("volumes").length) return; + const key = volumeListKey(); + const changed = key !== ui.volSizesKey; + const stale = !ui.volSizesAt || Date.now() - ui.volSizesAt >= VOL_SIZES_TTL; + if (!force && !changed && !stale) return; + if (ui.volSizesLoading && !changed && !force) return; + ui.volSizesKey = key; + ui.volSizesInFlight++; + ui.volSizesLoading = true; + send("volumesizes"); +} +function volumeSizeOf(v) { + if (Object.prototype.hasOwnProperty.call(ui.volSizes, v.Name)) return ui.volSizes[v.Name]; + if (typeof v.UsageData?.Size === "number") return v.UsageData.Size; + return null; +} +function volumeSizeCell(v) { + const s = volumeSizeOf(v); + if (typeof s === "number" && Number.isFinite(s) && s >= 0) return `${esc(size(s))}`; + if (ui.volSizesLoading && s === null) return '…'; + return '—'; +} +const VOLUME_SORT = { + name: (v) => v.Name || "", + driver: (v) => v.Driver || "", + size: (v) => { const s = volumeSizeOf(v); return typeof s === "number" && Number.isFinite(s) && s >= 0 ? s : -1; }, + created: (v) => (v.CreatedAt ? Date.parse(v.CreatedAt) || 0 : 0), +}; function renderVolumes() { - const items = listed("volumes"); + const items = sortBy(listed("volumes"), "volumes", VOLUME_SORT); if (!kept("volumes").length) return renderEmpty("volumes"); if (!items.length) return noMatch(); - table([[tr("Name")], [tr("Driver")], [tr("Created")]], items.map((v) => ` + table([[tr("Name"), "", "name"], [tr("Driver"), "", "driver"], [tr("Size"), "r", "size"], [tr("Created"), "", "created"]], items.map((v) => ` ${pickCell("volumes", v)}
${tile(null, "database")}${esc(v.Name.length > 40 ? short(v.Name) : v.Name)}
${esc(v.Driver)} + ${volumeSizeCell(v)} ${v.CreatedAt ? ago(Date.parse(v.CreatedAt) / 1000) : ""}
${ibtn("trash", tr("Remove"), `data-rmvol="${esc(v.Name)}"`, "danger")}
`), "volumes"); } @@ -7372,6 +7407,8 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) if (ui.view === "settings" && prefs.tab === "resources") render(); // Asleep, the VM holds no memory and the vm event says so (0 MB); off, there's nothing to read. if (state === "stopped" || state === "stopping") ["vm-mem"].forEach((id) => ($(id).textContent = "—")), ($("vm-meter").style.width = "0"); + if (state === "stopped") { ui.volSizesInFlight = 0; ui.volSizesLoading = false; ui.volSizesAt = 0; } + if (state === "running" && was !== "running") { ui.volSizesAt = 0; if (ui.view === "volumes") { requestVolumeSizes(); render(); } } if (state === "stopped" || was === "stopped") render(); } if (error) toast("error", error); @@ -8461,6 +8498,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r // rest of the builder (its image, its cache volume) in Images and Volumes. ui.containers = (e.containers || []).filter((c) => !c.Labels?.["io.kiri.probe"] && !isBuildWorker(c)); oomCheck(); starCheck(); ui.builderImage = (e.images || []).find(isBuilderImage) || null; ui.builderVolume = (e.volumes || []).find(isBuilderVolume) || null; ui.images = (e.images || []).filter((i) => !isBuilderImage(i)); ui.volumes = (e.volumes || []).filter((v) => !isBuilderVolume(v)); ui.networks = e.networks || []; + if (!kept("volumes").length) { ui.volSizes = {}; ui.volSizesKey = ""; ui.volSizesAt = 0; ui.volSizesInFlight = 0; ui.volSizesLoading = false; } + else if (ui.view === "volumes") requestVolumeSizes(); shPublished(); ctrActed(); groupActed(); fixWatch(); if (ui.view === "compose") cmpAsk(); @@ -8468,6 +8507,13 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r paintEngine(); if (ui.openAfter && ui.containers.some((c) => c.Id === ui.openAfter)) { openDetail(ui.openAfter); ui.openAfter = null; openedTab(); } break; + case "volumesizes": + ui.volSizes = e.sizes && typeof e.sizes === "object" ? e.sizes : {}; + ui.volSizesInFlight = Math.max(0, ui.volSizesInFlight - 1); + ui.volSizesLoading = ui.volSizesInFlight > 0; + ui.volSizesAt = Date.now(); + if (ui.view === "volumes") render(); + break; case "pull": pullEvent(e); break; case "composeprojects": case "composefile": case "composeplan": case "composelogs": case "composeapply": case "composeopened": case "composerestored": case "composeaction": cmpEvent(e); break; case "usb": usbList(e); break; diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index fb5c74452..bd38f783a 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -744,6 +744,40 @@ fn storage_status() { } } +/// Volumes view: reads each volume's disk usage asynchronously without waking +/// a sleeping VM or blocking `refresh()`. Single-flight with coalesced re-run +/// so repeated UI messages never accumulate background threads. +fn spawn_volume_sizes() { + use std::sync::atomic::{AtomicBool, Ordering}; + static BUSY: AtomicBool = AtomicBool::new(false); + static RERUN: AtomicBool = AtomicBool::new(false); + + if BUSY.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + RERUN.store(true, Ordering::Release); + return; + } + std::thread::spawn(|| { + struct Guard<'a>(&'a AtomicBool); + impl Drop for Guard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } + } + let _guard = Guard(&BUSY); + loop { + RERUN.store(false, Ordering::Release); + let sizes = client::get_background("/kiri/volumes/sizes") + .ok() + .and_then(|v| v.get("sizes").filter(|s| s.is_object()).cloned()) + .unwrap_or_else(|| serde_json::json!({})); + emit(serde_json::json!({"type": "volumesizes", "sizes": sizes}).to_string()); + if !RERUN.swap(false, Ordering::AcqRel) { + break; + } + } + }); +} + /// Validates a proposed storage folder and emits `storagecheck` to the page. fn storage_check(path: Option, fresh: bool, reset: bool) { let mut body = serde_json::json!({"fresh": fresh}); @@ -2576,6 +2610,10 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { std::thread::spawn(storage_status); Ok(()) } + "volumesizes" => { + spawn_volume_sizes(); + Ok(()) + } "storagepick" => { window::pick_folder(&tr("Choose a storage folder"), |path| { if let Some(p) = path { diff --git a/docs/fix-registry.md b/docs/fix-registry.md index da4faed42..088b94acd 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 +### #936 Volumes view: show each volume's disk size loaded asynchronously with daemon caching (unreleased) +- Fixes: #936 Volumes view: show each volume's size, loaded asynchronously +- Caused: none known +- Caused by: - +- Check: `tests/ui/volumes-size.js`, `crates/kiri/src/daemon/ops.rs` + ### #932 Networking: return `NODATA` for external `AAAA` queries on IPv4-only networks and relay enterprise macOS VPN tunnels through the host (unreleased) - Fixes: #932 Containers and the Kubernetes node fail to reach Docker Hub with IPv6 `Network unreachable` and `TLS handshake timeout` under macOS VPN / packet-tunnel extensions - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 8578de440..4da0fc635 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -357,3 +357,4 @@ crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v / crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded external AAAA queries returning unreachable IPv6 addresses, and enterprise macOS packet-tunnel / RTF_IFSCOPE VPNs bypassed host egress relay causing TLS handshake timeouts +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 diff --git a/tests/ui/volumes-size.js b/tests/ui/volumes-size.js new file mode 100644 index 000000000..6cbdf362d --- /dev/null +++ b/tests/ui/volumes-size.js @@ -0,0 +1,122 @@ +// Volumes view: asynchronous Size column loading, formatting, unmeasured +// fallback, cache reuse across view switches, and refresh on volume changes. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, what) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(`${what}: got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`); }; + +const vol = (name, secsAgo = 3600) => ({ + Name: name, + Driver: "local", + CreatedAt: new Date(Date.now() - secsAgo * 1000).toISOString(), + Labels: {}, +}); +const baseVolumes = [vol("empty_vol", 7200), vol("pg_data", 3600), vol("big_cache", 1800), vol("nfs_mount", 900)]; +const sendLists = (volumes) => kiri.on({ type: "lists", containers: ui.containers, images: ui.images, volumes, networks: ui.networks }); +const volSizeCount = () => sent.filter((m) => m.type === "volumesizes").length; +const sizeText = (name) => { + const row = document.querySelector(`#content tr[data-key="${name}"]`); + if (!row) throw new Error(`missing row ${name}`); + return row.cells[3].textContent.trim(); +}; + +sent.length = 0; +sendLists(baseVolumes); + +t("opening Volumes renders all rows immediately with … and requests volumesizes", () => { + eq(volSizeCount(), 0, "no request before visiting Volumes"); + show("volumes"); + const heads = [...document.querySelectorAll("#content thead th")].map((th) => th.textContent.replace(/[↑↓]/g, "").trim()).filter(Boolean); + eq(heads, ["Name", "Driver", "Size", "Created", "Actions"], "table headers"); + eq(volSizeCount(), 1, "requested volumesizes once"); + for (const v of baseVolumes) { + const cell = document.querySelector(`#content tr[data-key="${v.Name}"]`).cells[3]; + if (!cell.classList.contains("muted") || !cell.classList.contains("num")) { + throw new Error(`Size cell for ${v.Name} missing muted/num classes: ${cell.className}`); + } + eq(cell.textContent.trim(), "…", `loading indicator for ${v.Name}`); + } +}); + +t("delivering volumesizes updates each row asynchronously with formatted bytes and — for -1", () => { + kiri.on({ + type: "volumesizes", + sizes: { + empty_vol: 0, + pg_data: 807_700_000, + big_cache: 3_200_000_000, + nfs_mount: -1, + }, + }); + eq(ui.volSizesLoading, false, "loading cleared"); + eq(sizeText("empty_vol"), "0 B", "empty_vol"); + eq(sizeText("pg_data"), "807.7 MB", "pg_data"); + eq(sizeText("big_cache"), "3.2 GB", "big_cache"); + eq(sizeText("nfs_mount"), "—", "nfs_mount unmeasured"); +}); + +t("Size column sorts by measured bytes", () => { + const th = document.querySelector('#content thead th[data-sort="size"]'); + if (!th) throw new Error("missing sortable Size header"); + th.click(); + const desc = [...document.querySelectorAll("#content tbody tr")].map((r) => r.dataset.key); + eq(desc, ["big_cache", "pg_data", "empty_vol", "nfs_mount"], "descending by size"); + document.querySelector('#content thead th[data-sort="size"]').click(); + const asc = [...document.querySelectorAll("#content tbody tr")].map((r) => r.dataset.key); + eq(asc, ["nfs_mount", "empty_vol", "pg_data", "big_cache"], "ascending by size"); +}); + +t("switching away and back within the cache window keeps sizes without re-requesting", () => { + const before = volSizeCount(); + show("images"); + show("volumes"); + eq(volSizeCount(), before, "cache hit on view switch"); + eq(sizeText("empty_vol"), "0 B", "empty_vol preserved"); + eq(sizeText("pg_data"), "807.7 MB", "pg_data preserved"); + eq(sizeText("big_cache"), "3.2 GB", "big_cache preserved"); + eq(sizeText("nfs_mount"), "—", "nfs_mount preserved"); +}); + +t("periodic lists refresh with unchanged volumes does not spam volumesizes", () => { + const before = volSizeCount(); + sendLists(baseVolumes); + eq(volSizeCount(), before, "unchanged volume list stays cached"); + eq(sizeText("pg_data"), "807.7 MB", "pg_data unchanged"); +}); + +t("adding a new volume requests fresh sizes while keeping existing sizes visible", () => { + const before = volSizeCount(); + const next = [...baseVolumes, vol("fresh_vol", 10)]; + sendLists(next); + eq(volSizeCount(), before + 1, "new volume triggers volumesizes"); + eq(sizeText("pg_data"), "807.7 MB", "existing volume not blanked"); + eq(sizeText("big_cache"), "3.2 GB", "existing volume not blanked"); + eq(sizeText("fresh_vol"), "…", "new volume shows loading indicator"); + kiri.on({ + type: "volumesizes", + sizes: { + empty_vol: 0, + pg_data: 807_700_000, + big_cache: 3_200_000_000, + nfs_mount: -1, + fresh_vol: 1_500_000, + }, + }); + eq(sizeText("fresh_vol"), "1.5 MB", "new volume size applied"); +}); + +t("unmeasured response shows — and waking the VM re-requests sizes", () => { + kiri.on({ type: "state", state: "asleep" }); + ui.volSizesAt = 0; + const beforeAsleep = volSizeCount(); + show("volumes"); + eq(volSizeCount(), beforeAsleep + 1, "expired cache requests sizes"); + kiri.on({ type: "volumesizes", sizes: {} }); + eq(ui.volSizesLoading, false, "loading cleared after empty response"); + eq(sizeText("pg_data"), "—", "unmeasured while asleep"); + const beforeWake = volSizeCount(); + kiri.on({ type: "state", state: "running" }); + eq(volSizeCount(), beforeWake + 1, "VM wake triggers fresh volumesizes"); + eq(sizeText("pg_data"), "…", "shows loading while fetching after wake"); +}); + +report(R); From d81e51cbffc303504ceed8f3c28475aeee2c4b88 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:13:52 +0100 Subject: [PATCH 114/157] Tests: join multi-container cgroupns inspect output and allocate free loop nodes (#413, #934) (#945) --- tests/e2e.sh | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tests/e2e.sh b/tests/e2e.sh index ccae589da..d744ed956 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -474,7 +474,7 @@ $D rm -f cgns-d cgns-p cgns-h cgns-sd >/dev/null 2>&1 $D create --name cgns-d alpine true >/dev/null $D create --name cgns-p --cgroupns private alpine true >/dev/null $D create --name cgns-h --cgroupns host alpine true >/dev/null -t cgroupns-mode-inspect "private private host" $D inspect -f '{{.HostConfig.CgroupnsMode}}' cgns-d cgns-p cgns-h +t cgroupns-mode-inspect "private private host" bash -c "$D inspect -f '{{.HostConfig.CgroupnsMode}}' cgns-d cgns-p cgns-h | paste -sd' ' -" $D rm -f cgns-d cgns-p cgns-h >/dev/null 2>&1 t cgroupns-mode-invalid "invalid cgroup namespace mode: bogus" curl -s --unix-socket "$SOCK" -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["true"],"HostConfig":{"CgroupnsMode":"bogus"}}' http://d/v1.47/containers/create t cgroupns-private-default "0::/" $D run --rm alpine cat /proc/1/cgroup @@ -1667,23 +1667,25 @@ bu = sx(-100, b\"/upper.lock\", 0) print(\"btime-ok\" if b1 == b2 == b3 and b1[:3] == (0, (0, 0), (1700000000, 0)) and bu[:3] == (0, (0, 0), (1700000001, 0)) else (b1, b2, b3, bu))'); $D rmi kiri-test/btime:1 >/dev/null 2>&1; echo \"\$out\"" # Guest kernel supports ext2/ext3 (via ext4) and FAT/vfat for loop-mounted boot # and EFI/SD-card disk images (#934). -only mac t guest-kernel-ext2-vfat "fs=ext2,ext3,ext4,vfat ext2=hello-ext2 vfat=hello-vfat" bash -c "$D run --rm --privileged alpine:3.20 sh -c ' +only mac t guest-kernel-ext2-vfat "fs=ext2,ext3,ext4,vfat ext2=hello-ext2 vfat=hello-vfat" bash -c "$D run --rm --privileged alpine sh -c ' set -e fs=\$(awk \"{print \\\$NF}\" /proc/filesystems | grep -xE \"ext2|ext3|ext4|vfat\" | sort -u | paste -sd, -) - apk add -q --no-cache e2fsprogs dosfstools + apk add -q --no-cache e2fsprogs dosfstools util-linux dd if=/dev/zero of=/tmp/e2.img bs=1M count=4 status=none mkfs.ext2 -q -F /tmp/e2.img mkdir -p /mnt/e2 /mnt/vf - mount -t ext2 -o loop /tmp/e2.img /mnt/e2 + l1=\$(losetup -f --show /tmp/e2.img) + mount -t ext2 \"\$l1\" /mnt/e2 echo hello-ext2 > /mnt/e2/ok e2=\$(cat /mnt/e2/ok) - umount /mnt/e2 + umount /mnt/e2 && losetup -d \"\$l1\" dd if=/dev/zero of=/tmp/vf.img bs=1M count=4 status=none mkfs.vfat /tmp/vf.img >/dev/null - mount -t vfat -o loop /tmp/vf.img /mnt/vf + l2=\$(losetup -f --show /tmp/vf.img) + mount -t vfat \"\$l2\" /mnt/vf echo hello-vfat > /mnt/vf/ok vf=\$(cat /mnt/vf/ok) - umount /mnt/vf + umount /mnt/vf && losetup -d \"\$l2\" echo \"fs=\$fs ext2=\$e2 vfat=\$vf\" '" # Images of 59 to 125 layers start, with their top and lowest layers in the From 7a03a6be24eb388e1abb0451589f1d90c72f0210 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:43:35 +0100 Subject: [PATCH 115/157] Docs: add Simplified Chinese README (README.zh-CN.md) (#933) (#947) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 陈 --- README.md | 3 +- README.zh-CN.md | 351 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+), 1 deletion(-) create mode 100644 README.zh-CN.md diff --git a/README.md b/README.md index 334940e5b..e3f450017 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,8 @@ Docs · Features · Download · - Security + Security · + 简体中文

diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 000000000..7ff6280fc --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,351 @@ +
+ +

+ + + Kiri + +

+ +

Kiri:小巧、极速的 macOS / Windows / Linux 容器运行时

+ +

Docker Desktop 启动慢、空闲时占用资源多。Kiri 是用 Rust 编写的轻量级替代品。它能运行你的 Docker 镜像,并且兼容你已经在用的 docker CLI、Compose 和 buildx。

+ +

+ CI 状态 + 最新版本 + Apache 2.0 许可证 + Discord + 38 种语言 +

+ +

+ + 快速上手 · + 文档 · + 功能特性 · + 下载 · + 安全 · + English + +

+ +

+ Kiri 窗口:容器按 Compose 项目分组,显示状态、端口、本地域名和大小 +

+ +
+ +--- + +> 本文档是 [README.md](README.md) 的中文翻译。若两者内容有出入,以英文原版为准。 + +## 开始之前 + +请确认你的系统满足以下条件之一: + +- macOS 14 或更高版本,Apple 芯片或 Intel 均可 +- Windows 10 或 11,启用 WSL 2,x86-64 或 Arm 均可 +- Linux(Ubuntu、Fedora 等) + +## 第一步:安装并启动 Kiri + +macOS 上使用 Homebrew: + +```bash +brew install --cask libracoder/kiri/kiri +``` + +或下载对应系统的安装包: + +| 平台 | 获取方式 | +|------|----------| +| macOS 14+(Apple 芯片或 Intel) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.dmg`,或执行 `brew install --cask libracoder/kiri/kiri` | +| Windows 10 和 11(x86-64 或 Arm,通过 WSL 2) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.msi` | +| Linux(Ubuntu、Fedora 等) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.deb` 或 `.rpm` | + +首次打开 Kiri 时,它会自动配置一个 `kiri` Docker context。Kiri 会自动更新,并在更新前校验每个新版本的签名。 + +然后运行你的第一个容器: + +```bash +docker --context kiri run --rm alpine echo hello +``` + +--- + +## 目录 + +- [开始之前](#开始之前) +- [安装并启动 Kiri](#第一步安装并启动-kiri) +- [为什么选择 Kiri?](#为什么选择-kiri) +- [快速上手](#快速上手) +- [功能特性](#功能特性) +- [Docker 命令](#docker-命令) +- [基准测试](#基准测试) +- [对比](#对比) +- [Kiri 工作原理](#kiri-工作原理) +- [文档](#文档) +- [路线图](#路线图) +- [社区](#社区) +- [安全](#安全) +- [许可证](#许可证) + +--- + +## 为什么选择 Kiri? + +Kiri 在一个小型 Linux 虚拟机中运行容器(在 Linux 上则直接运行于内核之上),并实现了 Docker Engine API,因此你现有的工具可以直接使用。名字来源于伊博语单词 *ntakịrị*,意为"小"。 + +- **快**:通过 Docker API 启动并退出一个容器约需 2.5 毫秒,比 Docker Desktop 快约 80 倍。 +- **轻**:虚拟机空闲 60 秒后自动休眠,守护进程常驻内存约 15 MB,唤醒仅需约 0.15 秒。 +- **兼容**:支持 `docker`、Compose、buildx、`docker login`,在 Apple 芯片上可通过 Rosetta 运行 amd64 镜像。 +- **本地域名**:`http://.kiri.local`,并由 Kiri 自带的证书颁发机构提供 HTTPS。 +- **不止容器**:一条命令启动 Kubernetes 集群,还能创建 Linux 虚拟机。 +- **原生窗口**:管理容器、镜像、卷和网络,另有菜单栏图标。 +- **你的语言**:窗口支持 38 种语言,macOS、Windows 和 Linux 一致。 + +--- + +## 快速上手 + +```sh +docker --context kiri run --rm alpine echo hello +docker --context kiri compose up -d +kiri k8s start # 单节点 Kubernetes,作为 `kiri` kubectl context +kiri machine create dev --distro ubuntu && kiri machine shell dev +kiri import # 从 OrbStack 或 Docker Desktop 迁移镜像、卷和容器 +``` + +Docker 的命令同样可以作为 `kiri` 命令使用(`kiri run`、`kiri ps`、`kiri compose up` 等),并且始终指向 Kiri。 + +--- + +## 功能特性 + +| 领域 | 提供的能力 | +|------|------------| +| **容器** | 完整生命周期:`run`、`exec`、`logs`、`attach`、`stop`、`kill`、`restart`、`pause`、`update`、`stats`、`top`、`diff`、`export`、`commit`,以及双向 `cp`。守护进程重启后记录仍然保留。 | +| **资源限制与安全** | `--memory`、`--cpus`、`--pids-limit`、`--shm-size`。Docker 默认 capabilities 和默认 seccomp 过滤器,支持 `--cap-add`/`--cap-drop`、`--privileged`、`--read-only`、`no-new-privileges`。 | +| **网络** | 默认 bridge、按名称和别名 DNS 解析的自定义网络、TCP/UDP 的 `-p`/`-P`、`--network host\|none\|container:`、IPAM(`--subnet`、`--gateway`、`--ip`)、IPv6、`host.docker.internal`。 | +| **本地域名** | 每个容器都有 `http://.kiri.local`,Compose 服务为 `..kiri.local`,并由 Kiri 自带的证书颁发机构提供 HTTPS。 | +| **存储** | 具名和匿名卷、宿主机路径绑定挂载、`--tmpfs`、`--mount`。 | +| **镜像** | `pull`、`push`、`tag`、`save`、`load`、`history`、`search`,支持 `docker login` 凭据。Apple 芯片上通过 Rosetta 运行 amd64 镜像。 | +| **构建** | 通过 BuildKit 支持 `docker build` 和 `buildx build`,空闲时自动停止。 | +| **Compose** | `up`、`down`、`ps`、`logs`、`exec`、多网络、事件。项目在窗口中分组显示。 | +| **Kubernetes** | `kiri k8s start`:单节点 k3s 集群,约 20 秒就绪,作为 `kiri` kubectl context。LoadBalancer 服务发布在 `localhost` 上。 | +| **Linux 虚拟机** | `kiri machine create dev --distro ubuntu`:你的用户、sudo 和相同路径的家目录,可选 systemd。 | +| **分享** | `kiri share 3000` 将本地端口或容器发布到互联网。 | +| **USB 设备(beta)** | 将串口适配器、Zigbee 棒或开发板交给容器使用。 | +| **内存** | balloon 在运行时归还空闲内存,虚拟机空闲 60 秒后休眠。 | +| **窗口** | 容器、镜像、卷和网络,每个容器都有实时日志、命令行和文件浏览。菜单栏图标显示运行状态。 | +| **导入** | `kiri import` 从 OrbStack 或 Docker Desktop 迁移镜像、卷和容器。 | +| **更新** | Kiri 自动更新,更新前校验每个版本的 SHA-256 和签名。 | + +所有参数和已知问题见 **[docs/features.md](docs/features.md)**。 + +--- + +## Docker 命令 + +Kiri 实现了 Docker Engine API,你现有的 `docker` CLI 可以直接对接。只需切换一次 context,其余什么都不用改: + +```bash +docker context use kiri +``` + +| 领域 | 可用命令 | +|------|----------| +| 容器 | `run` `create` `start` `stop` `kill` `restart` `rm` `exec` `logs` `attach` `wait` `rename` `pause` `unpause` `update` `stats` `top` `diff` `export` `commit` `cp` `ps` `inspect` `container prune` | +| 镜像 | `pull` `push` `tag` `images` `rmi` `save` `load` `history` `search` `login` `image prune` | +| 构建 | `build` `buildx build` | +| 网络 | `network create` `ls` `rm` `inspect` `connect` `disconnect` | +| 卷 | `volume create` `ls` `rm` `inspect` `prune` | +| Compose | `compose up` `down` `ps` `logs` `exec` | +| 系统 | `system df` `events` `info` `version` | + +同样的命令也可以作为 `kiri` 命令使用,并且始终指向 Kiri: + +```bash +kiri run -d --name web -p 8080:80 nginx # 然后打开 http://web.kiri.local +kiri ps +kiri logs -f web +kiri exec -it web sh +kiri compose up -d +kiri build -t myapp . +``` + +Kiri 自有命令: + +| 命令 | 作用 | +|------|------| +| `kiri start` | 在 Stop 之后重新启动 Kiri,等同于窗口中的 Start | +| `kiri k8s start \| stop \| status \| delete` | 单节点 Kubernetes 集群 | +| `kiri machine create NAME [--distro D] \| list \| shell NAME \| stop \| delete NAME` | Linux 虚拟机 | +| `kiri share PORT\|CONTAINER [--name N]` | 将本地端口或容器分享到互联网 | +| `kiri import [orbstack \| desktop-linux]` | 迁移镜像、卷和容器 | +| `kiri domains [set --http N --https N \| reset]` | 本地域名监听的端口 | +| `kiri usb [list] \| attach DEVICE \| detach DEVICE` | 容器的 USB 设备(beta) | +| `kiri build-with [docker \| kiri]` | 选择 `docker build` 使用的构建器 | +| `kiri update [--check]` | 安装最新版本 | +| `kiri diag logs \| report` | 日志,以及随 bug 报告提交的报告文件 | +| `kiri bench [--runs N] [--network none\|bridge]` | 在你的机器上测量容器启动速度 | +| `kiri ui` | 打开窗口 | + +--- + +## 基准测试 + +所有数据均为中位数,在同一台机器的一次会话中,使用相同的 `docker` CLI 和相同的镜像对每个引擎测得。 + +### macOS + +`alpine` 运行 `true` 后删除,30 次运行,Apple 芯片 Mac: + +| 引擎 | Docker Engine API, p50 | p99 | `docker` CLI, p50 | p99 | +|------|----------------------:|----:|------------------:|----:| +| **Kiri** | **2.55 ms** | **4.72 ms** | **14.2 ms** | **17.4 ms** | +| Docker Desktop | 213 ms | 774 ms | 243 ms | 351 ms | +| OrbStack | 380 ms | 829 ms | 442 ms | 2383 ms | + +Kiri 通过 `docker` CLI 的 14 ms 中,大部分是 CLI 自身的启动时间。 + +引擎运行时的开销: + +| 指标 | Kiri | +|------|-----:| +| 虚拟机冷启动到就绪 | 112 ms | +| 客户机内核启动到 PID 1 | 8 ms | +| 干净关闭虚拟机 | 2.2 ms | +| 从休眠唤醒 | 约 150 ms | +| 虚拟机休眠时守护进程内存 | 约 15 MB | +| 每个容器的 shim 内存 | 0 MB(没有 shim) | +| 空闲时守护进程 CPU | 0.0 % | +| 宿主机到客户机往返,p50 / p99 | 31 µs / 62 µs | +| 客户机内核镜像 | 10 MB | +| 客户机 agent(PID 1 兼容器运行时) | 小于 1 MB | + +### Linux + +在一台 16 核 x86-64 Ubuntu 24.04 机器上对比六个引擎: + +| 引擎 | `run --rm alpine true` | 200 MB 容器 → 宿主机 | 1 GB 绑定挂载写入 | 1 GB 绑定挂载读取 | `build`,3 层,无缓存 | 发布端口 | +|------|----:|----:|----:|----:|----:|----:| +| **Kiri** | **188 ms** | **209 MB/s** | **1467 MB/s** | **3851 MB/s** | **1113 ms** | 10.3 Gbit/s | +| Docker Engine | 697 ms | 56 MB/s | 819 MB/s | 1307 MB/s | 1723 ms | **100.7 Gbit/s** | +| Podman | 1105 ms | 70 MB/s | 593 MB/s | 907 MB/s | 1148 ms | 51.9 Gbit/s | +| nerdctl | 631 ms | 72 MB/s | 845 MB/s | 1485 MB/s | 1211 ms | 52.4 Gbit/s | +| Colima | 635 ms | 20 MB/s | 493 MB/s | 1496 MB/s | 2472 ms | 0.8 Gbit/s | +| Docker Desktop | 714 ms | 114 MB/s | 826 MB/s | 1283 MB/s | 2008 ms | 87.8 Gbit/s | + +Kiri 启动容器比 Docker Engine 快 3.4 倍,读取绑定挂载快 2.9 倍。在通过发布端口的大流量传输上 Kiri 较慢,因为 Kiri 在用户空间中转发流量:对 Web 应用没有影响,大文件传输时较为明显。完整报告见 [`bench/ubuntu-2026-10-26.md`](bench/ubuntu-2026-10-26.md)。 + +### Windows + +Windows 11,16 核 x86-64 PC,两个引擎均运行于 WSL 2: + +| | Kiri | Docker Desktop | +|---|----:|----:| +| `docker run --rm alpine true` | **78 ms** | 491 ms | +| `docker exec … true` | **57 ms** | 89 ms | +| 200 MB 容器 → 宿主机 | **255 MB/s** | 40 MB/s | + +完整报告见 [`bench/windows-2026-10-25.md`](bench/windows-2026-10-25.md)。 + +### 自己跑一遍 + +```bash +kiri bench --network bridge --runs 30 # 在你的机器上测量容器启动 +bench/suite.sh # 完整的 Linux 对比测试 +``` + +测试方法和所有其他数据见 [`bench/results.json`](bench/results.json)。 + +--- + +## 对比 + +| | Kiri | Docker Desktop | OrbStack | Colima | +|---|:---:|:---:|:---:|:---:| +| 开源 | ✅ Apache-2.0 | ❌ | ❌ | ✅ MIT | +| 商用免费 | ✅ | 大公司需付费 | 付费 | ✅ | +| macOS | ✅ | ✅ | ✅ | ✅ | +| Windows | ✅ | ✅ | ❌ | ❌ | +| Linux | ✅ | ✅ | ❌ | ✅ | +| 兼容 `docker` CLI、Compose 和 buildx | ✅ | ✅ | ✅ | ✅ | +| 容器、镜像、卷和网络的图形窗口 | ✅ | ✅ | ✅ | ❌ | +| Kubernetes | ✅ | ✅ | ✅ | ✅ | +| Linux 虚拟机 | ✅ | ❌ | ✅ | ❌ | +| 带 HTTPS 的本地域名 | ✅ | ❌ | ✅ | ❌ | +| 虚拟机空闲休眠 | ✅ | ✅ | ❌ | ❌ | +| 从其他引擎导入 | ✅ | ❌ | ✅ | ❌ | +| macOS 容器启动(Docker API, p50) | **2.55 ms** | 213 ms | 380 ms | 未测量 | + +--- + +## Kiri 工作原理 + +``` +docker CLI ─┐ +compose ────┼─ Docker Engine API ─► kiri daemon ── vsock ──► guest agent (PID 1) +buildx ─────┤ 管理虚拟机 clone3 → 容器 +kiri UI ────┘ +``` + +虚拟机使用定制的 10 MB 内核,其 PID 1 是一个约 900 KB 的 Rust agent。该 agent 通过一次 `clone3` 进入命名空间和 cgroup 来启动容器。没有 runc、没有 shim、也没有 dockerd。更多细节见 [docs/development.md](docs/development.md#architecture)。 + +--- + +## 文档 + +- [docs.runkiri.com](https://docs.runkiri.com):每个功能的使用指南 +- [功能特性](docs/features.md):当前支持的全部能力、发布文件和已知问题 +- [开发指南](docs/development.md):构建、从源码运行、架构和仓库结构 +- [发布说明](docs/releases) + +--- + +## 路线图 + +接下来是更多分享方式(Tailscale 和 Cloudflare Tunnel,0.3.0)以及 Coolify 支持(0.4.0)。每个版本的计划见 [ROADMAP.md](ROADMAP.md)。 + +--- + +## 社区 + +Kiri 在开放中构建。欢迎提 issue 和 pull request:见 **[CONTRIBUTING.md](CONTRIBUTING.md)** 和[行为准则](CODE_OF_CONDUCT.md)。想迈出贡献第一步?看看 [`good first issue`](https://github.com/libracoder/kiri/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) 标签下的任务。 + +

+ + 加入我们的 Discord + +

+ +

+ + + + Star History Chart + + +

+ +感谢这些了不起的贡献者: + + + 贡献者 + + +--- + +## 安全 + +Kiri 会自动更新,并在更新前校验每个新版本的签名。如需私下报告漏洞,见 **[SECURITY.md](SECURITY.md)**。 + +--- + +## 许可证 + +[Apache-2.0](LICENSE)。第三方许可证见 [NOTICE](NOTICE)。客户机内核为 Linux(GPL-2.0);其配置、补丁和源码获取方式见 [`guest/kernel`](guest/kernel)。 + +"Kiri" 名称和 Kiri 徽标不在许可证覆盖范围内。欢迎 fork,但请使用不同的名称和徽标。 From 143bc926e7be043f7e86a2d51b7b4452b06cd1d2 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:28:31 +0100 Subject: [PATCH 116/157] Builds: show steps of a running build with one bounded log reader (#923) (#949) Co-authored-by: Arekatla Nishanth Chowdary --- crates/kiri/src/builds.rs | 89 +++++++++++++++++++++++++++++++++-- crates/kiri/src/ui/index.html | 7 +-- tests/regressions.tsv | 2 + tests/ui/builds-running.js | 32 +++++++++++++ 4 files changed, 123 insertions(+), 7 deletions(-) create mode 100644 tests/ui/builds-running.js diff --git a/crates/kiri/src/builds.rs b/crates/kiri/src/builds.rs index 28bccf571..e8a7c070f 100644 --- a/crates/kiri/src/builds.rs +++ b/crates/kiri/src/builds.rs @@ -27,7 +27,7 @@ fn kiri_host() -> io::Result { Ok(format!("npipe://{}", crate::client::pipe().replace('\\', "/"))) } -fn buildx(args: &[&str]) -> io::Result<(String, String)> { +fn buildx_command(args: &[&str]) -> io::Result { let docker = crate::client::docker_cli().ok_or_else(|| io::Error::other("no docker CLI found (Kiri.app bundles one)"))?; let host = kiri_host()?; let mut cmd = Command::new(docker); @@ -37,7 +37,14 @@ fn buildx(args: &[&str]) -> io::Result<(String, String)> { // Clear DOCKER_CONTEXT and point DOCKER_HOST at Kiri's socket/pipe so the // implicit "default" builder (used by `docker compose build`) resolves to // Kiri's engine while named builders on Kiri's context still work. - let out = cmd.env_remove("DOCKER_CONTEXT").env("DOCKER_HOST", host).arg("buildx").args(args).stdin(Stdio::null()).output()?; + cmd.env_remove("DOCKER_CONTEXT").env("DOCKER_HOST", host).arg("buildx").args(args).stdin(Stdio::null()); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + Ok(cmd) +} + +fn buildx(args: &[&str]) -> io::Result<(String, String)> { + let out = buildx_command(args)?.output()?; let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()); if !out.status.success() { let msg = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("buildx failed").trim_start_matches("ERROR: ").to_owned(); @@ -46,6 +53,58 @@ fn buildx(args: &[&str]) -> io::Result<(String, String)> { Ok((stdout, stderr)) } +/// What `buildx` prints to stderr within `limit`, then the command and the +/// plugin it started are stopped. `history logs` on a running build follows +/// it until it ends: waiting for that left the steps unshown and, with the +/// window asking again every 2 s, a reader piling up per ask (#923). +fn buildx_stderr_for(args: &[&str], limit: std::time::Duration) -> io::Result { + stderr_for(buildx_command(args)?, limit) +} + +fn stderr_for(mut cmd: Command, limit: std::time::Duration) -> io::Result { + cmd.stdout(Stdio::null()).stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn()?; + let mut err = child.stderr.take().ok_or_else(|| io::Error::other("no stderr"))?; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut b = Vec::new(); + let _ = io::Read::read_to_end(&mut err, &mut b); + let _ = tx.send(b); + }); + let until = std::time::Instant::now() + limit; + while child.try_wait()?.is_none() { + if std::time::Instant::now() >= until { + kill_tree(&mut child); + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + // The tree is gone, so the pipe closes; the wait only covers a straggler. + let b = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap_or_default(); + Ok(String::from_utf8_lossy(&b).into_owned()) +} + +/// Kills `child` and what it started: docker runs buildx as a child of its +/// own. As ui/compose.rs's, which the Windows build of this file can't reach. +fn kill_tree(child: &mut std::process::Child) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: a plain signal to the group this child leads (`process_group(0)`). + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + let _ = Command::new("taskkill").args(["/F", "/T", "/PID", &child.id().to_string()]).creation_flags(0x0800_0000).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + let _ = child.kill(); + let _ = child.wait(); +} + /// Every JSON value in `s`, whether one per line or run together. fn values(s: &str) -> Vec { serde_json::Deserializer::from_str(s).into_iter::().map_while(Result::ok).collect() @@ -133,8 +192,14 @@ pub fn detail(builder: &str, id: &str) -> io::Result { } let (info, _) = buildx(&["history", "inspect", "--builder", builder, id, "--format", "json"])?; let info: Value = serde_json::from_str(&info).map_err(io::Error::other)?; - // The raw progress stream goes to stderr. - let (_, raw) = buildx(&["history", "logs", "--builder", builder, "--progress", "rawjson", id]).unwrap_or_default(); + // The raw progress stream goes to stderr. A running build's is what it + // has printed so far: the window asks again for the rest. + let logs_args = ["history", "logs", "--builder", builder, "--progress", "rawjson", id]; + let raw = if info["Status"] == "Running" { + buildx_stderr_for(&logs_args, std::time::Duration::from_secs(2)).unwrap_or_default() + } else { + buildx(&logs_args).map(|(_, e)| e).unwrap_or_default() + }; let mut order: Vec = Vec::new(); let mut steps: HashMap = HashMap::new(); @@ -465,6 +530,22 @@ fn failure(what: &str, stderr: &[u8]) -> String { mod tests { use super::*; + /// A follower that never exits (a running build's `history logs`, its + /// plugin a child of docker) gives what it printed and is gone (#923). + #[cfg(unix)] + #[test] + fn a_follower_gives_what_it_printed_and_is_stopped_with_its_children() { + let marker = format!("kiri-builds-follow-{}", std::process::id()); + let mut cmd = Command::new("sh"); + cmd.args(["-c", &format!("echo '{{\"a\":1}}' >&2; sh -c 'exec sleep 30 {marker}' 2>/dev/null & sleep 30; wait")]); + let started = std::time::Instant::now(); + let out = stderr_for(cmd, std::time::Duration::from_millis(500)).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(3), "{:?}", started.elapsed()); + assert_eq!(values(&out), vec![json!({"a": 1})]); + let left = Command::new("pgrep").args(["-f", &marker]).output().unwrap(); + assert!(left.stdout.is_empty(), "left running: {}", String::from_utf8_lossy(&left.stdout)); + } + /// A build already removed (a second click, or several removed at once) /// is removed: BuildKit's "lease not found" isn't an error to show. But /// BuildKit says the same for a build still running, which stays listed: diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 9b40ad076..1b6cc14bc 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -6734,7 +6734,7 @@

${tr("Ports for {name}", { name: esc(name) })}

// Dockerfile steps are "[stage 3/9] …" or "[2/4] …"; the rest is BuildKit's own work. const blInternal = (name) => !/^\[([^\]]* )?\d+\/\d+\]/.test(name || ""); function pickBuild(b) { - ui.bl.sel = b; ui.bl.d = null; ui.bl.open = new Set(); ui.bl.confirm = null; ui.bl.layers = null; ui.bl.plat = null; + ui.bl.sel = b; ui.bl.d = null; ui.bl.open = new Set(); ui.bl.confirm = null; ui.bl.layers = null; ui.bl.plat = null; ui.bl.asking = b.id; send("build", { name: b.builder, id: b.id }); if (ui.bl.tab === "layers" || ui.bl.tab === "security") send("buildlayers", { name: b.builder, id: b.id }); } @@ -8609,7 +8609,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r b.items = (e.builds || b.items || []).filter((x) => !seen.has(x.id) && seen.add(x.id)); b.error = e.error || ""; const sel = b.sel && b.items.find((x) => x.id === b.sel.id); if (!sel && b.items.length) pickBuild(b.items[0]); - else if (sel && (sel.status === "Running" || sel.status !== b.sel.status)) { b.sel = sel; send("build", { name: sel.builder, id: sel.id }); } + // One ask at a time for a running build: each reads its log for a moment (#923). + else if (sel && (sel.status !== b.sel.status || (sel.status === "Running" && b.asking !== sel.id))) { b.sel = sel; b.asking = sel.id; send("build", { name: sel.builder, id: sel.id }); } if (ui.view === "builds") render(); else if ($("n-builds")) $("n-builds").textContent = b.items.length; break; } @@ -8626,7 +8627,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "scanhistory": { const x = ui.scans.get(e.name) || {}; x.history = e.scans || []; x.histErr = e.error || null; ui.scans.set(e.name, x); rerenderScan(); break; } case "imagelayers": if (ui.imgd?.name === e.name) { ui.imgd.layers = e; if (ui.view === "images") render(); } break; case "buildlayers": if (ui.bl.sel?.id === e.id) { ui.bl.layers = e; if (ui.view === "builds") renderBuilds(); } break; - case "build": if (ui.bl.sel?.id === e.id) { ui.bl.d = e; if (ui.view === "builds") renderBuilds(); } break; + case "build": if (ui.bl.asking === e.id) ui.bl.asking = null; if (ui.bl.sel?.id === e.id) { ui.bl.d = e; if (ui.view === "builds") renderBuilds(); } break; case "usedcontext": ui.ctxSwitching = false; if (e.error) toast("error", tr("Couldn't switch docker: {error}", { error: e.error })); if (ui.view === "settings") render(); break; case "importsources": ui.imp.sources = e.sources; { const s = e.sources.find((x) => x.id === ui.imp.source) || e.sources.find((x) => x.running && x.id === ui.status?.context) || e.sources.find((x) => x.running) || e.sources[0]; if (s) { ui.imp.source = s.id; if (s.running) send("inventory", { name: s.id }); } } if (ui.view === "settings") render(); break; case "inventory": ui.imp.inv = e; if (ui.view === "settings") render(); renderImportStrip(); drawImportModal(); break; diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 4da0fc635..1a5249f89 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -358,3 +358,5 @@ crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded external AAAA queries returning unreachable IPv6 addresses, and enterprise macOS packet-tunnel / RTF_IFSCOPE VPNs bypassed host egress relay causing TLS handshake timeouts 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 diff --git a/tests/ui/builds-running.js b/tests/ui/builds-running.js new file mode 100644 index 000000000..71df6e3c9 --- /dev/null +++ b/tests/ui/builds-running.js @@ -0,0 +1,32 @@ +// A running build's steps are asked again on each 2 s tick, but one ask at a +// time: each reads the build's log for a moment, and asking every tick left a +// log reader running per ask (#923). +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; +const at = new Date(Date.now() - 60e3).toISOString(); +const running = { builder: "kiri", id: "b1", name: "api", status: "Running", started: at, completed: null, steps: 9, done: 3, cached: 1 }; +const asks = () => sent.filter((s) => s.type === "build" && s.id === "b1").length; +show("builds"); +kiri.on({ type: "builds", builds: [running] }); +t("picking the running build asks for its steps", () => eq(asks(), 1, "asks")); +t("ticks while that ask is out ask nothing more", () => { + kiri.on({ type: "builds", builds: [running] }); + kiri.on({ type: "builds", builds: [running] }); + eq(asks(), 1, "asks"); +}); +t("once the steps come, the next tick asks again", () => { + kiri.on({ type: "build", builder: "kiri", id: "b1", name: "api", status: "Running", started: at, steps: [], warnings: [] }); + kiri.on({ type: "builds", builds: [running] }); + eq(asks(), 2, "asks"); +}); +t("an error answer counts as the answer", () => { + kiri.on({ type: "build", builder: "kiri", id: "b1", error: { message: "boom" }, steps: [], failed: true }); + kiri.on({ type: "builds", builds: [running] }); + eq(asks(), 3, "asks"); +}); +t("the build finishing is asked about at once, ask or no ask", () => { + kiri.on({ type: "builds", builds: [{ ...running, status: "Completed", completed: new Date().toISOString() }] }); + eq(asks(), 4, "asks"); +}); +report(R); From f85d40769a2ec51285dabd4ee59a8dfc55a8e1a3 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:36:41 +0100 Subject: [PATCH 117/157] Linux: compute .deb libc6 floor from non-weak GLIBC_* symbols (#252) (#950) Co-authored-by: Urdemonlord <150226383+Urdemonlord@users.noreply.github.com> --- packaging/linux/build.sh | 13 ++++++++++++- packaging/linux/test.sh | 13 +++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packaging/linux/build.sh b/packaging/linux/build.sh index d368afc2f..e1e2e4998 100644 --- a/packaging/linux/build.sh +++ b/packaging/linux/build.sh @@ -48,6 +48,17 @@ if [ -n "$window" ]; then [ -x "$window" ] || { echo "no $window" >&2; exit 1; } window=$(cd "$(dirname "$window")" && pwd)/$(basename "$window") fi +# The strongest glibc the window binary really needs: the highest non-weak +# GLIBC_ version it references. Weak refs (pidfd_spawnp, pidfd_getpid at +# 2.39) only warn on older systems, so they must not raise the floor. +# Reading the build host's glibc instead did exactly that and broke Ubuntu +# 22.04 (#252). Empty when objdump is missing or finds nothing; the caller +# then falls back to the host's version. +glibc_floor() { # binary -> e.g. 2.34 + local v + v=$(command -v objdump >/dev/null 2>&1 && objdump -T "$1" 2>/dev/null | grep -v ' w ' | grep -o 'GLIBC_2\.[0-9]*' | sed 's/GLIBC_//' | sort -Vu | tail -1) + [ -n "$v" ] && printf '%s' "$v" +} mkdir -p "$outdir" outdir=$(cd "$outdir" && pwd) work=$(mktemp -d) @@ -135,7 +146,7 @@ Homepage: https://runkiri.com Conflicts: $other Replaces: $other $([ "$full" = 1 ] || echo "Suggests: docker-cli | docker.io") -$([ "$full" = 1 ] && [ -n "$window" ] && echo "Depends: libc6 (>= $(ldd --version | sed -n '1s/.* //p')), libgtk-3-0t64 | libgtk-3-0, libwebkit2gtk-4.1-0") +$([ "$full" = 1 ] && [ -n "$window" ] && echo "Depends: libc6 (>= $(glibc_floor "$window" || ldd --version | sed -n '1s/.* //p')), libgtk-3-0t64 | libgtk-3-0, libwebkit2gtk-4.1-0") $([ "$full" = 1 ] && [ -n "$window" ] && echo "Recommends: pkexec | policykit-1") Description: Tiny, fast container runtime (Docker API)$([ "$full" = 1 ] || echo ", engine only") Kiri runs containers on this machine's kernel and speaks the Docker API on diff --git a/packaging/linux/test.sh b/packaging/linux/test.sh index 175ee97a8..7a5592e33 100644 --- a/packaging/linux/test.sh +++ b/packaging/linux/test.sh @@ -79,6 +79,19 @@ test_package() { # name full(0|1) step "$c" "dpkg -P drops data and group" "dpkg -P $name && test ! -e /var/lib/kiri -a ! -e /var/lib/kiri-daemon && ! getent group kiri" $docker rm -f "$c" >/dev/null 2>&1 + if [ "$full" = 1 ] && dpkg-deb -I "$deb" | grep -q 'Depends:.*libc6'; then + # Ubuntu 22.04 ships glibc 2.35; the .deb must install there (#252). + echo "== .deb installs on Ubuntu 22.04 (glibc 2.35)" + local c22=kiri-deb22-test-$name debname22 + debname22=$(basename "$deb") + $docker rm -f "$c22" >/dev/null 2>&1 + $docker run -d --name "$c22" --privileged --tmpfs /run --tmpfs /tmp -v "$out:/pkg:ro" ubuntu:22.04 sleep infinity >/dev/null + step "$c22" "apt installs the .deb on 22.04" "apt-get update -qq >/dev/null 2>&1 && DEBIAN_FRONTEND=noninteractive apt-get install -y /pkg/$debname22" + step "$c22" "window binary loads on glibc 2.35" "ldd /usr/lib/kiri/kiri-window >/dev/null 2>&1" + step "$c22" "dpkg -r removes the package" "dpkg -r $name && test ! -e /usr/bin/kiri" + $docker rm -f "$c22" >/dev/null 2>&1 + fi + echo "== .rpm in a Fedora container" local rpmname; rpmname=$(basename "$rpm") $docker run --rm -v "$out:/pkg:ro" fedora:41 bash -c " From 9d788ee7d217e7f55a918d86a3712c4410141f52 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:44:54 +0100 Subject: [PATCH 118/157] UI: show user-stopped containers exiting on SIGTERM as Stopped, not Failed (#903) (#951) Co-authored-by: sundarshahi --- crates/kiri/src/daemon/api.rs | 1 + crates/kiri/src/ui/index.html | 6 ++++-- tests/ui/vmstop.js | 17 +++++++++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 86b61d2ee..2e28020d0 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -3407,6 +3407,7 @@ fn list(req: &Request, engine: &Engine) -> Result { "KiriExitCode": c.exit_code, "KiriOOMKilled": c.oom_killed, "KiriVmStopped": c.vm_stopped, + "KiriStoppedByUser": c.stopped_by_user, "Ports": ports_list(c), "Labels": if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }, "HostConfig": {"NetworkMode": c.spec.network_mode}, diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 1b6cc14bc..5d4cb4189 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -2857,11 +2857,13 @@

Containers

c.KiriVmStopped || (c.KiriStoppedByUser && exitCode(c) !== 137); function statusText(c) { if (c.State === "exited" && c.KiriOOMKilled) return tr("Out of memory"); if (c.State === "running" && c.KiriStartedAt) return tr("Up {time}", { time: since(c.KiriStartedAt) }); if (c.State === "paused" && c.KiriStartedAt) return tr("Up {time} (Paused)", { time: since(c.KiriStartedAt) }); - if (c.State === "exited") return c.KiriVmStopped ? tr("Stopped") : exitWord(exitCode(c)); + if (c.State === "exited") return stoppedNotFailed(c) ? tr("Stopped") : exitWord(exitCode(c)); return shortStatus(c.Status); } /* The hover text: when it stopped, and Docker's own words for a failure. */ @@ -2877,7 +2879,7 @@

Containers

{ try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; @@ -7,7 +8,9 @@ const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new const at = Math.floor(Date.now() / 1000) - 120; const c = (id, extra) => ({ Id: id, Names: [`/${id}`], Image: "nginx", State: "exited", Status: "", KiriExitCode: 255, KiriFinishedAt: at, Ports: [], Labels: {}, ...extra }); show("containers"); -kiri.on({ type: "lists", containers: [c("vm", { KiriVmStopped: true }), c("app", {})], images: [], volumes: [], networks: [] }); +kiri.on({ type: "lists", containers: [c("vm", { KiriVmStopped: true }), c("app", {}), + c("term", { KiriExitCode: 143, KiriStoppedByUser: true }), c("slow", { KiriExitCode: 137, KiriStoppedByUser: true }), + c("sigterm", { KiriExitCode: 143 })], images: [], volumes: [], networks: [] }); const pill = (id) => document.querySelector(`[data-live="${id}"]`); t("stopped with the VM reads Stopped, uncoloured, and says why on hover", () => { eq([pill("vm").textContent, pill("vm").className.includes("failed"), pill("vm").title], ["Stopped", false, "Stopped 2 min ago, when the Linux VM stopped. Start it again whenever you like."], "vm"); @@ -15,4 +18,14 @@ t("stopped with the VM reads Stopped, uncoloured, and says why on hover", () => t("an app that really exited 255 still reads Failed", () => { eq([pill("app").textContent, pill("app").className.includes("failed")], ["Failed (255)", true], "app"); }); +t("stopped by the user, exit 143: Stopped, uncoloured, not counted as failed; the code stays on hover", () => { + eq([pill("term").textContent, pill("term").className.includes("failed"), pill("term").title, ctrState(ui.containers.find((x) => x.Id === "term"))], + ["Stopped", false, "Exited with code 143, 2 min ago", "stopped"], "term"); +}); +t("a stop that had to kill it still reads Killed (137)", () => { + eq([pill("slow").textContent, pill("slow").className.includes("killed")], ["Killed (137)", true], "slow"); +}); +t("exit 143 that no stop asked for still reads Failed", () => { + eq([pill("sigterm").textContent, pill("sigterm").className.includes("failed"), ctrState(ui.containers.find((x) => x.Id === "sigterm"))], ["Failed (143)", true, "failed"], "sigterm"); +}); report(R); From c133a1ace302b7524aa460495946313dec5ef92c Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:55:38 +0100 Subject: [PATCH 119/157] Compose: kill the compose plugin process group when cancelling apply (#862) (#952) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/ui/compose.rs | 121 ++++++++++++++++++++++++++++------ 1 file changed, 101 insertions(+), 20 deletions(-) diff --git a/crates/kiri/src/ui/compose.rs b/crates/kiri/src/ui/compose.rs index 68008766a..3fde6a0e3 100644 --- a/crates/kiri/src/ui/compose.rs +++ b/crates/kiri/src/ui/compose.rs @@ -2148,7 +2148,7 @@ fn run_ran(mut cmd: Command, input: Option<&str>, secs: u64) -> Ran { /// Kills `child` and every process it started (its own process group; on /// Windows, its tree). -fn kill_tree(child: &mut std::process::Child) { +fn kill_group(child: &mut std::process::Child) { #[cfg(unix)] if let Ok(pid) = i32::try_from(child.id()) { // SAFETY: a plain signal to the group this child leads (`process_group(0)`). @@ -2162,6 +2162,10 @@ fn kill_tree(child: &mut std::process::Child) { let _ = Command::new("taskkill").args(["/F", "/T", "/PID", &child.id().to_string()]).creation_flags(0x0800_0000).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status(); } let _ = child.kill(); +} + +fn kill_tree(child: &mut std::process::Child) { + kill_group(child); let _ = child.wait(); } @@ -4147,9 +4151,10 @@ static UPS: LazyLock>> = LazyLock::new(|| Mutex::new(H pub fn cancel(name: &str) -> bool { let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); let Some(up) = ups.get_mut(name) else { return false }; - up.cancelled = true; - if let Some(c) = up.child.as_mut() { - let _ = c.kill(); + if !std::mem::replace(&mut up.cancelled, true) + && let Some(c) = up.child.as_mut() + { + kill_group(c); } true } @@ -4194,8 +4199,7 @@ struct Applying(String); impl Drop for Applying { fn drop(&mut self) { if let Some(mut c) = UPS.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0).and_then(|u| u.child) { - let _ = c.kill(); - let _ = c.wait(); + kill_tree(&mut c); } } } @@ -4213,6 +4217,23 @@ pub fn restore(name: &str, store: Store) -> Result<(), String> { Ok(()) } +fn spawn_up(mut cmd: Command, name: &str) -> io::Result<(Option, Option)> { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn()?; + let out = child.stdout.take(); + let err = child.stderr.take(); + let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); + let up = ups.entry(name.to_owned()).or_default(); + // Cancel came while the file was being saved: `up` stops at once. + if up.cancelled { + kill_group(&mut child); + } + up.child = Some(child); + Ok((out, err)) +} + /// Apply: checks the draft, saves it, and runs `docker compose up -d /// --remove-orphans`, sending its progress lines as /// `{type: "composeapply", name, line}` and then `{…, done: true, ok, error, @@ -4311,22 +4332,11 @@ pub fn apply(cli: Cli, store: Store, name: &str, draft: &str, base: Option<&str> Ok(c) => c, Err(e) => return done(false, own(&e.to_string()), true, &hidden, Some(&hash)), }; - cmd.args(project_args(&p, None)).args(profile_args(&profs)).args(["--progress", "plain", "up", "-d", "--remove-orphans"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - let mut child = match cmd.spawn() { - Ok(c) => c, + cmd.args(project_args(&p, None)).args(profile_args(&profs)).args(["--progress", "plain", "up", "-d", "--remove-orphans"]); + let (out, err) = match spawn_up(cmd, name) { + Ok(pipes) => pipes, Err(e) => return done(false, own(&format!("couldn't run docker compose: {e}")), true, &hidden, Some(&hash)), }; - let out = child.stdout.take(); - let err = child.stderr.take(); - { - let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); - let up = ups.entry(name.to_owned()).or_default(); - // Cancel came while the file was being saved: `up` stops at once. - if up.cancelled { - let _ = child.kill(); - } - up.child = Some(child); - } let reader = std::thread::spawn(move || { let mut s = String::new(); if let Some(mut o) = out { @@ -6343,6 +6353,77 @@ mod tests { assert!(!cancelled("c1") && !UPS.lock().unwrap().contains_key("c1"), "gone once Apply ends"); } + #[test] + fn cancelling_apply_stops_the_compose_plugin_tree() { + if let Ok(addr) = std::env::var("KIRI_T_PLUGIN_GATE") { + let mut conn = std::net::TcpStream::connect(addr).unwrap(); + let _ = writeln!(io::stderr(), " Container celtree-web-1 Creating "); + let _ = io::stderr().flush(); + let mut b = [0u8; 1]; + if io::Read::read_exact(&mut conn, &mut b).is_ok() && b[0] == b'P' { + let _ = conn.write_all(b"A"); + let _ = conn.flush(); + let _ = io::Read::read(&mut conn, &mut b); + } + std::process::exit(1); + } + let wrapper = |gate: &str| { + let exe = std::env::current_exe().unwrap(); + #[cfg(unix)] + let mut c = { + let mut c = Command::new("sh"); + c.args(["-c", "\"$KIRI_T_EXE\" cancelling_apply_stops_the_compose_plugin_tree --nocapture; exit $?", "sh"]); + c + }; + #[cfg(windows)] + let mut c = { + use std::os::windows::process::CommandExt as _; + let mut c = Command::new("cmd"); + c.args(["/d", "/c"]).raw_arg("\"%KIRI_T_EXE%\" cancelling_apply_stops_the_compose_plugin_tree --nocapture"); + c + }; + c.env("KIRI_T_EXE", exe).env("KIRI_T_PLUGIN_GATE", gate); + c + }; + + // 1. Cancel during `up`: kills wrapper and plugin child, closing inherited pipes immediately. + let gate = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = gate.local_addr().unwrap().to_string(); + UPS.lock().unwrap().insert("celtree".into(), Up::default()); + let applying = Applying("celtree".into()); + let (out, err) = spawn_up(wrapper(&addr), "celtree").unwrap(); + let (mut conn, _) = gate.accept().unwrap(); + let mut lines = io::BufReader::new(err.unwrap()).lines(); + assert_eq!(lines.next().unwrap().unwrap(), " Container celtree-web-1 Creating "); + assert!(cancel("celtree")); + assert!(cancel("celtree")); + let _ = conn.write_all(b"P"); + let _ = conn.flush(); + let mut ack = [0u8; 1]; + assert!(!(io::Read::read_exact(&mut conn, &mut ack).is_ok() && ack[0] == b'A'), "compose plugin survived cancel"); + drop(conn); + assert!(lines.next().is_none(), "stderr pipe closed once plugin tree stopped"); + let mut stdout_rest = String::new(); + let _ = io::Read::read_to_string(&mut out.unwrap(), &mut stdout_rest); + let child = UPS.lock().unwrap().get_mut("celtree").and_then(|u| u.child.take()); + assert!(child.unwrap().wait().is_ok()); + drop(applying); + assert!(!cancel("celtree")); + + // 2. Cancel arrived while saving (before `spawn_up` registers `child`): stops tree at once. + let gate2 = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr2 = gate2.local_addr().unwrap().to_string(); + UPS.lock().unwrap().insert("celtree2".into(), Up { child: None, cancelled: true }); + let applying2 = Applying("celtree2".into()); + let (out2, err2) = spawn_up(wrapper(&addr2), "celtree2").unwrap(); + let mut rest_err = String::new(); + let mut rest_out = String::new(); + let _ = io::Read::read_to_string(&mut err2.unwrap(), &mut rest_err); + let _ = io::Read::read_to_string(&mut out2.unwrap(), &mut rest_out); + drop(applying2); + assert!(!cancel("celtree2")); + } + #[test] fn project_actions_go_by_name_in_composes_order_and_remove_its_network() { assert_eq!(action_args("shop", "start").unwrap(), ["compose", "--ansi", "never", "-p", "shop", "start"]); From e76ce865af2c904aa6b5c857f806aab601d93ad8 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:05:55 +0100 Subject: [PATCH 120/157] Kubernetes: keep malformed k8s.json settings instead of overwriting them (#926) (#953) Co-authored-by: takealook97 --- crates/kiri/src/k8s.rs | 63 ++++++++++++++++++++++++++++++++++++++++-- tests/e2e.sh | 7 +++++ tests/regressions.tsv | 1 + 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 667ee34be..763a4dc52 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -125,6 +125,30 @@ fn load_config_from(path: &std::path::Path) -> Config { std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() } +/// The settings `kiri k8s set` changes and saves back. Only a missing file is +/// the defaults: one that can't be read or parsed is an error, not replaced. +fn load_config_for_edit(path: &std::path::Path) -> io::Result { + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Config::default()), + Err(e) => { + return Err(io::Error::new( + e.kind(), + format!("cannot read {}: {e}", path.display()), + )); + } + }; + serde_json::from_slice(&bytes).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} is not valid Kubernetes settings ({e}); fix or remove it", + path.display() + ), + ) + }) +} + fn save_config_to(path: &std::path::Path, cfg: &Config) -> io::Result<()> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; @@ -355,7 +379,8 @@ pub(crate) fn format_status(info: Option<&serde_json::Value>, cfg: &Config) -> S /// `kiri k8s set [--lan on|off] [--tls-san a,b] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]`: /// saves the settings and, if the cluster exists and they changed, recreates its node with them. fn set(args: &[String]) -> io::Result<()> { - let mut cfg = config(); + let path = config_path()?; + let mut cfg = load_config_for_edit(&path)?; let before = cfg.clone(); apply_set_args(&mut cfg, args)?; ensure_daemon()?; @@ -365,7 +390,6 @@ fn set(args: &[String]) -> io::Result<()> { if port != before.api_port() && node.as_ref().and_then(bound_port) != Some(port) && !port_free(port, cfg.lan) { return Err(io::Error::other(format!("port {port} is in use on this Mac; choose another"))); } - let path = config_path()?; save_config_to(&path, &cfg)?; println!("{}", format_settings(&cfg)); let Some(node) = node else { @@ -1045,6 +1069,41 @@ fn delete() -> io::Result<()> { #[cfg(test)] mod tests { + #[test] + fn editing_rejects_malformed_settings() { + let dir = std::env::temp_dir().join(format!("kiri-k8s-edit-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("k8s.json"); + let bad = br#"{"lan":true,"port":6445,"tls_san":["#; + std::fs::write(&path, bad).unwrap(); + let err = super::load_config_for_edit(&path) + .expect_err("malformed settings must not load as defaults"); + assert!( + err.to_string().contains(&path.display().to_string()), + "{err}" + ); + assert_eq!(std::fs::read(&path).unwrap(), bad); + + // No file yet: the defaults, so a first `kiri k8s set` still saves. + std::fs::remove_file(&path).unwrap(); + assert_eq!( + super::load_config_for_edit(&path).unwrap(), + super::Config::default() + ); + + std::fs::write( + &path, + br#"{"lan":true,"port":6445,"tls_san":["k8s.example"]}"#, + ) + .unwrap(); + let cfg = super::load_config_for_edit(&path).unwrap(); + assert_eq!( + (cfg.port, cfg.tls_san), + (Some(6445), vec!["k8s.example".to_owned()]) + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_port_comes_from_the_binding_then_the_label() { let running = serde_json::json!({"NetworkSettings": {"Ports": {"6443/tcp": [{"HostIp": "127.0.0.1", "HostPort": "6444"}]}}, "Config": {"Labels": {"dev.kiri.k8s.port": "6450"}}}); diff --git a/tests/e2e.sh b/tests/e2e.sh index d744ed956..a8ea8dbb3 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2527,6 +2527,13 @@ if [ "${K8S:-0}" = 1 ]; then t k8s-context-gone "0" bash -c "env HOME=$KH kubectl config get-contexts -o name | grep -c kiri" rm -rf "$KH" fi +# A k8s.json that can't be parsed is reported, not replaced with the defaults. +# The first `set` (no file yet) saves one, which shows where it lives. +if [ -x "$KIRI" ]; then + t k8s-set-keeps-malformed-config "malformed-settings-kept" bash -c 'h=$(mktemp -d); k() { env HOME="$h" KIRI_SOCKET="$2" "$1" k8s set --lan off; }; k "$@" >/dev/null 2>&1 || exit; for f in "$h"/.kiri*/k8s.json; do :; done; [ -f "$f" ] || exit; printf %s "{\"lan\":true,\"port\":6445,\"tls_san\":[" > "$f"; cp "$f" "$h/before"; out=$(k "$@" 2>&1) || case $out in *"$f is not valid Kubernetes settings ("*"); fix or remove it"*) cmp -s "$h/before" "$f" && echo malformed-settings-kept ;; esac; rm -rf "$h"' _ "$KIRI" "$SOCK" +else + skip_setup k8s-set-keeps-malformed-config "no kiri CLI found: set KIRI=/path/to/kiri" +fi section "the API's answers, as Docker gives them" API="curl -s -m 20 --unix-socket $SOCK" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 1a5249f89..184f1895e 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -345,6 +345,7 @@ crates/kiri/src/daemon/hostroots.rs #303 Windows host roots persistence in WSL m crates/kiri/src/setup.rs #556 opening Kiri.app re-appended the ~/.kiri/bin PATH block to shell profiles on every launch even when removed or when a profile already put ~/.kiri/bin on PATH, with no kiri setup --no-profiles opt-out crates/kiri/src/k8s.rs #816 kiri k8s set had no --version or --k3s-arg/--clear-k3s-args options to pin a k3s image tag or pass custom k3s server flags, and kiri k8s start did not sync ~/.kiri/k8s-manifests into k3s crates/kiri-win/src/k8s.rs #816 Windows k8s.json config and container creation did not preserve or apply custom k3s version tags and extra k3s server arguments +k8s-set-keeps-malformed-config #926 kiri k8s set replaced a k8s.json it could not parse with defaults, losing every other setting, and reported success mac-gpg-ssh-agent-mount #763 macOS launchd-started daemons used Apple's empty default Listeners SSH socket instead of GnuPG's S.gpg-agent.ssh when enable-ssh-support was set, and direct host SSH agent socket bind mounts failed across virtiofs crates/kiri/src/daemon/grpc.rs #734 docker build run from a Docker CLI inside a socket-mounted container auto-created a buildx docker-container builder without default-load=true and never stored the built image in Kiri's image store crates/kiri-image/src/store.rs #864 an image put under a name another image had dropped the old record without freeing its unreferenced blobs, and Store::pin updated PINNED without BLOB_LOCK From 81ff57b3516b26767c507ae7d1008bacda9dc6e5 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:16:33 +0100 Subject: [PATCH 121/157] API: replay kept events for docker events --until without --since (#925) (#954) Co-authored-by: takealook97 --- crates/kiri/src/daemon/ops.rs | 69 +++++++++++++++++++++++++++++++---- tests/regressions.tsv | 1 + 2 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index 6d2e92c9c..c266c1d04 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -706,7 +706,31 @@ pub(super) fn gone(w: &UnixStream) -> bool { r == 0 || pfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 } -/// `docker events`: kept events since `since`, then live ones until `until`. +fn event_time(ev: &Value) -> f64 { + ev["timeNano"].as_u64().map_or(0.0, |n| n as f64 / 1e9) +} + +/// The kept events a subscription replays first: those inside the bounds. +fn replayed<'a>( + recent: &'a [Value], + f: &super::filters::Filters, + since: Option, + until: Option, +) -> Vec<&'a Value> { + if since.is_none() && until.is_none() { + return Vec::new(); + } + recent + .iter() + .filter(|ev| { + since.is_none_or(|s| event_time(ev) >= s) + && until.is_none_or(|u| event_time(ev) <= u) + && event_matches(f, ev) + }) + .collect() +} + +/// `docker events`: kept events inside the bounds, then live ones until `until`. fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result { let f = match filters(req, &["type", "event", "container", "image", "network", "volume", "label", "label!", "daemon", "scope"]) { Ok(f) => f, @@ -721,11 +745,8 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result io::Result<()> { http::chunk(w, format!("{ev}\n").as_bytes()) }; - let at = |ev: &Value| ev["timeNano"].as_u64().map_or(0.0, |n| n as f64 / 1e9); - if let Some(s) = since { - for ev in recent.iter().filter(|ev| at(ev) >= s && until.is_none_or(|u| at(ev) <= u) && event_matches(&f, ev)) { - send(w, ev)?; - } + for ev in replayed(&recent, &f, since, until) { + send(w, ev)?; } loop { if until.is_some_and(|u| now() >= u) { @@ -733,7 +754,7 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result { - if until.is_some_and(|u| at(&ev) > u) { + if until.is_some_and(|u| event_time(&ev) > u) { break; } if event_matches(&f, &ev) { @@ -752,6 +773,40 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result Value { + json!({"Type": "container", "Action": "create", "Actor": {"ID": format!("c{secs}"), "Attributes": {}}, "timeNano": secs * 1_000_000_000}) + } + + fn ids(v: Vec<&Value>) -> Vec<&str> { + v.into_iter() + .map(|e| e["Actor"]["ID"].as_str().unwrap()) + .collect() + } + + /// `docker events --until` alone replays the kept events up to it, as + /// Docker does; both bounds are inclusive and no bounds replays nothing. + #[test] + fn events_until_without_since_replays_matching_history() { + let recent = [ev(1), ev(2), ev(3)]; + let all = Filters::default(); + assert_eq!(ids(replayed(&recent, &all, None, Some(2.5))), ["c1", "c2"]); + assert_eq!(ids(replayed(&recent, &all, Some(1.5), None)), ["c2", "c3"]); + assert_eq!(ids(replayed(&recent, &all, Some(1.5), Some(2.5))), ["c2"]); + assert!(replayed(&recent, &all, None, None).is_empty()); + assert_eq!(ids(replayed(&recent, &all, None, Some(2.0))), ["c1", "c2"]); + assert_eq!(ids(replayed(&recent, &all, Some(2.0), Some(2.0))), ["c2"]); + let only_c3 = Filters::parse(Some(r#"{"container":["c3"]}"#)).unwrap(); + assert!(replayed(&recent, &only_c3, None, Some(2.5)).is_empty()); + assert_eq!(ids(replayed(&recent, &only_c3, None, Some(3.0))), ["c3"]); + } +} + #[cfg(test)] mod disk_usage_tests { use super::DiskUsage; diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 184f1895e..a7048fb25 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -5,6 +5,7 @@ connection-close-start #588 a start sent with Connection: close was never closed, so Docker.DotNet hung until its timeout (#520) http10-start-closes #588 an HTTP/1.0 request stayed open after its answer (#479) keep-alive-start-stays #588 the connection-close fix must not close a kept-alive connection +crates/kiri/src/daemon/ops.rs #925 docker events --until without --since printed none of the kept events; Docker replays them up to --until connection-close-said #588 the answer to Connection: close did not say Connection: close http10-ping-closes #588 an HTTP/1.0 ping stayed open after its answer (#479) pid-mode-inspect #588 --pid was accepted and ignored; inspect lost HostConfig.PidMode (#347) From a36e81fd1406d15c1c895314b4c36ef82d070874 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:27:12 +0100 Subject: [PATCH 122/157] API: word docker ps Status durations like Docker (#924) (#955) Co-authored-by: takealook97 --- crates/kiri/src/daemon/api.rs | 9 +---- crates/kiri/src/daemon/time.rs | 60 ++++++++++++++++++++++++++++++++++ tests/regressions.tsv | 1 + 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 2e28020d0..632badde0 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -3178,14 +3178,7 @@ fn links_from(list: &[String], engine: &Engine) -> Result String { let ago = |t: Option| { - let s = t.and_then(|t| t.elapsed().ok()).map_or(0, |d| d.as_secs()); - match s { - 0..=1 => "Less than a second".to_owned(), - 2..=59 => format!("{s} seconds"), - 60..=3599 => format!("{} minutes", s / 60), - 3600..=86399 => format!("{} hours", s / 3600), - _ => format!("{} days", s / 86400), - } + super::time::human_duration(t.and_then(|t| t.elapsed().ok()).map_or(0, |d| d.as_secs())) }; match c.status { Status::Created => "Created".into(), diff --git a/crates/kiri/src/daemon/time.rs b/crates/kiri/src/daemon/time.rs index 716e41002..addaa28dc 100644 --- a/crates/kiri/src/daemon/time.rs +++ b/crates/kiri/src/daemon/time.rs @@ -215,6 +215,26 @@ fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { era * 146_097 + doe - 719_468 } +/// Docker's wording for how long ago something happened (go-units `HumanDuration`). +/// Seconds and minutes truncate, hours round half up, years count whole hours. +pub fn human_duration(secs: u64) -> String { + let minutes = secs / 60; + let hours = secs / 3600 + u64::from(secs % 3600 >= 1800); + match secs { + 0 => "Less than a second".to_owned(), + 1 => "1 second".to_owned(), + 2..=59 => format!("{secs} seconds"), + _ if minutes == 1 => "About a minute".to_owned(), + _ if minutes < 60 => format!("{minutes} minutes"), + _ if hours == 1 => "About an hour".to_owned(), + _ if hours < 48 => format!("{hours} hours"), + _ if hours < 24 * 7 * 2 => format!("{} days", hours / 24), + _ if hours < 24 * 30 * 2 => format!("{} weeks", hours / 24 / 7), + _ if hours < 24 * 365 * 2 => format!("{} months", hours / 24 / 30), + _ => format!("{} years", secs / 3600 / 24 / 365), + } +} + #[cfg(test)] mod tests { use super::*; @@ -256,4 +276,44 @@ mod tests { assert_eq!(ts(bad), None, "{bad}"); } } + + #[test] + fn status_durations_read_like_docker() { + const H: u64 = 3600; + const D: u64 = 86_400; + for (secs, want) in [ + (0, "Less than a second"), + (1, "1 second"), + (2, "2 seconds"), + (59, "59 seconds"), + (60, "About a minute"), + (119, "About a minute"), + (120, "2 minutes"), + (3599, "59 minutes"), + (H, "About an hour"), + (H + 1799, "About an hour"), + (H + 1800, "2 hours"), + (D - 1, "24 hours"), + (D, "24 hours"), + (47 * H, "47 hours"), + (48 * H - 1801, "47 hours"), + (48 * H - 1800, "2 days"), + (48 * H, "2 days"), + (13 * D, "13 days"), + (14 * D - 1801, "13 days"), + (14 * D - 1800, "2 weeks"), + (14 * D, "2 weeks"), + (60 * D - 1801, "8 weeks"), + (60 * D - 1800, "2 months"), + (60 * D, "2 months"), + (365 * D, "12 months"), + (730 * D - 1801, "24 months"), + (730 * D - 1800, "1 years"), + (730 * D - 1, "1 years"), + (730 * D, "2 years"), + (u64::MAX, "584942417355 years"), + ] { + assert_eq!(human_duration(secs), want, "{secs} s"); + } + } } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index a7048fb25..23cf93878 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -32,6 +32,7 @@ top-eo #588 docker top -eo did not give the columns asked for (#348) top-eo-rss #588 docker top -eo rss gave no memory column (#348) top-ps-args-refused #588 unsupported ps_args were silently ignored instead of refused (#348) ps-limit-latest #839 docker ps -l and -n ignored the requested limit and skipped stopped containers +crates/kiri/src/daemon/time.rs #924 docker ps Status said "Up 1 minutes", "1 hours" and "1 days" instead of Docker's "About a minute", "About an hour", "24 hours", weeks, months and years ij-setup #588 sets up the damaged image list check below (#440) ij-info-warns #588 a repaired images.json gave no docker info warning (#440) ij-info-names-lost #588 the repair warning did not name the images it lost (#440) From 42c72f781df896edc531b27567dbbe571712896f Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:41:48 +0100 Subject: [PATCH 123/157] Engine: validate .kiri.local Host ports and verify local HTTPS CA keypairs (#914) (#956) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/daemon/domains.rs | 39 +++++++- crates/kiri/src/daemon/tls.rs | 151 ++++++++++++++++++++++++++---- 2 files changed, 165 insertions(+), 25 deletions(-) diff --git a/crates/kiri/src/daemon/domains.rs b/crates/kiri/src/daemon/domains.rs index f98900f90..4a59475b5 100644 --- a/crates/kiri/src/daemon/domains.rs +++ b/crates/kiri/src/daemon/domains.rs @@ -635,11 +635,17 @@ fn respond(client: &mut impl Write, status: u16, reason: &str, body: &str) -> io fn local_host(host: &str) -> bool { let host = host.trim(); // Without the port: `[::1]:80`, `127.0.0.1:80`, `web.kiri.localhost:8080`. + let valid_port = |p: &str| p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n != 0); let name = match host.strip_prefix('[') { - Some(v6) => v6.split(']').next().unwrap_or(""), + Some(v6) => match v6.split_once(']') { + Some((addr, "")) => addr, + Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr, + _ => return false, + }, None => match host.rsplit_once(':') { - Some((name, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => name, - _ => host, + Some((name, port)) if valid_port(port) => name, + Some(_) => return false, + None => host, }, }; let name = name.trim_end_matches('.').to_ascii_lowercase(); @@ -674,10 +680,33 @@ mod tests { /// machine's own names only: a rebinding page's Host is its own domain. #[test] fn only_this_machines_names_get_the_container_list() { - for local in ["localhost", "localhost:80", "nope.kiri.localhost", "NOPE.Kiri.Localhost:8080", "web.shop.kiri.local", "api.kiri.local:18780", "127.0.0.1", "127.0.0.1:80", "[::1]", "[::1]:443", "anything.localhost."] { + for local in ["localhost", "localhost:80", "localhost:65535", "nope.kiri.localhost", "NOPE.Kiri.Localhost:8080", "web.shop.kiri.local", "api.kiri.local:18780", "127.0.0.1", "127.0.0.1:80", "[::1]", "[::1]:1", "[::1]:443", "[::1]:65535", "anything.localhost."] { assert!(super::local_host(local), "{local}"); } - for foreign in ["", "rebind.example.com", "rebind.example.com:80", "kiri.localhost.example.com", "localhost.example.com", "192.168.1.10", "10.0.0.1:80", "[2001:db8::1]:80", "notlocalhost", "kiri.local.evil.io"] { + for foreign in [ + "", + "rebind.example.com", + "rebind.example.com:80", + "kiri.localhost.example.com", + "localhost.example.com", + "192.168.1.10", + "10.0.0.1:80", + "[2001:db8::1]:80", + "notlocalhost", + "kiri.local.evil.io", + "[::1]rebind.example.com", + "[::1]:notaport", + "[::1", + "[::1]:0", + "[::1]:65536", + "[::1]:+80", + "[::1]:", + "localhost:0", + "localhost:65536", + "localhost:+80", + "localhost:", + "localhost:abc", + ] { assert!(!super::local_host(foreign), "{foreign}"); } } diff --git a/crates/kiri/src/daemon/tls.rs b/crates/kiri/src/daemon/tls.rs index aa0e12420..d35eab712 100644 --- a/crates/kiri/src/daemon/tls.rs +++ b/crates/kiri/src/daemon/tls.rs @@ -8,7 +8,6 @@ use std::collections::HashMap; use std::io; -use std::ops::Not; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -62,9 +61,41 @@ fn err(e: rcgen::Error) -> io::Error { io::Error::other(e.to_string()) } +fn valid_ca_der(der: &[u8], key: &KeyPair) -> bool { + if der.len() < 4 || der[0] != 0x30 { + return false; + } + let total = match der[1] { + n if n < 0x80 => 2 + n as usize, + 0x81 => 3 + *der.get(2).unwrap_or(&0) as usize, + 0x82 if der.len() >= 4 => 4 + u16::from_be_bytes([der[2], der[3]]) as usize, + 0x83 if der.len() >= 5 => 5 + u32::from_be_bytes([0, der[2], der[3], der[4]]) as usize, + _ => return false, + }; + let Some(spki) = pem_to_der(&key.public_key_pem()) else { return false }; + total == der.len() && !spki.is_empty() && der.windows(spki.len()).any(|w| w == &*spki) +} + +fn write_private_atomic(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt; + let tmp = path.with_extension("tmp"); + let _ = std::fs::remove_file(&tmp); + std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?.write_all(bytes)?; + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + /// The authority: loaded from `~/.kiri/tls`, or made there the first time. fn authority() -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>)> { let dir = dir().ok_or_else(|| io::Error::other("HOME is not set"))?; + authority_in(&dir) +} + +fn authority_in(dir: &std::path::Path) -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>)> { let (cert_path, key_path) = (dir.join("ca.pem"), dir.join("ca-key.pem")); // The authority's format version: 2 added the exclusion of IP addresses // from its name constraints. An older authority is replaced (the user @@ -72,28 +103,37 @@ fn authority() -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>) // that already had one. const CA_VERSION: &str = "2"; let version_path = dir.join("ca.version"); - if key_path.is_file() && std::fs::read_to_string(&version_path).is_ok_and(|v| v.trim() == CA_VERSION).not() { - let _ = std::fs::remove_file(&key_path); - let _ = std::fs::remove_file(&cert_path); - } - let key = match std::fs::read_to_string(&key_path) { - Ok(pem) if cert_path.is_file() => KeyPair::from_pem(&pem).map_err(err)?, - _ => { - std::fs::create_dir_all(&dir)?; - std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; + let loaded = std::fs::read_to_string(&version_path) + .ok() + .filter(|v| v.trim() == CA_VERSION) + .and_then(|_| std::fs::read_to_string(&key_path).ok()) + .and_then(|pem| KeyPair::from_pem(&pem).ok()) + .and_then(|key| { + let pem = std::fs::read_to_string(&cert_path).ok()?; + let der = pem_to_der(&pem)?; + valid_ca_der(&der, &key).then_some((key, der)) + }); + let (key, der) = match loaded { + Some(pair) => pair, + None => { + std::fs::create_dir_all(dir)?; + std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; + let _ = std::fs::remove_file(&key_path); + let _ = std::fs::remove_file(&cert_path); + let _ = std::fs::remove_file(&version_path); let key = KeyPair::generate().map_err(err)?; let cert = ca_params().map_err(err)?.self_signed(&key).map_err(err)?; - let tmp = key_path.with_extension("tmp"); - std::fs::write(&tmp, key.serialize_pem())?; - std::fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(0o600))?; - std::fs::rename(&tmp, &key_path)?; - std::fs::write(&cert_path, cert.pem())?; + let cert_pem = cert.pem(); + let der = pem_to_der(&cert_pem).ok_or_else(|| io::Error::other("ca.pem is not a certificate"))?; + write_private_atomic(&key_path, key.serialize_pem().as_bytes())?; + let cert_tmp = cert_path.with_extension("pem.tmp"); + let _ = std::fs::remove_file(&cert_tmp); + std::fs::write(&cert_tmp, cert_pem)?; + std::fs::rename(&cert_tmp, &cert_path)?; std::fs::write(&version_path, CA_VERSION)?; - key + (key, der) } }; - let pem = std::fs::read_to_string(&cert_path)?; - let der = pem_to_der(&pem).ok_or_else(|| io::Error::other("ca.pem is not a certificate"))?; Ok((Issuer::new(ca_params().map_err(err)?, key), der)) } @@ -117,8 +157,19 @@ fn civil(days: i64) -> (i32, u8, u8) { /// Whether `host` is a name this authority may vouch for. pub fn ours(host: &str) -> bool { - let h = host.trim_end_matches('.').to_ascii_lowercase(); - SUFFIXES.iter().any(|s| h.ends_with(&format!(".{s}"))) && h.split('.').all(|l| !l.is_empty() && l.len() <= 63) + let h = host.strip_suffix('.').unwrap_or(host); + if h.is_empty() || h.len() > 253 { + return false; + } + let h = h.to_ascii_lowercase(); + SUFFIXES.iter().any(|s| h.ends_with(&format!(".{s}"))) + && h.split('.').all(|l| { + !l.is_empty() + && l.len() <= 63 + && !l.starts_with('-') + && !l.ends_with('-') + && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) } /// Certificates for container names, made on first use and kept while the @@ -431,9 +482,69 @@ mod tests { #[test] fn only_kiri_names() { assert!(super::ours("myapp.kiri.local")); + assert!(super::ours("myapp.kiri.local.")); assert!(super::ours("web.shop.kiri.localhost")); assert!(!super::ours("kiri.local")); assert!(!super::ours("example.com")); assert!(!super::ours("evil.kiri.local.example.com")); + for bad in [ + "*.kiri.local", + "-bad.kiri.local", + "bad-.kiri.local", + "foo/bar.kiri.local", + "myapp.kiri.local..", + &format!("{}.{}.{}.{}.kiri.localhost", "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(47)), + ] { + assert!(!super::ours(bad), "{bad}"); + } + } + + #[test] + fn authority_regenerates_damaged_or_mismatched_files_privately() { + use std::os::unix::fs::PermissionsExt; + let base = std::env::temp_dir().join(format!("kiri-tls-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("tls"); + std::fs::create_dir_all(&dir).unwrap(); + let sentinel = base.join("sentinel.txt"); + std::fs::write(&sentinel, "untouched").unwrap(); + std::os::unix::fs::symlink(&sentinel, dir.join("ca-key.tmp")).unwrap(); + + let (_, first_der) = super::authority_in(&dir).unwrap(); + assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "untouched"); + assert_eq!(std::fs::metadata(dir.join("ca-key.pem")).unwrap().permissions().mode() & 0o777, 0o600); + let (_, same_der) = super::authority_in(&dir).unwrap(); + assert_eq!(first_der.as_ref(), same_der.as_ref()); + + // Mismatched ca-key.pem with existing ca.pem + ca.version regenerates cleanly. + let other_key = rcgen::KeyPair::generate().unwrap(); + std::fs::write(dir.join("ca-key.pem"), other_key.serialize_pem()).unwrap(); + let (issuer, rotated_der) = super::authority_in(&dir).unwrap(); + assert_ne!(first_der.as_ref(), rotated_der.as_ref()); + + // Verify leaf certificate signed by `issuer` chains validly to `rotated_der`. + let leaf_key = rcgen::KeyPair::generate().unwrap(); + let leaf_params = rcgen::CertificateParams::new(vec!["myapp.kiri.local".into()]).unwrap(); + let leaf = leaf_params.signed_by(&leaf_key, &issuer).unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(rotated_der).unwrap(); + let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider()); + let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(std::sync::Arc::new(roots), provider).build().unwrap(); + rustls::client::danger::ServerCertVerifier::verify_server_cert( + &*verifier, + leaf.der(), + &[], + &rustls::pki_types::ServerName::try_from("myapp.kiri.local").unwrap(), + &[], + rustls::pki_types::UnixTime::now(), + ) + .unwrap(); + + // Empty ca.pem regenerates cleanly as well. + std::fs::write(dir.join("ca.pem"), "").unwrap(); + let (_, healed_der) = super::authority_in(&dir).unwrap(); + assert!(!healed_der.is_empty()); + + let _ = std::fs::remove_dir_all(&base); } } From dc0bfb1e0fc7a4f5a5e5ab5f57b8b0ae88fe2967 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:50:38 +0100 Subject: [PATCH 124/157] Images: omit untagged sha256 IDs on save and accept lowercase Bearer auth (#911) (#957) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri-image/src/archive.rs | 44 ++++++++++++++++++++++++++++++- crates/kiri-image/src/registry.rs | 8 +++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/kiri-image/src/archive.rs b/crates/kiri-image/src/archive.rs index d56940cc4..7145e446b 100644 --- a/crates/kiri-image/src/archive.rs +++ b/crates/kiri-image/src/archive.rs @@ -397,7 +397,11 @@ pub fn save(store: &Store, images: &[Image], out: impl Write) -> io::Result<()> let mut by_config: Vec<(&Image, Vec)> = Vec::new(); for i in images { match by_config.iter_mut().find(|(first, _)| first.config_digest == i.config_digest) { - Some((_, tags)) => tags.push(i.name.clone()), + Some((_, tags)) => { + if !i.name.starts_with("sha256:") { + tags.push(i.name.clone()); + } + } None => by_config.push((i, if i.name.starts_with("sha256:") { vec![] } else { vec![i.name.clone()] })), } } @@ -1177,4 +1181,42 @@ mod tests { } std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn failed_loads_remove_ingested_blobs_and_save_skips_untagged_ids() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + for (name, body) in [("layer1.tar", &b"one"[..]), ("layer2.tar", &b"two"[..])] { + let mut h = tar::Header::new_ustar(); + h.set_size(body.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, name, body).unwrap(); + } + let mut cut = b.into_inner().unwrap(); + cut.truncate(512 + 300); + assert!(load(&store, cut.as_slice()).is_err()); + assert_eq!(std::fs::read_dir(dir.join("blobs/sha256")).unwrap().count(), 0); + + let put = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let cfg = json!({"os": "linux", "architecture": "arm64", "config": {}}); + let (cfg_digest, _) = put(&serde_json::to_vec(&cfg).unwrap()); + let (layer, size) = put(b"layer"); + let layers = vec![Layer { digest: layer, size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }]; + let named = from_config("demo:1".into(), &cfg_digest, &cfg, layers.clone()); + let untagged = from_config(cfg_digest.clone(), &cfg_digest, &cfg, layers); + let mut tarball = Vec::new(); + save(&store, &[named, untagged], &mut tarball).unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + let loaded = load(&other, tarball.as_slice()).unwrap(); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].name, "demo:1"); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 28d6bf3ac..40f78bc48 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -1894,7 +1894,10 @@ fn printable(text: &str) -> String { /// Parses `Bearer realm="…",service="…",scope="…"`. fn parse_challenge(header: &str) -> HashMap { - let rest = header.strip_prefix("Bearer ").unwrap_or(header); + let rest = match header.get(..7) { + Some(p) if p.eq_ignore_ascii_case("bearer ") => &header[7..], + _ => header, + }; let mut out = HashMap::new(); let mut s = rest; while let Some(eq) = s.find('=') { @@ -2278,6 +2281,9 @@ mod tests { assert_eq!(p["realm"], "https://auth.docker.io/token"); assert_eq!(p["service"], "registry.docker.io"); assert_eq!(p["scope"], "repository:library/alpine:pull"); + let lower = parse_challenge(r#"bearer realm="https://ghcr.io/token",service="ghcr.io""#); + assert_eq!(lower["realm"], "https://ghcr.io/token"); + assert_eq!(lower["service"], "ghcr.io"); } #[test] From 9af5ae5b802174024ccec9207e8e028d0274a7f6 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:14:20 +0100 Subject: [PATCH 125/157] VM: swap on the data disk, 1 GiB by default, set in Settings -> Resources (#326) (#958) Co-authored-by: Masih Moloodian --- crates/kiri-init/src/linux/mod.rs | 3 + crates/kiri-init/src/linux/swap.rs | 206 +++++++++++++++++++++++++++ crates/kiri/src/daemon/api.rs | 54 ++++++- crates/kiri/src/daemon/engine.rs | 41 +++++- crates/kiri/src/guest.rs | 7 + crates/kiri/src/ui/index.html | 18 ++- crates/kiri/src/ui/lang/am.json | 4 +- crates/kiri/src/ui/lang/ar.json | 4 +- crates/kiri/src/ui/lang/bg.json | 4 +- crates/kiri/src/ui/lang/bn.json | 4 +- crates/kiri/src/ui/lang/ca.json | 4 +- crates/kiri/src/ui/lang/ckb.json | 4 +- crates/kiri/src/ui/lang/cs.json | 4 +- crates/kiri/src/ui/lang/de.json | 4 +- crates/kiri/src/ui/lang/el.json | 4 +- crates/kiri/src/ui/lang/es.json | 4 +- crates/kiri/src/ui/lang/fa.json | 4 +- crates/kiri/src/ui/lang/fi.json | 4 +- crates/kiri/src/ui/lang/fr.json | 4 +- crates/kiri/src/ui/lang/hi.json | 4 +- crates/kiri/src/ui/lang/hu.json | 4 +- crates/kiri/src/ui/lang/id.json | 4 +- crates/kiri/src/ui/lang/it.json | 4 +- crates/kiri/src/ui/lang/ja.json | 4 +- crates/kiri/src/ui/lang/kk.json | 4 +- crates/kiri/src/ui/lang/ko.json | 4 +- crates/kiri/src/ui/lang/lo.json | 4 +- crates/kiri/src/ui/lang/lt.json | 4 +- crates/kiri/src/ui/lang/nb.json | 4 +- crates/kiri/src/ui/lang/pl.json | 4 +- crates/kiri/src/ui/lang/pt-BR.json | 4 +- crates/kiri/src/ui/lang/ro.json | 4 +- crates/kiri/src/ui/lang/ru.json | 4 +- crates/kiri/src/ui/lang/sl.json | 4 +- crates/kiri/src/ui/lang/sq.json | 4 +- crates/kiri/src/ui/lang/ta.json | 4 +- crates/kiri/src/ui/lang/te.json | 4 +- crates/kiri/src/ui/lang/th.json | 4 +- crates/kiri/src/ui/lang/tr.json | 4 +- crates/kiri/src/ui/lang/uk.json | 4 +- crates/kiri/src/ui/lang/vi.json | 4 +- crates/kiri/src/ui/lang/zh-Hans.json | 4 +- crates/kiri/src/ui/lang/zh-Hant.json | 4 +- docs/development.md | 5 + docs/features.md | 6 +- tests/e2e.sh | 12 ++ tests/regressions.tsv | 2 + tests/ui/resources-swap.js | 72 ++++++++++ 48 files changed, 523 insertions(+), 51 deletions(-) create mode 100644 crates/kiri-init/src/linux/swap.rs create mode 100644 tests/ui/resources-swap.js diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index 6df6e9879..3118c1fbd 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -18,6 +18,7 @@ mod pid1; mod relay; mod roots; mod seccomp; +mod swap; mod sys; mod tarnum; mod transport; @@ -676,6 +677,8 @@ fn data_dirs() -> io::Result { // Overlay lower dirs are given relative to the layer store. std::env::set_current_dir(&paths.layers)?; if disk.is_ok() { + // On the data disk only: swap in the tmpfs fallback would be memory. + swap::start(); trim::start(DATA); } Ok(paths) diff --git a/crates/kiri-init/src/linux/swap.rs b/crates/kiri-init/src/linux/swap.rs new file mode 100644 index 000000000..f6c84e40c --- /dev/null +++ b/crates/kiri-init/src/linux/swap.rs @@ -0,0 +1,206 @@ +//! The VM's swap (#326): a file on the data disk, the size the host names +//! on the kernel command line (`kiri.swap=`). Docker Desktop gives its +//! VM 1 GiB the same way; without it a container that outgrows the VM's +//! memory is killed even when its pages could wait on disk. zswap is on in +//! the kernel, so pages are compressed in memory first, and its shrinker +//! moves them on to the file. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::Path; + +/// Where the swap file lives: the data disk's top, beside `layers` and +/// `containers`, so nothing that sweeps those touches it. +pub(super) const FILE: &str = "/var/lib/kiri/swapfile"; + +/// ``: freed swap pages are discarded, so the Mac's sparse +/// disk image gets their space back as for trimmed ext4 blocks. +const SWAP_FLAG_DISCARD: libc::c_int = 0x10000; + +/// Lets zswap write cold pages out to the swap file under memory pressure. +const ZSWAP_SHRINKER: &str = "/sys/module/zswap/parameters/shrinker_enabled"; + +/// The size the host asked for, in MiB, from the kernel command line. None +/// when it said nothing (an older host): the file is then left as it is. +pub(super) fn requested(cmdline: &str) -> Option { + cmdline.split_ascii_whitespace().filter_map(|a| a.strip_prefix("kiri.swap=")).next_back().and_then(|v| v.parse().ok()) +} + +/// Reads the command line and keeps the swap file as asked; only says why +/// on the console if it can't, since the VM runs without swap all the same. +pub(super) fn start() { + let Some(mib) = fs::read_to_string("/proc/cmdline").ok().as_deref().and_then(requested) else { return }; + // SAFETY: sysconf has no preconditions. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap_or(4096); + let path = Path::new(FILE); + match ensure(path, mib, page) { + Ok(false) => {} + Ok(true) => { + if let Err(e) = swapon(path) { + // A file that is not fit for swap (holes, a header the + // kernel refuses) is made again once. + let _ = fs::remove_file(path); + if let Err(e2) = ensure(path, mib, page).and_then(|_| swapon(path)) { + let _ = fs::remove_file(path); + eprintln!("kiri-init: no swap ({e}; again: {e2})"); + return; + } + } + // zswap keeps swapped pages compressed in memory, charged to the + // container. Without its shrinker they never reach the file, and + // a container over its `--memory` is killed with its swap unused. + if let Err(e) = super::sys::write_file(ZSWAP_SHRINKER, "Y") { + eprintln!("kiri-init: zswap's shrinker stays off ({e}); swap may fill memory first"); + } + } + Err(e) => { + let _ = fs::remove_file(path); + eprintln!("kiri-init: no swap of {mib} MiB ({e})"); + } + } +} + +/// Makes `path` a swap file of `mib` MiB, keeping one already that size, +/// or removes it for 0. Returns whether there is a swap file to turn on. +pub(super) fn ensure(path: &Path, mib: u64, page: usize) -> io::Result { + if mib == 0 { + return match fs::remove_file(path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(false), + }; + } + let len = mib.checked_shl(20).ok_or_else(|| io::Error::from_raw_os_error(libc::EFBIG))?; + if len < (page as u64).saturating_mul(10) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "swap file smaller than kernel minimum (10 pages)")); + } + if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file() && m.len() == len && (m.permissions().mode() & 0o777) == 0o600) + && has_header(path, page) + { + return Ok(true); + } + let _ = fs::remove_file(path); + // Only root may read it: swapped pages are any container's memory. + let f = OpenOptions::new().write(true).create_new(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(path)?; + // Real blocks, not a sparse file: the kernel refuses swap with holes. + // ext4 marks them unwritten, so no zeros go to the Mac's disk. + let size = libc::off_t::try_from(len).map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?; + // SAFETY: fallocate on a descriptor this function owns. + if unsafe { libc::fallocate(f.as_raw_fd(), 0, 0, size) } != 0 { + return Err(io::Error::last_os_error()); + } + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + write_header(&f, len, page)?; + f.sync_all()?; + Ok(true) +} + +/// mkswap's header, version 1: the page count at 1028 and the magic at the +/// end of the first page. +pub(super) fn header(len: u64, page: usize) -> Vec { + let mut h = vec![0u8; page]; + let last_page = u32::try_from((len / page as u64).saturating_sub(1)).unwrap_or(u32::MAX); + h[1024..1028].copy_from_slice(&1u32.to_ne_bytes()); + h[1028..1032].copy_from_slice(&last_page.to_ne_bytes()); + h[page - 10..].copy_from_slice(b"SWAPSPACE2"); + h +} + +fn write_header(mut f: &File, len: u64, page: usize) -> io::Result<()> { + f.seek(SeekFrom::Start(0))?; + f.write_all(&header(len, page)) +} + +/// Whether the regular file starts with a swap header for this page size. +fn has_header(path: &Path, page: usize) -> bool { + let mut h = vec![0u8; page]; + OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .and_then(|mut f| f.read_exact(&mut h)) + .is_ok() + && &h[page - 10..] == b"SWAPSPACE2" +} + +fn swapon(path: &Path) -> io::Result<()> { + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(io::Error::other)?; + // SAFETY: a NUL-terminated path and flags; the kernel reads nothing else. + if unsafe { libc::swapon(c.as_ptr(), SWAP_FLAG_DISCARD) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_size_comes_from_the_kernel_command_line() { + assert_eq!(requested("console=hvc0 rdinit=/init kiri.swap=1024 quiet"), Some(1024)); + assert_eq!(requested("kiri.swap=0"), Some(0)); + assert_eq!(requested("kiri.swap=512 kiri.swap=2048"), Some(2048), "the last one counts, as for the kernel's own"); + assert_eq!(requested("console=hvc0 quiet"), None, "an older host says nothing"); + assert_eq!(requested("kiri.swap=lots"), None); + assert_eq!(requested("kiri.swapfile=1"), None); + } + + #[test] + fn the_header_is_mkswaps() { + for page in [4096, 16384] { + let h = header(1 << 30, page); + assert_eq!(h.len(), page); + assert_eq!(&h[1024..1028], &1u32.to_ne_bytes(), "version 1"); + assert_eq!(u32::from_ne_bytes(h[1028..1032].try_into().unwrap()) as u64, (1u64 << 30) / page as u64 - 1, "last page"); + assert_eq!(&h[1032..1036], &[0; 4], "no bad pages"); + assert_eq!(&h[page - 10..], b"SWAPSPACE2"); + } + } + + #[test] + fn the_file_is_made_kept_resized_and_removed() { + let dir = std::env::temp_dir().join(format!("kiri-swap-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let path = dir.join("swapfile"); + let page = 4096; + + assert!(ensure(&path, 2, page).unwrap()); + let m = fs::metadata(&path).unwrap(); + assert_eq!(m.len(), 2 << 20); + assert_eq!(m.permissions().mode() & 0o777, 0o600, "only root reads swapped memory"); + assert!(has_header(&path, page)); + use std::os::unix::fs::MetadataExt; + assert!(m.blocks() * 512 >= 2 << 20, "allocated, not sparse: the kernel refuses holes"); + + // The same size is kept as it is (its inode too). + let ino = m.ino(); + assert!(ensure(&path, 2, page).unwrap()); + assert_eq!(fs::metadata(&path).unwrap().ino(), ino); + + // A new size, or a file with no header, is made again. + assert!(ensure(&path, 3, page).unwrap()); + assert_eq!(fs::metadata(&path).unwrap().len(), 3 << 20); + fs::write(&path, vec![0u8; 3 << 20]).unwrap(); + assert!(ensure(&path, 3, page).unwrap()); + assert!(has_header(&path, page)); + + // A symlink at `path` is never followed; it is replaced by a real 0600 file. + let target = dir.join("decoy"); + fs::write(&target, vec![0u8; 3 << 20]).unwrap(); + let _ = fs::remove_file(&path); + std::os::unix::fs::symlink(&target, &path).unwrap(); + assert!(ensure(&path, 3, page).unwrap()); + assert!(fs::symlink_metadata(&path).unwrap().file_type().is_file()); + assert!(!has_header(&target, page), "decoy target was never written"); + + // 0: no swap file, and none is fine too. + assert!(!ensure(&path, 0, page).unwrap()); + assert!(!path.exists()); + assert!(!ensure(&path, 0, page).unwrap()); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 632badde0..1f8c6e180 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -1039,8 +1039,8 @@ fn resources(engine: &Engine) -> Value { let disk: Option<(u64, u64, u64)> = None; let overridden = std::env::var_os("KIRI_CPUS").is_some() || std::env::var_os("KIRI_MEMORY_MIB").is_some() - || (cfg!(target_os = "macos") && std::env::var_os("KIRI_DISK_GB").is_some()); - resources_payload( + || (cfg!(target_os = "macos") && (std::env::var_os("KIRI_DISK_GB").is_some() || std::env::var_os("KIRI_SWAP_MIB").is_some())); + let mut v = resources_payload( e::vm_cpus(), e::memory_ceiling() >> 20, engine.cpus(), @@ -1050,7 +1050,19 @@ fn resources(engine: &Engine) -> Value { e::physical_memory_bytes() >> 20, overridden, disk, - ) + ); + // Swap is the VM's, on its data disk: a Linux host has its own. + if cfg!(target_os = "macos") { + swap_payload(&mut v, e::vm_swap_mib(), engine.swap_mib()); + } + v +} + +/// The swap the VM boots with next, what it has now, and the most it may have. +fn swap_payload(v: &mut Value, swap_mib: u64, running_swap_mib: u64) { + v["swap_mib"] = json!(swap_mib); + v["running_swap_mib"] = json!(running_swap_mib); + v["max_swap_mib"] = json!(super::engine::MAX_SWAP_MIB); } #[allow(clippy::too_many_arguments)] @@ -1214,6 +1226,12 @@ fn save_resources( .unwrap_or_else(|| json!({})); out["cpus"] = json!(cpus); out["memory_mib"] = json!(mem); + // Left out, the saved swap stays (#326). + if let Some(val) = body.get("swap_mib").filter(|v| !v.is_null()) { + let max = super::engine::MAX_SWAP_MIB; + let swap = val.as_u64().filter(|s| *s <= max).ok_or_else(|| Error::BadRequest(format!("swap_mib must be 0 to {max}")))?; + out["swap_mib"] = json!(swap); + } if let Some(val) = body.get("disk_gb").filter(|v| !v.is_null()) { let current = current_disk_gb.unwrap_or(crate::guest::disk::DEFAULT_GB); let (min_disk, max_disk) = crate::guest::disk::ui_bounds(current, existing_disk_gb.unwrap_or(current)); @@ -8146,4 +8164,34 @@ mod resources_disk_tests { let _ = std::fs::remove_dir_all(&root); } + + /// Settings → Resources keeps the VM's swap (#326): 0 to 16 GiB, kept + /// when a save leaves it out. + #[test] + fn swap_is_saved_checked_and_kept() { + let dir = std::env::temp_dir().join(format!("kiri-res-swap-{}", std::process::id())); + let path = dir.join("vm.json"); + let _ = std::fs::remove_dir_all(&dir); + let save = |body: Value| save_resources(body.to_string().as_bytes(), &path, 12, 32768, Some(64), None, None); + let saved = || serde_json::from_slice::(&std::fs::read(&path).unwrap()).unwrap(); + + save(json!({"cpus": 4, "memory_mib": 8192, "swap_mib": 2048})).unwrap(); + assert_eq!(saved()["swap_mib"], 2048); + save(json!({"cpus": 4, "memory_mib": 4096})).unwrap(); + assert_eq!(saved()["swap_mib"], 2048, "left out, the swap stays"); + save(json!({"cpus": 4, "memory_mib": 4096, "swap_mib": 0})).unwrap(); + assert_eq!(saved()["swap_mib"], 0, "0 is no swap"); + for bad in [json!(-1), json!(16 * 1024 + 1), json!("1024"), json!(1.5)] { + match save(json!({"cpus": 4, "memory_mib": 4096, "swap_mib": bad})) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("swap_mib must be 0 to 16384"), "{msg}"), + other => panic!("expected BadRequest for {bad}, got {other:?}"), + } + } + assert_eq!(saved()["swap_mib"], 0, "a refused save changes nothing"); + + let mut v = json!({}); + swap_payload(&mut v, 2048, 1024); + assert_eq!(v, json!({"swap_mib": 2048, "running_swap_mib": 1024, "max_swap_mib": 16384})); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 431bd6ee8..790e082e2 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -427,6 +427,20 @@ pub fn shared_nat() -> bool { shared_nat_for(env.as_deref(), vm_shared_nat_config()) } +/// The most swap Settings → Resources offers, in MiB. +pub const MAX_SWAP_MIB: u64 = 16 << 10; + +/// The VM's swap file on its data disk, in MiB (#326): `KIRI_SWAP_MIB`, +/// else Settings → Resources (`vm.json`'s `swap_mib`), else 1 GiB, as +/// Docker Desktop has. 0 is no swap. +pub fn vm_swap_mib() -> u64 { + swap_mib_for(std::env::var("KIRI_SWAP_MIB").ok().as_deref(), resources()["swap_mib"].as_u64()) +} + +pub fn swap_mib_for(env: Option<&str>, configured: Option) -> u64 { + env.and_then(|v| v.trim().parse().ok()).or(configured).unwrap_or(1024).min(MAX_SWAP_MIB) +} + /// Configured `balloon` from `vm.json`, if present. pub fn vm_balloon_config() -> Option { resources()["balloon"].as_bool() @@ -1687,6 +1701,8 @@ pub struct Engine { cpus: std::sync::atomic::AtomicUsize, /// Data disk capacity in GiB the running VM booted with (macOS). disk_gb: std::sync::atomic::AtomicU64, + /// Swap in MiB the running VM booted with (macOS). + swap_mib: std::sync::atomic::AtomicU64, /// Whether the running macOS VM booted with `VZNATNetworkDeviceAttachment`. shared_nat: std::sync::atomic::AtomicBool, /// Whether the running macOS VM dynamically adjusts its memory balloon @@ -1863,6 +1879,7 @@ impl Engine { ceiling: std::sync::atomic::AtomicU64::new(ceiling), cpus: std::sync::atomic::AtomicUsize::new(vm_cpus()), disk_gb: std::sync::atomic::AtomicU64::new(vm_disk_gb()), + swap_mib: std::sync::atomic::AtomicU64::new(vm_swap_mib()), shared_nat: std::sync::atomic::AtomicBool::new(shared_nat()), balloon_enabled: std::sync::atomic::AtomicBool::new(balloon_enabled()), memory_min: std::sync::atomic::AtomicU64::new(memory_min_bytes(ceiling)), @@ -2040,10 +2057,11 @@ impl Engine { if recovery && !self.lock().containers.values().any(recover_after_vm_loss) { return Err(io::Error::new(io::ErrorKind::WouldBlock, "VM recovery was canceled")); } - let (ceiling, cpus, disk_cfg, shared_nat, balloon) = (memory_ceiling(), vm_cpus(), vm_disk_gb_config(), shared_nat(), balloon_enabled()); + let (ceiling, cpus, disk_cfg, shared_nat, balloon, swap) = (memory_ceiling(), vm_cpus(), vm_disk_gb_config(), shared_nat(), balloon_enabled(), vm_swap_mib()); let memory_min = memory_min_bytes(ceiling); self.ceiling.store(ceiling, std::sync::atomic::Ordering::Relaxed); self.cpus.store(cpus, std::sync::atomic::Ordering::Relaxed); + self.swap_mib.store(swap, std::sync::atomic::Ordering::Relaxed); self.shared_nat.store(shared_nat, std::sync::atomic::Ordering::Relaxed); self.balloon_enabled.store(balloon, std::sync::atomic::Ordering::Relaxed); self.memory_min.store(memory_min, std::sync::atomic::Ordering::Relaxed); @@ -2058,6 +2076,7 @@ impl Engine { cpus: Some(cpus), disk_gb: disk_cfg, shared_nat: Some(shared_nat), + swap_mib: Some(swap), ..Default::default() }) .map_err(|e| match self.storage_readonly() { @@ -2667,6 +2686,11 @@ impl Engine { self.disk_gb.load(std::sync::atomic::Ordering::Relaxed) } + /// Swap in MiB the VM has (or will boot with). + pub fn swap_mib(&self) -> u64 { + self.swap_mib.load(std::sync::atomic::Ordering::Relaxed) + } + /// Whether the running macOS VM booted with `VZNATNetworkDeviceAttachment`. #[allow(dead_code)] pub fn shared_nat(&self) -> bool { @@ -6512,7 +6536,7 @@ mod memory_target_tests { use std::time::{Duration, Instant}; use super::{ - balloon_enabled_for, boot_without_vm, estimate_used, memory_floor, memory_headroom, memory_min_bytes_for, next_memory_target, BalloonPolicy, + balloon_enabled_for, boot_without_vm, swap_mib_for, MAX_SWAP_MIB, estimate_used, memory_floor, memory_headroom, memory_min_bytes_for, next_memory_target, BalloonPolicy, BalloonState, MemorySample, MEMORY_DEADBAND, MEMORY_FLOOR_ACTIVE_MIN, MEMORY_FLOOR_IDLE, MEMORY_GROW, MEMORY_HEADROOM_MAX, MEMORY_HEADROOM_MIN, MEMORY_SHRINK_STEP, SHRINK_COOLDOWN, WS_PEAK_DECAY_INTERVAL, WS_PEAK_DECAY_STEP, }; @@ -7103,6 +7127,19 @@ mod memory_target_tests { assert_eq!(settle_guest_with(clamped_ceiling, MEM_TOTAL, USED, 200 * MIB, None), CEILING); } + /// The VM's swap (#326): `KIRI_SWAP_MIB`, else `vm.json`, else 1 GiB + /// as in Docker Desktop, never above the most Settings offers. + #[test] + fn swap_is_the_environment_then_the_setting_then_one_gib() { + assert_eq!(swap_mib_for(None, None), 1024); + assert_eq!(swap_mib_for(None, Some(0)), 0); + assert_eq!(swap_mib_for(None, Some(4096)), 4096); + assert_eq!(swap_mib_for(Some("512"), Some(4096)), 512); + assert_eq!(swap_mib_for(Some(" 0 "), None), 0); + assert_eq!(swap_mib_for(Some("lots"), Some(2048)), 2048, "an unreadable variable is ignored"); + assert_eq!(swap_mib_for(None, Some(1 << 30)), MAX_SWAP_MIB); + } + /// `"balloon": false` in `vm.json` and `KIRI_NO_BALLOON=1` disable /// `vm.set_memory_target(...)` while keeping `vm.stats()` telemetry /// (`memory_used`, `mem_available_kib`, `memory_stall`, `oom_kills`) live. diff --git a/crates/kiri/src/guest.rs b/crates/kiri/src/guest.rs index 239e3b76e..e7a454585 100644 --- a/crates/kiri/src/guest.rs +++ b/crates/kiri/src/guest.rs @@ -76,6 +76,9 @@ pub struct BootOptions { /// Whether to attach `VZNATNetworkDeviceAttachment` (`InternetSharing`) on /// macOS (`None` reads `KIRI_SHARED_NAT` / `vm.json`'s `shared_nat`). pub shared_nat: Option, + /// The swap file the guest keeps on the data disk, in MiB; 0 removes + /// it, and `None` leaves it as it is. + pub swap_mib: Option, } fn console_output(opts: &BootOptions) -> io::Result> { @@ -181,6 +184,10 @@ impl Guest { // Keep warnings and oopses even in release builds. cmdline.push_str(" quiet loglevel=4"); } + // How much swap the agent keeps on the data disk (#326). + if let Some(mib) = opts.swap_mib.filter(|_| opts.data_disk) { + cmdline.push_str(&format!(" kiri.swap={mib}")); + } let shared_nat = opts.shared_nat.unwrap_or_else(crate::daemon::engine::shared_nat); let cfg = Config { cpus: opts.cpus.unwrap_or(2), diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 5d4cb4189..31ab8f21b 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4542,13 +4542,14 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const gb = (mib) => `${Math.round(mib / 1024)} GB`; const diskGb = (g) => `${g} GB`; const cpuText = (n) => trn(n, "{n} CPU", "{n} CPUs"); +const swapText = (mib) => mib ? (mib % 1024 ? `${(mib / 1024).toFixed(1)} GB` : gb(mib)) : tr("Off"); /* How far along its track a slider's blue fill reaches, as CSS: to the middle of the thumb, which travels the track less its own 26 px. */ const rangeFill = (v, min, max) => { const f = max > min ? (v - min) / (max - min) : 0; return `calc(13px + (100% - 26px) * ${f.toFixed(4)})`; }; -const resChanged = () => ui.res && (ui.resDraft.cpus !== ui.res.cpus || ui.resDraft.memory_mib !== ui.res.memory_mib || (ui.res.disk_gb != null && ui.resDraft.disk_gb !== ui.res.disk_gb)); +const resChanged = () => ui.res && (ui.resDraft.cpus !== ui.res.cpus || ui.resDraft.memory_mib !== ui.res.memory_mib || (ui.res.disk_gb != null && ui.resDraft.disk_gb !== ui.res.disk_gb) || (ui.res.swap_mib != null && ui.resDraft.swap_mib !== ui.res.swap_mib)); /* Settings › Resources: the engine's on/off, the same switch as the card. */ function enginePane() { const { shown } = engineShown(), off = shown === "stopped"; @@ -4573,12 +4574,17 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const maxDisk = Math.max(minDisk, r.max_disk_gb ?? 1024); const diskVal = hasDisk ? Math.min(Math.max(d.disk_gb ?? r.disk_gb, minDisk), maxDisk) : minDisk; const diskStep = minDisk % 8 === 0 && diskVal % 8 === 0 && maxDisk % 8 === 0 ? 8 : 1; - const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64 || (hasDisk && r.running_disk_gb != null && r.running_disk_gb !== r.disk_gb)); + const hasSwap = r.swap_mib != null; + const maxSwap = r.max_swap_mib ?? 16384; + const swapVal = hasSwap ? Math.min(d.swap_mib ?? r.swap_mib, maxSwap) : 0; + const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64 || (hasDisk && r.running_disk_gb != null && r.running_disk_gb !== r.disk_gb) || (hasSwap && r.running_swap_mib != null && r.running_swap_mib !== r.swap_mib)); return `

${tr("Resources")}

${tr("CPUs")}${LINUX ? tr("Shared with Linux: containers only use them while busy.") : tr("Shared with {os}: the VM only uses them while containers are busy.", { os: OS })}
${cpuText(d.cpus)}
${tr("Memory")}${LINUX ? tr("The most containers and the engine may take. Unused memory stays free on Linux.") : tr("The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.", { os: OS })}
${gb(d.memory_mib)}
+ ${hasSwap ? `
${tr("Swap")}${tr("Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.")} +
${swapText(swapVal)}
` : ""} ${hasDisk ? `
${tr("Disk image size")}${tr("The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.", { os: OS, storage: `` })}
${diskGb(diskVal)}
` : ""} ${r.overridden ? `

${hasDisk ? tr("KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.") : tr("KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.")}

` : ""} @@ -4944,11 +4950,11 @@

${tr("Storage location unavailable")}

const go = document.querySelector("#content [data-impgo]"), n = importCount(); if (go) { go.disabled = !n; go.textContent = n ? trn(n, "Import {n} item", "Import {n} items") : tr("Import"); } })); - for (const id of ["res-cpus", "res-mem", "res-disk"]) $(id)?.addEventListener("input", (ev) => { + for (const id of ["res-cpus", "res-mem", "res-disk", "res-swap"]) $(id)?.addEventListener("input", (ev) => { const v = +ev.target.value; - ui.resDraft[id === "res-cpus" ? "cpus" : id === "res-mem" ? "memory_mib" : "disk_gb"] = v; + ui.resDraft[{ "res-cpus": "cpus", "res-mem": "memory_mib", "res-disk": "disk_gb", "res-swap": "swap_mib" }[id]] = v; ev.target.style.setProperty("--fill", rangeFill(v, +ev.target.min, +ev.target.max)); - $(`${id}-v`).textContent = id === "res-cpus" ? cpuText(v) : id === "res-mem" ? gb(v) : diskGb(v); + $(`${id}-v`).textContent = id === "res-cpus" ? cpuText(v) : id === "res-mem" ? gb(v) : id === "res-swap" ? swapText(v) : diskGb(v); $("res-save").disabled = !resChanged(); }); $("pref-font")?.addEventListener("change", (ev) => setPref("font", ev.target.value)); @@ -8664,7 +8670,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (ui.view === "settings") render(); break; } - case "resources": ui.res = e; if (e.watch_bind_mounts != null && prefs.watchBindMounts == null) prefs.watchBindMounts = !!e.watch_bind_mounts; ui.resDraft = { cpus: e.cpus, memory_mib: e.memory_mib, ...(e.disk_gb != null ? { disk_gb: e.disk_gb } : {}) }; if (ui.view === "settings") render(); break; + case "resources": ui.res = e; if (e.watch_bind_mounts != null && prefs.watchBindMounts == null) prefs.watchBindMounts = !!e.watch_bind_mounts; ui.resDraft = { cpus: e.cpus, memory_mib: e.memory_mib, ...(e.disk_gb != null ? { disk_gb: e.disk_gb } : {}), ...(e.swap_mib != null ? { swap_mib: e.swap_mib } : {}) }; if (ui.view === "settings") render(); break; case "storage": { const wasUnavail = ui.storage?.state === "unavailable"; ui.storage = e; diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index 3def09c72..effee4283 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "የሼል ፕሮፋይሎችን ማዘመን አልተቻለም፦ {error}", "Uninstalling Kiri…": "Kiriን በማራገፍ ላይ…", "Could not uninstall Kiri: {error}": "Kiriን ማራገፍ አልተቻለም፦ {error}", - "Uninstall Kiri using your system package manager": "የሥርዓትዎን የጥቅል አስተዳዳሪ በመጠቀም Kiriን ያራግፉ" + "Uninstall Kiri using your system package manager": "የሥርዓትዎን የጥቅል አስተዳዳሪ በመጠቀም Kiriን ያራግፉ", + "Swap": "ስዋፕ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "የVM ማህደረ ትውስታ ሲያልቅ VM ሊጠቀምበት የሚችል የዲስክ ቦታ፣ ስለዚህ ኮንቴይነሮች ከመቆም ይልቅ ይዘገያሉ። ዳግም ሲጀመር ይተገበራል።" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index d72f5a2e7..3326dc3b5 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "تعذر تحديث ملفات تعريف الصدفة: {error}", "Uninstalling Kiri…": "جارٍ إزالة تثبيت Kiri…", "Could not uninstall Kiri: {error}": "تعذرت إزالة تثبيت Kiri: {error}", - "Uninstall Kiri using your system package manager": "أزِل تثبيت Kiri باستخدام مدير الحزم في نظامك" + "Uninstall Kiri using your system package manager": "أزِل تثبيت Kiri باستخدام مدير الحزم في نظامك", + "Swap": "التبديل (Swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "مساحة على القرص يمكن للجهاز الافتراضي استخدامها عند نفاد ذاكرته، فتتباطأ الحاويات بدلًا من إيقافها. يُطبَّق عند إعادة التشغيل." } diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 675f26431..8d4866ad5 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Неуспешно обновяване на профилите на обвивката: {error}", "Uninstalling Kiri…": "Деинсталиране на Kiri…", "Could not uninstall Kiri: {error}": "Неуспешно деинсталиране на Kiri: {error}", - "Uninstall Kiri using your system package manager": "Деинсталирайте Kiri чрез пакетния мениджър на системата си" + "Uninstall Kiri using your system package manager": "Деинсталирайте Kiri чрез пакетния мениджър на системата си", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Дисково пространство, което VM може да използва, когато паметта ѝ свърши, така че контейнерите да се забавят, вместо да бъдат спрени. Прилага се при рестартиране." } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 695d4cc4b..596b26e2e 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "শেল প্রোফাইল আপডেট করা যায়নি: {error}", "Uninstalling Kiri…": "Kiri আনইনস্টল হচ্ছে…", "Could not uninstall Kiri: {error}": "Kiri আনইনস্টল করা যায়নি: {error}", - "Uninstall Kiri using your system package manager": "আপনার সিস্টেমের প্যাকেজ ম্যানেজার দিয়ে Kiri আনইনস্টল করুন" + "Uninstall Kiri using your system package manager": "আপনার সিস্টেমের প্যাকেজ ম্যানেজার দিয়ে Kiri আনইনস্টল করুন", + "Swap": "সোয়াপ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "মেমরি ফুরিয়ে গেলে VM যে ডিস্ক স্পেস ব্যবহার করতে পারে, ফলে কন্টেইনার বন্ধ না হয়ে ধীর হয়ে যায়। রিস্টার্টে প্রযোজ্য হয়।" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index 34cb18bea..ac4e8adda 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "No s'han pogut actualitzar els perfils de l'intèrpret: {error}", "Uninstalling Kiri…": "S'està desinstal·lant Kiri…", "Could not uninstall Kiri: {error}": "No s'ha pogut desinstal·lar Kiri: {error}", - "Uninstall Kiri using your system package manager": "Desinstal·la Kiri amb el gestor de paquets del sistema" + "Uninstall Kiri using your system package manager": "Desinstal·la Kiri amb el gestor de paquets del sistema", + "Swap": "Intercanvi (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espai de disc que la VM pot fer servir quan se li acaba la memòria, perquè els contenidors s’alenteixin en lloc d’aturar-se. S’aplica en reiniciar." } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index abcc03323..df0e8f10f 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "نەتوانرا پرۆفایلەکانی شێڵ نوێ بکرێنەوە: {error}", "Uninstalling Kiri…": "سڕینەوەی Kiri…", "Could not uninstall Kiri: {error}": "نەتوانرا Kiri بسڕدرێتەوە: {error}", - "Uninstall Kiri using your system package manager": "Kiri بە بەڕێوەبەری پاکێجی سیستەمەکەت بسڕەوە" + "Uninstall Kiri using your system package manager": "Kiri بە بەڕێوەبەری پاکێجی سیستەمەکەت بسڕەوە", + "Swap": "سواپ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "شوێنی دیسک کە VM دەتوانێت بەکاری بهێنێت کاتێک بیرگەکەی تەواو دەبێت، بۆ ئەوەی کۆنتەینەرەکان خاو ببنەوە لەجیاتی ڕاگیران. لە دەستپێکردنەوەدا جێبەجێ دەبێت." } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index 6dfd5f055..a3d585cb2 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Profily shellu se nepodařilo aktualizovat: {error}", "Uninstalling Kiri…": "Odinstalovávání Kiri…", "Could not uninstall Kiri: {error}": "Kiri se nepodařilo odinstalovat: {error}", - "Uninstall Kiri using your system package manager": "Odinstalujte Kiri pomocí správce balíčků vašeho systému" + "Uninstall Kiri using your system package manager": "Odinstalujte Kiri pomocí správce balíčků vašeho systému", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Místo na disku, které VM může použít, když jí dojde paměť, takže se kontejnery zpomalí, místo aby byly zastaveny. Projeví se po restartu." } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index a9e47500c..b7a2e291f 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Shell-Profile konnten nicht aktualisiert werden: {error}", "Uninstalling Kiri…": "Kiri wird deinstalliert…", "Could not uninstall Kiri: {error}": "Kiri konnte nicht deinstalliert werden: {error}", - "Uninstall Kiri using your system package manager": "Deinstalliere Kiri über die Paketverwaltung deines Systems" + "Uninstall Kiri using your system package manager": "Deinstalliere Kiri über die Paketverwaltung deines Systems", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Speicherplatz auf der Festplatte, den die VM nutzen darf, wenn ihr Arbeitsspeicher ausgeht. Container werden dann langsamer, statt gestoppt zu werden. Gilt nach einem Neustart." } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 7460781a6..638bd6388 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Δεν ήταν δυνατή η ενημέρωση των προφίλ κελύφους: {error}", "Uninstalling Kiri…": "Απεγκατάσταση Kiri…", "Could not uninstall Kiri: {error}": "Δεν ήταν δυνατή η απεγκατάσταση του Kiri: {error}", - "Uninstall Kiri using your system package manager": "Απεγκαταστήστε το Kiri μέσω του διαχειριστή πακέτων του συστήματός σας" + "Uninstall Kiri using your system package manager": "Απεγκαταστήστε το Kiri μέσω του διαχειριστή πακέτων του συστήματός σας", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Χώρος στον δίσκο που μπορεί να χρησιμοποιήσει η VM όταν εξαντληθεί η μνήμη της, ώστε τα containers να επιβραδύνονται αντί να σταματούν. Εφαρμόζεται κατά την επανεκκίνηση." } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index d46419ef0..0a9f7e21b 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "No se pudieron actualizar los perfiles de la shell: {error}", "Uninstalling Kiri…": "Desinstalando Kiri…", "Could not uninstall Kiri: {error}": "No se pudo desinstalar Kiri: {error}", - "Uninstall Kiri using your system package manager": "Desinstala Kiri con el gestor de paquetes de tu sistema" + "Uninstall Kiri using your system package manager": "Desinstala Kiri con el gestor de paquetes de tu sistema", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espacio en disco que la VM puede usar cuando se queda sin memoria, para que los contenedores vayan más lentos en lugar de detenerse. Se aplica al reiniciar." } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index 542e95e8a..bc054a9cc 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "به‌روزرسانی پروفایل‌های شل ممکن نشد: {error}", "Uninstalling Kiri…": "در حال حذف نصب Kiri…", "Could not uninstall Kiri: {error}": "حذف نصب Kiri ممکن نشد: {error}", - "Uninstall Kiri using your system package manager": "Kiri را با مدیر بستهٔ سیستم خود حذف نصب کنید" + "Uninstall Kiri using your system package manager": "Kiri را با مدیر بستهٔ سیستم خود حذف نصب کنید", + "Swap": "سواپ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "فضای دیسکی که VM هنگام تمام شدن حافظه‌اش می‌تواند استفاده کند تا کانتینرها به‌جای متوقف شدن کند شوند. پس از راه‌اندازی مجدد اعمال می‌شود." } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index 9038fe400..d67b88b13 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Komentotulkin profiileja ei voitu päivittää: {error}", "Uninstalling Kiri…": "Poistetaan Kirin asennusta…", "Could not uninstall Kiri: {error}": "Kirin asennusta ei voitu poistaa: {error}", - "Uninstall Kiri using your system package manager": "Poista Kirin asennus järjestelmän paketinhallinnalla" + "Uninstall Kiri using your system package manager": "Poista Kirin asennus järjestelmän paketinhallinnalla", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Levytilaa, jota VM voi käyttää, kun sen muisti loppuu, jolloin kontit hidastuvat pysäyttämisen sijaan. Tulee voimaan uudelleenkäynnistyksessä." } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index 3e0b0eeb2..bcabeadc8 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Impossible de mettre à jour les profils shell : {error}", "Uninstalling Kiri…": "Désinstallation de Kiri…", "Could not uninstall Kiri: {error}": "Impossible de désinstaller Kiri : {error}", - "Uninstall Kiri using your system package manager": "Désinstallez Kiri avec le gestionnaire de paquets de votre système" + "Uninstall Kiri using your system package manager": "Désinstallez Kiri avec le gestionnaire de paquets de votre système", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espace disque que la VM peut utiliser quand sa mémoire est épuisée : les conteneurs ralentissent au lieu d’être arrêtés. Appliqué au redémarrage." } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 13912178b..76cd063d9 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "शेल प्रोफ़ाइल अपडेट नहीं कर सके: {error}", "Uninstalling Kiri…": "Kiri अनइंस्टॉल हो रहा है…", "Could not uninstall Kiri: {error}": "Kiri अनइंस्टॉल नहीं कर सके: {error}", - "Uninstall Kiri using your system package manager": "अपने सिस्टम पैकेज मैनेजर से Kiri अनइंस्टॉल करें" + "Uninstall Kiri using your system package manager": "अपने सिस्टम पैकेज मैनेजर से Kiri अनइंस्टॉल करें", + "Swap": "स्वैप", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "डिस्क स्थान जिसे VM अपनी मेमोरी खत्म होने पर उपयोग कर सकता है, ताकि कंटेनर रुकने के बजाय धीमे हो जाएं। रीस्टार्ट पर लागू होता है।" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index c61dff354..ce78de880 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Nem sikerült frissíteni a shell-profilokat: {error}", "Uninstalling Kiri…": "A Kiri eltávolítása…", "Could not uninstall Kiri: {error}": "Nem sikerült eltávolítani a Kirit: {error}", - "Uninstall Kiri using your system package manager": "Távolítsd el a Kirit a rendszer csomagkezelőjével" + "Uninstall Kiri using your system package manager": "Távolítsd el a Kirit a rendszer csomagkezelőjével", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Lemezterület, amelyet a VM akkor használhat, ha elfogy a memóriája, így a konténerek leállítás helyett lelassulnak. Újraindításkor lép életbe." } diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 3be9fae91..437c72e63 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Tidak bisa memperbarui profil shell: {error}", "Uninstalling Kiri…": "Menghapus instalasi Kiri…", "Could not uninstall Kiri: {error}": "Tidak bisa menghapus instalasi Kiri: {error}", - "Uninstall Kiri using your system package manager": "Hapus instalasi Kiri menggunakan manajer paket sistem Anda" + "Uninstall Kiri using your system package manager": "Hapus instalasi Kiri menggunakan manajer paket sistem Anda", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Ruang disk yang boleh dipakai VM saat memorinya habis, sehingga kontainer melambat alih-alih dihentikan. Berlaku saat dimulai ulang." } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index ccdda15f9..516c01c4a 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Impossibile aggiornare i profili shell: {error}", "Uninstalling Kiri…": "Disinstallazione di Kiri…", "Could not uninstall Kiri: {error}": "Impossibile disinstallare Kiri: {error}", - "Uninstall Kiri using your system package manager": "Disinstalla Kiri usando il gestore di pacchetti del sistema" + "Uninstall Kiri using your system package manager": "Disinstalla Kiri usando il gestore di pacchetti del sistema", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spazio su disco che la VM può usare quando esaurisce la memoria, così i container rallentano invece di essere fermati. Si applica al riavvio." } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index dae93c701..c1e9bd038 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "シェルプロファイルを更新できませんでした:{error}", "Uninstalling Kiri…": "Kiri をアンインストールしています…", "Could not uninstall Kiri: {error}": "Kiri をアンインストールできませんでした:{error}", - "Uninstall Kiri using your system package manager": "システムのパッケージマネージャーで Kiri をアンインストールしてください" + "Uninstall Kiri using your system package manager": "システムのパッケージマネージャーで Kiri をアンインストールしてください", + "Swap": "スワップ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM のメモリが足りなくなったときに使えるディスク領域です。コンテナは停止されずに遅くなるだけで済みます。再起動時に適用されます。" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 3f4882ae2..9e374ff11 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Shell профильдерін жаңарту мүмкін болмады: {error}", "Uninstalling Kiri…": "Kiri өшірілуде…", "Could not uninstall Kiri: {error}": "Kiri-ді өшіру мүмкін болмады: {error}", - "Uninstall Kiri using your system package manager": "Kiri-ді жүйенің пакет менеджері арқылы өшіріңіз" + "Uninstall Kiri using your system package manager": "Kiri-ді жүйенің пакет менеджері арқылы өшіріңіз", + "Swap": "Своп", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM жадысы таусылғанда пайдалана алатын диск кеңістігі: контейнерлер тоқтатылмай, баяулайды. Қайта іске қосқанда қолданылады." } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 40e624847..86c2dd7a8 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "셸 프로필을 업데이트할 수 없습니다: {error}", "Uninstalling Kiri…": "Kiri 제거 중…", "Could not uninstall Kiri: {error}": "Kiri를 제거할 수 없습니다: {error}", - "Uninstall Kiri using your system package manager": "시스템 패키지 관리자로 Kiri를 제거하세요" + "Uninstall Kiri using your system package manager": "시스템 패키지 관리자로 Kiri를 제거하세요", + "Swap": "스왑", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM의 메모리가 부족할 때 사용할 수 있는 디스크 공간입니다. 컨테이너가 중지되지 않고 느려지기만 합니다. 다시 시작하면 적용됩니다." } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index b11c41b6a..4bc17c876 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "ອັບເດດໂປຣໄຟລ໌ shell ບໍ່ໄດ້: {error}", "Uninstalling Kiri…": "ກຳລັງຖອນການຕິດຕັ້ງ Kiri…", "Could not uninstall Kiri: {error}": "ຖອນການຕິດຕັ້ງ Kiri ບໍ່ໄດ້: {error}", - "Uninstall Kiri using your system package manager": "ຖອນການຕິດຕັ້ງ Kiri ໂດຍໃຊ້ຕົວຈັດການແພັກເກັດຂອງລະບົບທ່ານ" + "Uninstall Kiri using your system package manager": "ຖອນການຕິດຕັ້ງ Kiri ໂດຍໃຊ້ຕົວຈັດການແພັກເກັດຂອງລະບົບທ່ານ", + "Swap": "ສະວັບ", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "ພື້ນທີ່ດິສກ໌ທີ່ VM ໃຊ້ໄດ້ເມື່ອໜ່ວຍຄວາມຈຳໝົດ ເພື່ອໃຫ້ຄອນເທນເນີຊ້າລົງແທນທີ່ຈະຖືກຢຸດ. ມີຜົນເມື່ອເລີ່ມໃໝ່." } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 5567563bb..8977eb45e 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Nepavyko atnaujinti apvalkalo profilių: {error}", "Uninstalling Kiri…": "Šalinamas Kiri…", "Could not uninstall Kiri: {error}": "Nepavyko pašalinti Kiri: {error}", - "Uninstall Kiri using your system package manager": "Pašalinkite Kiri naudodami sistemos paketų tvarkyklę" + "Uninstall Kiri using your system package manager": "Pašalinkite Kiri naudodami sistemos paketų tvarkyklę", + "Swap": "Sukeitimų sritis (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Disko vieta, kurią VM gali naudoti pritrūkusi atminties, kad konteineriai sulėtėtų, o ne būtų sustabdyti. Įsigalioja paleidus iš naujo." } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index b818dba77..5c6dfebb8 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Kunne ikke oppdatere skallprofiler: {error}", "Uninstalling Kiri…": "Avinstallerer Kiri…", "Could not uninstall Kiri: {error}": "Kunne ikke avinstallere Kiri: {error}", - "Uninstall Kiri using your system package manager": "Avinstaller Kiri med systemets pakkebehandler" + "Uninstall Kiri using your system package manager": "Avinstaller Kiri med systemets pakkebehandler", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Diskplass VM-en kan bruke når minnet går tomt, slik at containere går tregere i stedet for å bli stoppet. Brukes ved omstart." } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index b003d8126..67760d94e 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Nie udało się zaktualizować profili powłoki: {error}", "Uninstalling Kiri…": "Odinstalowywanie Kiri…", "Could not uninstall Kiri: {error}": "Nie udało się odinstalować Kiri: {error}", - "Uninstall Kiri using your system package manager": "Odinstaluj Kiri za pomocą systemowego menedżera pakietów" + "Uninstall Kiri using your system package manager": "Odinstaluj Kiri za pomocą systemowego menedżera pakietów", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Miejsce na dysku, którego VM może używać, gdy zabraknie jej pamięci, dzięki czemu kontenery zwalniają zamiast zostać zatrzymane. Obowiązuje po ponownym uruchomieniu." } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index 948d083eb..cf4286886 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Não foi possível atualizar os perfis do shell: {error}", "Uninstalling Kiri…": "Desinstalando o Kiri…", "Could not uninstall Kiri: {error}": "Não foi possível desinstalar o Kiri: {error}", - "Uninstall Kiri using your system package manager": "Desinstale o Kiri usando o gerenciador de pacotes do sistema" + "Uninstall Kiri using your system package manager": "Desinstale o Kiri usando o gerenciador de pacotes do sistema", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espaço em disco que a VM pode usar quando a memória acaba, para que os contêineres fiquem mais lentos em vez de serem parados. Aplicado ao reiniciar." } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index cab8bdfc5..e2e36c58c 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Nu s-au putut actualiza profilurile shell: {error}", "Uninstalling Kiri…": "Se dezinstalează Kiri…", "Could not uninstall Kiri: {error}": "Nu s-a putut dezinstala Kiri: {error}", - "Uninstall Kiri using your system package manager": "Dezinstalează Kiri folosind gestionarul de pachete al sistemului" + "Uninstall Kiri using your system package manager": "Dezinstalează Kiri folosind gestionarul de pachete al sistemului", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spațiu pe disc pe care VM îl poate folosi când îi rămâne fără memorie, astfel încât containerele încetinesc în loc să fie oprite. Se aplică la repornire." } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index fcc1248af..9da5fc966 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Не удалось обновить профили оболочки: {error}", "Uninstalling Kiri…": "Удаление Kiri…", "Could not uninstall Kiri: {error}": "Не удалось удалить Kiri: {error}", - "Uninstall Kiri using your system package manager": "Удалите Kiri с помощью системного пакетного менеджера" + "Uninstall Kiri using your system package manager": "Удалите Kiri с помощью системного пакетного менеджера", + "Swap": "Подкачка (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Место на диске, которое VM может использовать, когда заканчивается память: контейнеры замедляются, а не останавливаются. Применяется после перезапуска." } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index 79b032c8b..8b83987d0 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Profilov lupine ni bilo mogoče posodobiti: {error}", "Uninstalling Kiri…": "Odstranjevanje Kirija …", "Could not uninstall Kiri: {error}": "Kirija ni bilo mogoče odstraniti: {error}", - "Uninstall Kiri using your system package manager": "Odstranite Kiri z upraviteljem paketov svojega sistema" + "Uninstall Kiri using your system package manager": "Odstranite Kiri z upraviteljem paketov svojega sistema", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Prostor na disku, ki ga VM lahko uporabi, ko ji zmanjka pomnilnika, da se vsebniki upočasnijo, namesto da bi se ustavili. Velja po ponovnem zagonu." } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index dfded937e..bb245507c 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Profilet e shell-it nuk u përditësuan dot: {error}", "Uninstalling Kiri…": "Po çinstalohet Kiri…", "Could not uninstall Kiri: {error}": "Kiri nuk u çinstalua dot: {error}", - "Uninstall Kiri using your system package manager": "Çinstaloni Kiri duke përdorur menaxherin e paketave të sistemit" + "Uninstall Kiri using your system package manager": "Çinstaloni Kiri duke përdorur menaxherin e paketave të sistemit", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Hapësirë në disk që VM mund ta përdorë kur i mbaron memoria, që kontejnerët të ngadalësohen në vend që të ndalen. Zbatohet pas rinisjes." } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index dfc556569..20aa2bb37 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "ஷெல் சுயவிவரங்களைப் புதுப்பிக்க முடியவில்லை: {error}", "Uninstalling Kiri…": "Kiri நிறுவல் நீக்கப்படுகிறது…", "Could not uninstall Kiri: {error}": "Kiri-ஐ நிறுவல் நீக்க முடியவில்லை: {error}", - "Uninstall Kiri using your system package manager": "உங்கள் கணினி தொகுப்பு மேலாளரைப் பயன்படுத்தி Kiri-ஐ நிறுவல் நீக்கவும்" + "Uninstall Kiri using your system package manager": "உங்கள் கணினி தொகுப்பு மேலாளரைப் பயன்படுத்தி Kiri-ஐ நிறுவல் நீக்கவும்", + "Swap": "ஸ்வாப்", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "நினைவகம் தீர்ந்தால் VM பயன்படுத்தக்கூடிய வட்டு இடம்; இதனால் கண்டெய்னர்கள் நிறுத்தப்படாமல் மெதுவாகும். மறுதொடக்கத்தில் பொருந்தும்." } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index fbe229378..469fbba3e 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "షెల్ ప్రొఫైల్‌లను అప్‌డేట్ చేయలేకపోయాం: {error}", "Uninstalling Kiri…": "Kiri అన్‌ఇన్‌స్టాల్ అవుతోంది…", "Could not uninstall Kiri: {error}": "Kiriని అన్‌ఇన్‌స్టాల్ చేయలేకపోయాం: {error}", - "Uninstall Kiri using your system package manager": "మీ సిస్టమ్ ప్యాకేజీ మేనేజర్‌తో Kiriని అన్‌ఇన్‌స్టాల్ చేయండి" + "Uninstall Kiri using your system package manager": "మీ సిస్టమ్ ప్యాకేజీ మేనేజర్‌తో Kiriని అన్‌ఇన్‌స్టాల్ చేయండి", + "Swap": "స్వాప్", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "మెమరీ అయిపోయినప్పుడు VM ఉపయోగించగల డిస్క్ స్థలం, దీని వల్ల కంటైనర్లు ఆపబడకుండా నెమ్మదిస్తాయి. రీస్టార్ట్‌లో వర్తిస్తుంది." } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index f0ff9933f..df8e13079 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "อัปเดตโปรไฟล์เชลล์ไม่ได้: {error}", "Uninstalling Kiri…": "กำลังถอนการติดตั้ง Kiri…", "Could not uninstall Kiri: {error}": "ถอนการติดตั้ง Kiri ไม่ได้: {error}", - "Uninstall Kiri using your system package manager": "ถอนการติดตั้ง Kiri ด้วยตัวจัดการแพ็กเกจของระบบ" + "Uninstall Kiri using your system package manager": "ถอนการติดตั้ง Kiri ด้วยตัวจัดการแพ็กเกจของระบบ", + "Swap": "สวอป", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "พื้นที่ดิสก์ที่ VM ใช้ได้เมื่อหน่วยความจำหมด เพื่อให้คอนเทนเนอร์ทำงานช้าลงแทนที่จะถูกหยุด มีผลเมื่อเริ่มใหม่" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index 3b298ccca..9e4f94498 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Kabuk profilleri güncellenemedi: {error}", "Uninstalling Kiri…": "Kiri kaldırılıyor…", "Could not uninstall Kiri: {error}": "Kiri kaldırılamadı: {error}", - "Uninstall Kiri using your system package manager": "Kiri'yi sistem paket yöneticinizi kullanarak kaldırın" + "Uninstall Kiri using your system package manager": "Kiri'yi sistem paket yöneticinizi kullanarak kaldırın", + "Swap": "Takas (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM'nin belleği tükendiğinde kullanabileceği disk alanı; böylece kapsayıcılar durdurulmak yerine yavaşlar. Yeniden başlatınca uygulanır." } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 493a9d528..17488b7de 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Не вдалося оновити профілі оболонки: {error}", "Uninstalling Kiri…": "Видалення Kiri…", "Could not uninstall Kiri: {error}": "Не вдалося видалити Kiri: {error}", - "Uninstall Kiri using your system package manager": "Видаліть Kiri за допомогою системного менеджера пакунків" + "Uninstall Kiri using your system package manager": "Видаліть Kiri за допомогою системного менеджера пакунків", + "Swap": "Підкачка (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Місце на диску, яке VM може використовувати, коли закінчується пам'ять: контейнери сповільнюються, а не зупиняються. Застосовується після перезапуску." } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index aeae1c4e0..1b7282d25 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "Không thể cập nhật hồ sơ shell: {error}", "Uninstalling Kiri…": "Đang gỡ cài đặt Kiri…", "Could not uninstall Kiri: {error}": "Không thể gỡ cài đặt Kiri: {error}", - "Uninstall Kiri using your system package manager": "Hãy gỡ cài đặt Kiri bằng trình quản lý gói của hệ thống" + "Uninstall Kiri using your system package manager": "Hãy gỡ cài đặt Kiri bằng trình quản lý gói của hệ thống", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Dung lượng đĩa mà VM có thể dùng khi hết bộ nhớ, để container chạy chậm lại thay vì bị dừng. Áp dụng khi khởi động lại." } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index d3ea11a00..6383854ea 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "无法更新 Shell 配置文件:{error}", "Uninstalling Kiri…": "正在卸载 Kiri…", "Could not uninstall Kiri: {error}": "无法卸载 Kiri:{error}", - "Uninstall Kiri using your system package manager": "请使用系统包管理器卸载 Kiri" + "Uninstall Kiri using your system package manager": "请使用系统包管理器卸载 Kiri", + "Swap": "交换空间", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虚拟机内存用尽时可使用的磁盘空间,容器会变慢而不是被停止。重启后生效。" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 4e12f1ccb..40baefcde 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -2033,5 +2033,7 @@ "Could not update shell profiles: {error}": "無法更新 Shell 設定檔:{error}", "Uninstalling Kiri…": "正在解除安裝 Kiri…", "Could not uninstall Kiri: {error}": "無法解除安裝 Kiri:{error}", - "Uninstall Kiri using your system package manager": "請使用系統套件管理員解除安裝 Kiri" + "Uninstall Kiri using your system package manager": "請使用系統套件管理員解除安裝 Kiri", + "Swap": "交換空間", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虛擬機記憶體用盡時可使用的磁碟空間,容器會變慢而不是被停止。重新啟動後生效。" } diff --git a/docs/development.md b/docs/development.md index 1a163e0ff..fa81aa2e6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -79,6 +79,11 @@ removing the setting never shrinks an existing disk. The extra capacity uses space on the Mac only as it is written. Linux and WSL use their host's storage instead of this disk image. +The VM also keeps a swap file on that disk, 1 GiB unless Settings → Resources +says otherwise (`"swap_mib"` in `~/.kiri/vm.json`, 0 for none) or `KIRI_SWAP_MIB` +overrides it. The guest makes, resizes or removes `/var/lib/kiri/swapfile` at +boot; freed swap is discarded, so it too uses space on the Mac only while in use. + `python3 tests/disk-grow.py` checks growth and data preservation across restarts in a disposable VM, after building the host and guest above. diff --git a/docs/features.md b/docs/features.md index 82387ca9c..868ea0c90 100644 --- a/docs/features.md +++ b/docs/features.md @@ -124,9 +124,9 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr a command line (and "Open in Terminal" for a full shell) and its files (preview, Save to Downloads, Show in Finder); Settings for fonts, text size, starting at sign-in, stopping the engine when Kiri quits, the VM's - CPUs, memory and disk image size (`~/.kiri/vm.json`, used from the VM's next - start; `KIRI_CPUS`, `KIRI_MEMORY_MIB` and `KIRI_DISK_GB` override it; the - disk grows online on boot and never shrinks) and local names + CPUs, memory, swap and disk image size (`~/.kiri/vm.json`, used from the VM's + next start; `KIRI_CPUS`, `KIRI_MEMORY_MIB`, `KIRI_SWAP_MIB` and `KIRI_DISK_GB` + 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 diff --git a/tests/e2e.sh b/tests/e2e.sh index a8ea8dbb3..4890397de 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1938,6 +1938,18 @@ t limit-memory-swap-refused "nomem=ok small=ok over=ok" bash -c " echo \"nomem=\$nm small=\$sm over=\$ov\" " t oom-kill "137" bash -c "$D run --rm --memory 32m alpine sh -c 'tail /dev/zero' >/dev/null 2>&1; echo \$?" +# The VM has the swap Settings → Resources names, on its data disk, and a +# container's --memory-swap reaches it: zswap's shrinker moves the pages on +# to the file rather than keeping them in the container's memory (#326). +only mac t vm-swap-as-set "ok" bash -c " + want=\$(curl -s --unix-socket '$SOCK' http://d/kiri/resources | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"running_swap_mib\"])') + got=\$($D run --rm alpine awk 'NR>1 && \$1==\"/var/lib/kiri/swapfile\" {print int((\$3+4)/1024)}' /proc/swaps) + [ \"\${got:-0}\" = \"\$want\" ] && echo ok || echo \"swap \${got:-none} MiB, resources say \$want\" +" +only mac t vm-swap-container-over-memory "dd=0 oom_kill=0" bash -c " + [ \"\$(curl -s --unix-socket '$SOCK' http://d/kiri/resources | python3 -c 'import json,sys; print(json.load(sys.stdin).get(\"running_swap_mib\", 1024))')\" -ge 256 ] || { echo 'dd=0 oom_kill=0 (the VM has less than 256 MiB of swap: nothing to check)'; exit; } + $D run --rm -m 64m --memory-swap 512m --tmpfs /t:size=400m alpine sh -c 'dd if=/dev/urandom of=/t/x bs=1M count=200 2>/dev/null; echo \"dd=\$? oom_kill=\$(grep oom_kill /sys/fs/cgroup/memory.events | cut -d\" \" -f2)\"' +" t stats "128MiB" $D stats --no-stream --format '{{.MemUsage}}' lim t stats-pids "PIDS" $D stats --no-stream lim t stats-stream "lim" bash -c "perl -e 'alarm 3; exec @ARGV' $D stats --format '{{.Name}}' lim 2>/dev/null | head -1" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 23cf93878..b701ce68b 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -363,3 +363,5 @@ 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 +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 diff --git a/tests/ui/resources-swap.js b/tests/ui/resources-swap.js new file mode 100644 index 000000000..366df5f67 --- /dev/null +++ b/tests/ui/resources-swap.js @@ -0,0 +1,72 @@ +// Settings -> Resources: the VM's swap slider on macOS (#326): its range and +// labels, the save, the restart notice, and no slider where the host has +// its own swap (no swap_mib). +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, what) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(`${what}: got ${JSON.stringify(a)}, want ${JSON.stringify(b)}`); }; +const res = (extra) => kiri.on({ + type: "resources", + cpus: 4, + memory_mib: 8192, + running_cpus: 4, + running_memory_mib: 8192, + awake: true, + max_cpus: 12, + max_memory_mib: 32768, + overridden: false, + ...extra, +}); +const slide = (v) => { + const s = document.getElementById("res-swap"); + s.value = String(v); + s.dispatchEvent(new Event("input", { bubbles: true })); +}; +const saved = () => { + const before = sent.length; + document.getElementById("res-save").click(); + const msg = sent.slice(before).find((m) => m.cmd === "setresources"); + if (!msg) throw new Error("setresources not sent"); + return msg.value; +}; + +res({ swap_mib: 1024, running_swap_mib: 1024, max_swap_mib: 16384 }); +prefs.tab = "resources"; +show("settings"); + +t("The swap slider shows the VM's swap, from none to the most", () => { + const s = document.getElementById("res-swap"); + if (!s) throw new Error("missing #res-swap"); + eq([s.min, s.max, s.step, s.value], ["0", "16384", "512", "1024"], "min, max, step, value"); + eq(document.getElementById("res-swap-v").textContent, "1 GB", "label"); + eq(document.getElementById("res-save").disabled, true, "nothing to save yet"); + if (document.getElementById("res-restart")) throw new Error("no restart while the VM has what is saved"); +}); + +t("Half gigabytes and none read as such", () => { + slide(1536); + eq(document.getElementById("res-swap-v").textContent, "1.5 GB", "1536 MiB"); + slide(0); + eq(document.getElementById("res-swap-v").textContent, "Off", "0"); +}); + +t("Moving it enables Save and sends swap_mib with the rest", () => { + slide(4096); + eq(document.getElementById("res-save").disabled, false, "save enabled"); + eq(saved(), { cpus: 4, memory_mib: 8192, swap_mib: 4096 }, "setresources payload"); +}); + +t("A saved swap the VM doesn't have yet offers the restart", () => { + res({ swap_mib: 4096, running_swap_mib: 1024, max_swap_mib: 16384 }); + if (!document.getElementById("res-restart")) throw new Error("missing Restart VM button"); +}); + +t("Without swap_mib (Linux, Windows) there is no slider, and Save sends none", () => { + res({}); + if (document.getElementById("res-swap")) throw new Error("res-swap should not render without swap_mib"); + const cpus = document.getElementById("res-cpus"); + cpus.value = "6"; + cpus.dispatchEvent(new Event("input", { bubbles: true })); + eq(saved(), { cpus: 6, memory_mib: 8192 }, "payload without swap_mib"); +}); + +report(R); From c1e1a0d1869fe9236cea16be8274409df34e5240 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:33:26 +0100 Subject: [PATCH 126/157] CLI: --json for domains, k8s status, machine list, usb list and registry (#748) (#959) Co-authored-by: Arekatla Nishanth Chowdary --- README.md | 10 +++--- README.zh-CN.md | 8 ++--- crates/kiri/src/domains_cli.rs | 17 +++++++--- crates/kiri/src/k8s.rs | 55 ++++++++++++++++++++++++++------- crates/kiri/src/machine.rs | 27 ++++++++++++++-- crates/kiri/src/registry_cli.rs | 34 +++++++++++++------- crates/kiri/src/usb.rs | 14 ++++++++- 7 files changed, 125 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index e3f450017..36e98d8dc 100644 --- a/README.md +++ b/README.md @@ -182,18 +182,20 @@ Kiri's own commands: | Command | What it does | |---------|--------------| | `kiri start` | Start Kiri again after a Stop, as Start in the window does | -| `kiri k8s start \| stop \| status \| delete` | A single-node Kubernetes cluster | -| `kiri machine create NAME [--distro D] \| list \| shell NAME \| stop \| delete NAME` | Linux machines | +| `kiri k8s start \| stop \| status [--json] \| delete` | A single-node Kubernetes cluster | +| `kiri machine create NAME [--distro D] \| list [--json] \| shell NAME \| stop \| delete NAME` | Linux machines | | `kiri share PORT\|CONTAINER [--name N]` | Share a local port or container on the internet | | `kiri import [orbstack \| desktop-linux]` | Bring images, volumes and containers over | -| `kiri domains [set --http N --https N \| reset]` | The ports local domains answer on | -| `kiri usb [list] \| attach DEVICE \| detach DEVICE` | USB devices for containers (beta) | +| `kiri domains [set --http N --https N \| reset] [--json]` | The ports local domains answer on | +| `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | USB devices for containers (beta) | | `kiri build-with [docker \| kiri]` | Which builder `docker build` uses | | `kiri update [--check]` | Install the newest release | | `kiri diag logs \| report` | Logs, and a report file to send with a bug | | `kiri bench [--runs N] [--network none\|bridge]` | Measure container start on your machine | | `kiri ui` | Open the window | +`--json` prints one line of JSON for scripts, as the window gets it; `kiri registry` and `kiri share status` take it too. + --- ## Benchmarks diff --git a/README.zh-CN.md b/README.zh-CN.md index 7ff6280fc..8941fca48 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -180,12 +180,12 @@ Kiri 自有命令: | 命令 | 作用 | |------|------| | `kiri start` | 在 Stop 之后重新启动 Kiri,等同于窗口中的 Start | -| `kiri k8s start \| stop \| status \| delete` | 单节点 Kubernetes 集群 | -| `kiri machine create NAME [--distro D] \| list \| shell NAME \| stop \| delete NAME` | Linux 虚拟机 | +| `kiri k8s start \| stop \| status [--json] \| delete` | 单节点 Kubernetes 集群 | +| `kiri machine create NAME [--distro D] \| list [--json] \| shell NAME \| stop \| delete NAME` | Linux 虚拟机 | | `kiri share PORT\|CONTAINER [--name N]` | 将本地端口或容器分享到互联网 | | `kiri import [orbstack \| desktop-linux]` | 迁移镜像、卷和容器 | -| `kiri domains [set --http N --https N \| reset]` | 本地域名监听的端口 | -| `kiri usb [list] \| attach DEVICE \| detach DEVICE` | 容器的 USB 设备(beta) | +| `kiri domains [set --http N --https N \| reset] [--json]` | 本地域名监听的端口 | +| `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | 容器的 USB 设备(beta) | | `kiri build-with [docker \| kiri]` | 选择 `docker build` 使用的构建器 | | `kiri update [--check]` | 安装最新版本 | | `kiri diag logs \| report` | 日志,以及随 bug 报告提交的报告文件 | diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index 5ca458bf1..2f6f613b1 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -10,7 +10,8 @@ use crate::client; const USAGE: &str = "usage: kiri domains the routers' ports, and whether each runs kiri domains set [--http N] [--https N] move them (no restart) - kiri domains reset back to the ports a start gives (a test copy's: off)"; + kiri domains reset back to the ports a start gives (a test copy's: off) + --json, with any of them, prints the engine's answer as one line of JSON"; #[derive(Debug, PartialEq)] enum Cmd { @@ -80,7 +81,9 @@ pub fn run(args: &[String]) -> io::Result<()> { } fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { - let cmd = parse(args).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + 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`")); } @@ -94,7 +97,11 @@ fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { } Cmd::Reset => answer(client::request("DELETE", "/kiri/domains", None)?)?, }; - print!("{}", format(&v)); + if json { + println!("{v}"); + } else { + print!("{}", format(&v)); + } Ok(()) } @@ -142,7 +149,7 @@ mod tests { #[test] fn bad_arguments_fail_before_touching_the_socket() { - for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown"] { + for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown", "--json show"] { let err = run_with(&args(bad), || panic!("checked daemon before arguments: {bad}")).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad}: {err}"); } @@ -150,7 +157,7 @@ mod tests { #[test] fn says_when_the_daemon_is_not_running() { - for cmd in ["", "set --http 8080 --https 8443", "set --http 8080", "reset"] { + for cmd in ["", "--json", "set --http 8080 --https 8443", "set --http 8080 --json", "reset"] { 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/k8s.rs b/crates/kiri/src/k8s.rs index 763a4dc52..7f9998356 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -61,7 +61,7 @@ const MAX_K3S_ARGS: usize = 64; const MAX_MANIFEST_BYTES: u64 = 4 << 20; const USAGE_SET: &str = "usage: kiri k8s set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]"; -const USAGE_K8S: &str = "usage: kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]"; +const USAGE_K8S: &str = "usage: kiri k8s start [--use] | stop | status [--json] | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]"; impl Config { pub(crate) fn api_port(&self) -> u16 { @@ -361,14 +361,7 @@ pub(crate) fn format_status(info: Option<&serde_json::Value>, cfg: &Config) -> S let port = bound_port(info).unwrap_or(API_PORT); let want = cfg.api_port(); let moved = if port != want { format!(" ({want} was in use)") } else { String::new() }; - let version = if state == "running" { - info["Config"]["Image"] - .as_str() - .and_then(|img| img.split_once(':').map(|(_, tag)| tag)) - .unwrap_or_else(|| cfg.version_tag()) - } else { - cfg.version_tag() - }; + let version = node_version(info, cfg); let mut out = format!("Kubernetes: {state}, k3s {version}, API on 127.0.0.1:{port}{moved}"); if !cfg.k3s_args.is_empty() { out.push_str(&format!(", k3s args: {}", cfg.k3s_args.join(" "))); @@ -376,6 +369,30 @@ pub(crate) fn format_status(info: Option<&serde_json::Value>, cfg: &Config) -> S out } +/// The k3s a running node runs (its image's tag), else the one a start runs. +fn node_version<'a>(info: &'a serde_json::Value, cfg: &'a Config) -> &'a str { + if info["State"]["Status"] == "running" { + info["Config"]["Image"].as_str().and_then(|img| img.split_once(':').map(|(_, tag)| tag)).unwrap_or_else(|| cfg.version_tag()) + } else { + cfg.version_tag() + } +} + +/// `kiri k8s status --json`: what `format_status` says, as one object. A +/// cluster not created has `state` null and no `port` yet. +pub(crate) fn status_json(info: Option<&serde_json::Value>, cfg: &Config) -> serde_json::Value { + serde_json::json!({ + "state": info.map(|i| i["State"]["Status"].as_str().unwrap_or("unknown")), + "version": info.map_or_else(|| cfg.version_tag(), |i| node_version(i, cfg)), + "port": info.map(|i| bound_port(i).unwrap_or(API_PORT)), + "requested_port": cfg.api_port(), + "lan": cfg.lan, + "tls_san": cfg.tls_san, + "k3s_args": cfg.k3s_args, + "context": CONTEXT.get(), + }) +} + /// `kiri k8s set [--lan on|off] [--tls-san a,b] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]`: /// saves the settings and, if the cluster exists and they changed, recreates its node with them. fn set(args: &[String]) -> io::Result<()> { @@ -517,7 +534,7 @@ fn run_inner(args: &[String]) -> io::Result<()> { println!("Kubernetes stopped (its state is kept; `kiri k8s start` resumes it)"); Ok(()) } - Some("status") => status(), + Some("status") => status(flag("--json")), Some("delete") => delete(), Some("set") => set(&args[1..]), _ => Err(io::Error::other(USAGE_K8S)), @@ -1029,15 +1046,23 @@ pub(crate) fn forget() { } } -fn status() -> io::Result<()> { +fn status(json: bool) -> io::Result<()> { ensure_daemon()?; let cfg = config(); if !exists()? { - println!("{}", format_status(None, &cfg)); + println!("{}", if json { status_json(None, &cfg).to_string() } else { format_status(None, &cfg) }); return Ok(()); } let info = client::get(&format!("/containers/{NAME}/json"))?; let state = info["State"]["Status"].as_str().unwrap_or("unknown").to_owned(); + if json { + // The context is put right as below, quietly: the line stays JSON. + if state == "running" { + let _ = sync(Duration::ZERO); + } + println!("{}", status_json(Some(&info), &cfg)); + return Ok(()); + } println!("{}", format_status(Some(&info), &cfg)); if state == "running" { // A context missing or out of date (written by an older Kiri, or not at all) is put right. @@ -1348,6 +1373,12 @@ mod tests { super::format_status(Some(&running), &cfg), "Kubernetes: running, k3s v1.31.4-k3s1, API on 127.0.0.1:6443, k3s args: --flannel-backend=none --disable=traefik" ); + let j = super::status_json(Some(&running), &cfg); + assert_eq!((&j["state"], &j["version"], &j["port"], &j["requested_port"]), (&"running".into(), &"v1.31.4-k3s1".into(), &6443.into(), &6443.into())); + assert_eq!(j["k3s_args"], serde_json::json!(["--flannel-backend=none", "--disable=traefik"])); + let none = super::status_json(None, &super::Config::default()); + assert!(none["state"].is_null() && none["port"].is_null(), "{none}"); + assert_eq!(none["version"], super::IMAGE.1); } #[test] diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index 6658934ae..7433bd1d5 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -47,7 +47,7 @@ pub fn run(args: &[String]) -> io::Result<()> { let pick = args.iter().position(|a| a == "--distro" || a == "--image").and_then(|i| args.get(i + 1)).map_or("ubuntu", String::as_str); create(name, pick, args.iter().any(|a| a == "--systemd")) } - Some("list" | "ls") => list(), + Some("list" | "ls") => list(args.iter().any(|a| a == "--json")), Some("shell") => { need_name()?; let cmd: Vec<&str> = args.iter().position(|a| a == "--").map(|i| args[i + 1..].iter().map(String::as_str).collect()).unwrap_or_default(); @@ -70,7 +70,7 @@ pub fn run(args: &[String]) -> io::Result<()> { Ok(()) } _ => Err(io::Error::other( - "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list | shell NAME [-- CMD...] | start | stop | restart | delete NAME", + "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME", )), } } @@ -256,9 +256,13 @@ fn create(name: &str, pick: &str, systemd: bool) -> io::Result<()> { Ok(()) } -fn list() -> io::Result<()> { +fn list(json: bool) -> io::Result<()> { let filters = format!("{{\"label\":[\"{LABEL}\"]}}"); let rows = client::get(&format!("/containers/json?all=1&filters={}", urlish(&filters)))?; + if json { + println!("{}", list_json(&rows)); + return Ok(()); + } println!("{:<16} {:<28} {}", "NAME", "IMAGE", "STATE"); for c in rows.as_array().into_iter().flatten() { println!("{:<16} {:<28} {}", c["Labels"][LABEL].as_str().unwrap_or("?"), c["Image"].as_str().unwrap_or(""), c["Status"].as_str().unwrap_or("")); @@ -266,6 +270,16 @@ fn list() -> io::Result<()> { Ok(()) } +/// `kiri machine list --json`: each machine's name, image, state (Docker's +/// `running`, `exited`…) and status (`Up 2 hours`…). +fn list_json(rows: &serde_json::Value) -> serde_json::Value { + rows.as_array() + .into_iter() + .flatten() + .map(|c| json!({"name": c["Labels"][LABEL], "image": c["Image"], "state": c["State"], "status": c["Status"]})) + .collect() +} + fn urlish(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } @@ -550,4 +564,11 @@ mod tests { assert_eq!(err.to_string(), "a machine name is letters, digits and dashes"); } } + + #[test] + fn list_json_has_each_machines_name_image_and_state() { + let rows = json!([{"Labels": {(super::LABEL): "dev"}, "Image": "ubuntu:24.04", "State": "running", "Status": "Up 2 hours"}]); + assert_eq!(super::list_json(&rows), json!([{"name": "dev", "image": "ubuntu:24.04", "state": "running", "status": "Up 2 hours"}])); + assert_eq!(super::list_json(&json!([])), json!([])); + } } diff --git a/crates/kiri/src/registry_cli.rs b/crates/kiri/src/registry_cli.rs index 581c1f61f..913722bec 100644 --- a/crates/kiri/src/registry_cli.rs +++ b/crates/kiri/src/registry_cli.rs @@ -26,7 +26,9 @@ usage: kiri registry both lists and the file th registries without a verified certificate (self-signed or plain HTTP): registry.lan:5000, 10.0.0.0/8 kiri registry mirror [list] | add URL... | remove URL... - Docker Hub mirrors, tried in order before Docker Hub"; + Docker Hub mirrors, tried in order before Docker Hub + --json, with any of them: one line of JSON, the daemon's report for + `kiri registry`, the list itself for the others"; /// Checks an entry and writes it the way daemon.json keeps it. type Check = fn(&str) -> Result; @@ -35,6 +37,8 @@ const INSECURE: &str = "insecure-registries"; const MIRRORS: &str = "registry-mirrors"; pub fn run(args: &[String]) -> io::Result<()> { + let json = args.iter().any(|a| a == "--json"); + let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); let arg = |i: usize| args.get(i).map(String::as_str); if matches!(arg(0), Some("-h" | "--help" | "help")) { println!("{USAGE}"); @@ -44,7 +48,7 @@ pub fn run(args: &[String]) -> io::Result<()> { return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); } let (key, check): (&str, Check) = match arg(0) { - None => return show(&client::get("/kiri/registries")?), + None => return show(&client::get("/kiri/registries")?, json), Some("insecure") => (INSECURE, |s| Insecure::parse(s).map(|e| e.as_string())), Some("mirror" | "mirrors") => (MIRRORS, |s| Mirror::parse(s).map(|m| m.as_url())), _ => return Err(io::Error::other(USAGE)), @@ -59,7 +63,7 @@ pub fn run(args: &[String]) -> io::Result<()> { match arg(1) { Some("list" | "ls") | None => { let now = client::get("/kiri/registries")?; - list(key, &strings(&now[key])); + list(key, &strings(&now[key]), json); problems(&now); Ok(()) } @@ -70,7 +74,7 @@ pub fn run(args: &[String]) -> io::Result<()> { now.push(n); } } - save(key, &now) + save(key, &now, json) } Some("remove" | "rm") => { let mut now = strings(&client::get("/kiri/registries")?[key]); @@ -81,7 +85,7 @@ pub fn run(args: &[String]) -> io::Result<()> { return Err(io::Error::other(format!("{n} is not in {key}"))); } } - save(key, &now) + save(key, &now, json) } _ => Err(io::Error::other(USAGE)), } @@ -91,7 +95,11 @@ fn strings(v: &Value) -> Vec { v.as_array().into_iter().flatten().filter_map(|s| s.as_str()).map(str::to_owned).collect() } -fn list(key: &str, entries: &[String]) { +fn list(key: &str, entries: &[String], json: bool) { + if json { + println!("{}", json!(entries)); + return; + } match (key, entries.is_empty()) { (INSECURE, true) => println!("no insecure registries: every registry is reached over verified HTTPS"), (INSECURE, false) => println!("insecure registries (no verified certificate; HTTPS first, then plain HTTP):"), @@ -109,9 +117,13 @@ fn problems(report: &Value) { } } -fn show(report: &Value) -> io::Result<()> { - list(INSECURE, &strings(&report[INSECURE])); - list(MIRRORS, &strings(&report[MIRRORS])); +fn show(report: &Value, json: bool) -> io::Result<()> { + if json { + println!("{report}"); + return Ok(()); + } + list(INSECURE, &strings(&report[INSECURE]), false); + list(MIRRORS, &strings(&report[MIRRORS]), false); if let Some(p) = report["path"].as_str() { println!("in {p}"); } @@ -119,12 +131,12 @@ fn show(report: &Value) -> io::Result<()> { Ok(()) } -fn save(key: &str, entries: &[String]) -> io::Result<()> { +fn save(key: &str, entries: &[String], json: bool) -> io::Result<()> { let r = client::request("POST", "/kiri/registries", Some(&json!({ key: entries })))?; if !r.ok() { return Err(io::Error::other(r.error())); } let now = client::get("/kiri/registries")?; - list(key, &strings(&now[key])); + list(key, &strings(&now[key]), json); Ok(()) } diff --git a/crates/kiri/src/usb.rs b/crates/kiri/src/usb.rs index a213325b4..4507f3fc1 100644 --- a/crates/kiri/src/usb.rs +++ b/crates/kiri/src/usb.rs @@ -25,11 +25,13 @@ mod usbip; #[cfg_attr(target_os = "macos", allow(dead_code))] pub mod sysfs; -const USAGE: &str = "usage: kiri usb [list] | attach DEVICE | detach DEVICE | helper remove\n\ +const USAGE: &str = "usage: kiri usb [list [--json]] | attach DEVICE | detach DEVICE | helper remove\n\ DEVICE is a location (0x02114000), vendor:product (1532:00d7) or part of the name"; pub fn run(args: &[String]) -> io::Result<()> { match (args.first().map(String::as_str), args.get(1)) { + // The window's own list: each device's key, name, id, state, paths… + (None | Some("list" | "ls" | "--json"), _) if args.iter().any(|a| a == "--json") => list_json(), (None | Some("list" | "ls"), _) => list(), (Some("attach"), Some(d)) => attach(d), (Some("detach"), Some(d)) => detach(d), @@ -46,6 +48,16 @@ pub fn run(args: &[String]) -> io::Result<()> { } } +/// `kiri usb list --json`: the devices as the window's USB view has them. +fn list_json() -> io::Result<()> { + let v = ui_list(); + if let Some(e) = v["error"].as_str() { + return Err(io::Error::other(e.to_owned())); + } + println!("{}", v["devices"]); + Ok(()) +} + #[cfg(target_os = "macos")] fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a String> { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)) From 8e8ceccab9582392a908d79cff128f127e574637 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:44:36 +0100 Subject: [PATCH 127/157] CLI: kiri doctor, one read-only look at whether Kiri works (#747) (#960) Co-authored-by: Arekatla Nishanth Chowdary --- README.md | 1 + README.zh-CN.md | 1 + crates/kiri/src/doctor.rs | 1118 +++++++++++++++++++++++++++++++++++++ crates/kiri/src/main.rs | 12 +- crates/kiri/src/wsl.rs | 5 +- 5 files changed, 1134 insertions(+), 3 deletions(-) create mode 100644 crates/kiri/src/doctor.rs diff --git a/README.md b/README.md index 36e98d8dc..d7d3080d7 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ Kiri's own commands: | `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | USB devices for containers (beta) | | `kiri build-with [docker \| kiri]` | Which builder `docker build` uses | | `kiri update [--check]` | Install the newest release | +| `kiri doctor [--json]` | Whether Kiri works here, one line per part, and what to run when one doesn't | | `kiri diag logs \| report` | Logs, and a report file to send with a bug | | `kiri bench [--runs N] [--network none\|bridge]` | Measure container start on your machine | | `kiri ui` | Open the window | diff --git a/README.zh-CN.md b/README.zh-CN.md index 8941fca48..ed0d80bfc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -188,6 +188,7 @@ Kiri 自有命令: | `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | 容器的 USB 设备(beta) | | `kiri build-with [docker \| kiri]` | 选择 `docker build` 使用的构建器 | | `kiri update [--check]` | 安装最新版本 | +| `kiri doctor [--json]` | 检查 Kiri 各组件是否正常工作,异常时给出修复命令 | | `kiri diag logs \| report` | 日志,以及随 bug 报告提交的报告文件 | | `kiri bench [--runs N] [--network none\|bridge]` | 在你的机器上测量容器启动速度 | | `kiri ui` | 打开窗口 | diff --git a/crates/kiri/src/doctor.rs b/crates/kiri/src/doctor.rs new file mode 100644 index 000000000..df3dc9960 --- /dev/null +++ b/crates/kiri/src/doctor.rs @@ -0,0 +1,1118 @@ +//! `kiri doctor`: whether this installation works, one line per part, and +//! what to run for a part that doesn't (#747). It asks what the window and +//! `kiri diag report` already ask, as the window's own background requests +//! (they neither wake the VM nor count as use), and changes nothing: each +//! fix stays its own command. +//! +//! On Windows the engine's lines come from the `kiri` in WSL, asked without +//! `kiri-start` so a stopped engine stays stopped, and the docker line from +//! the user's own `docker.exe`. + +use std::io::{self, Read}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::flavor::CONTEXT; + +const USAGE: &str = "usage: kiri doctor [--json] whether Kiri works here, and what to run when a part doesn't (exit 1 on a failure)"; + +/// How long the engine gets for all its answers, and docker for its. +const ENGINE_WAIT: Duration = Duration::from_secs(10); +const DOCKER_WAIT: Duration = Duration::from_secs(10); + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Status { + Ok, + /// Works, but not all the way: names, a router moved aside, docker elsewhere. + Warn, + /// Kiri can't be used until it is put right: the exit code says so. + Fail, +} + +impl Status { + fn word(self) -> &'static str { + match self { + Status::Ok => "ok", + Status::Warn => "warn", + Status::Fail => "fail", + } + } + + #[cfg(any(windows, test))] + fn from_word(w: &str) -> Option { + [Status::Ok, Status::Warn, Status::Fail] + .into_iter() + .find(|s| s.word() == w) + } +} + +#[derive(Debug, PartialEq)] +struct Check { + name: String, + status: Status, + detail: String, +} + +fn check(name: impl Into, status: Status, detail: impl Into) -> Check { + Check { + name: name.into(), + status, + detail: detail.into(), + } +} + +pub fn run(args: &[String]) -> io::Result<()> { + let json = match args + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + [] => false, + ["--json"] => true, + ["-h" | "--help" | "help"] => { + println!("{USAGE}"); + return Ok(()); + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + }; + let checks = checks(); + if json { + println!("{}", to_json(&checks)); + } else { + print!("{}", render(&checks)); + } + if checks.iter().any(|c| c.status == Status::Fail) { + // The lines said what is wrong; a `kiri: …` line after them would only repeat it. + std::process::exit(1); + } + Ok(()) +} + +// ---- the engine (Mac, Linux, and WSL for Windows) ---- + +#[cfg(any(unix, test))] +/// An answer from the engine: its JSON, or the error's kind and text. `None` +/// in its slot means no answer within `ENGINE_WAIT`. +type Answer = Option>; + +#[cfg(unix)] +/// What the engine is asked, in order: once /_ping fails nothing else is. +const ASKED: [&str; 4] = ["/_ping", "/version", "/info", "/kiri/domains"]; + +#[cfg(unix)] +fn checks() -> Vec { + // Set by Windows' `kiri doctor`, which checks docker on its own side. + let forwarded = std::env::var_os("KIRI_DOCTOR_FORWARDED").is_some(); + let socket = crate::client::socket() + .map(|p| p.display().to_string()) + .unwrap_or_else(|_| "?".into()); + let got = engine_answers(); + // Down, the engine can't say; a read-only disk is what keeps it down (#768). + let local = if matches!(got[0], Some(Ok(_))) { + None + } else { + crate::daemon::rofs::check_daemon_storage(None) + }; + let mut out = engine_checks(&got, &socket, forwarded, local); + if !forwarded { + let create = format!( + "docker context create {c} --docker host=unix://{socket} && docker context use {c}", + c = CONTEXT.get() + ); + out.insert(1, docker(&ours_unix, &create)); + } + #[cfg(target_os = "macos")] + out.push(names(crate::daemon::dns::installed())); + out +} + +/// The engine's answers, each as soon as it comes, for at most `ENGINE_WAIT` +/// in all: an engine that is hung, or answers a byte at a time, would +/// otherwise keep this waiting (the client's limit is per read). +#[cfg(unix)] +fn engine_answers() -> [Answer; 4] { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for (i, path) in ASKED.into_iter().enumerate() { + let r = crate::client::get_background(path).map_err(|e| { + // Nothing there, or a socket this user can't open: say it as other commands do. + let gone = !matches!( + e.kind(), + io::ErrorKind::Other | io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ); + let e = if i == 0 && gone { + crate::client::check_alive().err().unwrap_or(e) + } else { + e + }; + (e.kind(), e.to_string()) + }); + let stop = i == 0 && r.is_err(); + if tx.send((i, r)).is_err() || stop { + return; + } + } + }); + let until = Instant::now() + ENGINE_WAIT; + let mut got: [Answer; 4] = Default::default(); + while let Ok((i, r)) = rx.recv_timeout(until.saturating_duration_since(Instant::now())) { + got[i] = Some(r); + } + got +} + +#[cfg(any(unix, test))] +/// The engine's lines from its answers: engine, http, https, storage. +fn engine_checks( + got: &[Answer; 4], + socket: &str, + forwarded: bool, + local_storage: Option, +) -> Vec { + let mut out = Vec::new(); + let engine = match &got[0] { + None => check( + "engine", + Status::Fail, + format!( + "{socket} took the connection but answered nothing in 10 s: the engine may be hung (kiri diag logs --engine)" + ), + ), + Some(Err((io::ErrorKind::Other, m))) => check( + "engine", + Status::Fail, + format!("the engine answers, with an error: {m}"), + ), + Some(Err((io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut, _))) => check( + "engine", + Status::Fail, + format!( + "{socket} took the connection but answered nothing: the engine may be hung (kiri diag logs --engine)" + ), + ), + Some(Err((io::ErrorKind::PermissionDenied, m))) => check("engine", Status::Fail, m.clone()), + Some(Err(_)) if forwarded => check( + "engine", + Status::Fail, + "the engine isn't running in Kiri's WSL distro: kiri start", + ), + Some(Err((_, m))) => check("engine", Status::Fail, m.clone()), + Some(Ok(_)) => engine_line(&got[1], &got[2], socket), + }; + out.push(engine); + if !matches!(got[0], Some(Ok(_))) { + out.extend(local_storage.map(|m| check("storage", Status::Fail, m))); + return out; + } + out.extend(domains(&got[3])); + out.extend(storage(&got[2])); + out +} + +#[cfg(any(unix, test))] +fn engine_line(version: &Answer, info: &Answer, socket: &str) -> Check { + let mut c = match version { + None => check( + "engine", + Status::Warn, + "answers /_ping but not /version within 10 s: it may be busy or hung", + ), + Some(Err((_, m))) => check( + "engine", + Status::Warn, + format!("answers /_ping, but /version failed: {m}"), + ), + // A Docker engine of another kind behind KIRI_SOCKET. + Some(Ok(v)) if v["Platform"]["Name"].as_str().is_some_and(|n| n != "Kiri") => check( + "engine", + Status::Warn, + format!( + "{socket} is {}, not Kiri", + v["Platform"]["Name"].as_str().unwrap_or("?") + ), + ), + // KiriVersion, or Version from an engine older than that field (client::kiri_version). + Some(Ok(v)) => check( + "engine", + Status::Ok, + format!( + "Kiri {}, socket {socket}", + v["KiriVersion"] + .as_str() + .or_else(|| v["Version"].as_str()) + .unwrap_or("?") + ), + ), + }; + if matches!(info, Some(Ok(i)) if i["KiriStopped"] == true) { + c.status = Status::Warn; + c.detail + .push_str("; stopped (Stop in the window or tray): kiri start starts it"); + } + c +} + +#[cfg(any(unix, test))] +/// The `*.kiri.local` routers, from the engine's `/kiri/domains`. +fn domains(answer: &Answer) -> Vec { + let both = |status, detail: String| { + vec![ + check("http", status, detail.clone()), + check("https", status, detail), + ] + }; + let report = match answer { + None => return both(Status::Warn, "the engine didn't say within 10 s".into()), + Some(Err((_, m))) => return both(Status::Warn, format!("the engine didn't say: {m}")), + Some(Ok(r)) if r["http"].is_object() && r["https"].is_object() => r, + Some(Ok(_)) => return both(Status::Warn, "the engine's answer wasn't readable".into()), + }; + ["http", "https"] + .into_iter() + .map(|key| { + let r = &report[key]; + let port = r["port"].as_u64().map_or_else(|| "?".into(), |p| p.to_string()); + // A port set by the environment can't be moved here (domains.rs refuses it). + let (by, fix) = match r["env"].as_str() { + Some(var) => (format!(" (set by {var})"), format!("change or unset {var}")), + None => (String::new(), format!("kiri domains set --{key} N")), + }; + match (r["running"] == true, r["serving"] != false) { + (true, true) => check(key, Status::Ok, format!("port {port}{by}")), + (true, false) => check(key, Status::Warn, format!("port {port}{by}: a container has the port for now; {fix} moves the router")), + (false, _) => check(key, Status::Warn, format!("off, port {port}{by}: names under kiri.local don't answer over {key}; {fix} tries another port")), + } + }) + .collect() +} + +#[cfg(any(unix, test))] +/// The engine's storage: read-only means nothing can be written (#768). An +/// engine that predates the field says nothing, and nor does this. +fn storage(info: &Answer) -> Option { + match info { + None => Some(check( + "storage", + Status::Warn, + "the engine didn't say within 10 s", + )), + Some(Err((_, m))) => Some(check( + "storage", + Status::Warn, + format!("the engine didn't say: {m}"), + )), + Some(Ok(i)) => match i.get("KiriStorageReadOnly") { + Some(Value::String(why)) => Some(check("storage", Status::Fail, why.clone())), + Some(_) => Some(check("storage", Status::Ok, "writable")), + None => None, + }, + } +} + +/// macOS sends `*.kiri.local` lookups to Kiri only with its resolver file. +#[cfg(any(target_os = "macos", test))] +fn names(installed: bool) -> Check { + if installed { + check("names", Status::Ok, "*.kiri.local resolves to Kiri") + } else { + check( + "names", + Status::Warn, + "*.kiri.local doesn't resolve (/etc/resolver/kiri.local is missing; *.kiri.localhost works): kiri setup --domains", + ) + } +} + +// ---- docker ---- + +/// Whether a docker host is this Kiri's socket: `Some(false)` only when +/// both are local sockets and resolve to different files (another Kiri, +/// such as the installed one next to Kiri Dev). +#[cfg(unix)] +fn ours_unix(host: &str) -> Option { + let theirs = std::fs::canonicalize(host.strip_prefix("unix://")?).ok()?; + let ours = std::fs::canonicalize(crate::client::socket().ok()?).ok()?; + Some(theirs == ours) +} + +enum Reached { + /// The server's platform name ("" from an engine that has none). + Server(String), + Failed, + TimedOut, +} + +/// Which engine plain `docker` reaches, asked of docker itself, so a +/// context, DOCKER_HOST and a packaged wrapper count as they do for the user. +fn docker(ours: &dyn Fn(&str) -> Option, create: &str) -> Check { + let until = Instant::now() + DOCKER_WAIT; + let docker = || { + let mut c = Command::new("docker"); + c.env_remove("KIRI_DOCTOR_FORWARDED"); + c + }; + let version = match run_for( + docker().args(["version", "--format", "{{.Server.Platform.Name}}"]), + until, + ) { + Err(e) if e.kind() == io::ErrorKind::NotFound => { + return check("docker", Status::Warn, "no `docker` command found on PATH"); + } + Err(e) => { + return check( + "docker", + Status::Warn, + format!("`docker` couldn't be run: {e}"), + ); + } + Ok(r) => r, + }; + let (reached, why) = match &version { + None => (Reached::TimedOut, String::new()), + Some(r) if r.ok => ( + Reached::Server(first_line(&text(&r.out)).to_owned()), + String::new(), + ), + // docker's own error is its last line; Docker Desktop's WSL shim says why on stdout, first. + Some(r) => { + let err = text(&r.err); + let why = match err.lines().rev().find(|l| !l.trim().is_empty()) { + Some(last) => first_line(last).to_owned(), + None => first_line(&text(&r.out)).to_owned(), + }; + (Reached::Failed, why) + } + }; + let context = run_for( + docker().args([ + "context", + "inspect", + "--format", + "{{.Name}}\t{{.Endpoints.docker.Host}}", + ]), + Instant::now() + Duration::from_secs(2), + ) + .ok() + .flatten() + .filter(|r| r.ok) + .and_then(|r| { + text(&r.out) + .lines() + .next() + .and_then(|l| l.split_once('\t')) + .map(|(n, h)| (n.to_owned(), h.to_owned())) + }); + let env_host = std::env::var("DOCKER_HOST").ok().filter(|s| !s.is_empty()); + let pinned = if env_host.is_some() { + Some("DOCKER_HOST") + } else if std::env::var_os("DOCKER_CONTEXT").is_some_and(|s| !s.is_empty()) { + Some("DOCKER_CONTEXT") + } else { + None + }; + let (name, ctx_host) = context + .as_ref() + .map_or((None, None), |(n, h)| (Some(n.as_str()), Some(h.as_str()))); + let host = env_host.as_deref().or(ctx_host); + let ours = host.and_then(ours); + let have_ours = || { + run_for( + docker().args(["context", "inspect", CONTEXT.get()]), + Instant::now() + Duration::from_secs(2), + ) + .ok() + .flatten() + .is_some_and(|r| r.ok) + }; + let fix = match pinned { + Some(var) => format!("unset {var}, or point it at Kiri"), + // At this Kiri already: nothing to say, and no time spent asking. + None if ours != Some(false) && matches!(reached, Reached::Server(ref n) if n == "Kiri") => { + String::new() + } + None if have_ours() => format!("docker context use {}", CONTEXT.get()), + None => create.to_owned(), + }; + docker_verdict(&reached, &why, name, host, pinned, ours, &fix) +} + +fn docker_verdict( + reached: &Reached, + why: &str, + context: Option<&str>, + host: Option<&str>, + pinned: Option<&str>, + ours: Option, + fix: &str, +) -> Check { + let how = match (pinned, context) { + (Some(var), _) => format!("{var} is set"), + (None, Some(c)) => format!("context `{c}`"), + (None, None) => "context unknown".into(), + }; + // Already pointed at Kiri: no answer then is the engine's trouble, not docker's. + let at_kiri = ours == Some(true) || (pinned.is_none() && context == Some(CONTEXT.get())); + match reached { + Reached::Server(n) if n == "Kiri" && ours == Some(false) => check( + "docker", + Status::Warn, + format!( + "`docker` reaches another Kiri ({how}, {}): {fix}", + host.unwrap_or("?") + ), + ), + Reached::Server(n) if n == "Kiri" => check( + "docker", + Status::Ok, + format!("`docker` reaches Kiri ({how})"), + ), + Reached::Server(n) if !n.is_empty() => check( + "docker", + Status::Warn, + format!("`docker` reaches {n}, not Kiri ({how}): {fix}"), + ), + Reached::Server(_) => check( + "docker", + Status::Warn, + format!("`docker` reaches an engine that isn't Kiri ({how}): {fix}"), + ), + Reached::Failed | Reached::TimedOut if at_kiri => check( + "docker", + Status::Warn, + format!("`docker` is set to Kiri ({how}) but gets no answer: see the engine line"), + ), + Reached::Failed => check( + "docker", + Status::Warn, + format!( + "`docker` reaches no engine ({how}): {}; {fix}", + if why.is_empty() { "no answer" } else { why } + ), + ), + Reached::TimedOut => check( + "docker", + Status::Warn, + format!("`docker` got no answer in 10 s ({how}): {fix}"), + ), + } +} + +/// A line of a tool's output fit for one line here: its first non-empty +/// one, cut at 200 characters. +fn first_line(s: &str) -> &str { + let l = s + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or(""); + l.char_indices().nth(200).map_or(l, |(i, _)| &l[..i]) +} + +fn text(b: &[u8]) -> String { + String::from_utf8_lossy(b).into_owned() +} + +struct Ran { + ok: bool, + out: Vec, + err: Vec, +} + +/// Runs `cmd` until `until` at the latest, its output read as it comes (so +/// a full pipe never stalls it). Past `until` it is killed with what it +/// started, and the answer is `None`. +fn run_for(cmd: &mut Command, until: Instant) -> io::Result> { + cmd.stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(cmd, 0); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(cmd, 0x0800_0000); + let mut child = cmd.spawn()?; + let (out, err) = (reader(child.stdout.take()), reader(child.stderr.take())); + let status = loop { + if let Some(s) = child.try_wait()? { + break s; + } + if Instant::now() >= until { + kill_tree(&mut child); + return Ok(None); + } + std::thread::sleep(Duration::from_millis(20)); + }; + // A process it left holding the pipes doesn't hold this up past `until`. + let grace = until + .saturating_duration_since(Instant::now()) + .max(Duration::from_millis(200)); + let take = |rx: mpsc::Receiver>| rx.recv_timeout(grace).unwrap_or_default(); + Ok(Some(Ran { + ok: status.success(), + out: take(out), + err: take(err), + })) +} + +fn reader(r: Option) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut b = Vec::new(); + if let Some(mut r) = r { + let _ = r.read_to_end(&mut b); + } + let _ = tx.send(b); + }); + rx +} + +/// Kills `child` and every process it started (its process group; on +/// Windows, its tree). +fn kill_tree(child: &mut std::process::Child) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: a plain signal to the group this child leads (`process_group(0)`). + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + let _ = Command::new("taskkill") + .args(["/F", "/T", "/PID", &child.id().to_string()]) + .creation_flags(0x0800_0000) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + let _ = child.kill(); + let _ = child.wait(); +} + +// ---- Windows ---- + +/// The engine's own `kiri doctor` in WSL, without kiri-start (which would +/// start a stopped engine) and without its docker line. +#[cfg(any(windows, test))] +const FORWARD_SCRIPT: &str = r#"export HOME=/var/lib/kiri-daemon KIRI_DOCTOR_FORWARDED=1; exec /usr/local/bin/kiri doctor --json"#; + +#[cfg(windows)] +fn checks() -> Vec { + let mut out = engine_from_wsl(); + out.insert( + 1.min(out.len()), + docker( + &|_| None, + &format!( + "docker context use {} (Kiri creates it at start)", + CONTEXT.get() + ), + ), + ); + out +} + +#[cfg(windows)] +fn engine_from_wsl() -> Vec { + let stopped = |why: String| { + vec![check( + "engine", + Status::Warn, + format!("stopped{why}: kiri start starts it"), + )] + }; + let local = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from); + if local + .as_ref() + .is_some_and(|d| crate::wsl::stopped_marker_in(d).exists()) + { + return stopped(" (Stop in the window or tray)".into()); + } + let Some(distro) = crate::wsl::distro() else { + return vec![check( + "engine", + Status::Fail, + "Kiri isn't set up yet: open Kiri from the Start menu", + )]; + }; + let system = std::env::var_os("SystemRoot").map_or_else( + || std::path::PathBuf::from(r"C:\Windows"), + std::path::PathBuf::from, + ); + let wsl = system.join("System32").join("wsl.exe"); + // Asking a distro that isn't running would boot it, and the engine with it. + if let Ok(Some(r)) = run_for( + Command::new(&wsl).args(["--list", "--running", "--quiet"]), + Instant::now() + ENGINE_WAIT, + ) && r.ok + && !running_distros(&r.out) + .iter() + .any(|d| d.eq_ignore_ascii_case(&distro)) + { + return stopped(format!(" (its WSL distro {distro} isn't running)")); + } + match run_for(Command::new(&wsl).args(["-d", &distro, "-u", "root", "-e", "sh", "-c", FORWARD_SCRIPT]), Instant::now() + ENGINE_WAIT * 3) { + Ok(Some(r)) => from_forwarded(&text(&r.out)).unwrap_or_else(|| { + let err = text(&r.err); + let detail = match first_line(&err) { + // A kiri from before `kiri doctor` prints its usage. + why if why.is_empty() || why.starts_with("usage: kiri") => "the engine's kiri in WSL has no `kiri doctor` (it is older than this one): update Kiri".to_owned(), + why => format!("the engine's kiri in WSL gave no doctor answer: {why}"), + }; + vec![check("engine", Status::Fail, detail)] + }), + Ok(None) => vec![check("engine", Status::Fail, "the engine's kiri in WSL didn't answer in 30 s")], + Err(e) => vec![check("engine", Status::Fail, format!("could not run wsl.exe ({e})"))], + } +} + +/// `wsl --list --quiet` writes UTF-16, one distro a line. +#[cfg(any(windows, test))] +fn running_distros(out: &[u8]) -> Vec { + let s = if out.contains(&0) { + String::from_utf16_lossy( + &out.as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .collect::>(), + ) + } else { + text(out) + }; + s.lines() + .map(|l| { + l.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}') + .to_owned() + }) + .filter(|l| !l.is_empty()) + .collect() +} + +/// The checks from the WSL side's `--json`. +#[cfg(any(windows, test))] +fn from_forwarded(out: &str) -> Option> { + let v: Value = serde_json::from_str(out.trim()).ok()?; + v["checks"] + .as_array()? + .iter() + .map(|c| { + Some(check( + c["name"].as_str()?, + Status::from_word(c["status"].as_str()?)?, + c["detail"].as_str()?, + )) + }) + .collect() +} + +// ---- output ---- + +fn render(checks: &[Check]) -> String { + checks + .iter() + .map(|c| format!("{:<13} {:<5} {}\n", c.name, c.status.word(), c.detail)) + .collect() +} + +fn to_json(checks: &[Check]) -> Value { + json!({ + "ok": !checks.iter().any(|c| c.status == Status::Fail), + "checks": checks.iter().map(|c| json!({"name": c.name, "status": c.status.word(), "detail": c.detail})).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ok(v: Value) -> Answer { + Some(Ok(v)) + } + fn err(kind: io::ErrorKind, m: &str) -> Answer { + Some(Err((kind, m.into()))) + } + const SOCK: &str = "/run/kiri/docker.sock"; + fn healthy() -> [Answer; 4] { + [ + ok(Value::Null), + ok(json!({"KiriVersion": "0.2.3", "Platform": {"Name": "Kiri"}})), + ok(json!({"KiriStorageReadOnly": null, "KiriStopped": false})), + ok( + json!({"http": {"port": 80, "running": true, "serving": true, "env": null}, "https": {"port": 443, "running": true, "serving": true, "env": null}}), + ), + ] + } + fn names_of(c: &[Check]) -> Vec<&str> { + c.iter().map(|c| c.name.as_str()).collect() + } + + #[test] + fn a_healthy_engine_gives_four_ok_lines() { + let c = engine_checks(&healthy(), SOCK, false, None); + assert_eq!(names_of(&c), ["engine", "http", "https", "storage"]); + assert!(c.iter().all(|c| c.status == Status::Ok), "{c:?}"); + assert_eq!(c[0].detail, "Kiri 0.2.3, socket /run/kiri/docker.sock"); + } + + #[test] + fn an_engine_that_is_down_hung_or_erroring_says_which() { + let mut got: [Answer; 4] = Default::default(); + let down = engine_checks(&got, SOCK, false, None); + assert_eq!((down.len(), down[0].status), (1, Status::Fail)); + assert!( + down[0].detail.contains("answered nothing in 10 s"), + "{down:?}" + ); + got[0] = err(io::ErrorKind::Other, "Internal Server Error"); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "the engine answers, with an error: Internal Server Error" + ); + got[0] = err(io::ErrorKind::NotConnected, "Kiri isn't running. Open Kiri"); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "Kiri isn't running. Open Kiri" + ); + assert_eq!( + engine_checks(&got, SOCK, true, None)[0].detail, + "the engine isn't running in Kiri's WSL distro: kiri start" + ); + got[0] = err( + io::ErrorKind::PermissionDenied, + "permission denied. Run `sudo kiri host-access $USER`", + ); + assert!( + engine_checks(&got, SOCK, true, None)[0] + .detail + .starts_with("permission denied") + ); + // Down because the disk went read-only: that is the line that says why. + let ro = engine_checks(&got, SOCK, false, Some("Kiri's disk is read-only".into())); + assert_eq!( + ro[1], + check("storage", Status::Fail, "Kiri's disk is read-only") + ); + } + + #[test] + fn a_stopped_or_foreign_or_slow_engine_is_not_ok() { + let mut got = healthy(); + got[2] = ok(json!({"KiriStorageReadOnly": null, "KiriStopped": true})); + let c = engine_checks(&got, SOCK, false, None); + assert_eq!(c[0].status, Status::Warn); + assert!( + c[0].detail + .ends_with("stopped (Stop in the window or tray): kiri start starts it"), + "{}", + c[0].detail + ); + got = healthy(); + got[1] = + ok(json!({"Version": "27.3.1", "Platform": {"Name": "Docker Engine - Community"}})); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "/run/kiri/docker.sock is Docker Engine - Community, not Kiri" + ); + got[1] = ok(json!({"Version": "0.1.9"})); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0], + check( + "engine", + Status::Ok, + "Kiri 0.1.9, socket /run/kiri/docker.sock" + ) + ); + got[1] = None; + got[2] = None; + got[3] = None; + let slow = engine_checks(&got, SOCK, false, None); + assert_eq!(names_of(&slow), ["engine", "http", "https", "storage"]); + assert!(slow.iter().all(|c| c.status == Status::Warn), "{slow:?}"); + } + + #[test] + fn each_router_is_ok_moved_aside_off_or_unreadable() { + let r = |http: Value| { + ok(json!({"http": http, "https": {"port": 443, "running": true, "serving": true}})) + }; + assert_eq!( + domains(&r(json!({"port": 80, "running": true})))[0], + check("http", Status::Ok, "port 80") + ); + let moved = &domains(&r(json!({"port": 80, "running": true, "serving": false})))[0]; + assert_eq!( + moved.detail, + "port 80: a container has the port for now; kiri domains set --http N moves the router" + ); + let pinned = &domains(&r( + json!({"port": 18780, "running": false, "env": "KIRI_HTTP_PORT"}), + ))[0]; + assert!( + pinned + .detail + .starts_with("off, port 18780 (set by KIRI_HTTP_PORT)") + && pinned + .detail + .ends_with("change or unset KIRI_HTTP_PORT tries another port"), + "{}", + pinned.detail + ); + for bad in [ + ok(json!({})), + ok(Value::Null), + ok(json!({"http": 1, "https": 2})), + err( + io::ErrorKind::Other, + "Kiri does not support GET /kiri/domains yet", + ), + None, + ] { + let c = domains(&bad); + assert_eq!(names_of(&c), ["http", "https"]); + assert!( + c.iter() + .all(|c| c.status == Status::Warn && !c.detail.contains("tries another port")), + "{c:?}" + ); + } + } + + #[test] + fn storage_says_only_what_the_engine_said() { + assert_eq!( + storage(&ok( + json!({"KiriStorageReadOnly": "the store is read-only"}) + )), + Some(check("storage", Status::Fail, "the store is read-only")) + ); + assert_eq!( + storage(&ok(json!({"KiriStorageReadOnly": null}))), + Some(check("storage", Status::Ok, "writable")) + ); + assert_eq!(storage(&ok(json!({"Containers": 3}))), None); + assert_eq!( + storage(&err(io::ErrorKind::Other, "boom")).unwrap().status, + Status::Warn + ); + assert_eq!(storage(&None).unwrap().status, Status::Warn); + } + + #[test] + fn docker_is_ok_only_at_this_kiri_and_its_advice_fits_the_case() { + let ctx = CONTEXT.get(); + let kiri = Reached::Server("Kiri".into()); + assert_eq!( + docker_verdict( + &kiri, + "", + Some(ctx), + Some("unix:///x"), + None, + Some(true), + "" + ) + .status, + Status::Ok + ); + let other_kiri = docker_verdict( + &kiri, + "", + Some("default"), + Some("unix:///var/run/docker.sock"), + None, + Some(false), + "docker context use kiri", + ); + assert!( + other_kiri.status == Status::Warn && other_kiri.detail.contains("another Kiri"), + "{other_kiri:?}" + ); + let desktop = docker_verdict( + &Reached::Server("Docker Desktop 4.40.0 (187762)".into()), + "", + Some("desktop-linux"), + None, + None, + None, + "docker context use kiri", + ); + assert_eq!( + desktop.detail, + "`docker` reaches Docker Desktop 4.40.0 (187762), not Kiri (context `desktop-linux`): docker context use kiri" + ); + assert!( + docker_verdict( + &Reached::Server(String::new()), + "", + Some("default"), + None, + None, + None, + "x" + ) + .detail + .contains("isn't Kiri") + ); + // On Kiri's context and nothing answers: the engine is the trouble, not the context. + let down = docker_verdict( + &Reached::Failed, + "Cannot connect", + Some(ctx), + None, + None, + None, + "docker context use kiri", + ); + assert_eq!( + down.detail, + format!( + "`docker` is set to Kiri (context `{ctx}`) but gets no answer: see the engine line" + ) + ); + let pinned = docker_verdict( + &Reached::Failed, + "Cannot connect to the Docker daemon at tcp://10.0.0.9:2375.", + Some("default"), + None, + Some("DOCKER_HOST"), + None, + "unset DOCKER_HOST, or point it at Kiri", + ); + assert_eq!( + pinned.detail, + "`docker` reaches no engine (DOCKER_HOST is set): Cannot connect to the Docker daemon at tcp://10.0.0.9:2375.; unset DOCKER_HOST, or point it at Kiri" + ); + assert!( + docker_verdict( + &Reached::TimedOut, + "", + Some("remote"), + None, + None, + None, + "f" + ) + .detail + .starts_with("`docker` got no answer in 10 s") + ); + } + + #[test] + fn a_tools_message_is_one_line() { + let shim = "\nThe command 'docker' could not be found in this WSL 2 distro.\nWe recommend to activate the WSL integration in Docker Desktop settings.\n"; + assert_eq!( + first_line(shim), + "The command 'docker' could not be found in this WSL 2 distro." + ); + assert_eq!(first_line(&"x".repeat(500)).len(), 200); + assert_eq!(first_line("é".repeat(300).as_str()).chars().count(), 200); + } + + /// A tool that floods its pipes, or hangs leaving a child behind, is + /// read or stopped within the time it was given. + #[cfg(unix)] + #[test] + fn a_tool_is_read_as_it_writes_and_stopped_with_its_children() { + let big = run_for( + Command::new("sh").args(["-c", "head -c 300000 /dev/zero | tr '\\0' x >&2; echo Kiri"]), + Instant::now() + Duration::from_secs(5), + ) + .unwrap() + .unwrap(); + assert!(big.ok && big.err.len() == 300_000 && text(&big.out).trim() == "Kiri"); + let marker = format!("kiri-doctor-hang-{}", std::process::id()); + let t = Instant::now(); + let hung = run_for( + Command::new("sh").args(["-c", &format!("sh -c 'exec sleep 30 {marker}' & sleep 30")]), + Instant::now() + Duration::from_millis(300), + ) + .unwrap(); + assert!( + hung.is_none() && t.elapsed() < Duration::from_secs(3), + "{:?}", + t.elapsed() + ); + let left = Command::new("pgrep") + .args(["-f", &marker]) + .output() + .unwrap(); + assert!( + left.stdout.is_empty(), + "left running: {}", + text(&left.stdout) + ); + assert_eq!( + run_for( + &mut Command::new("kiri-doctor-no-such-tool"), + Instant::now() + Duration::from_secs(1) + ) + .err() + .map(|e| e.kind()), + Some(io::ErrorKind::NotFound) + ); + } + + #[test] + fn windows_reads_the_wsl_sides_answer() { + let out = r#"{"checks":[{"detail":"Kiri 0.2.3","name":"engine","status":"ok"},{"detail":"read-only","name":"storage","status":"fail"}],"ok":false}"#; + assert_eq!( + from_forwarded(out).unwrap(), + vec![ + check("engine", Status::Ok, "Kiri 0.2.3"), + check("storage", Status::Fail, "read-only") + ] + ); + for bad in [ + "", + "kiri: usage: kiri COMMAND", + r#"{"checks":[{"name":"engine","status":"maybe","detail":""}]}"#, + ] { + assert!(from_forwarded(bad).is_none(), "{bad}"); + } + let utf16: Vec = "Kiri\r\nUbuntu\r\n" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!(running_distros(&utf16), ["Kiri", "Ubuntu"]); + assert!(!FORWARD_SCRIPT.contains("kiri-start")); + } + + #[test] + fn only_a_failure_makes_it_not_ok() { + let warn_only = [check("http", Status::Warn, "off"), names(false)]; + assert_eq!(to_json(&warn_only)["ok"], true); + let failed = [ + check("engine", Status::Ok, "Kiri 0.2.3"), + check("storage", Status::Fail, "the store is read-only"), + ]; + let j = to_json(&failed); + assert_eq!(j["ok"], false); + assert_eq!( + j["checks"][1], + json!({"name": "storage", "status": "fail", "detail": "the store is read-only"}) + ); + assert_eq!( + render(&failed), + "engine ok Kiri 0.2.3\nstorage fail the store is read-only\n" + ); + } + + #[test] + fn refuses_what_it_does_not_take() { + for bad in [&["--fix"][..], &["--json", "--json"], &["engine"]] { + let args: Vec = bad.iter().map(|s| s.to_string()).collect(); + assert_eq!( + run(&args).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + "{bad:?}" + ); + } + assert!(!crate::docker::handles("doctor")); + } +} diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 899fa96ca..064ca6645 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -44,6 +44,9 @@ mod docker; #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), test))] #[cfg_attr(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))), allow(dead_code))] mod dockerctx; +// `kiri doctor`: whether this installation works (Windows: docker here, the engine in WSL). +#[cfg(any(unix, windows))] +mod doctor; // `kiri domains`: the container-domain routers' ports (Windows: in WSL). #[cfg(unix)] mod domains_cli; @@ -116,6 +119,7 @@ const USAGE_LINES: &[&str] = &[ " kiri update [--check] update Kiri (with a container: docker's update)", #[cfg(target_os = "linux")] " kiri update --check check for a newer Kiri (with a container: docker's update)", + " kiri doctor [--json] whether Kiri works here, and what to run when a part doesn't", " kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N]", " kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out)", " kiri PORT [NAME] share a local port on the internet (same as kiri share PORT)", @@ -180,6 +184,8 @@ enum Command<'a> { BuildWith(&'a [String]), #[cfg(unix)] Domains(&'a [String]), + #[cfg(any(unix, windows))] + Doctor(&'a [String]), #[cfg(unix)] Storage(&'a [String]), #[cfg(unix)] @@ -250,6 +256,8 @@ impl<'a> Command<'a> { Some("build-with") => Some(Command::BuildWith(&args[1..])), #[cfg(unix)] Some("domains") => Some(Command::Domains(&args[1..])), + #[cfg(any(unix, windows))] + Some("doctor") => Some(Command::Doctor(&args[1..])), #[cfg(unix)] Some("storage") => Some(Command::Storage(&args[1..])), #[cfg(unix)] @@ -336,6 +344,8 @@ fn main() -> ExitCode { Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] Some(Command::Domains(rest)) => domains_cli::run(rest), + #[cfg(any(unix, windows))] + Some(Command::Doctor(rest)) => doctor::run(rest), #[cfg(unix)] Some(Command::Storage(rest)) => storage_cli::run(rest), #[cfg(unix)] @@ -497,7 +507,7 @@ mod tests { fn usage_lists_only_commands_for_this_os() { let help = usage(); let cmds = advertised_subcommands(&help); - for common in ["COMMAND", "start", "domains", "storage", "registry", "scan", "diag", "PORT", "share", "k8s", "usb", "machine"] { + for common in ["COMMAND", "start", "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}"); diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 17bd4fa15..42079ab3e 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -1,5 +1,6 @@ //! `kiri k8s`, `kiri machine`, `kiri diag`, `kiri usb`, `kiri domains`, -//! `kiri registry` and `kiri scan` on Windows: the engine's own +//! `kiri registry`, `kiri scan` and `kiri storage` on Windows (and the +//! engine's half of `kiri doctor`, doctor.rs): the engine's own //! commands, run by the Linux `kiri` in the WSL distro Kiri's engine lives //! in, as the engine runs (root, with its HOME), so it finds the daemon's //! socket and store. `kiri diag report [--out PATH]` writes the report file @@ -335,7 +336,7 @@ pub fn run(args: &[String]) -> io::Result<()> { } /// The distro setup put the engine in (crates/kiri-win/src/setup.rs). -fn distro() -> Option { +pub(crate) fn distro() -> Option { let dir = PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Kiri"); let v: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("setup.json")).ok()?).ok()?; v["distro"].as_str().map(str::to_owned) From 6f2595cfaab778ed509585aebe2c017bc4e2be46 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:53:30 +0100 Subject: [PATCH 128/157] Guest kernel: enable NFSv3/v4 client for type=nfs volumes and dm-crypt/LUKS (#494) (#961) Co-authored-by: meutex Co-authored-by: Marcin Uliasz --- docs/features.md | 11 ++++++++++- guest/kernel/kiri.config | 25 +++++++++++++++++++++++++ tests/e2e.sh | 3 +++ tests/regressions.tsv | 1 + 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index 868ea0c90..6e05d4c39 100644 --- a/docs/features.md +++ b/docs/features.md @@ -48,7 +48,11 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr `kiri domains reset` puts back 80 and 443 - **Storage**: named and anonymous volumes, bind mounts of Mac paths (virtiofs), `--tmpfs`, `--mount`, `volume` commands; local volumes that - bind a folder (`driver_opts: {type: none, o: bind, device: /path}`) + bind a folder (`driver_opts: {type: none, o: bind, device: /path}`); + local-driver volumes with `driver_opts` `type=nfs` mount a remote NFS + export — NFSv4 (minorversion 4.0 and 4.1) and NFSv3, honouring `addr=`, + `nfsvers=`, `hard`/`soft`, `timeo`, `retrans`, `ro`/`rw` and `noatime`; + LUKS / `dm-crypt` in the guest kernel (`CONFIG_DM_CRYPT`) - **Images**: `pull` (with `docker login` credentials), `push`, `tag`, `save`, `load`, `history`, `search`, `image prune`, `system df`; **amd64 images run through Rosetta**, `--platform` honoured @@ -246,3 +250,8 @@ To trust a private certificate authority at a Kiri Share edge only, set `KIRI_SH registry-1.docker.io ...`). The builder runs on the default bridge, so check from a container there: `docker run --rm alpine nslookup registry-1.docker.io`. + +- **`type=cifs` (SMB) volumes don't mount yet.** Kiri's guest kernel has no + CIFS client, so a local-driver volume with `driver_opts: {type: cifs}` + fails the same way NFS-backed volumes did before NFS support landed. + SMB support is a separate change. diff --git a/guest/kernel/kiri.config b/guest/kernel/kiri.config index dfb9d00da..b41a9522d 100644 --- a/guest/kernel/kiri.config +++ b/guest/kernel/kiri.config @@ -91,6 +91,20 @@ CONFIG_BLK_DEV_LOOP=y CONFIG_NETDEVICES=y CONFIG_NET_CORE=y +# --- device mapper (dm-crypt, LUKS) ---------------------------------------------- +# dm-crypt for encrypted disk images and LUKS volumes in privileged +# containers. The device-mapper core lives in drivers/md, gated behind the +# MD umbrella config (RAID/LVM core, no RAID personalities enabled). +# DM_CRYPT selects CRC32/CRYPTO/CBC/ESSIV itself; AES+XTS cover LUKS2's +# default aes-xts-plain64 cipher (XTS pulls in ECB) and SHA256 the essiv IV +# hash LUKS1 volumes use. +CONFIG_MD=y +CONFIG_BLK_DEV_DM=y +CONFIG_DM_CRYPT=y +CONFIG_CRYPTO_AES=y +CONFIG_CRYPTO_XTS=y +CONFIG_CRYPTO_SHA256=y + # --- filesystems ---------------------------------------------------------------- CONFIG_PROC_FS=y CONFIG_SYSFS=y @@ -127,6 +141,17 @@ CONFIG_FUSE_FS=y CONFIG_VIRTIO_FS=y CONFIG_FS_POSIX_ACL=y CONFIG_SECURITY=y +# NFS client, so local-driver volumes with type=nfs mount (Compose +# driver_opts). The user space already builds the mount fields; the kernel +# must register the nfs filesystem type or mount(2) fails with ENODEV +# ("no such device"). NFSv3 and NFSv4 (minor 4.0 and 4.1); NFSv2, pNFS, +# Kerberos (sec=krb5*) and NFS swap stay off. NETWORK_FILESYSTEMS is the +# menu gate: without it fs/nfs/Kconfig is not even parsed. +CONFIG_NETWORK_FILESYSTEMS=y +CONFIG_NFS_FS=y +CONFIG_NFS_V3=y +CONFIG_NFS_V4=y +CONFIG_NFS_V4_1=y # --- container primitives ------------------------------------------------------- CONFIG_NAMESPACES=y diff --git a/tests/e2e.sh b/tests/e2e.sh index 4890397de..28d3e2ed8 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -1239,6 +1239,9 @@ t inspect-binds "ok" bash -c "$D inspect -f '{{json .HostConfig.Binds}}' hcm | p t inspect-mounts-tmpfs 'ok {"/t2":"size=1m"} {"/anon":{}}' bash -c "m=\$($D inspect -f '{{json .HostConfig.Mounts}}' hcm | python3 -c 'import json, sys; ms = json.load(sys.stdin) or []; ok = len(ms) == 2 and {\"Type\": \"volume\", \"Source\": \"thcmro\", \"Target\": \"/rodata\", \"ReadOnly\": True} in ms and {\"Type\": \"tmpfs\", \"Target\": \"/t\"} in ms; print(\"ok\" if ok else ms)'); echo \"\$m \$($D inspect -f '{{json .HostConfig.Tmpfs}} {{json .Config.Volumes}}' hcm)\"" t inspect-recreate-mounts "code=201 kept|rokept|from the mac|bro=ro|vro=ro|t1=ok|t2=ok|ds=ok|ss=ok anon=fresh" bash -c "a1=\$($D inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' hcm); b=\$(curl -s --unix-socket '$SOCK' http://d/v1.47/containers/hcm/json | python3 -c 'import json, sys; c = json.load(sys.stdin); print(json.dumps(dict(c[\"Config\"], HostConfig=c[\"HostConfig\"])))'); code=\$(curl -s -o /dev/null -w '%{http_code}' --unix-socket '$SOCK' -X POST -H 'Content-Type: application/json' -d \"\$b\" 'http://d/v1.47/containers/create?name=hcm2'); out=\$($D start -a hcm2); a2=\$($D inspect -f '{{range .Mounts}}{{if eq .Destination \"/anon\"}}{{.Name}}{{end}}{{end}}' hcm2); [ -n \"\$a1\" ] && [ -n \"\$a2\" ] && [ \"\$a1\" != \"\$a2\" ] && an=fresh || an=\"same:\$a1:\$a2\"; echo \"code=\$code \$out anon=\$an\"" $D rm -f -v hcm hcm2 >/dev/null 2>&1; $D volume rm thcm thcmro >/dev/null 2>&1 +# The macOS guest kernel builds in the NFSv3/v4 client (#494) and dm-crypt/LUKS +# device-mapper (#755) in guest/kernel/kiri.config. +only mac t guest-kernel-nfs-dmcrypt "nfs dm" $D run --rm --privileged alpine sh -c 'grep -qw nfs /proc/filesystems && grep -qw device-mapper /proc/devices && test -c /dev/mapper/control && echo "nfs dm"' t anon-from-image "volume:/var/lib/postgresql/data" bash -c "$D run -d --name pgv -e POSTGRES_PASSWORD=x postgres:17-alpine >/dev/null; $D inspect -f '{{range .Mounts}}{{.Type}}:{{.Destination}}{{end}}' pgv" # Waits for the entrypoint's "init process complete" and then a working query, # not for pg_isready: on first start Postgres runs a temporary server to diff --git a/tests/regressions.tsv b/tests/regressions.tsv index b701ce68b..619a1cc51 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -355,6 +355,7 @@ bind-chown-chmod #382 chown on a macOS virtiofs bind mount returned 0 while leav crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350) finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount +guest-kernel-nfs-dmcrypt #494 guest kernel lacked CONFIG_NFS_FS / NFSv3 / NFSv4 client and CONFIG_DM_CRYPT / device-mapper so type=nfs volumes and LUKS dm-crypt devices failed in the macOS VM crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone From 806977e94837f51cbc65bb29f8e7057ab2d12c5c Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:15:07 +0100 Subject: [PATCH 129/157] Linux / WSL 2: guard host bridge and firewall tables per network namespace (#443) (#962) --- crates/kiri-init/src/linux/agent.rs | 3 + crates/kiri-init/src/linux/mod.rs | 1 + crates/kiri-init/src/linux/net.rs | 147 ++++++++++++++++++++++++-- crates/kiri-init/src/linux/netlink.rs | 12 ++- tests/regressions.tsv | 1 + 5 files changed, 152 insertions(+), 12 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 253bec551..82d564cac 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -113,6 +113,9 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap = if host_process { if let Err(e) = net::host_uplink() { + if e.kind() == io::ErrorKind::AddrInUse { + return Err(e); + } eprintln!("kiri-init: no uplink: {e}"); } None diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index 3118c1fbd..5bd60a8f1 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -250,6 +250,7 @@ fn host_dirs() -> io::Result { } }; take_over(&root, leftovers)?; + net::claim_host_netns()?; let (cgroup_root, cgroup) = host_cgroup()?; let paths = container::Paths { layers: root.join("layers"), diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 86867bec2..3f6a5076d 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -273,11 +273,124 @@ fn update_foreign_bridges() -> bool { } } -/// On a Linux host: enables IPv4 forwarding, detects foreign local bridges, -/// installs Kiri's nftables table, and adapts to any host firewall. Does not -/// require a main-table default route at boot (policy-routed VPNs such as -/// Tailscale or delayed interfaces work as routes appear). +/// Abstract Unix-domain socket name guarding Kiri's host networking (`kiri0` +/// and `nft table ip/ip6 kiri`) within a Linux network namespace (#443). +/// Abstract socket addresses are scoped per network namespace and released by +/// the kernel automatically when the agent exits or crashes. +const HOST_NETNS_LOCK_NAME: &[u8] = b"kiri-engine-netns"; + +static HOST_NETNS_LOCK: std::sync::OnceLock = std::sync::OnceLock::new(); +static HOST_NETNS_CLAIMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn make_abstract_sockaddr(name: &[u8]) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { + // SAFETY: zeroed `sockaddr_un` is valid; `sun_path[0] = 0` followed by `name` + // forms a Linux abstract socket address of length `offsetof(sun_path) + 1 + name.len()`. + let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() }; + addr.sun_family = libc::AF_UNIX as libc::sa_family_t; + if 1 + name.len() > addr.sun_path.len() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "netns lock name too long")); + } + for (dst, &src) in addr.sun_path[1..1 + name.len()].iter_mut().zip(name) { + *dst = src as libc::c_char; + } + let addr_len = (std::mem::offset_of!(libc::sockaddr_un, sun_path) + 1 + name.len()) as libc::socklen_t; + Ok((addr, addr_len)) +} + +/// Checks whether an active listener on `name` belongs to `owner` (prevents an +/// unprivileged local process from squatting the abstract socket name to deny +/// service to a root `kiri-init`). +fn abstract_lock_owned_by(name: &[u8], owner: u32) -> bool { + let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return false }; + let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) }; + if raw < 0 { + return false; + } + // SAFETY: `raw` is a freshly created socket descriptor owned here. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + // SAFETY: `addr` is initialized through `addr_len` bytes. + if unsafe { libc::connect(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { + return false; + } + // SAFETY: zeroed `ucred` is valid for `getsockopt(SO_PEERCRED)`. + let mut peer: libc::ucred = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + let rc = unsafe { + libc::getsockopt( + fd.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PEERCRED, + (&raw mut peer).cast(), + &mut len, + ) + }; + rc == 0 && len == std::mem::size_of::() as libc::socklen_t && peer.uid == owner +} + +fn try_bind_abstract_socket(name: &[u8]) -> Result { + let (addr, addr_len) = make_abstract_sockaddr(name).map_err(|_| libc::EINVAL)?; + let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) }; + if raw < 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } + // SAFETY: `raw` is a freshly created socket descriptor owned here. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + // SAFETY: `addr` is initialized through `addr_len` bytes. + if unsafe { libc::bind(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } + // Listen so peer engines can verify ownership without `accept()`. + // SAFETY: `fd` is a bound `SOCK_STREAM` socket owned here. + let _ = unsafe { libc::listen(fd.as_raw_fd(), 16) }; + Ok(fd) +} + +const NETNS_BUSY_MSG: &str = + "another Kiri engine is already running in this network namespace (for example in another WSL 2 distribution): stop it first"; + +/// Claims ownership of Kiri's bridge and firewall tables in the current Linux +/// network namespace (#443). All WSL 2 distributions share one network +/// namespace; refusing early prevents a second engine from overwriting +/// `nft table ip kiri` or deleting `kiri0` when stopping. +pub fn claim_host_netns() -> io::Result<()> { + use std::sync::atomic::Ordering; + if HOST_NETNS_CLAIMED.load(Ordering::Acquire) { + return Ok(()); + } + // SAFETY: `geteuid` has no preconditions. + let me = unsafe { libc::geteuid() }; + let start = Instant::now(); + loop { + match try_bind_abstract_socket(HOST_NETNS_LOCK_NAME) { + Ok(fd) => { + let _ = HOST_NETNS_LOCK.set(fd); + HOST_NETNS_CLAIMED.store(true, Ordering::Release); + return Ok(()); + } + Err(code) if code == libc::EADDRINUSE => { + if !abstract_lock_owned_by(HOST_NETNS_LOCK_NAME, me) { + eprintln!("kiri-init: ignoring unprivileged holder on abstract netns socket"); + HOST_NETNS_CLAIMED.store(true, Ordering::Release); + return Ok(()); + } + if start.elapsed() < Duration::from_millis(500) { + std::thread::sleep(Duration::from_millis(25)); + continue; + } + return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)); + } + Err(code) => return Err(io::Error::from_raw_os_error(code)), + } + } +} + +/// On a Linux host: claims the network namespace, enables IPv4 forwarding, +/// detects foreign local bridges, installs Kiri's nftables table, and adapts +/// to any host firewall. Does not require a main-table default route at boot +/// (policy-routed VPNs such as Tailscale or delayed interfaces work as routes +/// appear). pub fn host_uplink() -> io::Result<()> { + claim_host_netns()?; sys::write_file("/proc/sys/net/ipv4/ip_forward", "1")?; // No host.docker.internal loopback redirect on a Linux host: it would // let containers reach the real machine's 127.0.0.1 services. host.docker @@ -976,9 +1089,10 @@ impl Bridges { BridgePlan::Recreate => self.remove(name), BridgePlan::Create => {} } - let r = self.bring_up(name, gateway, prefix, v6); + let mut created = false; + let r = self.bring_up(name, gateway, prefix, v6, &mut created); if r.is_err() { - if let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { + if created && let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { let _ = netlink::delete_link(&mut nl, name); } MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|m| m != name); @@ -1003,9 +1117,9 @@ impl Bridges { Ok(index) } - fn bring_up(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option) -> io::Result { + fn bring_up(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option, created: &mut bool) -> io::Result { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; - netlink::create_bridge(&mut nl, name)?; + *created = netlink::create_bridge(&mut nl, name)?; let mut made = MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()); if !made.iter().any(|m| m == name) { made.push(name.to_owned()); @@ -1140,6 +1254,9 @@ static MADE_BRIDGES: std::sync::Mutex> = std::sync::Mutex::new(Vec:: /// those: another engine's may share the network namespace) and Kiri's /// nftables table, so nothing of the engine is left in the host's network. pub fn remove_host_network() { + if !HOST_NETNS_CLAIMED.load(std::sync::atomic::Ordering::Acquire) { + return; + } let names = std::mem::take(&mut *MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner())); BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).clear(); EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -1463,4 +1580,18 @@ mod tests { assert!(!pid_file_alive(&pid_path, |_| false)); let _ = std::fs::remove_file(&pid_path); } + + #[test] + fn abstract_netns_lock_rejects_second_holder_until_first_drops() { + let name = format!("kiri-netns-test-{}", std::process::id()); + let first = try_bind_abstract_socket(name.as_bytes()).expect("first holder binds abstract netns lock"); + let code = try_bind_abstract_socket(name.as_bytes()).expect_err("second holder in same netns must fail"); + assert_eq!(code, libc::EADDRINUSE); + let me = unsafe { libc::geteuid() }; + assert!(abstract_lock_owned_by(name.as_bytes(), me)); + assert!(!abstract_lock_owned_by(name.as_bytes(), me.wrapping_add(1))); + drop(first); + let rebound = try_bind_abstract_socket(name.as_bytes()).expect("rebind succeeds once first fd closes"); + drop(rebound); + } } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 76db7a04d..be69aecad 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -251,19 +251,23 @@ fn ifinfo(index: i32, flags: u32, change: u32) -> [u8; 16] { /// broke mid-TLS until it was asked again. Docker gives its bridges an /// address for the same reason. A bridge left by an earlier run without /// one (a Linux host) gets one too. -pub fn create_bridge(nl: &mut Netlink, name: &str) -> io::Result<()> { +/// Returns `Ok(true)` when a new bridge was created, or `Ok(false)` when an +/// interface named `name` already existed. +pub fn create_bridge(nl: &mut Netlink, name: &str) -> io::Result { match nl.request(&mut [new_bridge(name, bridge_mac(random_bytes()))]) { + Ok(()) => Ok(true), Err(e) if e.raw_os_error() == Some(libc::EEXIST) => { // NET_ADDR_SET (3): someone set it, so it no longer follows the ports. let kind = std::fs::read_to_string(format!("/sys/class/net/{name}/addr_assign_type")).unwrap_or_default(); if kind.trim() == "3" { - return Ok(()); + return Ok(false); } let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); m.raw(&ifinfo(index_of(name)?, 0, 0)).attr(IFLA_ADDRESS, &bridge_mac(random_bytes())); - nl.request(&mut [m]) + nl.request(&mut [m])?; + Ok(false) } - r => r, + Err(e) => Err(e), } } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 619a1cc51..2a68f9ba1 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -366,3 +366,4 @@ crates/kiri/src/builds.rs #923 a running build's steps were read with `buildx hi 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 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 +crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit From f1eb18c545071cd098b0b5fb71422a57da462204 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:38:44 +0100 Subject: [PATCH 130/157] macOS setup: skip shell profile edits when Homebrew already links kiri to this app (#733) (#963) --- crates/kiri/src/setup.rs | 109 +++++++++++++++++++++++++++++++++++---- tests/regressions.tsv | 2 +- 2 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index 38c2e41ce..41e616dac 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -575,14 +575,18 @@ fn bundled_cli(contents: &Path) -> io::Result<()> { let ours = bin_dir()?; std::fs::create_dir_all(&ours)?; // `kiri` itself, for `kiri k8s`, `kiri machine`, `kiri import`… + let app_kiri = contents.join("MacOS/kiri"); let kiri = ours.join("kiri"); let _ = std::fs::remove_file(&kiri); - std::os::unix::fs::symlink(contents.join("MacOS/kiri"), &kiri)?; + std::os::unix::fs::symlink(&app_kiri, &kiri)?; + let brew_linked = !dev() && homebrew_links_this_app(&app_kiri); // Kiri Dev's commands are run by path: ~/.kiri-dev/bin/kiri. - if !dev() { + // When Homebrew's cask `binary` stanza already links `kiri` on PATH to + // this app (#733), leave shell profiles and Homebrew's symlink untouched. + if !dev() && !brew_linked { let h = home()?; shell_path_once(&h, &zdotdir(&h))?; - system_link(&kiri); + system_link(&kiri, &app_kiri); } let mut bin = contents.join("Resources/bin"); if !bin.join("docker").is_file() { @@ -610,7 +614,7 @@ fn bundled_cli(contents: &Path) -> io::Result<()> { } cfg["cliPluginsExtraDirs"] = dirs.into(); write_json(&path, &cfg)?; - if home().is_ok_and(|h| no_profiles_file(&h).exists()) { + if brew_linked || home().is_ok_and(|h| no_profiles_file(&h).exists()) { println!("docker and kiri commands: {}", ours.display()); } else { println!("docker and kiri commands: {} (on PATH in new terminal windows)", ours.display()); @@ -618,17 +622,57 @@ fn bundled_cli(contents: &Path) -> io::Result<()> { Ok(()) } +/// Candidate Homebrew `bin/kiri` symlink paths on Apple silicon, Intel Macs, +/// and custom `$HOMEBREW_PREFIX` installations (#733). +fn homebrew_kiri_candidates(homebrew_prefix: Option<&std::ffi::OsStr>) -> Vec { + let mut out = vec![PathBuf::from("/opt/homebrew/bin/kiri"), PathBuf::from(SYSTEM_LINK)]; + if let Some(prefix) = homebrew_prefix.filter(|p| !p.is_empty()) { + let cand = PathBuf::from(prefix).join("bin/kiri"); + if !out.contains(&cand) { + out.push(cand); + } + } + out +} + +/// True when any candidate symlink points directly to `app_kiri` (rather than +/// going through `~/.kiri/bin/kiri`, which `system_link` makes on Intel Macs). +fn homebrew_links_app_in(candidates: &[PathBuf], app_kiri: &Path) -> bool { + let Ok(ours) = std::fs::canonicalize(app_kiri) else { return false }; + let state_bin = format!("/{}/bin/", crate::flavor::STATE.get()); + candidates.iter().any(|cand| { + let Ok(raw) = std::fs::read_link(cand) else { return false }; + let raw_str = raw.to_string_lossy(); + if raw_str.contains("/.kiri/bin/") || raw_str.contains(&state_bin) { + return false; + } + std::fs::canonicalize(cand).is_ok_and(|real| real == ours) + }) +} + +fn homebrew_links_this_app(app_kiri: &Path) -> bool { + homebrew_links_app_in(&homebrew_kiri_candidates(std::env::var_os("HOMEBREW_PREFIX").as_deref()), app_kiri) +} + /// `/usr/local/bin/kiri`, when the user can write there (Homebrew on Intel /// Macs makes it theirs). That directory is on every shell's PATH already, /// so `kiri` works even in a terminal opened before Kiri was. A `kiri` -/// there that isn't Kiri's is left alone. +/// there that isn't Kiri's (or that Homebrew's cask already linked directly to +/// this app) is left alone. const SYSTEM_LINK: &str = "/usr/local/bin/kiri"; -fn system_link(kiri: &Path) { - let link = Path::new(SYSTEM_LINK); +fn system_link(kiri: &Path, app_kiri: &Path) { + system_link_at(Path::new(SYSTEM_LINK), kiri, app_kiri); +} + +fn system_link_at(link: &Path, kiri: &Path, app_kiri: &Path) { // Missing, or a link an older Kiri left (to a Kiri.app or ~/.kiri/bin - // that moved, or to nothing): made again to this one. Anything else there - // isn't Kiri's to replace; stale::stale_kiri() names it. + // that moved, or to nothing): made again to this one. If Homebrew's cask + // already linked `/usr/local/bin/kiri` directly to `app_kiri`, keep + // Homebrew's link so `brew uninstall` owns it (#733). + if homebrew_links_app_in(&[link.to_path_buf()], app_kiri) { + return; + } let replace = match std::fs::read_link(link) { Ok(target) => target != kiri && (kiri_link(&target) || !link.exists()), Err(_) => link.symlink_metadata().is_err(), @@ -1481,4 +1525,51 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + + // #733: when Homebrew's cask `binary` stanza links `$(brew --prefix)/bin/kiri` + // directly to `Kiri.app/Contents/MacOS/kiri`, setup recognizes it, skips + // shell profile edits, and preserves Homebrew's `/usr/local/bin/kiri` link, + // while Kiri's own `~/.kiri/bin/kiri` indirect link is not mistaken for Homebrew's. + #[test] + fn homebrew_cask_binary_link_is_detected_and_preserved() { + let d = scratch("homebrew-link"); + let app_kiri = d.join("Applications/Kiri.app/Contents/MacOS/kiri"); + let other_app = d.join("Downloads/Kiri.app/Contents/MacOS/kiri"); + let our_bin_kiri = d.join(".kiri/bin/kiri"); + let opt_brew_kiri = d.join("opt/homebrew/bin/kiri"); + let usr_local_kiri = d.join("usr/local/bin/kiri"); + for p in [&app_kiri, &other_app, &our_bin_kiri, &opt_brew_kiri, &usr_local_kiri] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + } + std::fs::write(&app_kiri, "#!/bin/sh\n").unwrap(); + std::fs::write(&other_app, "#!/bin/sh\n").unwrap(); + std::os::unix::fs::symlink(&app_kiri, &our_bin_kiri).unwrap(); + + // No Homebrew link yet. + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone(), usr_local_kiri.clone()], &app_kiri)); + + // Kiri's own `system_link` (`/usr/local/bin/kiri -> ~/.kiri/bin/kiri`) is NOT a Homebrew cask link. + super::system_link_at(&usr_local_kiri, &our_bin_kiri, &app_kiri); + assert_eq!(std::fs::read_link(&usr_local_kiri).unwrap(), our_bin_kiri); + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone(), usr_local_kiri.clone()], &app_kiri)); + + // Homebrew cask link on Apple silicon (`/opt/homebrew/bin/kiri -> .../Kiri.app/Contents/MacOS/kiri`). + std::os::unix::fs::symlink(&app_kiri, &opt_brew_kiri).unwrap(); + assert!(super::homebrew_links_app_in(&[opt_brew_kiri.clone()], &app_kiri)); + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone()], &other_app)); + + // Homebrew cask link on Intel (`/usr/local/bin/kiri -> .../Kiri.app/Contents/MacOS/kiri`) is preserved by `system_link_at`. + std::fs::remove_file(&usr_local_kiri).unwrap(); + std::os::unix::fs::symlink(&app_kiri, &usr_local_kiri).unwrap(); + assert!(super::homebrew_links_app_in(&[usr_local_kiri.clone()], &app_kiri)); + super::system_link_at(&usr_local_kiri, &our_bin_kiri, &app_kiri); + assert_eq!(std::fs::read_link(&usr_local_kiri).unwrap(), app_kiri, "Homebrew's direct cask link stays untouched"); + + // Custom `$HOMEBREW_PREFIX` adds `/bin/kiri` without duplicating standard prefixes. + let cands = super::homebrew_kiri_candidates(Some(std::ffi::OsStr::new("/custom/brew"))); + assert!(cands.contains(&std::path::PathBuf::from("/custom/brew/bin/kiri"))); + assert_eq!(super::homebrew_kiri_candidates(Some(std::ffi::OsStr::new("/opt/homebrew"))).len(), 2); + + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 2a68f9ba1..b3146ef38 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -344,7 +344,7 @@ tls-company-root-login #303 docker login to a registry signed by a root the syst tls-unknown-root-refused #303 a root the system does not trust must still be refused crates/kiri-image/src/roots.rs #303 root store merge, system distrust filtering (macOS Never Trust, Windows Disallowed and disabled Server Auth EKU), cross-cert preservation, caps, and KIRI_TLS_ROOTS=webpki escape hatch crates/kiri/src/daemon/hostroots.rs #303 Windows host roots persistence in WSL must enforce Caller::Host, 0600 atomic writes, non-symlink/non-FIFO reads, and bounded sizes -crates/kiri/src/setup.rs #556 opening Kiri.app re-appended the ~/.kiri/bin PATH block to shell profiles on every launch even when removed or when a profile already put ~/.kiri/bin on PATH, with no kiri setup --no-profiles opt-out +crates/kiri/src/setup.rs #556 opening Kiri.app re-appended the ~/.kiri/bin PATH block on every launch, and modified shell profiles or replaced /usr/local/bin/kiri even when Homebrew's cask binary stanza already linked kiri directly to the running app (#733) crates/kiri/src/k8s.rs #816 kiri k8s set had no --version or --k3s-arg/--clear-k3s-args options to pin a k3s image tag or pass custom k3s server flags, and kiri k8s start did not sync ~/.kiri/k8s-manifests into k3s crates/kiri-win/src/k8s.rs #816 Windows k8s.json config and container creation did not preserve or apply custom k3s version tags and extra k3s server arguments k8s-set-keeps-malformed-config #926 kiri k8s set replaced a k8s.json it could not parse with defaults, losing every other setting, and reported success From 2ccef3e96a591d77dd5d2f349571e4d6ce2b66e1 Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:47:39 +0100 Subject: [PATCH 131/157] UI: replace WebView browser right-click menu with Kiri's app editing menu (#964) --- crates/kiri/src/ui/index.html | 145 +++++++++++++++++++++++++++++++++- tests/ui/menu.js | 75 ++++++++++++++++-- 2 files changed, 209 insertions(+), 11 deletions(-) diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 31ab8f21b..1232423aa 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -2371,6 +2371,15 @@ .htctx .mi { display: flex; align-items: center; gap: 8px; width: 100%; height: 28px; padding: 0 8px; border: 0; border-radius: 6px; background: none; cursor: pointer; color: var(--text); font: var(--fs) var(--ui-font); text-align: var(--start); } .htctx .mi:hover { background: var(--blue); color: #fff; } .htctx .mi:disabled { color: var(--faint); background: none; cursor: default; } +.appctx { position: fixed; z-index: 120; min-width: 160px; padding: 5px; background: var(--raised); border: 1px solid var(--line); border-radius: 10px; box-shadow: 0 14px 40px rgb(0 0 0 / .45); } +.appctx[hidden] { display: none; } +.appctx .mi { display: flex; align-items: center; justify-content: space-between; gap: 16px; width: 100%; height: 28px; padding-block: 0; padding-inline: 8px; border: 0; border-radius: 6px; background: none; cursor: pointer; color: var(--text); font: var(--fs) var(--ui-font); text-align: var(--start); } +.appctx .mi:hover { background: var(--blue); color: #fff; } +.appctx .mi:hover .k { color: rgb(255 255 255 / .8); } +.appctx .mi:disabled { color: var(--faint); background: none; cursor: default; } +.appctx .mi:disabled .k { color: var(--faint); } +.appctx .mi .k { color: var(--faint); font-size: var(--fs-xs); } +.appctx hr { border: 0; border-top: 1px solid var(--line); margin: 4px 2px; } .httab .x:hover { background: color-mix(in srgb, var(--text) 10%, transparent); color: var(--text); } .hthead .grow { flex: 1; min-width: 10px; align-self: stretch; } .hthead .sep { width: 1px; height: 16px; background: var(--line); margin: 0 4px; } @@ -3017,12 +3026,129 @@

Containers

${label}${key ? `${esc(key)}` : ""}`; +} +function openAppCtx(ev, html) { + setHTML(appCtxEl, html); + appCtxEl.hidden = false; + const zoom = Number(prefs.scale) || 1, vw = (innerWidth || 800) / zoom, vh = (innerHeight || 600) / zoom; + const rect = appCtxEl.getBoundingClientRect(), mw = (rect.width || 168) / zoom, mh = (rect.height || 38) / zoom; + const x = Math.max(6, Math.min((ev.clientX || 0) / zoom, vw - mw - 6)); + const y = Math.max(6, Math.min((ev.clientY || 0) / zoom, vh - mh - 6)); + appCtxEl.style.left = `${x}px`; + appCtxEl.style.top = `${y}px`; +} document.addEventListener("contextmenu", (ev) => { - const editable = ev.target.closest?.("input, textarea, [contenteditable]"); - if (!editable && !String(getSelection()).trim()) ev.preventDefault(); + ev.preventDefault(); + const htMenuEl = document.querySelector(".htctx"); + if (htMenuEl) htMenuEl.hidden = true; + const modKey = WIN || LINUX ? "Ctrl+" : "⌘"; + const field = ev.target.closest?.("input, textarea"); + if (isTextField(field) && !field.disabled) { + if (document.activeElement !== field) field.focus(); + const [start, end, hasRange] = fieldRange(field); + const isPwd = (field.type || "").toLowerCase() === "password"; + const writable = !field.readOnly; + const selected = !isPwd && hasRange && end > start ? (field.value || "").slice(start, end) : (!isPwd && !hasRange ? (field.value || "") : ""); + const hasText = (field.value || "").length > 0; + ctxTarget = { kind: "field", el: field, start, end, hasRange, text: selected, writable }; + const items = writable + ? [ + ctxItem("cut", tr("Cut"), `${modKey}X`, !selected), + ctxItem("copy", tr("Copy"), `${modKey}C`, !selected), + ctxItem("paste", tr("Paste"), `${modKey}V`, false), + "
", + ctxItem("selectall", tr("Select All"), `${modKey}A`, !hasText), + ] + : [ + ctxItem("copy", tr("Copy"), `${modKey}C`, !selected), + ctxItem("selectall", tr("Select All"), `${modKey}A`, !hasText), + ]; + openAppCtx(ev, items.join("")); + return; + } + const paneEl = ev.target.closest?.(".htpane"); + if (paneEl && ev.target.closest?.(".htx, .xterm") && typeof htPane === "function") { + const p = htPane(paneEl.dataset.id); + if (!p) { hideAppCtx(); return; } + const selected = p.term?.getSelection() || ""; + ctxTarget = { kind: "term", pane: p, text: selected }; + const tk = WIN || LINUX ? "Ctrl+Shift+" : "⌘"; + openAppCtx(ev, [ + ctxItem("copy", tr("Copy"), `${tk}C`, !selected), + ctxItem("paste", tr("Paste"), `${tk}V`, Boolean(p.exited)), + ].join("")); + return; + } + const selected = String(getSelection()); + if (!selected.trim()) { hideAppCtx(); return; } + ctxTarget = { kind: "selection", text: selected }; + openAppCtx(ev, ctxItem("copy", tr("Copy"), `${modKey}C`, false)); +}); +appCtxEl.addEventListener("mousedown", (ev) => ev.preventDefault()); +appCtxEl.addEventListener("click", (ev) => { + const btn = ev.target.closest?.("[data-ctx]"); + if (!btn || btn.disabled) return; + const act = btn.dataset.ctx, t = ctxTarget; + hideAppCtx(); + if (!t) return; + if (act === "copy") { + if (t.kind === "term") htCopy(t.pane); + else if (t.text) send("term", { name: "copy", value: t.text }); + } else if (act === "cut" && t.kind === "field" && t.writable && t.text) { + send("term", { name: "copy", value: t.text }); + replaceFieldText(t.el, "", t.start, t.end, t.hasRange); + } else if (act === "paste") { + if (t.kind === "term") send("term", { name: "paste", id: t.pane.id }); + else if (t.kind === "field" && t.writable) { ctxPasteField = t.el; send("term", { name: "paste", id: "__field" }); } + } else if (act === "selectall" && t.kind === "field") { + t.el.focus(); + try { t.el.select(); } catch {} + } }); +document.addEventListener("mousedown", (ev) => { if (!ev.target.closest?.("#app-ctx")) hideAppCtx(); }); +document.addEventListener("keydown", (ev) => { if (ev.key === "Escape" && !appCtxEl.hidden) hideAppCtx(); }); +document.addEventListener("scroll", hideAppCtx, true); +addEventListener("blur", hideAppCtx); /* Copy with the keyboard: selected text (a log, a row's value) goes to the clipboard the way the terminal's does. On the Mac, Edit → Copy does it. Text fields and the terminal keep their own handling. */ @@ -12325,6 +12451,17 @@

${live ? tr("You're sharing {name}", { name: `${esc(kShName if (ht.wantTab) { const want = ht.wantTab; ht.wantTab = false; htNewTab(want === true ? undefined : want); } return; } + if (e.ev === "paste" && e.id === "__field") { + const el = ctxPasteField; + ctxPasteField = null; + if (el && el.isConnected && !el.readOnly && !el.disabled) { + const raw = String(e.text || ""); + const text = el.tagName === "INPUT" ? raw.replace(/[\r\n]+/g, " ") : raw; + const [s, end, hasRange] = fieldRange(el); + replaceFieldText(el, text, s, end, hasRange); + } + return; + } const p = htPane(e.id); if (!p?.term) return; if (e.ev === "data") p.term.write(htUnB64(e.b64)); diff --git a/tests/ui/menu.js b/tests/ui/menu.js index 26e52d3f3..ab50798c3 100644 --- a/tests/ui/menu.js +++ b/tests/ui/menu.js @@ -1,13 +1,74 @@ -// Right-click: no browser menu (Reload…) except in text fields and on selected text. +// Right-click: never opens the browser's menu (Search with Google, Look Up, +// Translate, Reload…); Kiri draws its own app menu (#app-ctx) with only editing +// actions (Copy on selected text, Cut / Copy / Paste / Select All in fields). kiri.on({ type: "status", version: "0.1.4", dev: true, app: "Kiri Dev", ours: "kiri-dev", context: "kiri-dev" }); const R = []; const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; -const menu = (el) => { const ev = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); el.dispatchEvent(ev); return !ev.defaultPrevented; }; -t("no browser menu on the Images view", () => { getSelection().removeAllRanges(); show("images"); eq(menu($("content")), false, "menu shown"); }); -t("a text field keeps its menu", () => { const i = document.createElement("input"); document.body.append(i); eq(menu(i), true, "menu shown"); i.remove(); }); -t("selected text keeps its menu", () => { - const p = document.createElement("p"); p.textContent = "copy me"; p.style.userSelect = p.style.webkitUserSelect = "text"; document.body.append(p); - getSelection().selectAllChildren(p); eq(menu(p), true, "menu shown"); getSelection().removeAllRanges(); p.remove(); +const menu = (el) => { const ev = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 120, clientY: 120 }); el.dispatchEvent(ev); return !ev.defaultPrevented; }; +const ctxLabels = () => [...$("app-ctx").querySelectorAll("[data-ctx]")].map((b) => [b.dataset.ctx, b.disabled]); + +t("no browser or app menu on unselected UI", () => { + getSelection().removeAllRanges(); + show("images"); + eq(menu($("content")), false, "browser menu prevented"); + eq($("app-ctx").hidden, true, "app menu stays hidden"); }); + +t("selected log text opens Kiri's Copy-only menu (no browser Search with Google)", () => { + sent.length = 0; + const p = document.createElement("p"); + p.textContent = "2026-11-20 10:14:34.716 UTC starting: time"; + p.style.userSelect = p.style.webkitUserSelect = "text"; + document.body.append(p); + getSelection().selectAllChildren(p); + eq(menu(p), false, "browser menu prevented"); + eq($("app-ctx").hidden, false, "app menu shown"); + eq(ctxLabels(), [["copy", false]], "only Copy shown"); + eq($("app-ctx").textContent.includes("Google"), false, "never mentions Google"); + $("app-ctx").querySelector('[data-ctx="copy"]').click(); + eq($("app-ctx").hidden, true, "menu closes on click"); + eq(sent.at(-1), { type: "term", cmd: "term", name: "copy", value: "2026-11-20 10:14:34.716 UTC starting: time" }, "copied through native bridge"); + getSelection().removeAllRanges(); + p.remove(); +}); + +t("a text field gets Kiri's Cut, Copy, Paste and Select All menu", () => { + sent.length = 0; + const i = document.createElement("input"); + i.value = "hello world"; + document.body.append(i); + i.focus(); + i.setSelectionRange(0, 5); + eq(menu(i), false, "browser menu prevented"); + eq($("app-ctx").hidden, false, "app menu shown"); + eq(ctxLabels(), [["cut", false], ["copy", false], ["paste", false], ["selectall", false]], "field actions"); + $("app-ctx").querySelector('[data-ctx="cut"]').click(); + eq(i.value, " world", "Cut removes selection"); + eq(sent.at(-1), { type: "term", cmd: "term", name: "copy", value: "hello" }, "Cut copies selection"); + menu(i); + $("app-ctx").querySelector('[data-ctx="paste"]').click(); + eq(sent.at(-1), { type: "term", cmd: "term", name: "paste", id: "__field" }, "Paste asks native clipboard"); + kiri.on({ type: "term", ev: "paste", id: "__field", text: "kiri\nlogs" }); + eq(i.value, "kiri logs world", "Paste inserts sanitized single-line text"); + i.remove(); +}); + +t("number and email inputs support Cut, Copy and Paste without setRangeText InvalidStateError", () => { + sent.length = 0; + const n = document.createElement("input"); + n.type = "number"; + n.value = "8080"; + document.body.append(n); + eq(menu(n), false, "browser menu prevented on number input"); + $("app-ctx").querySelector('[data-ctx="cut"]').click(); + eq(n.value, "", "Cut clears number input safely"); + eq(sent.at(-1), { type: "term", cmd: "term", name: "copy", value: "8080" }, "Cut copied number value"); + menu(n); + $("app-ctx").querySelector('[data-ctx="paste"]').click(); + kiri.on({ type: "term", ev: "paste", id: "__field", text: "9090" }); + eq(n.value, "9090", "Paste updates number input safely"); + n.remove(); +}); + report(R); From e8acc5d9ab20e410c636ea6fee793ba4db6bfcff Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:52:17 +0100 Subject: [PATCH 132/157] Linux / WSL 2: harden netns lock, container socket gate, and Host routing (#970) --- crates/kiri-init/src/linux/agent.rs | 6 + crates/kiri-init/src/linux/mod.rs | 32 +- crates/kiri-init/src/linux/net.rs | 170 ++++++++--- crates/kiri/src/daemon/access.rs | 452 +++++++++++++++++++++++----- crates/kiri/src/daemon/domains.rs | 68 +++-- crates/kiri/src/daemon/engine.rs | 37 ++- crates/kiri/src/daemon/mod.rs | 56 +++- crates/kiri/src/doctor.rs | 27 +- 8 files changed, 711 insertions(+), 137 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 82d564cac..522531fb3 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -134,6 +134,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap 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)?; + } else { + detach_deleted_bind_mount(&root); } if let Some(kind) = sys::detect_readonly_fs(&root) { return Err(sys::readonly_storage_error(kind)); @@ -250,7 +255,6 @@ fn host_dirs() -> io::Result { } }; take_over(&root, leftovers)?; - net::claim_host_netns()?; let (cgroup_root, cgroup) = host_cgroup()?; let paths = container::Paths { layers: root.join("layers"), @@ -299,6 +303,32 @@ fn mount_agent_data(src: &std::path::Path, target: &std::path::Path) -> io::Resu check(unsafe { libc::mount(c_src.as_ptr(), c_target.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null()) } as _, "bind-mount KIRI_AGENT_DATA").map(drop) } +/// If `target` (`/var/lib/kiri`) is currently covered by a stale bind mount +/// whose backing directory was deleted (`st_nlink == 0`), detaches it so +/// `create_dir_all` can use the underlying `/var/lib/kiri` directory instead +/// of failing with `ENOENT`. Real filesystem roots always have `st_nlink >= 2`. +fn detach_deleted_bind_mount(target: &std::path::Path) { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::MetadataExt; + let Ok(c_target) = CString::new(target.as_os_str().as_bytes()) else { return }; + for _ in 0..4 { + let Ok(md) = std::fs::symlink_metadata(target) else { break }; + if md.file_type().is_symlink() || md.nlink() != 0 { + break; + } + if !std::fs::read_to_string("/proc/self/mountinfo").is_ok_and(|m| is_mounted_at(&m, target)) { + break; + } + // SAFETY: valid NUL-terminated non-symlink mountpoint; `UMOUNT_NOFOLLOW` + // prevents following any racing symlink replacement. + if unsafe { libc::umount2(c_target.as_ptr(), libc::MNT_DETACH | libc::UMOUNT_NOFOLLOW) } != 0 { + eprintln!("kiri-init: detach deleted bind mount on {}: {}", target.display(), io::Error::last_os_error()); + break; + } + } +} + /// Whether `/proc/self/mountinfo` lists a mount whose target is `target`. fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool { let want = target.to_string_lossy(); diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 3f6a5076d..935507284 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -297,20 +297,31 @@ fn make_abstract_sockaddr(name: &[u8]) -> io::Result<(libc::sockaddr_un, libc::s Ok((addr, addr_len)) } -/// Checks whether an active listener on `name` belongs to `owner` (prevents an -/// unprivileged local process from squatting the abstract socket name to deny -/// service to a root `kiri-init`). -fn abstract_lock_owned_by(name: &[u8], owner: u32) -> bool { - let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return false }; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LockProbe { + /// Connected and `SO_PEERCRED.uid == owner`. + OwnedByOwner, + /// Connected and `SO_PEERCRED.uid != owner` (unprivileged squatter). + OwnedByOther, + /// `connect()` failed transiently (`EAGAIN` backlog full, `ECONNREFUSED` + /// bind-to-listen window or closing holder, `EINTR`, etc.). Never treated + /// as an unprivileged squatter. + TransientBusy, +} + +/// Probes an active listener on `name` to distinguish a legitimate `owner` +/// engine from an unprivileged squatter or transient backlog/startup state. +fn probe_abstract_lock(name: &[u8], owner: u32) -> LockProbe { + let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return LockProbe::TransientBusy }; let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) }; if raw < 0 { - return false; + return LockProbe::TransientBusy; } // SAFETY: `raw` is a freshly created socket descriptor owned here. let fd = unsafe { OwnedFd::from_raw_fd(raw) }; // SAFETY: `addr` is initialized through `addr_len` bytes. if unsafe { libc::connect(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { - return false; + return LockProbe::TransientBusy; } // SAFETY: zeroed `ucred` is valid for `getsockopt(SO_PEERCRED)`. let mut peer: libc::ucred = unsafe { std::mem::zeroed() }; @@ -324,12 +335,19 @@ fn abstract_lock_owned_by(name: &[u8], owner: u32) -> bool { &mut len, ) }; - rc == 0 && len == std::mem::size_of::() as libc::socklen_t && peer.uid == owner + if rc != 0 || len != std::mem::size_of::() as libc::socklen_t { + return LockProbe::TransientBusy; + } + if peer.uid == owner { + LockProbe::OwnedByOwner + } else { + LockProbe::OwnedByOther + } } fn try_bind_abstract_socket(name: &[u8]) -> Result { let (addr, addr_len) = make_abstract_sockaddr(name).map_err(|_| libc::EINVAL)?; - let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) }; + let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) }; if raw < 0 { return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); } @@ -339,49 +357,108 @@ fn try_bind_abstract_socket(name: &[u8]) -> Result { if unsafe { libc::bind(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); } - // Listen so peer engines can verify ownership without `accept()`. // SAFETY: `fd` is a bound `SOCK_STREAM` socket owned here. - let _ = unsafe { libc::listen(fd.as_raw_fd(), 16) }; + if unsafe { libc::listen(fd.as_raw_fd(), 128) } != 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } Ok(fd) } +/// Descriptor of the held abstract netns lock socket, polled by the +/// single-threaded `agent::serve_loop` (`kiri-init` never spawns threads, so +/// `signalfd` and `clone3` stay single-threaded). +pub fn netns_lock_fd() -> Option { + HOST_NETNS_LOCK.get().map(AsRawFd::as_raw_fd) +} + +/// Drains up to 64 pending `SO_PEERCRED` probe connections per `poll()` tick so +/// `sk_max_ack_backlog` does not fill under normal retries while a local +/// `connect()` flood can never starve `agent::serve_loop`. +pub fn drain_netns_lock(fd: std::os::fd::RawFd) { + for _ in 0..64 { + // SAFETY: `fd` is a non-blocking listening `AF_UNIX` socket. + let cfd = unsafe { libc::accept4(fd, std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK) }; + if cfd >= 0 { + // SAFETY: `cfd` is a freshly accepted descriptor owned here. + unsafe { libc::close(cfd) }; + continue; + } + let err = io::Error::last_os_error().raw_os_error().unwrap_or(libc::EAGAIN); + if err == libc::EMFILE || err == libc::ENFILE { + std::thread::sleep(Duration::from_millis(1)); + } + break; + } +} + const NETNS_BUSY_MSG: &str = "another Kiri engine is already running in this network namespace (for example in another WSL 2 distribution): stop it first"; +const MAX_NETNS_LOCK_SLOTS: usize = 64; + +fn netns_slot_name(base: &[u8], idx: usize) -> Vec { + if idx == 0 { + base.to_vec() + } else { + let mut v = Vec::with_capacity(base.len() + 8); + v.extend_from_slice(base); + v.extend_from_slice(format!("-{idx}").as_bytes()); + v + } +} /// Claims ownership of Kiri's bridge and firewall tables in the current Linux /// network namespace (#443). All WSL 2 distributions share one network /// namespace; refusing early prevents a second engine from overwriting /// `nft table ip kiri` or deleting `kiri0` when stopping. pub fn claim_host_netns() -> io::Result<()> { + claim_host_netns_on(HOST_NETNS_LOCK_NAME, &HOST_NETNS_LOCK, &HOST_NETNS_CLAIMED) +} + +fn claim_host_netns_on( + base: &[u8], + slot: &std::sync::OnceLock, + claimed: &std::sync::atomic::AtomicBool, +) -> io::Result<()> { use std::sync::atomic::Ordering; - if HOST_NETNS_CLAIMED.load(Ordering::Acquire) { + if claimed.load(Ordering::Acquire) { return Ok(()); } // SAFETY: `geteuid` has no preconditions. let me = unsafe { libc::geteuid() }; - let start = Instant::now(); - loop { - match try_bind_abstract_socket(HOST_NETNS_LOCK_NAME) { - Ok(fd) => { - let _ = HOST_NETNS_LOCK.set(fd); - HOST_NETNS_CLAIMED.store(true, Ordering::Release); - return Ok(()); - } - Err(code) if code == libc::EADDRINUSE => { - if !abstract_lock_owned_by(HOST_NETNS_LOCK_NAME, me) { - eprintln!("kiri-init: ignoring unprivileged holder on abstract netns socket"); - HOST_NETNS_CLAIMED.store(true, Ordering::Release); + let mut idx = 0usize; + while idx < MAX_NETNS_LOCK_SLOTS { + let candidate = netns_slot_name(base, idx); + let start = Instant::now(); + loop { + match try_bind_abstract_socket(&candidate) { + Ok(fd) => { + let _ = slot.set(fd); + claimed.store(true, Ordering::Release); return Ok(()); } - if start.elapsed() < Duration::from_millis(500) { - std::thread::sleep(Duration::from_millis(25)); - continue; - } - return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)); + Err(code) if code == libc::EADDRINUSE => match probe_abstract_lock(&candidate, me) { + LockProbe::OwnedByOther => { + // Unprivileged squatter on `candidate`: advance to the next + // deterministic slot so the first root engine still binds a + // real lock and a second root engine hits that bound slot + // (preventing split-brain without arming `claimed` unlocked). + eprintln!("kiri-init: skipping unprivileged squatter on abstract netns socket slot {idx}"); + idx += 1; + break; + } + LockProbe::OwnedByOwner | LockProbe::TransientBusy => { + if start.elapsed() < Duration::from_millis(500) { + std::thread::sleep(Duration::from_millis(25)); + continue; + } + return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)); + } + }, + Err(code) => return Err(io::Error::from_raw_os_error(code)), } - Err(code) => return Err(io::Error::from_raw_os_error(code)), } } + Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)) } /// On a Linux host: claims the network namespace, enables IPv4 forwarding, @@ -1582,15 +1659,34 @@ mod tests { } #[test] - fn abstract_netns_lock_rejects_second_holder_until_first_drops() { + fn abstract_netns_lock_rejects_second_holder_across_full_retry_loop() { + use std::sync::atomic::AtomicBool; + use std::sync::OnceLock; let name = format!("kiri-netns-test-{}", std::process::id()); - let first = try_bind_abstract_socket(name.as_bytes()).expect("first holder binds abstract netns lock"); - let code = try_bind_abstract_socket(name.as_bytes()).expect_err("second holder in same netns must fail"); - assert_eq!(code, libc::EADDRINUSE); + let slot1 = OnceLock::new(); + let claimed1 = AtomicBool::new(false); + claim_host_netns_on(name.as_bytes(), &slot1, &claimed1).expect("first holder claims abstract netns lock"); + + // Run 8 full 500ms `claim_host_netns_on` retry loops (> 160 probes, + // exceeding `listen(128)` when drained between ticks as `agent::serve_loop` + // does) to verify `drain_netns_lock` prevents `EAGAIN` false negatives. + for _ in 0..8 { + let slot2 = OnceLock::new(); + let claimed2 = AtomicBool::new(false); + let err = claim_host_netns_on(name.as_bytes(), &slot2, &claimed2) + .expect_err("second holder in same netns must fail after full retry window"); + assert_eq!(err.kind(), io::ErrorKind::AddrInUse); + assert!(!claimed2.load(std::sync::atomic::Ordering::Acquire)); + drain_netns_lock(slot1.get().unwrap().as_raw_fd()); + } + let me = unsafe { libc::geteuid() }; - assert!(abstract_lock_owned_by(name.as_bytes(), me)); - assert!(!abstract_lock_owned_by(name.as_bytes(), me.wrapping_add(1))); - drop(first); + assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::OwnedByOwner); + assert_eq!(probe_abstract_lock(name.as_bytes(), me.wrapping_add(1)), LockProbe::OwnedByOther); + + drop(slot1); + // Unbound socket returns TransientBusy (`ECONNREFUSED`), never OwnedByOther. + assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::TransientBusy); let rebound = try_bind_abstract_socket(name.as_bytes()).expect("rebind succeeds once first fd closes"); drop(rebound); } diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index e6628fca4..035d7cd27 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -269,19 +269,44 @@ enum GetentRaw { Ran(std::process::ExitStatus, Vec), } -/// Runs `program -- ` with a sanitized environment, bounded duration, +#[derive(Clone, Copy)] +enum GetentDb { + Passwd, + Group, + Initgroups, +} + +impl GetentDb { + fn as_str(self) -> &'static str { + match self { + Self::Passwd => "passwd", + Self::Group => "group", + Self::Initgroups => "initgroups", + } + } +} + +/// Runs `program ` with a sanitized environment, bounded duration, /// and bounded stdout capture. Kills the child process group and reaps it on /// timeout or oversized output. -fn exec_getent(program: &Path, args: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result { +/// +/// `db` is a closed enum (`passwd`, `group`, `initgroups`) and every element of +/// `keys` is validated against empty or dash-prefixed values so no option flag +/// can be injected without needing `"--"` (which `musl-utils` `getent` rejects). +fn exec_getent(program: &Path, db: GetentDb, keys: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result { use std::io::Read; use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; + if keys.is_empty() || keys.iter().any(|a| a.as_bytes().is_empty() || a.as_bytes()[0] == b'-') { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid getent argument")); + } + let mut cmd = Command::new(program); cmd.env_clear() .env("LC_ALL", "C") - .arg("--") - .args(args) + .arg(db.as_str()) + .args(keys) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -394,8 +419,8 @@ fn getent_account_lookup_with(program: &Path, key: &[u8], timeout: Duration, max if !valid_key(key) { return Ok(LookupResult::NotFound); } - let args = [OsStr::new("passwd"), OsStr::from_bytes(key)]; - match exec_getent(program, &args, timeout, max_bytes)? { + let keys = [OsStr::from_bytes(key)]; + match exec_getent(program, GetentDb::Passwd, &keys, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(LookupResult::NotFound), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => passwd_line(&stdout) @@ -453,12 +478,8 @@ fn getent_accounts_batch_with(program: &Path, keys: &[&CStr], timeout: Duration, if keys.is_empty() { return Ok(BatchAccounts::default()); } - let mut args: Vec<&OsStr> = Vec::with_capacity(1 + keys.len()); - args.push(OsStr::new("passwd")); - for k in keys { - args.push(OsStr::from_bytes(k.to_bytes())); - } - match exec_getent(program, &args, timeout, max_bytes)? { + let args: Vec<&OsStr> = keys.iter().map(|k| OsStr::from_bytes(k.to_bytes())).collect(); + match exec_getent(program, GetentDb::Passwd, &args, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(BatchAccounts::default()), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => { @@ -508,8 +529,8 @@ fn getent_group_lookup_with(program: &Path, key: &[u8]) -> io::Result Ok(None), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => group_line(&stdout) @@ -557,8 +578,8 @@ fn initgroups_has_detailed_with_limits(program: &Path, user: &CStr, gid: u32, ti if !valid_key(key) { return Ok(InitgroupsResult::NotMember); } - let args = [OsStr::new("initgroups"), OsStr::from_bytes(key)]; - match exec_getent(program, &args, timeout, max_bytes)? { + let keys = [OsStr::from_bytes(key)]; + match exec_getent(program, GetentDb::Initgroups, &keys, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(InitgroupsResult::NotMember), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => { @@ -833,6 +854,93 @@ fn peer_uid(conn: &UnixStream) -> io::Result { Ok(cred.uid) } +/// Parses a `/proc//status` `Groups:` line into GIDs. +fn parse_status_groups(status: &str) -> Vec { + status + .lines() + .find_map(|l| l.strip_prefix("Groups:")) + .map(|line| line.split_whitespace().filter_map(|tok| tok.parse::().ok()).collect()) + .unwrap_or_default() +} + +fn status_groups_contain(status: &str, want_gid: u32) -> bool { + parse_status_groups(status).contains(&want_gid) +} + +/// Verifies that the effective UID in `/proc//status` (`Uid:\treal\teff...`) +/// matches `want_uid` from `SO_PEERCRED`, defeating PID-reuse races. +fn status_euid_matches(status: &str, want_uid: u32) -> bool { + status + .lines() + .find_map(|l| l.strip_prefix("Uid:")) + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|tok| tok.parse::().ok()) + == Some(want_uid) +} + +fn read_proc_file_at(dir_fd: std::os::fd::RawFd, name: &CStr) -> Option { + use std::io::Read; + use std::os::fd::FromRawFd; + // SAFETY: `dir_fd` is a valid open directory fd and `name` is NUL-terminated. + let raw = unsafe { libc::openat(dir_fd, name.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW) }; + if raw < 0 { + return None; + } + // SAFETY: `raw` is a freshly opened descriptor owned here. + let mut f = unsafe { std::fs::File::from_raw_fd(raw) }; + let mut out = String::new(); + f.take(64 * 1024).read_to_string(&mut out).ok()?; + Some(out) +} + +/// Snapshot of a peer's credentials and `/proc/` state captured +/// synchronously at `accept()` time through a single pinned `/proc/` +/// directory descriptor before spawning `kiri-api` (prevents short-lived client +/// exit races and multi-step `/proc/` PID-reuse TOCTOU). +pub struct PinnedPeer { + uid: u32, + gid: u32, + groups: Vec, + cgroup: String, +} + +impl PinnedPeer { + pub fn capture(conn: &UnixStream) -> Option { + use std::os::fd::FromRawFd; + // SAFETY: connected socket and zeroed `ucred` storage. + let mut cred: libc::ucred = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: valid output pointers and buffer length. + let r = unsafe { libc::getsockopt(conn.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&mut cred as *mut libc::ucred).cast(), &mut len) }; + if r != 0 || len as usize != std::mem::size_of::() || cred.pid <= 0 { + return None; + } + let proc_path = CString::new(format!("/proc/{}", cred.pid)).ok()?; + // SAFETY: valid NUL-terminated path; pins the `/proc/` directory inode. + let raw_dir = unsafe { libc::open(proc_path.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + if raw_dir < 0 { + return None; + } + // SAFETY: `raw_dir` is a freshly opened directory descriptor owned here. + let dir_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(raw_dir) }; + let status = read_proc_file_at(dir_fd.as_raw_fd(), c"status")?; + if !status_euid_matches(&status, cred.uid) { + return None; + } + let cgroup = read_proc_file_at(dir_fd.as_raw_fd(), c"cgroup")?; + Some(PinnedPeer { + uid: cred.uid, + gid: cred.gid, + groups: parse_status_groups(&status), + cgroup, + }) + } + + fn holds_gid(&self, want_gid: u32) -> bool { + self.gid == want_gid || self.groups.contains(&want_gid) + } +} + /// Whether the account is in the group by name or as its primary group. fn group_member(user: &CStr, primary_gid: libc::gid_t, group: &Group) -> bool { primary_gid == group.gid || group.members.iter().any(|m| m.as_c_str() == user) @@ -1025,6 +1133,17 @@ impl AclState { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum PeerSubject { + HostUser(u32), + /// Containerized client on `docker.container.sock` verified to belong to a + /// live Kiri container cgroup and holding `gid`, whose numeric `uid` had no + /// host account at connect time (#127). Retains `uid` so sweeps re-verify + /// both group GID validity (with `DIRECTORY_MISS_GRACE`) and host user + /// absence. + ContainerGroup { uid: u32, gid: u32 }, +} + /// Who may use the engine's socket: root, the account the daemon runs as, and /// the members of one group, checked when they connect and again while they /// stay connected. @@ -1033,18 +1152,23 @@ pub struct Gate { /// The daemon's socket, and the one containers are given (caller.rs). sockets: Vec, owner: u32, - open: Mutex>, + open: Mutex>, next: AtomicU64, failing: AtomicBool, /// Recent per-uid decisions, in-flight coalescing, and concurrency cap so /// bursts of connections or local lookup storms stay bounded. lookup: Mutex, lookup_slot: Condvar, + /// Bounded/cached host-account absence checks for container UIDs (#127) so + /// bursts of container socket connections never spawn unthrottled `getent`. + container_uid_absent: Mutex>, /// Short-TTL group lookup cache for the accept path, invalidated when /// `/etc/group` changes. group_cache: Mutex>, /// Consecutive ambiguous exit-2 misses per connected uid. misses: Mutex>, + /// Consecutive ambiguous exit-2 group misses per container subject. + container_misses: Mutex>, /// UIDs written by `grant()` at startup, used to seed `watch()` so an /// outage right after boot does not shrink the initial ACL on tick 1. startup_uids: Mutex>>, @@ -1076,8 +1200,10 @@ impl Gate { failing: AtomicBool::new(false), lookup: Mutex::default(), lookup_slot: Condvar::new(), + container_uid_absent: Mutex::default(), group_cache: Mutex::default(), misses: Mutex::default(), + container_misses: Mutex::default(), startup_uids: Mutex::default(), })) } @@ -1223,13 +1349,30 @@ impl Gate { } let closed_uids = if connected { - self.sweep_membership_with(|uid| { - if uid == 0 || uid == self.owner { - return Ok(Membership::Allowed); - } - let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; - check_member(uid, g) - }) + self.sweep_subjects_with( + |uid| { + if uid == 0 || uid == self.owner { + return Ok(Membership::Allowed); + } + let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; + check_member(uid, g) + }, + |uid, gid| { + let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; + match g { + LookupResult::Found(found) if found.gid == gid => { + // Re-verify `uid` is still not a revoked host account + // (e.g., if NSS recovered after an ambiguous connect-time miss). + match account_by_uid_detailed(uid)? { + LookupResult::Found(_) => check_member(uid, g), + LookupResult::NotFound | LookupResult::UnavailableOrNotFound => Ok(Membership::Allowed), + } + } + LookupResult::Found(_) | LookupResult::NotFound => Ok(Membership::Revoked), + LookupResult::UnavailableOrNotFound => Ok(Membership::MissingFromDirectory), + } + }, + ) } else { HashSet::new() }; @@ -1434,11 +1577,108 @@ impl Gate { set_each(&self.sockets, uids, set) } - /// Checks a new connection. `None`: refused, and the reason logged. + /// Checks a new host connection. `None`: refused, and the reason logged. pub fn admit(self: &Arc, conn: &UnixStream) -> Option { self.admit_with(conn, |uid| self.allowed(uid)) } + /// Checks a new connection on `docker.container.sock`: admits host group + /// members as usual, and also admits containerized clients inside a live + /// Kiri container cgroup holding the access group's GID whose numeric UID + /// has no host account (#127). + pub fn admit_container( + self: &Arc, + conn: &UnixStream, + pinned: Option, + is_running_container_cgroup: impl FnOnce(&str) -> bool, + ) -> Option { + let uid = match pinned.as_ref().map(|p| Ok(p.uid)).unwrap_or_else(|| peer_uid(conn)) { + Ok(u) => u, + Err(e) => { + crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e); + return None; + } + }; + let subject = match self.allowed(uid) { + Ok(true) => PeerSubject::HostUser(uid), + Ok(false) => match self.container_group_subject(pinned, is_running_container_cgroup) { + Ok(Some(sub)) => sub, + Ok(None) => { + crate::diag::warn!("socket connection refused: user is not in the access group", group = self.name(), uid = uid); + return None; + } + Err(e) => { + crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e); + return None; + } + }, + Err(e) => { + crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e); + return None; + } + }; + self.track_seat(conn, subject) + } + + fn uid_absent_throttled(&self, uid: u32) -> io::Result { + { + let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()); + cache.retain(|_, (_, at)| at.elapsed() < RECHECK); + if let Some(&(absent, _)) = cache.get(&uid) { + return Ok(absent); + } + } + // Acquire one of Gate's bounded lookup slots (MAX_CONCURRENT_LOOKUPS = 4) + // so container connection bursts never spawn unthrottled `getent` children. + { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + while state.active >= MAX_CONCURRENT_LOOKUPS { + if state.waiting >= MAX_WAITING_LOOKUPS { + return Err(io::Error::new(io::ErrorKind::WouldBlock, "too many concurrent access checks")); + } + state.waiting += 1; + state = self.lookup_slot.wait(state).unwrap_or_else(|e| e.into_inner()); + state.waiting -= 1; + } + state.active += 1; + } + let lookup_res = account_by_uid_detailed(uid); + { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + state.active = state.active.saturating_sub(1); + self.lookup_slot.notify_all(); + } + let absent = match lookup_res? { + LookupResult::NotFound | LookupResult::UnavailableOrNotFound => true, + LookupResult::Found(_) => false, + }; + let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()); + if cache.len() >= MAX_RECENT_ENTRIES + && !cache.contains_key(&uid) + && let Some(&oldest) = cache.iter().min_by_key(|(_, (_, at))| *at).map(|(k, _)| k) + { + cache.remove(&oldest); + } + cache.insert(uid, (absent, Instant::now())); + Ok(absent) + } + + fn container_group_subject( + &self, + pinned: Option, + is_running_container_cgroup: impl FnOnce(&str) -> bool, + ) -> io::Result> { + let Some(peer) = pinned else { return Ok(None) }; + let LookupResult::Found(group) = self.cached_group()? else { return Ok(None) }; + if !peer.holds_gid(group.gid) || !is_running_container_cgroup(&peer.cgroup) { + return Ok(None); + } + if !self.uid_absent_throttled(peer.uid)? { + return Ok(None); + } + Ok(Some(PeerSubject::ContainerGroup { uid: peer.uid, gid: group.gid })) + } + fn admit_with(self: &Arc, conn: &UnixStream, check: impl Fn(u32) -> io::Result) -> Option { let checked = peer_uid(conn).and_then(|uid| Ok((uid, check(uid)?))); let uid = match checked { @@ -1452,6 +1692,10 @@ impl Gate { return None; } }; + self.track_seat(conn, PeerSubject::HostUser(uid)) + } + + fn track_seat(self: &Arc, conn: &UnixStream, subject: PeerSubject) -> Option { let keep = match conn.try_clone() { Ok(c) => c, Err(e) => { @@ -1460,44 +1704,88 @@ impl Gate { } }; let id = self.next.fetch_add(1, Ordering::Relaxed); - self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (uid, keep)); + self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (subject, keep)); Some(Seat { gate: self.clone(), id }) } - /// Checks everyone still connected, once per account, and closes the + #[cfg(test)] + fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result) -> HashSet { + self.sweep_subjects_with(check, |_, _| Ok(Membership::Allowed)) + } + + /// Checks everyone still connected, once per subject, and closes the /// connections of anyone no longer allowed. A failed lookup leaves the /// connections open (new ones are refused until lookups work again). /// Ambiguous directory exit-2 misses use a grace window before closing. - fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result) -> HashSet { - let uids: HashSet = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(u, _)| *u).collect(); - let mut removed = HashSet::new(); + fn sweep_subjects_with( + &self, + check_user: impl Fn(u32) -> io::Result, + check_container: impl Fn(u32, u32) -> io::Result, + ) -> HashSet { + let subjects: HashSet = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(s, _)| *s).collect(); + let host_uids: HashSet = subjects + .iter() + .filter_map(|s| match s { + PeerSubject::HostUser(u) => Some(*u), + PeerSubject::ContainerGroup { .. } => None, + }) + .collect(); + let mut removed_subjects = HashSet::new(); + let mut removed_uids = HashSet::new(); + let mut removed_container_uids = HashSet::new(); let mut failed = None; - let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); - misses.retain(|u, _| uids.contains(u)); - drop(misses); - - for uid in uids { - match check(uid) { - Ok(Membership::Allowed) => { - self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); - self.remember_decision(uid, CachedDecision::Allowed); - } - Ok(Membership::Revoked) => { - self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); - self.remember_decision(uid, CachedDecision::Denied); - removed.insert(uid); - } - Ok(Membership::MissingFromDirectory) => { - self.remember_decision(uid, CachedDecision::Denied); - let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); - let count = misses.entry(uid).or_insert(0); - *count = count.saturating_add(1); - if *count >= DIRECTORY_MISS_GRACE { - misses.remove(&uid); - removed.insert(uid); + self.misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|u, _| host_uids.contains(u)); + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|s, _| subjects.contains(s)); + + for subject in subjects { + match subject { + PeerSubject::HostUser(uid) => match check_user(uid) { + Ok(Membership::Allowed) => { + self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + self.remember_decision(uid, CachedDecision::Allowed); } - } - Err(e) => failed = Some(e), + Ok(Membership::Revoked) => { + self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + self.remember_decision(uid, CachedDecision::Denied); + removed_subjects.insert(subject); + removed_uids.insert(uid); + } + Ok(Membership::MissingFromDirectory) => { + self.remember_decision(uid, CachedDecision::Denied); + let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); + let count = misses.entry(uid).or_insert(0); + *count = count.saturating_add(1); + if *count >= DIRECTORY_MISS_GRACE { + misses.remove(&uid); + removed_subjects.insert(subject); + removed_uids.insert(uid); + } + } + Err(e) => failed = Some(e), + }, + PeerSubject::ContainerGroup { uid, gid } => match check_container(uid, gid) { + Ok(Membership::Allowed) => { + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject); + } + Ok(Membership::Revoked) => { + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject); + self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + removed_subjects.insert(subject); + removed_container_uids.insert(uid); + } + Ok(Membership::MissingFromDirectory) => { + let mut misses = self.container_misses.lock().unwrap_or_else(|e| e.into_inner()); + let count = misses.entry(subject).or_insert(0); + *count = count.saturating_add(1); + if *count >= DIRECTORY_MISS_GRACE { + misses.remove(&subject); + self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + removed_subjects.insert(subject); + removed_container_uids.insert(uid); + } + } + Err(e) => failed = Some(e), + }, } } match failed { @@ -1505,13 +1793,13 @@ impl Gate { None if self.failing.swap(false, Ordering::Relaxed) => crate::diag::info!("access check works again", group = self.name()), _ => {} } - if removed.is_empty() { - return removed; + if removed_subjects.is_empty() { + return removed_uids; } // Taken out as they're closed, so a thread that takes a while to // notice isn't closed and logged again on every recheck. - self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (uid, conn)| { - if !removed.contains(uid) { + self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (subject, conn)| { + if !removed_subjects.contains(subject) { return true; } // Ends the connection for every thread using it: reads see the @@ -1519,10 +1807,10 @@ impl Gate { let _ = conn.shutdown(Shutdown::Both); false }); - for uid in &removed { + for uid in removed_uids.iter().chain(removed_container_uids.iter()) { crate::diag::warn!("connections closed: user is no longer in the access group", group = self.name(), uid = uid); } - removed + removed_uids } #[cfg(test)] @@ -1964,8 +2252,7 @@ mod tests { let touched = dir.join("touched"); let script = format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ db=\"$1\"; key=\"$2\"\n\ case \"$key\" in -*) echo bad > \"{}\"; exit 9 ;; esac\n\ case \"$db:$key\" in\n\ @@ -2087,8 +2374,7 @@ mod tests { "fake-getent", &format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1\" in\n\ passwd) export -p > \"{}\"; echo 'alice:x:5001:5001::/:/bin/sh'; exit 0 ;;\n\ initgroups) export -p > \"{}\"; echo 'alice 998'; exit 0 ;;\n\ @@ -2128,8 +2414,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$2\" in\n\ hang) [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\ hang_closed) exec >&-; [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\ @@ -2193,8 +2478,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1:$2\" in\n\ passwd:alice|passwd:Alice@corp.example) echo 'alice@corp.example:x:5001:5001::/home/alice:/bin/sh'; exit 0 ;;\n\ passwd:0|'passwd:+0'|'passwd: 0'|'passwd: -0') echo 'root:x:0:0:root:/root:/bin/sh'; exit 0 ;;\n\ @@ -2245,8 +2529,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1:$2\" in\n\ initgroups:alice) echo 'alice -2147483648 -1000 998'; exit 0 ;;\n\ *) exit 2 ;;\n\ @@ -2267,8 +2550,7 @@ mod tests { "fake-getent", &format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ db=\"$1\"; shift\n\ echo x >> \"{}\"\n\ [ \"$db\" = \"passwd\" ] || exit 2\n\ @@ -3037,4 +3319,28 @@ mod tests { assert_eq!(state.uids, Some(vec![1001, 5002]), "bob must get a fresh grace window after alice was dropped"); assert_eq!(state.shrink_streak, 1); } + + #[test] + fn container_group_subject_parses_supplementary_groups_and_revokes_on_gid_change() { + let status = "Name:\tpython3\nUid:\t54321\t54321\t54321\t54321\nGid:\t54321\t54321\t54321\t54321\nGroups:\t100 998 65534 \n"; + assert!(status_groups_contain(status, 998)); + assert!(!status_groups_contain(status, 999)); + assert!(status_euid_matches(status, 54321)); + assert!(!status_euid_matches(status, 1000)); + assert!(exec_getent(Path::new("/usr/bin/getent"), GetentDb::Passwd, &[OsStr::new("-V")], Duration::from_secs(1), 1024).is_err()); + + let g = gate(); + let (a, _b) = UnixStream::pair().unwrap(); + let _seat = g.track_seat(&a, PeerSubject::ContainerGroup { uid: 54321, gid: 998 }).unwrap(); + // Matching GID keeps the container connection open across sweeps. + assert!(g.sweep_subjects_with(|_| unreachable!(), |u, gid| Ok(if u == 54321 && gid == 998 { Membership::Allowed } else { Membership::Revoked })).is_empty()); + assert_eq!(g.open.lock().unwrap().len(), 1); + // Transient directory exit-2 misses honor DIRECTORY_MISS_GRACE before closing. + for _ in 1..DIRECTORY_MISS_GRACE { + assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty()); + assert_eq!(g.open.lock().unwrap().len(), 1); + } + assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty()); + assert!(g.open.lock().unwrap().is_empty()); + } } diff --git a/crates/kiri/src/daemon/domains.rs b/crates/kiri/src/daemon/domains.rs index 4a59475b5..82c526f7a 100644 --- a/crates/kiri/src/daemon/domains.rs +++ b/crates/kiri/src/daemon/domains.rs @@ -418,10 +418,15 @@ fn route(client: &mut impl ReadWrite, engine: &Engine, scheme: &str) -> io::Resu } }; let text = String::from_utf8_lossy(&head[..end]); - let host = text + let mut hosts = text .lines() - .find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned())) - .unwrap_or_default(); + .skip(1) + .filter_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned())); + let host = hosts.next().unwrap_or_default(); + if hosts.next().is_some() { + respond(client, 400, "Bad Request", "")?; + return Ok(None); + } let Some(target) = engine.route(&host) else { // The running containers are listed only for this machine's own // names. A page reached through DNS rebinding asks with its own @@ -628,27 +633,42 @@ fn respond(client: &mut impl Write, status: u16, reason: &str, body: &str) -> io ) } +/// Parses a request `Host` header (`[::1]:80`, `127.0.0.1:80`, +/// `web.kiri.local:8080`, `web.kiri.local.`), rejecting malformed or zero +/// ports, non-IPv6 bracketed hosts, and multiple trailing dots. +pub(super) fn parse_host_name(host: &str) -> Option { + let host = host.trim(); + if host.is_empty() { + return None; + } + let valid_port = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n != 0); + if let Some(v6) = host.strip_prefix('[') { + let addr = match v6.split_once(']') { + Some((addr, "")) => addr, + Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr, + _ => return None, + }; + addr.parse::().ok()?; + return Some(addr.to_ascii_lowercase()); + } + let name = match host.rsplit_once(':') { + Some((name, port)) if !name.contains(':') && valid_port(port) => name, + Some(_) => return None, + None => host, + }; + let name = name.strip_suffix('.').unwrap_or(name); + if name.is_empty() || name.ends_with('.') { + return None; + } + Some(name.to_ascii_lowercase()) +} + /// Whether a request's Host is a name for this machine itself: `localhost`, /// anything under `.localhost` (which always resolves to loopback), a /// `.kiri.local` name, or a loopback address. Another site's domain is not, /// even when its DNS answers with 127.0.0.1. fn local_host(host: &str) -> bool { - let host = host.trim(); - // Without the port: `[::1]:80`, `127.0.0.1:80`, `web.kiri.localhost:8080`. - let valid_port = |p: &str| p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n != 0); - let name = match host.strip_prefix('[') { - Some(v6) => match v6.split_once(']') { - Some((addr, "")) => addr, - Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr, - _ => return false, - }, - None => match host.rsplit_once(':') { - Some((name, port)) if valid_port(port) => name, - Some(_) => return false, - None => host, - }, - }; - let name = name.trim_end_matches('.').to_ascii_lowercase(); + let Some(name) = parse_host_name(host) else { return false }; name == "localhost" || name.ends_with(".localhost") || name.ends_with(".kiri.local") || name.parse::().is_ok_and(|ip| ip.is_loopback()) } @@ -743,4 +763,14 @@ mod tests { // Listening elsewhere only: keep the first candidate. assert_eq!(choose(&[3000], Some(&[9229])), 3000); } + + #[test] + fn parse_host_name_trims_trailing_dot_and_rejects_bad_ports() { + assert_eq!(super::parse_host_name("web.kiri.local."), Some("web.kiri.local".into())); + assert_eq!(super::parse_host_name("WEB.KIRI.LOCAL:8080"), Some("web.kiri.local".into())); + assert_eq!(super::parse_host_name("[::1]:8080"), Some("::1".into())); + for bad in ["", "web.kiri.local:0", "web.kiri.local:65536", "web.kiri.local:abc", "web.kiri.local:", "web.kiri.local:+80", "a:b:80", "[web.kiri.local]:80", "[localhost]", "web.kiri.local.."] { + assert_eq!(super::parse_host_name(bad), None, "{bad}"); + } + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 790e082e2..ec99457eb 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -4712,7 +4712,7 @@ impl Engine { /// Names are the container name, or `.` for Compose /// services. pub fn route(&self, host: &str) -> Option { - let host = host.split(':').next()?.to_ascii_lowercase(); + let host = super::domains::parse_host_name(host)?; let name = host.strip_suffix(".kiri.localhost").or_else(|| host.strip_suffix(".kiri.local"))?.to_owned(); let st = self.lock(); let c = st.containers.values().find(|c| { @@ -4743,6 +4743,41 @@ impl Engine { c.first_if = Some(0); } + /// Checks whether a `/proc//cgroup` snapshot belongs to one of this + /// engine's currently running containers under a root-owned `kiri/` + /// cgroup directory (#127). Prevents unprivileged host `unshare -Um` + + /// `newuidmap` processes from impersonating containers on `docker.container.sock`. + #[cfg(target_os = "linux")] + pub fn has_running_container_cgroup(&self, cgroup_text: &str) -> bool { + use std::os::unix::fs::MetadataExt; + for line in cgroup_text.lines() { + let Some((_, rest)) = line.split_once(':') else { continue }; + let Some((_, rel_path)) = rest.split_once(':') else { continue }; + if !rel_path.starts_with('/') { + continue; + } + let segs: Vec<&str> = rel_path.split('/').filter(|s| !s.is_empty()).collect(); + for i in 1..segs.len() { + let id = segs[i]; + if segs[i - 1] != "kiri" || id.len() != 64 || !id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + continue; + } + let is_running = self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running); + if !is_running { + continue; + } + let prefix = format!("/sys/fs/cgroup/{}", segs[..=i].join("/")); + let parent = format!("/sys/fs/cgroup/{}", segs[..i].join("/")); + if std::fs::symlink_metadata(&prefix).is_ok_and(|m| m.is_dir() && m.uid() == 0) + && std::fs::symlink_metadata(&parent).is_ok_and(|m| m.is_dir() && m.uid() == 0) + { + return true; + } + } + } + false + } + /// For the Finder view (macOS). #[cfg_attr(not(target_os = "macos"), allow(dead_code))] pub fn fs_stat(&self, id: &str, path: &str) -> io::Result { diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index 2a5972969..c58dc4050 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -428,9 +428,26 @@ pub fn run(_args: &[String]) -> io::Result<()> { } #[cfg(target_os = "linux")] +#[cfg(test)] fn admit_connection(gate: &Option>, conn: &UnixStream) -> Result, ()> { + admit_connection_for(gate, conn, None, &None) +} + +#[cfg(target_os = "linux")] +fn admit_connection_for( + gate: &Option>, + conn: &UnixStream, + pinned: Option, + container_engine: &Option>, +) -> Result, ()> { match gate { - Some(gate) => gate.admit(conn).map(Some).ok_or(()), + Some(gate) => { + let seat = match container_engine { + Some(eng) => gate.admit_container(conn, pinned, |cg| eng.has_running_container_cgroup(cg)), + None => gate.admit(conn), + }; + seat.map(Some).ok_or(()) + } None => Ok(None), } } @@ -443,12 +460,16 @@ fn accept( who: caller::Caller, ) { let cap = open_conns_for(&who); + #[cfg(target_os = "linux")] + let container_engine = matches!(who, caller::Caller::Container).then(|| engine.clone()); let engine = engine.clone(); - serve_each_with( + serve_each_inner( listener, cap, #[cfg(target_os = "linux")] gate, + #[cfg(target_os = "linux")] + container_engine, std::sync::Arc::new(move |conn| { let _ = api::serve(conn, engine.clone(), who.clone()); }), @@ -582,6 +603,24 @@ fn serve_each_with( cap: &std::sync::Arc, #[cfg(target_os = "linux")] gate: &Option>, serve: std::sync::Arc, +) { + serve_each_inner( + listener, + cap, + #[cfg(target_os = "linux")] + gate, + #[cfg(target_os = "linux")] + None, + serve, + ); +} + +fn serve_each_inner( + listener: &UnixListener, + cap: &std::sync::Arc, + #[cfg(target_os = "linux")] gate: &Option>, + #[cfg(target_os = "linux")] container_engine: Option>, + serve: std::sync::Arc, ) { for conn in listener.incoming() { let Ok(conn) = conn else { continue }; @@ -590,15 +629,26 @@ fn serve_each_with( drop(conn); continue; }; + // Capture `/proc/` credentials + cgroup synchronously at `accept()` + // before spawning `kiri-api`, preventing short-lived client exit races + // and PID-reuse TOCTOU (#127). + #[cfg(target_os = "linux")] + let pinned = if gate.is_some() && container_engine.is_some() { + access::PinnedPeer::capture(&conn) + } else { + None + }; let serve = serve.clone(); #[cfg(target_os = "linux")] let gate = gate.clone(); + #[cfg(target_os = "linux")] + let container_engine = container_engine.clone(); let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { let _permit = permit; // Checked here, not in the accept loop: a slow user lookup holds up // this connection only. #[cfg(target_os = "linux")] - let Ok(_seat) = admit_connection(&gate, &conn) else { + let Ok(_seat) = admit_connection_for(&gate, &conn, pinned, &container_engine) else { return; }; serve(conn); diff --git a/crates/kiri/src/doctor.rs b/crates/kiri/src/doctor.rs index df3dc9960..625a23b75 100644 --- a/crates/kiri/src/doctor.rs +++ b/crates/kiri/src/doctor.rs @@ -331,12 +331,33 @@ fn names(installed: bool) -> Check { /// Whether a docker host is this Kiri's socket: `Some(false)` only when /// both are local sockets and resolve to different files (another Kiri, -/// such as the installed one next to Kiri Dev). +/// such as the installed one next to Kiri Dev). On Linux, a root daemon +/// without `KIRI_SOCKET` binds both `/run/kiri/docker.sock` and +/// `~/.kiri/run/docker.sock`, so both belong to this Kiri. #[cfg(unix)] fn ours_unix(host: &str) -> Option { - let theirs = std::fs::canonicalize(host.strip_prefix("unix://")?).ok()?; + let raw = std::path::Path::new(host.strip_prefix("unix://")?); + let theirs = std::fs::canonicalize(raw).ok()?; let ours = std::fs::canonicalize(crate::client::socket().ok()?).ok()?; - Some(theirs == ours) + if theirs == ours { + return Some(true); + } + #[cfg(target_os = "linux")] + if std::env::var_os("KIRI_SOCKET").is_none() { + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + if let Ok(home_sock) = crate::daemon::home_socket_path() + && let Ok(md) = std::fs::symlink_metadata(&home_sock) + && !md.file_type().is_symlink() + && md.file_type().is_socket() + && md.uid() == 0 + && std::fs::symlink_metadata(crate::client::SERVICE_SOCKET) + .is_ok_and(|smd| !smd.file_type().is_symlink() && smd.file_type().is_socket() && smd.uid() == 0) + && std::fs::canonicalize(&home_sock).ok().as_ref() == Some(&theirs) + { + return Some(true); + } + } + Some(false) } enum Reached { From e0abcea257cb90bfc2e0c3a93809a21700eef921 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 133/157] Host configs: keep kubeconfig, docker config and buildx state intact on odd input (#965) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/buildwith.rs | 77 ++++++++++++++++++++---- crates/kiri/src/dockerctx.rs | 59 ++++++++++++++---- crates/kiri/src/kubeconfig.rs | 109 +++++++++++++++++++++++++++++----- 3 files changed, 208 insertions(+), 37 deletions(-) diff --git a/crates/kiri/src/buildwith.rs b/crates/kiri/src/buildwith.rs index 87832d19d..4bf796aff 100644 --- a/crates/kiri/src/buildwith.rs +++ b/crates/kiri/src/buildwith.rs @@ -86,14 +86,28 @@ fn read_json(path: &Path) -> io::Result { } } +fn read_object(path: &Path) -> io::Result { + let v = read_json(path)?; + if v.is_object() { + Ok(v) + } else { + Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", path.display()))) + } +} + /// Through a temporary file, so a crash never leaves half a file. fn write_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("kiri-tmp"); - std::fs::write(&tmp, bytes)?; - std::fs::rename(tmp, path) + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir)?; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("tmp"); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); + } + res } fn write_json(path: &Path, v: &Value) -> io::Result<()> { @@ -114,7 +128,7 @@ impl Places { } fn state(&self) -> Value { - read_json(&self.state).unwrap_or_else(|_| json!({})) + read_json(&self.state).ok().filter(Value::is_object).unwrap_or_else(|| json!({})) } /// What was chosen (or set for a machine with no other engine). @@ -163,10 +177,16 @@ impl Places { Ok(()) } - /// Whether a builder is Kiri's copy: its nodes are Kiri's builder's. + /// Whether a builder is Kiri's copy: its nodes are Kiri's builder's (`0`, …). fn copied(&self, instance: &Value) -> bool { let nodes = instance["Nodes"].as_array().map(Vec::as_slice).unwrap_or_default(); - !nodes.is_empty() && nodes.iter().all(|n| n["Name"].as_str().is_some_and(|name| name.starts_with(&self.builder))) + !nodes.is_empty() + && nodes.iter().all(|n| { + n["Name"] + .as_str() + .and_then(|name| name.strip_prefix(&self.builder)) + .is_some_and(|idx| !idx.is_empty() && idx.bytes().all(|b| b.is_ascii_digit())) + }) } fn save(&self, with: With, auto: bool) -> io::Result<()> { @@ -185,7 +205,7 @@ impl Places { } let mut s = self.state(); if s["before"].is_null() { - let cfg = read_json(&self.config())?; + let cfg = read_object(&self.config())?; let current = match std::fs::read_to_string(self.current()) { Ok(t) => Value::String(t), Err(e) if e.kind() == io::ErrorKind::NotFound => Value::Null, @@ -194,7 +214,7 @@ impl Places { s["before"] = json!({"alias": cfg["aliases"]["builder"], "aliases": cfg.get("aliases").is_some(), "current": current}); write_json(&self.state, &s)?; } - let mut cfg = read_json(&self.config())?; + let mut cfg = read_object(&self.config())?; if !cfg["aliases"].is_object() { cfg["aliases"] = json!({}); } @@ -217,7 +237,7 @@ impl Places { if before.is_null() { return Ok(()); } - let mut cfg = read_json(&self.config())?; + let mut cfg = read_object(&self.config())?; if cfg["aliases"]["builder"] == "buildx" { match &before["alias"] { Value::Null => { @@ -598,4 +618,37 @@ mod tests { assert_eq!(read_json(&p.config()).unwrap(), json!({})); assert!(!p.current().exists() && !p.instance("kiri").exists() && !p.state.exists()); } + + #[test] + fn rejects_non_object_configs_without_panicking_and_preserves_prefix_builders() { + let d = scratch("non-obj"); + let p = places(&d); + builder(&p); + std::fs::create_dir_all(&p.docker).unwrap(); + for bad in ["[1, 2]", "\"str\"", "true", "null"] { + std::fs::write(p.config(), bad).unwrap(); + assert_eq!(p.choose(With::Kiri).unwrap_err().kind(), io::ErrorKind::InvalidData, "{bad}"); + assert_eq!(std::fs::read_to_string(p.config()).unwrap(), bad); + } + std::fs::remove_file(p.config()).unwrap(); + + // Corrupt non-object build.json recovers as `{}` without panicking. + std::fs::create_dir_all(p.state.parent().unwrap()).unwrap(); + std::fs::write(&p.state, "[1, 2]").unwrap(); + p.choose(With::Kiri).unwrap(); + assert!(p.taken()); + p.choose(With::Docker).unwrap(); + assert!(!p.taken()); + + // Foreign builders whose node names share prefix `kiri-build` (`kiri-builder0`, `kiri-build-dev0`) stay untouched. + for node_name in ["kiri-builder0", "kiri-build-dev0", "kiri-build"] { + let foreign = json!({"Name": "kiri", "Driver": "docker-container", "Nodes": [{"Name": node_name, "Endpoint": "desktop-linux"}]}); + write_json(&p.instance("kiri"), &foreign).unwrap(); + p.choose(With::Docker).unwrap(); + assert_eq!(read_json(&p.instance("kiri")).unwrap(), foreign, "{node_name}"); + p.uninstall().unwrap(); + assert!(p.instance("kiri").is_file(), "{node_name}"); + } + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs index da2a2251b..19d600ee2 100644 --- a/crates/kiri/src/dockerctx.rs +++ b/crates/kiri/src/dockerctx.rs @@ -83,18 +83,25 @@ pub fn cli(env: &Env, ours: &str, our_hosts: &[&str], endpoint: &Endpoint) -> Cl Cli { context, pinned, kiri } } +fn strip_bom(bytes: &[u8]) -> &[u8] { + bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes) +} + /// config.json's `currentContext`, when it names one. fn current(config: Option<&[u8]>) -> Option { - let cfg: Value = serde_json::from_slice(config?).ok()?; + let cfg: Value = serde_json::from_slice(strip_bom(config?)).ok()?; cfg["currentContext"].as_str().map(str::trim).filter(|c| !c.is_empty()).map(str::to_owned) } /// Two docker hosts that are the same endpoint: `npipe:////./pipe/x` and /// `npipe://./pipe/x`, any case, are one pipe. fn same_host(a: &str, b: &str) -> bool { - let norm = |h: &str| match h.get(..6) { - Some(s) if s.eq_ignore_ascii_case("npipe:") => format!("npipe:{}", h[6..].replace('\\', "/").trim_start_matches('/').to_ascii_lowercase()), - _ => h.trim_end_matches('/').to_owned(), + let norm = |h: &str| match h.split_once(':') { + Some((scheme, rest)) if scheme.eq_ignore_ascii_case("npipe") => { + format!("npipe:{}", rest.replace('\\', "/").trim_matches('/').to_ascii_lowercase()) + } + Some((scheme, rest)) => format!("{}:{}", scheme.to_ascii_lowercase(), rest.trim_end_matches('/')), + None => h.trim_end_matches('/').to_owned(), }; norm(a) == norm(b) } @@ -187,7 +194,7 @@ fn dir_in(config: Option, home: Option) -> Option { pub fn read_json(path: &Path) -> io::Result { match std::fs::read(path) { - Ok(b) => serde_json::from_slice(&b).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), + Ok(b) => serde_json::from_slice(strip_bom(&b)).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(json!({})), Err(e) => Err(e), } @@ -195,12 +202,18 @@ pub fn read_json(path: &Path) -> io::Result { /// Writes JSON through a temporary file, so a crash never leaves half a config. pub fn write_json(path: &Path, v: &Value) -> io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir)?; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config.json"); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let bytes = serde_json::to_vec_pretty(v).map_err(io::Error::other)?; + let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); } - let tmp = path.with_extension("kiri-tmp"); - std::fs::write(&tmp, serde_json::to_vec_pretty(v).map_err(io::Error::other)?)?; - std::fs::rename(tmp, path) + res } /// A context's meta.json, as `docker context create NAME --docker @@ -460,6 +473,32 @@ mod tests { assert_eq!((sk["context"].as_str(), sk["pinned"].is_null()), (Some("kiri"), true)); } + #[test] + fn reads_bom_configs_normalizes_host_schemes_and_isolates_temp_files() { + let mut bom_cfg = vec![0xEF, 0xBB, 0xBF]; + bom_cfg.extend_from_slice(br#"{"currentContext":"desktop-linux","auths":{"ghcr.io":{}}}"#); + let c = cli(&Env { config: Some(&bom_cfg), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri); + assert_eq!((c.context.as_str(), c.kiri), ("desktop-linux", false)); + + let home = scratch_home("bom-tmp"); + let cfg_path = home.join("config.json"); + std::fs::write(&cfg_path, &bom_cfg).unwrap(); + set_current(&cfg_path, "kiri").unwrap(); + assert_eq!(read_json(&cfg_path).unwrap()["currentContext"], "kiri"); + + write_json(&home.join("ctx.one"), &json!({"n": 1})).unwrap(); + write_json(&home.join("ctx.two"), &json!({"n": 2})).unwrap(); + assert_eq!(read_json(&home.join("ctx.one")).unwrap()["n"], 1); + assert_eq!(read_json(&home.join("ctx.two")).unwrap()["n"], 2); + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 3); + + for h in ["UNIX:///var/run/docker.sock", "NPIPE:////./PIPE/DOCKER_ENGINE/", r"npipe://\\.\pipe\docker_engine\"] { + assert!(cli(&Env { host: Some(h), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri).kiri, "{h}"); + } + assert!(cli(&Env { host: Some("npipe:////./pipe/kiri/"), ..Env::default() }, OURS, &["npipe:////./pipe/kiri"], &Endpoint::Free).kiri); + let _ = std::fs::remove_dir_all(&home); + } + #[cfg(unix)] #[test] fn sock_at_detects_kiri_taken_and_free() { diff --git a/crates/kiri/src/kubeconfig.rs b/crates/kiri/src/kubeconfig.rs index 5b1d7bb33..abfee778b 100644 --- a/crates/kiri/src/kubeconfig.rs +++ b/crates/kiri/src/kubeconfig.rs @@ -106,6 +106,7 @@ fn read(path: &Path) -> io::Result> { /// The new text by a temporary file and a rename, 0600; the one before it /// kept as `config.bak.kiri`. fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); std::fs::create_dir_all(dir)?; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config"); @@ -114,7 +115,8 @@ fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { std::fs::write(&backup, before)?; private(&backup)?; } - let tmp = dir.join(format!(".{file}.kiri-{}", std::process::id())); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-{}-{seq}", std::process::id())); let done = std::fs::write(&tmp, text).and_then(|()| private(&tmp)).and_then(|()| std::fs::rename(&tmp, path)); if done.is_err() { let _ = std::fs::remove_file(&tmp); @@ -149,16 +151,52 @@ fn blank(l: &str) -> bool { t.is_empty() || t.starts_with('#') } -fn tops(text: &str) -> Vec> { +/// Strips a YAML `#` comment starting at index 0 or preceded by whitespace. +fn uncomment(s: &str) -> &str { + let bytes = s.as_bytes(); + for (i, &b) in bytes.iter().enumerate() { + if b == b'#' && (i == 0 || matches!(bytes[i - 1], b' ' | b'\t')) { + return &s[..i]; + } + } + s +} + +fn is_doc_marker(l: &str, marker: &str) -> bool { + uncomment(l).trim_end() == marker +} + +fn tops(text: &str) -> Result>, String> { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut tops = vec![Top { key: "", lines: Vec::new() }]; + let mut seen_content = false; + let mut seen_end = false; for l in text.lines() { + if seen_end && !blank(l) { + return Err("a multi-document kubeconfig; not changing it".into()); + } + if is_doc_marker(l, "---") { + if seen_content { + return Err("a multi-document kubeconfig; not changing it".into()); + } + tops.last_mut().expect("there is one").lines.push(l); + continue; + } + if is_doc_marker(l, "...") { + seen_end = true; + tops.push(Top { key: "...", lines: vec![l] }); + continue; + } + if !blank(l) { + seen_content = true; + } let top = !l.starts_with([' ', '\t', '-', '#']) && !l.trim().is_empty(); match l.split_once(':').filter(|_| top) { Some((key, _)) => tops.push(Top { key: key.trim(), lines: vec![l] }), None => tops.last_mut().expect("there is one").lines.push(l), } } - tops + Ok(tops) } /// The lines before a list's first item, its items (each its lines), and their indent. @@ -166,7 +204,7 @@ type Items<'a> = (Vec<&'a str>, Vec>, usize); /// A list's items; an error for a list that isn't a block list. fn items<'a>(top: &Top<'a>) -> Result, String> { - let value = top.lines[0].split_once(':').map_or("", |(_, v)| v).split(" #").next().unwrap_or("").trim(); + let value = uncomment(top.lines[0].split_once(':').map_or("", |(_, v)| v)).trim(); if !matches!(value, "" | "[]" | "null" | "~") { return Err(format!("`{}` is not a list kubectl writes; not changing it", top.key)); } @@ -185,13 +223,25 @@ fn items<'a>(top: &Top<'a>) -> Result, String> { Ok((body[..at].to_vec(), items, dash)) } -/// An item's `name`, the key at the column after its dash. +/// An item's `name`, the key at the column after its dash (or on the lines below a bare `-`). fn item_name<'a>(item: &[&'a str], dash: usize) -> Option<&'a str> { let rest = &item[0][dash + 1..]; - let col = dash + 1 + indent(rest); let first = rest.trim_start(); - let line = if first.starts_with("name:") { Some(first) } else { item[1..].iter().find(|l| indent(l) == col && l.trim_start().starts_with("name:")).map(|l| l.trim_start()) }; - line.map(|l| scalar(&l["name:".len()..])) + let has_inline_key = !blank(rest); + let col = if has_inline_key { + dash + 1 + indent(rest) + } else { + item[1..].iter().find(|l| !blank(l)).map(|l| indent(l)).filter(|&c| c > dash)? + }; + let match_name = |s: &'a str| { + s.strip_prefix("name:") + .filter(|after| after.is_empty() || after.starts_with([' ', '\t', '#'])) + .map(scalar) + }; + if has_inline_key && let Some(n) = match_name(first) { + return Some(n); + } + item[1..].iter().filter(|l| indent(l) == col).find_map(|l| match_name(l.trim_start())) } /// A plain or quoted YAML scalar, without a trailing comment. @@ -202,11 +252,11 @@ fn scalar(v: &str) -> &str { return inner; } } - v.split(" #").next().unwrap_or("").trim() + uncomment(v).trim() } fn not_json(text: &str) -> Result<(), String> { - if text.trim_start().starts_with('{') { + if text.strip_prefix('\u{feff}').unwrap_or(text).trim_start().starts_with('{') { return Err("a JSON kubeconfig; not changing it".into()); } Ok(()) @@ -232,7 +282,7 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul return Ok(ours.to_owned()); } // Ours, per list: the item called `name`, its lines from its dash on. - let theirs = tops(ours); + let theirs = tops(ours)?; let mut new: Vec<(&str, Vec)> = Vec::new(); for list in LISTS { let Some(top) = theirs.iter().find(|t| t.key == list) else { continue }; @@ -243,9 +293,14 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul } let nl = newline(existing); let mut out: Vec = Vec::new(); + let mut doc_end: Vec = Vec::new(); let mut seen: Vec<&str> = Vec::new(); let mut current = false; - for top in tops(existing) { + for top in tops(existing)? { + if top.key == "..." { + doc_end.extend(top.lines.iter().map(|l| l.to_string())); + continue; + } if top.key == "current-context" && use_context { out.push(format!("current-context: {name}")); out.extend(top.lines[1..].iter().map(|l| l.to_string())); @@ -259,7 +314,8 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul seen.push(top.key); let (before, items, dash) = items(&top)?; let dash = if items.is_empty() { 0 } else { dash }; - out.push(format!("{}:", top.key)); + let header_val = uncomment(top.lines[0].split_once(':').map_or("", |(_, v)| v)).trim(); + out.push(if header_val.is_empty() { top.lines[0].to_owned() } else { format!("{}:", top.key) }); out.extend(before.iter().map(|l| l.to_string())); let kept: Vec<&Vec<&str>> = items.iter().filter(|i| item_name(i, dash) != Some(name)).collect(); let mut body: Vec = kept.iter().flat_map(|i| i.iter().map(|l| l.to_string())).collect(); @@ -279,6 +335,7 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul if use_context && !current { out.push(format!("current-context: {name}")); } + out.extend(doc_end); Ok(join(&out, nl)) } @@ -291,7 +348,7 @@ pub fn remove(existing: &str, name: &str) -> Result { } let mut out: Vec = Vec::new(); let mut changed = false; - for top in tops(existing) { + for top in tops(existing)? { if top.key == "current-context" && scalar(top.lines[0].split_once(':').map_or("", |(_, v)| v)) == name { out.push("current-context: \"\"".into()); out.extend(top.lines[1..].iter().map(|l| l.to_string())); @@ -383,7 +440,7 @@ users: "; fn names(text: &str, list: &str) -> Vec { - let tops = tops(text); + let tops = tops(text).unwrap(); let top = tops.iter().find(|t| t.key == list).unwrap(); let (_, items, dash) = items(top).unwrap(); items.iter().map(|i| item_name(i, dash).unwrap().to_owned()).collect() @@ -495,4 +552,26 @@ users: assert_eq!(std::fs::read_dir(dir.join(".kube")).unwrap().count(), 2); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn handles_bare_dashes_document_markers_and_comments() { + let ours = from_k3s(K3S, "kiri", 6445); + let bare_dash = "apiVersion: v1\nclusters:\n-\n cluster:\n server: https://127.0.0.1:6443\n name: kiri\n-\n cluster:\n server: https://prod\n name: prod\ncontexts:\n-\n context:\n cluster: kiri\n user: kiri\n name: kiri\n-\n context:\n cluster: prod\n user: prod\n name: prod\ncurrent-context: prod\nkind: Config\nusers:\n-\n name: kiri\n user: {}\n-\n name: prod\n user: {}\n"; + let merged = merge(bare_dash, &ours, "kiri", false).unwrap(); + assert_eq!(merged.matches("name: kiri").count(), 3); + assert!(merged.contains("https://127.0.0.1:6445")); + let removed = remove(&merged, "kiri").unwrap(); + assert!(!removed.contains("name: kiri")); + assert_eq!(removed.matches("name: prod").count(), 3); + + let markers = "\u{feff}---\napiVersion: v1\nclusters:\t# managed\n- cluster:\n server: https://x\n name: prod\ncontexts:# ctxs\n- context:\n cluster: prod\n user: prod\n name: prod\nkind: Config\n...\n"; + let merged_doc = merge(markers, &ours, "kiri", true).unwrap(); + assert!(merged_doc.trim_end().ends_with("\n..."), "{merged_doc:?}"); + assert!(merged_doc.contains("clusters:\t# managed\n")); + assert!(merged_doc.contains("contexts:# ctxs\n")); + assert!(merged_doc.contains("users:\n- name: kiri\n")); + assert!(merged_doc.contains("current-context: kiri\n")); + + assert!(merge("apiVersion: v1\nclusters: []\n---\napiVersion: v1\n", &ours, "kiri", false).is_err()); + } } From cc54667113ce7187c5f06bec7bd5c3d73fa466f9 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 134/157] Engine: read a daemon.json that starts with a BOM and refuse non-integer ulimits (#966) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/daemon/daemon_json.rs | 31 ++++++++++++++++++++++++--- crates/kiri/src/daemon/hostopts.rs | 24 ++++++++++++++++----- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/crates/kiri/src/daemon/daemon_json.rs b/crates/kiri/src/daemon/daemon_json.rs index 9c73b0725..12f1c825e 100644 --- a/crates/kiri/src/daemon/daemon_json.rs +++ b/crates/kiri/src/daemon/daemon_json.rs @@ -125,10 +125,16 @@ fn parse(bytes: &[u8]) -> (RegistryConfig, Vec) { (config, problems) } +/// `bytes` past a leading UTF-8 byte order mark, which dockerd skips when it +/// reads daemon.json (Windows PowerShell and older Notepad write one). +fn without_bom(bytes: &[u8]) -> &[u8] { + bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes) +} + /// [`parse`], and every mirror the file lists, the unused ones included. fn parse_all(bytes: &[u8]) -> (RegistryConfig, Vec, Vec) { let mut problems = Problems::default(); - let v: Value = match serde_json::from_slice(bytes) { + let v: Value = match serde_json::from_slice(without_bom(bytes)) { Ok(v @ Value::Object(_)) => v, Ok(_) => return (RegistryConfig::default(), vec!["daemon.json is not a JSON object".into()], Vec::new()), Err(e) => return (RegistryConfig::default(), vec![format!("daemon.json is not valid JSON: {e}")], Vec::new()), @@ -325,8 +331,8 @@ fn set_with(body: &Value, path: &std::path::Path, current: impl Fn() -> Arc Result<(), String> { let existing_mode = std::fs::metadata(path).ok().map(|m| mode_of(&m)); let mut file = match read_limited(path) { - Ok(b) if b.iter().all(u8::is_ascii_whitespace) => Map::new(), - Ok(b) => match serde_json::from_slice::(&b) { + Ok(b) if without_bom(&b).iter().all(u8::is_ascii_whitespace) => Map::new(), + Ok(b) => match serde_json::from_slice::(without_bom(&b)) { Ok(Value::Object(m)) => m, _ => return Err(format!("{} is not a JSON object; fix it or remove it, then save again", path.display())), }, @@ -636,4 +642,23 @@ mod tests { let mirrors = normalize(&json!(["mirror.example.com", "https://mirror.example.com/", "http://mirror.lan:5000"]), MIRRORS, 8, |s| Mirror::parse(s).map(|m| m.as_url())).unwrap(); assert_eq!(mirrors, ["https://mirror.example.com", "http://mirror.lan:5000"]); } + + #[test] + fn a_file_with_a_utf8_bom_is_read_and_saved() { + let (c, problems) = parse(b"\xEF\xBB\xBF{\"insecure-registries\": [\"registry.lan:5000\"], \"registry-mirrors\": [\"https://mirror.example.com\"]}"); + assert!(problems.is_empty(), "{problems:?}"); + assert!(c.is_insecure("registry.lan:5000")); + assert_eq!(c.mirrors.iter().map(Mirror::as_url).collect::>(), ["https://mirror.example.com"]); + + let d = scratch("bom"); + let f = d.join("daemon.json"); + std::fs::write(&f, b"\xEF\xBB\xBF{\"debug\": true}").unwrap(); + save_at(&f, &json!({INSECURE: ["registry.lan:5000"]})).unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); + assert_eq!(saved["debug"], json!(true)); + assert_eq!(saved[INSECURE], json!(["registry.lan:5000"])); + std::fs::write(&f, b"\xEF\xBB\xBF\n").unwrap(); + save_at(&f, &json!({INSECURE: ["registry.lan:5000"]})).unwrap(); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/daemon/hostopts.rs b/crates/kiri/src/daemon/hostopts.rs index d102cdbb5..764f9bc48 100644 --- a/crates/kiri/src/daemon/hostopts.rs +++ b/crates/kiri/src/daemon/hostopts.rs @@ -125,12 +125,15 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> for u in opts["Ulimits"].as_array().into_iter().flatten() { let name = u["Name"].as_str().unwrap_or(""); let res = RLIMITS.iter().find(|(n, _)| *n == name).map(|(_, r)| *r).ok_or_else(|| format!("invalid ulimit type: {name}"))?; - let value = |k: &str| match u[k].as_i64() { - Some(v) if v < 0 => UNLIMITED, - Some(v) => v as u64, - None => u[k].as_u64().unwrap_or(0), + // Docker decodes Soft and Hard as int64: a missing one is 0, and a + // string or fraction is refused rather than read as 0. + let value = |k: &str| match (&u[k], u[k].as_i64()) { + (_, Some(v)) if v < 0 => Ok(UNLIMITED), + (_, Some(v)) => Ok(v as u64), + (Value::Null, None) => Ok(0), + (v, None) => v.as_u64().ok_or_else(|| format!("invalid ulimit {name} {k}: {v} is not an integer")), }; - let (soft, hard) = (value("Soft"), value("Hard")); + let (soft, hard) = (value("Soft")?, value("Hard")?); if soft > hard { return Err(format!("ulimit soft limit must be less than or equal to hard limit: {} > {}", u["Soft"], u["Hard"])); } @@ -429,4 +432,15 @@ mod tests { assert!(guest_lines(&from_host(&json!({"CgroupnsMode": 123})), false).is_err()); assert!(guest_lines(&from_host(&json!({"CgroupnsMode": true})), false).is_err()); } + + #[test] + fn a_ulimit_that_is_not_an_integer_is_refused() { + let opts = json!({"Ulimits": [{"Name": "nofile", "Soft": "65536", "Hard": "65536"}]}); + assert_eq!(guest_lines(&opts, false).unwrap_err(), "invalid ulimit nofile Soft: \"65536\" is not an integer"); + let opts = json!({"Ulimits": [{"Name": "nproc", "Soft": 10, "Hard": 65536.5}]}); + assert_eq!(guest_lines(&opts, false).unwrap_err(), "invalid ulimit nproc Hard: 65536.5 is not an integer"); + // A missing value is Docker's zero, as before. + let opts = json!({"Ulimits": [{"Name": "core", "Hard": 0}]}); + assert_eq!(guest_lines(&opts, false).unwrap(), ["rlimit\t4\t0\t0", "rlimit\t7\t1048576\t1048576"]); + } } From 83fde3f7d0f5d657b07ae68cca09b46b8fcea423 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 135/157] Storage & volumes: pass sockets on a move, undo a partial fresh start, resolve cifs addr= (#967) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/daemon/storage.rs | 29 ++++++++++++++++++++-- crates/kiri/src/daemon/treecopy.rs | 20 +++++++++++++++ crates/kiri/src/daemon/volumes.rs | 40 +++++++++++++++++++++++++++++- 3 files changed, 86 insertions(+), 3 deletions(-) diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index 57220ff32..214182c77 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -277,7 +277,10 @@ pub fn migrate_fresh(parts: &[Part], config: &Path, choice: &Choice, step: &mut chosen::write_marker(&p.from)?; } std::fs::create_dir_all(&p.to)?; - let mut done = Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }; + // Recorded before anything is set aside, so a failure partway + // through this folder is undone along with the ones before it. + placed.push(Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }); + let done = placed.last_mut().expect("just pushed"); for e in std::fs::read_dir(&p.to)? { let name = e?.file_name(); if IGNORED.iter().any(|n| name == *n) || p.skip.iter().any(|n| name == *n) { @@ -288,7 +291,6 @@ pub fn migrate_fresh(parts: &[Part], config: &Path, choice: &Choice, step: &mut done.set_aside.push(name); } chosen::write_marker(&p.to)?; - placed.push(done); } chosen::write_at(config, choice) })(); @@ -1123,6 +1125,29 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Starting fresh in a folder that holds earlier Kiri data sets that data + /// aside; when setting one entry aside fails, the ones already set aside + /// come back. + #[test] + fn start_fresh_failing_partway_brings_back_what_it_set_aside() { + let d = scratch("fresh-partial"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + data(&target); + // In the order migrate_fresh will meet them. + let names: Vec<_> = std::fs::read_dir(&target).unwrap().map(|e| e.unwrap().file_name()).collect(); + let last = names.last().unwrap(); + // What an interrupted earlier move left set aside under that name. + std::fs::create_dir_all(target.join(REPLACED).join(last).join("left")).unwrap(); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + assert!(migrate_fresh(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).is_err()); + for n in &names { + assert!(target.join(n).exists(), "{n:?} not brought back"); + } + assert!(!config.exists(), "nothing committed"); + let _ = std::fs::remove_dir_all(&d); + } + /// A broken symlink or regular file at the target path is refused. #[test] fn non_directory_and_broken_symlink_targets_are_refused() { diff --git a/crates/kiri/src/daemon/treecopy.rs b/crates/kiri/src/daemon/treecopy.rs index de2078292..3681a3d76 100644 --- a/crates/kiri/src/daemon/treecopy.rs +++ b/crates/kiri/src/daemon/treecopy.rs @@ -306,6 +306,10 @@ pub fn verify_tree(src: &Path, dst: &Path, skip: &[&str], progress: &mut Progres } let (s, d) = (entry.path(), dst.join(&name)); let m = fs::symlink_metadata(&s)?; + if m.file_type().is_socket() { + // `copy_tree` leaves sockets out. + continue; + } let differs = |what: &str| io::Error::other(format!("the copy of {} {what}", s.display())); let got = fs::symlink_metadata(&d).map_err(|_| differs("is missing"))?; if m.is_dir() { @@ -547,6 +551,22 @@ mod tests { let _ = fs::remove_dir_all(&d); } + #[test] + fn a_socket_is_left_out_of_the_copy_and_its_check() { + let d = scratch("socket"); + let src = d.join("src"); + fs::create_dir_all(src.join("run")).unwrap(); + fs::write(src.join("images.json"), b"[]").unwrap(); + let _listening = std::os::unix::net::UnixListener::bind(src.join("run/app.sock")).unwrap(); + let dst = d.join("dst"); + copy_tree(&src, &dst, &[], &mut none).unwrap(); + assert!(fs::symlink_metadata(dst.join("run/app.sock")).is_err()); + verify_tree(&src, &dst, &[], &mut none).unwrap(); + fs::remove_file(dst.join("images.json")).unwrap(); + assert!(verify_tree(&src, &dst, &[], &mut none).unwrap_err().to_string().contains("missing")); + let _ = fs::remove_dir_all(&d); + } + fn sha256_of(b: &[u8]) -> String { use sha2::Digest as _; sha2::Sha256::digest(b).iter().map(|x| format!("{x:02x}")).collect() diff --git a/crates/kiri/src/daemon/volumes.rs b/crates/kiri/src/daemon/volumes.rs index 4ddf78f01..7ccad2097 100644 --- a/crates/kiri/src/daemon/volumes.rs +++ b/crates/kiri/src/daemon/volumes.rs @@ -82,6 +82,10 @@ impl Volumes { if let Some(v) = self.get(name) { return Ok(v.clone()); } + // Docker's local driver refuses a new one-character name. + if name.len() == 1 { + return Err("volume name is too short, names should be at least two alphanumeric characters".into()); + } let v = Volume { name: name.to_owned(), created_ns: SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0), @@ -209,7 +213,9 @@ pub fn guest_mount_fields(options: &BTreeMap, host_path: impl Fn } else { device }; - if kind.starts_with("nfs") { + // Docker resolves `addr=` for nfs and cifs alike; the kernel takes only + // an address there. + if kind.starts_with("nfs") || kind == "cifs" { data = data .split(',') .map(|w| match w.strip_prefix("addr=") { @@ -288,4 +294,36 @@ mod tests { "\tcifs\t//10.0.0.9/share\t0\tusername=u,password=p" ); } + + #[test] + fn a_cifs_addr_is_resolved_like_an_nfs_one() { + let opts = |v: serde_json::Value| local_options(&v).unwrap(); + let dns = |h: &str| (h == "nas.local").then(|| "10.0.0.9".to_owned()); + assert_eq!( + guest_mount_fields(&opts(json!({"type": "cifs", "device": "//nas.local/share", "o": "addr=nas.local,username=u,password=p"})), str::to_owned, dns), + "\tcifs\t//10.0.0.9/share\t0\taddr=10.0.0.9,username=u,password=p" + ); + assert_eq!( + guest_mount_fields(&opts(json!({"type": "cifs", "device": "//10.0.0.9/share", "o": "addr=gone,username=u"})), str::to_owned, dns), + "\tcifs\t//10.0.0.9/share\t0\taddr=gone,username=u" + ); + } + + #[test] + fn a_new_one_character_name_is_refused_as_docker_does() { + let d = std::env::temp_dir().join(format!("kiri-volumes-short-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let mut v = Volumes::load(&d).unwrap(); + assert_eq!(v.ensure("a", json!({}), false).unwrap_err(), "volume name is too short, names should be at least two alphanumeric characters"); + assert!(v.get("a").is_none()); + v.ensure("ab", json!({}), false).unwrap(); + // One made before this rule keeps working. + let file = d.join("volumes.json"); + let saved = std::fs::read_to_string(&file).unwrap().replace("\"ab\"", "\"a\""); + std::fs::write(&file, saved).unwrap(); + let mut v = Volumes::load(&d).unwrap(); + assert_eq!(v.ensure("a", json!({}), false).unwrap().name, "a"); + let _ = std::fs::remove_dir_all(&d); + } } From e1701c41b307e011edd1160412d22c0b75850ae2 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 136/157] test: allow shell-defined OLDPWD in clean-env unit tests (#968) Co-authored-by: Hakan K. --- crates/kiri/src/daemon/access.rs | 2 +- crates/kiri/src/hostaccess.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index 035d7cd27..ffcc2329d 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -2398,7 +2398,7 @@ mod tests { assert!(v == "'C'" || v == "C" || v == "\"C\"", "unexpected LC_ALL: {line}"); saw_lc_all = true; } else { - assert!(matches!(k, "PWD" | "SHLVL" | "_"), "unexpected inherited env var in getent: {line}"); + assert!(matches!(k, "PWD" | "OLDPWD" | "SHLVL" | "_"), "unexpected inherited env var in getent: {line}"); } } assert!(saw_lc_all, "LC_ALL=C not set in {text}"); diff --git a/crates/kiri/src/hostaccess.rs b/crates/kiri/src/hostaccess.rs index ef7a58d93..e847d83f8 100644 --- a/crates/kiri/src/hostaccess.rs +++ b/crates/kiri/src/hostaccess.rs @@ -262,7 +262,7 @@ mod tests { assert!(v == "'C'" || v == "C" || v == "\"C\"", "unexpected LC_ALL: {line}"); saw_lc_all = true; } - "PWD" | "SHLVL" | "_" => {} + "PWD" | "OLDPWD" | "SHLVL" | "_" => {} _ => panic!("unexpected inherited env var in usermod: {line}"), } } From f9e23e9b9425eb14e5a4e9dfa14bd52e12e2bf9f Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 137/157] =?UTF-8?q?UI:=20Turkish=20=E2=80=94=20natural=20d?= =?UTF-8?q?eveloper=20terminology=20and=20consistent=20wording=20(#969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Hakan K. --- crates/kiri/src/ui/lang/tr.json | 756 ++++++++++++++++---------------- 1 file changed, 378 insertions(+), 378 deletions(-) diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index 9e4f94498..f85057fdf 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -17,27 +17,27 @@ "+ Uses the Ubuntu you already have: nothing to download": "+ Zaten sahip olduğunuz Ubuntu'yu kullanır: indirme yok", "+{n} more": "+{n} tane daha", ", ": ", ", - "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Kiri ile derleyin. docker build ve docker compose build Kiri'de çalışır, görüntüler de Kiri'de olur. {engine} bunları görmez. İstediğiniz zaman Ayarlar → Derlemeler'den değiştirebilirsiniz.", - "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Docker ile derlemeye devam edin. Hiçbir şey değişmez: docker build şimdi nerede derliyorsa orada derler, görüntüler de {engine} içinde kalır.", - "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "Korunanlar: kapsayıcının kendisi, dosyaları, görüntüsü, portları, birimleri, ağı ve yeniden başlatma ilkesi.", + "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Kiri ile build edin. docker build ve docker compose build Kiri'de çalışır, imajlar da Kiri'de olur. {engine} bunları görmez. İstediğiniz zaman Ayarlar → Build'ler bölümünden değiştirebilirsiniz.", + "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Docker ile build etmeye devam edin. Hiçbir şey değişmez: docker build şu an nerede build ediyorsa orada eder, imajlar da {engine} içinde kalır.", + "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "Korunanlar: konteynerin kendisi, dosyaları, imajı, portları, volume'leri, ağı ve restart politikası.", "docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.": "docker hâlâ şunu kullanıyor: {engine}; bu yüzden terminalde çalıştırdıklarınız burada görünmez. Görüntülerinizi taşıyabilirsiniz.", - "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node, Kubernetes'i Docker içinde çalıştıran bir araç olan kind'ın düğüm görüntüsüdür. kind onu ayrıcalıklı modla ve gereken ayarlarla sizin için başlatır. Tek başına başlatılırsa şu noktada durur: {mount}.", + "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node, Kubernetes'i Docker içinde çalıştıran bir araç olan kind'ın node imajıdır. kind onu ayrıcalıklı modla ve gereken ayarlarla sizin için başlatır. Tek başına başlatılırsa şu noktada durur: {mount}.", "{name} has {list} that aren't in Kiri yet.": "{name}: {list} henüz Kiri'de yok.", "{name} isn't answering on {addr}, so visitors get an error page. Is the app inside it running?": "{name} yanıt vermiyor (adres: {addr}), bu yüzden ziyaretçiler bir hata sayfası görüyor. İçindeki uygulama çalışıyor mu?", "{name} isn't answering, so visitors get an error page. Is the app inside it running?": "{name} yanıt vermiyor, bu yüzden ziyaretçiler bir hata sayfası görüyor. İçindeki uygulama çalışıyor mu?", - "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "Bu portlardan birini yayınlayan bir kapsayıcı onu alır; o porttaki adlar kapsayıcı bırakana kadar duraklar.", + "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "Bu portlardan birini yayınlayan bir konteyner onu alır; o porttaki adlar konteyner bırakana kadar duraklar.", "A couple more steps: set them up, or skip.": "Birkaç adım daha: bunları ayarlayın veya atlayın.", "A deployment (its ReplicaSet)": "Bir deployment (ReplicaSet'i)", - "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri'deki bir cihaz, ayırana kadar Windows'ta görünmez. Kapsayıcıda: --device /dev/ttyUSB0 (serial), /dev/input (HID) veya /dev/bus/usb (raw).", - "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri'deki bir cihaz, ayırana kadar Mac'te görünmez. Kapsayıcıda: --device /dev/ttyUSB0 (serial), /dev/input (HID) veya /dev/bus/usb (raw).", - "A few things need fixing before Kiri can run containers.": "Kiri'nin kapsayıcı çalıştırabilmesi için birkaç şeyin düzeltilmesi gerekiyor.", + "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri'deki bir cihaz, ayırana kadar Windows'ta görünmez. Konteynerde: --device /dev/ttyUSB0 (serial), /dev/input (HID) veya /dev/bus/usb (raw).", + "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri'deki bir cihaz, ayırana kadar Mac'te görünmez. Konteynerde: --device /dev/ttyUSB0 (serial), /dev/input (HID) veya /dev/bus/usb (raw).", + "A few things need fixing before Kiri can run containers.": "Kiri'nin konteyner çalıştırabilmesi için birkaç şeyin düzeltilmesi gerekiyor.", "A kiri command": "Bir kiri komutu", "A kiri command crashed": "Bir kiri komutu çöktü", "A proxy on this Mac is reached as {host}.": "Bu Mac'teki bir proxy'ye şu adresle erişilir: {host}.", "A service sends traffic to this pod": "Bir servis bu pod'a trafik gönderiyor", - "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "Tek kapsayıcıda tek düğümlü bir küme (k3s); kubectl'in {context} bağlamı için. Kapalı konuma getirmek onu durdurur ve durumunu korur.", - "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "Tek kapsayıcıda tek düğümlü bir küme (k3s). Yaklaşık 20 sn sürer; k3s indirildiği için ilk seferde daha uzun sürer.", - "A small, fast container runtime.": "Küçük, hızlı bir kapsayıcı çalışma zamanı.", + "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "Tek konteynerde tek node'lu bir cluster (k3s); kubectl'in {context} context'i için. Kapalı konuma getirmek onu durdurur ve durumunu korur.", + "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "Tek konteynerde tek node'lu bir cluster (k3s). Yaklaşık 20 sn sürer; k3s indirildiği için ilk seferde daha uzun sürer.", + "A small, fast container runtime.": "Küçük, hızlı bir konteyner runtime'ı.", "A tiny Linux made only for Kiri, built from Alpine. It stays out of sight and leaves with Kiri.": "Yalnızca Kiri için yapılmış, Alpine tabanlı minik bir Linux. Gözden uzak durur ve Kiri ile birlikte kaldırılır.", "API on {addr}": "API adresi: {addr}", "API server": "API sunucusu", @@ -47,16 +47,16 @@ "About": "Hakkında", "Accent": "Vurgu rengi", "Accept the SQL Server licence": "SQL Server lisansını kabul et", - "Access token": "Erişim belirteci", - "Access token or password": "Erişim belirteci veya parola", + "Access token": "Erişim token'ı", + "Access token or password": "Erişim token'ı veya parola", "Action {op}": "İşlem: {op}", "Actions": "İşlemler", "Actual Size": "Gerçek Boyut", "Add": "Ekle", "Add it to WSL": "WSL'ye ekle", "Add port": "Port ekle", - "Added by this build": "Bu derlemeyle eklenen", - "Added in this image": "Bu görüntüde eklenen", + "Added by this build": "Bu build ile eklenen", + "Added in this image": "Bu imajda eklenen", "Additional certificate names": "Ek sertifika adları", "Administrator approval": "Yönetici onayı", "After the restart": "Yeniden başlattıktan sonra", @@ -71,10 +71,10 @@ "Allow an empty password": "Boş parolaya izin ver", "Already there": "Zaten var", "Always send crash reports": "Çökme raporlarını her zaman gönder", - "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR parola değil belirteç ister: kullanıcı adı {user}, belirteç ise şu komuttan gelir: {cmd}. 12 saat geçerlidir.", + "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR parola değil token ister: kullanıcı adı {user}, token ise şu komuttan gelir: {cmd}. 12 saat geçerlidir.", "Anchore, open source": "Anchore, açık kaynak", - "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "O zamandan beri ({use}) {build} için başka bir derleyici seçildi. Kiri'de derlemek için Kiri'yi yeniden seçin.", - "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "127.0.0.1:53 başka bir programda, bu yüzden Kiri .kiri.local için yanıt veremiyor; kapsayıcılar .kiri.localhost adresinde kalır", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "O zamandan beri ({use}) {build} için başka bir builder seçildi. Kiri'de build etmek için Kiri'yi yeniden seçin.", + "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "127.0.0.1:53 başka bir programda, bu yüzden Kiri .kiri.local için yanıt veremiyor; konteynerler .kiri.localhost adresinde kalır", "Answers on /run/kiri/docker.sock": "/run/kiri/docker.sock üzerinden yanıt verir", "Anyone who can reach the port signs in as root.": "Porta erişebilen herkes root olarak oturum açar.", "Anyone with this link can open it while Kiri is running.": "Bu bağlantıya sahip olan herkes, Kiri çalıştığı sürece onu açabilir.", @@ -93,12 +93,12 @@ "Back (Esc)": "Geri (Esc)", "Back to Share": "Paylaş'a dön", "Back to editing": "Düzenlemeye dön", - "Base image": "Temel görüntü", + "Base image": "Temel imaj", "Beta": "Beta", "Bigger": "Daha büyük", "Blue": "Mavi", "Bring all my {engine} images to {app}": "Tüm {engine} görüntülerimi şuraya taşı: {app}", - "Bring images, volumes and containers over to Kiri.": "Görüntüleri, birimleri ve kapsayıcıları Kiri'ye taşıyın.", + "Bring images, volumes and containers over to Kiri.": "Görüntüleri, volume'leri ve konteynerleri Kiri'ye taşıyın.", "Bring your {name} things to Kiri": "{name} öğelerinizi Kiri'ye taşıyın", "Bringing your images over from {engine}: {done} of {total}.": "Görüntüleriniz taşınıyor ({engine}): {done} / {total}.", "Brought {n} item over from {engine}.": "{engine} kaynağından {n} öğe taşındı.", @@ -106,19 +106,19 @@ "Brought {n} items over from {engine}.": "{engine} kaynağından {n} öğe taşındı.", "Brought {n} items over from {engine}; {failed} failed (Settings → Import says why).": "{engine} kaynağından {n} öğe taşındı; {failed} öğe başarısız oldu (nedeni Ayarlar → İçe aktar'da).", "Browsers see a short Kiri Cloud notice page first.": "Tarayıcılar önce kısa bir Kiri Cloud bildirim sayfası görür.", - "Build cache cleared": "Derleme önbelleği temizlendi", - "Build cache cleared: freed {size}": "Derleme önbelleği temizlendi: {size} boşaltıldı", - "Build context": "Derleme bağlamı", - "Build record": "Derleme kaydı", - "Build with": "Derleyici", - "Build with Kiri": "Kiri ile derle", - "Build with Kiri.": "Kiri ile derle.", + "Build cache cleared": "Build önbelleği temizlendi", + "Build cache cleared: freed {size}": "Build önbelleği temizlendi: {size} boşaltıldı", + "Build context": "Build context'i", + "Build record": "Build kaydı", + "Build with": "Builder", + "Build with Kiri": "Kiri ile build et", + "Build with Kiri.": "Kiri ile build et.", "BuildKit starts if it's asleep.": "BuildKit uykudaysa başlar.", "BuildKit {size}": "BuildKit {size}", - "BuildKit {size} and its build cache": "BuildKit {size} ve derleme önbelleği", - "Building": "Derleniyor", - "Builds": "Derlemeler", - "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build ile çalıştırdığınız derlemeler, her adımın süresi, önbelleği ve çıktısıyla burada görünür.", + "BuildKit {size} and its build cache": "BuildKit {size} ve build önbelleği", + "Building": "Build ediliyor", + "Builds": "Build'ler", + "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build ile çalıştırdığınız build'ler, her adımın süresi, önbelleği ve çıktısıyla burada görünür.", "Built from source": "Kaynaktan derlendi", "Bus {bus} · Device {dev}": "Veri yolu {bus} · Aygıt {dev}", "By name, no ports.": "Adla, port olmadan.", @@ -140,14 +140,14 @@ "Cancelled": "İptal edildi", "Cancelled. Nothing was added; layers that finished are kept for the next pull.": "İptal edildi. Hiçbir şey eklenmedi; tamamlanan katmanlar sonraki çekme için saklanır.", "Change ports": "Portları değiştir", - "Changing it restarts the cluster.": "Bunu değiştirmek kümeyi yeniden başlatır.", + "Changing it restarts the cluster.": "Bunu değiştirmek cluster'ı yeniden başlatır.", "Changing this asks Windows for an administrator's approval, since it adds or removes a DNS rule for {local}.": "Bunu değiştirmek Windows'tan yönetici onayı ister, çünkü şunun için bir DNS kuralı ekler veya kaldırır: {local}.", "Changing this needs admin rights (an administrator password), since it adds or removes {path}.": "Bunu değiştirmek yönetici yetkisi (yönetici parolası) gerektirir, çünkü şunu ekler veya kaldırır: {path}.", "Check for Updates…": "Güncellemeleri Denetle…", "Check for updates automatically": "Güncellemeleri otomatik olarak denetle", "Check now": "Şimdi denetle", "Check the spelling, or paste a full reference like {ref}.": "Yazımı kontrol edin veya {ref} gibi tam bir başvuru yapıştırın.", - "Checked once the engine runs": "Motor çalışınca denetlenir", + "Checked once the engine runs": "Engine çalışınca denetlenir", "Checked once your account can use Kiri": "Hesabınız Kiri'yi kullanabildiğinde denetlenir", "Checking the code with AWS…": "Kod AWS ile doğrulanıyor…", "Checking your plan…": "Planınız denetleniyor…", @@ -157,7 +157,7 @@ "Choose what to bring…": "Taşınacakları seçin…", "Choose your language": "Dilinizi seçin", "Clear": "Temizle", - "Clear build cache": "Derleme önbelleğini temizle", + "Clear build cache": "Build önbelleğini temizle", "Clear the selection": "Seçimi temizle", "Clear the selection (Esc)": "Seçimi temizle (Esc)", "Clear {n} failed": "Başarısız {n} öğeyi temizle", @@ -170,28 +170,28 @@ "Close tab": "Sekmeyi kapat", "Close this scan": "Bu taramayı kapat", "Close to your plan's speed limit": "Planınızın hız sınırına yakın", - "Cluster IP": "Küme IP'si", + "Cluster IP": "Cluster IP'si", "Collapse all": "Tümünü daralt", "Command": "Komut", - "Command to run in the container": "Kapsayıcıda çalıştırılacak komut", + "Command to run in the container": "Konteynerde çalıştırılacak komut", "Completed": "Tamamlandı", "Compose project {project} made it: {cmd} puts back what the compose file says, so change it there too.": "Bunu {project} Compose projesi oluşturdu: {cmd} compose dosyasındakini geri getirir, bu yüzden orada da değiştirin.", "Compose services answer at {addr}.": "Compose servisleri şu adreste yanıt verir: {addr}.", "Connect Windows to it": "Windows'u buna bağla", "Connecting…": "Bağlanıyor…", "Connection lost.": "Bağlantı kesildi.", - "Container": "Kapsayıcı", - "Container files are not on Windows' disk: use Save to Downloads": "Kapsayıcı dosyaları Windows diskinde değil: İndirilenler'e kaydet'i kullanın", - "Container list": "Kapsayıcı listesi", - "Container port {q}{port}{q} is not a port number (1–65535).": "Kapsayıcı portu {q}{port}{q} bir port numarası değil (1–65535).", - "Container traffic leaves through WSL's network.": "Kapsayıcı trafiği WSL'nin ağı üzerinden çıkar.", - "Container, Kubernetes and diagnostics logs.": "Kapsayıcı, Kubernetes ve tanılama günlükleri.", - "Containers": "Kapsayıcılar", - "Containers answer at .kiri.localhost": "Kapsayıcılar .kiri.localhost adresinde yanıt verir", - "Containers now answer at .kiri.local": "Kapsayıcılar artık .kiri.local adresinde yanıt veriyor", - "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "Kapsayıcılar bu bilgisayarın kendi çekirdeğinde çalışır, bu yüzden USB cihazlarını olduğu gibi görür: gösterilen yolla docker run --device.", - "Containers see it": "Kapsayıcılar görüyor", - "Containers you start with docker run or Compose show up here, with the {context} context.": "docker run veya Compose ile başlattığınız kapsayıcılar {context} bağlamıyla burada görünür.", + "Container": "Konteyner", + "Container files are not on Windows' disk: use Save to Downloads": "Konteyner dosyaları Windows diskinde değil: İndirilenler'e kaydet'i kullanın", + "Container list": "Konteyner listesi", + "Container port {q}{port}{q} is not a port number (1–65535).": "Konteyner portu {q}{port}{q} bir port numarası değil (1–65535).", + "Container traffic leaves through WSL's network.": "Konteyner trafiği WSL'nin ağı üzerinden çıkar.", + "Container, Kubernetes and diagnostics logs.": "Konteyner, Kubernetes ve tanılama logları.", + "Containers": "Konteynerler", + "Containers answer at .kiri.localhost": "Konteynerler .kiri.localhost adresinde yanıt verir", + "Containers now answer at .kiri.local": "Konteynerler artık .kiri.local adresinde yanıt veriyor", + "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "Konteynerler bu bilgisayarın kendi çekirdeğinde çalışır, bu yüzden USB cihazlarını olduğu gibi görür: gösterilen yolla docker run --device.", + "Containers see it": "Konteynerler görüyor", + "Containers you start with docker run or Compose show up here, with the {context} context.": "docker run veya Compose ile başlattığınız konteynerler {context} bağlamıyla burada görünür.", "Continue": "Devam", "Continue with GitHub": "GitHub ile devam et", "Controlled by": "Denetleyen", @@ -201,14 +201,14 @@ "Copy ID": "ID'yi kopyala", "Copy link": "Bağlantıyı kopyala", "Copy {what}": "Kopyala: {what}", - "Could not change container names: {error}": "Kapsayıcı adları değiştirilemedi: {error}", + "Could not change container names: {error}": "Konteyner adları değiştirilemedi: {error}", "Could not change the certificate's trust: {error}": "Sertifikanın güven ayarı değiştirilemedi: {error}", "Could not change the ports: {error}": "Portlar değiştirilemedi: {error}", "Could not open Terminal: {error}": "Terminal açılamadı: {error}", "Could not open a terminal: {error}": "Terminal açılamadı: {error}", "Could not restart WSL: {error}": "WSL yeniden başlatılamadı: {error}", "Could not restart the VM: {error}": "VM yeniden başlatılamadı: {error}", - "Could not restart the engine: {error}": "Motor yeniden başlatılamadı: {error}", + "Could not restart the engine: {error}": "Engine yeniden başlatılamadı: {error}", "Could not save .wslconfig: {error}": ".wslconfig kaydedilemedi: {error}", "Could not save the SBOM: {error}": "SBOM kaydedilemedi: {error}", "Could not save the file: {error}": "Dosya kaydedilemedi: {error}", @@ -217,16 +217,16 @@ "Could not save the setting to {path}": "Ayar şuraya kaydedilemedi: {path}", "Could not save the setting to ~/.kiri/ui.json": "Ayar ~/.kiri/ui.json dosyasına kaydedilemedi", "Could not save: {error}": "Kaydedilemedi: {error}", - "Couldn't change which builder docker build uses: {error}": "docker build'in kullandığı derleyici değiştirilemedi: {error}", + "Couldn't change which builder docker build uses: {error}": "docker build'in kullandığı builder değiştirilemedi: {error}", "Couldn't check for updates: {error}": "Güncellemeler denetlenemedi: {error}", "Couldn't check: {error}": "Denetlenemedi: {error}", - "Couldn't clear the build cache: {error}": "Derleme önbelleği temizlenemedi: {error}", + "Couldn't clear the build cache: {error}": "Build önbelleği temizlenemedi: {error}", "Couldn't copy to the clipboard": "Panoya kopyalanamadı", "Couldn't download it: {error}": "İndirilemedi: {error}", "Couldn't list the tags": "Etiketler listelenemedi", "Couldn't read the USB devices": "USB cihazları okunamadı", - "Couldn't read the build history": "Derleme geçmişi okunamadı", - "Couldn't remove the build: {error}": "Derleme kaldırılamadı: {error}", + "Couldn't read the build history": "Build geçmişi okunamadı", + "Couldn't remove the build: {error}": "Build kaldırılamadı: {error}", "Couldn't save it: {error}": "Kaydedilemedi: {error}", "Couldn't save the report: {error}": "Rapor kaydedilemedi: {error}", "Couldn't send it: {error}": "Gönderilemedi: {error}", @@ -254,9 +254,9 @@ "Database": "Veritabanı", "Debug": "Hata ayıklama", "Delete": "Sil", - "Delete cluster": "Kümeyi sil", + "Delete cluster": "Cluster'ı sil", "Delete pod {name}?": "{name} pod'u silinsin mi?", - "Delete the Kubernetes cluster?": "Kubernetes kümesi silinsin mi?", + "Delete the Kubernetes cluster?": "Kubernetes cluster'ı silinsin mi?", "Delete {what}?": "Silinsin mi: {what}?", "Deleting": "Siliniyor", "Deleting Kubernetes": "Kubernetes siliniyor", @@ -277,11 +277,11 @@ "Dismiss": "Kapat", "Docker Desktop": "Docker Desktop", "Docker Hub can't be reached": "Docker Hub'a ulaşılamıyor", - "Docker Hub has no image called {name}.": "Docker Hub'da şu adda bir görüntü yok: {name}.", - "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub görüntüleri bu aynalardan sırayla çekilir; görüntüye sahip ilk ayna yanıt verir, yoksa Docker Hub’ın kendisi kullanılır. Diğer kayıt defterleri doğrudan çekilir.", + "Docker Hub has no image called {name}.": "Docker Hub'da şu adda bir imaj yok: {name}.", + "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub görüntüleri bu aynalardan sırayla çekilir; imaja sahip ilk ayna yanıt verir, yoksa Docker Hub’ın kendisi kullanılır. Diğer kayıt defterleri doğrudan çekilir.", "Docker tools": "Docker araçları", "Docker tools are ready": "Docker araçları hazır", - "Docker's default engine": "Docker'ın varsayılan motoru", + "Docker's default engine": "Docker'ın varsayılan Engine'i", "Docker's own page signs you in. Check that it shows this code:": "Oturumu Docker'ın kendi sayfası açar. Şu kodu gösterdiğini kontrol edin:", "Docs": "Belgeler", "Domains": "Alan adları", @@ -303,16 +303,16 @@ "Ended: pod deleted": "Bitti: pod silindi", "Ended: pod restarted · share the service to keep a link": "Bitti: pod yeniden başlatıldı · bağlantıyı korumak için servisi paylaşın", "Ended: service deleted": "Bitti: servis silindi", - "Engine": "Motor", - "Engine running": "Motor çalışıyor", - "Engine updated": "Motor güncellendi", + "Engine": "Engine", + "Engine running": "Engine çalışıyor", + "Engine updated": "Engine güncellendi", "Enter the port the app in the pod listens on, 1 to 65535": "Pod'daki uygulamanın dinlediği portu girin (1–65535)", "Enter this code on GitHub": "Bu kodu GitHub'da girin", "Enter your MFA code": "MFA kodunuzu girin", "Environment": "Ortam", "Error": "Hata", "Errors": "Hatalar", - "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "İçindeki her şey silinir: pod'ları, servisleri, birimleri ve diğer kaynakları ile {context} kubectl bağlamı. Sonraki başlatma yeni, boş bir küme oluşturur.", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "İçindeki her şey silinir: pod'ları, servisleri, volume'leri ve diğer kaynakları ile {context} kubectl context'i. Sonraki başlatma yeni, boş bir cluster oluşturur.", "Everything in the window.": "Penceredeki her şey.", "Everything is in Kiri.": "Her şey Kiri'de.", "Exit code": "Çıkış kodu", @@ -322,13 +322,13 @@ "External": "Harici", "Failed": "Başarısız", "Failed ({code})": "Başarısız ({code})", - "Failing": "Başarısız oluyor", + "Failing": "Başarısız", "Feedback": "Geri bildirim", "Files": "Dosyalar", "Find": "Bul", "Find ({keys})": "Bul ({keys})", "Find a path, method or status": "Yol, yöntem veya durum bul", - "Find in logs": "Günlüklerde bul", + "Find in logs": "Loglarda bul", "Find in the terminal": "Terminalde bul", "Finish updating to Kiri {version}": "Kiri {version} güncellemesini tamamla", "Finished": "Bitti", @@ -339,15 +339,15 @@ "Follow {os} (now {lang}), or always use one language.": "{os} ayarını izleyin (şu an {lang}) veya her zaman tek bir dil kullanın.", "Follow {os}, or always use the dark or light theme.": "{os} ayarını izleyin veya her zaman koyu ya da açık temayı kullanın.", "Font": "Yazı tipi", - "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "Bu {host} üzerinde Kubernetes için Kiri'nin kendine ait bir kümesi var. Kenar çubuğunda Kubernetes altındaki anahtardır.", + "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "Bu {host} üzerinde Kubernetes için Kiri'nin kendine ait bir cluster'ı var. Kenar çubuğunda Kubernetes altındaki anahtardır.", "For pulling and pushing images.": "Görüntüleri çekmek ve göndermek için.", "Forward": "İleri", "Found": "Bulunan", "Freed {size}": "{size} boşaltıldı", "Frees {size}": "{size} boşaltır", "From": "Kaynak", - "From its base image": "Temel görüntüsünden", - "From the base image": "Temel görüntüden", + "From its base image": "Temel imajından", + "From the base image": "Temel imajdan", "From ubuntu.com, through Microsoft's WSL list.": "ubuntu.com'dan, Microsoft'un WSL listesi üzerinden.", "Generate": "Oluştur", "Getting a link…": "Bağlantı alınıyor…", @@ -359,17 +359,17 @@ "Give {name} a public https link": "{name} için herkese açık bir https bağlantısı oluştur", "Given back to Windows": "Windows'a geri verildi", "Given back to the Mac": "Mac'e geri verildi", - "Go to Containers": "Kapsayıcılar'a git", + "Go to Containers": "Konteynerler'a git", "Gone from Kiri": "Kiri'den kaldırıldı", "Graphics|process": "Grafik", "Green": "Yeşil", "Grype, the open-source scanner from Anchore": "Grype, Anchore'un açık kaynak tarayıcısı", "HTTP proxy": "HTTP proxy", "HTTPS proxy": "HTTPS proxy", - "Hand it to Kiri's containers": "Kiri'nin kapsayıcılarına ver", + "Hand it to Kiri's containers": "Kiri'nin konteynerlerine ver", "Has a fix": "Düzeltmesi var", "Have": "Mevcut", - "Headless: there's no cluster address to share. Share one of its pods.": "Headless: paylaşılacak bir küme adresi yok. Pod'larından birini paylaşın.", + "Headless: there's no cluster address to share. Share one of its pods.": "Headless: paylaşılacak bir cluster adresi yok. Pod'larından birini paylaşın.", "Health check": "Sağlık denetimi", "Helpers|process": "Yardımcılar", "Hide": "Gizle", @@ -383,17 +383,17 @@ "High": "Yüksek", "Host or network": "Ana makine veya ağ", "How it runs": "Nasıl çalışır", - "How should you reach your containers?": "Kapsayıcılarınıza nasıl erişmek istersiniz?", + "How should you reach your containers?": "Konteynerlerinize nasıl erişmek istersiniz?", "ID": "ID", "IDs, commands and code.": "ID'ler, komutlar ve kod.", - "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "API sunucusunun sertifikasının ayrıca kapsadığı, virgülle ayrılmış IP adresleri veya alan adları; örneğin bu {host} cihazının ağınızdaki adresi. Kaydetmek kümeyi yeniden başlatır.", + "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "API sunucusunun sertifikasının ayrıca kapsadığı, virgülle ayrılmış IP adresleri veya alan adları; örneğin bu {host} cihazının ağınızdaki adresi. Kaydetmek cluster'ı yeniden başlatır.", "If Kiri's useful, a star on GitHub helps others find it.": "Kiri işinize yarıyorsa, GitHub'da bir yıldız başkalarının onu bulmasına yardımcı olur.", "If it's private, run {cmd} first.": "Özelse önce şunu çalıştırın: {cmd}", "If it's private, sign in first:": "Özelse önce oturum açın:", "If it's private, {link} first.": "Özelse önce: {link}.", "If it's private, {link}.": "Özelse: {link}.", - "Image": "Görüntü", - "Image to pull": "Çekilecek görüntü", + "Image": "Imaj", + "Image to pull": "Çekilecek imaj", "Images": "Görüntüler", "Images you pull or build show up here: docker pull alpine, or search above.": "Çektiğiniz veya derlediğiniz görüntüler burada görünür: docker pull alpine ya da yukarıda arayın.", "Import": "İçe aktar", @@ -406,10 +406,10 @@ "Imported {n} items.": "{n} öğe içe aktarıldı.", "Importing…": "İçe aktarılıyor…", "In Kiri": "Kiri'de", - "In a container": "Kapsayıcıda", + "In a container": "Konteynerde", "In a week": "Bir hafta içinde", "In use": "Kullanımda", - "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "Kullanılan: {used}. VM şu anda en fazla {target} kullanabilir ve kapsayıcılar ihtiyaç duydukça büyür.", + "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "Kullanılan: {used}. VM şu anda en fazla {target} kullanabilir ve konteynerler ihtiyaç duydukça büyür.", "In use: {proxy}, except {hosts}.": "Kullanılan: {proxy}, şunlar hariç: {hosts}.", "In use: {proxy}.": "Kullanılan: {proxy}.", "Included": "Dahil", @@ -417,7 +417,7 @@ "Info and up": "Bilgi ve üstü", "Insecure registries": "Güvensiz kayıt defterleri", "Inside Linux": "Linux içinde", - "Install Kiri's engine in it": "Kiri'nin motorunu buna yükle", + "Install Kiri's engine in it": "Kiri'nin Engine'ini buna yükle", "Install WSL": "WSL'yi yükle", "Install usbipd-win": "usbipd-win'i yükle", "Installed": "Yüklendi", @@ -427,34 +427,34 @@ "Installs when you quit Kiri": "Kiri'den çıktığınızda yüklenir", "Interface font": "Arayüz yazı tipi", "Internal steps": "Dahili adımlar", - "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "Linux VM'nin kendisini değiştirmek istiyor; Çalıştır buna izin vermez. {image} görüntüsüne güveniyorsanız şu komutla kendiniz başlatın: {cmd}.", + "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "Linux VM'nin kendisini değiştirmek istiyor; Çalıştır buna izin vermez. {image} imajına güveniyorsanız şu komutla kendiniz başlatın: {cmd}.", "It has no selector, so it picks no pods.": "Seçicisi olmadığı için hiçbir pod seçmez.", "It restarts, so open connections drop.": "Yeniden başlar, bu yüzden açık bağlantılar kopar.", "It stays up while Kiri is running.": "Kiri çalıştığı sürece açık kalır.", "It takes effect when it next starts.": "Bir sonraki başlatmada geçerli olur.", "It works with serial adapters, Zigbee sticks, mice and keyboards; webcams and audio aren't supported yet.": "Seri adaptörler, Zigbee çubukları, fareler ve klavyelerle çalışır; web kameraları ve ses henüz desteklenmiyor.", - "It wrote nothing to its log.": "Günlüğüne hiçbir şey yazmadı.", + "It wrote nothing to its log.": "Loguna hiçbir şey yazmadı.", "It's a network interface inside Linux, not a device file.": "Linux'ta bir ağ arabirimi, aygıt dosyası değil.", - "It's deleted, with its files and unnamed volumes. Named volumes stay.": "Dosyaları ve adsız birimleriyle birlikte silinir. Adlandırılmış birimler kalır.", - "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "Durdurulur ve dosyaları ve adsız birimleriyle birlikte silinir. Adlandırılmış birimler kalır.", + "It's deleted, with its files and unnamed volumes. Named volumes stay.": "Dosyaları ve adsız volume'leriyle birlikte silinir. Adlandırılmış volume'ler kalır.", + "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "Durdurulur ve dosyaları ve adsız volume'leriyle birlikte silinir. Adlandırılmış volume'ler kalır.", "Its API server stalls or stops answering · {free}": "API sunucusu takılıyor veya yanıt vermiyor · {free}", - "Its container is stopped and deleted, with their files. Named volumes stay.": "Kapsayıcısı durdurulur ve dosyalarıyla birlikte silinir. Adlandırılmış birimler kalır.", - "Its containers stop and their files go.": "Kapsayıcıları durur ve dosyaları silinir.", + "Its container is stopped and deleted, with their files. Named volumes stay.": "Konteyneri durdurulur ve dosyalarıyla birlikte silinir. Adlandırılmış volume'ler kalır.", + "Its containers stop and their files go.": "Konteynerleri durur ve dosyaları silinir.", "Its data is deleted for good.": "Verileri kalıcı olarak silinir.", "Its deployment starts a new pod in its place.": "Deployment'ı onun yerine yeni bir pod başlatır.", "Its job may start it again.": "Job'ı onu yeniden başlatabilir.", - "Its last container stopped because {name} wasn't set.": "Son kapsayıcısı durdu, çünkü şu ayarlanmamıştı: {name}.", - "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "Düğümü çalışıyor ama API sunucusu yanıt vermiyor. Meşgul veya belleği yetersiz bir VM buna yol açabilir; Kiri sormaya devam ediyor.", - "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "Düğümü çalışıyor ama API sunucusu yanıt vermiyor: {error}. Meşgul veya belleği yetersiz bir VM buna yol açabilir; Kiri sormaya devam ediyor.", + "Its last container stopped because {name} wasn't set.": "Son konteyneri durdu, çünkü şu ayarlanmamıştı: {name}.", + "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "Node'u çalışıyor ama API sunucusu yanıt vermiyor. Meşgul veya belleği yetersiz bir VM buna yol açabilir; Kiri sormaya devam ediyor.", + "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "Node'u çalışıyor ama API sunucusu yanıt vermiyor: {error}. Meşgul veya belleği yetersiz bir VM buna yol açabilir; Kiri sormaya devam ediyor.", "Its start script stops when {name} isn't set.": "Başlatma betiği şu ayarlanmadığında durur: {name}.", "Its start script stops without it: “{why}”.": "Başlatma betiği bu olmadan durur: “{why}”.", "Its value": "Değeri", - "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "{n} kapsayıcısı durdurulur ve dosyalarıyla birlikte silinir. Adlandırılmış birimler kalır.", + "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "{n} konteyneri durdurulur ve dosyalarıyla birlikte silinir. Adlandırılmış volume'ler kalır.", "Its {owner} starts a new pod in its place.": "Bağlı olduğu {owner} onun yerine yeni bir pod başlatır.", "KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_CPUS veya KIRI_MEMORY_MIB ayarlı ve bunlar buradakilerden önceliklidir.", "Keep": "Koru", - "Keep building with Docker": "Docker ile derlemeye devam et", - "Keep building with Docker.": "Docker ile derlemeye devam et.", + "Keep building with Docker": "Docker ile build'e devam et", + "Keep building with Docker.": "Docker ile build'e devam et.", "Keep typing to search Docker Hub.": "Docker Hub'da aramak için yazmaya devam edin.", "Keep using your PC meanwhile.": "Bu arada PC'nizi kullanmaya devam edin.", "Kept in Credential Manager": "Kimlik Bilgileri Yöneticisi'nde saklanır", @@ -468,21 +468,21 @@ "Kiri Cloud gives it a public https link through a secure tunnel from this {host}. You sign in with GitHub, so every link traces back to a person. Kiri never sees your password.": "Kiri Cloud, bu {host} cihazından güvenli bir tünel üzerinden ona herkese açık bir https bağlantısı verir. GitHub ile oturum açarsınız; böylece her bağlantı bir kişiye dayanır. Kiri parolanızı asla görmez.", "Kiri Setup": "Kiri Kurulumu", "Kiri and this Mac": "Kiri ve bu Mac", - "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri henüz ses ve görüntü aktaramıyor: kapsayıcılar ondan bir şey almaz.", - "Kiri engine installed": "Kiri motoru yüklendi", - "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri görüntüdeki her paketi (işletim sistemi paketleri, dil kitaplıkları ve ikili dosyalar) bulur ve her birini bir güvenlik açığı veritabanıyla karşılaştırır. Henüz tarama yok: ilkini çalıştırın.", + "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri henüz ses ve görüntü aktaramıyor: konteynerler ondan bir şey almaz.", + "Kiri engine installed": "Kiri Engine'i yüklendi", + "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri imajdaki her paketi (işletim sistemi paketleri, dil kitaplıkları ve ikili dosyalar) bulur ve her birini bir güvenlik açığı veritabanıyla karşılaştırır. Henüz tarama yok: ilkini çalıştırın.", "Kiri is not running": "Kiri çalışmıyor", "Kiri is ready": "Kiri hazır", "Kiri is set up.": "Kiri kuruldu.", "Kiri quit unexpectedly last time": "Kiri geçen sefer beklenmedik şekilde kapandı", - "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri, Grype'ı burada, Mac'inizde Kiri deposundaki görüntü üzerinde çalıştırır. Görüntü hiçbir yere yüklenmez.", - "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri, Linux kapsayıcılarını WSL içinde, kendine ait bir Linux'ta çalıştırır. İki seçenek de aynı kapsayıcıları aynı hızda çalıştırır; boyutları ve size sundukları diğer şeyler farklıdır.", - "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri, Linux kapsayıcılarını Windows'ta Docker Desktop olmadan çalıştırır. Bunun için Microsoft'un Linux çalıştırma yolu olan Linux için Windows Alt Sistemi (WSL) gerekir; bu PC'de henüz yok.", + "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri, Grype'ı burada, Mac'inizde Kiri deposundaki imaj üzerinde çalıştırır. Imaj hiçbir yere yüklenmez.", + "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri, Linux konteynerlerini WSL içinde, kendine ait bir Linux'ta çalıştırır. İki seçenek de aynı konteynerleri aynı hızda çalıştırır; boyutları ve size sundukları diğer şeyler farklıdır.", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri, Linux konteynerlerini Windows'ta Docker Desktop olmadan çalıştırır. Bunun için Microsoft'un Linux çalıştırma yolu olan Linux için Windows Alt Sistemi (WSL) gerekir; bu PC'de henüz yok.", "Kiri sets itself up for your Windows account only.": "Kiri yalnızca sizin Windows hesabınız için kurulur.", - "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Kiri, motoru çalışınca derleyicisini kurar; derlemeler o andan itibaren ona gider.", + "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Kiri, Engine'i çalışınca builder'ını kurar; build'ler o andan itibaren ona gider.", "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri, Docker Hub'da docker komutuyla oturum açar, ancak bu komut yüklü değil. Yükleyin ve yeniden deneyin.", "Kiri signs in to GitHub with the GitHub CLI (gh), which isn't installed. Install it, then try again.": "Kiri, GitHub'da GitHub CLI (gh) ile oturum açar, ancak bu yüklü değil. Yükleyin ve yeniden deneyin.", - "Kiri started your container.": "Kiri kapsayıcınızı başlattı.", + "Kiri started your container.": "Kiri konteynerinizi başlattı.", "Kiri started {name} in {time}.": "Kiri başlattı: {name} ({time}).", "Kiri started {name}.": "Kiri başlattı: {name}.", "Kiri uses your AWS profile through the AWS CLI, which isn't installed. Public images still pull.": "Kiri, AWS profilinizi AWS CLI üzerinden kullanır, ancak bu yüklü değil. Herkese açık görüntüler yine de çekilir.", @@ -492,18 +492,18 @@ "Kiri {version} is downloaded": "Kiri {version} indirildi", "Kiri {version} is ready to install": "Kiri {version} yüklenmeye hazır", "Kiri {version} is the newest version": "Kiri {version} en yeni sürüm", - "Kiri's Kubernetes cluster": "Kiri'nin Kubernetes kümesi", - "Kiri's builder": "Kiri'nin derleyicisi", + "Kiri's Kubernetes cluster": "Kiri'nin Kubernetes cluster'ı", + "Kiri's builder": "Kiri'nin builder'ı", "Kiri's certificate is no longer trusted": "Kiri'nin sertifikasına artık güvenilmiyor", - "Kiri's certificate is trusted: containers open over HTTPS": "Kiri'nin sertifikasına güveniliyor: kapsayıcılar HTTPS üzerinden açılır", - "Kiri's containers and engine use {used}, of the {total} this computer has.": "Kiri'nin kapsayıcıları ve motoru, bu bilgisayardaki {total} belleğin {used} kadarını kullanıyor.", - "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "Kiri'nin kapsayıcıları, motoru ve aracısı WSL'nin {total} belleğinin {used} kadarını tutuyor (bunu .wslconfig belirler).", - "Kiri's log": "Kiri'nin günlüğü", - "Kiri's logs": "Kiri'nin günlükleri", + "Kiri's certificate is trusted: containers open over HTTPS": "Kiri'nin sertifikasına güveniliyor: konteynerler HTTPS üzerinden açılır", + "Kiri's containers and engine use {used}, of the {total} this computer has.": "Kiri'nin konteynerleri ve Engine'i, bu bilgisayardaki {total} belleğin {used} kadarını kullanıyor.", + "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "Kiri'nin konteynerleri, Engine'i ve aracısı WSL'nin {total} belleğinin {used} kadarını tutuyor (bunu .wslconfig belirler).", + "Kiri's log": "Kiri'nin log'u", + "Kiri's logs": "Kiri'nin logları", "Kiri's own, {name}, is on, so another copy isn't needed.": "Kiri'nin kendi kopyası ({name}) açık, bu yüzden başka bir kopyaya gerek yok.", "Kiri: {state}": "Kiri: {state}", - "Kiri’s engine": "Kiri’nin motoru", - "Kubernetes cluster": "Kubernetes kümesi", + "Kiri’s engine": "Kiri’nin Engine'i", + "Kubernetes cluster": "Kubernetes cluster'ı", "Kubernetes deleted, with its state": "Kubernetes durumuyla birlikte silindi", "Kubernetes is busy with another change; try again in a moment": "Kubernetes başka bir değişiklikle meşgul; birazdan yeniden deneyin", "Kubernetes is managed in Settings → Kubernetes": "Kubernetes, Ayarlar → Kubernetes'ten yönetilir", @@ -533,7 +533,7 @@ "Layer": "Katman", "Layers": "Katmanlar", "Let it pick a random one": "Rastgele birini seçsin", - "Lets {user} run containers without sudo": "{user} kullanıcısının sudo olmadan kapsayıcı çalıştırmasını sağlar", + "Lets {user} run containers without sudo": "{user} kullanıcısının sudo olmadan konteyner çalıştırmasını sağlar", "Level": "Düzey", "Light": "Açık", "Linux VM": "Linux VM", @@ -551,17 +551,17 @@ "Loading…": "Yükleniyor…", "Local names": "Yerel adlar", "Location": "Konum", - "Log lines for this action": "Bu işlemin günlük satırları", + "Log lines for this action": "Bu işlemin log satırları", "Log out now": "Şimdi oturumu kapat", "Log out to finish": "Bitirmek için oturumu kapatın", - "Log text": "Günlük metni", - "Logs": "Günlükler", - "Logs: {error}": "Günlükler: {error}", + "Log text": "Log metni", + "Logs": "Loglar", + "Logs: {error}": "Loglar: {error}", "Looking for Kubernetes…": "Kubernetes aranıyor…", "Looking for OrbStack and Docker Desktop…": "OrbStack ve Docker Desktop aranıyor…", "Looking for USB devices…": "USB cihazları aranıyor…", "Looking for crash reports…": "Çökme raporları aranıyor…", - "Looking for shells…": "Kabuklar aranıyor…", + "Looking for shells…": "Shell'ler aranıyor…", "Low": "Düşük", "MFA code": "MFA kodu", "Mac": "Mac", @@ -587,9 +587,9 @@ "Mouse": "Fare", "MySQL won't start until you choose how its root account signs in.": "MySQL, root hesabının nasıl oturum açacağını seçene kadar başlamaz.", "Name": "Ad", - "Named volumes from docker volume create or -v name:/path show up here.": "docker volume create veya -v name:/path ile oluşturulan adlandırılmış birimler burada görünür.", + "Named volumes from docker volume create or -v name:/path show up here.": "docker volume create veya -v name:/path ile oluşturulan adlandırılmış volume'ler burada görünür.", "Names answer on {http} and {https}. Pick other ports when another app needs these; links then carry the port, like {url}.": "Adlar {http} ve {https} üzerinde yanıt verir. Başka bir uygulama bunlara ihtiyaç duyarsa başka portlar seçin; bağlantılar o zaman {url} gibi portu içerir.", - "Names, images and status. Not their files, logs or environment.": "Adlar, görüntüler ve durum. Dosyaları, günlükleri veya ortamları değil.", + "Names, images and status. Not their files, logs or environment.": "Adlar, görüntüler ve durum. Dosyaları, logları veya ortamları değil.", "Namespace": "Ad alanı", "Namespace · {up} of {all} running": "Ad alanı · {up} / {all} çalışıyor", "Needs a restart": "Yeniden başlatma gerekiyor", @@ -600,20 +600,20 @@ "Networks": "Ağlar", "Networks you create with docker network create show up here.": "docker network create ile oluşturduğunuz ağlar burada görünür.", "Network|process": "Ağ", - "New containers get {http}, {https} and {no}.": "Yeni kapsayıcılar şunları alır: {http}, {https} ve {no}.", + "New containers get {http}, {https} and {no}.": "Yeni konteynerler şunları alır: {http}, {https} ve {no}.", "New tab": "Yeni sekme", "New tab ({keys})": "Yeni sekme ({keys})", "Next match": "Sonraki eşleşme", "No Linux username is needed now: Kiri runs inside Ubuntu on its own. Ubuntu asks for one only the first time you open it yourself. * Estimate.": "Şimdi Linux kullanıcı adı gerekmez: Kiri, Ubuntu içinde kendi başına çalışır. Ubuntu yalnızca onu ilk kez kendiniz açtığınızda bir kullanıcı adı ister. * Tahmini.", "No USB devices": "USB cihazı yok", - "No build matches.": "Eşleşen derleme yok.", - "No builds yet": "Henüz derleme yok", + "No build matches.": "Eşleşen build yok.", + "No builds yet": "Henüz build yok", "No changes": "Değişiklik yok", - "No containers running": "Çalışan kapsayıcı yok", - "No containers yet": "Henüz kapsayıcı yok", + "No containers running": "Çalışan konteyner yok", + "No containers yet": "Henüz konteyner yok", "No crashes. Kiri keeps a report here if one of its parts ever stops unexpectedly.": "Çökme yok. Parçalarından biri beklenmedik şekilde durursa Kiri burada bir rapor tutar.", "No fix yet": "Henüz düzeltme yok", - "No images yet": "Henüz görüntü yok", + "No images yet": "Henüz imaj yok", "No known vulnerabilities in {n} packages": "{n} pakette bilinen güvenlik açığı yok", "No language matches. Try its English name.": "Eşleşen dil yok. İngilizce adını deneyin.", "No languages match": "Eşleşen dil yok", @@ -634,49 +634,49 @@ "No services": "Servis yok", "No steps here.": "Burada adım yok.", "No visitors in the last 2 minutes": "Son 2 dakikada ziyaretçi yok", - "No volumes yet": "Henüz birim yok", + "No volumes yet": "Henüz volume yok", "No {label}": "{label} yok", - "Node": "Düğüm", + "Node": "Node", "None": "Yok", "None (headless)": "Yok (headless)", "None found": "Hiçbiri bulunamadı", "None match these filters.": "Bu filtrelerle eşleşen yok.", "None: every registry is checked over HTTPS.": "Yok: her kayıt defteri HTTPS üzerinden doğrulanır.", "Not a web port, so it isn't shared": "Web portu değil, bu yüzden paylaşılmaz", - "Not an image name: {reference}": "Görüntü adı değil: {reference}", + "Not an image name: {reference}": "Imaj adı değil: {reference}", "Not answering · visitors get an error": "Yanıt vermiyor · ziyaretçiler hata görüyor", "Not created yet": "Henüz oluşturulmadı", "Not found.": "Bulunamadı.", - "Not in use: no container was made from it": "Kullanılmıyor: ondan hiç kapsayıcı oluşturulmadı", + "Not in use: no container was made from it": "Kullanılmıyor: ondan hiç konteyner oluşturulmadı", "Not now": "Şimdi değil", "Not now: ask again in a week": "Şimdi değil: bir hafta sonra yeniden sor", "Not running": "Çalışmıyor", "Not sent": "Gönderilmedi", - "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "Henüz kurulmadı. İlk derlemenizde oluşturulur; bu sırada BuildKit (yaklaşık 110 MB) bir kez indirilir.", + "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "Henüz kurulmadı. İlk build'inizde oluşturulur; bu sırada BuildKit (yaklaşık 110 MB) bir kez indirilir.", "Not signed in": "Oturum açılmadı", "Not signed in to any registry": "Hiçbir kayıt defterinde oturum açılmadı", "Nothing called “{q}” on Docker Hub": "Docker Hub'da “{q}” adında bir şey yok", "Nothing changes: {build} builds where it does now, and the images stay in {engine}.": "Hiçbir şey değişmez: {build} şimdi nerede derliyorsa orada derler, görüntüler de {engine} içinde kalır.", "Nothing here.": "Burada bir şey yok.", "Nothing is deleted. You can switch back any time from the status bar.": "Hiçbir şey silinmez. Durum çubuğundan istediğiniz zaman geri dönebilirsiniz.", - "Nothing logged yet.": "Henüz günlüğe bir şey yazılmadı.", + "Nothing logged yet.": "Henüz log'a bir şey yazılmadı.", "Nothing matches “{q}” in {tab}.": "{tab} içinde “{q}” ile eşleşen bir şey yok.", "Nothing matches “{q}”.": "“{q}” ile eşleşen bir şey yok.", "Nothing restarts it either: when the pod is deleted or restarts, the link ends.": "Onu yeniden başlatan bir şey de yok: pod silinince veya yeniden başlayınca bağlantı sona erer.", "Nothing shared yet": "Henüz paylaşılan bir şey yok", - "Nothing shared. Press the globe beside a running container to give it a public link.": "Paylaşılan bir şey yok. Çalışan bir kapsayıcıya herkese açık bağlantı vermek için yanındaki küre simgesine basın.", + "Nothing shared. Press the globe beside a running container to give it a public link.": "Paylaşılan bir şey yok. Çalışan bir konteynere herkese açık bağlantı vermek için yanındaki küre simgesine basın.", "Nothing starts it again: no deployment or other controller owns it.": "Onu yeniden başlatan bir şey yok: hiçbir deployment veya başka bir denetleyici ona sahip değil.", "Nothing to download": "İndirilecek bir şey yok", "Nothing to download: it came inside Kiri.": "İndirilecek bir şey yok: Kiri'yle birlikte geldi.", "Nothing to import from: OrbStack and Docker Desktop aren't on this {host}.": "İçe aktarılacak kaynak yok: OrbStack ve Docker Desktop bu {host} üzerinde yok.", - "Nothing to pass to a container yet.": "Henüz bir kapsayıcıya verilecek bir şey yok.", + "Nothing to pass to a container yet.": "Henüz bir konteynere verilecek bir şey yok.", "Nothing to type: it uses the AWS sign-in already on this computer.": "Bir şey yazmanız gerekmez: bu bilgisayardaki mevcut AWS oturumu kullanılır.", "Now": "Şimdi", "OK": "Tamam", "Off": "Kapalı", "Off: Kiri checks only when you click Check now.": "Kapalı: Kiri yalnızca Şimdi denetle'ye tıkladığınızda denetler.", - "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "Kapalı: kapsayıcılar kurulum gerektirmeyen <name>.kiri.localhost adresinde yanıt verir.", - "Off: press Start engine to run containers. It stays off after a restart until you start it.": "Kapalı: kapsayıcı çalıştırmak için Motoru başlat'a basın. Siz başlatana kadar yeniden başlatmadan sonra da kapalı kalır.", + "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "Kapalı: konteynerler kurulum gerektirmeyen <name>.kiri.localhost adresinde yanıt verir.", + "Off: press Start engine to run containers. It stays off after a restart until you start it.": "Kapalı: konteyner çalıştırmak için Engine'i başlat'a basın. Siz başlatana kadar yeniden başlatmadan sonra da kapalı kalır.", "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "Kapalı: API sunucusu ve LoadBalancer servisleri yalnızca bu {host} üzerinde (127.0.0.1) yanıt verir.", "Official": "Resmî", "On": "Açık", @@ -686,8 +686,8 @@ "On {registry} an image is named owner/image, such as {example}. Type one to choose its tag, or paste a full reference.": "{registry} üzerinde bir imajın adı owner/image biçimindedir, örneğin {example}. Etiketini seçmek için bir ad yazın ya da tam bir referans yapıştırın.", "On {targets}": "Hedef: {targets}", "On: Kiri checks each time it opens. It never updates without asking.": "Açık: Kiri her açılışında denetler. Sormadan asla güncelleme yapmaz.", - "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "Açık: kapsayıcılar, yalnızca .kiri.local ve .kiri.localhost adlarına kefil olan Kiri sertifikasıyla https:// üzerinden açılır.", - "On: running containers answer at <name>.kiri.local.": "Açık: çalışan kapsayıcılar <name>.kiri.local adresinde yanıt verir.", + "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "Açık: konteynerler, yalnızca .kiri.local ve .kiri.localhost adlarına kefil olan Kiri sertifikasıyla https:// üzerinden açılır.", + "On: running containers answer at <name>.kiri.local.": "Açık: çalışan konteynerler <name>.kiri.local adresinde yanıt verir.", "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "Açık: API sunucusu ve LoadBalancer servisleri her ağ arabiriminde yanıt verir; böylece ağınızdaki diğer cihazlar onlara erişebilir.", "One more step: log out and back in.": "Bir adım daha: oturumu kapatıp yeniden açın.", "One more step: set it up, or skip.": "Bir adım daha: kurun veya atlayın.", @@ -700,7 +700,7 @@ "Open Pods": "Pod'ları aç", "Open Share": "Paylaş'ı aç", "Open in Terminal": "Terminal'de aç", - "Open logs folder": "Günlük klasörünü aç", + "Open logs folder": "Log klasörünü aç", "Open the page again": "Sayfayı yeniden aç", "Open {addr}": "Aç: {addr}", "Open {name}": "Aç: {name}", @@ -725,8 +725,8 @@ "Pane zoomed": "Bölme büyütüldü", "Part": "Bölüm", "Part of Kiri": "Kiri'nin parçası", - "Part of the cluster itself (kube-system). Not shared.": "Kümenin kendi parçası (kube-system). Paylaşılmaz.", - "Pass to containers": "Kapsayıcılara aktar", + "Part of the cluster itself (kube-system). Not shared.": "Cluster'ın kendi parçası (kube-system). Paylaşılmaz.", + "Pass to containers": "Konteynerlere aktar", "Paste": "Yapıştır", "Paste NAME=value lines, or a .env file, into a name.": "NAME=value satırlarını veya bir .env dosyasını bir ad alanına yapıştırın.", "Paste {n} lines? Each line runs as a command.": "{n} satır yapıştırılsın mı? Her satır bir komut olarak çalışır.", @@ -744,13 +744,13 @@ "Plug one in: a serial adapter, a Zigbee stick, a microcontroller. It shows up here.": "Bir tane takın: seri adaptör, Zigbee çubuğu, mikrodenetleyici. Burada görünür.", "Pod IP": "Pod IP'si", "Pod in {ns}": "Pod, ad alanı: {ns}", - "Pod in {ns} · on {node}": "Pod, ad alanı: {ns} · düğüm: {node}", + "Pod in {ns} · on {node}": "Pod, ad alanı: {ns} · node: {node}", "Pods": "Pod'lar", "Pods you create with kubectl show up here, grouped by namespace.": "kubectl ile oluşturduğunuz pod'lar ad alanına göre gruplanmış olarak burada görünür.", "Port": "Port", - "Port in the container": "Kapsayıcıdaki port", + "Port in the container": "Konteynerdeki port", "Port on your {host}": "{host} cihazınızdaki port", - "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "{host} cihazınızdaki port (localhost) → kapsayıcının içindeki port. Boş bir port seçilmesi için {host} tarafını boş bırakın.", + "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "{host} cihazınızdaki port (localhost) → konteynerin içindeki port. Boş bir port seçilmesi için {host} tarafını boş bırakın.", "Port {port} is already in use on this {host}": "Port {port} bu {host} üzerinde zaten kullanımda", "Port {port}. The link keeps working when pods restart.": "Port {port}. Pod'lar yeniden başlasa da bağlantı çalışmaya devam eder.", "Ports": "Portlar", @@ -761,12 +761,12 @@ "Ports…": "Portlar…", "Postgres won't start without a superuser password.": "Postgres süper kullanıcı parolası olmadan başlamaz.", "Powered by": "Altyapı", - "Press Share on a running container to give it a public https link anyone can open.": "Çalışan bir kapsayıcıya herkesin açabileceği herkese açık bir https bağlantısı vermek için Paylaş'a basın.", + "Press Share on a running container to give it a public https link anyone can open.": "Çalışan bir konteynere herkesin açabileceği herkese açık bir https bağlantısı vermek için Paylaş'a basın.", "Press to see it, or disconnect it.": "Görmek veya bağlantıyı kesmek için basın.", "Press to try again": "Yeniden denemek için basın", "Previous match": "Önceki eşleşme", "Previous run": "Önceki çalıştırma", - "Printed once in the container's log.": "Kapsayıcının günlüğüne bir kez yazılır.", + "Printed once in the container's log.": "Konteynerin loguna bir kez yazılır.", "Private images won't pull until you sign in again.": "Yeniden oturum açana kadar özel görüntüler çekilemez.", "Processes": "İşlemler", "Progress": "İlerleme", @@ -781,11 +781,11 @@ "Publish the port {name} listens on, and give it a public https link": "{name} tarafından dinlenen portu yayımla ve ona herkese açık bir https bağlantısı ver", "Pull": "Çek", "Pull again": "Yeniden çek", - "Pull an image": "Görüntü çek", - "Pull an image ({key})": "Görüntü çek ({key})", + "Pull an image": "Imaj çek", + "Pull an image ({key})": "Imaj çek ({key})", "Pull exactly this": "Tam olarak bunu çek", "Pull from": "Çekilecek kaynak", - "Pull image": "Görüntüyü çek", + "Pull image": "Imajı çek", "Pull {tag}": "Çek: {tag}", "Pulled": "Çekildi", "Pulled {name}": "Çekildi: {name}", @@ -803,14 +803,14 @@ "Reachable at {addr}": "Erişim adresi: {addr}", "Reachable at {url}": "Erişim adresi: {url}", "Read more on runkiri.com ↗": "runkiri.com'da daha fazlasını okuyun ↗", - "Reading build history…": "Derleme geçmişi okunuyor…", - "Reading the image…": "Görüntü okunuyor…", - "Reading the log…": "Günlük okunuyor…", + "Reading build history…": "Build geçmişi okunuyor…", + "Reading the image…": "Imaj okunuyor…", + "Reading the log…": "Log okunuyor…", "Reading the scans…": "Taramalar okunuyor…", "Reading what {name} has…": "{name} içeriği okunuyor…", "Ready": "Hazır", "Recent crashes": "Son çökmeler", - "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Bir sorun olduğunda kullanmak için son günlükler, çökme raporları ve sürümler, hassas bilgileri ayıklanmış tek bir dosyada.", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Bir sorun olduğunda kullanmak için son loglar, çökme raporları ve sürümler, hassas bilgileri ayıklanmış tek bir dosyada.", "Recent pulls": "Son çekmeler", "Recommended": "Önerilen", "Reconnecting": "Yeniden bağlanıyor", @@ -825,28 +825,28 @@ "Registry settings saved": "Kayıt defteri ayarları kaydedildi", "Reload": "Yenile", "Remove": "Kaldır", - "Remove Kubernetes' container?": "Kubernetes'in kapsayıcısı kaldırılsın mı?", + "Remove Kubernetes' container?": "Kubernetes'in konteyneri kaldırılsın mı?", "Remove all": "Tümünü kaldır", "Remove both": "İkisini de kaldır", "Remove network {name}?": "{name} ağı kaldırılsın mı?", "Remove project": "Projeyi kaldır", - "Remove this build from the history?": "Bu derleme geçmişten kaldırılsın mı?", + "Remove this build from the history?": "Bu build geçmişten kaldırılsın mı?", "Remove this port": "Bu portu kaldır", - "Remove volume {name}?": "{name} birimi kaldırılsın mı?", + "Remove volume {name}?": "{name} volume'ü kaldırılsın mı?", "Remove {name} and {image}?": "{name} ve {image} kaldırılsın mı?", "Remove {name}?": "{name} kaldırılsın mı?", - "Remove {n} containers and {image}?": "{n} kapsayıcı ve {image} kaldırılsın mı?", - "Remove {n} untagged": "Etiketsiz {n} görüntüyü kaldır", + "Remove {n} containers and {image}?": "{n} konteyner ve {image} kaldırılsın mı?", + "Remove {n} untagged": "Etiketsiz {n} imajı kaldır", "Removed {gone} of {n} {what}": "{n} {what} öğesinden {gone} tanesi kaldırıldı", "Removed {name}": "{name} kaldırıldı", "Removed {n} {what}": "{n} {what} kaldırıldı", - "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "{cmd} komutunun yaptığı gibi kümenin kapsayıcısını, içindeki her şeyi ({volume} birimi) ve {context} kubectl bağlamını kaldırır.", - "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "Hatayla çıkan {n} kapsayıcıyı dosyalarıyla birlikte kaldırır. Adlandırılmış birimler kalır.", - "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "Hatayla çıkan {n} kapsayıcıyı dosyalarıyla birlikte kaldırır. Adlandırılmış birimler kalır.", - "Removes the {n} failed build from the history.": "Başarısız {n} derlemeyi geçmişten kaldırır.", - "Removes the {n} failed builds from the history.": "Başarısız {n} derlemeyi geçmişten kaldırır.", - "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "Yeniden derlemelerin geride bıraktığı etiketsiz {n} görüntüyü kaldırır. Hiçbir şey onları kullanmıyor. {size} boşaltır.", - "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "Yeniden derlemelerin geride bıraktığı etiketsiz {n} görüntüyü kaldırır. Hiçbir şey onları kullanmıyor. {size} boşaltır.", + "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "{cmd} komutunun yaptığı gibi cluster'ın konteynerini, içindeki her şeyi ({volume} volume'ü) ve {context} kubectl bağlamını kaldırır.", + "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "Hatayla çıkan {n} konteyneri dosyalarıyla birlikte kaldırır. Adlandırılmış volume'ler kalır.", + "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "Hatayla çıkan {n} konteyneri dosyalarıyla birlikte kaldırır. Adlandırılmış volume'ler kalır.", + "Removes the {n} failed build from the history.": "Başarısız {n} build'i geçmişten kaldırır.", + "Removes the {n} failed builds from the history.": "Başarısız {n} build'i geçmişten kaldırır.", + "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "Yeniden build'lerin geride bıraktığı etiketsiz {n} imajı kaldırır. Hiçbir şey onları kullanmıyor. {size} boşaltır.", + "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "Yeniden build'lerin geride bıraktığı etiketsiz {n} imajı kaldırır. Hiçbir şey onları kullanmıyor. {size} boşaltır.", "Removing {gone} of {n}…": "Kaldırılıyor: {gone} / {n}…", "Report ID": "Rapor kimliği", "Report sent": "Rapor gönderildi", @@ -854,16 +854,16 @@ "Requests to {name}": "İstekler: {name}", "Resources": "Kaynaklar", "Restart": "Yeniden başlat", - "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "Bitirmek için Kiri'yi yeniden başlatın. Çalışan kapsayıcılar durur; yeniden başlatma ilkesi olanlar yeniden başlar.", + "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "Bitirmek için Kiri'yi yeniden başlatın. Çalışan konteynerler durur; restart politikası olanlar yeniden başlar.", "Restart VM to apply": "Uygulamak için VM'yi yeniden başlat", "Restart all": "Tümünü yeniden başlat", - "Restart engine": "Motoru yeniden başlat", - "Restart engine to finish": "Bitirmek için motoru yeniden başlatın", + "Restart engine": "Engine'i yeniden başlat", + "Restart engine to finish": "Bitirmek için Engine'i yeniden başlatın", "Restart later": "Daha sonra yeniden başlat", "Restart now": "Şimdi yeniden başlat", "Restart to update": "Güncellemek için yeniden başlat", "Restart {name} with the new environment?": "{name} yeni ortamla yeniden başlatılsın mı?", - "Restarting stops the running containers; start them again afterwards.": "Yeniden başlatma çalışan kapsayıcıları durdurur; ardından onları yeniden başlatın.", + "Restarting stops the running containers; start them again afterwards.": "Yeniden başlatma çalışan konteynerleri durdurur; ardından onları yeniden başlatın.", "Restarting…": "Yeniden başlatılıyor…", "Restarts": "Yeniden başlatmalar", "Restore": "Geri yükle", @@ -872,19 +872,19 @@ "Retry starts it again; the layers already here are kept.": "Yeniden dene onu yeniden başlatır; burada olan katmanlar korunur.", "Review": "Gözden geçir", "Run": "Çalıştır", - "Run a test container": "Test kapsayıcısı çalıştır", + "Run a test container": "Test konteyneri çalıştır", "Run {cmd}, then Retry.": "{cmd} komutunu çalıştırın, sonra Yeniden dene'ye basın.", - "Running": "Çalışıyor", + "Running": "Aktif", "Running Kiri {version} · back in {time}": "Kiri {version} çalışıyor · {time} içinde geri döner", - "Running containers answer at <name>.kiri.localhost, which needs no setup.": "Çalışan kapsayıcılar kurulum gerektirmeyen <name>.kiri.localhost adresinde yanıt verir.", + "Running containers answer at <name>.kiri.localhost, which needs no setup.": "Çalışan konteynerler kurulum gerektirmeyen <name>.kiri.localhost adresinde yanıt verir.", "Running now with {cpus} and up to {mem}.": "Şu anda {cpus} ve en fazla {mem} ile çalışıyor.", - "Running, not ready": "Çalışıyor, hazır değil", + "Running, not ready": "Aktif, hazır değil", "Running: it rests by itself when nothing runs and wakes when you use it.": "Çalışıyor: hiçbir şey çalışmadığında kendiliğinden dinlenir, kullandığınızda uyanır.", "Running: {cmd}": "Çalışıyor: {cmd}", "Runs": "Çalıştırılan", "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "Her komutu {name} içinde {sh} ile çalıştırır; {cd} korunur. ↑ ve ↓ ile önceki komutlar arasında gezinin.", - "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "Burada, Mac'inizde Kiri'deki görüntü kopyası üzerinde çalışır; hiçbir şey yüklenmez.", - "Runs your containers": "Kapsayıcılarınızı çalıştırır", + "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "Burada, Mac'inizde Kiri'deki imaj kopyası üzerinde çalışır; hiçbir şey yüklenmez.", + "Runs your containers": "Konteynerlerinizi çalıştırır", "SQL Server won't start without a strong password for its sa account, and its licence accepted.": "SQL Server, sa hesabı için güçlü bir parola ve lisansı kabul edilmeden başlamaz.", "Same as the window ({font})": "Pencereyle aynı ({font})", "Same as {os}": "{os} ile aynı", @@ -895,26 +895,26 @@ "Save to Downloads": "İndirilenler'e kaydet", "Save {name}'s new environment?": "{name} için yeni ortam kaydedilsin mi?", "Saved in .wslconfig. WSL uses these from its next start": ".wslconfig dosyasına kaydedildi. WSL bunları bir sonraki başlatmada kullanır", - "Saved in the container's environment. Kiri doesn't keep a copy.": "Kapsayıcının ortamına kaydedildi. Kiri bir kopya tutmaz.", - "Saved in this container's environment. Kiri doesn't keep a copy.": "Bu kapsayıcının ortamına kaydedildi. Kiri bir kopya tutmaz.", + "Saved in the container's environment. Kiri doesn't keep a copy.": "Konteynerin ortamına kaydedildi. Kiri bir kopya tutmaz.", + "Saved in this container's environment. Kiri doesn't keep a copy.": "Bu konteynerin ortamına kaydedildi. Kiri bir kopya tutmaz.", "Saved the SBOM to Downloads as {file}": "SBOM, İndirilenler'e kaydedildi: {file}", "Saved the report to {path}": "Rapor kaydedildi: {path}", "Saved to Downloads as {file}": "İndirilenler'e kaydedildi: {file}", "Saved. The VM uses these from its next start": "Kaydedildi. VM bunları bir sonraki başlatmada kullanır", "Saving…": "Kaydediliyor…", "Scan again": "Yeniden tara", - "Scan image": "Görüntüyü tara", + "Scan image": "Imajı tara", "Scan of {when}": "Tarama: {when}", "Scan with": "Tarayıcı", "Scan {image}": "Tara: {image}", - "Scan {image} for known vulnerabilities": "{image} görüntüsünü bilinen güvenlik açıklarına karşı tara", + "Scan {image} for known vulnerabilities": "{image} imajını bilinen güvenlik açıklarına karşı tara", "Scanned": "Tarandı", - "Scanning the image's packages": "Görüntünün paketleri taranıyor", + "Scanning the image's packages": "Imajın paketleri taranıyor", "Scans": "Taramalar", - "Search Docker Hub, or paste an image reference": "Docker Hub'da arayın veya bir görüntü başvurusu yapıştırın", + "Search Docker Hub, or paste an image reference": "Docker Hub'da arayın veya bir imaj başvurusu yapıştırın", "Search Kiri": "Kiri'de ara", "Search Kiri…": "Kiri'de ara…", - "Search containers, images…": "Kapsayıcılarda, görüntülerde ara…", + "Search containers, images…": "Konteynerlerde, görüntülerde ara…", "Search languages": "Dil ara", "Search {view}…": "Ara: {view}…", "Searching Docker Hub": "Docker Hub'da aranıyor", @@ -950,11 +950,11 @@ "Set it and start": "Ayarla ve başlat", "Set up": "Kur", "Set up Kiri": "Kiri'yi kur", - "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "docker build'in burada çalışması için Kiri'nin derleyicisini kurun. İlk derlemenize kadar hiçbir şey indirilmez", + "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "docker build'in burada çalışması için Kiri'nin builder'ını kurun. İlk build'inize kadar hiçbir şey indirilmez", "Set up with Kiri Linux": "Kiri Linux ile kur", "Set up with Ubuntu": "Ubuntu ile kur", "Set {what}": "Ayarla: {what}", - "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Microsoft'un görüntüsünün istediği gibi ACCEPT_EULA=Y ayarlar.", + "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Microsoft'un imajının istediği gibi ACCEPT_EULA=Y ayarlar.", "Setting up": "Kuruluyor", "Setting up Docker tools…": "Docker araçları kuruluyor…", "Setting up Docker tools… {pct}%": "Docker araçları kuruluyor… %{pct}", @@ -963,13 +963,13 @@ "Setting up the Docker tools": "Docker araçları kuruluyor", "Settings": "Ayarlar", "Settings…": "Ayarlar…", - "Setup log": "Kurulum günlüğü", + "Setup log": "Kurulum log'u", "Setup steps": "Kurulum adımları", "Setup time": "Kurulum süresi", "Severity": "Önem derecesi", "Share": "Paylaş", "Share again": "Yeniden paylaş", - "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "Paylaş, bir kapsayıcıya veya Kubernetes servisine Kiri Cloud'a giden güvenli bir tünel üzerinden herkese açık bir https bağlantısı verir.", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "Paylaş, bir konteynere veya Kubernetes servisine Kiri Cloud'a giden güvenli bir tünel üzerinden herkese açık bir https bağlantısı verir.", "Share pod {name}?": "{name} pod'u paylaşılsın mı?", "Share service {name}": "{name} servisini paylaş", "Share this pod on a port…": "Bu pod'u bir portta paylaş…", @@ -979,7 +979,7 @@ "Shared": "Paylaşıldı", "Shared by {who}": "Paylaşan: {who}", "Shared now": "Şu an paylaşılan", - "Shared with {os}: the VM only uses them while containers are busy.": "{os} ile paylaşılır: VM bunları yalnızca kapsayıcılar meşgulken kullanır.", + "Shared with {os}: the VM only uses them while containers are busy.": "{os} ile paylaşılır: VM bunları yalnızca konteynerler meşgulken kullanır.", "Shared · {url}": "Paylaşıldı · {url}", "Shares": "Paylaşımlar", "Sharing…": "Paylaşılıyor…", @@ -987,8 +987,8 @@ "Show": "Göster", "Show Images": "Görüntüleri Göster", "Show all actions": "Tüm işlemleri göster", - "Show containers": "Kapsayıcıları göster", - "Show full log": "Günlüğün tamamını göster", + "Show containers": "Konteynerleri göster", + "Show full log": "Log'un tamamını göster", "Show in Diagnostics": "Tanılama'da göster", "Show in Finder": "Finder'da göster", "Show its requests": "İsteklerini göster", @@ -1026,7 +1026,7 @@ "Skip": "Atla", "Skip this version": "Bu sürümü atla", "Skipped: docker build builds where docker points": "Atlandı: docker build, docker nereyi gösteriyorsa orada derler", - "Skipped: docker keeps using the engine it has now": "Atlandı: docker şu anki motorunu kullanmaya devam eder", + "Skipped: docker keeps using the engine it has now": "Atlandı: docker şu anki Engine'ini kullanmaya devam eder", "Skipped: {problem}": "Atlandı: {problem}", "Slow because the VM is out of memory": "VM'nin belleği tükendiği için yavaş", "Small": "Küçük", @@ -1049,24 +1049,24 @@ "Start Kiri when I sign in (in the tray)": "Oturum açtığımda Kiri'yi başlat (sistem tepsisinde)", "Start Kubernetes": "Kubernetes'i başlat", "Start Linux VM": "Linux VM'yi başlat", - "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "Tek bir Kiri kapsayıcısında tek düğümlü bir küme (k3s) başlatın. API'si {api} adresindedir (veya bir sonraki boş port) ve kubectl, kiri k8s start ile olduğu gibi {context} bağlamını alır.", + "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "Tek bir Kiri konteynerinde tek node'lu bir cluster (k3s) başlatın. API'si {api} adresindedir (veya bir sonraki boş port) ve kubectl, kiri k8s start ile olduğu gibi {context} bağlamını alır.", "Start again": "Yeniden başlat", "Start all": "Tümünü başlat", - "Start engine": "Motoru başlat", + "Start engine": "Engine'i başlat", "Start it": "Başlat", "Start it to restart it": "Yeniden başlatmak için başlatın", - "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "Kapsayıcı çalıştırmak için başlatın. Saniyenin küçük bir kesrinde başlar ve boştayken uyur.", + "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "Konteyner çalıştırmak için başlatın. Saniyenin küçük bir kesrinde başlar ve boştayken uyur.", "Start it to share it": "Paylaşmak için başlatın", "Start scan": "Taramayı başlat", - "Start the container to run commands in it.": "İçinde komut çalıştırmak için kapsayıcıyı başlatın.", - "Start the engine": "Motoru başlat", + "Start the container to run commands in it.": "İçinde komut çalıştırmak için konteyneri başlatın.", + "Start the engine": "Engine'i başlat", "Start {engine} to bring its images over now, or later from Settings → Import.": "Görüntülerini şimdi taşımak için {engine} uygulamasını başlatın veya daha sonra Ayarlar → İçe aktar'dan taşıyın.", "Started": "Başlatıldı", "Started with {name} set": "{name} ayarlanarak başlatıldı", "Started {name}": "Başlatıldı: {name}", "Started {name} on {ports}": "Başlatıldı: {name}, portlar: {ports}", "Starting": "Başlatılıyor", - "Starting Kiri’s engine": "Kiri’nin motoru başlatılıyor", + "Starting Kiri’s engine": "Kiri’nin Engine'i başlatılıyor", "Starting Kubernetes…": "Kubernetes başlatılıyor…", "Starting the scan": "Tarama başlatılıyor", "Starting…": "Başlatılıyor…", @@ -1127,75 +1127,75 @@ "The API server port must be a number from 1024 to 65535": "API sunucusu portu 1024 ile 65535 arasında bir sayı olmalıdır", "The AWS CLI has no profiles yet. Set one up with {cmd}.": "AWS CLI'da henüz profil yok. Şu komutla bir tane oluşturun: {cmd}", "The GitHub CLI stays signed in.": "GitHub CLI oturumu açık kalır.", - "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes API sunucusu. Asla paylaşılmaz: bağlantıya sahip herkes kümeyi denetlemeyi deneyebilir.", + "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes API sunucusu. Asla paylaşılmaz: bağlantıya sahip herkes cluster'ı denetlemeyi deneyebilir.", "The Linux VM restarted with the new resources": "Linux VM yeni kaynaklarla yeniden başlatıldı", "The VM has {mem}; {free}.": "VM'de {mem} var; {free}.", "The VM is asleep; it starts with these next time.": "VM uykuda; bir sonraki sefer bunlarla başlar.", "The VM's memory is nearly full: {used} of {max}.": "VM'nin belleği neredeyse dolu: {used} / {max}.", "The app on {host} keeps running, and {program} there shows the share as stopped from another computer.": "{host} üzerindeki uygulama çalışmaya devam eder ve oradaki {program}, paylaşımı başka bir bilgisayardan durdurulmuş olarak gösterir.", - "The build failed": "Derleme başarısız oldu", - "The build was canceled": "Derleme iptal edildi", + "The build failed": "Build başarısız oldu", + "The build was canceled": "Build iptal edildi", "The code goes straight to the AWS CLI; Kiri doesn't keep it.": "Kod doğrudan AWS CLI'a gider; Kiri kodu saklamaz.", - "The container keeps running.": "Kapsayıcı çalışmaya devam eder.", + "The container keeps running.": "Konteyner çalışmaya devam eder.", "The docker command is signed out too.": "docker komutunun oturumu da kapanır.", "The docker command uses {app}": "docker komutu şunu kullanıyor: {app}", "The docker command uses {engine}. Switch it to {app}": "docker komutu şunu kullanıyor: {engine}. Şuna geçirin: {app}", - "The engine": "Motor", - "The engine is running but not answering": "Motor çalışıyor ama yanıt vermiyor", - "The engine is stopped": "Motor durduruldu", - "The engine isn't here: reinstall the kiri package": "Motor bulunamadı: kiri paketini yeniden yükleyin", - "The engine still runs Kiri {version}": "Motor hâlâ Kiri {version} çalıştırıyor", - "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Motor hâlâ {version} çalıştırıyor. Yeniden başlatmak çalışan kapsayıcıları durdurur; yeniden başlatma ilkesi olanlar yeniden başlar.", + "The engine": "Engine", + "The engine is running but not answering": "Engine çalışıyor ama yanıt vermiyor", + "The engine is stopped": "Engine durduruldu", + "The engine isn't here: reinstall the kiri package": "Engine bulunamadı: kiri paketini yeniden yükleyin", + "The engine still runs Kiri {version}": "Engine hâlâ Kiri {version} çalıştırıyor", + "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Engine hâlâ {version} çalıştırıyor. Yeniden başlatmak çalışan konteynerleri durdurur; restart politikası olanlar yeniden başlar.", "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "İlk tarama Grype'ı ve veritabanını indirir: yaklaşık 230 MB (açılınca 3 GB).", "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Microsoft'un WSL listesindeki tam Ubuntu. Kiri onun içinde çalışır; onu kendi Linux'unuz olarak da açabilirsiniz.", - "The image's own way to start without it.": "Görüntünün bu olmadan başlamak için kendi yolu.", + "The image's own way to start without it.": "Imajın bu olmadan başlamak için kendi yolu.", "The kiri share there stops.": "Oradaki kiri share durur.", - "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "Pencereden, motordan ve kiri komutlarından son 300 satır ile motorun kendi çıktısı", + "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "Pencereden, Engine'den ve kiri komutlarından son 300 satır ile Engine'in kendi çıktısı", "The last {n} seconds": "Son {n} saniye", "The link ends when the pod does.": "Bağlantı, pod sona erince sona erer.", - "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "VM'nin alabileceği en fazla bellek. Belleği yalnızca kapsayıcılar ihtiyaç duydukça kullanır ve kalanı {os} sistemine geri verir.", + "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "VM'nin alabileceği en fazla bellek. Belleği yalnızca konteynerler ihtiyaç duydukça kullanır ve kalanı {os} sistemine geri verir.", "The name comes from the Igbo word ntakịrị, “small”.": "Ad, “küçük” anlamına gelen İgboca ntakịrị sözcüğünden gelir.", - "The part that runs your containers, inside {linux}.": "Kapsayıcılarınızı çalıştıran parça; {linux} içinde.", - "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "Bu {host} üzerinde API sunucusu için port; 1024 ile 65535 arası (varsayılan 6443). Küme başlarken kullanımdaysa bir sonraki boş port alınır. Kaydetmek kümeyi yeniden başlatır ve {context} bağlamını günceller.", + "The part that runs your containers, inside {linux}.": "Konteynerlerinizi çalıştıran parça; {linux} içinde.", + "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "Bu {host} üzerinde API sunucusu için port; 1024 ile 65535 arası (varsayılan 6443). Cluster başlarken kullanımdaysa bir sonraki boş port alınır. Kaydetmek cluster'ı yeniden başlatır ve {context} bağlamını günceller.", "The profile {profile} asks for a code from your MFA device {device}.": "{profile} profili, {device} MFA cihazınızdan bir kod istiyor.", "The profile {profile} asks for a code from your MFA device.": "{profile} profili, MFA cihazınızdan bir kod istiyor.", "The profile {profile} signs in through AWS IAM Identity Center. Kiri runs {cmd}, which opens AWS's page.": "{profile} profili AWS IAM Identity Center üzerinden oturum açar. Kiri, AWS'nin sayfasını açan şu komutu çalıştırır: {cmd}", - "The run before the container's last restart": "Kapsayıcının son yeniden başlatılmasından önceki çalıştırma", + "The run before the container's last restart": "Konteynerin son yeniden başlatılmasından önceki çalıştırma", "The same docker commands you know, talking to Kiri. Each file is checked against its pinned SHA-256.": "Bildiğiniz docker komutları, Kiri ile konuşur. Her dosya sabitlenmiş SHA-256 değerine göre denetlenir.", "The window": "Pencere", "The {n} packages as CycloneDX JSON, saved to Downloads": "{n} paket, CycloneDX JSON olarak İndirilenler'e kaydedilir", "The {vm} is asleep: it holds no memory": "{vm} uykuda: bellek tutmuyor", "Theme": "Tema", "They appear in Images as they arrive.": "Geldikçe Görüntüler'de görünürler.", - "This action left no log lines.": "Bu işlem günlük satırı bırakmadı.", - "This build made no image to scan: it failed before exporting, or its output was the cache only.": "Bu derleme taranacak bir görüntü oluşturmadı: dışa aktarmadan önce başarısız oldu veya çıktısı yalnızca önbellekti.", - "This build made no image: it failed before exporting, or its output was the cache only.": "Bu derleme görüntü oluşturmadı: dışa aktarmadan önce başarısız oldu veya çıktısı yalnızca önbellekti.", - "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "Bu derlemenin görüntüsü Kiri'de değil, bu yüzden burada taranacak bir şey yok. Başka bir yere gönderildi, dışa aktarıldı veya o zamandan beri kaldırıldı. Burada taramak için --load ile derleyin.", + "This action left no log lines.": "Bu işlem log satırı bırakmadı.", + "This build made no image to scan: it failed before exporting, or its output was the cache only.": "Bu build taranacak bir imaj oluşturmadı: dışa aktarmadan önce başarısız oldu veya çıktısı yalnızca önbellekti.", + "This build made no image: it failed before exporting, or its output was the cache only.": "Bu build imaj oluşturmadı: dışa aktarmadan önce başarısız oldu veya çıktısı yalnızca önbellekti.", + "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "Bu build'in imajı Kiri'de değil, bu yüzden burada taranacak bir şey yok. Başka bir yere gönderildi, dışa aktarıldı veya o zamandan beri kaldırıldı. Burada taramak için --load ile derleyin.", "This can't be undone.": "Bu işlem geri alınamaz.", "This closes that tunnel on {host}, from here. The link stops working for everyone.": "Bu, {host} üzerindeki o tüneli buradan kapatır. Bağlantı herkes için çalışmayı durdurur.", "This computer can't use it while it's in Kiri: detach it to get it back.": "Bu bilgisayar, Kiri'deyken onu kullanamaz: geri almak için ayırın.", "This file is binary or larger than 256 KB.": "Bu dosya ikili veya 256 KB'tan büyük.", "This folder is empty.": "Bu klasör boş.", - "This image": "Bu görüntü", - "This image needs privileged mode": "Bu görüntü ayrıcalıklı mod gerektiriyor", + "This image": "Bu imaj", + "This image needs privileged mode": "Bu imaj ayrıcalıklı mod gerektiriyor", "This is Kubernetes. Kiri runs it for you": "Bu Kubernetes. Kiri onu sizin için çalıştırır", "This lists every link on your account, on any computer.": "Bu liste, hesabınızdaki tüm bağlantıları her bilgisayardan gösterir.", "This month": "Bu ay", "This pod's name changes when it restarts, and the link would end.": "Bu pod'un adı yeniden başladığında değişir ve bağlantı sona erer.", - "This sign-in's ID: a hash of its token, safe to quote when asking for help": "Bu oturumun kimliği: belirtecinin karma değeri; yardım isterken belirtmek güvenlidir", + "This sign-in's ID: a hash of its token, safe to quote when asking for help": "Bu oturumun kimliği: token'ının karma değeri; yardım isterken belirtmek güvenlidir", "This system applies your new access when you sign in again. Kiri opens ready after that.": "Bu sistem yeni erişiminizi yeniden oturum açtığınızda uygular. Kiri bundan sonra hazır açılır.", "Time": "Zaman", "To make names like {name} work, Kiri adds one small settings file to your Mac ({path}), and changing system settings always needs an administrator. Kiri uses the password only for that, once. It never sees the password: macOS handles it.": "{name} gibi adların çalışması için Kiri, Mac'inize küçük bir ayar dosyası ekler ({path}) ve sistem ayarlarını değiştirmek her zaman yönetici gerektirir. Kiri parolayı yalnızca bunun için, bir kez kullanır. Parolayı asla görmez: macOS halleder.", "Today {time}": "Bugün {time}", - "Token": "Belirteç", - "Token or password": "Belirteç veya parola", + "Token": "Token", + "Token or password": "Token veya parola", "Tomorrow": "Yarın", "Took": "Süre", "Traffic over the last two minutes": "Son iki dakikadaki trafik", "Traffic served": "Sunulan trafik", "Trust Kiri's certificate so {url} works. macOS asks for your password. The certificate can only vouch for Kiri's own names.": "{url} adresinin çalışması için Kiri'nin sertifikasına güvenin. macOS parolanızı sorar. Sertifika yalnızca Kiri'nin kendi adlarına kefil olabilir.", "Try again": "Yeniden dene", - "Turn off engine": "Motoru kapat", + "Turn off engine": "Engine'i kapat", "Turn on Kiri's in Settings → Kubernetes instead of starting a copy.": "Bir kopya başlatmak yerine Ayarlar → Kubernetes'ten Kiri'ninkini açın.", "Turn on Kubernetes": "Kubernetes'i aç", "Turn on WSL's Windows components": "Turn on WSL's Windows components", @@ -1231,29 +1231,29 @@ "Use Kiri's Kubernetes": "Kiri'nin Kubernetes'ini kullan", "Use Save to Downloads to open it.": "Açmak için İndirilenler'e kaydet'i kullanın.", "Use Show in Finder to open it.": "Açmak için Finder'da göster'i kullanın.", - "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Bir Docker Hub kişisel erişim belirteci kullanın (Hesap ayarları → Kişisel erişim belirteçleri).", - "Use a GitHub personal access token (classic) with the {scope} scope.": "{scope} kapsamına sahip bir GitHub kişisel erişim belirteci (klasik) kullanın.", - "Use a personal or deploy token with the {scope} scope.": "{scope} kapsamına sahip kişisel veya dağıtım belirteci kullanın.", + "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Bir Docker Hub kişisel erişim token'ı kullanın (Hesap ayarları → Kişisel erişim token'ları).", + "Use a GitHub personal access token (classic) with the {scope} scope.": "{scope} kapsamına sahip bir GitHub kişisel erişim token'ı (klasik) kullanın.", + "Use a personal or deploy token with the {scope} scope.": "{scope} kapsamına sahip kişisel veya dağıtım token'ı kullanın.", "Use another port": "Başka bir port kullan", "Use the Ubuntu already here": "Buradaki Ubuntu'yu kullan", "Use this profile": "Bu profili kullan", "Use your AWS profile": "AWS profilinizi kullanın", - "Use your password, or a robot account's name and token.": "Parolanızı veya bir robot hesabının adını ve belirtecini kullanın.", + "Use your password, or a robot account's name and token.": "Parolanızı veya bir robot hesabının adını ve token'ını kullanın.", "Use {app} for docker?": "docker için {app} kullanılsın mı?", "Use {name} instead": "Bunun yerine şunu kullan: {name}", "Used by": "Kullanan", "User": "Kullanıcı", "Username": "Kullanıcı adı", "Using the Ubuntu already on this PC: nothing to download.": "Bu PC'deki mevcut Ubuntu kullanılıyor: indirme yok.", - "VPNs need no setting: container traffic leaves through macOS.": "VPN'ler ayar gerektirmez: kapsayıcı trafiği macOS üzerinden çıkar.", + "VPNs need no setting: container traffic leaves through macOS.": "VPN'ler ayar gerektirmez: konteyner trafiği macOS üzerinden çıkar.", "Value": "Değer", "Version {version}": "Sürüm {version}", - "Versions, macOS, whether the engine runs, how many containers and images": "Sürümler, macOS, motorun çalışıp çalışmadığı, kapsayıcı ve görüntü sayısı", + "Versions, macOS, whether the engine runs, how many containers and images": "Sürümler, macOS, Engine'in çalışıp çalışmadığı, konteyner ve imaj sayısı", "View": "Görünüm", - "View container": "Kapsayıcıyı görüntüle", + "View container": "Konteyneri görüntüle", "Visitors": "Ziyaretçiler", "Visitors' browsers see a short Kiri Cloud notice page first, then your app.": "Ziyaretçilerin tarayıcıları önce kısa bir Kiri Cloud bildirim sayfası, ardından uygulamanızı görür.", - "Volumes": "Birimler", + "Volumes": "Volume'ler", "Vulnerabilities": "Güvenlik açıkları", "Vulnerability": "Güvenlik açığı", "WSL restarted with the new resources": "WSL yeni kaynaklarla yeniden başlatıldı", @@ -1278,14 +1278,14 @@ "What's new": "Yenilikler", "What's new in Kiri {version}": "Kiri {version} sürümündeki yenilikler", "What's new in {version}": "{version} sürümündeki yenilikler", - "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Kiri'nin bir parçası çöktüğünde yığın izi ve öncesindeki son 200 günlük satırı; Kiri'nin ve sistemin sürümleri, bilgisayarın modeli ve bu kurulum için rastgele bir kimlikle birlikte Kiri Cloud'a gönderilir. Kiri Cloud hesabınız ve kapsayıcılarınızın içinden hiçbir şey asla gönderilmez. Ana klasörünüz, görüntü ve kapsayıcı adları, belirteçler ve parolalar çıkarılır.", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Kiri'nin bir parçası çöktüğünde stack trace ve öncesindeki son 200 log satırı; Kiri'nin ve sistemin sürümleri, bilgisayarın modeli ve bu kurulum için rastgele bir kimlikle birlikte Kiri Cloud'a gönderilir. Kiri Cloud hesabınız ve konteynerlerinizin içinden hiçbir şey asla gönderilmez. Ana klasörünüz, imaj ve konteyner adları, token'lar ve parolalar çıkarılır.", "When the pod restarts, it gets a new name and the link ends.": "Pod yeniden başladığında yeni bir ad alır ve bağlantı sona erer.", - "Where should your containers run?": "Kapsayıcılarınız nerede çalışsın?", + "Where should your containers run?": "Konteynerleriniz nerede çalışsın?", "Which steps": "Hangi adımlar", "Window": "Pencere", "Windows Subsystem for Linux": "Linux için Windows Alt Sistemi", "Windows asks for an administrator's approval once.": "Windows bir kez yönetici onayı ister.", - "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows, USB cihazlarını Microsoft'un önerdiği araç usbipd-win ile Kiri'nin kapsayıcılarının çalıştığı WSL'ye verir.", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows, USB cihazlarını Microsoft'un önerdiği araç usbipd-win ile Kiri'nin konteynerlerinin çalıştığı WSL'ye verir.", "Windows is asking": "Windows soruyor", "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows, açılırken Sanal Makine Platformu'nu etkinleştirir. Kiri ardından kendiliğinden yeniden açılır ve 2. adımdan devam eder. Önce çalışmanızı kaydedin.", "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "Bu işlem bitince Windows'un bir kez yeniden başlatılması gerekecek. Kiri yeniden başlatmadan önce sorar, böylece önce çalışmanızı kaydedebilirsiniz.", @@ -1298,38 +1298,38 @@ "You can keep working while they copy.": "Kopyalanırken çalışmaya devam edebilirsiniz.", "You can pull it again later.": "Daha sonra yeniden çekebilirsiniz.", "You can still pull the name as typed.": "Adı yazıldığı gibi yine de çekebilirsiniz.", - "You can switch any time in Settings → Builds.": "İstediğiniz zaman Ayarlar → Derlemeler'den değiştirebilirsiniz.", + "You can switch any time in Settings → Builds.": "İstediğiniz zaman Ayarlar → Build'ler'den değiştirebilirsiniz.", "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "Sizde {ref} var ({when}). Güncellemeleri almak için yeniden çekin; yalnızca değişen katmanlar indirilir.", "You have {ref}. Pull again to get any updates; only changed layers download.": "Sizde {ref} var. Güncellemeleri almak için yeniden çekin; yalnızca değişen katmanlar indirilir.", "You have {tags}": "Sizdekiler: {tags}", "You have {version}": "Sizdeki: {version}", "You have {version}.": "Sizdeki: {version}.", - "You sign in on github.com. Kiri gets a token that can only read packages.": "Oturumu github.com'da açarsınız. Kiri yalnızca paketleri okuyabilen bir belirteç alır.", + "You sign in on github.com. Kiri gets a token that can only read packages.": "Oturumu github.com'da açarsınız. Kiri yalnızca paketleri okuyabilen bir token alır.", "You're sharing {name}": "Paylaşıyorsunuz: {name}", "Your AWS sign-in expired": "AWS oturumunuzun süresi doldu", "Your account can use Kiri": "Hesabınız Kiri'yi kullanabilir", - "Your containers keep running while it downloads.": "İndirme sırasında kapsayıcılarınız çalışmaya devam eder.", - "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "Herhangi bir şey yazılmadan önce ana klasörünüzün yolu, belirteçler, parolalar ve diğer gizli bilgiler silinir.", + "Your containers keep running while it downloads.": "İndirme sırasında konteynerleriniz çalışmaya devam eder.", + "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "Herhangi bir şey yazılmadan önce ana klasörünüzün yolu, token'lar, parolalar ve diğer gizli bilgiler silinir.", "Your link for {name} is live.": "{name} için bağlantınız yayında.", "Your other Docker": "Diğer Docker'ınız", "Your own registry…": "Kendi kayıt defteriniz…", "Your password and two-step code go to Docker, not Kiri.": "Parolanız ve iki adımlı doğrulama kodunuz Kiri'ye değil, Docker'a gider.", - "Your password, or an access token if the registry offers them.": "Parolanız veya kayıt defteri sunuyorsa bir erişim belirteci.", + "Your password, or an access token if the registry offers them.": "Parolanız veya kayıt defteri sunuyorsa bir erişim token'ı.", "Your plan allows {limit} tunnels at once, and all {limit} are in use: {slots}.": "Planınız aynı anda {limit} tünele izin veriyor ve {limit} tünelin tümü kullanımda: {slots}.", "Your plan allows {limit} tunnels at once. In use: {slots}.": "Planınız aynı anda {limit} tünele izin veriyor. Kullanımda: {slots}.", "Your plan allows {limit} tunnels at once; close one first.": "Planınız aynı anda {limit} tünele izin veriyor; önce birini kapatın.", "Your plan allows {n} at once": "Planınız aynı anda {n} taneye izin veriyor", - "Your test container said hello. Open a new terminal and try it yourself:": "Test kapsayıcınız merhaba dedi. Yeni bir terminal açın ve kendiniz deneyin:", - "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "{engine} görüntüleriniz ve kapsayıcılarınız {engine} içinde kalır. {app}, siz taşıyana kadar onları göremez.", + "Your test container said hello. Open a new terminal and try it yourself:": "Test konteyneriniz merhaba dedi. Yeni bir terminal açın ve kendiniz deneyin:", + "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "{engine} görüntüleriniz ve konteynerleriniz {engine} içinde kalır. {app}, siz taşıyana kadar onları göremez.", "Your {engine} images stay there. Bring them over any time from Settings → Import.": "{engine} görüntüleriniz orada kalır. İstediğiniz zaman Ayarlar → İçe aktar'dan taşıyabilirsiniz.", "Yours": "Sizin", "Zoom In": "Yakınlaştır", "Zoom Out": "Uzaklaştır", - "a container": "bir kapsayıcı", + "a container": "bir konteyner", "a free port": "boş bir port", "a password": "bir parola", "a root password": "bir root parolası", - "a saved token": "kayıtlı bir belirteç", + "a saved token": "kayıtlı bir token", "about {min} min left": "yaklaşık {min} dk kaldı", "about {n} min left": "yaklaşık {n} dk kaldı", "about {n} s left": "yaklaşık {n} sn kaldı", @@ -1345,8 +1345,8 @@ "approved": "onaylandı", "auto": "otomatik", "back": "geri", - "build ID": "derleme kimliği", - "builds": "derleme", + "build ID": "build kimliği", + "builds": "build", "cached": "önbellekte", "checked {ago}": "denetlendi: {ago}", "choose tag": "etiket seç", @@ -1354,8 +1354,8 @@ "compose lines": "compose satırları", "compressed": "sıkıştırılmış", "computer": "bilgisayar", - "container ID": "kapsayıcı kimliği", - "containers": "kapsayıcı", + "container ID": "konteyner kimliği", + "containers": "konteyner", "couldn't pull alpine: {why}": "alpine indirilemedi: {why}", "created {date}": "oluşturuldu: {date}", "database from {date}": "veritabanı tarihi: {date}", @@ -1367,7 +1367,7 @@ "docker flag": "docker bayrağı", "docker now uses {app}": "docker artık şunu kullanıyor: {app}", "docker run, from any terminal": "docker run, herhangi bir terminalden", - "docker talks to another engine now": "docker artık başka bir motorla konuşuyor", + "docker talks to another engine now": "docker artık başka bir Engine ile konuşuyor", "docker uses Kiri": "docker Kiri'yi kullanıyor", "docker, Compose and Docker-socket tools reach Kiri": "docker, Compose ve Docker soketi kullanan araçlar Kiri'ye ulaşır", "docker, docker compose and docker build use Kiri in every new terminal. Another Docker was found on this PC; leave this off to keep using it as the default.": "docker, docker compose ve docker build her yeni terminalde Kiri'yi kullanır. Bu PC'de başka bir Docker bulundu; onu varsayılan olarak kullanmaya devam etmek için bunu kapalı bırakın.", @@ -1376,29 +1376,29 @@ "done": "bitti", "downloading": "indiriliyor", "failed": "başarısız", - "failed builds": "başarısız derleme", - "failed containers": "başarısız kapsayıcı", + "failed builds": "başarısız build", + "failed containers": "başarısız konteyner", "for that user": "o kullanıcı için", "from any page": "her sayfadan", - "from the container's log": "kapsayıcının günlüğünden", - "from the engine, when it tried to start it": "motordan, onu başlatmaya çalışırken", - "from the engine, when it tried to start {name}": "motordan, {name} başlatılmaya çalışılırken", + "from the container's log": "konteynerin logundan", + "from the engine, when it tried to start it": "Engine'den, onu başlatmaya çalışırken", + "from the engine, when it tried to start {name}": "Engine'den, {name} başlatılmaya çalışılırken", "idle": "boşta", "idle · nobody is visiting": "boşta · ziyaretçi yok", - "image ID": "görüntü kimliği", - "images": "görüntü", + "image ID": "imaj kimliği", + "images": "imaj", "in": "gelen", "in config.json": "config.json içinde", "in progress": "sürüyor", "in {time}": "{time} içinde", "input events": "giriş olayları", "installed": "yüklendi", - "its build cache": "derleme önbelleği", + "its build cache": "build önbelleği", "just now": "az önce", "kept in {v}": "saklandığı yer: {v}", "kernel {version}": "çekirdek {version}", - "kiri.service and the engine are in place": "kiri.service ve motor yerinde", - "kubectl context": "kubectl bağlamı", + "kiri.service and the engine are in place": "kiri.service ve Engine yerinde", + "kubectl context": "kubectl context'i", "latest": "en son", "layers": "katman", "line {n}": "satır {n}", @@ -1412,7 +1412,7 @@ "needs {name}": "gerekli: {name}", "network interface": "ağ arabirimi", "networks": "ağ", - "no layer: this line only changes the image's settings": "katman yok: bu satır yalnızca görüntünün ayarlarını değiştirir", + "no layer: this line only changes the image's settings": "katman yok: bu satır yalnızca imajın ayarlarını değiştirir", "no monthly cap": "aylık sınır yok", "no speed limit": "hız sınırı yok", "none": "yok", @@ -1446,35 +1446,35 @@ "same as the user": "kullanıcıyla aynı", "saved with {v}": "şununla kaydedildi: {v}", "sent to visitors": "ziyaretçilere gönderilen", - "serial port": "seri bağlantı noktası", + "serial port": "seri port", "services": "servis", "sets {var}, for local use only.": "{var} ayarlar; yalnızca yerel kullanım için.", "sets {var}, so it runs without a login or TLS.": "{var} ayarlar; böylece oturum açma veya TLS olmadan çalışır.", - "sets {var}; it prints the password once in its log.": "{var} ayarlar; parolayı günlüğüne bir kez yazar.", + "sets {var}; it prints the password once in its log.": "{var} ayarlar; parolayı loguna bir kez yazar.", "settings": "ayarlar", "sign in to {host}": "şurada oturum açın: {host}", "skipped": "atlandı", "sound card": "ses kartı", "tag": "etiket", - "the image's settings": "görüntünün ayarları", - "the last error lines in the container's log": "kapsayıcının günlüğündeki son hata satırları", - "the last lines in the container's log": "kapsayıcının günlüğündeki son satırlar", + "the image's settings": "imajın ayarları", + "the last error lines in the container's log": "konteynerin logundaki son hata satırları", + "the last lines in the container's log": "konteynerin logundaki son satırlar", "the link didn't open": "bağlantı açılmadı", "the only web port": "tek web portu", "the port the app in it listens on": "içindeki uygulamanın dinlediği port", "the saved sign-in": "kayıtlı oturum", - "the test container did not run": "test kapsayıcısı çalışmadı", - "the test container did not run: {why}": "test kapsayıcısı çalışmadı: {why}", + "the test container did not run": "test konteyneri çalışmadı", + "the test container did not run: {why}": "test konteyneri çalışmadı: {why}", "this Mac": "bu Mac", "this PC": "bu PC", - "this build": "bu derleme", - "this image": "bu görüntü", + "this build": "bu build", + "this image": "bu imaj", "to do": "yapılacak", "today at {time}": "bugün {time}", "total ↓ {rx} · ↑ {tx}": "toplam ↓ {rx} · ↑ {tx}", "tunnels in use": "kullanılan tünel", "untagged": "etiketsiz", - "untagged images": "etiketsiz görüntü", + "untagged images": "etiketsiz imaj", "up": "çalışma süresi", "up to {size}": "en fazla {size}", "up {time}": "{time} süredir çalışıyor", @@ -1482,7 +1482,7 @@ "used by {names}": "kullanan: {names}", "value": "değer", "video": "video", - "volumes": "birim", + "volumes": "volume", "when the VM's {mem} ran out.": "VM'nin {mem} belleği tükendiğinde.", "yesterday": "dün", "yesterday at {time}": "dün {time}", @@ -1493,12 +1493,12 @@ "{app} doesn't update itself: rebuild it with cargo xtask app-dev": "{app} kendini güncellemez: cargo xtask app-dev ile yeniden derleyin", "{app} needs a password to start": "{app} başlamak için bir parola gerektiriyor", "{app} needs an admin password to start": "{app} başlamak için bir yönetici parolası gerektiriyor", - "{app}: its own engine, containers and settings": "{app}: kendi motoru, kapsayıcıları ve ayarları", - "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "docker hangi motoru kullanırsa kullansın, {build} ve {compose} Kiri'de çalışır ve görüntüler Kiri'de olur.", + "{app}: its own engine, containers and settings": "{app}: kendi Engine'i, konteynerleri ve ayarları", + "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "docker hangi Engine'i kullanırsa kullansın, {build} ve {compose} Kiri'de çalışır ve görüntüler Kiri'de olur.", "{build} and {compose} run on Kiri, and the images are in Kiri. {engine} won't see them; run them with Kiri.": "{build} ve {compose} Kiri'de çalışır ve görüntüler Kiri'de olur. {engine} bunları görmez; onları Kiri ile çalıştırın.", - "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "{build}, docker nereyi gösteriyorsa orada derler; bu yüzden {engine} derlemeleri {engine} içinde kalır. docker Kiri'yi kullandığında derlemeler Kiri'de çalışır.", - "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "{build}, docker nereyi gösteriyorsa orada derler. docker Kiri'yi kullandığında derlemeler Kiri'de çalışır.", - "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} her zaman Kiri'de derler. Geçiş, açık terminallerde de hemen uygulanır. Docker'a geri dönmek, docker'ın derleme ayarlarını Kiri değiştirmeden önceki hâline getirir.", + "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "{build}, docker nereyi gösteriyorsa orada derler; bu yüzden {engine} build'leri {engine} içinde kalır. docker Kiri'yi kullandığında build'ler Kiri'de çalışır.", + "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "{build}, docker nereyi gösteriyorsa orada derler. docker Kiri'yi kullandığında build'ler Kiri'de çalışır.", + "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} her zaman Kiri'de derler. Geçiş, açık terminallerde de hemen uygulanır. Docker'a geri dönmek, docker'ın build ayarlarını Kiri değiştirmeden önceki hâline getirir.", "{docker}, {compose} and your tools run on {app} from now on.": "{docker}, {compose} ve araçlarınız bundan sonra şurada çalışır: {app}.", "{done} of {total}": "{done} / {total}", "{engine} doesn't see them.": "{engine} bunları görmez.", @@ -1512,18 +1512,18 @@ "{host} wants a sign-in for {path}.": "{host}, {path} için oturum açılmasını istiyor.", "{h} h": "{h} sa", "{h} h {m} min": "{h} sa {m} dk", - "{image} is a whole Kubernetes cluster in a container.": "{image}, bir kapsayıcı içinde eksiksiz bir Kubernetes kümesidir.", + "{image} is a whole Kubernetes cluster in a container.": "{image}, bir konteyner içinde eksiksiz bir Kubernetes cluster'ıdır.", "{image} needs {what} to start": "{image} başlamak için şunu gerektiriyor: {what}", - "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s}, Kiri'nin Kubernetes kümesidir. Kaldırmak Kubernetes'i kapatır. Kümenin verileri {k8s} biriminde kalır; Ayarlar → Kubernetes'teki Kümeyi sil her şeyi kaldırır.", - "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s}, Kiri'nin Kubernetes kümesidir. Durdurmak Kubernetes'i kapatır ve pod'ları yeniden başlayana kadar durur.", + "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s}, Kiri'nin Kubernetes cluster'ıdır. Kaldırmak Kubernetes'i kapatır. Cluster'ın verileri {k8s} volume'ünde kalır; Ayarlar → Kubernetes'teki Cluster'ı sil her şeyi kaldırır.", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s}, Kiri'nin Kubernetes cluster'ıdır. Durdurmak Kubernetes'i kapatır ve pod'ları yeniden başlayana kadar durur.", "{kind} names are off: port {port} is in use. Pick another.": "{kind} adları kapalı: {port} portu kullanımda. Başka birini seçin.", - "{kind} names are paused: a container has port {port}.": "{kind} adları duraklatıldı: {port} portunu bir kapsayıcı kullanıyor.", + "{kind} names are paused: a container has port {port}.": "{kind} adları duraklatıldı: {port} portunu bir konteyner kullanıyor.", "{label}, last minute": "{label}, son dakika", "{list} and {last}": "{list} ve {last}", - "{list} are running from this image. Stop them first, then remove the image.": "Bu görüntüden çalışanlar: {list}. Önce onları durdurun, sonra görüntüyü kaldırın.", - "{list} is running from this image. Stop it first, then remove the image.": "Bu görüntüden çalışan: {list}. Önce onu durdurun, sonra görüntüyü kaldırın.", - "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "Bu görüntüden oluşturuldu ve onsuz yeniden başlayamaz, bu yüzden dosyalarıyla birlikte o da kaldırılır: {list}. Birimler kalır.", - "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "Bu görüntüden oluşturuldular ve onsuz yeniden başlayamazlar, bu yüzden dosyalarıyla birlikte onlar da kaldırılır: {list}. Birimler kalır.", + "{list} are running from this image. Stop them first, then remove the image.": "Bu imajdan çalışanlar: {list}. Önce onları durdurun, sonra imajı kaldırın.", + "{list} is running from this image. Stop it first, then remove the image.": "Bu imajdan çalışan: {list}. Önce onu durdurun, sonra imajı kaldırın.", + "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "Bu imajdan oluşturuldu ve onsuz yeniden başlayamaz, bu yüzden dosyalarıyla birlikte o da kaldırılır: {list}. Volume'ler kalır.", + "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "Bu imajdan oluşturuldular ve onsuz yeniden başlayamazlar, bu yüzden dosyalarıyla birlikte onlar da kaldırılır: {list}. Volume'ler kalır.", "{list}, and {last}": "{list} ve {last}", "{live} for {time}": "{live} · {time}", "{live} live, {starting} starting": "{live} canlı, {starting} başlatılıyor", @@ -1541,15 +1541,15 @@ "{name} is listening on {ports}": "{name} şu portları dinliyor: {ports}", "{name} is shared": "{name} paylaşılıyor", "{name} is shared by {who}": "{name} paylaşılıyor, paylaşan: {who}", - "{name} is still used by the container {container}. Remove the container first.": "{name} hâlâ şu kapsayıcı tarafından kullanılıyor: {container}. Önce kapsayıcıyı kaldırın.", - "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} değiştirilmez: görüntüler kopyalanır, birimler ise sonradan kaldırılan geçici, salt okunur bir yardımcıyla okunur. Kapsayıcılar durdurulmuş olarak gelir.", + "{name} is still used by the container {container}. Remove the container first.": "{name} hâlâ şu konteyner tarafından kullanılıyor: {container}. Önce konteyneri kaldırın.", + "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} değiştirilmez: görüntüler kopyalanır, volume'ler ise sonradan kaldırılan geçici, salt okunur bir yardımcıyla okunur. Konteynerler durdurulmuş olarak gelir.", "{name} isn't listening on a port yet, so there's nothing to share. Try again once it's up.": "{name} henüz bir portu dinlemiyor, bu yüzden paylaşılacak bir şey yok. Çalışmaya başlayınca yeniden deneyin.", "{name} isn't running. Start it to import from it; it doesn't need to stay open afterwards.": "{name} çalışmıyor. İçe aktarmak için başlatın; sonrasında açık kalması gerekmez.", "{name} needs {var} to start": "{name} başlamak için şunu gerektiriyor: {var}", "{name} ran and finished": "{name} çalıştı ve bitti", "{name} ran out of memory": "{name} için bellek tükendi", "{name} restarted with the new environment": "{name} yeni ortamla yeniden başlatıldı", - "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} olduğu gibi kalır: Kiri yalnızca kopyalar. Kapsayıcılar durdurulmuş olarak gelir.", + "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} olduğu gibi kalır: Kiri yalnızca kopyalar. Konteynerler durdurulmuş olarak gelir.", "{name} stays: Kubernetes is turned off or deleted in Settings → Kubernetes.": "{name} kalır: Kubernetes, Ayarlar → Kubernetes'ten kapatılır veya silinir.", "{name} stopped": "{name} durdu", "{name} stopped after {n} s": "{name} {n} sn sonra durdu", @@ -1563,8 +1563,8 @@ "{n} change": "{n} değişiklik", "{n} changed": "{n} değişti", "{n} changes": "{n} değişiklik", - "{n} container": "{n} kapsayıcı", - "{n} containers": "{n} kapsayıcı", + "{n} container": "{n} konteyner", + "{n} containers": "{n} konteyner", "{n} d ago": "{n} gün önce", "{n} days ago": "{n} gün önce", "{n} device": "{n} cihaz", @@ -1572,16 +1572,16 @@ "{n} error": "{n} hata", "{n} errors": "{n} hata", "{n} external": "{n} harici", - "{n} failed container": "{n} başarısız kapsayıcı", - "{n} failed containers": "{n} başarısız kapsayıcı", + "{n} failed container": "{n} başarısız konteyner", + "{n} failed containers": "{n} başarısız konteyner", "{n} from {what}": "{n} tanesi {what} kaynaklı", "{n} h ago": "{n} sa önce", - "{n} image": "{n} görüntü", - "{n} image, {size}.": "{n} görüntü, {size}.", - "{n} image.": "{n} görüntü.", - "{n} images": "{n} görüntü", - "{n} images, {size}.": "{n} görüntü, {size}.", - "{n} images.": "{n} görüntü.", + "{n} image": "{n} imaj", + "{n} image, {size}.": "{n} imaj, {size}.", + "{n} image.": "{n} imaj.", + "{n} images": "{n} imaj", + "{n} images, {size}.": "{n} imaj, {size}.", + "{n} images.": "{n} imaj.", "{n} in Kiri": "Kiri'de {n}", "{n} item isn't in Kiri yet. Pick what to copy over.": "{n} öğe henüz Kiri'de değil. Kopyalanacakları seçin.", "{n} items aren't in Kiri yet. Pick what to copy over.": "{n} öğe henüz Kiri'de değil. Kopyalanacakları seçin.", @@ -1590,12 +1590,12 @@ "{n} line": "{n} satır", "{n} lines": "{n} satır", "{n} live": "{n} canlı", - "{n} log line": "{n} günlük satırı", - "{n} log line from the {parts}": "{parts} kaynağından {n} günlük satırı", - "{n} log lines": "{n} günlük satırı", - "{n} log lines from the {parts}": "{parts} kaynağından {n} günlük satırı", + "{n} log line": "{n} log satırı", + "{n} log line from the {parts}": "{parts} kaynağından {n} log satırı", + "{n} log lines": "{n} log satırı", + "{n} log lines from the {parts}": "{parts} kaynağından {n} log satırı", "{n} min ago": "{n} dk önce", - "{n} of this image, newest first": "Bu görüntüden {n} tane, en yenisi önce", + "{n} of this image, newest first": "Bu imajdan {n} tane, en yenisi önce", "{n} of {limit} tunnels in use": "{n} / {limit} tünel kullanımda", "{n} of {total}": "{n} / {total}", "{n} of {total} running": "{n} / {total} çalışıyor", @@ -1608,21 +1608,21 @@ "{n} requests · {size} served": "{n} istek · {size} sunuldu", "{n} result": "{n} sonuç", "{n} results": "{n} sonuç", - "{n} running container": "{n} çalışan kapsayıcı", - "{n} running containers": "{n} çalışan kapsayıcı", + "{n} running container": "{n} çalışan konteyner", + "{n} running containers": "{n} çalışan konteyner", "{n} selected": "{n} seçili", "{n} shared": "{n} paylaşılıyor", "{n} shared · {where}": "{n} paylaşılıyor · {where}", "{n} shared, on {where}": "{n} paylaşılıyor · {where}", "{n} shared, {where}": "{n} paylaşılıyor · {where}", "{n} shown": "{n} gösteriliyor", - "{n} stopped container": "{n} durdurulmuş kapsayıcı", - "{n} stopped containers": "{n} durdurulmuş kapsayıcı", + "{n} stopped container": "{n} durdurulmuş konteyner", + "{n} stopped containers": "{n} durdurulmuş konteyner", "{n} total": "toplam {n}", "{n} variable": "{n} değişken", "{n} variables": "{n} değişken", - "{n} volume": "{n} birim", - "{n} volumes": "{n} birim", + "{n} volume": "{n} volume", + "{n} volumes": "{n} volume", "{n} vulnerabilities in {packages} packages": "{packages} pakette {n} güvenlik açığı", "{n} vulnerability in {packages} packages": "{packages} pakette {n} güvenlik açığı", "{n} with a fix": "{n} tanesinin düzeltmesi var", @@ -1631,7 +1631,7 @@ "{os} settings": "{os} ayarları", "{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.": "{os} otomatik proxy yapılandırma (PAC) dosyası kullanıyor; Kiri bunu izleyemez. Özel'i seçin ve proxy'yi girin.", "{owner} runs this pod": "Bu pod'u çalıştıran: {owner}", - "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}. Görüntüler'de veya Birimler'de listelenmez: docker build'in altyapısıdır.", + "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}. Görüntüler'de veya Volume'ler'de listelenmez: docker build'in altyapısıdır.", "{path} comes first on your PATH, so terminals run it instead of this Kiri. If it's an older Kiri, remove it: rm {path}": "PATH'inizde önce {path} geliyor, bu yüzden terminaller bu Kiri yerine onu çalıştırıyor. Eski bir Kiri ise kaldırın: rm {path}", "{pct}% of this month's cap": "Bu ayki sınırın %{pct} kadarı", "{ports} aren't web ports, so they aren't listed.": "{ports} web portu değil, bu yüzden listelenmiyor.", @@ -1640,7 +1640,7 @@ "{q}{name}{q} can't be a name: names have no spaces or {q}={q}.": "{q}{name}{q} bir ad olamaz: adlarda boşluk veya {q}={q} olamaz.", "{rate} limit": "{rate} sınırı", "{rate}/s limit": "{rate}/sn sınırı", - "{ready} containers": "{ready} kapsayıcı", + "{ready} containers": "{ready} konteyner", "{running} of {all} running": "{running} / {all} çalışıyor", "{running} running · {total}": "{running} çalışıyor · {total}", "{showing} of {all} lines": "{showing} / {all} satır", @@ -1656,7 +1656,7 @@ "{time} ago": "{time} önce", "{time} ago, when the VM's {mem} ran out.": "{time} önce, VM'nin {mem} belleği tükendiğinde.", "{used} of {total}": "{used} / {total}", - "{user} can run containers without sudo": "{user} sudo olmadan kapsayıcı çalıştırabilir", + "{user} can run containers without sudo": "{user} sudo olmadan konteyner çalıştırabilir", "{user}'s sign-in is forgotten on this computer.": "{user} oturumu bu bilgisayarda unutulur.", "{var} sets the {kind} port, so it can't be changed here.": "{var} {kind} portunu belirliyor, bu yüzden burada değiştirilemez.", "{version} available": "{version} kullanılabilir", @@ -1665,7 +1665,7 @@ "{vm} running": "{vm} çalışıyor", "{what}?": "{what}?", "{who} has it. Give {name} another port on this {host}, or stop {holder} first.": "Port şunda: {who}. {name} için bu {host} üzerinde başka bir port verin veya önce şunu durdurun: {holder}.", - "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who} durdu ({when}).{more} Bir rapor düzeltmemize yardımcı olur: yığın izi ve öncesindeki son 200 günlük satırı, ana klasörünüz ve belirteçleriniz silinmiş olarak.", + "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who} durdu ({when}).{more} Bir rapor düzeltmemize yardımcı olur: stack trace ve öncesindeki son 200 log satırı, ana klasörünüz ve token'larınız silinmiş olarak.", "{who} stopped {when}.{more} Crash reports are sent automatically, so this one goes to Kiri too.": "{who} durdu ({when}).{more} Çökme raporları otomatik gönderilir, bu yüzden bu rapor da Kiri'ye gider.", "{why}. Give the VM more memory in Settings → Resources": "{why}. Ayarlar → Kaynaklar'dan VM'ye daha fazla bellek verin", "{zout} smaller · {zin} bigger · {z0} reset": "{zout} küçült · {zin} büyüt · {z0} sıfırla", @@ -1674,7 +1674,7 @@ "– Kiri shares it with your own Linux work": "– Kiri onu kendi Linux çalışmalarınızla paylaşır", "– Not a Linux to use yourself": "– Kendiniz kullanacağınız bir Linux değil", "— the end of the run before the last restart —": "— son yeniden başlatmadan önceki çalıştırmanın sonu —", - "— the log stream ended —": "— günlük akışı sona erdi —", + "— the log stream ended —": "— log akışı sona erdi —", "‹ Back": "‹ Geri", "★ Star on GitHub": "★ GitHub'da yıldız ver", "✓ Installed": "✓ Yüklendi", @@ -1687,12 +1687,12 @@ "Not applied": "Uygulanmadı", "Saved, but the file has an error": "Kaydedildi, ancak dosyada hata var", "Your edits stay here. Apply waits until the file is back.": "Düzenlemeleriniz burada kalır. Uygula, dosya geri gelene kadar bekler.", - "build": "derleme", + "build": "build", "Queue": "Kuyruk", "The file changed outside Kiri since Apply saved it": "Dosya, Uygula onu kaydettiğinden beri Kiri dışında değişti", "Couldn't apply {name}: {error}": "{name} uygulanamadı: {error}", "Saved, not started yet": "Kaydedildi, henüz başlatılmadı", - "image": "görüntü", + "image": "imaj", "Overwrite their changes": "Onların değişikliklerinin üzerine yaz", "Recreating…": "Yeniden oluşturuluyor…", "Service": "Servis", @@ -1713,7 +1713,7 @@ "Apply cancelled. No service was changed.": "Uygulama iptal edildi. Hiçbir servis değişmedi.", "Arrows point at what a service needs; Compose starts those first.": "Oklar bir servisin neye ihtiyaç duyduğunu gösterir; Compose önce onları başlatır.", "Starts on line {n} · click to jump there": "{n}. satırda başlar · oraya gitmek için tıklayın", - "Not in the file any more: stopped and removed. Its volumes stay.": "Artık dosyada yok: durduruldu ve kaldırıldı. Birimleri kalır.", + "Not in the file any more: stopped and removed. Its volumes stay.": "Artık dosyada yok: durduruldu ve kaldırıldı. Volume'leri kalır.", "the file changed outside Kiri": "dosya Kiri dışında değişti", "Overwrite their changes?": "Onların değişikliklerinin üzerine yazılsın mı?", "No Compose projects yet": "Henüz Compose projesi yok", @@ -1727,7 +1727,7 @@ "Zoom out": "Uzaklaştır", "That project is gone": "O proje artık yok", "Couldn't run docker compose: {error}": "docker compose çalıştırılamadı: {error}", - "No logs yet.": "Henüz günlük yok.", + "No logs yet.": "Henüz log yok.", "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "{name} adlı bir proje zaten {dir} içinden çalışıyor. Onu açın veya bu dosyaya kendi name: satırını verin.", "{n} needs it": "{n} servis buna ihtiyaç duyuyor", "File": "Dosya", @@ -1746,7 +1746,7 @@ "docker compose up stopped": "docker compose up durdu", "Applying…": "Uygulanıyor…", "Cache": "Önbellek", - "New service from {image}.": "{image} görüntüsünden yeni servis.", + "New service from {image}.": "{image} imajından yeni servis.", "{n} new": "{n} yeni", "Apply cancelled. {n} services had already changed; the rest were not changed.": "Uygulama iptal edildi. {n} servis zaten değişmişti; diğerleri değiştirilmedi.", "Compose rejects this file: YAML error on line {n}": "Compose bu dosyayı reddediyor: {n}. satırda YAML hatası", @@ -1775,7 +1775,7 @@ "Recreate": "Yeniden oluştur", "Applied {name}, but {svc} stopped": "{name} uygulandı, ama {svc} durdu", "Web": "Web", - "See its logs": "Günlüklerine bak", + "See its logs": "Loglarına bak", "Remove from the list": "Listeden kaldır", "Compose rejects this file. A required variable may not be set: {name}.": "Compose bu dosyayı reddediyor. Gerekli bir değişken ayarlanmamış olabilir: {name}.", "environment": "ortam", @@ -1806,7 +1806,7 @@ "YAML files": "YAML dosyaları", "{n} service": "{n} servis", "{name} are used in a name or folder path. Docker shows those in plain text.": "{name} bir adda veya klasör yolunda kullanılıyor. Docker bunları düz metin olarak gösterir.", - "Its logs, Start, Stop and Remove still work.": "Günlükleri, Başlat, Durdur ve Kaldır hâlâ çalışır.", + "Its logs, Start, Stop and Remove still work.": "Logları, Başlat, Durdur ve Kaldır hâlâ çalışır.", "Showing the file as edited, not applied yet.": "Dosya düzenlendiği haliyle gösteriliyor, henüz uygulanmadı.", "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "Henüz bir şey yok: dosya çalışanla aynı. Değiştirdiğinizde burada her servise ne olacağı listelenir.", "Kiri can't read the compose file: {error}": "Kiri compose dosyasını okuyamıyor: {error}", @@ -1830,28 +1830,28 @@ "Open project": "Projeyi aç", "not started": "başlatılmadı", "Apply the compose file to create it": "Oluşturmak için compose dosyasını uygula", - "Hide {name}'s containers": "{name} kapsayıcılarını gizle", - "Show {name}'s containers": "{name} kapsayıcılarını göster", + "Hide {name}'s containers": "{name} konteynerlerini gizle", + "Show {name}'s containers": "{name} konteynerlerini göster", "Hide {name}'s pods": "{name} pod'larını gizle", "Show {name}'s pods": "{name} pod'larını göster", "{n} more in a Compose project": "Bir Compose projesinde {n} tane daha", "{n} more in Compose projects": "Compose projelerinde {n} tane daha", - "Your only container is in a Compose project": "Tek kapsayıcınız bir Compose projesinde", - "All {n} containers are in Compose projects": "{n} kapsayıcının tümü Compose projelerinde", + "Your only container is in a Compose project": "Tek konteyneriniz bir Compose projesinde", + "All {n} containers are in Compose projects": "{n} konteynerin tümü Compose projelerinde", "Skipped until Kiri next opens": "Kiri bir sonraki açılışına kadar atlandı", - "Couldn't add the kiri docker context": "docker için kiri bağlamı eklenemedi", + "Couldn't add the kiri docker context": "docker için kiri context'i eklenemedi", "The kiri and docker commands": "kiri ve docker komutları", "Ready in any new terminal": "Her yeni terminalde hazır", - "Couldn't add them to your shell": "Kabuğunuza eklenemedi", + "Couldn't add them to your shell": "Shell'inize eklenemedi", "Starts at login": "Oturum açılınca başlar", - "The engine starts when you log in": "Oturum açtığınızda motor başlar", - "The engine runs from the app for now": "Motor şimdilik uygulamadan çalışıyor", - "Show log": "Günlüğü göster", + "The engine starts when you log in": "Oturum açtığınızda Engine başlar", + "The engine runs from the app for now": "Engine şimdilik uygulamadan çalışıyor", + "Show log": "Log'u göster", "Continue anyway": "Yine de devam et", "One step didn't work. Everything else is ready.": "Bir adım çalışmadı. Geri kalan her şey hazır.", "Some steps didn't work. Everything else is ready.": "Bazı adımlar çalışmadı. Geri kalan her şey hazır.", "No matches": "Eşleşme yok", - "Disk image size": "Disk görüntüsü boyutu", + "Disk image size": "Disk imajı boyutu", "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_CPUS, KIRI_MEMORY_MIB veya KIRI_DISK_GB ayarlı ve bunlar buradakilerden önceliklidir.", "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Şu anda {cpus}, en fazla {mem} ve {disk} disk ile çalışıyor.", "No other WSL distros installed.": "Başka WSL dağıtımı kurulu değil.", @@ -1861,27 +1861,27 @@ "Hide: the window stays ready and opens again at once.": "Gizle: pencere hazır bekler ve hemen yeniden açılır.", "Start Kiri at sign-in": "Oturum açıldığında Kiri'yi başlat", "Start Kiri in the background when you sign in.": "Oturum açtığınızda Kiri'yi arka planda başlatır.", - "Stop the engine when Kiri quits": "Kiri'den çıkıldığında motoru durdur", - "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri'den çıkmak çalışan kapsayıcıları ve motoru durdurur. Kiri'yi açmak onu yeniden başlatır.", - "{env} is set, so docker uses another engine instead of {app}": "{env} ayarlı olduğundan docker, {app} yerine başka bir motor kullanıyor", - "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} ayarlı olduğundan {docker}, {app} yerine başka bir motor kullanıyor. {app} kullanmak için kabuğunuzdan kaldırın.", + "Stop the engine when Kiri quits": "Kiri'den çıkıldığında Engine'i durdur", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri'den çıkmak çalışan konteynerleri ve Engine'i durdurur. Kiri'yi açmak onu yeniden başlatır.", + "{env} is set, so docker uses another engine instead of {app}": "{env} ayarlı olduğundan docker, {app} yerine başka bir Engine kullanıyor", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} ayarlı olduğundan {docker}, {app} yerine başka bir Engine kullanıyor. {app} kullanmak için shell'inizden kaldırın.", "{env} is set": "{env} ayarlı", - "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} bu oturumda docker bağlamını geçersiz kıldığı için bağlam değiştirmek {docker} komutunu {app} hedefine yönlendirmez. {cmd} ile temizleyin veya profilinizden kaldırın.", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} bu oturumda docker bağlamını geçersiz kıldığı için context değiştirmek {docker} komutunu {app} hedefine yönlendirmez. {cmd} ile temizleyin veya profilinizden kaldırın.", "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path}, {app} uygulamasına gider. Testcontainers, IDE eklentileri ve SDK’ler gibi araçlar doğrudan bunu kullanır.", - "another engine": "başka bir motor", - "{path} belongs to {engine} and stays so.": "{path}, {engine} motoruna aittir ve öyle kalır.", + "another engine": "başka bir Engine", + "{path} belongs to {engine} and stays so.": "{path}, {engine} Engine'ine aittir ve öyle kalır.", "Tools that ignore docker contexts can use {hint}": "docker bağlamlarını yok sayan araçlar {hint} kullanabilir", "command": "komut", "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} boş. docker bağlamlarını yok sayan araçların {app} bulabilmesi için bunu {app} ile bağlayın.", - "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} boş. Başka bir Docker motoru çalışmadığında {app} her çalıştığında sunar.", - "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} boş. Başka bir Docker motoru kullanmadığında Kiri başlatılırken {service} bunu bağlar.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} boş. Başka bir Docker Engine'i çalışmadığında {app} her çalıştığında sunar.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} boş. Başka bir Docker Engine'i kullanmadığında Kiri başlatılırken {service} bunu bağlar.", "{path} is free. {app} leaves it for the installed Kiri.": "{path} boş. {app} bunu kurulu Kiri için bırakır.", "Linking…": "Bağlanıyor…", "Use {app}": "{app} kullan", "Free": "Boş", "Docker socket": "Docker soketi", "The {docker} command uses {app}.": "{docker} komutu {app} kullanıyor.", - "{env} is set in this session, so {docker} uses another engine.": "Bu oturumda {env} ayarlı, bu yüzden {docker} başka bir motor kullanıyor.", + "{env} is set in this session, so {docker} uses another engine.": "Bu oturumda {env} ayarlı, bu yüzden {docker} başka bir Engine kullanıyor.", "The {docker} command uses {engine}.": "{docker} komutu {engine} kullanıyor.", "Switching…": "Geçiliyor…", "{docker} command": "{docker} komutu", @@ -1891,7 +1891,7 @@ "Copying data…": "Veriler kopyalanıyor…", "Verifying copy…": "Kopya doğrulanıyor…", "Switching storage…": "Depolama değiştiriliyor…", - "Restarting engine…": "Motor yeniden başlatılıyor…", + "Restarting engine…": "Engine yeniden başlatılıyor…", "Moving data…": "Veriler taşınıyor…", "Storage location unavailable": "Depolama konumu kullanılamıyor", "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri verilerini {path} konumunda bulamadı. Sürücüyü bağlayıp yeniden deneyin, başka bir klasör seçin veya varsayılan konuma sıfırlayın.", @@ -1910,21 +1910,21 @@ "Remove old data": "Eski verileri kaldır", "Storage location": "Depolama konumu", "{var} sets Kiri's storage location, so it can't be changed here.": "{var}, Kiri'nin depolama konumunu belirlediğinden burada değiştirilemez.", - "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "İmajlar, konteynerler ve birimler bu klasörde bulunur. Harici sürücüler yerel bir dosya sistemi kullanmalıdır (macOS'te APFS, Linux'ta ext4/xfs/btrfs, Windows'ta NTFS); FAT ve exFAT sürücüleri desteklenmez.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "İmajlar, konteynerler ve volume'ler bu klasörde bulunur. Harici sürücüler yerel bir dosya sistemi kullanmalıdır (macOS'te APFS, Linux'ta ext4/xfs/btrfs, Windows'ta NTFS); FAT ve exFAT sürücüleri desteklenmez.", "Reset storage location to default?": "Depolama konumu varsayılana sıfırlansın mı?", "Change storage location?": "Depolama konumu değiştirilsin mi?", "Destination: {path} ({free} free).": "Hedef: {path} ({free} boş).", "Destination: {path}.": "Hedef: {path}.", "Existing Kiri data in this folder will be replaced.": "Bu klasördeki mevcut Kiri verileri değiştirilecektir.", "Migration mode": "Taşıma modu", - "Move existing images, containers, and volumes": "Mevcut imajları, konteynerleri ve birimleri taşı", + "Move existing images, containers, and volumes": "Mevcut imajları, konteynerleri ve volume'leri taşı", "Stops running containers, copies your data, and starts them again.": "Çalışan konteynerleri durdurur, verilerinizi kopyalar ve yeniden başlatır.", "Start fresh": "Sıfırdan başla", "Starts empty in the new folder. Your old folder stays until you remove it.": "Yeni klasörde boş olarak başlar. Eski klasörünüz siz kaldırana kadar kalır.", - "Kiri will switch to this folder and restart the engine.": "Kiri bu klasöre geçecek ve motoru yeniden başlatacaktır.", + "Kiri will switch to this folder and restart the engine.": "Kiri bu klasöre geçecek ve Engine'i yeniden başlatacaktır.", "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri verilerinizi taşırken çalışan konteynerler durdurulur ve işlem bittiğinde yeniden başlatılır.", "Move data": "Verileri taşı", - "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri varsayılan klasöre dönecek ve motoru yeniden başlatacaktır. Bağlı olmayan sürücüdeki veriler silinmez.", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri varsayılan klasöre dönecek ve Engine'i yeniden başlatacaktır. Bağlı olmayan sürücüdeki veriler silinmez.", "Remove old data?": "Eski veriler kaldırılsın mı?", "Everything in {path} will be deleted for good.": "{path} konumundaki her şey kalıcı olarak silinecek.", "Choose a storage folder": "Depolama klasörü seçin", @@ -1933,29 +1933,29 @@ "Storage is available again": "Depolama yeniden kullanılabilir", "Old data removed": "Eski veriler kaldırıldı", "A proxy on this computer is reached as {host}.": "Bu bilgisayardaki bir proxy'ye şu adresle erişilir: {host}.", - "VPNs need no setting: container traffic leaves through Linux.": "VPN'ler ayar gerektirmez: kapsayıcı trafiği Linux üzerinden çıkar.", - "Shared with Linux: containers only use them while busy.": "Linux ile paylaşılır: kapsayıcılar bunları yalnızca meşgulken kullanır.", - "The most containers and the engine may take. Unused memory stays free on Linux.": "Kapsayıcıların ve motorun alabileceği en fazla bellek. Kullanılmayan bellek Linux'ta boş kalır.", - "The engine is off; it starts with these next time.": "Motor kapalı; bir sonraki sefer bunlarla başlar.", - "Restart engine to apply": "Uygulamak için motoru yeniden başlat", + "VPNs need no setting: container traffic leaves through Linux.": "VPN'ler ayar gerektirmez: konteyner trafiği Linux üzerinden çıkar.", + "Shared with Linux: containers only use them while busy.": "Linux ile paylaşılır: konteynerler bunları yalnızca meşgulken kullanır.", + "The most containers and the engine may take. Unused memory stays free on Linux.": "Konteynerlerin ve Engine'in alabileceği en fazla bellek. Kullanılmayan bellek Linux'ta boş kalır.", + "The engine is off; it starts with these next time.": "Engine kapalı; bir sonraki sefer bunlarla başlar.", + "Restart engine to apply": "Uygulamak için Engine'i yeniden başlat", "Windows bind-mount file events": "Windows bağlama noktası dosya olayları", - "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "Canlı yenileme için Windows sürücülerindeki ({path} gibi) dosya değişikliklerini kapsayıcılara iletir. Boştayken CPU kullanmaz.", + "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "Canlı yenileme için Windows sürücülerindeki ({path} gibi) dosya değişikliklerini konteynerlere iletir. Boştayken CPU kullanmaz.", "One text file, redacted, saved to your Desktop. Read it before you share it.": "Masaüstünüze kaydedilen, hassas bilgileri ayıklanmış tek bir metin dosyası. Paylaşmadan önce okuyun.", "The 5 newest crash reports for Kiri": "Kiri için en yeni 5 çökme raporu", "Kiri and this PC": "Kiri ve bu PC", "Kiri and this computer": "Kiri ve bu bilgisayar", - "Versions, {os}, whether the engine runs, how many containers and images": "Sürümler, {os}, motorun çalışıp çalışmadığı, kapsayıcı ve görüntü sayısı", - "Saved. The engine uses these from its next start": "Kaydedildi. Motor bunları bir sonraki başlatmada kullanır", + "Versions, {os}, whether the engine runs, how many containers and images": "Sürümler, {os}, Engine'in çalışıp çalışmadığı, konteyner ve imaj sayısı", + "Saved. The engine uses these from its next start": "Kaydedildi. Engine bunları bir sonraki başlatmada kullanır", "5 min": "5 dk", "10 min": "10 dk", "30 min": "30 dk", "Never": "Asla", - "Build cache limit": "Derleme önbelleği sınırı", + "Build cache limit": "Build önbelleği sınırı", "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit önbelleği bu boyutu aştığında en eski önbellek katmanları otomatik olarak temizlenir.", - "Stop builder when idle": "Boştayken derleyiciyi durdur", - "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Boştayken bellek kullanmaması için derlemeler arasında BuildKit'i durdurur; sonraki derleme bir saniyeden kısa sürede uyandırır.", + "Stop builder when idle": "Boştayken builder'ı durdur", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Boştayken bellek kullanmaması için build'ler arasında BuildKit'i durdurur; sonraki build bir saniyeden kısa sürede uyandırır.", "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Daemon için KIRI_BUILD_CACHE_GB veya KIRI_BUILDER_IDLE_SECS ayarlı ve bunlar buradakilerden önceliklidir.", - "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: en hızlısı. Cloudflare WARP veya kurumsal bir güvenlik duvarı kapsayıcı HTTPS trafiğini engelliyorsa Ana makine aktarımı'na geçin. VM yeniden başlatıldığında uygulanır.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: en hızlısı. Cloudflare WARP veya kurumsal bir güvenlik duvarı konteyner HTTPS trafiğini engelliyorsa Ana makine aktarımı'na geçin. VM yeniden başlatıldığında uygulanır.", "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Ana makine aktarımı: bağlantılar Virtualization.framework NAT yerine macOS üzerindeki Kiri üzerinden çıkar. VM yeniden başlatıldığında uygulanır.", "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Ortamda KIRI_SHARED_NAT ayarlı ve önceliklidir.", "Outbound VM traffic": "Giden VM trafiği", @@ -1964,12 +1964,12 @@ "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM diskinin büyüyebileceği en fazla boyut. {os} üzerinde alan yalnızca veri yazıldıkça kullanılır; kullanılmayan alan {storage} bölümünden geri kazanılabilir. Yeniden başlatmada uygulanır.", "Settings → Storage": "Ayarlar → Depolama", "VM disk space": "VM disk alanı", - "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Yerel Linux doğrudan ana bilgisayar dosya sistemini kullanır — silinen görüntüler ve birimler alanı anında boşaltır.", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Yerel Linux doğrudan host dosya sistemini kullanır — silinen imajlar ve volume'ler alanı anında boşaltır.", "Compact disk…": "Diski sıkıştır…", "Reclaim space": "Alanı geri kazan", "Compacting…": "Sıkıştırılıyor…", "Reclaiming…": "Geri kazanılıyor…", - "Compacting {vhdx} and restarting the engine…": "{vhdx} sıkıştırılıyor ve motor yeniden başlatılıyor…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} sıkıştırılıyor ve Engine yeniden başlatılıyor…", "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · kullanılmayan bloklar kırpılıyor…", "Trimming unused blocks inside the VM disk…": "VM diski içindeki kullanılmayan bloklar kırpılıyor…", "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · {freed}.", @@ -1978,24 +1978,24 @@ "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · geri kazanılacak alan yok.", "Nothing to reclaim.": "Geri kazanılacak alan yok.", "{size} can be given back": "{size} geri verilebilir", - "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · {can}. Sıkıştırma motoru yeniden başlatır.", - "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · kapsayıcıları durdurmadan {can}.", - "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows üzerinde {host} ({vhdx}). Sıkıştırma kullanılmayan alanı geri verir ve motoru yeniden başlatır.", - "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} üzerinde {host}. Geri kazanma, kapsayıcıları durdurmadan VM diskindeki kullanılmayan blokları kırpar.", - "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} içindeki kullanılmayan alanı Windows'a geri verir. Sıkıştırma motoru yeniden başlatır.", - "Returns unused blocks in the VM disk to {os} without stopping containers.": "VM diskindeki kullanılmayan blokları kapsayıcıları durdurmadan {os} sistemine geri verir.", - "Cleaning up stopped containers, untagged images, and build cache…": "Durdurulmuş kapsayıcılar, etiketsiz görüntüler ve derleme önbelleği temizleniyor…", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows üzerinde {host} ({vhdx}), {inUse} kullanımda · {can}. Sıkıştırma Engine'i yeniden başlatır.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} üzerinde {host}, VM içinde {inUse} kullanımda · konteynerleri durdurmadan {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows üzerinde {host} ({vhdx}). Sıkıştırma kullanılmayan alanı geri verir ve Engine'i yeniden başlatır.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} üzerinde {host}. Geri kazanma, konteynerleri durdurmadan VM diskindeki kullanılmayan blokları kırpar.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} içindeki kullanılmayan alanı Windows'a geri verir. Sıkıştırma Engine'i yeniden başlatır.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "VM diskindeki kullanılmayan blokları konteynerleri durdurmadan {os} sistemine geri verir.", + "Cleaning up stopped containers, untagged images, and build cache…": "Durdurulmuş konteynerler, etiketsiz görüntüler ve build önbelleği temizleniyor…", "{count} ({size})": "{count} ({size})", - "build cache": "derleme önbelleği", - "No stopped containers, untagged images or build cache · {freed}.": "Durdurulmuş kapsayıcı, etiketsiz görüntü veya derleme önbelleği yok · {freed}.", - "No stopped containers, untagged images or build cache.": "Durdurulmuş kapsayıcı, etiketsiz görüntü veya derleme önbelleği yok.", + "build cache": "build önbelleği", + "No stopped containers, untagged images or build cache · {freed}.": "Durdurulmuş konteyner, etiketsiz imaj veya build önbelleği yok · {freed}.", + "No stopped containers, untagged images or build cache.": "Durdurulmuş konteyner, etiketsiz imaj veya build önbelleği yok.", "Cleaning up…": "Temizleniyor…", "Clean up…": "Temizle…", "Unused Docker data": "Kullanılmayan Docker verileri", - "Command-line tools in shell": "Kabukta komut satırı araçları", + "Command-line tools in shell": "Shell'de komut satırı araçları", "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Yeni terminallerde {docker}, {kubectl} ve {kiri} komutlarının çalışması için {zshrc} ve {zprofile} dosyalarına {bin} ekleyin.", "Uninstall Kiri": "Kiri'yi kaldır", - "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Motoru durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve kabuk profili kayıtlarını kaldırır ve önceki Docker bağlamınızı ({cmd}) geri yükler.", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Engine'i durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve shell profili kayıtlarını kaldırır ve önceki Docker context'inizi ({cmd}) geri yükler.", "Uninstall Kiri…": "Kiri'yi kaldır…", "Couldn't reclaim disk space: {error}": "Disk alanı geri kazanılamadı: {error}", "Reclaimed {size} on {os}": "{os} üzerinde {size} geri kazanıldı", @@ -2004,36 +2004,36 @@ "Cleaned up {size} of unused Docker data": "{size} kullanılmayan Docker verisi temizlendi", "Cleaned up unused Docker data": "Kullanılmayan Docker verileri temizlendi", "Compact WSL disk?": "WSL diski sıkıştırılsın mı?", - "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} dosyasını sıkıştırmak kullanılmayan alanı Windows'a geri verir ve Kiri motorunu ve çalışan kapsayıcıları kısa süreliğine yeniden başlatır.", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} dosyasını sıkıştırmak kullanılmayan alanı Windows'a geri verir ve Kiri Engine'ini ve çalışan konteynerleri kısa süreliğine yeniden başlatır.", "Compact disk": "Diski sıkıştır", "Clean up unused Docker data?": "Kullanılmayan Docker verileri temizlensin mi?", - "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Durdurulmuş kapsayıcıları, etiketsiz görüntüleri ve BuildKit derleme önbelleğini kaldırır. Çalışan kapsayıcılar ve etiketli görüntüler korunur.", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Durdurulmuş konteynerleri, etiketsiz görüntüleri ve BuildKit build önbelleğini kaldırır. Çalışan konteynerler ve etiketli görüntüler korunur.", "Clean up": "Temizle", "Uninstall Kiri?": "Kiri kaldırılsın mı?", - "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Motoru durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve kabuk profili kayıtlarını kaldırır ve önceki Docker bağlamınızı geri yükler. Görüntüleriniz ve birimleriniz siz silene kadar Kiri'nin veri klasöründe kalır.", - "Cluster": "Küme", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Engine'i durdurur, Kiri'nin arka plan servisini, CLI bağlantılarını ve shell profili kayıtlarını kaldırır ve önceki Docker context'inizi geri yükler. Görüntüleriniz ve volume'leriniz siz silene kadar Kiri'nin veri klasöründe kalır.", + "Cluster": "Cluster", "default": "varsayılan", "k3s version": "k3s sürümü", - "Image version for the cluster node ({cmd}). Applies when recreated.": "Küme düğümü için görüntü sürümü ({cmd}). Yeniden oluşturulduğunda uygulanır.", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Cluster node'u için imaj sürümü ({cmd}). Yeniden oluşturulduğunda uygulanır.", "Extra server flags": "Ek sunucu bayrakları", "Passed to {srv} ({flag}), separated by spaces.": "Boşluklarla ayrılarak {srv} komutuna ({flag}) iletilir.", "Startup manifests": "Başlangıç manifestleri", - "YAML files in {path} are applied whenever the cluster starts.": "{path} içindeki YAML dosyaları küme her başladığında uygulanır.", + "YAML files in {path} are applied whenever the cluster starts.": "{path} içindeki YAML dosyaları cluster her başladığında uygulanır.", "Open folder": "Klasörü aç", - "{n} untagged image": "{n} etiketsiz görüntü", - "{n} untagged images": "{n} etiketsiz görüntü", + "{n} untagged image": "{n} etiketsiz imaj", + "{n} untagged images": "{n} etiketsiz imaj", "Uninstall Kiri from Windows Settings → Apps": "Kiri'yi Windows Ayarları → Uygulamalar'dan kaldırın", - "Builder settings saved": "Derleyici ayarları kaydedildi", - "Could not save builder settings: {error}": "Derleyici ayarları kaydedilemedi: {error}", + "Builder settings saved": "Builder ayarları kaydedildi", + "Could not save builder settings: {error}": "Builder ayarları kaydedilemedi: {error}", "Disk reclaim is already running": "Disk alanı geri kazanma işlemi zaten çalışıyor", "Outbound VM traffic setting saved. Restart the VM to apply.": "Giden VM trafiği ayarı kaydedildi. Uygulamak için VM'yi yeniden başlatın.", "Could not save VM networking setting: {error}": "VM ağ ayarı kaydedilemedi: {error}", - "Added Kiri command-line tools to shell profiles": "Kiri komut satırı araçları kabuk profillerine eklendi", - "Removed Kiri command-line tools from shell profiles": "Kiri komut satırı araçları kabuk profillerinden kaldırıldı", - "Could not update shell profiles: {error}": "Kabuk profilleri güncellenemedi: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri komut satırı araçları shell profillerine eklendi", + "Removed Kiri command-line tools from shell profiles": "Kiri komut satırı araçları shell profillerinden kaldırıldı", + "Could not update shell profiles: {error}": "Shell profilleri güncellenemedi: {error}", "Uninstalling Kiri…": "Kiri kaldırılıyor…", "Could not uninstall Kiri: {error}": "Kiri kaldırılamadı: {error}", "Uninstall Kiri using your system package manager": "Kiri'yi sistem paket yöneticinizi kullanarak kaldırın", "Swap": "Takas (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM'nin belleği tükendiğinde kullanabileceği disk alanı; böylece kapsayıcılar durdurulmak yerine yavaşlar. Yeniden başlatınca uygulanır." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM'nin belleği tükendiğinde kullanabileceği disk alanı; böylece konteynerler durdurulmak yerine yavaşlar. Yeniden başlatınca uygulanır." } From 1c083755ee3ff665afbfc1b45ec35d3828a8729f Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 01:10:25 +0100 Subject: [PATCH 138/157] Release 0.2.3 polish: VM disk reclaim overhead, uniform Pod logs, Mac menu & Linux speed (#776) Fixes macOS VM disk reclaim accounting for ext4 static metadata overhead, shares the numbered log console component with Kubernetes Pod logs, strips native AppKit WKWebView menus on macOS, optimizes Linux container creation/startup hot paths, and adds the head-to-head Kiri vs Docker Linux benchmark workflow (Closes #776). --- .github/workflows/benchmark.yml | 63 ++++ crates/kiri-init/src/linux/agent.rs | 6 + crates/kiri-init/src/linux/container.rs | 123 +++++-- crates/kiri-init/src/linux/hostopts.rs | 81 +++-- crates/kiri-init/src/linux/net.rs | 103 ++++-- crates/kiri-init/src/linux/netlink.rs | 56 +++- crates/kiri-init/src/linux/relay.rs | 2 + crates/kiri-init/src/linux/sys.rs | 12 + crates/kiri-init/src/linux/trim.rs | 10 +- crates/kiri/src/daemon/access.rs | 10 + crates/kiri/src/daemon/storage.rs | 184 ++++++++++- crates/kiri/src/daemon/vmlink.rs | 23 +- crates/kiri/src/ui/index.html | 159 ++++----- crates/kiri/src/ui/mac.rs | 41 ++- scripts/bench-linux-docker.py | 411 ++++++++++++++++++++++++ tests/ui/podlogs.js | 79 +++++ 16 files changed, 1164 insertions(+), 199 deletions(-) create mode 100644 .github/workflows/benchmark.yml create mode 100755 scripts/bench-linux-docker.py create mode 100644 tests/ui/podlogs.js diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml new file mode 100644 index 000000000..c7deaf7b4 --- /dev/null +++ b/.github/workflows/benchmark.yml @@ -0,0 +1,63 @@ +# Head-to-head Linux benchmark comparing Kiri Engine against Docker Engine +# (`dockerd`) on the same runner (#776): ephemeral alpine lifecycle, multi-layer +# PHP app cold start & warm restart, container exec, 1,000-file bind-mount I/O, +# published-port HTTP latency, teardown, and engine RSS. +name: Linux Benchmark + +on: + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: linux-benchmark-${{ github.ref }} + cancel-in-progress: false + +jobs: + linux-benchmark: + name: Kiri vs Docker (Linux) + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build static Linux engine + run: | + mkdir -p "$RUNNER_TEMP/bin" + docker run --rm -v "$PWD:/src" -v "$RUNNER_TEMP/bin:/out" \ + -w /src -e CARGO_TARGET_DIR=/tmp/target rust:1-alpine sh -c \ + 'apk add -q musl-dev && cargo build --release --locked -p kiri -p kiri-init && cp /tmp/target/release/kiri /tmp/target/release/kiri-init /out/' + - name: Run head-to-head Kiri vs Docker benchmark + env: + VERSION: ${{ github.event.release.tag_name || github.sha }} + run: | + set -eu + WORK="$RUNNER_TEMP/vs-docker" + mkdir -p "$WORK/data" "$WORK/run" + sudo env KIRI_DATA_DIR="$WORK/data" \ + KIRI_SOCKET="$WORK/run/docker.sock" KIRI_HTTP_PORT=18080 KIRI_HTTPS_PORT=18443 \ + "$RUNNER_TEMP/bin/kiri" daemon >"$WORK/daemon.log" 2>&1 & + KIRI_PID=$! + trap 'sudo kill -TERM $KIRI_PID 2>/dev/null || true' EXIT + for _ in $(seq 1 100); do + [ -S "$WORK/run/docker.sock" ] && break + sleep 0.2 + done + sudo python3 scripts/bench-linux-docker.py \ + --docker-sock /var/run/docker.sock \ + --kiri-sock "$WORK/run/docker.sock" \ + --kiri-pid "$KIRI_PID" \ + --version "${VERSION}" \ + --out "$WORK/benchmark.json" \ + --report "$WORK/report.md" + cat "$WORK/report.md" >> "$GITHUB_STEP_SUMMARY" + - name: Upload benchmark results + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: linux-benchmark-results + path: ${{ runner.temp }}/vs-docker/benchmark.json diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 522531fb3..413478b05 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -55,12 +55,18 @@ type FileStamp = Option<(u64, u64, i64, i64)>; #[derive(Default)] struct HostDns { stamp: Option<[FileStamp; 2]>, + checked_at: Option, servers: Vec<[u8; 4]>, } impl HostDns { fn get(&mut self) -> &[[u8; 4]] { use std::os::unix::fs::MetadataExt; + let now_inst = std::time::Instant::now(); + if self.checked_at.is_some_and(|t| now_inst.saturating_duration_since(t) < std::time::Duration::from_millis(250)) { + return &self.servers; + } + self.checked_at = Some(now_inst); let stat = |p: &str| std::fs::metadata(p).ok().map(|m| (m.ino(), m.len(), m.mtime(), m.mtime_nsec())); let now = [stat("/etc/resolv.conf"), stat("/run/systemd/resolve/resolv.conf")]; if self.stamp != Some(now) { diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index e3384058b..3b9c8e014 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -590,10 +590,10 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

> = std::sync::OnceLock::new(); if !had_ping - && let Ok(map) = fs::read_to_string("/proc/self/gid_map") + && let Some(max) = *SELF_PING_MAX.get_or_init(|| fs::read_to_string("/proc/self/gid_map").ok().map(|m| ping_group_max(&m))) { - let max = ping_group_max(&map); if max < DEFAULT_PING_MAX && let Some(s) = host.sysctls.iter_mut().find(|s| s.path == "net/ipv4/ping_group_range") { @@ -616,9 +616,16 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

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

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

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

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

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

f, + None => { + opened = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + &opened } - Ok(()) - }) + }; + net.dns.serve_in(ns, pid, spec.net.bridge)?; + // User networks it joins once it runs: their names + // answer from its first lookup (#449). + for b in net_opts::values(spec.net.opts, net_opts::DNS_BRIDGE) { + net.dns.serve_in(ns, pid, b)?; + } + Ok(()) }); if let Some(e) = in_err { net.dns.drop_container(pid); @@ -837,7 +856,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

io::Error { pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writable: bool) -> io::Result { valid_id(id)?; let base = paths.containers.join(id); - if writable + let fresh_base = !base.exists(); + if !fresh_base + && writable && let Some(kind) = sys::detect_readonly_fs(&base) { return Err(sys::readonly_storage_error(kind)); } let (upper, work, rootfs) = (base.join("upper"), base.join("work"), base.join("rootfs")); - let _ = sys::umount_lazy(&rootfs); - for d in [&upper, &work, &rootfs] { - if !d.is_dir() { + if fresh_base { + for d in [&upper, &work, &rootfs] { fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?; } + } else { + let _ = sys::umount_lazy(&rootfs); + for d in [&upper, &work, &rootfs] { + if !d.is_dir() { + fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?; + } + } } // Lower dirs are relative to the agent's working directory (the layer // store), which keeps the option string short enough for many layers. @@ -1001,14 +1028,33 @@ pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writa } lower.push(empty.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "container folder is not UTF-8"))?.to_owned()); } - let plain = plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))?; + let plain = if fresh_base { + match fs::write(base.join(PLAIN_UPPER), b"") { + Ok(()) => true, + Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => true, + Err(e) => return Err(map_rofs_error(&base, writable, e)), + } + } else { + plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))? + }; let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain)); sys::mount_overlay(&rootfs, &lower, &rest, 0).map_err(|e| map_rofs_error(&base, writable, e))?; - if writable - && let Err(e) = ensure_writable_rootfs(&base, &rootfs) - { - super::roots::unmount(&rootfs); - return Err(e); + if writable { + let ro_err = if fresh_base { + // `create_dir_all` already verified `base` is writable; one `statvfs` + // on `rootfs` catches overlayfs's silent read-only fallback (#768). + if sys::is_statvfs_readonly(&rootfs).unwrap_or(false) { + ensure_writable_rootfs(&base, &rootfs).err() + } else { + None + } + } else { + ensure_writable_rootfs(&base, &rootfs).err() + }; + if let Some(e) = ro_err { + super::roots::unmount(&rootfs); + return Err(e); + } } Ok(rootfs) } @@ -1041,8 +1087,13 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile let (parent_io, child_io) = stdio(&prepared)?; // The child waits here until the agent has moved it into its cgroup, for // a start that clone3 could not place there itself. - let (child_cgroup_ready, cgroup_go) = sys::pipe()?; - prepared.cgroup_ready = Some(child_cgroup_ready); + let cgroup_go = if sys::clone3_works() { + None + } else { + let (child_cgroup_ready, go_fd) = sys::pipe()?; + prepared.cgroup_ready = Some(child_cgroup_ready); + Some(go_fd) + }; let args = CloneArgs { flags: CLONE_INTO_CGROUP, exit_signal: libc::SIGCHLD as u64, @@ -1093,7 +1144,9 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile if !child.into_cgroup { // clone(2) cannot put the exec in the container's cgroup: do it now, // then let it join the container's namespaces. - if let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, &cgroup_go) { + if let Some(go_fd) = &cgroup_go + && let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, go_fd) + { // SAFETY: killing and reaping the child we just cloned. unsafe { libc::kill(pid, libc::SIGKILL); diff --git a/crates/kiri-init/src/linux/hostopts.rs b/crates/kiri-init/src/linux/hostopts.rs index 020d93a9c..2c2d56e52 100644 --- a/crates/kiri-init/src/linux/hostopts.rs +++ b/crates/kiri-init/src/linux/hostopts.rs @@ -221,46 +221,85 @@ pub fn add_net_defaults(sysctls: &mut Vec) { sysctls.splice(0..0, mine); } +thread_local! { + static OWN_NS: std::cell::RefCell<[Option<(fs::File, (u64, u64))>; 3]> = const { std::cell::RefCell::new([None, None, None]) }; +} + +fn own_ns_entry(ns: Ns) -> io::Result<(std::os::fd::RawFd, (u64, u64))> { + let (slot, name) = match ns { + Ns::Net => (0, "net"), + Ns::Ipc => (1, "ipc"), + Ns::Uts => (2, "uts"), + }; + OWN_NS.with(|arr| { + let mut arr = arr.borrow_mut(); + if let Some((f, id)) = &arr[slot] { + return Ok((f.as_raw_fd(), *id)); + } + let f = fs::File::open(format!("/proc/self/ns/{name}"))?; + let m = f.metadata()?; + let id = (m.dev(), m.ino()); + let raw = f.as_raw_fd(); + arr[slot] = Some((f, id)); + Ok((raw, id)) + }) +} + /// Writes the sysctls from the agent, inside the container's namespaces: /// /proc/sys shows the calling task's network, IPC and UTS namespace, so /// the agent joins the one each key belongs to, writes, and comes back. /// Runs after the network is set up, so per-interface keys (eth0) exist. -pub fn apply_sysctls(pid: libc::pid_t, sysctls: &[Sysctl]) -> io::Result<()> { - for s in sysctls { - let (name, kind) = match s.ns { +pub fn apply_sysctls(pid: libc::pid_t, netns: Option<&fs::File>, sysctls: &[Sysctl]) -> io::Result<()> { + let mut i = 0; + while i < sysctls.len() { + let ns = sysctls[i].ns; + let mut end = i + 1; + while end < sysctls.len() && sysctls[end].ns == ns { + end += 1; + } + let (name, kind) = match ns { Ns::Net => ("net", libc::CLONE_NEWNET), Ns::Ipc => ("ipc", libc::CLONE_NEWIPC), Ns::Uts => ("uts", libc::CLONE_NEWUTS), }; - let own = fs::File::open(format!("/proc/self/ns/{name}"))?; - let theirs = fs::File::open(format!("/proc/{pid}/ns/{name}"))?; + let (own_fd, own_id) = own_ns_entry(ns)?; + let opened; + let theirs = match (ns, netns) { + (Ns::Net, Some(f)) => f, + _ => { + opened = fs::File::open(format!("/proc/{pid}/ns/{name}"))?; + &opened + } + }; + let tm = theirs.metadata()?; // The container shares the agent's own namespace (host network, // directly or through `--network container:`): the key would change // the whole VM or Linux host. The daemon refuses this first. - if same_namespace(&own, &theirs)? { + if (tm.dev(), tm.ino()) == own_id { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - format!("sysctl {:?} not allowed in host {name} namespace", s.path.replace('/', ".")), + format!("sysctl {:?} not allowed in host {name} namespace", sysctls[i].path.replace('/', ".")), )); } sys::setns(theirs.as_raw_fd(), kind)?; - let written = fs::write(format!("/proc/sys/{}", s.path), &s.value); + let mut result = Ok(()); + for s in &sysctls[i..end] { + if let Err(e) = fs::write(format!("/proc/sys/{}", s.path), &s.value) { + result = Err(io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e)))); + break; + } + } // Coming back must work, or the agent itself is in the container. - if let Err(e) = sys::setns(own.as_raw_fd(), kind) { + if let Err(e) = sys::setns(own_fd, kind) { eprintln!("kiri-init: cannot leave a container's {name} namespace: {e}"); std::process::abort(); } - written.map_err(|e| io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e))))?; + result?; + i = end; } Ok(()) } -/// Two /proc/*/ns files name the same namespace when their inodes match. -fn same_namespace(a: &fs::File, b: &fs::File) -> io::Result { - let (a, b) = (a.metadata()?, b.metadata()?); - Ok((a.dev(), a.ino()) == (b.dev(), b.ino())) -} - /// The limits the engine's agent sets on itself as it starts, before it /// starts anything, so that every container and build step inherits them /// (a run's own `--ulimit` still replaces them in the child). In the VM the @@ -453,11 +492,13 @@ mod tests { fn own_namespace_is_refused() { // A "container" that is this very process shares every namespace. let me = std::process::id() as libc::pid_t; - let own = fs::File::open("/proc/self/ns/net").unwrap(); - assert!(same_namespace(&own, &fs::File::open(format!("/proc/{me}/ns/net")).unwrap()).unwrap()); - assert!(!same_namespace(&own, &fs::File::open("/proc/self/ns/ipc").unwrap()).unwrap()); + let (_, own_net) = own_ns_entry(Ns::Net).unwrap(); + let me_net = fs::File::open(format!("/proc/{me}/ns/net")).unwrap().metadata().unwrap(); + let me_ipc = fs::File::open("/proc/self/ns/ipc").unwrap().metadata().unwrap(); + assert_eq!(own_net, (me_net.dev(), me_net.ino())); + assert_ne!(own_net, (me_ipc.dev(), me_ipc.ino())); let s = Sysctl { ns: Ns::Net, path: "net/ipv4/ip_unprivileged_port_start".into(), value: "77".into() }; - let e = apply_sysctls(me, &[s]).unwrap_err(); + let e = apply_sysctls(me, None, &[s]).unwrap_err(); assert_eq!(e.to_string(), "sysctl \"net.ipv4.ip_unprivileged_port_start\" not allowed in host net namespace"); } } diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index 935507284..ecf418291 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -1110,10 +1110,11 @@ fn mac_of(name: &str) -> io::Result<[u8; 6]> { type Bridge6 = Option<([u8; 16], u8)>; /// Bridges that exist so far: name → (index, gateway (none when -/// IPv6-only), prefix, IPv6). +/// IPv6-only), prefix, IPv6), plus a persistent host `NETLINK_ROUTE` socket. #[derive(Default)] pub struct Bridges { made: HashMap, u8, Bridge6)>, + route: Option, } /// What `Bridges::ensure` needs to do for a bridge given its cached state. @@ -1131,6 +1132,13 @@ enum BridgePlan { } impl Bridges { + fn route_nl(&mut self) -> io::Result<&mut Netlink> { + if self.route.is_none() { + self.route = Some(Netlink::open(libc::NETLINK_ROUTE)?); + } + Ok(self.route.as_mut().expect("opened above")) + } + /// Whether `name` currently exists with an IPv6 subnet configured. pub fn has_ipv6(&self, name: &str) -> bool { matches!(self.made.get(name), Some((.., Some(_)))) @@ -1359,6 +1367,7 @@ pub fn attach_container( bridge: &str, host_ifname: &str, pid: libc::pid_t, + netns: Option<&std::fs::File>, ip: [u8; 4], prefix: u8, gateway: [u8; 4], @@ -1366,7 +1375,7 @@ pub fn attach_container( v6: Option, plug: Plug, ) -> io::Result<()> { - attach(bridges, bridge, host_ifname, pid, 0, ip, prefix, gateway, mac, v6, plug) + attach_with_ns(bridges, bridge, host_ifname, pid, netns, 0, ip, prefix, gateway, mac, v6, plug) } /// Plugs the container into `bridge` as `eth{n}`. The first non-internal @@ -1381,31 +1390,73 @@ pub fn attach_container( /// MAC is made from it): neither the interface nor the bridge gets it. #[allow(clippy::too_many_arguments)] pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc::pid_t, n: u32, ip: [u8; 4], prefix: u8, gateway: [u8; 4], mac: Option<[u8; 6]>, v6: Option, plug: Plug) -> io::Result<()> { + attach_with_ns(bridges, bridge, host_ifname, pid, None, n, ip, prefix, gateway, mac, v6, plug) +} + +#[allow(clippy::too_many_arguments)] +fn attach_with_ns( + bridges: &mut Bridges, + bridge: &str, + host_ifname: &str, + pid: libc::pid_t, + netns_fd: Option<&std::fs::File>, + n: u32, + ip: [u8; 4], + prefix: u8, + gateway: [u8; 4], + mac: Option<[u8; 6]>, + v6: Option, + plug: Plug, +) -> io::Result<()> { let Plug { internal, no_ipv4 } = plug; let mac = Some(mac.unwrap_or_else(|| mac_for(ip))); let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?; - let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; - let mut host = Netlink::open(libc::NETLINK_ROUTE)?; - // A stopped container's veth may still hold this address and MAC. - delete_retired(&mut host); + let opened_ns; + let netns = match netns_fd { + Some(f) => f, + None => { + opened_ns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + &opened_ns + } + }; let ifname = format!("eth{n}"); - netlink::create_veth(&mut host, host_ifname, bridge_index, &netns, CONTAINER_MTU, &ifname, mac)?; - // By name: a new namespace may have tunl0, gre0 … before it. - let index = netlink::index_in(&netns, &ifname)?; - if v6.is_none() { - // Before it is up, so it never gets a link-local address. A kernel - // without IPv6 has no such file, and nothing to turn off. - let _ = netlink::in_netns(&netns, || sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1")); - } - let mut inner = Netlink::open_in(&netns)?; - netlink::set_up(&mut inner, 1)?; // lo - if !no_ipv4 { - netlink::add_address(&mut inner, index, ip, prefix)?; - } - if let Some(v) = v6 { - netlink::add_address6(&mut inner, index, v.ip, v.prefix)?; + { + let host = bridges.route_nl()?; + // A stopped container's veth may still hold this address and MAC. + delete_retired(host); + netlink::create_veth(host, host_ifname, bridge_index, netns, CONTAINER_MTU, &ifname, mac)?; + } + // Enter the container's network namespace once to resolve the peer index, + // disable IPv6 link-local when IPv6 is off, and open the inner route socket. + let (index, mut inner) = netlink::in_netns(netns, || { + let idx = netlink::index_of(&ifname)?; + if v6.is_none() { + let _ = sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1"); + } + let nl = Netlink::open(libc::NETLINK_ROUTE)?; + Ok((idx, nl)) + })?; + if n == 0 { + let mut batch = Vec::with_capacity(4); + batch.push(netlink::set_up_msg(1)); // lo + if !no_ipv4 { + batch.push(netlink::add_address_msg(index, ip, prefix)); + } + if let Some(v) = v6 { + batch.push(netlink::add_address6_msg(index, v.ip, v.prefix)); + } + batch.push(netlink::set_up_msg(index)); + inner.request(&mut batch)?; + } else { + netlink::set_up(&mut inner, 1)?; // lo + if !no_ipv4 { + netlink::add_address(&mut inner, index, ip, prefix)?; + } + if let Some(v) = v6 { + netlink::add_address6(&mut inner, index, v.ip, v.prefix)?; + } + netlink::set_up(&mut inner, index)?; } - netlink::set_up(&mut inner, index)?; if !internal && !no_ipv4 { netlink::add_default_route(&mut inner, index, gateway)?; } @@ -1417,6 +1468,7 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc: /// Host-side veths of stopped containers, deleted by the next `attach`. static RETIRED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static HAS_RETIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Notes a stopped container's host-side veths for the next `attach` to /// delete. Deleting one waits out RCU, 15-40 ms that every request after @@ -1427,12 +1479,19 @@ static RETIRED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new() /// to the old namespace, and that answered with resets (a download that /// broke mid-TLS or stalled). pub fn retire(veths: &[String]) { + if veths.is_empty() { + return; + } RETIRED.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(veths); + HAS_RETIRED.store(true, std::sync::atomic::Ordering::Release); } /// Deletes the veths `retire` noted. Gone already (the kernel took them /// with their namespace) is fine. fn delete_retired(nl: &mut Netlink) { + if !HAS_RETIRED.swap(false, std::sync::atomic::Ordering::AcqRel) { + return; + } for v in std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())) { let _ = netlink::delete_link(nl, &v); } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index be69aecad..91736467f 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -126,11 +126,7 @@ impl Netlink { /// A route socket inside another network namespace: entered just long /// enough to create the socket, which stays bound to that namespace. pub fn open_in(netns: &std::fs::File) -> io::Result { - let own = std::fs::File::open("/proc/self/ns/net")?; - sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?; - let nl = Netlink::open(libc::NETLINK_ROUTE); - sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?; - nl + in_netns(netns, || Netlink::open(libc::NETLINK_ROUTE)) } /// Sends messages (one batch) and waits for every acknowledgement. @@ -314,13 +310,17 @@ pub fn delete_link(nl: &mut Netlink, name: &str) -> io::Result<()> { nl.request(&mut [m]) } -pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> { +pub fn set_up_msg(index: i32) -> Msg { let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); m.raw(&ifinfo(index, libc::IFF_UP as u32, libc::IFF_UP as u32)); - nl.request(&mut [m]) + m } -pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> { +pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> { + nl.request(&mut [set_up_msg(index)]) +} + +pub fn add_address_msg(index: i32, addr: [u8; 4], prefix: u8) -> Msg { let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); // struct ifaddrmsg: family, prefixlen, flags, scope, index. let mut ifa = [0u8; 8]; @@ -328,7 +328,11 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i ifa[1] = prefix; ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes()); m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); - match nl.request(&mut [m]) { + m +} + +pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> { + match nl.request(&mut [add_address_msg(index, addr, prefix)]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, } @@ -337,7 +341,7 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i /// An IPv6 address, usable at once: no duplicate address detection, which /// would leave it tentative (not usable as a source) for about a second. /// Kiri hands out every address on its networks, so none can be taken. -pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> { +pub fn add_address6_msg(index: i32, addr: [u8; 16], prefix: u8) -> Msg { const IFA_F_NODAD: u8 = 0x02; let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); let mut ifa = [0u8; 8]; @@ -346,7 +350,11 @@ pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> ifa[2] = IFA_F_NODAD; ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes()); m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); - match nl.request(&mut [m]) { + m +} + +pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> { + match nl.request(&mut [add_address6_msg(index, addr, prefix)]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, } @@ -397,7 +405,7 @@ fn default_route(nl: &mut Netlink, family: i32, gateway: &[u8], index: i32, flag /// containers) succeed route lookup and reach nftables `output` redirect rules /// instead of failing immediately with `ENETUNREACH`. pub fn add_device_default_route(nl: &mut Netlink, index: i32, prefsrc: Option<[u8; 4]>) -> io::Result<()> { - let mut m = device_default_route_msg(index, prefsrc); + let m = device_default_route_msg(index, prefsrc); match nl.request(&mut [m]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, @@ -445,12 +453,32 @@ pub fn index_in(netns: &std::fs::File, name: &str) -> io::Result { in_netns(netns, || index_of(name)) } +thread_local! { + static OWN_NETNS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn own_netns_fd() -> io::Result { + OWN_NETNS.with(|slot| { + let mut slot = slot.borrow_mut(); + if let Some(f) = slot.as_ref() { + return Ok(f.as_raw_fd()); + } + let f = std::fs::File::open("/proc/self/ns/net")?; + let raw = f.as_raw_fd(); + *slot = Some(f); + Ok(raw) + }) +} + /// Runs `f` with this thread in `netns`, then back in its own. pub fn in_netns(netns: &std::fs::File, f: impl FnOnce() -> io::Result) -> io::Result { - let own = std::fs::File::open("/proc/self/ns/net")?; + let own = own_netns_fd()?; sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?; let r = f(); - sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?; + if let Err(e) = sys::setns(own, libc::CLONE_NEWNET) { + eprintln!("kiri-init: cannot return to own network namespace: {e}"); + std::process::abort(); + } r } diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index ca2ea2fbf..c5ef31372 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -932,6 +932,7 @@ mod tests { "kiri0", "kv_eg1", c1_pid, + None, [172, 18, 0, 2], 16, [172, 18, 0, 1], @@ -945,6 +946,7 @@ mod tests { "kiri0", "kv_eg2", c2_pid, + None, [172, 18, 0, 3], 16, [172, 18, 0, 1], diff --git a/crates/kiri-init/src/linux/sys.rs b/crates/kiri-init/src/linux/sys.rs index 39016f782..1c5bfa26b 100644 --- a/crates/kiri-init/src/linux/sys.rs +++ b/crates/kiri-init/src/linux/sys.rs @@ -555,17 +555,29 @@ fn clone_flags(args: &CloneArgs) -> libc::c_ulong { /// # Safety /// The caller must be single-threaded, as with fork(): the child gets a copy /// of this thread only, so no other thread may hold a lock it needs. +static CLONE3_STATE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// True once `clone3(..., CLONE_INTO_CGROUP)` has succeeded in this process, +/// allowing later spawns/execs to skip creating the fallback `cgroup_ready` pipe. +pub fn clone3_works() -> bool { + CLONE3_STATE.load(std::sync::atomic::Ordering::Relaxed) == 1 +} + pub unsafe fn clone3(args: &CloneArgs) -> io::Result { // SAFETY: `args` is a valid clone_args of the size passed; the caller // upholds the single-thread requirement. let ret = unsafe { libc::syscall(libc::SYS_clone3, args as *const CloneArgs, std::mem::size_of::()) }; if ret >= 0 { + if ret > 0 { + CLONE3_STATE.store(1, std::sync::atomic::Ordering::Relaxed); + } return Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: true }); } let e = io::Error::last_os_error(); if !clone3_unavailable(e.raw_os_error()) { return Err(io::Error::new(e.kind(), format!("clone3: {e}"))); } + CLONE3_STATE.store(2, std::sync::atomic::Ordering::Relaxed); // SAFETY: as above. clone(2) has no cgroup, pidfd, set_tid, stack or tls // arguments here: the child runs on a copy of this thread's stack, like // fork(). Passing 0 for the four arguments after `flags` is identical on diff --git a/crates/kiri-init/src/linux/trim.rs b/crates/kiri-init/src/linux/trim.rs index 214da7e5a..f3cdd05e2 100644 --- a/crates/kiri-init/src/linux/trim.rs +++ b/crates/kiri-init/src/linux/trim.rs @@ -84,8 +84,10 @@ pub(super) fn trim(mountpoint: &str) -> io::Result { } /// Reports `(in_use, capacity)` in bytes for the filesystem mounted at -/// `mountpoint`, using `statvfs` (`in_use = (blocks - bavail) * frsize`, -/// `capacity = blocks * frsize`). +/// `mountpoint`, using `statvfs` (`in_use = (blocks - bfree) * frsize`, +/// `capacity = blocks * frsize`). Uses `f_bfree` rather than `f_bavail` +/// because `FITRIM` discards free blocks (`f_bfree`), never root-reserved +/// non-free blocks. pub(super) fn stat(mountpoint: &str) -> io::Result<(u64, u64)> { let path = std::ffi::CString::new(mountpoint).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; // SAFETY: statvfs fills a zero-initialized struct for a valid NUL-terminated path. @@ -95,8 +97,8 @@ pub(super) fn stat(mountpoint: &str) -> io::Result<(u64, u64)> { } let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 }; let blocks = s.f_blocks as u64; - let bavail = s.f_bavail as u64; - let in_use = blocks.saturating_sub(bavail).saturating_mul(frsize); + let bfree = s.f_bfree as u64; + let in_use = blocks.saturating_sub(bfree).saturating_mul(frsize); let capacity = blocks.saturating_mul(frsize); Ok((in_use, capacity)) } diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index ffcc2329d..ce175796d 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -915,6 +915,16 @@ impl PinnedPeer { if r != 0 || len as usize != std::mem::size_of::() || cred.pid <= 0 { return None; } + // `uid == 0` is unconditionally admitted by `Gate::check_subject` + // without inspecting supplementary groups or container cgroups. + if cred.uid == 0 { + return Some(PinnedPeer { + uid: 0, + gid: cred.gid, + groups: Vec::new(), + cgroup: String::new(), + }); + } let proc_path = CString::new(format!("/proc/{}", cred.pid)).ok()?; // SAFETY: valid NUL-terminated path; pins the `/proc/` directory inode. let raw_dir = unsafe { libc::open(proc_path.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index 214182c77..07f7dca78 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -384,8 +384,18 @@ static USED_CACHE: Mutex> = Mutex::new(None); #[cfg(target_os = "macos")] static LAST_IN_USE: Mutex> = Mutex::new(None); #[cfg(target_os = "macos")] +static LAST_CAPACITY: Mutex> = Mutex::new(None); +#[cfg(target_os = "macos")] static RECLAIMING: AtomicBool = AtomicBool::new(false); +/// Persisted non-trimmable VM disk allocation (`/vm/disk-overhead`), +/// measured right after `FITRIM` so ext4's own journal, bitmaps, and +/// initialized inode tables (up to ~2.5% of disk size, excluded from +/// `statvfs.f_blocks`) are counted as in-use VM disk rather than promised as +/// reclaimable space that `FITRIM` can never free. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +const DISK_OVERHEAD_FILE: &str = "vm/disk-overhead"; + /// Reclaimable bytes under this threshold (64 MiB) are reported as 0 so /// filesystem metadata slack does not prompt pointless trims. pub const RECLAIM_THRESHOLD: u64 = 64 << 20; @@ -397,10 +407,94 @@ pub fn reclaimable_bytes(disk_host: Option, disk_in_use: Option) -> Op Some(if diff > RECLAIM_THRESHOLD { diff } else { 0 }) } +/// Allocated bytes (`st_blocks * 512`) and logical byte length (`st_size`) of +/// `/vm/data.img`, if present. +pub fn data_img_stats(root: &Path) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(root.join("vm/data.img")).ok()?; + Some((m.blocks().saturating_mul(512), m.len())) +} + /// Allocated bytes of `/vm/data.img` (`st_blocks * 512`), if present. pub fn data_img_allocated(root: &Path) -> Option { - use std::os::unix::fs::MetadataExt; - std::fs::metadata(root.join("vm/data.img")).ok().map(|m| m.blocks().saturating_mul(512)) + data_img_stats(root).map(|(alloc, _)| alloc) +} + +/// Upper bound on ext4's static metadata overhead (`logical_len - capacity`: +/// superblocks, group descriptors, bitmaps, journal, and inode tables), capped +/// to 1/16th of `capacity` + 512 MiB so an online-grown `data.img` whose guest +/// filesystem has not resized yet never treats the unmounted tail as overhead. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn max_ext4_overhead(logical_len: u64, capacity: u64) -> u64 { + if capacity == 0 || logical_len <= capacity { + return 0; + } + let cap = (capacity >> 4).saturating_add(512 << 20); + logical_len.saturating_sub(capacity).min(cap) +} + +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn read_disk_overhead(root: &Path) -> Option { + std::fs::read_to_string(root.join(DISK_OVERHEAD_FILE)) + .ok()? + .trim() + .parse::() + .ok() +} + +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn write_disk_overhead(root: &Path, bytes: u64) { + let path = root.join(DISK_OVERHEAD_FILE); + let tmp = root.join("vm/disk-overhead.tmp"); + if std::fs::write(&tmp, format!("{bytes}\n")).is_ok() { + let _ = std::fs::rename(&tmp, &path); + } +} + +/// Effective bytes in use inside `data.img`, combining occupied filesystem +/// data blocks (`raw_in_use`) with allocated non-trimmable ext4 metadata so +/// `reclaimable_bytes(disk_host, effective_in_use)` matches what `FITRIM` can +/// actually return to macOS. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn effective_vm_in_use( + disk_host: Option, + logical_len: Option, + raw_in_use: Option, + capacity: Option, + recorded_overhead: Option, +) -> (Option, Option) { + let Some(raw) = raw_in_use else { + return (None, None); + }; + let ext4_meta = match (logical_len, capacity) { + (Some(len), Some(cap)) => max_ext4_overhead(len, cap), + _ => 0, + }; + let overhead = match recorded_overhead { + Some(saved) => match disk_host { + // If host allocation minus used data shrank below the saved floor + // (e.g. newly written files reused previously-allocated blocks), + // clamp downward and update the saved floor. + Some(host) => saved.min(host.saturating_sub(raw)), + None => saved, + }, + None => { + // Before the first explicit reclaim records an exact post-FITRIM + // floor: a fresh disk (< 1 GiB of files) has near-zero initialized + // inode tables, whereas a mature populated disk (>= 1 GiB of files) + // has already completed `ext4lazyinit` across its block groups. + if raw >= (1 << 30) { + match disk_host { + Some(host) => ext4_meta.min(host.saturating_sub(raw)), + None => ext4_meta, + } + } else { + 0 + } + } + }; + let clamped_update = recorded_overhead.filter(|&saved| overhead < saved).map(|_| overhead); + (Some(raw.saturating_add(overhead)), clamped_update) } #[cfg(target_os = "linux")] @@ -513,14 +607,24 @@ pub fn report(engine: &Engine) -> Value { let root = engine.store.root(); #[cfg(target_os = "macos")] let disk = { - let disk_host = data_img_allocated(root); - let disk_in_use = match engine.disk_usage_if_awake() { - Some((in_use, _)) => { + let stats = data_img_stats(root); + let (disk_host, logical_len) = (stats.map(|(a, _)| a), stats.map(|(_, l)| l)); + let (raw_in_use, capacity) = match engine.disk_usage_if_awake() { + Some((in_use, cap)) => { *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(in_use); - Some(in_use) + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(cap); + (Some(in_use), Some(cap)) } - None => *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()), + None => ( + *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()), + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()), + ), }; + let recorded = read_disk_overhead(root); + let (disk_in_use, clamped) = effective_vm_in_use(disk_host, logical_len, raw_in_use, capacity, recorded); + if let Some(updated) = clamped { + write_disk_overhead(root, updated); + } let disk_limit = Some(super::engine::vm_disk_gb().saturating_mul(1 << 30)); let reclaimable = reclaimable_bytes(disk_host, disk_in_use); DiskInfo { disk_host, disk_in_use, disk_limit, reclaimable } @@ -557,9 +661,18 @@ pub fn reclaim(engine: &Engine) -> Result { let t0 = Instant::now(); let root = engine.store.root(); let before = data_img_allocated(root).unwrap_or(0); - let (trimmed, in_use, _capacity) = engine.trim_disk().map_err(Error::Io)?; - *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(in_use); + let (trimmed, raw_in_use, capacity) = engine.trim_disk().map_err(Error::Io)?; + // Flush pending VirtioBlock DISCARD hole-punches through XNU/APFS before + // sampling `st_blocks` so `after` reflects every reclaimed block immediately. + if let Ok(f) = std::fs::File::open(root.join("vm/data.img")) { + let _ = f.sync_all(); + } + *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(raw_in_use); + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(capacity); let after = data_img_allocated(root).unwrap_or(0); + let overhead = after.saturating_sub(raw_in_use); + write_disk_overhead(root, overhead); + let in_use = raw_in_use.saturating_add(overhead); invalidate_used_cache(); let reclaimed = before.saturating_sub(after); let elapsed_ms = t0.elapsed().as_millis() as u64; @@ -570,6 +683,8 @@ pub fn reclaim(engine: &Engine) -> Result { reclaimed = reclaimed, trimmed = trimmed, in_use = in_use, + raw_in_use = raw_in_use, + overhead = overhead, elapsed_ms = elapsed_ms ); Ok(json!({ @@ -577,6 +692,7 @@ pub fn reclaim(engine: &Engine) -> Result { "after": after, "reclaimed": reclaimed, "in_use": in_use, + "reclaimable": 0, "elapsed_ms": elapsed_ms, })) } @@ -1235,4 +1351,54 @@ mod tests { assert_eq!(s["reclaimable"], 12_100_000_000u64); let _ = std::fs::remove_dir_all(&d); } + + #[test] + fn ext4_metadata_overhead_is_excluded_from_reclaimable_space() { + // Mature 128 GiB disk (`137.44 GB` logical, `134.15 GB` statvfs capacity -> + // `3.29 GB` ext4 journal + inode table overhead): `104.0 GB` on macOS with + // `98.4 GB` of files promises only the `2.31 GB` that FITRIM can free, and + // reports 0 reclaimable once `101.69 GB` remains after FITRIM. + let logical = 128u64 << 30; + let capacity = logical - 3_290_000_000; + let raw_used = 98_400_000_000u64; + let (in_use_before, clamped) = effective_vm_in_use( + Some(104_000_000_000), + Some(logical), + Some(raw_used), + Some(capacity), + None, + ); + assert_eq!(clamped, None); + assert_eq!(in_use_before, Some(101_690_000_000)); + assert_eq!(reclaimable_bytes(Some(104_000_000_000), in_use_before), Some(2_310_000_000)); + + // After FITRIM leaves `101.69 GB` on host, recorded overhead is `3.29 GB` and reclaimable is 0. + let d = scratch("reclaim-overhead"); + std::fs::create_dir_all(d.join("vm")).unwrap(); + write_disk_overhead(&d, 3_290_000_000); + assert_eq!(read_disk_overhead(&d), Some(3_290_000_000)); + let (in_use_after, _) = effective_vm_in_use( + Some(101_690_000_000), + Some(logical), + Some(raw_used), + Some(capacity), + read_disk_overhead(&d), + ); + assert_eq!(reclaimable_bytes(Some(101_690_000_000), in_use_after), Some(0)); + + // Fresh sparse disk (< 1 GiB of files) before first trim does not over-subtract lazy overhead. + let (fresh_used, _) = effective_vm_in_use( + Some(2_020_000_000), + Some(logical), + Some(20_000_000), + Some(capacity), + None, + ); + assert_eq!(fresh_used, Some(20_000_000)); + assert_eq!(reclaimable_bytes(Some(2_020_000_000), fresh_used), Some(2_000_000_000)); + + // Online-grown un-resized disk (`logical >> capacity`) caps static overhead safely. + assert!(max_ext4_overhead(256 << 30, 64 << 30) <= (4 << 30) + (512 << 20)); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index 8e3826701..f6eca08ac 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -79,6 +79,9 @@ pub struct VmLink { /// The guest's latest `Usage` lines, for `usage`. usage: Arc, pending: Arc>>>, + /// Layer digests confirmed unpacked in this guest instance, avoiding + /// repeated `LayerQuery` round-trips across `create` and `start`. + layers: Mutex>, /// Kept so the VM lives as long as the link. Behind a mutex only so the /// link can be shared between threads; nothing touches it after boot. _vm: Mutex, @@ -345,6 +348,7 @@ impl VmLink { agent_dir: vm.agent_dir().to_owned(), writer: Mutex::new(Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024] }), pending, + layers: Mutex::new(std::collections::HashSet::new()), windows, usage, connector: vm.connector(), @@ -401,8 +405,16 @@ impl VmLink { } pub fn has_layer(&self, digest: &str) -> io::Result { + if self.layers.lock().unwrap_or_else(|e| e.into_inner()).contains(digest) { + return Ok(true); + } match self.call(|o| Msg::LayerQuery(digest).encode(o), None)? { - Reply::LayerStatus(have) => Ok(have), + Reply::LayerStatus(have) => { + if have { + self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned()); + } + Ok(have) + } other => Err(io::Error::other(format!("expected LayerStatus, got {other:?}"))), } } @@ -412,8 +424,9 @@ impl VmLink { // fails here rather than half-way through the request. let file = File::open(blob)?; let size = file.metadata()?.len(); - self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size))) - .map(drop) + self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))?; + self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned()); + Ok(()) } #[allow(clippy::too_many_arguments)] @@ -638,6 +651,10 @@ impl VmLink { /// Tells the guest which unpacked layers are still used; it deletes the rest. pub fn retain_layers(&self, digests: &[String]) -> io::Result<()> { + { + let keep: std::collections::HashSet<&str> = digests.iter().map(String::as_str).collect(); + self.layers.lock().unwrap_or_else(|e| e.into_inner()).retain(|d| keep.contains(d.as_str())); + } self.send(|o| kiri_proto::encode_retain_layers(o, digests)) } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 1232423aa..a85c0833e 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -3506,8 +3506,12 @@

Containers

@@ -3661,21 +3665,29 @@

Containers

(!f || div.textContent.toLowerCase().includes(f)) && (!lvl || div.dataset.lvl === lvl); -function logCount() { - const el = $("log-count"); - if (!el) return; - const all = logEl.childElementCount, d = ui.detail; - const showing = d.logFilter || d.logLevel ? [...logEl.children].filter((x) => !x.classList.contains("hide")).length : all; - el.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() }); -} - -function addLogs(parts) { - const atEnd = logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight < 40; - const filter = ui.detail.logFilter.toLowerCase(), level = ui.detail.logLevel; +const LOG_LEVEL_OPTS = () => [["", tr("All levels")], ["error", tr("Error")], ["warn", tr("Warn")], ["info", tr("Info")], ["debug", tr("Debug")]]; +function logToolbarHtml({ prefix, filter, level, follow, left = "", right = "", reloadAttr = "", clearAttr }) { + return `
${left} + + + + ${right}${reloadAttr ? btn(tr("Reload"), reloadAttr) : ""}${btn(tr("Clear"), clearAttr)}
`; +} +function updateLogCount(el, countId, d) { + const cnt = $(countId); + if (!cnt || !d) return; + const all = el.childElementCount; + const showing = d.logFilter || d.logLevel ? [...el.children].filter((x) => !x.classList.contains("hide")).length : all; + cnt.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() }); +} +function appendLogParts(el, countId, d, partial, nextN, parts) { + const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; + const filter = d.logFilter.toLowerCase(), level = d.logLevel; const frag = document.createDocumentFragment(); for (const p of parts) { - const lines = (ui.partial[p.e] + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n"); - ui.partial[p.e] = lines.pop(); + const key = Boolean(p.e); + const lines = ((partial[key] || "") + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n"); + partial[key] = lines.pop(); for (const line of lines) { const div = document.createElement("div"); const lvl = levelOf(line); @@ -3683,22 +3695,37 @@

Containers

LOG_MAX) logEl.firstElementChild.remove(); - if (ui.detail.follow && atEnd || ui.detail.follow && parts.length > 50) logEl.scrollTop = logEl.scrollHeight; - logCount(); -} - -function filterLogs() { - const d = ui.detail, f = d.logFilter.toLowerCase(); - for (const div of logEl.children) div.classList.toggle("hide", !shown(div, f, d.logLevel)); - logCount(); -} + el.append(frag); + while (el.childElementCount > LOG_MAX) el.firstElementChild.remove(); + if (d.follow && atEnd || d.follow && parts.length > 50) el.scrollTop = el.scrollHeight; + updateLogCount(el, countId, d); +} +function applyLogFilter(el, countId, d) { + const f = d.logFilter.toLowerCase(); + for (const div of el.children) div.classList.toggle("hide", !shown(div, f, d.logLevel)); + updateLogCount(el, countId, d); +} +function appendLogEnd(el, text) { + const div = document.createElement("div"); + div.className = "quiet"; + div.textContent = text; + el.append(div); +} +function clearLogConsole(el, countId, d, partial, resetN) { + el.textContent = ""; + partial.false = ""; + partial.true = ""; + resetN(); + updateLogCount(el, countId, d); +} +function logCount() { updateLogCount(logEl, "log-count", ui.detail); } +function addLogs(parts) { appendLogParts(logEl, "log-count", ui.detail, ui.partial, () => ++ui.logN, parts); } +function filterLogs() { applyLogFilter(logEl, "log-count", ui.detail); } /* The prompt, as a shell shows it: user@host:dir# (or $ for other users). Until the container has answered, it comes from the inspect data. */ @@ -3848,12 +3875,7 @@

Containers

- - - - ${btn(tr("Clear"), "data-logclear")}`; + body.innerHTML = logToolbarHtml({ prefix: "log", filter: d.logFilter, level: d.logLevel, follow: d.follow, clearAttr: "data-logclear" }); body.append(logEl); logCount(); $("log-filter").addEventListener("input", (ev) => { d.logFilter = ev.target.value; filterLogs(); }); @@ -8812,7 +8834,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r } else { ui.stReclaimed = e; if (ui.storage && e.after != null) { - ui.storage = { ...ui.storage, disk_host: e.after, ...(e.in_use != null ? { disk_in_use: e.in_use } : {}), reclaimable: 0 }; + ui.storage = { ...ui.storage, disk_host: e.after, ...(e.in_use != null ? { disk_in_use: e.in_use } : {}), reclaimable: e.reclaimable ?? 0 }; } toast("ok", e.reclaimed > 0 ? tr("Reclaimed {size} on {os}", { size: size(e.reclaimed), os: OS }) : tr("Nothing to reclaim")); } @@ -8862,7 +8884,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "stats": if (ui.detail?.id === e.id) { e.at = Date.now(); addSample(e); } break; case "stats-end": if (ui.detail?.id === e.id) ui.detail.statsOn = false; break; case "logs": if (ui.detail?.id === e.id) addLogs(e.parts); break; - case "logs-end": if (ui.detail?.id === e.id) { const d = document.createElement("div"); d.className = "quiet"; d.textContent = tr("— the log stream ended —"); logEl.append(d); ui.detail.logsOn = false; } break; + case "logs-end": if (ui.detail?.id === e.id) { appendLogEnd(logEl, tr("— the log stream ended —")); ui.detail.logsOn = false; } break; case "exec": if (ui.detail?.id === e.id) finishExec(e); break; case "files": if (ui.detail?.name === e.name) { Object.assign(ui.detail.files, { path: e.path, entries: e.entries, error: e.error, loading: false }); render(); } break; case "preview": if (ui.detail?.name === e.name && ui.detail.files.selected === e.path) { ui.detail.files.preview = e; render(); } break; @@ -9051,7 +9073,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-file]"))) { ui.detail.files.selected = el.dataset.file; ui.detail.files.preview = null; send("preview", { name: ui.detail.name, path: el.dataset.file }); render(); } else if ((el = t("[data-reveal]"))) send("reveal", { name: ui.detail.name, path: el.dataset.reveal }); else if ((el = t("[data-terminal]"))) send("terminal", { name: ui.detail.name }); - else if ((el = t("[data-logclear]"))) { logEl.textContent = ""; logCount(); } + else if ((el = t("[data-logclear]"))) clearLogConsole(logEl, "log-count", ui.detail, ui.partial, () => { ui.logN = 0; }); else if ((el = t("[data-save]"))) send("download", { name: ui.detail.name, path: el.dataset.save }); }); $("impstrip").addEventListener("click", (ev) => { @@ -9135,7 +9157,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r the sidebar's counts, every 30 s, and only while the node runs (the VM is awake for it then anyway). Nothing here starts the cluster but Start. */ const K8S_VIEWS = new Set(["pods", "services"]); -const k8s = { state: null, ready: false, pods: [], services: [], icon: null, asked: 0, sig: "", detail: null, svc: null, partial: "", +const k8s = { state: null, ready: false, pods: [], services: [], icon: null, asked: 0, sig: "", detail: null, svc: null, partial: { false: "", true: "" }, logN: 0, op: "", opAt: 0, opLine: "", context: "", config: null, sanDraft: null, port: null, wantPort: 6443, portDraft: null, argsDraft: null, defaultVer: "", manifestsDir: "" }; empty.pods = { title: "No pods", body: "Pods you create with kubectl show up here, grouped by namespace.", art: "pods" }; empty.services = { title: "No services", body: "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.", art: "services" }; @@ -9246,10 +9268,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "k8slogs": if (d?.logKey === e.key) addKLogs(e.parts); break; case "k8slogs-end": if (d?.logKey === e.key) { - const div = document.createElement("div"); - div.className = "quiet"; - div.textContent = d.previous ? tr("— the end of the run before the last restart —") : tr("— the log stream ended —"); - klogEl.append(div); + appendLogEnd(klogEl, d.previous ? tr("— the end of the run before the last restart —") : tr("— the log stream ended —")); d.logsOn = false; } break; @@ -9471,15 +9490,14 @@

${tr("Cluster")}

scrim.querySelector("[data-go]")?.focus(); } -/* A pod's page: Info and Logs. The log console is kept as a live element, - as the container page's is. */ -const klogEl = Object.assign(document.createElement("div"), { className: "console", tabIndex: 0 }); -klogEl.setAttribute("role", "log"); +/* A pod's page: Info and Logs. Shares the numbered log console component with + container logs (`makeLogConsole`, `appendLogParts`, `logToolbarHtml`). */ +const klogEl = makeLogConsole(); function openPod(key, tab = "info") { closePod(); const [ns, name] = key.split("/"); k8s.detail = { ns, name, tab: "info", container: "", previous: false, follow: true, logFilter: "", logLevel: "", logsOn: false, logKey: "" }; - klogEl.textContent = ""; + clearLogConsole(klogEl, "klog-count", k8s.detail, k8s.partial, () => { k8s.logN = 0; }); if (tab === "logs") podTab("logs"); else render(); $("content").scrollTop = 0; } @@ -9502,42 +9520,12 @@

${tr("Cluster")}

const key = `${d.ns}/${d.name}/${d.container}${d.previous ? "/previous" : ""}`; if (!again && d.logKey === key && (d.logsOn || d.previous)) return; Object.assign(d, { logKey: key, logsOn: !d.previous }); - klogEl.textContent = ""; - k8s.partial = ""; + clearLogConsole(klogEl, "klog-count", d, k8s.partial, () => { k8s.logN = 0; }); send("k8s", { action: "logs", value: { ns: d.ns, pod: d.name, container: d.container, previous: d.previous } }); } -function addKLogs(parts) { - const d = k8s.detail, atEnd = klogEl.scrollHeight - klogEl.scrollTop - klogEl.clientHeight < 40; - const filter = d.logFilter.toLowerCase(), frag = document.createDocumentFragment(); - for (const p of parts) { - const lines = (k8s.partial + p.t.replace(ansi, "")).split("\n"); - k8s.partial = lines.pop(); - for (const line of lines) { - const div = document.createElement("div"), lvl = levelOf(line); - div.dataset.lvl = lvl || "none"; - if (lvl && lvl !== "info") div.className = `lvl-${lvl}`; - div.textContent = line || " "; - if (!shown(div, filter, d.logLevel)) div.classList.add("hide"); - frag.append(div); - } - } - klogEl.append(frag); - while (klogEl.childElementCount > LOG_MAX) klogEl.firstElementChild.remove(); - if (d.follow && atEnd || d.follow && parts.length > 50) klogEl.scrollTop = klogEl.scrollHeight; - klogCount(); -} -function klogCount() { - const el = $("klog-count"), d = k8s.detail; - if (!el || !d) return; - const all = klogEl.childElementCount; - const showing = d.logFilter || d.logLevel ? [...klogEl.children].filter((x) => !x.classList.contains("hide")).length : all; - el.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() }); -} -function filterKLogs() { - const d = k8s.detail, f = d.logFilter.toLowerCase(); - for (const div of klogEl.children) div.classList.toggle("hide", !shown(div, f, d.logLevel)); - klogCount(); -} +function addKLogs(parts) { appendLogParts(klogEl, "klog-count", k8s.detail, k8s.partial, () => ++k8s.logN, parts); } +function klogCount() { updateLogCount(klogEl, "klog-count", k8s.detail); } +function filterKLogs() { applyLogFilter(klogEl, "klog-count", k8s.detail); } function renderPod() { const d = k8s.detail, p = podOf(d); @@ -9556,15 +9544,10 @@

${tr("Cluster")}

`; const body = $("dbody"); if (d.tab === "info") { body.innerHTML = podInfo(p); return; } - const levels = [["", tr("All levels")], ["error", tr("Error")], ["warn", tr("Warn")], ["info", tr("Info")], ["debug", tr("Debug")]]; const picker = p.containers.length > 1 ? `` : ""; const restarted = p.containers.find((c) => c.name === d.container)?.restarts > 0; - body.innerHTML = `
${picker} - - - - ${restarted || d.previous ? `` : ""} - ${btn(tr("Reload"), "data-klogreload")}${btn(tr("Clear"), "data-klogclear")}
`; + const prevToggle = restarted || d.previous ? `` : ""; + body.innerHTML = logToolbarHtml({ prefix: "klog", filter: d.logFilter, level: d.logLevel, follow: d.follow, left: picker, right: prevToggle, reloadAttr: "data-klogreload", clearAttr: "data-klogclear" }); body.append(klogEl); klogCount(); $("klog-container")?.addEventListener("change", (ev) => { d.container = ev.target.value; podLogs(); }); @@ -9886,7 +9869,7 @@

${tr("Labels")}

else if (t("[data-k8smanifests]")) send("k8s", { action: "manifests" }); else if (t("[data-k8sdelete]")) deleteCluster(); else if (t("[data-klogreload]")) podLogs(true); - else if (t("[data-klogclear]")) { klogEl.textContent = ""; klogCount(); } + else if (t("[data-klogclear]")) clearLogConsole(klogEl, "klog-count", k8s.detail, k8s.partial, () => { k8s.logN = 0; }); }); $("title").addEventListener("click", (ev) => { if (ev.target.closest("[data-kback]")) { closePod(); render(); } }); $("content").addEventListener("paste", envPaste); diff --git a/crates/kiri/src/ui/mac.rs b/crates/kiri/src/ui/mac.rs index 8a61cf3d0..7b17c4162 100644 --- a/crates/kiri/src/ui/mac.rs +++ b/crates/kiri/src/ui/mac.rs @@ -13,8 +13,8 @@ use objc2::runtime::{AnyObject, ProtocolObject}; use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send}; use objc2::sel; use objc2_app_kit::{ - NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType, NSMenu, NSMenuDelegate, NSMenuItem, - NSWindow, NSWindowStyleMask, NSWindowTitleVisibility, + NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType, NSEvent, NSMenu, NSMenuDelegate, NSMenuItem, + NSResponder, NSView, NSWindow, NSWindowStyleMask, NSWindowTitleVisibility, }; use objc2_foundation::{NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString}; use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandler, WKUserContentController, WKWebView, WKWebViewConfiguration}; @@ -141,7 +141,8 @@ fn make_webview(mtm: MainThreadMarker, frame: NSRect, tx: Sender, autostart config .userContentController() .addScriptMessageHandler_name(ProtocolObject::from_ref(&*handler), &NSString::from_str("kiri")); - let webview = WKWebView::initWithFrame_configuration(WKWebView::alloc(mtm), frame, &config); + let webview = WebView::new(mtm, frame, &config); + webview.setAllowsLinkPreview(false); if cfg!(debug_assertions) { webview.setInspectable(true); } @@ -149,7 +150,7 @@ fn make_webview(mtm: MainThreadMarker, frame: NSRect, tx: Sender, autostart let no: Retained = msg_send![objc2::class!(NSNumber), numberWithBool: false]; let _: () = msg_send![&webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")]; webview.loadHTMLString_baseURL(&NSString::from_str(&super::assemble::page(PAGE, prefs()["lang"].as_str())), None); - webview + Retained::into_super(webview) } } @@ -637,6 +638,38 @@ struct HandlerIvars { view: Option, } +define_class!( + // SAFETY: WKWebView is a main-thread AppKit view safe to subclass without Drop. + #[unsafe(super(WKWebView, NSView, NSResponder, NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "KiriWebView"] + struct WebView; + + unsafe impl NSObjectProtocol for WebView {} + + impl WebView { + /// Kiri renders its own app editing menu (`#app-ctx` in `index.html`). + /// Clearing any AppKit `NSMenu` items WebKit builds guarantees Safari / + /// browser items (`Search with Google`, `Look Up`, `Translate`, + /// `Copy Link with Highlight`, `Share…`, `Speech`, `Services`) never + /// appear on macOS right-click or Ctrl-click. + #[unsafe(method(willOpenMenu:withEvent:))] + fn will_open_menu(&self, menu: &NSMenu, event: &NSEvent) { + menu.removeAllItems(); + // SAFETY: forwarding `willOpenMenu:withEvent:` to `WKWebView` with valid args. + let _: () = unsafe { msg_send![super(self), willOpenMenu: menu, withEvent: event] }; + } + } +); + +impl WebView { + fn new(mtm: MainThreadMarker, frame: NSRect, config: &WKWebViewConfiguration) -> Retained { + let this = Self::alloc(mtm).set_ivars(()); + // SAFETY: `WKWebView`'s designated initializer on a freshly allocated subclass instance. + unsafe { msg_send![super(this), initWithFrame: frame, configuration: config] } + } +} + define_class!( // SAFETY: NSObject has no subclassing requirements and this type has no Drop. #[unsafe(super(NSObject))] diff --git a/scripts/bench-linux-docker.py b/scripts/bench-linux-docker.py new file mode 100755 index 000000000..945b58ee9 --- /dev/null +++ b/scripts/bench-linux-docker.py @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 +"""Head-to-head Linux benchmark: Kiri Engine vs Docker Engine (`dockerd`). + +Measures real-world container lifecycle and developer-workflow workloads on the +same Linux machine (alternating iterations so scheduler noise affects both +equally), producing a transparent markdown summary and JSON artifact (#776): + + 1. Ephemeral lifecycle (`docker run --rm alpine:3.21 true`, median & p95) + 2. Multi-layer PHP app cold start (`php:8.2-cli-alpine` + 1,000-file bind mount + + published port + HTTP readiness, modeling Lando / Compose dev stacks) + 3. Warm app restart (`POST /containers/{id}/restart` + HTTP readiness) + 4. Container `exec` (`100x php -r "echo 'ok';"` over Engine API) + 5. Bind-mount filesystem I/O (`1,000` PHP files `glob` + `file_get_contents`) + 6. Published-port HTTP latency (`250` GET requests) + 7. App teardown (`stop` + `DELETE`, `SIGINT` stop signal) + 8. Idle & post-benchmark engine RSS memory + +Usage: + python3 scripts/bench-linux-docker.py --docker-sock /var/run/docker.sock \\ + --kiri-sock /tmp/kiri-bench/docker.sock --kiri-pid \\ + [--out results.json] [--report report.md] + +Standard library only. +""" + +import argparse +import http.client +import json +import os +import re +import socket +import statistics +import subprocess +import tempfile +import time +import urllib.request + +ALPINE_IMG, ALPINE_TAG = "alpine", "3.21" +PHP_IMG, PHP_TAG = "php", "8.2-cli-alpine" + + +class UnixHTTP(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=120) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(120) + self.sock.connect(self.path) + + +class Client: + def __init__(self, name, sock): + self.name = name + self.sock = sock + self.conn = UnixHTTP(sock) + + def reset(self): + try: + self.conn.close() + except Exception: + pass + self.conn = UnixHTTP(self.sock) + + def call(self, method, path, body=None, want=(200, 201, 204, 304)): + data = json.dumps(body).encode() if body is not None else None + headers = {"Content-Type": "application/json"} if data is not None else {} + for attempt in range(2): + try: + self.conn.request(method, path, body=data, headers=headers) + r = self.conn.getresponse() + out = r.read() + break + except (http.client.HTTPException, OSError): + self.reset() + if attempt: + raise + if r.status not in want: + raise RuntimeError(f"[{self.name}] {method} {path}: {r.status} {out[:300]!r}") + return out + + def pull(self, image, tag): + self.call("POST", f"/images/create?fromImage={image}&tag={tag}") + + def run_ephemeral(self): + cid = json.loads( + self.call("POST", "/containers/create", {"Image": f"{ALPINE_IMG}:{ALPINE_TAG}", "Cmd": ["true"]}) + )["Id"] + self.call("POST", f"/containers/{cid}/start") + self.call("POST", f"/containers/{cid}/wait") + self.call("DELETE", f"/containers/{cid}?force=1") + + def exec_run(self, cid, cmd): + eid = json.loads( + self.call( + "POST", + f"/containers/{cid}/exec", + {"AttachStdout": True, "AttachStderr": True, "Cmd": cmd}, + ) + )["Id"] + return self.call("POST", f"/exec/{eid}/start", {"Detach": False, "Tty": False}) + + +def proc_tree_rss_kib(pids): + seen = set() + queue = [p for p in pids if p and p > 0] + while queue: + pid = queue.pop() + if pid in seen: + continue + seen.add(pid) + try: + with open(f"/proc/{pid}/task/{pid}/children") as f: + for tok in f.read().split(): + queue.append(int(tok)) + except OSError: + for entry in os.listdir("/proc"): + if not entry.isdigit(): + continue + try: + with open(f"/proc/{entry}/stat") as sf: + st = sf.read() + ppid = int(st.rsplit(")", 1)[1].split()[1]) + if ppid == pid: + queue.append(int(entry)) + except OSError: + pass + total = 0 + for pid in seen: + try: + with open(f"/proc/{pid}/status") as f: + m = re.search(r"VmRSS:\s+(\d+)", f.read()) + if m: + total += int(m.group(1)) + except OSError: + pass + return total + + +def pidof_names(names): + out = [] + for entry in os.listdir("/proc"): + if not entry.isdigit(): + continue + try: + with open(f"/proc/{entry}/comm") as f: + comm = f.read().strip() + if comm in names: + out.append(int(entry)) + except OSError: + pass + return out + + +def wait_http_ok(port, timeout_s=15.0): + deadline = time.perf_counter() + timeout_s + url = f"http://127.0.0.1:{port}/" + while time.perf_counter() < deadline: + try: + with urllib.request.urlopen(url, timeout=1.0) as resp: + if resp.status == 200 and b"ok" in resp.read(): + return + except Exception: + time.sleep(0.01) + raise RuntimeError(f"HTTP server on port {port} did not become ready within {timeout_s}s") + + +def create_php_app(client, app_dir): + body = { + "Image": f"{PHP_IMG}:{PHP_TAG}", + "Cmd": ["php", "-S", "0.0.0.0:80", "-t", "/app"], + "StopSignal": "SIGINT", + "ExposedPorts": {"80/tcp": {}}, + "HostConfig": { + "Binds": [f"{app_dir}:/app"], + "PortBindings": {"80/tcp": [{"HostIp": "127.0.0.1", "HostPort": "0"}]}, + }, + } + cid = json.loads(client.call("POST", "/containers/create", body))["Id"] + client.call("POST", f"/containers/{cid}/start") + info = json.loads(client.call("GET", f"/containers/{cid}/json")) + port = int(info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"]) + wait_http_ok(port) + return cid, port + + +def destroy_php_app(client, cid): + client.call("POST", f"/containers/{cid}/stop?t=5") + client.call("DELETE", f"/containers/{cid}?force=1") + + +def restart_php_app(client, cid): + client.call("POST", f"/containers/{cid}/restart?t=5") + info = json.loads(client.call("GET", f"/containers/{cid}/json")) + port = int(info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"]) + wait_http_ok(port) + return port + + +def summary(xs): + xs = sorted(xs) + p95_idx = max(0, int(len(xs) * 0.95) - 1) + return {"median": statistics.median(xs), "mean": statistics.mean(xs), "p95": xs[p95_idx], "n": len(xs)} + + +def extract_digits(raw): + # Strip Docker multiplexed stream headers (8-byte frames) and extract trailing integer. + clean = re.sub(rb"[\x00-\x08]", b"", raw).decode("utf-8", errors="ignore").strip().splitlines() + for line in reversed(clean): + digits = "".join(ch for ch in line if ch.isdigit()) + if digits: + return float(digits) + raise RuntimeError(f"could not parse numeric output from {raw!r}") + + +def http_burst_ms(port, count=250): + t0 = time.perf_counter() + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + try: + for _ in range(count): + conn.request("GET", "/") + r = conn.getresponse() + r.read() + finally: + conn.close() + return (time.perf_counter() - t0) * 1000.0 + + +def run_benchmark(args): + docker = Client("docker", args.docker_sock) + kiri = Client("kiri", args.kiri_sock) + engines = [("docker", docker), ("kiri", kiri)] + + d_ver = json.loads(docker.call("GET", "/version")) + if "kiri" in json.dumps(d_ver).lower(): + raise RuntimeError(f"--docker-sock ({args.docker_sock}) answered as Kiri ({d_ver.get('Platform')}); start dockerd first") + + for _, c in engines: + c.call("GET", "/_ping") + c.pull(ALPINE_IMG, ALPINE_TAG) + c.pull(PHP_IMG, PHP_TAG) + for _ in range(5): + c.run_ephemeral() + + time.sleep(1.0) + docker_pids = pidof_names({"dockerd", "containerd"}) + kiri_pids = [args.kiri_pid] if args.kiri_pid else pidof_names({"kiri", "kiri-init"}) + + res = { + "kiri_version": args.version or "HEAD", + "docker": {"rss_idle_kib": proc_tree_rss_kib(docker_pids)}, + "kiri": {"rss_idle_kib": proc_tree_rss_kib(kiri_pids)}, + } + + # 1. Alternating `docker run --rm alpine true` + ephemeral = {"docker": [], "kiri": []} + for i in range(args.ephemeral_runs): + pair = engines if i % 2 == 0 else list(reversed(engines)) + for name, c in pair: + t0 = time.perf_counter() + c.run_ephemeral() + ephemeral[name].append((time.perf_counter() - t0) * 1000.0) + for name in ("docker", "kiri"): + res[name]["ephemeral_run_ms"] = summary(ephemeral[name]) + + # Prepare 1,000-file PHP fixture app (matching Xilonz/lando-engine-kiri) + with tempfile.TemporaryDirectory(prefix="kiri-php-bench-") as app_dir: + with open(os.path.join(app_dir, "index.php"), "w") as f: + f.write(" 1.0 else "on par") + return f"{k_val - d_val:+.{decimals}f} {unit} ({abs(pct):.1f}% {word})" + + +def render_markdown(res): + d, k = res["docker"], res["kiri"] + lines = [ + f"## Linux Benchmark: Kiri (`{res.get('kiri_version', 'HEAD')}`) vs Docker Engine", + "", + "Alternating head-to-head runs on the same Linux host (ephemeral `alpine:3.21` + `php:8.2-cli-alpine` app stack with 1,000 bind-mounted files and published HTTP port).", + "", + "| Workload | Docker Engine | Kiri Engine | Comparison |", + "| :--- | ---: | ---: | :--- |", + f"| `docker run --rm alpine true` (median) | {d['ephemeral_run_ms']['median']:.2f} ms | {k['ephemeral_run_ms']['median']:.2f} ms | {format_diff(d['ephemeral_run_ms']['median'], k['ephemeral_run_ms']['median'])} |", + f"| `docker run --rm alpine true` (p95) | {d['ephemeral_run_ms']['p95']:.2f} ms | {k['ephemeral_run_ms']['p95']:.2f} ms | {format_diff(d['ephemeral_run_ms']['p95'], k['ephemeral_run_ms']['p95'])} |", + f"| PHP app cold start + HTTP ready (avg) | {d['app_cold_start_ms']['mean']:.1f} ms | {k['app_cold_start_ms']['mean']:.1f} ms | {format_diff(d['app_cold_start_ms']['mean'], k['app_cold_start_ms']['mean'], 'ms', 1)} |", + f"| PHP app warm restart + HTTP ready (avg) | {d['app_warm_restart_ms']['mean']:.1f} ms | {k['app_warm_restart_ms']['mean']:.1f} ms | {format_diff(d['app_warm_restart_ms']['mean'], k['app_warm_restart_ms']['mean'], 'ms', 1)} |", + f"| `{k['exec_runs']}x` `exec php -r \"echo 'ok';\"` | {d['exec_total_ms']:.1f} ms | {k['exec_total_ms']:.1f} ms | {format_diff(d['exec_total_ms'], k['exec_total_ms'], 'ms', 1)} |", + f"| Bind-mount I/O (1,000 PHP files, avg) | {d['bind_io_ms']:.2f} ms | {k['bind_io_ms']:.2f} ms | {format_diff(d['bind_io_ms'], k['bind_io_ms'])} |", + f"| Published-port HTTP (250 GETs) | {d['http_250_ms']:.1f} ms | {k['http_250_ms']:.1f} ms | {format_diff(d['http_250_ms'], k['http_250_ms'], 'ms', 1)} |", + f"| App teardown (`SIGINT` stop + rm, avg) | {d['app_teardown_ms']['mean']:.1f} ms | {k['app_teardown_ms']['mean']:.1f} ms | {format_diff(d['app_teardown_ms']['mean'], k['app_teardown_ms']['mean'], 'ms', 1)} |", + f"| Engine RSS at rest | {d['rss_idle_kib'] / 1024:.1f} MiB | {k['rss_idle_kib'] / 1024:.1f} MiB | {format_diff(d['rss_idle_kib'] / 1024, k['rss_idle_kib'] / 1024, 'MiB', 1)} |", + f"| Engine RSS after benchmark | {d['rss_after_kib'] / 1024:.1f} MiB | {k['rss_after_kib'] / 1024:.1f} MiB | {format_diff(d['rss_after_kib'] / 1024, k['rss_after_kib'] / 1024, 'MiB', 1)} |", + "", + ] + return "\n".join(lines) + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--docker-sock", default="/var/run/docker.sock") + p.add_argument("--kiri-sock", required=True) + p.add_argument("--kiri-pid", type=int, default=0) + p.add_argument("--version", default="") + p.add_argument("--ephemeral-runs", type=int, default=100) + p.add_argument("--app-runs", type=int, default=10) + p.add_argument("--exec-runs", type=int, default=100) + p.add_argument("--out", default="") + p.add_argument("--report", default="") + args = p.parse_args() + + res = run_benchmark(args) + if args.out: + with open(args.out, "w") as f: + json.dump(res, f, indent=2) + md = render_markdown(res) + if args.report: + with open(args.report, "w") as f: + f.write(md) + print(md) + + +if __name__ == "__main__": + main() diff --git a/tests/ui/podlogs.js b/tests/ui/podlogs.js new file mode 100644 index 000000000..220e2335d --- /dev/null +++ b/tests/ui/podlogs.js @@ -0,0 +1,79 @@ +// parity: macos windows linux +// Pod logs share the numbered log console component with Container logs. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; + +kiri.on({ + type: "lists", + containers: [{ Id: "k8snode000001", Names: ["/kiri-k8s"], Image: "rancher/k3s:v1.31.4-k3s1", State: "running", Status: "Up 2m", Created: 1700000000, Ports: [], Labels: {} }], + images: [], volumes: [], networks: [], +}); +kiri.on({ + type: "k8s", + state: "running", + ready: true, + context: "kiri", + port: 6443, + pods: [{ + ns: "default", + name: "api-7d4b9", + phase: "Running", + ready: "1/1", + restarts: 1, + node: "kiri-k8s", + created: "2026-11-25T10:00:00Z", + containers: [{ name: "api", image: "app:1", state: "running", ready: true, restarts: 1 }], + }], + services: [], +}); + +show("pods"); +openPod("default/api-7d4b9", "logs"); +const key = "default/api-7d4b9/api"; +kiri.on({ + type: "k8slogs", + key, + parts: [ + { t: "2026-11-25T10:00:01Z INFO boot ready\r\n2026-11-25T10:00:02Z WARN slow query\n", e: false }, + { t: "2026-11-25T10:00:03Z ERROR connection dropped\n", e: true }, + ], +}); + +t("pod logs render in .console.numbered with line numbers, level classes, and count", () => { + const klog = document.querySelector("#dbody .console.numbered"); + if (!klog) throw new Error("missing .console.numbered on pod logs"); + const rows = [...klog.children]; + eq(rows.map((r) => r.dataset.n), ["1", "2", "3"], "line numbers"); + eq([rows[1].className, rows[2].className], ["lvl-warn", "lvl-error"], "level classes"); + eq(document.querySelector("#klog-count")?.textContent, tr("{all} lines", { all: "3" }), "line count"); +}); + +t("selecting pod logs omits line numbers", () => { + const klog = document.querySelector("#dbody .console.numbered"); + getSelection().selectAllChildren(klog); + eq( + getSelection().toString().trim().split("\n"), + ["2026-11-25T10:00:01Z INFO boot ready", "2026-11-25T10:00:02Z WARN slow query", "2026-11-25T10:00:03Z ERROR connection dropped"], + "copied lines", + ); + getSelection().removeAllRanges(); +}); + +t("filtering and clearing pod logs share uniform behavior and reset numbering", () => { + const klog = document.querySelector("#dbody .console.numbered"); + const filter = document.querySelector("#klog-filter"); + filter.value = "warn"; + filter.dispatchEvent(new Event("input", { bubbles: true })); + const visible = [...klog.children].filter((r) => !r.classList.contains("hide")); + eq(visible.map((r) => r.dataset.n), ["2"], "filtered visible line"); + filter.value = ""; + filter.dispatchEvent(new Event("input", { bubbles: true })); + + document.querySelector("[data-klogclear]").click(); + eq(klog.childElementCount, 0, "cleared"); + kiri.on({ type: "k8slogs", key, parts: [{ t: "restarted line\n", e: false }] }); + eq(klog.firstElementChild?.dataset.n, "1", "restarted line number"); +}); + +report(R); From fdaf77409ddaf747b6f8854702cb29e66ddb04e1 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:15:36 +0100 Subject: [PATCH 139/157] WSL: follow a distro's absolute links inside the distro and keep C:\.. on the drive (#972) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri/src/daemon/binds.rs | 85 ++++++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 7 deletions(-) diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index ad4da7d36..b45b0abe5 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -285,17 +285,59 @@ pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result /usr/share/zoneinfo/...`) + // means the distro's own file: follow it inside the distro's root. With + // only relative links on the way the source stays as given; the kernel + // follows those inside the root itself. + let target = match resolve_in_root(Path::new(&distro_root), &lex) { + Some((inside, true)) if on_drive(&inside) => return Ok(inside), + Some((inside, true)) => confine_to_root(&distro_root, &inside), + Some((_, false)) => confine_to_root(&distro_root, &lex), + None => return Err(Error::BadRequest(format!("invalid mount source {src}: too many levels of symbolic links"))), + }; verify_on_disk_confinement(src, distro, Path::new(&distro_root), Path::new(&target))?; Ok(target) } +/// `path` (absolute, in a distro whose `/` is `root` on disk) with every +/// symlink on the way followed as the distro would: an absolute target +/// from `root`, `..` stopping at it. The path returned is the distro's +/// spelling, with whether an absolute link was on the way; None after 40 +/// links, as Linux gives up. +fn resolve_in_root(root: &Path, path: &str) -> Option<(String, bool)> { + if !root.is_dir() { + return Some((lexical_clean(path), false)); + } + let parts = |p: &str| p.split('/').filter(|c| !c.is_empty() && *c != ".").map(str::to_owned).rev().collect::>(); + let (mut todo, mut done, mut links, mut absolute) = (parts(path), Vec::::new(), 0, false); + while let Some(c) = todo.pop() { + if c == ".." { + done.pop(); + continue; + } + match std::fs::read_link(root.join(done.join("/")).join(&c)) { + Ok(link) => { + links += 1; + if links > 40 { + return None; + } + let link = link.to_string_lossy().into_owned(); + if link.starts_with('/') { + done.clear(); + absolute = true; + } + todo.extend(parts(&link)); + } + Err(_) => done.push(c), + } + } + Some((format!("/{}", done.join("/")), absolute)) +} + /// How many leading bytes hold a colon that is not a separator: `C:` and /// `\\?\C:` (moby's Windows parser allows both). fn drive_prefix(spec: &str) -> usize { @@ -365,9 +407,10 @@ pub fn source_with_roots(src: &str, wsl: &Wsl, distro_root: impl Fn(&str) -> Opt Err(bad("Kiri's WSL can reach the Windows drives (C:\\…) and its own files, not network shares or devices")) } -/// A path on drive `letter`, under WSL's automount root. +/// A path on drive `letter`, under WSL's automount root. `..` stops at the +/// drive's root, as Windows resolves `C:\..` to `C:\`. fn drive(wsl: &Wsl, letter: u8, rest: &str) -> String { - clean(&format!("{}{}/{}", wsl.root, letter.to_ascii_lowercase() as char, rest.replace('\\', "/"))) + confine_to_root(&format!("{}{}", wsl.root, letter.to_ascii_lowercase() as char), &rest.replace('\\', "/")) } /// Whether `path` is under WSL's automount root (`/...`, @@ -872,4 +915,32 @@ mod tests { ); assert!(source_with_roots(r"\\wsl.localhost\Debian\home\alice", &w, with_ubuntu).is_err()); } + + #[test] + fn dotdot_on_a_drive_stops_at_its_root() { + assert_eq!(ok(r"C:\..\..\etc:/x:ro"), t("/mnt/c/etc", "/x", "ro")); + assert_eq!(ok("//c/../../etc:/x"), t("/mnt/c/etc", "/x", "")); + assert_eq!(ok(r"C:\Users\me\proj\..\other:/x"), t("/mnt/c/Users/me/other", "/x", "")); + } + + #[test] + fn a_link_in_a_distro_is_followed_inside_it() { + let root = std::env::temp_dir().join(format!("kiri-binds-distro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("usr/share/zoneinfo/Europe")).unwrap(); + std::fs::create_dir_all(root.join("etc")).unwrap(); + std::fs::write(root.join("usr/share/zoneinfo/Europe/Berlin"), b"TZif").unwrap(); + std::os::unix::fs::symlink("/usr/share/zoneinfo/Europe/Berlin", root.join("etc/localtime")).unwrap(); + std::os::unix::fs::symlink("../../../..", root.join("etc/up")).unwrap(); + std::os::unix::fs::symlink("/mnt/c/Users/me", root.join("etc/win")).unwrap(); + std::os::unix::fs::symlink("loop", root.join("loop")).unwrap(); + let followed = |p: &str| resolve_in_root(&root, p); + assert_eq!(followed("/etc/localtime").unwrap(), ("/usr/share/zoneinfo/Europe/Berlin".to_owned(), true)); + assert_eq!(followed("/etc/up/etc").unwrap(), ("/etc".to_owned(), false)); + assert_eq!(followed("/etc/win/src").unwrap(), ("/mnt/c/Users/me/src".to_owned(), true)); + assert_eq!(followed("/home/me/app").unwrap(), ("/home/me/app".to_owned(), false)); + assert_eq!(followed("/loop"), None); + assert_eq!(resolve_in_root(&root.join("missing"), "/etc/../x").unwrap(), ("/x".to_owned(), false)); + let _ = std::fs::remove_dir_all(&root); + } } From c610b4350d3e8d46a4ece89deaea6f4e7cba1670 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:15:36 +0100 Subject: [PATCH 140/157] Updates & WSL: refuse non-version strings and odd staged versions, drain wsl.exe pipes, keep one [boot] command (#973) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri-win/src/update.rs | 85 +++++++++++++++++++++++++++++++--- crates/kiri-win/src/wslsync.rs | 28 ++++++++++- crates/kiri/src/update.rs | 30 +++++++++++- 3 files changed, 134 insertions(+), 9 deletions(-) diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index d1fb63864..c188c071e 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -66,8 +66,27 @@ pub struct Release { pub size: u64, } -/// `1.2.10` > `1.2.9`; a missing part counts as 0. +/// Whether `v` reads as a version: `[v]N(.N)*`, optionally `-` and +/// dot-separated alphanumeric identifiers (`0.1.8-dev.42`). +fn is_version(v: &str) -> bool { + let s = v.strip_prefix('v').unwrap_or(v); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (s, None), + }; + let numeric = |seg: &str| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()); + let ident = |id: &str| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + core.split('.').all(numeric) && pre.is_none_or(|p| p.split('.').all(ident)) +} + +/// `1.2.10` > `1.2.9`; a missing part counts as 0, and a test build +/// (`0.1.8-dev.42`, scripts/ci/test-version.sh) sorts above its release. +/// A string that isn't a version is never newer, and nothing is newer +/// than one. pub fn newer(candidate: &str, current: &str) -> bool { + if !is_version(candidate) || !is_version(current) { + return false; + } let parts = |v: &str| -> Vec { v.trim_start_matches('v').split(['.', '-']).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(candidate), parts(current)); for i in 0..a.len().max(b.len()) { @@ -169,6 +188,7 @@ fn fetch_and_check(release: &Release, dir: &Path, progress: &mut dyn FnMut(u64, loop { if cancel.load(Ordering::Relaxed) { let _ = child.kill(); + let _ = child.wait(); return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); } let got = std::fs::metadata(&part).map_or(0, |m| m.len()); @@ -207,10 +227,15 @@ fn staged_msi(version: &str) -> PathBuf { stage_dir().join(format!("Kiri-{version}.msi")) } +fn staged_in(dir: &Path) -> Option { + let raw = std::fs::read_to_string(dir.join("version")).ok()?; + let version = raw.trim().strip_prefix('v').unwrap_or(raw.trim()).to_owned(); + (is_version(&version) && dir.join(format!("Kiri-{version}.msi")).is_file() && newer(&version, CURRENT)).then_some(version) +} + /// The staged update's version, when there is one newer than this build. pub fn staged() -> Option { - let version = std::fs::read_to_string(stage_dir().join("version")).ok()?.trim().to_owned(); - (staged_msi(&version).is_file() && newer(&version, CURRENT)).then_some(version) + staged_in(&stage_dir()) } /// The staged MSI, checked again (it sat on disk since the download). @@ -623,6 +648,17 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result>| { + std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(mut r) = pipe { + let _ = r.read_to_end(&mut buf); + } + buf + }) + }; + let out_reader = drain(child.stdout.take().map(|s| Box::new(s) as Box)); + let err_reader = drain(child.stderr.take().map(|s| Box::new(s) as Box)); let ms = u32::try_from(limit.as_millis()).unwrap_or(u32::MAX - 1); // SAFETY: waits on the child's own process handle, open while `child` lives. let waited = unsafe { windows_sys::Win32::System::Threading::WaitForSingleObject(child.as_raw_handle() as _, ms) }; @@ -632,10 +668,15 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result &'static str { /// spaces, a `#` comment, or the `\r` of a file saved with CRLF /// ([[:space:]] has it). On one line, with no backslash, as the rest of /// the script. -const BOOT_AWK: &str = "function key(l) { sub(/#.*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return l } \ +const BOOT_AWK: &str = "function key(l) { if (NR == 1) sub(/^\u{feff}/, \"\", l); sub(/[#;].*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return tolower(l) } \ function flush() { if (boot && !done) { print want; done = 1 } } \ + NR == 1 { sub(/^\u{feff}/, \"\") } \ substr(key($0), 1, 1) == \"[\" { flush(); boot = key($0) == \"[boot]\"; print; next } \ boot && index(key($0), \"command=\") == 1 { if (!done) { print want; done = 1 } next } \ { print } \ @@ -134,7 +135,8 @@ pub fn valid_distro_name(name: &str) -> bool { !name.is_empty() && name != "." && name != ".." - && !name.contains(['/', '\\', '\0']) + && !name.starts_with('-') + && !name.contains(['/', '\\', '\0', ':', '*', '?', '"', '<', '>', '|']) && !name.bytes().any(|b| b.is_ascii_control()) } @@ -505,6 +507,16 @@ mod tests { assert_eq!(run(Some("[boot] # Kiri's\ncommand=/old # mine\n")), format!("[boot] # Kiri's\n{want}\n")); // A commented-out command is left, and one added. assert_eq!(run(Some("[boot]\n# command = /off\n")), format!("[boot]\n# command = /off\n{want}\n")); + // Case-insensitive [Boot]/Command, UTF-8 BOM, and ';' comments. + assert_eq!(run(Some("[Boot]\nCommand = /old\nsystemd = false\n")), format!("[Boot]\n{want}\nsystemd = false\n")); + assert_eq!( + run(Some("\u{feff}[BOOT]\nCOMMAND = /old\n[automount]\noptions = metadata;umask=22\n")), + format!("[BOOT]\n{want}\n[automount]\noptions = metadata;umask=22\n") + ); + assert_eq!( + run(Some("; [boot]\n[boot] ; header\n; command = /off\ncommand = /old ; inline\n")), + format!("; [boot]\n[boot] ; header\n; command = /off\n{want}\n") + ); assert_eq!(run(None), format!("[boot]\n{want}\n")); let _ = std::fs::remove_dir_all(root.parent().unwrap()); } @@ -753,4 +765,16 @@ mod ro_tests { assert!(msg.contains(r#"wsl --mount "D:\KiriData\ext4.vhdx" --vhd --bare"#), "{msg}"); assert!(msg.contains("wsl --shutdown") && msg.contains("e2fsck -f -y -D") && msg.contains("Settings -> Storage"), "{msg}"); } + + #[test] + fn validates_distro_names_and_sync_script_has_no_backslash() { + for bad in ["", ".", "..", "-e", "--shutdown", "a/b", r"a\b", "bad:distro", "bad*distro", "bad?distro", "bad\"distro", "bad|distro"] { + assert!(!valid_distro_name(bad), "expected false for {bad:?}"); + } + for good in ["Ubuntu", "Ubuntu-24.04", "NixOS", "Arch_Linux", "my.distro"] { + assert!(valid_distro_name(good), "expected true for {good:?}"); + } + assert_eq!(parse_enabled_distros(br#"{"distros":["Ubuntu","--shutdown","bad:name","NixOS"]}"#), vec!["Ubuntu".to_owned(), "NixOS".to_owned()]); + assert!(!sync_script(Path::new("C:/Users/x/AppData/Local/Kiri"), "", true).contains('\\')); + } } diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 366d1fb06..3d3a679c5 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -55,8 +55,27 @@ pub struct Release { pub notes_url: String, } -/// `1.2.10` > `1.2.9`; a missing part counts as 0. +/// Whether `v` reads as a version: `[v]N(.N)*`, optionally `-` and +/// dot-separated alphanumeric identifiers (`0.1.8-dev.42`). +fn is_version(v: &str) -> bool { + let s = v.strip_prefix('v').unwrap_or(v); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (s, None), + }; + let numeric = |seg: &str| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()); + let ident = |id: &str| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + core.split('.').all(numeric) && pre.is_none_or(|p| p.split('.').all(ident)) +} + +/// `1.2.10` > `1.2.9`; a missing part counts as 0, and a test build +/// (`0.1.8-dev.42`, scripts/ci/test-version.sh) sorts above its release. +/// A string that isn't a version is never newer, and nothing is newer +/// than one. pub fn newer(candidate: &str, current: &str) -> bool { + if !is_version(candidate) || !is_version(current) { + return false; + } let parts = |v: &str| -> Vec { v.trim_start_matches('v').split(['.', '-']).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(candidate), parts(current)); for i in 0..a.len().max(b.len()) { @@ -563,8 +582,17 @@ mod tests { assert!(newer("0.2.0", "0.1.9")); assert!(newer("1.2.10", "1.2.9")); assert!(newer("v1.0.1", "1.0")); + assert!(!newer("1.0.0", "1.0")); assert!(!newer("0.1.0", "0.1.0")); assert!(!newer("0.1.0", "0.2.0")); + // A test build (scripts/ci/test-version.sh) sorts above its release. + assert!(newer("0.1.8-dev.42", "0.1.8")); + assert!(!newer("0.1.8", "0.1.8-dev.42")); + assert!(newer("0.1.8-dev.43", "0.1.8-dev.42")); + for bad in ["", "vv1.0.0", "1.+2.0", "1.2.", "1.2.0-", "1.2.0-rc..1", "99.0.0/../../evil", "99.0.0\\evil"] { + assert!(!newer(bad, "0.2.0"), "accepted invalid candidate {bad:?}"); + assert!(!newer("99.0.0", bad), "accepted invalid current {bad:?}"); + } } #[test] From be2a1c5c998e57f47b5b0205ba77eedc4091396c Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:15:36 +0100 Subject: [PATCH 141/157] Windows: release UDP forward ports on stop, plan uppercase protocols, and keep watch events intact (#974) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri-win/src/ports.rs | 120 ++++++++++++++++++++++++------- crates/kiri-win/src/watch.rs | 134 ++++++++++++++++++++++++++++++----- 2 files changed, 211 insertions(+), 43 deletions(-) diff --git a/crates/kiri-win/src/ports.rs b/crates/kiri-win/src/ports.rs index 39ab22cd2..f8182567f 100644 --- a/crates/kiri-win/src/ports.rs +++ b/crates/kiri-win/src/ports.rs @@ -92,7 +92,8 @@ pub fn plan_forwards( } let target_addr = SocketAddr::V4(SocketAddrV4::new(wsl_ip, p.host_port)); let host_ip = p.host_ip.trim(); - match p.proto.as_str() { + let proto = p.proto.to_ascii_lowercase(); + match proto.as_str() { "udp" => { if host_ip.is_empty() || host_ip == "0.0.0.0" { specs.insert(ForwardSpec { @@ -307,9 +308,10 @@ fn copy_stream(from: &mut impl Read, to: &mut impl Write) -> io::Result<()> { struct UdpClientSession { backend: UdpSocket, + target_addr: SocketAddr, last: Arc>, stop: Arc, - reader: JoinHandle<()>, + reader: Option>, } impl UdpClientSession { @@ -321,7 +323,6 @@ impl UdpClientSession { }; let backend = UdpSocket::bind(bind_any)?; disable_udp_connreset(&backend); - backend.connect(target_addr)?; let backend_read = backend.try_clone()?; backend_read.set_read_timeout(Some(UDP_POLL))?; let reply_sock = listener.try_clone()?; @@ -331,13 +332,23 @@ impl UdpClientSession { let stop_r = stop.clone(); let reader = std::thread::Builder::new().name("kiri-win-udp-reply".into()).spawn(move || { let mut rbuf = vec![0u8; 65_536]; - while !stop_r.load(Ordering::Relaxed) { - match backend_read.recv(&mut rbuf) { - Ok(n) => { - *last_r.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); - let _ = reply_sock.send_to(&rbuf[..n], client_addr); + while !stop_r.load(Ordering::SeqCst) { + match backend_read.recv_from(&mut rbuf) { + Ok((n, from)) => { + if stop_r.load(Ordering::SeqCst) { + break; + } + if from == target_addr { + *last_r.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); + let _ = reply_sock.send_to(&rbuf[..n], client_addr); + } } - Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::Interrupted) => { + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::ConnectionReset | io::ErrorKind::Interrupted + ) => + { if last_r.lock().unwrap_or_else(PoisonError::into_inner).elapsed() >= UDP_IDLE { break; } @@ -346,12 +357,15 @@ impl UdpClientSession { } } })?; - Ok(UdpClientSession { - backend, - last, - stop, - reader, - }) + Ok(UdpClientSession { backend, target_addr, last, stop, reader: Some(reader) }) + } + + fn send(&self, payload: &[u8]) -> io::Result { + self.backend.send_to(payload, self.target_addr) + } + + fn is_finished(&self) -> bool { + self.reader.as_ref().is_none_or(JoinHandle::is_finished) } fn last_active(&self) -> Instant { @@ -362,14 +376,34 @@ impl UdpClientSession { *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); } - fn close(self) { + fn stop_inner(&mut self) { self.stop.store(true, Ordering::SeqCst); + if let Some(r) = self.reader.take() { + if !r.is_finished() + && let Ok(local) = self.backend.local_addr() + { + let wake_target = wake_connect_addr(local); + let bind_any = if wake_target.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) + }; + if let Ok(waker) = UdpSocket::bind(bind_any) { + let _ = waker.send_to(&[], wake_target); + } + } + let _ = r.join(); + } + } + + fn close(mut self) { + self.stop_inner(); } } impl Drop for UdpClientSession { fn drop(&mut self) { - self.stop.store(true, Ordering::SeqCst); + self.stop_inner(); } } @@ -439,7 +473,7 @@ fn udp_forward_loop(listener: UdpSocket, target_addr: SocketAddr, stop: Arc= Duration::from_secs(1) { last_reap = Instant::now(); - let expired: Vec = sessions - .iter() - .filter(|(_, s)| s.last_active().elapsed() >= UDP_IDLE || s.reader.is_finished()) - .map(|(k, _)| *k) - .collect(); + let expired: Vec = sessions.iter().filter(|(_, s)| s.last_active().elapsed() >= UDP_IDLE || s.is_finished()).map(|(k, _)| *k).collect(); for k in expired { if let Some(s) = sessions.remove(&k) { s.close(); @@ -982,4 +1012,46 @@ mod tests { let rebound = TcpListener::bind(fwd_addr); assert!(rebound.is_ok(), "port should be released after TcpForwarder::stop()"); } + + #[test] + fn udp_forwarder_releases_bound_port_on_stop_and_plans_uppercase_protos() { + for explicit_stop in [true, false] { + let backend = UdpSocket::bind("127.0.0.1:0").unwrap(); + backend.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let spoofer = UdpSocket::bind("127.0.0.1:0").unwrap(); + let echo = std::thread::spawn(move || { + let mut buf = [0u8; 64]; + let (n, peer) = backend.recv_from(&mut buf).unwrap(); + spoofer.send_to(b"spoofed", peer).unwrap(); + backend.send_to(&buf[..n], peer).unwrap(); + }); + + let fwd = UdpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + let fwd_addr = fwd.local_addr(); + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + client.send_to(b"ping", fwd_addr).unwrap(); + let mut rbuf = [0u8; 64]; + let (n, from) = client.recv_from(&mut rbuf).unwrap(); + assert_eq!(&rbuf[..n], b"ping"); + assert_eq!(from, fwd_addr); + echo.join().unwrap(); + + if explicit_stop { + fwd.stop(); + } else { + drop(fwd); + } + let rebound = UdpSocket::bind(fwd_addr); + assert!(rebound.is_ok(), "port should be released immediately after UdpForwarder shutdown"); + } + + let upper = vec![ + PublishedPort { proto: "UDP".into(), host_ip: "127.0.0.1".into(), host_port: 19123 }, + PublishedPort { proto: "TCP".into(), host_ip: "192.0.2.50".into(), host_port: 19124 }, + ]; + let specs = plan_forwards(Ipv4Addr::new(198, 51, 100, 107), &upper, &[Ipv4Addr::new(192, 0, 2, 50)], &[]); + assert_eq!(specs.len(), 2); + } } diff --git a/crates/kiri-win/src/watch.rs b/crates/kiri-win/src/watch.rs index 7ec41efd8..54652cc06 100644 --- a/crates/kiri-win/src/watch.rs +++ b/crates/kiri-win/src/watch.rs @@ -98,7 +98,7 @@ pub fn wsl_to_windows(wsl_path: &str, automount_root: &str) -> Option { if !automount_root.starts_with('/') || !automount_root.ends_with('/') { return None; } - if wsl_path.contains(['\n', '\r', '\0']) { + if wsl_path.contains(['\n', '\r', '\0', '\t']) { return None; } let rest = wsl_path.strip_prefix(automount_root)?; @@ -118,7 +118,7 @@ pub fn wsl_to_windows(wsl_path: &str, automount_root: &str) -> Option { if part.is_empty() { continue; } - if part == "." || part == ".." || part.contains('\\') { + if part == "." || part == ".." || part.contains(['\\', ':']) { return None; } parts.push(part); @@ -133,12 +133,12 @@ pub fn wsl_to_windows(wsl_path: &str, automount_root: &str) -> Option { /// Translates a watched Windows root (`C:\Users\me\app`) plus a relative path /// from `ReadDirectoryChangesW` (`src\main.js`) back to a WSL automount path /// (`/mnt/c/Users/me/app/src/main.js`). Rejects `..`, `.`, control characters, -/// or malformed roots. +/// NTFS Alternate Data Streams (`:`), or malformed roots. pub fn windows_to_wsl(win_root: &str, rel_win: &str, automount_root: &str) -> Option { if !automount_root.starts_with('/') || !automount_root.ends_with('/') { return None; } - if win_root.contains(['\n', '\r', '\0']) || rel_win.contains(['\n', '\r', '\0']) { + if win_root.contains(['\n', '\r', '\0', '\t']) || rel_win.contains(['\n', '\r', '\0', '\t']) { return None; } let b = win_root.as_bytes(); @@ -151,7 +151,7 @@ pub fn windows_to_wsl(win_root: &str, rel_win: &str, automount_root: &str) -> Op if part.is_empty() { continue; } - if part == "." || part == ".." { + if part == "." || part == ".." || part.contains(':') { return None; } comps.push(part); @@ -161,7 +161,7 @@ pub fn windows_to_wsl(win_root: &str, rel_win: &str, automount_root: &str) -> Op if part.is_empty() { continue; } - if part == "." || part == ".." { + if part == "." || part == ".." || part.contains(':') { return None; } comps.push(part); @@ -239,9 +239,9 @@ pub fn decode_notify_buffer(buf: &[u8]) -> Vec<(char, String)> { /// Merges two ops for the same path arriving within one 50 ms debounce window. fn merge_op(prev: char, next: char) -> char { match (prev, next) { - (_, 'D') => 'D', - ('C', 'M') | ('M', 'C') | ('C', 'C') => 'C', - ('D', 'C') | ('D', 'M') | ('M', 'M') => 'M', + (_, 'D') | ('D', 'A') => 'D', + ('C', 'M') | ('M', 'C') | ('C', 'C') | ('C', 'A') | ('A', 'C') => 'C', + ('D', 'C') | ('D', 'M') | ('M', 'M') | ('M', 'A') | ('A', 'M') => 'M', _ => next, } } @@ -417,37 +417,40 @@ mod runtime { } } - struct DirWatcher { + pub(super) struct DirWatcher { /// Manual-reset event: once set, the worker's wait returns at once, /// whether it is waiting already or not yet. stop: HANDLE, thread: Option>, + /// Whether `watch_dir_loop` opened the directory and emitted `P`. + pinned: Arc, /// The root's WSL path and the channel its `U` line goes out on. unpin: Option<(String, mpsc::Sender<(char, String)>)>, } impl DirWatcher { - fn start(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>) -> Option { + pub(super) fn start(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>) -> Option { // SAFETY: an unnamed manual-reset event, initially not set. let stop = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; if stop == 0 { return None; } let pin = if spec.recursive { wsl_dir(&spec.dir, &automount_root) } else { None }; + let pinned = Arc::new(AtomicBool::new(false)); + let pinned_w = pinned.clone(); + let pin_w = pin.clone(); let tx_c = tx.clone(); - let thread = std::thread::Builder::new().name("kiri-win-dirwatch".into()).spawn(move || watch_dir_loop(spec, automount_root, tx_c, stop)); + let thread = + std::thread::Builder::new().name("kiri-win-dirwatch".into()).spawn(move || watch_dir_loop(spec, automount_root, tx_c, stop, pin_w, pinned_w)); let Ok(thread) = thread else { // SAFETY: our own event, never shared. unsafe { CloseHandle(stop) }; return None; }; - if let Some(root) = &pin { - let _ = tx.send(('P', root.clone())); - } - Some(DirWatcher { stop, thread: Some(thread), unpin: pin.map(|root| (root, tx)) }) + Some(DirWatcher { stop, thread: Some(thread), pinned, unpin: pin.map(|root| (root, tx)) }) } - fn stop(mut self) { + pub(super) fn stop(mut self) { // SAFETY: `self.stop` stays open until after the join below. unsafe { SetEvent(self.stop) }; if let Some(t) = self.thread.take() { @@ -455,7 +458,9 @@ mod runtime { } // SAFETY: the worker has exited; nothing else uses the event. unsafe { CloseHandle(self.stop) }; - if let Some((root, tx)) = self.unpin.take() { + if self.pinned.load(Ordering::Acquire) + && let Some((root, tx)) = self.unpin.take() + { let _ = tx.send(('U', root)); } } @@ -463,7 +468,7 @@ mod runtime { /// Reads changes with overlapped `ReadDirectoryChangesW`, waiting on the /// read and `stop` together, so a stop ends the wait at once. - fn watch_dir_loop(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>, stop: HANDLE) { + fn watch_dir_loop(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>, stop: HANDLE, pin: Option, pinned: Arc) { let wide: Vec = OsStr::new(&spec.dir).encode_wide().chain(std::iter::once(0)).collect(); // SAFETY: valid NUL-terminated UTF-16 path with standard directory flags. let h = unsafe { @@ -487,6 +492,17 @@ mod runtime { unsafe { CloseHandle(h) }; return; } + if let Some(root) = &pin { + if tx.send(('P', root.clone())).is_err() { + // SAFETY: closing our own handles before any read is started. + unsafe { + CloseHandle(io); + CloseHandle(h); + } + return; + } + pinned.store(true, Ordering::Release); + } // 64 KiB DWORD-aligned buffer as required by ReadDirectoryChangesW. let mut buf = vec![0u32; 16384]; @@ -792,4 +808,84 @@ mod tests { ] ); } + + #[test] + fn preserves_mutations_across_attribute_events_and_rejects_ads_and_tabs() { + let expected_pairs = [ + (('C', 'C'), 'C'), + (('C', 'M'), 'C'), + (('C', 'A'), 'C'), + (('C', 'D'), 'D'), + (('M', 'C'), 'C'), + (('M', 'M'), 'M'), + (('M', 'A'), 'M'), + (('M', 'D'), 'D'), + (('A', 'C'), 'C'), + (('A', 'M'), 'M'), + (('A', 'A'), 'A'), + (('A', 'D'), 'D'), + (('D', 'C'), 'M'), + (('D', 'M'), 'M'), + (('D', 'A'), 'D'), + (('D', 'D'), 'D'), + ]; + for ((first, second), want) in expected_pairs { + assert_eq!(coalesce_events(&[(first, "/mnt/c/app/f.js".into()), (second, "/mnt/c/app/f.js".into())]), vec![format!("{want}\t/mnt/c/app/f.js")]); + } + + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"assets\logo.png:Zone.Identifier:$DATA", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\bad:ads", r"a.js", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", "src\\bad\tname.js", "/mnt/"), None); + assert_eq!(windows_to_wsl("C:\\Users\\bad\troot", r"a.js", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/me/bad\tname", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/me/file:Zone.Identifier", "/mnt/"), None); + } + + #[cfg(windows)] + #[test] + fn dir_watcher_emits_pin_before_events_and_skips_unopened_roots() { + let (vtx, vrx) = std::sync::mpsc::channel(); + let vanished = WatchSpec { dir: format!(r"C:\kiri-nonexistent-watch-{}", std::process::id()), recursive: true, only_file: None }; + if let Some(w) = runtime::DirWatcher::start(vanished, "/mnt/".into(), vtx) { + w.stop(); + } + assert!(vrx.try_recv().is_err(), "unopened directory must emit neither P nor U"); + + let dir = std::env::temp_dir().join(format!("kiri-win-watch-pin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let win_dir = dir.to_string_lossy().replace('/', "\\"); + let wsl_root = wsl_dir(&win_dir, "/mnt/").unwrap(); + + let (tx, rx) = std::sync::mpsc::channel(); + let spec = WatchSpec { dir: win_dir, recursive: true, only_file: None }; + let watcher = runtime::DirWatcher::start(spec, "/mnt/".into(), tx).unwrap(); + + let first = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + assert_eq!(first, ('P', wsl_root.clone())); + + let file = dir.join("app.js"); + std::fs::write(&file, b"1\n").unwrap(); + let _ = std::fs::write(format!("{}:Zone.Identifier", file.display()), b"[ZoneTransfer]\r\nZoneId=3\r\n"); + + let want_file = format!("{wsl_root}/app.js"); + let mut saw_file = false; + while !saw_file { + let (op, path) = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + assert!(!path.contains(":Zone.Identifier"), "ADS event leaked: {path}"); + if path == want_file { + assert!(matches!(op, 'C' | 'M')); + saw_file = true; + } + } + + watcher.stop(); + let mut tail = Vec::new(); + while let Ok(ev) = rx.try_recv() { + assert!(!ev.1.contains(":Zone.Identifier")); + tail.push(ev); + } + assert_eq!(tail.last(), Some(&('U', wsl_root))); + let _ = std::fs::remove_dir_all(&dir); + } } From 93ff60c77093c54205208b393151db2eaf44896f Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:16:35 +0100 Subject: [PATCH 142/157] Arch: package Kiri desktop UI (#526) Co-authored-by: Cesar Roberto Pamplona Filho --- .gitignore | 3 +++ packaging/README.md | 9 ++++++++ packaging/arch/PKGBUILD | 47 ++++++++++++++++++++++++++++++++++++++++ packaging/arch/README.md | 22 +++++++++++++++++++ 4 files changed, 81 insertions(+) create mode 100644 packaging/arch/PKGBUILD create mode 100644 packaging/arch/README.md diff --git a/.gitignore b/.gitignore index 110daab99..dd0efb3cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ /target +/packaging/arch/src/ +/packaging/arch/pkg/ +/packaging/arch/*.pkg.tar.zst # Raw benchmark output: kept outside this repository. /bench/results/ /guest/out/ diff --git a/packaging/README.md b/packaging/README.md index d0cc7733f..212096dcc 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -86,6 +86,15 @@ there, so it wants `KIRI_TEST_KILL=1`). Not yet: an apt/dnf repository (today the packages are release assets; a repository is what gives `apt upgrade`), and signing. +## Arch Linux + +`arch/PKGBUILD` builds `kiri-ui`, the desktop window (`kiri --features window`), +for Arch Linux (`x86_64` and `aarch64`, including Omarchy and Asahi). It +installs `/usr/lib/kiri/kiri-window` where `kiri ui` expects it, plus the +application-menu launcher and icons, without replacing an installed Kiri engine, +CLI, systemd service, Docker context, or container store. See `arch/README.md` +for build and install steps. + ## Homebrew (planned, not built) The Mac already has the app and the dmg; Homebrew is the third way in, for diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD new file mode 100644 index 000000000..8c59c052e --- /dev/null +++ b/packaging/arch/PKGBUILD @@ -0,0 +1,47 @@ +pkgname=kiri-ui +pkgver=0.2.2 +pkgrel=1 +pkgdesc='Desktop window for the Kiri container runtime' +arch=('x86_64' 'aarch64') +options=('!lto') +url='https://runkiri.com' +license=('Apache-2.0') +depends=('gtk3' 'webkit2gtk-4.1') +makedepends=('rust' 'pkgconf') +optdepends=( + 'kiri: Kiri engine and CLI, required to manage containers' + 'polkit: graphical password prompt for engine setup' +) +source=("https://github.com/libracoder/kiri/archive/refs/tags/v${pkgver}.tar.gz") +sha256sums=('aaa88911bdfc8e83253cefc9cfd884c3d0aa55ee9dc1f67a19b94564dde6fbbf') + +prepare() { + cd "kiri-${pkgver}" + + # Release archives keep 0.0.0 in the workspace manifest; stamp pkgver into + # Cargo.toml and sync workspace member entries in Cargo.lock offline. + sed -i "0,/^version = \"0.0.0\"$/s//version = \"${pkgver}\"/" Cargo.toml + cargo update --workspace --offline +} + +build() { + cd "kiri-${pkgver}" + cargo build --locked --release -p kiri --features window +} + +package() { + cd "kiri-${pkgver}" + + install -Dm755 target/release/kiri "$pkgdir/usr/lib/kiri/kiri-window" + install -Dm644 contrib/linux/kiri.desktop "$pkgdir/usr/share/applications/kiri.desktop" + install -Dm644 brand/icon/kiri-app-icon.svg \ + "$pkgdir/usr/share/icons/hicolor/scalable/apps/kiri.svg" + + for size in 16 32 64 128 256 512; do + install -Dm644 "brand/icon/png/kiri-app-icon-${size}.png" \ + "$pkgdir/usr/share/icons/hicolor/${size}x${size}/apps/kiri.png" + done + + install -Dm644 LICENSE "$pkgdir/usr/share/licenses/${pkgname}/LICENSE" + install -Dm644 NOTICE "$pkgdir/usr/share/licenses/${pkgname}/NOTICE" +} diff --git a/packaging/arch/README.md b/packaging/arch/README.md new file mode 100644 index 000000000..1f2316f73 --- /dev/null +++ b/packaging/arch/README.md @@ -0,0 +1,22 @@ +# Kiri UI on Arch Linux + +`kiri-ui` packages the Linux desktop window (`kiri --features window`) for Arch +Linux (`x86_64` and `aarch64`, including Omarchy and Asahi). It installs the +executable at `/usr/lib/kiri/kiri-window`, where `kiri ui` launches it, along +with the desktop entry and icons. + +The package intentionally leaves the Kiri engine, CLI, Docker context, and +container store untouched. Install it alongside an existing Kiri Linux engine +and CLI. GTK 3 and WebKitGTK 4.1 are required to build and run the window. + +Build and install locally: + +```sh +cd packaging/arch +makepkg -si +kiri ui --view containers +``` + +When updating `pkgver`, update `sha256sums` to the matching upstream release tag +archive (`v${pkgver}.tar.gz`) and keep the offline workspace version stamp in +`prepare()` so the window reports the installed package version. From 7cf1cac3118e954f21b3f87d65377d36c39a3fb7 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:17:53 +0100 Subject: [PATCH 143/157] Add Nix flake and NixOS module (#335) Co-authored-by: Victor Borja --- .gitignore | 4 ++ flake.lock | 27 ++++++++++++ flake.nix | 105 ++++++++++++++++++++++++++++++++++++++++++++ packaging/README.md | 9 ++++ 4 files changed, 145 insertions(+) create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.gitignore b/.gitignore index dd0efb3cf..b5cf175ab 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,10 @@ /guest/out/ .wrangler/ +# Nix build symlinks +result +result-* + # Built binaries and downloaded installers: never in the repo. The Windows # bundle (cargo xtask windows) lands under /target and is shared from there. *.exe diff --git a/flake.lock b/flake.lock new file mode 100644 index 000000000..6c335e223 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1794537146, + "narHash": "sha256-Wpz/7x/YWnDIBu7yj6ixe8j6fIMsidd9Y+o1PqPF3iM=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "d5cc6833999746cffdfe0598f7bc801a57b887a9", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 000000000..61476d18d --- /dev/null +++ b/flake.nix @@ -0,0 +1,105 @@ +{ + description = "Kiri container engine"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { self, nixpkgs }: + let + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAllSystems = nixpkgs.lib.genAttrs systems; + packages = forAllSystems (system: + let + pkgs = import nixpkgs { inherit system; }; + manifestVersion = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version; + kiri = pkgs.rustPlatform.buildRustPackage { + pname = "kiri"; + version = + if manifestVersion != "0.0.0" then manifestVersion + else "0.0.0-${self.shortRev or self.dirtyShortRev or "dev"}"; + src = self; + + cargoLock.lockFile = ./Cargo.lock; + cargoBuildFlags = [ "-p" "kiri" "-p" "kiri-init" ]; + cargoTestFlags = [ "-p" "kiri" "-p" "kiri-init" ]; + + # Some unit tests inspect /home or require real root namespaces absent in the Nix build sandbox. + doCheck = false; + + postInstall = '' + install -Dm644 packaging/linux/dev.kiri.host-access.policy \ + "$out/share/polkit-1/actions/dev.kiri.host-access.policy" + ''; + + meta = { + description = "Small, fast container runtime"; + homepage = "https://runkiri.com/"; + license = pkgs.lib.licenses.asl20; + platforms = systems; + mainProgram = "kiri"; + }; + }; + in + { + inherit kiri; + default = kiri; + }); + in + { + packages = packages; + + nixosModules.default = { config, lib, pkgs, ... }: + let + cfg = config.services.kiri; + in + { + options.services.kiri = { + enable = lib.mkEnableOption "the Kiri container engine"; + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.kiri; + defaultText = lib.literalExpression "inputs.kiri.packages.\${pkgs.stdenv.hostPlatform.system}.kiri"; + description = "The Kiri package to run and install."; + }; + }; + + config = lib.mkIf cfg.enable { + environment.systemPackages = [ cfg.package ]; + users.groups.kiri = { }; + + environment.etc."NetworkManager/conf.d/kiri.conf" = lib.mkIf config.networking.networkmanager.enable { + source = ./packaging/linux/kiri-nm.conf; + }; + + systemd.services.kiri = { + description = "Kiri container engine"; + documentation = [ "https://runkiri.com" ]; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" "docker.service" ]; + path = [ pkgs.nftables pkgs.iptables pkgs.coreutils ]; + serviceConfig = { + ExecStart = "${cfg.package}/bin/kiri daemon"; + ExecStartPost = "-${pkgs.runtimeShell} -c '[ \"$(readlink /run/docker.sock)\" = /run/kiri/docker.sock ] || [ -e /run/docker.sock ] || [ -L /run/docker.sock ] || ln -s /run/kiri/docker.sock /run/docker.sock'"; + ExecStopPost = "-${pkgs.runtimeShell} -c '[ \"$(readlink /run/docker.sock)\" != /run/kiri/docker.sock ] || rm -f /run/docker.sock'"; + Environment = [ + "KIRI_SOCKET=/run/kiri/docker.sock" + "KIRI_SOCKET_GROUP=kiri" + "HOME=/var/lib/kiri-daemon" + ]; + Delegate = true; + LimitNPROC = "infinity"; + LimitCORE = "infinity"; + TasksMax = "infinity"; + KillMode = "mixed"; + Restart = "on-failure"; + RuntimeDirectory = "kiri"; + RuntimeDirectoryMode = "0755"; + StateDirectory = "kiri-daemon"; + StateDirectoryMode = "0700"; + UMask = "0027"; + }; + }; + }; + }; + }; +} diff --git a/packaging/README.md b/packaging/README.md index 212096dcc..856dbde1e 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -95,6 +95,15 @@ application-menu launcher and icons, without replacing an installed Kiri engine, CLI, systemd service, Docker context, or container store. See `arch/README.md` for build and install steps. +## Nix and NixOS + +`flake.nix` builds `kiri` and `kiri-init` on `x86_64-linux` and `aarch64-linux` +(`nix build .#kiri`), and exports `nixosModules.default` (`services.kiri.enable = true;`), +which creates the `kiri` group, configures NetworkManager to leave Kiri's +bridges and veths unmanaged, and runs `kiri.service` with the same cgroup +delegation, resource limits, and `/run/docker.sock` fallback link as the `.deb` +and `.rpm` packages. + ## Homebrew (planned, not built) The Mac already has the app and the dmg; Homebrew is the third way in, for From 7779274308f3d73eff25797097cbb4e10f8d83ac Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 07:19:48 +0100 Subject: [PATCH 144/157] UI: show universal Restarting overlay and shared spinner across all restarts --- crates/kiri-win/src/update.rs | 1 + crates/kiri-win/src/wslconfig.rs | 8 +- crates/kiri/src/ui/index.html | 148 ++++++++++++++++++++++++------- crates/kiri/src/ui/mod.rs | 27 +++--- tests/ui/restartnow.js | 130 +++++++++++++++++++++++++-- 5 files changed, 264 insertions(+), 50 deletions(-) diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index c188c071e..0cb3aea50 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -726,6 +726,7 @@ fn restart_and_report() { } Err(e) => { crate::serve::log(&format!("engine: did not restart ({e})")); + emit(json!({"type": "enginerestarted", "error": e.to_string()}).to_string()); emit(notice("error", &trf("Could not restart the engine: {error}", &[("error", &e)]))); if let Some(v) = engine_version() && newer(CURRENT, &v) diff --git a/crates/kiri-win/src/wslconfig.rs b/crates/kiri-win/src/wslconfig.rs index 466d33815..ab5a7a92b 100644 --- a/crates/kiri-win/src/wslconfig.rs +++ b/crates/kiri-win/src/wslconfig.rs @@ -334,17 +334,23 @@ pub fn resources(body: Option) { /// Restart to apply: WSL stops and Kiri's engine starts again. pub fn restart() { std::thread::spawn(|| { + emit(json!({"type": "state", "state": "stopping"}).to_string()); let mut cmd = crate::win::tool("wsl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| crate::engine::ensure_daemon()); + let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| { + emit(json!({"type": "state", "state": "booting"}).to_string()); + crate::engine::ensure_daemon() + }); if r.is_ok() { let _ = apply_wsl_integration(None, true); } + emit(json!({"type": "vmrestarted", "ok": r.is_ok()}).to_string()); emit(match r { Ok(()) => notice("ok", &tr("WSL restarted with the new resources")), Err(e) => notice("error", &trf("Could not restart WSL: {error}", &[("error", &e)])), }); emit(event().to_string()); + crate::engine::send(crate::engine::Cmd::Refresh); }); } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index a85c0833e..c0c677fbd 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -160,7 +160,7 @@ body.rail[data-vm=running] .vm .dot::after { content: ""; position: absolute; inset: 0; border-radius: 50%; background: var(--moss); --ring: 2.8; animation: var(--beat); pointer-events: none; } .mark .speed { fill: currentColor; opacity: .35; transition: opacity .3s; } [data-vm=running] .mark .speed { opacity: .9; } -[data-vm=booting] .mark .speed { animation: zoom .25s infinite alternate; } +[data-vm=booting] .mark .speed, [data-vm=restarting] .mark .speed { animation: zoom .25s infinite alternate; } [data-vm=stopped] .mark .eyes, [data-vm=asleep] .mark .eyes { transform: scaleY(.25); transform-origin: 46px 29px; } .navlabel { font-size: var(--fs); font-weight: 600; color: var(--faint); padding: 10px 8px 4px; text-transform: uppercase; letter-spacing: .06em; } @@ -180,7 +180,7 @@ .vm-head { display: flex; align-items: center; gap: 7px; font-weight: 600; } .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; } [data-vm=running] .dot { background: var(--moss); box-shadow: 0 0 0 3px color-mix(in srgb, var(--moss) 25%, transparent); } -[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } +[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot, [data-vm=restarting] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } [data-vm=asleep] .dot { background: transparent; box-shadow: inset 0 0 0 2px var(--moss); } .vm-sub { color: var(--faint); font-size: var(--fs-small); margin-top: -6px; } #vm-state { margin-inline-start: auto; font-weight: 500; color: var(--muted); font-size: var(--fs); } @@ -868,7 +868,7 @@ .statusbar .k8s { width: 13px; height: 13px; fill: #326CE5; flex: none; } .statusbar .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); } .statusbar .dot.running { background: var(--moss); } -.statusbar .dot.booting, .statusbar .dot.stopping { background: var(--sun); } +.statusbar .dot.booting, .statusbar .dot.stopping, .statusbar .dot.restarting { background: var(--sun); } .statusbar .dot.asleep { background: transparent; box-shadow: inset 0 0 0 1.5px var(--moss); } .statusbar .sep { color: var(--faint); } /* Kiri Dev, after the version: solid amber with near-black text, the same in either theme. */ @@ -1234,7 +1234,7 @@ #onb .st.no, #onb .st.restart { background: rgba(255, 194, 61, .15); color: var(--sun-text); } #onb .st.bad { background: rgba(220, 53, 69, .16); color: var(--red-text); } #onb .st.off { background: var(--raised); color: var(--faint); } -#onb .st.wait { border: 2px solid var(--line); border-top-color: var(--blue); animation: onbspin .8s linear infinite; } +#onb .st.wait { border: 2px solid color-mix(in srgb, var(--sun) 20%, var(--line)); border-top-color: var(--sun); border-right-color: color-mix(in srgb, var(--sun) 65%, transparent); animation: onbspin .8s linear infinite; } @keyframes onbspin { to { transform: rotate(360deg); } } #onb .btn svg.i { width: 13px; height: 13px; } #onb .onb-ft { display: flex; align-items: center; gap: 8px; margin-top: 14px; } @@ -1249,6 +1249,26 @@ #onb .onb-rs p { color: var(--muted); font-size: var(--fs-small); margin: 2px 0 8px; } #onb .onb-rs .a { display: flex; gap: 6px; } .scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); display: grid; place-items: center; z-index: 8; } +/* Universal Restarting overlay & shared restarting spinner (.rspin). */ +.rspin { --sz: 40px; position: relative; width: var(--sz); height: var(--sz); display: inline-grid; place-items: center; flex: none; } +.rspin::before { content: ""; position: absolute; inset: 0; border-radius: 50%; border: 2.5px solid color-mix(in srgb, var(--sun) 20%, var(--line)); border-top-color: var(--sun); border-right-color: color-mix(in srgb, var(--sun) 65%, transparent); animation: spin .85s cubic-bezier(.42, .15, .58, .85) infinite; } +.rspin.sm { --sz: 16px; } +.rspin.sm::before { border-width: 2px; } +.rspin.md { --sz: 28px; } +.rspin.md::before { border-width: 2.2px; } +.rspin .kdot { width: 16px; height: 17px; animation: bob 1.5s ease-in-out infinite; } +.rspin.md .kdot { width: 12px; height: 13px; } +.rspin.plain .kdot { display: none; } +.rscrim { position: fixed; inset: 0; z-index: 25; background: rgba(8, 12, 16, .58); -webkit-backdrop-filter: blur(3px); backdrop-filter: blur(3px); display: grid; place-items: center; animation: sh-fade .16s ease-out; } +@media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) .rscrim { background: rgba(15, 20, 25, .36); } } +:root[data-theme="light"] .rscrim { background: rgba(15, 20, 25, .36); } +.rdlg { width: min(360px, calc(100% - 32px)); background: var(--panel); border: 1px solid color-mix(in srgb, var(--sun) 32%, var(--line)); border-radius: 14px; padding: 24px 22px 20px; display: grid; justify-items: center; text-align: center; gap: 8px; box-shadow: 0 24px 60px rgba(0, 0, 0, .48); animation: sh-rise .2s ease-out; } +.rdlg h3 { font-size: var(--fs-head); font-weight: 700; letter-spacing: -.01em; margin-top: 4px; } +.rdlg .rwhat { color: var(--muted); font-size: var(--fs); max-width: 300px; line-height: 1.45; overflow-wrap: anywhere; } +.rdlg .rstep { margin-top: 4px; display: inline-flex; align-items: center; gap: 7px; padding: 4px 11px; border-radius: 999px; background: var(--raised); border: 1px solid var(--line); font-size: var(--fs-small); color: var(--muted); font-variant-numeric: tabular-nums; max-width: 100%; } +.rdlg .rstep i { width: 6px; height: 6px; border-radius: 50%; background: var(--sun); flex: none; animation: pulse .75s infinite alternate; } +.rdlg .rbar { width: 100%; height: 4px; border-radius: 99px; background: var(--raised); overflow: hidden; margin-top: 6px; } +.rdlg .rbar span { display: block; height: 100%; background: var(--sun); border-radius: 99px; transition: width .35s ease; } /* The language step's dialog takes its height from this box, not the window's: Text size zooms the page, and 100vh would be the unzoomed window. */ .scrim.langstep { z-index: 40; grid-template: minmax(0, 1fr) / minmax(0, 1fr); } @@ -2610,6 +2630,7 @@

Containers

+ @@ -2815,15 +2836,15 @@

Containers

Containers

const v = ui.vmnet; if (!v || v.supported === false) return ""; const nat = v.shared_nat !== false; + const pending = v.awake && v.running_shared_nat != null && v.running_shared_nat !== nat; const desc = nat ? tr("macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.") : tr("Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart."); const envNote = v.env ? ` ${tr("KIRI_SHARED_NAT is set in the environment and takes precedence.")}` : ""; return `
${tr("Outbound VM traffic")} ${desc}${envNote} -
`; +
${pending ? `` : ""}
`; } function networkPane() { @@ -4703,8 +4762,8 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const { shown } = engineShown(), off = shown === "stopped"; const d = off ? tr("Off: press Start engine to run containers. It stays off after a restart until you start it.") : shown === "running" ? tr("Running: it rests by itself when nothing runs and wakes when you use it.") - : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : ""; - const busy = shown === "booting" || shown === "stopping"; + : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : shown === "restarting" ? tr("Restarting…") : ""; + const busy = shown === "booting" || shown === "stopping" || shown === "restarting"; const btn = off ? `` : ``; return `

${tr(VM)}

${vmLabels[shown] != null ? tr(vmLabels[shown]) : "—"}${d}${btn}
`; @@ -4893,7 +4952,7 @@

${tr("Storage location unavailable")}

const m = s.moving; const pct = m && m.total > 0 ? Math.min(100, Math.round((m.done / m.total) * 100)) : null; const progressBox = moving && m ? `
-
${stPhaseText(m.phase)}
+
${rspin("sm plain")}${stPhaseText(m.phase)}

${tr("Moving Kiri's data to {path}.", { path: `${esc(m.to || "")}` })}

${pct != null ? `

${size(m.done)} / ${size(m.total)} (${pct}%)

` : ""}

${tr("Running containers pause while Kiri copies its data and start again once it's done.")}

@@ -4961,6 +5020,7 @@

${tr("Storage location unavailable")}

if (ev.target.closest("[data-stgo]")) { const fresh = scrim.querySelector('input[name="st-mode"]:checked')?.value === "fresh"; ui.stErr = ""; + startRestartOverlay("storage", c.reset ? tr("Kiri will switch to this folder and restart the engine.") : tr("Moving Kiri's data to {path}.", { path: `${esc(c.path)}` }), tr("Stopping containers…")); if (c.reset) send("storagereset"); else send("storagemove", { path: c.path, value: { fresh } }); close(); @@ -7266,7 +7326,7 @@

${tr("Scan {image}", { image: esc(label) })}

const k8s = ui.containers.find((c) => c.Names?.[0] === "/kiri-k8s" && c.State === "running"); const k8sVersion = k8s ? (k8s.Image.split(":")[1] || "").replace(/-k3s\d+$/, "") : ""; const { shown: vshown } = engineShown(); - const vmText = { running: tr("{vm} running", { vm: tr(VM) }), stopped: tr("{vm} off", { vm: tr(VM) }), booting: tr("Starting…"), stopping: tr("Stopping…") }[vshown] || vshown; + const vmText = { running: tr("{vm} running", { vm: tr(VM) }), stopped: tr("{vm} off", { vm: tr(VM) }), booting: tr("Starting…"), stopping: tr("Stopping…"), restarting: tr("Restarting…") }[vshown] || vshown; const mem = ui.mem ? tr("{used} of {total}", { used: memText(ui.mem.used), total: `${Math.round(ui.mem.ceiling / 1024)} GB` }) : ""; const parts = [ `${KDOT}Kiri ${esc(ui.status?.version || "")}${ui.status?.dev ? `DEV` : ""}`, @@ -7333,7 +7393,7 @@

${tr("Scan {image}", { image: esc(label) })}

} else if (u?.phase === "ready") { row = `${tr("Kiri {version} is downloaded", { version: esc(u.version) })}${btn(tr("Restart to update"), 'data-upd="restart"', "primary")}`; } else if (u?.phase === "available") { - const whatsNew = u.notes.trim() || NOTES_URL.test(u.notesUrl) ? `` : ""; + const whatsNew = (u.notes || "").trim() || NOTES_URL.test(u.notesUrl) ? `` : ""; row = `${tr("Version {version}", { version: v })}${tr("{version} available", { version: esc(u.version) })}${btn(u.error ? tr("Try again") : tr("Download"), 'data-upd="download"', "primary")}${whatsNew}`; } else if (s?.state === "available") { row = `${tr("Version {version}", { version: v })}${tr("{version} available", { version: esc(s.latest) })}${btn(tr("Show"), "data-updcheck", "primary")}`; @@ -7346,7 +7406,7 @@

${tr("Scan {image}", { image: esc(label) })}

} else if (s?.state === "error") { row = `${tr("Version {version}", { version: v })}${tr("Couldn't check: {error}", { error: esc(s.error || "") })}${check}`; } else row = `${tr("Version {version}", { version: v })}${check}`; - const notes = u?.phase === "available" && u.notes.trim() ? `
${tr("What's new in {version}", { version: esc(u.version) })}${notesHtml(u.notes)}
` : ""; + const notes = u?.phase === "available" && (u.notes || "").trim() ? `
${tr("What's new in {version}", { version: esc(u.version) })}${notesHtml(u.notes)}
` : ""; const fixed = s?.state === "test" || s?.state === "dev"; const auto = prefs.updateAuto !== false; return `
${row}
${notes}${fixed ? "" : `
${tr("Check for updates automatically")}${auto ? tr("On: Kiri checks each time it opens. It never updates without asking.") : tr("Off: Kiri checks only when you click Check now.")} @@ -7362,8 +7422,8 @@

${tr("Scan {image}", { image: esc(label) })}

${UPD_ICON[ic]}

${esc(title)}

${sub}
${close ? `` : ""}
${body}
`; if (u && !u.hidden && u.phase === "available") { - const whatsNew = u.notes.trim() || NOTES_URL.test(u.notesUrl) ? ` · ` : ""; - const sub = `${tr("You have {version}", { version: esc(u.current) })}${whatsNew}${u.error ? `
${tr("Couldn't download it: {error}", { error: esc(u.error) })}
` : ""}`; + const whatsNew = (u.notes || "").trim() || NOTES_URL.test(u.notesUrl) ? ` · ` : ""; + const sub = `${tr("You have {version}", { version: esc(u.current || "") })}${whatsNew}${u.error ? `
${tr("Couldn't download it: {error}", { error: esc(u.error) })}
` : ""}`; el.innerHTML = card("up", tr("Kiri {version} is available", { version: u.version }), sub, "hide", `
${btn(u.error ? tr("Try again") : tr("Download"), 'data-upd="download"', "primary")} ${u.snoozing ? `${btn(tr("Tomorrow"), 'data-upd="snooze1"')}${btn(tr("In a week"), 'data-upd="snooze7"')}` : btn(tr("Snooze ▾"), 'data-upd="snooze" aria-haspopup="true"')} @@ -7388,9 +7448,9 @@

${tr("Scan {image}", { image: esc(label) })}

case "snooze1": snooze(1); break; case "snooze7": snooze(7); break; case "skip": setPref("updateSkip", u.version); ui.upd = null; break; - case "notes": if (u.notes.trim()) openNotes(); else send("updatenotes", { name: u.notesUrl }); break; - case "restart": send("updaterestart"); break; - case "engine": send("restartengine"); ui.engineStale = null; break; + case "notes": if ((u?.notes || "").trim()) openNotes(); else send("updatenotes", { name: u?.notesUrl || "" }); break; + case "restart": startRestartOverlay("update", tr("Finish updating to Kiri {version}", { version: esc(u?.version || "") }), tr("Restarting…")); send("updaterestart"); break; + case "engine": startRestartOverlay("engine", tr("Finish updating to Kiri {version}", { version: esc(ui.status?.version || "") }), tr("Restarting engine…")); send("restartengine"); ui.engineStale = null; break; case "enginelater": ui.staleHidden = true; break; case "showengine": ui.staleHidden = false; break; } @@ -7553,6 +7613,10 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) } function setVm(state, error) { + if (ui.restarting && ["vm", "engine", "reclaim"].includes(ui.restarting.kind)) { + if (state === "stopping") setRestartStep(tr("Stopping containers…")); + else if (state === "booting") setRestartStep(tr("Starting…")); + } if (ui.vm !== state) { const was = ui.vm; ui.vm = state; @@ -7576,6 +7640,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) VM rests to save memory and the next docker command wakes it, so it reads Running, and waking does too. Off is only Stop (or no engine at all). */ function engineShown() { + if (ui.restarting && ui.restarting.kind !== "k8s") return { look: "restarting", on: false, shown: "restarting" }; const look = ui.vmLook || ui.vm; const shown = ui.vm === "stopped" ? "stopped" : ui.vm === "stopping" ? "stopping" @@ -7595,7 +7660,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) const { shown } = engineShown(); document.body.dataset.vm = shown; const label = tr(vmLabels[shown] ?? shown); - /* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…")]; + /* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…"), tr("Restarting…")]; $("vm-state").textContent = label; const sub = $("vm-sub"); sub.textContent = ""; sub.hidden = true; @@ -7605,9 +7670,9 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) /* When it last turned into a Stop button: see the press guard below. */ const act = shown === "running" ? "stop" : "start"; if (b.dataset.act !== act) { b.dataset.act = act; b.dataset.flipped = String(Date.now()); } - b.textContent = shown === "running" ? tr("Stop") : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : tr("Start"); - b.classList.toggle("primary", shown !== "running"); - b.disabled = shown === "booting" || shown === "stopping"; + b.textContent = shown === "running" ? tr("Stop") : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : shown === "restarting" ? tr("Restarting…") : tr("Start"); + b.classList.toggle("primary", shown !== "running" && shown !== "restarting"); + b.disabled = shown === "booting" || shown === "stopping" || shown === "restarting"; headTitles(); } /* The name or state says itself on hover only when it is cut. */ @@ -7739,7 +7804,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) // Resources saved while the VM runs: restart it now to use them. if (!error && act === "restartvm") { el.querySelector(".txt").insertAdjacentHTML("beforeend", `
`); - el.querySelector("[data-trestart]").addEventListener("click", () => { el.remove(); send("restartvm"); }); + el.querySelector("[data-trestart]").addEventListener("click", () => { el.remove(); restartVm(); }); } $("toasts").append(el); retire(el, ms); @@ -8513,7 +8578,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r ${done ? `
${tr("Report ID")}${esc(rp.id)}
` : ""} ${rp.error ? `

${send_ ? tr("Couldn't send it: {error}", { error: esc(rp.error) }) : tr("Couldn't save it: {error}", { error: esc(rp.error) })}

` : ""}
${done ? `` - : ` `}

`; + : ` `}
`; } /* The card after a crash, in the update card's place (an update offer goes @@ -8683,6 +8748,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (e.kind === "search" && [...ui.pulls.values()].some((p) => p.kind === "notfound")) pullsChanged(); break; case "notice": + if (ui.restarting && (ui.restarting.kind === "vm" || (e.kind === "error" && ["storage", "engine", "update", "reclaim"].includes(ui.restarting.kind)))) stopRestartOverlay(); // Each pod a batch deletes says so; the batch's own toast already has. if (e.kind === "ok" && /^Deleting pod /.test(e.text) && ui.batches.some((b) => b.view === "pods" && b.phase === "going")) break; if (e.kind === "ok" && e.image && e.open) { ui.launched.set(e.image, e.open); runHold(e.image, e.text, e.open, e.ms); break; } @@ -8712,7 +8778,8 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "textsize": if (htHasFocus()) htStep(e.step); else stepTextSize(e.step); break; case "term": htOn(e); break; case "closekey": htCloseKey(); break; - case "enginerestarted": engineToast(e); break; + case "vmrestarted": if (ui.restarting?.kind === "vm") stopRestartOverlay(); break; + case "enginerestarted": if (ui.restarting?.kind === "engine") stopRestartOverlay(); if (!e.error) engineToast(e); break; case "view": if (empty[e.view] || e.view === "settings") show(e.view); break; case "prefs": { const was = prefs.lang; Object.assign(prefs, e.prefs || {}); prefsIn = true; if (prefs.lang !== was) relang(); applyPrefs(); render(); paintEngine(); renderStatus(); break; } case "starprompt": starCard(tr("Kiri started your container.")); break; @@ -8752,10 +8819,10 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (ui.upd.phase !== "downloading") Object.assign(ui.upd, { phase: "downloading", t0: Date.now(), g0: e.got }); Object.assign(ui.upd, { got: e.got, total: e.total }); renderUpdate(); break; case "updatestate": ui.updState = { ...e, checking: false }; if (ui.view === "settings" && prefs.tab === "about") render(); break; - case "updateready": if (ui.upd?.phase === "ready" && ui.upd.version === e.version && ui.upd.hidden) break; ui.upd = { ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break; + case "updateready": if (ui.upd?.phase === "ready" && ui.upd.version === e.version && ui.upd.hidden) break; ui.upd = { notes: "", notesUrl: "", ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break; case "updatecancelled": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: true }); renderUpdate(); break; - case "updateerror": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: false, error: e.error }); else toast("error", e.error); renderUpdate(); break; - case "enginestale": ui.engineStale = e.version; ui.staleHidden = false; renderUpdate(); break; + case "updateerror": if (ui.restarting?.kind === "update") stopRestartOverlay(); if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: false, error: e.error }); else toast("error", e.error); renderUpdate(); break; + case "enginestale": if (e.version && ui.restarting?.kind === "engine") stopRestartOverlay(); ui.engineStale = e.version; ui.staleHidden = false; renderUpdate(); break; case "tools": toolsBar(e); break; case "share": case "shares": case "shareaccount": case "sharelogin": case "shareusage": case "sharetunnels": case "sharetraffic": shEvent(e); break; case "builds": { @@ -8822,13 +8889,20 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "storage": { const wasUnavail = ui.storage?.state === "unavailable"; ui.storage = e; - if (e.state === "moving") ui.stErr = ""; + if (e.state === "moving") { + ui.stErr = ""; + const m = e.moving, pct = m && m.total > 0 ? Math.min(100, Math.round((m.done / m.total) * 100)) : null; + startRestartOverlay("storage", m?.to ? tr("Moving Kiri's data to {path}.", { path: `${esc(m.to)}` }) : tr("Kiri will switch to this folder and restart the engine."), stPhaseText(m?.phase), pct); + } else if (ui.restarting?.kind === "storage") { + stopRestartOverlay(); + } if (e.reclaimable > 0) ui.stReclaimed = null; if (ui.view === "settings" || e.state === "unavailable" || wasUnavail) render(); break; } case "storagereclaimed": ui.stReclaiming = false; + if (ui.restarting?.kind === "reclaim") stopRestartOverlay(); if (e.error) { toast("error", tr("Couldn't reclaim disk space: {error}", { error: e.error })); } else { @@ -8851,6 +8925,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (ui.view === "settings") render(); break; case "storagecheck": + if (ui.restarting?.kind === "storage") stopRestartOverlay(); if (e.error) { ui.stErr = e.error; if (ui.view === "settings") render(); else toast("error", e.error); } else { ui.stErr = ""; storageConfirm(e); } break; @@ -8957,7 +9032,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if (t("[data-stpick]")) { ui.stErr = ""; send("storagepick"); } else if (t("[data-streclaim]")) { if (WIN) { - confirmRemove(tr("Compact WSL disk?"), tr("Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.", { vhdx: 'ext4.vhdx' }), tr("Compact disk"), () => { ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); }, "primary"); + confirmRemove(tr("Compact WSL disk?"), tr("Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.", { vhdx: 'ext4.vhdx' }), tr("Compact disk"), () => { ui.stReclaiming = true; ui.stReclaimed = null; startRestartOverlay("reclaim", tr("Compacting {vhdx} and restarting the engine…", { vhdx: 'ext4.vhdx' }), tr("Restarting engine…")); send("storagereclaim"); render(); }, "primary"); } else { ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); } @@ -8967,7 +9042,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r } else if (t("[data-streset]")) { if (ui.storage?.state === "unavailable") { - confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => send("storagereset"), "primary"); + confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => { startRestartOverlay("storage", tr("Kiri will switch to this folder and restart the engine."), tr("Restarting engine…")); send("storagereset"); }, "primary"); } else { ui.stErr = ""; send("storagecheck", { path: "", value: { reset: true } }); @@ -9044,7 +9119,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r if (cur && !!cur.on !== on) { cur.on = on; send("setresources", { value: { wsl_distro: name, on } }); render(); } } else if ((el = t("[data-vmpower]"))) { el.disabled = true; powerEngine(el.dataset.vmpower); } - else if ((el = t("[data-restartvm]"))) { el.disabled = true; el.textContent = tr("Restarting…"); send("restartvm"); } + else if ((el = t("[data-restartvm]"))) { el.disabled = true; el.textContent = tr("Restarting…"); restartVm(); } else if ((el = t("[data-detail]"))) openDetail(el.dataset.detail); else if (t("[data-ctrcompose]")) show("compose"); else if ((el = t("[data-img]"))) openImage(el.dataset.img); @@ -9250,9 +9325,11 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "k8sop": if (e.state === "progress") { k8s.opLine = e.line.endsWith("…") || e.line.endsWith(".") || e.line.endsWith(")") ? e.line : `${e.line}…`; + if (ui.restarting?.kind === "k8s") setRestartStep(k8s.opLine); if (k8sShown()) { const el = $("k8s-step"); if (el) el.textContent = k8s.opLine; else render(); } break; } + if (ui.restarting?.kind === "k8s") stopRestartOverlay(); k8s.op = ""; k8s.opLine = ""; k8s.opAt = 0; k8s.sanDraft = null; k8s.portDraft = null; k8s.argsDraft = null; if (e.port) k8s.port = e.port; if (e.want_port) k8s.wantPort = e.want_port; @@ -9279,6 +9356,9 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r function k8sDo(op, value) { if (k8s.op) return; Object.assign(k8s, { op, opAt: Date.now(), opLine: op === "start" ? tr("Starting Kubernetes…") : tr(OP_WORDS[op]) }); + if (op === "set" && (k8sNode()?.State === "running" || k8s.state === "running")) { + startRestartOverlay("k8s", esc(tr("Kiri's Kubernetes cluster")), tr("Restarting…")); + } send("k8s", { action: op, value }); k8sSide(); render(); diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index bd38f783a..55ba2047c 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -999,20 +999,18 @@ fn builder_settings(save: Option) { #[cfg(target_os = "macos")] fn vm_net(save: Option) { - if let Some(body) = save { - if let Some(enabled) = body["shared_nat"].as_bool() { - match crate::vm_cli::set_shared_nat(enabled) { - Ok(()) => emit(notice("ok", &tr("Outbound VM traffic setting saved. Restart the VM to apply."))), - Err(e) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), - } - } - } + let saved = save.and_then(|body| body["shared_nat"].as_bool().map(crate::vm_cli::set_shared_nat)); let configured = crate::daemon::engine::vm_shared_nat_config(); let env_override = crate::daemon::engine::shared_nat_env(); let effective = env_override.or(configured).unwrap_or(true); let info = client::get_background("/info").ok(); let awake = info.as_ref().is_some_and(|i| i["KiriVmAwake"] == true); let running_shared_nat = awake.then(|| info.as_ref().and_then(|i| i["KiriVmUplink"]["mode"].as_str()).is_none_or(|m| m != "host-egress")); + match saved { + Some(Ok(())) => emit(serde_json::json!({"type": "notice", "kind": "ok", "text": tr("Outbound VM traffic setting saved. Restart the VM to apply."), "act": if awake { "restartvm" } else { "" }}).to_string()), + Some(Err(e)) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), + None => {} + } emit( serde_json::json!({ "type": "vmnet", @@ -1178,6 +1176,7 @@ fn restart_engine_now() { } Err(e) => { diag::error!("the engine did not restart", error = e); + emit(serde_json::json!({"type": "enginerestarted", "error": e.to_string()}).to_string()); emit(notice("error", &trf("Could not restart the engine: {error}", &[("error", &e)]))); if let Some(v) = client::request("GET", "/version", None).ok().filter(|r| r.ok()).and_then(|r| client::kiri_version(&r.json()).map(str::to_owned)) && update::newer(env!("CARGO_PKG_VERSION"), &v) @@ -2706,14 +2705,22 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { Ok(()) } "restartvm" => { - std::thread::spawn(|| { + let tx = tx.clone(); + std::thread::spawn(move || { let _op = diag::enter_op(diag::new_op("restartvm")); - let result = expect_ok(client::request("POST", "/kiri/sleep", None)).and_then(|()| expect_ok(client::request("POST", "/kiri/wake", None))); + emit(state("stopping", None)); + let result = expect_ok(client::request("POST", "/kiri/sleep", None)).and_then(|()| { + emit(state("booting", None)); + expect_ok(client::request("POST", "/kiri/wake", None)) + }); + emit(serde_json::json!({"type": "vmrestarted", "ok": result.is_ok()}).to_string()); match result { Ok(()) => emit(notice("ok", &tr("The Linux VM restarted with the new resources"))), Err(e) => emit(notice("error", &trf("Could not restart the VM: {error}", &[("error", &e)]))), } resources(None); + vm_net(None); + let _ = tx.send(Cmd::Refresh); }); Ok(()) } diff --git a/tests/ui/restartnow.js b/tests/ui/restartnow.js index f22688eff..d4cbd889b 100644 --- a/tests/ui/restartnow.js +++ b/tests/ui/restartnow.js @@ -1,16 +1,136 @@ -// Resources saved while the VM runs: the toast's Restart now restarts it. +// Every restart trigger opens the universal Restarting… overlay (#rscrim) with +// the shared .rspin spinner, syncs the VM card and status bar, and clears when +// the restart completes or fails. const R = []; const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; -kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "restartvm" }); -t("the toast has Restart now", () => { +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; + +kiri.on({ type: "status", version: "0.2.3", dev: false, share: true, app: "Kiri", ours: "kiri", context: "kiri" }); +kiri.on({ type: "state", state: "running" }); + +t("toast Restart now opens universal Restarting overlay with .rspin and syncs VM card + status bar", () => { + kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "restartvm" }); const b = document.querySelector("#toasts [data-trestart]"); if (!b) throw new Error("no link"); b.click(); if (!sent.some((m) => m.type === "restartvm")) throw new Error("sent " + sent.map((m) => m.type).join(",")); if (document.querySelector("#toasts [data-trestart]")) throw new Error("toast stayed"); + const scrim = document.getElementById("rscrim"); + if (!scrim || scrim.hidden) throw new Error("Restarting overlay did not open"); + if (!scrim.querySelector(".rspin")) throw new Error("missing .rspin spinner"); + eq(scrim.querySelector("h3")?.textContent.trim(), "Restarting…", "overlay heading"); + eq(document.body.dataset.vm, "restarting", "body data-vm"); + eq(document.getElementById("vm-state")?.textContent.trim(), "Restarting…", "sidebar VM state"); + if (!document.querySelector("#statusbar .dot.restarting")) throw new Error("status bar missing restarting dot"); + + // Live step updates as VM stops and starts + kiri.on({ type: "state", state: "booting" }); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Starting…", "step updated on booting"); + + // Completion clears overlay and restores running state + kiri.on({ type: "state", state: "running" }); + kiri.on({ type: "vmrestarted", ok: true }); + if (!scrim.hidden) throw new Error("overlay stayed after vmrestarted"); + eq(document.body.dataset.vm, "running", "restored to running"); }); -kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "" }); -t("no link while the VM is asleep", () => { + +t("no Restart now link while the VM is asleep", () => { + kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "" }); if (document.querySelector("#toasts [data-trestart]")) throw new Error("link shown"); }); + +t("Resources Restart VM to apply and Network Restart VM to apply open Restarting overlay", () => { + kiri.on({ + type: "resources", cpus: 4, memory_mib: 11264, disk_gb: 160, + running_cpus: 2, running_memory_mib: 12288, running_disk_gb: 160, + awake: true, max_cpus: 12, max_memory_mib: 32768, min_disk_gb: 64, max_disk_gb: 1024, overridden: false, + }); + prefs.tab = "resources"; + show("settings"); + const resBtn = document.getElementById("res-restart"); + if (!resBtn) throw new Error("missing #res-restart"); + sent.length = 0; + resBtn.click(); + if (!sent.some((m) => m.type === "restartvm")) throw new Error("did not send restartvm"); + if (document.getElementById("rscrim").hidden) throw new Error("overlay not shown for #res-restart"); + kiri.on({ type: "vmrestarted", ok: true }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay did not close"); + + prefs.tab = "network"; + show("settings"); + kiri.on({ type: "proxy", settings: { mode: "system", containers: false }, effective: { http: null, https: null, no_proxy: [], pac: false } }); + kiri.on({ type: "vmnet", supported: true, shared_nat: false, env: false, awake: true, running_shared_nat: true }); + const netRestart = document.querySelector(".settings .pane [data-restartvm]"); + if (!netRestart) throw new Error("missing Restart VM to apply in Network when pending"); + netRestart.click(); + if (document.getElementById("rscrim").hidden) throw new Error("overlay not shown from Network restart"); + kiri.on({ type: "vmrestarted", ok: false }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay did not close on failed vmrestarted"); +}); + +t("Update Restart now and Stale engine Restart engine open Restarting overlay", () => { + kiri.on({ type: "updateready", version: "0.2.4" }); + const updBtn = document.querySelector('#updcard [data-upd="restart"]'); + if (!updBtn) throw new Error("missing update restart button"); + updBtn.click(); + if (document.getElementById("rscrim").hidden || !document.querySelector("#rscrim .rspin")) throw new Error("overlay missing on updaterestart"); + kiri.on({ type: "updateerror", error: "staged bundle missing" }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay stayed after updateerror"); + + ui.upd = null; + kiri.on({ type: "enginestale", version: "0.2.2" }); + const engBtn = document.querySelector('#updcard [data-upd="engine"]'); + if (!engBtn) throw new Error("missing stale engine restart button"); + engBtn.click(); + if (document.getElementById("rscrim").hidden || !document.querySelector("#rscrim .rspin")) throw new Error("overlay missing on restartengine"); + kiri.on({ type: "enginerestarted", version: "0.2.3", ms: 420 }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay stayed after enginerestarted"); +}); + +t("Storage move shows Restarting overlay with progress bar and .rspin in pane", () => { + prefs.tab = "storage"; + show("settings"); + kiri.on({ + type: "storage", + path: "/Users/me/Library/Application Support/Kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: false, env: false, state: "moving", + used: null, free: 120_000_000_000, fs: "apfs", + moving: { to: "/Volumes/SSD/kiri", phase: "restarting", done: 3_000_000_000, total: 4_000_000_000 }, + error: null, old: null, + }); + const scrim = document.getElementById("rscrim"); + if (scrim.hidden || !scrim.querySelector(".rspin")) throw new Error("storage moving did not show Restarting overlay"); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Restarting engine…", "storage phase step"); + eq(scrim.querySelector(".rbar span")?.style.width, "75%", "storage progress bar"); + if (!document.querySelector(".settings .st-box .rspin")) throw new Error("storage pane box missing .rspin"); + + kiri.on({ + type: "storage", + path: "/Volumes/SSD/kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: true, env: false, state: "ok", + used: 4_000_000_000, free: 300_000_000_000, fs: "apfs", + moving: null, error: null, old: null, + }); + if (!scrim.hidden) throw new Error("storage overlay stayed after state=ok"); +}); + +t("Kubernetes set while running opens Restarting overlay and streams progress", () => { + ui.containers = [{ Id: "k8s1", Names: ["/kiri-k8s"], Image: "rancher/k3s:v1.37.1-k3s1", State: "running", Ports: [], Labels: { "dev.kiri.k8s": "1" } }]; + kiri.on({ + type: "k8s", state: "running", ready: true, context: "kiri", port: 6443, want_port: 6443, + config: { lan: false, tls_san: [] }, pods: [], services: [], + }); + prefs.tab = "kubernetes"; + show("settings"); + document.querySelector('[data-k8slan="1"]').click(); + const scrim = document.getElementById("rscrim"); + if (scrim.hidden || !scrim.querySelector(".rspin")) throw new Error("k8s restart did not open Restarting overlay"); + kiri.on({ type: "k8sop", op: "set", state: "progress", line: "Waiting for the API server" }); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Waiting for the API server…", "k8s progress line"); + kiri.on({ type: "k8sop", op: "set", state: "done", context: "kiri", port: 6443, want_port: 6443 }); + if (!scrim.hidden) throw new Error("k8s overlay stayed after k8sop done"); +}); + report(R); From 99c76f0ea7474231528b74e54cf6dfe61d7ff906 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 08:37:21 +0100 Subject: [PATCH 145/157] UI & Storage: pin Settings sidebar while body scrolls, eliminate UI main-thread/worker stalls, and persist Windows VHDX overhead --- crates/kiri-win/src/engine.rs | 90 +++++---- crates/kiri-win/src/ports.rs | 20 +- crates/kiri-win/src/storage.rs | 77 +++++++- crates/kiri/src/ui/index.html | 167 +++++++++++------ crates/kiri/src/ui/mod.rs | 271 +++++++++++++++------------ tests/ui/searchselect.js | 2 +- tests/ui/settings-scroll-and-perf.js | 138 ++++++++++++++ 7 files changed, 554 insertions(+), 211 deletions(-) create mode 100644 tests/ui/settings-scroll-and-perf.js diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 7d700aadf..11b171510 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -261,38 +261,57 @@ fn engine(rx: &Receiver, tx: Sender) { } Ok(Cmd::Pull(name)) => pull(name), Ok(Cmd::Run(name, env)) => { - // The page shows its spinner until this says how it went. - let result = run_image(&name, &env); - emit(json!({"type": "ran", "name": name, "error": result.is_err()}).to_string()); - act(result) + std::thread::spawn(move || { + // The page shows its spinner until this says how it went. + let result = run_image(&name, &env); + emit(json!({"type": "ran", "name": name, "error": result.is_err()}).to_string()); + act(result); + }); + } + Ok(Cmd::RemoveImage(name)) => { + std::thread::spawn(move || { + match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { + Ok(r) if r.ok() => { + // Only untagged when another name still points at it: nothing freed. + let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); + emit(json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); + } + Ok(r) => emit(notice("error", &r.error())), + Err(e) => emit(notice("error", &e.to_string())), + } + send(Cmd::Refresh); + }); } - Ok(Cmd::RemoveImage(name)) => match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { - Ok(r) if r.ok() => { - // Only untagged when another name still points at it: nothing freed. - let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); - emit(json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); - } - Ok(r) => emit(notice("error", &r.error())), - Err(e) => emit(notice("error", &e.to_string())), - }, Ok(Cmd::Container { action, id }) => { let (method, path) = match action.as_str() { "remove" => ("DELETE", format!("/containers/{id}?force=1&v=1")), a @ ("start" | "stop" | "restart" | "pause" | "unpause") => ("POST", format!("/containers/{id}/{a}")), _ => continue, }; - let result = expect_done(client::request(method, &path, None)); - // Refused to start (a port taken): the container's page says why. - if let (Err(e), "start") = (&result, action.as_str()) { - emit(json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); - } - act(result); + std::thread::spawn(move || { + let result = expect_done(client::request(method, &path, None)); + // Refused to start (a port taken): the container's page says why. + if let (Err(e), "start") = (&result, action.as_str()) { + emit(json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); + } + act(result); + }); + } + Ok(Cmd::RemoveVolume(name)) => { + std::thread::spawn(move || act(expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None)))); + } + Ok(Cmd::RemoveNetwork(id)) => { + std::thread::spawn(move || act(expect_ok(client::request("DELETE", &format!("/networks/{id}"), None)))); + } + Ok(Cmd::Ports { id, ports }) => { + std::thread::spawn(move || act(set_ports(&id, ports))); + } + Ok(Cmd::Env { id, env }) => { + std::thread::spawn(move || act(set_env(&id, env))); + } + Ok(Cmd::About) => { + std::thread::spawn(about); } - Ok(Cmd::RemoveVolume(name)) => act(expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None))), - Ok(Cmd::RemoveNetwork(id)) => act(expect_ok(client::request("DELETE", &format!("/networks/{id}"), None))), - Ok(Cmd::Ports { id, ports }) => act(set_ports(&id, ports)), - Ok(Cmd::Env { id, env }) => act(set_env(&id, env)), - Ok(Cmd::About) => about(), Err(RecvTimeoutError::Disconnected) => return, Err(RecvTimeoutError::Timeout) => { emit_docker_state_if_changed(); @@ -1516,16 +1535,18 @@ pub fn on_message(msg: &str) { let theme = c.value.as_str().unwrap_or("").to_owned(); Handle.run(move |ui| ui.set_theme(&theme)); } - if c.name == "startAtLogin" - && let Some(on) = c.value.as_bool() - && let Err(e) = crate::setup::set_start_at_login(on) - { - crate::serve::log(&format!("start at sign-in: {e}")); - emit(notice("error", &e.to_string())); - emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); - return; - } + let start_login = (c.name == "startAtLogin").then(|| c.value.as_bool()).flatten(); set_pref(&c.name, c.value); + if let Some(on) = start_login { + std::thread::spawn(move || { + if let Err(e) = crate::setup::set_start_at_login(on) { + crate::serve::log(&format!("start at sign-in: {e}")); + set_pref("startAtLogin", (!on).into()); + emit(notice("error", &e.to_string())); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); + } + }); + } } // A language the page doesn't carry yet (the main window and setup open // with one; setup's langwords comes here too, not being a setup- command): @@ -1677,7 +1698,8 @@ pub fn on_message(msg: &str) { "storagepick" => { crate::app::pick_folder(&tr("Choose a storage folder"), |path| { if let Some(p) = path { - crate::storage::check_and_emit(Some(p.to_string_lossy().into_owned()), false, false); + let s = p.to_string_lossy().into_owned(); + std::thread::spawn(move || crate::storage::check_and_emit(Some(s), false, false)); } }); } diff --git a/crates/kiri-win/src/ports.rs b/crates/kiri-win/src/ports.rs index f8182567f..ec00eed54 100644 --- a/crates/kiri-win/src/ports.rs +++ b/crates/kiri-win/src/ports.rs @@ -1027,7 +1027,12 @@ mod tests { backend.send_to(&buf[..n], peer).unwrap(); }); - let fwd = UdpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + // Pick a port outside the OS ephemeral range (49152..65535) so a concurrent + // `:0` bind in another parallel test thread never steals `fwd_addr` right + // after `fwd.stop()` releases it. + let fwd = (38100..38900) + .find_map(|port| UdpForwarder::start(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)), backend_addr).ok()) + .expect("free loopback UDP port in 38100..38900"); let fwd_addr = fwd.local_addr(); let client = UdpSocket::bind("127.0.0.1:0").unwrap(); client.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); @@ -1043,8 +1048,17 @@ mod tests { } else { drop(fwd); } - let rebound = UdpSocket::bind(fwd_addr); - assert!(rebound.is_ok(), "port should be released immediately after UdpForwarder shutdown"); + // Allow brief retries in case a concurrent test's `Command::spawn` on Unix + // is mid-fork/exec when the socket fd closes. + let mut rebound = UdpSocket::bind(fwd_addr); + for _ in 0..50 { + if rebound.is_ok() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + rebound = UdpSocket::bind(fwd_addr); + } + assert!(rebound.is_ok(), "port should be released after UdpForwarder shutdown: {:?}", rebound.err()); } let upper = vec![ diff --git a/crates/kiri-win/src/storage.rs b/crates/kiri-win/src/storage.rs index 03ea799d0..4950693b5 100644 --- a/crates/kiri-win/src/storage.rs +++ b/crates/kiri-win/src/storage.rs @@ -180,10 +180,49 @@ pub fn headroom(bytes: u64) -> u64 { bytes / 10 + 1_000_000_000 } +/// Persisted non-compactable VHDX + ext4 metadata floor (`/vhdx-overhead`), +/// measured right after `fstrim` + VHDX compaction so WSL2's VHDX header/BAT and +/// allocated ext4 metadata aren't repeatedly advertised as reclaimable space. +pub const VHDX_OVERHEAD_FILE: &str = "vhdx-overhead"; + /// Reclaimable bytes below 64 MiB are reported as 0 to avoid prompting /// pointless VHDX compaction over filesystem slack. pub const RECLAIM_THRESHOLD: u64 = 64 << 20; +/// Effective bytes occupied inside `ext4.vhdx`, adding the measured post-compact +/// metadata floor (`recorded_overhead`, clamped downward if blocks were reused) +/// without guessing from WSL's 1 TB virtual capacity on an uncompacted dynamic VHDX. +pub fn effective_vhdx_in_use( + disk_host: Option, + raw_in_use: Option, + recorded_overhead: Option, +) -> (Option, Option) { + let Some(raw) = raw_in_use else { + return (None, None); + }; + let Some(saved) = recorded_overhead else { + return (Some(raw), None); + }; + let overhead = match disk_host { + Some(host) => saved.min(host.saturating_sub(raw)), + None => saved, + }; + let clamped = (overhead < saved).then_some(overhead); + (Some(raw.saturating_add(overhead)), clamped) +} + +pub fn read_vhdx_overhead(root: &Path) -> Option { + fs::read_to_string(root.join(VHDX_OVERHEAD_FILE)).ok()?.trim().parse::().ok() +} + +pub fn write_vhdx_overhead(root: &Path, bytes: u64) { + let path = root.join(VHDX_OVERHEAD_FILE); + let tmp = root.join("vhdx-overhead.tmp"); + if fs::write(&tmp, format!("{bytes}\n")).is_ok() { + let _ = fs::rename(&tmp, &path); + } +} + /// Reclaimable bytes from host `ext4.vhdx` allocated size vs in-use bytes /// inside WSL, applying [`RECLAIM_THRESHOLD`]. pub fn reclaimable_bytes(disk_host: Option, disk_in_use: Option) -> Option { @@ -428,7 +467,12 @@ mod imp { let near = root.ancestors().find(|p| p.is_dir()); let (disk_host, disk_in_use, disk_limit, reclaimable) = if !is_missing && !active { let host = vhdx_allocated(&root.join("ext4.vhdx")); - let (in_use, limit) = wsl_disk_usage(); + let (raw_in_use, limit) = wsl_disk_usage(); + let recorded = read_vhdx_overhead(&root); + let (in_use, clamped) = effective_vhdx_in_use(host, raw_in_use, recorded); + if let Some(updated) = clamped { + write_vhdx_overhead(&root, updated); + } let rec = reclaimable_bytes(host, in_use); (host, in_use, limit, rec) } else { @@ -851,7 +895,14 @@ mod imp { let after = vhdx_allocated(&vhdx).unwrap_or(mid); let reclaimed = before.saturating_sub(after); let elapsed_ms = t0.elapsed().as_millis() as u64; - let (in_use, _) = wsl_disk_usage(); + let (raw_in_use, _) = wsl_disk_usage(); + if compact_err.is_none() + && let (Some(raw), Some(root)) = (raw_in_use, vhdx.parent()) + { + write_vhdx_overhead(root, after.saturating_sub(raw)); + } + let recorded = vhdx.parent().and_then(read_vhdx_overhead); + let (in_use, _) = effective_vhdx_in_use(Some(after), raw_in_use, recorded); if let Some(err) = compact_err && reclaimed == 0 { emit(json!({"type": "storagereclaimed", "error": err}).to_string()); } else { @@ -960,4 +1011,26 @@ mod tests { assert!(r.is_err()); let _ = (Checked { needed: 0, free: 0, replaces: false }, IGNORED, MOVING, format_gb(1_000_000_000)); } + + #[test] + fn vhdx_overhead_floor_prevents_phantom_reclaimable_and_clamps_downward() { + let d = scratch("vhdx-overhead"); + assert_eq!(read_vhdx_overhead(&d), None); + // Before first compaction: dynamic VHDX never guesses overhead from 1 TB virtual limit. + let (eff0, clamp0) = effective_vhdx_in_use(Some(20_000_000_000), Some(15_000_000_000), None); + assert_eq!((eff0, clamp0), (Some(15_000_000_000), None)); + assert_eq!(reclaimable_bytes(Some(20_000_000_000), eff0), Some(5_000_000_000)); + + // After compaction leaves 2.4 GB of non-compactable VHDX + ext4 metadata: + write_vhdx_overhead(&d, 2_400_000_000); + assert_eq!(read_vhdx_overhead(&d), Some(2_400_000_000)); + let (eff1, clamp1) = effective_vhdx_in_use(Some(17_400_000_000), Some(15_000_000_000), read_vhdx_overhead(&d)); + assert_eq!((eff1, clamp1), (Some(17_400_000_000), None)); + assert_eq!(reclaimable_bytes(Some(17_400_000_000), eff1), Some(0)); + + // If new container files reuse preallocated blocks so host - raw < saved floor, clamp downward. + let (eff2, clamp2) = effective_vhdx_in_use(Some(17_400_000_000), Some(16_000_000_000), read_vhdx_overhead(&d)); + assert_eq!((eff2, clamp2), (Some(17_400_000_000), Some(1_400_000_000))); + let _ = fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index c0c677fbd..6a0dab62c 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -1065,9 +1065,12 @@ font: 500 var(--fs) var(--ui-font); text-align: var(--start); cursor: pointer; } .menu button:hover, .menu button:focus-visible { background: var(--raised); outline: none; } .menu button.danger { color: var(--red); } -/* Settings */ -.settings { display: grid; grid-template-columns: 180px 1fr; gap: 28px; align-items: start; max-width: 860px; } -.settings .tabs { display: grid; gap: 2px; } +/* Settings: the left tab rail stays static while the pane body scrolls. */ +.content:has(> .settings) { display: flex; flex-direction: column; overflow: hidden; padding-block: 0; padding-inline-end: 0; } +.settings { flex: 1; min-height: 0; display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; align-items: stretch; } +.settings .tabs { display: grid; gap: 2px; align-content: start; padding-block: 4px 20px; overflow-y: auto; } +.settings-body { min-width: 0; height: 100%; overflow-y: auto; overflow-x: hidden; padding-block: 4px calc(20px + var(--hold, 0px)); padding-inline-end: 24px; } +.settings-body > :is(.pane, .panes) { max-width: 652px; } .settings .tabs button { display: flex; align-items: center; gap: 9px; height: 31px; padding: 0 10px; border: 0; border-radius: 7px; background: transparent; color: var(--muted); font: 500 var(--fs) var(--ui-font); text-align: var(--start); cursor: pointer; } .settings .tabs button:hover { background: var(--row-hover); color: var(--text); } @@ -3023,7 +3026,7 @@

Containers

`; } const fontLists = { families: [], mono: [] }; -const optsMemo = {}, settingsShown = { html: "", el: null }; +const optsMemo = {}, settingsShown = { html: "", el: null, tab: "" }; let about = null; const SIZES = [0.9, 1, 1.1, 1.25]; /* Logs are small unless you choose otherwise: they're long and wide. */ @@ -3346,12 +3349,20 @@

Containers

Containers

Containers

Containers

Containers

Containers

LOG_MAX) el.firstElementChild.remove(); + while (el.childElementCount > LOG_MAX) { + if (!el.firstElementChild.classList.contains("hide")) el._shown--; + el.firstElementChild.remove(); + } if (d.follow && atEnd || d.follow && parts.length > 50) el.scrollTop = el.scrollHeight; updateLogCount(el, countId, d); } function applyLogFilter(el, countId, d) { const f = d.logFilter.toLowerCase(); - for (const div of el.children) div.classList.toggle("hide", !shown(div, f, d.logLevel)); + let visCount = 0; + for (const div of el.children) { + const vis = shown(div, f, d.logLevel); + div.classList.toggle("hide", !vis); + if (vis) visCount++; + } + el._shown = visCount; updateLogCount(el, countId, d); } function appendLogEnd(el, text) { const div = document.createElement("div"); div.className = "quiet"; div.textContent = text; + el._shown = (el._shown ?? el.childElementCount) + 1; el.append(div); } function clearLogConsole(el, countId, d, partial, resetN) { el.textContent = ""; + el._shown = 0; partial.false = ""; partial.true = ""; resetN(); @@ -5031,27 +5056,28 @@

${tr("Storage location unavailable")}

function renderSettings() { const tab = (id, icon, label) => ``; - const opts = (list, current, system) => { - const memo = optsMemo[system]; - if (memo?.list !== list || memo.current !== current) optsMemo[system] = { list, current, html: [system, ...list].map((f) => - ``).join("") }; - return optsMemo[system].html; - }; - /* A tiny window in each theme's colours, for the Theme choice. */ - const mini = (dark) => { - const c = dark ? { bg: "#0F1419", side: "#121920", line: "#2A313A", bar: "#66707C", text: "#98A1AC" } : { bg: "#FFFFFF", side: "#EDF0F5", line: "#DDE3EB", bar: "#8A929C", text: "#5E6773" }; - const accent = (ACCENTS.find(([id]) => id === prefs.accent) || ACCENTS[0])[2]; - const rows = [0, 1, 2, 3].map((i) => ``).join(""); - return ``; - }; - const inUse = darkNow(); - const sysName = LANGS.find(([id]) => id === resolveLang("system"))?.[1] || "English"; - const startAtLogin = prefs.startAtLogin ?? !LINUX; - const stopOnQuit = prefs.stopOnQuit === true; - const appearance = `

${tr("Appearance")}

+ const appearancePane = () => { + const opts = (list, current, system) => { + const memo = optsMemo[system]; + if (memo?.list !== list || memo.current !== current) optsMemo[system] = { list, current, html: [system, ...list].map((f) => + ``).join("") }; + return optsMemo[system].html; + }; + /* A tiny window in each theme's colours, for the Theme choice. */ + const mini = (dark) => { + const c = dark ? { bg: "#0F1419", side: "#121920", line: "#2A313A", bar: "#66707C", text: "#98A1AC" } : { bg: "#FFFFFF", side: "#EDF0F5", line: "#DDE3EB", bar: "#8A929C", text: "#5E6773" }; + const accent = (ACCENTS.find(([id]) => id === prefs.accent) || ACCENTS[0])[2]; + const rows = [0, 1, 2, 3].map((i) => ``).join(""); + return ``; + }; + const inUse = darkNow(); + const sysName = LANGS.find(([id]) => id === resolveLang("system"))?.[1] || "English"; + const startAtLogin = prefs.startAtLogin ?? !LINUX; + const stopOnQuit = prefs.stopOnQuit === true; + return `

${tr("Appearance")}

${tr("Language")}${tr("Follow {os} (now {lang}), or always use one language.", { os: OS, lang: sysName })} ${langButton(sysName)}
@@ -5080,9 +5106,11 @@

${tr("Storage location unavailable")}

${ui.shellPath && ui.shellPath.supported !== false ? `
${tr("Command-line tools in shell")}${tr("Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.", { bin: '~/.kiri/bin', zshrc: '.zshrc', zprofile: '.zprofile', docker: 'docker', kubectl: 'kubectl', kiri: 'kiri' })}
` : ""}
`; - const portsPref = routerPortsPref(); - // On Linux: kiri.localhost only, for now; nothing to switch. - const domainsPane = LINUX ? `

${tr("Domains")}

+ }; + const domainsPane = () => { + const portsPref = routerPortsPref(); + // On Linux: kiri.localhost only, for now; nothing to switch. + return LINUX ? `

${tr("Domains")}

${tr("Local names")}${tr("Running containers answer at <name>.kiri.localhost, which needs no setup.")}
${portsPref}

${tr("Compose services answer at {addr}.", { addr: `<service>.<project>.kiri.localhost` })} ${tr("{local} names and HTTPS aren't on Linux yet.", { local: `.kiri.local` })}

@@ -5107,10 +5135,12 @@

${tr("Storage location unavailable")}

${portsPref}

${tr("Compose services answer at {addr}.", { addr: `<service>.<project>.${ui.suffix}` })} ${tr("Changing this needs admin rights (an administrator password), since it adds or removes {path}.", { path: `/etc/resolver/kiri.local` })}

`; - const a = about; - const mib = (b) => (b ? `${(b / 1073741824).toFixed(1)} GB` : "—"); - const canUninstall = a?.can_uninstall ?? (!WIN && !LINUX); - const aboutPane = `
+ }; + const aboutPane = () => { + const a = about; + const mib = (b) => (b ? `${(b / 1073741824).toFixed(1)} GB` : "—"); + const canUninstall = a?.can_uninstall ?? (!WIN && !LINUX); + return `

${tr("Storage location unavailable")}

${canUninstall ? `
${tr("Uninstall Kiri")} ${tr("Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).", { cmd: 'kiri setup --uninstall' })}
` : ""}
`; + }; + const body = prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane() : prefs.tab === "domains" ? domainsPane() : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "storage" ? storagePane() : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearancePane(); const html = `
${tab("appearance", "textaa", tr("Appearance"))}${tab("resources", "stack", tr("Resources"))}${tab("storage", "harddrive", tr("Storage"))}${tab("network", "globe", tr("Network"))}${tab("builds", "hammer", tr("Builds"))}${tab("registries", "lock", tr("Registries"))}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", tr("Import"))}${tab("domains", "network", tr("Domains"))}${tab("diagnostics", "bug", tr("Diagnostics"))}${tab("about", "info", tr("About"))}
- ${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `
${enginePane()}${resourcesPane()}${wslPane()}
` : prefs.tab === "storage" ? storagePane() : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" ? `
${loginsOn() ? registriesPane() : ""}${regListPane("insecure")}${regListPane("mirrors")}
` : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}
`; +
${body}
`; // The container lists arrive every few seconds; rebuilding an unchanged page // closes an open menu. The font menus list names in the interface font: an // option in its own font made WebKit load every installed font (438 here) // the first time Appearance showed, freezing the window for about 3 s. The // preview below them shows the chosen fonts. if (html === settingsShown.html && settingsShown.el?.isConnected) return; - const kept = signinKeep($("content")); - $("content").innerHTML = html; - signinPut($("content"), kept); - settingsShown.html = html; settingsShown.el = $("content").firstElementChild; + const c = $("content"), sameTab = settingsShown.el?.isConnected && settingsShown.tab === prefs.tab; + const tscroll = c.querySelector(".settings .tabs")?.scrollTop || 0; + const bscroll = sameTab ? (c.querySelector(".settings-body")?.scrollTop || 0) : 0; + const kept = signinKeep(c); + c.innerHTML = html; + signinPut(c, kept); + if (tscroll) c.querySelector(".settings .tabs").scrollTop = tscroll; + if (bscroll) c.querySelector(".settings-body").scrollTop = bscroll; + settingsShown.html = html; settingsShown.el = c.firstElementChild; settingsShown.tab = prefs.tab; diagDrawn(); for (const k of ["http", "https", "no_proxy"]) $(`px-${k}`)?.addEventListener("input", (ev) => { ui.pxDraft[k] = ev.target.value; }); for (const k of ["insecure", "mirrors"]) { @@ -5207,6 +5244,8 @@

${tr("Storage location unavailable")}

// From the top, as a container's or pod's page opens: leaving a page scrolled // down (a long Terminal or Logs tab) otherwise opened the next view below its rows. $("content").scrollTop = 0; + const sb = $("content").querySelector(".settings-body"); + if (sb) sb.scrollTop = 0; } const empty = { @@ -7556,6 +7595,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) addEventListener("resize", navTags); function render() { if (held(render)) return; + schedulePlaceFloats(); if (ui.view !== "compose") cmpHWait(false); if (langPopState.close) queueMicrotask(() => { if (langPopState.close && !$("pref-lang-btn")) langPopState.close(false); }); themeBtn(); @@ -7901,8 +7941,8 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) // Before the button in reading order: on its left, or on its right right to left (.run-tip's transform). el.style.left = `${rtl() ? r.right : r.left}px`; el.style.top = `${r.top + r.height / 2}px`; - requestAnimationFrame(place); }; + el._place = place; place(); el.timer = setTimeout(() => el.remove(), 8000); return true; @@ -7921,6 +7961,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) el.innerHTML = `${why.short ? tr("{name} stopped: {why}", { name: `${esc(name)}`, why: esc(why.short) }) : tr("{name} stopped", { name: `${esc(name)}` })}` + (why.kind === "env" ? `` : ``) + `·`; + el._place?.(); } /* Why a container stopped, from its own words: the last lines of its log @@ -8048,7 +8089,19 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) p.el.remove(); if (ui.view === "images") render(); } -// Below the Run button, or above it when there's no room; it follows the list as it redraws. +// Below the Run button, or above it when there's no room; it follows the list on scroll, resize and redraw. +let floatRaf = 0; +function placeFloats() { + floatRaf = 0; + document.querySelector(".run-tip")?._place?.(); + if (ui.need) needPlace(); +} +function schedulePlaceFloats() { + if (floatRaf || (!ui.need && !document.querySelector(".run-tip"))) return; + floatRaf = requestAnimationFrame(placeFloats); +} +addEventListener("scroll", schedulePlaceFloats, { capture: true, passive: true }); +addEventListener("resize", schedulePlaceFloats, { passive: true }); function needPlace() { const p = ui.need; if (!p || !p.el.isConnected) return; @@ -8063,7 +8116,6 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) const up = h > roomBelow && roomAbove > roomBelow; el.classList.toggle("above", up); el.classList.toggle("below", !up); el.style.top = `${up ? Math.max(8, r.top - 9 - h) : r.bottom + 9}px`; - requestAnimationFrame(needPlace); } // What Run sends, or null while something it needs is missing. function needEnv() { @@ -8093,6 +8145,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) } p.el.classList.toggle("sec-off", !!p.el.querySelector("[data-needoff]")?.checked); p.el.querySelector("[data-needgo]").disabled = !needEnv(); + needPlace(); } document.addEventListener("input", (ev) => { if (ev.target.closest(".need")) needCheck(); }); document.addEventListener("change", (ev) => { if (ev.target.closest(".need")) needCheck(); }); @@ -8122,6 +8175,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) } else if (b?.matches("[data-needdisc]")) { const x = b.getAttribute("aria-expanded") !== "true"; b.setAttribute("aria-expanded", x); b.nextElementSibling.hidden = !x; + needPlace(); } }); const appName = (image) => { const b = (image || "").split("@")[0].split(":")[0].split("/").pop(); return APPS[b] || (b ? b[0].toUpperCase() + b.slice(1) : tr("This image")); }; @@ -8438,9 +8492,9 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) } const dgFields = (l) => Object.entries(l.fields || {}).map(([k, v]) => ` ${k}=${typeof v === "string" ? (/\s/.test(v) || !v ? JSON.stringify(v) : v) : JSON.stringify(v)}`); const dgText = (l) => `${l.msg || ""}${dgFields(l).join("")}`; -function dgRow(l) { +function dgRow(l, key = "") { const lv = ["error", "warn", "info", "debug"].includes(l.level) ? l.level : "info"; - return `
${esc(dgTime(l.time))}${lv.toUpperCase()}${(DG_PART[l.part] && tr(DG_PART[l.part])) || esc(l.part || "")}${dgMark(l.msg || "")}${dgFields(l).map((f) => `${dgMark(f)}`).join("")}
`; + return `
${esc(dgTime(l.time))}${lv.toUpperCase()}${(DG_PART[l.part] && tr(DG_PART[l.part])) || esc(l.part || "")}${dgMark(l.msg || "")}${dgFields(l).map((f) => `${dgMark(f)}`).join("")}
`; } // A line as text, for Copy: local time, level, part, message and fields. const dgPlain = (l) => `${dgTime(l.time)} ${(l.level || "").toUpperCase().padEnd(5)} ${(DG_PART[l.part] || l.part || "").padEnd(6)} ${dgText(l)}`; @@ -8464,10 +8518,16 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) const key = `${rows.length}|${rows.at(-1)?.time}|${rows[0]?.time}|${dg.find}`; $("dg-count").textContent = dg.lines ? trn(rows.length, "{n} line", "{n} lines") : ""; if (key === dg.shown && el.childElementCount) return; + const sel = getSelection(); + if (dg.shown && sel && !sel.isCollapsed && (el.contains(sel.anchorNode) || el.contains(sel.focusNode))) return; dg.shown = key; - const top = el.scrollTop; - el.innerHTML = !dg.lines ? `
${tr("Reading the log…")}
` : rows.length ? rows.map(dgRow).join("") - : `
${dg.find || dg.level || dg.part || dg.op ? tr("No lines match.") : tr("Nothing logged yet.")}
`; + const top = el.scrollTop, seen = new Map(); + const html = !dg.lines ? `
${tr("Reading the log…")}
` : rows.length ? rows.map((l) => { + const base = `${l.time}|${l.level}|${l.part}|${l.msg || ""}`, n = (seen.get(base) || 0) + 1; + seen.set(base, n); + return dgRow(l, `${base}#${n}`); + }).join("") : `
${dg.find || dg.level || dg.part || dg.op ? tr("No lines match.") : tr("Nothing logged yet.")}
`; + morph(el, html); el.scrollTop = dg.follow ? el.scrollHeight : top; } @@ -9264,7 +9324,6 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r closePod(); prefs.tab = "kubernetes"; show("settings"); - document.querySelector("#content .pane")?.scrollIntoView({ block: "start" }); } /* Short enough for the group label's row: a restart is a start there. */ const SIDE_WORDS = { start: "Starting", stop: "Stopping", set: "Starting", deletecluster: "Deleting" }; diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 55ba2047c..31e521d90 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -216,11 +216,19 @@ fn json_str(out: &mut String, v: &str) { out.push('"'); } +fn spawn_op(f: impl FnOnce() + Send + 'static) { + let op = diag::op(); + std::thread::spawn(move || { + let _op = op.map(diag::enter_op); + f(); + }); +} + /// The engine thread: a client of `kiri daemon`. It answers the window's /// commands and sends it the daemon's lists whenever an event says they /// changed, so the page never polls. fn engine(rx: Receiver, tx: Sender) { - watch(tx); + watch(tx.clone()); let mut connected = false; // A command that came while a burst of refreshes was being gathered: it's next. let mut next = None; @@ -282,40 +290,43 @@ fn engine(rx: Receiver, tx: Sender) { refresh(&mut connected); } Ok(Cmd::Pull(name)) => pull(name), - Ok(Cmd::Run(name, env)) => { + Ok(Cmd::Run(name, env)) => spawn_op(move || { // The page shows Starting… until this says how it went. let result = run_image(&name, &env); emit(serde_json::json!({"type": "ran", "name": name, "error": result.is_err()}).to_string()); - act("run", result) - } + act("run", result); + }), Ok(Cmd::RemoveImage(name, with)) => { - // The stopped containers made from it go first, never forced: a - // running one refuses, and then the image stays too. - let mut blocked = None; - for id in &with { - match client::request("DELETE", &format!("/containers/{}", path_escape(id)), None) { - Ok(r) if r.ok() || r.status == 404 => {} - Ok(r) => blocked = Some(trf("Kept {name}: {container} couldn't be removed ({error})", &[("name", &name), ("container", &container_name(id)), ("error", &r.error())])), - Err(e) => blocked = Some(trf("Kept {name}: {error}", &[("name", &name), ("error", &e)])), + let tx = tx.clone(); + spawn_op(move || { + // The stopped containers made from it go first, never forced: a + // running one refuses, and then the image stays too. + let mut blocked = None; + for id in &with { + match client::request("DELETE", &format!("/containers/{}", path_escape(id)), None) { + Ok(r) if r.ok() || r.status == 404 => {} + Ok(r) => blocked = Some(trf("Kept {name}: {container} couldn't be removed ({error})", &[("name", &name), ("container", &container_name(id)), ("error", &r.error())])), + Err(e) => blocked = Some(trf("Kept {name}: {error}", &[("name", &name), ("error", &e)])), + } + if blocked.is_some() { + break; + } } - if blocked.is_some() { - break; + match blocked { + Some(why) => emit(notice("error", &why)), + None => match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { + Ok(r) if r.ok() => { + // Only untagged when another name still points at it: nothing freed. + let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); + emit(serde_json::json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); + } + Ok(r) => emit(notice("error", &image_refusal(&name, &r.error()))), + Err(e) => emit(notice("error", &e.to_string())), + }, } - } - match blocked { - Some(why) => emit(notice("error", &why)), - None => match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { - Ok(r) if r.ok() => { - // Only untagged when another name still points at it: nothing freed. - let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); - emit(serde_json::json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); - } - Ok(r) => emit(notice("error", &image_refusal(&name, &r.error()))), - Err(e) => emit(notice("error", &e.to_string())), - }, - } - // Older daemons send no image events: refresh by hand. - refresh(&mut connected); + // Older daemons send no image events: refresh by hand. + let _ = tx.send(Cmd::Refresh); + }); } Ok(Cmd::Container { action, id }) => { let (method, path) = match action.as_str() { @@ -323,35 +334,40 @@ fn engine(rx: Receiver, tx: Sender) { a @ ("start" | "stop" | "restart" | "pause" | "unpause") => ("POST", format!("/containers/{id}/{a}")), _ => continue, }; - let result = expect_done(client::request(method, &path, None)); - // Refused to start (a port taken): the container's page says why. - if let (Err(e), "start") = (&result, action.as_str()) { - emit(serde_json::json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); - } - act(&action, result); + spawn_op(move || { + let result = expect_done(client::request(method, &path, None)); + // Refused to start (a port taken): the container's page says why. + if let (Err(e), "start") = (&result, action.as_str()) { + emit(serde_json::json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); + } + act(&action, result); + }); } - Ok(Cmd::RemoveVolume(name)) => act("rmvol", expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None))), - Ok(Cmd::Ports { id, ports }) => act("ports", set_ports(&id, ports)), - Ok(Cmd::Env { id, env }) => act("env", set_env(&id, env)), - Ok(Cmd::About) => about(), + Ok(Cmd::RemoveVolume(name)) => spawn_op(move || act("rmvol", expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None)))), + Ok(Cmd::Ports { id, ports }) => spawn_op(move || act("ports", set_ports(&id, ports))), + Ok(Cmd::Env { id, env }) => spawn_op(move || act("env", set_env(&id, env))), + Ok(Cmd::About) => spawn_op(about), Ok(Cmd::Domains(on)) => { - let result = if on { setup::domains() } else { setup::remove_domains() }; - // Cancelling macOS's password prompt is a choice, not an error. - match result { - Err(e) if !e.to_string().contains("-128") => emit(notice("error", &trf("Could not change container names: {error}", &[("error", &e)]))), - _ if crate::daemon::dns::installed() => emit(notice("ok", &tr("Containers now answer at .kiri.local"))), - _ if !on => emit(notice("ok", &tr("Containers answer at .kiri.localhost"))), - _ => {} - } - // /var/run/docker.sock was asked for with the same password. - if let Some(note) = setup::docker_socket_note().filter(|_| on) { - emit(notice("ok", ¬e)); - } - emit(domains_event()); - emit_docker_state(); - refresh(&mut connected); + let tx = tx.clone(); + spawn_op(move || { + let result = if on { setup::domains() } else { setup::remove_domains() }; + // Cancelling macOS's password prompt is a choice, not an error. + match result { + Err(e) if !e.to_string().contains("-128") => emit(notice("error", &trf("Could not change container names: {error}", &[("error", &e)]))), + _ if crate::daemon::dns::installed() => emit(notice("ok", &tr("Containers now answer at .kiri.local"))), + _ if !on => emit(notice("ok", &tr("Containers answer at .kiri.localhost"))), + _ => {} + } + // /var/run/docker.sock was asked for with the same password. + if let Some(note) = setup::docker_socket_note().filter(|_| on) { + emit(notice("ok", ¬e)); + } + emit(domains_event()); + emit_docker_state(); + let _ = tx.send(Cmd::Refresh); + }); } - Ok(Cmd::TakeSocket) => { + Ok(Cmd::TakeSocket) => spawn_op(|| { match setup::docker_socket() { Ok(()) if setup::docker_sock() == crate::dockerctx::Endpoint::Kiri => { emit(notice("ok", &tr("/var/run/docker.sock now points to Kiri"))); @@ -366,8 +382,8 @@ fn engine(rx: Receiver, tx: Sender) { Err(_) => {} } emit_docker_state(); - } - Ok(Cmd::RemoveNetwork(id)) => act("rmnet", expect_ok(client::request("DELETE", &format!("/networks/{id}"), None))), + }), + Ok(Cmd::RemoveNetwork(id)) => spawn_op(move || act("rmnet", expect_ok(client::request("DELETE", &format!("/networks/{id}"), None)))), Ok(Cmd::Quit) | Err(RecvTimeoutError::Disconnected) => { quit_with( stop_on_quit(), @@ -2222,16 +2238,18 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { if msg.name == "theme" { window::set_appearance(msg.value.as_str().unwrap_or("system")); } - if msg.name == "startAtLogin" - && let Some(on) = msg.value.as_bool() - && let Err(e) = setup::set_start_at_login(on) - { - diag::warn!("could not change start at sign-in", on = on, error = e); - emit(notice("error", &e.to_string())); - emit(serde_json::json!({"type": "prefs", "prefs": prefs()}).to_string()); - return; - } + let start_login = (msg.name == "startAtLogin").then(|| msg.value.as_bool()).flatten(); set_pref(&msg.name, msg.value); + if let Some(on) = start_login { + std::thread::spawn(move || { + if let Err(e) = setup::set_start_at_login(on) { + diag::warn!("could not change start at sign-in", on = on, error = e); + set_pref("startAtLogin", (!on).into()); + emit(notice("error", &e.to_string())); + emit(serde_json::json!({"type": "prefs", "prefs": prefs()}).to_string()); + } + }); + } Ok(()) } // A language the page doesn't carry yet (it opens with one): its words, @@ -2341,13 +2359,14 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { Ok(()) } "savesbom" => { - match crate::scan::save_sbom(&msg.name, msg.id.parse().unwrap_or(0), &msg.path) { + let (name, at, path) = (msg.name, msg.id.parse().unwrap_or(0), msg.path); + std::thread::spawn(move || match crate::scan::save_sbom(&name, at, &path) { Ok(to) => { emit(notice("ok", &trf("Saved the SBOM to Downloads as {file}", &[("file", &to.file_name().unwrap_or_default().to_string_lossy())]))); reveal(&to); } Err(e) => emit(notice("error", &trf("Could not save the SBOM: {error}", &[("error", &e)]))), - } + }); Ok(()) } // Share: public links for a port or container, and the Share account. @@ -2489,14 +2508,17 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { } // Which engine plain `docker` uses: Kiri, or back to the one before. "usecontext" => { - let result = setup::use_context(&msg.name); - emit_docker_state(); - emit(serde_json::json!({"type": "usedcontext", "name": msg.name, "error": result.as_ref().err().map(|e| e.to_string())}).to_string()); + let name = msg.name; + std::thread::spawn(move || { + let result = setup::use_context(&name); + emit_docker_state(); + emit(serde_json::json!({"type": "usedcontext", "name": name, "error": result.as_ref().err().map(|e| e.to_string())}).to_string()); + }); Ok(()) } // Settings → Network: Docker socket state and taking /var/run/docker.sock when free. "dockersock" => { - emit_docker_state(); + std::thread::spawn(emit_docker_state); Ok(()) } "takesocket" => tx.send(Cmd::TakeSocket), @@ -2792,9 +2814,12 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { Ok(()) } "terminal" => { - if let Err(e) = detail::terminal(&msg.name) { - emit(notice("error", &trf("Could not open Terminal: {error}", &[("error", &e)]))); - } + let name = msg.name; + std::thread::spawn(move || { + if let Err(e) = detail::terminal(&name) { + emit(notice("error", &trf("Could not open Terminal: {error}", &[("error", &e)]))); + } + }); Ok(()) } "files" => { @@ -2806,19 +2831,23 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { Ok(()) } "download" => { - match detail::download(&msg.name, &msg.path) { + let (name, path) = (msg.name, msg.path); + std::thread::spawn(move || match detail::download(&name, &path) { Ok(to) => { emit(notice("ok", &trf("Saved to Downloads as {file}", &[("file", &to.file_name().unwrap_or_default().to_string_lossy())]))); reveal(&to); } Err(e) => emit(notice("error", &trf("Could not save the file: {error}", &[("error", &e)]))), - } + }); Ok(()) } "reveal" => { - if let Err(e) = detail::reveal(&msg.name, &msg.path) { - emit(notice("error", &e.to_string())); - } + let (name, path) = (msg.name, msg.path); + std::thread::spawn(move || { + if let Err(e) = detail::reveal(&name, &path) { + emit(notice("error", &e.to_string())); + } + }); Ok(()) } // Only the container's own addresses: a page cannot open arbitrary URLs. @@ -2940,13 +2969,12 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { if std::env::var_os("KIRI_STAR_PROMPT").is_some() { emit(r#"{"type":"starprompt"}"#.to_owned()); } - // Kiri Lite: fetch the docker CLI, Compose and buildx the - // first time, unless this Mac already has a docker CLI. - if crate::tools::lite() && !crate::tools::installed() && !other_docker_cli() { - setup_tools(); + ask_language(); + // The first time the app opens: ask, once, whether to use *.kiri.local (the Mac only, so far). + if cfg!(target_os = "macos") && !crate::flavor::dev() && !crate::daemon::dns::installed() && prefs()["domainsAsked"] != true { + set_pref("domainsAsked", true.into()); + emit(r#"{"type":"welcome"}"#.to_owned()); } - emit(domains_event()); - emit_docker_state(); std::thread::spawn(storage_status); // A crash since the window last opened, for the page to // offer a report; crash files go if the person allowed it. @@ -2961,12 +2989,6 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { // engine still on an older build. std::thread::spawn(|| update_check(false)); recheck::start(|| feed_check(false)); - ask_language(); - // The first time the app opens: ask, once, whether to use *.kiri.local (the Mac only, so far). - if cfg!(target_os = "macos") && !crate::flavor::dev() && !crate::daemon::dns::installed() && prefs()["domainsAsked"] != true { - set_pref("domainsAsked", true.into()); - emit(r#"{"type":"welcome"}"#.to_owned()); - } // Another engine is here and nobody has chosen: ask once which // builder docker build uses (after the welcome, if that shows). std::thread::spawn(|| { @@ -2975,38 +2997,53 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { } emit(crate::buildwith::event()); }); - // Linux: Kiri checks it can run containers for this account - // first; until it can, the page shows the setup checklist and - // nothing starts (its Open Kiri sends "onbopen"). - #[cfg(target_os = "linux")] - { - let checks = linux::onboarding::checks(); - if linux::onboarding::needed(&checks) { - emit(checks.to_string()); - return; + // Subprocess and socket probes run off the main UI thread so the + // window stays responsive from its first frame. + let tx = tx.clone(); + let _ = std::thread::Builder::new().name("kiri-ready".into()).spawn(move || { + // Kiri Lite: fetch the docker CLI, Compose and buildx the + // first time, unless this Mac already has a docker CLI. + if crate::tools::lite() && !crate::tools::installed() && !other_docker_cli() { + setup_tools(); } - } - // The Mac: the first launch's steps that failed wait in the same - // checklist, over a window that works (the engine starts anyway). - #[cfg(target_os = "macos")] - { - let checks = macsetup::checks(); - if macsetup::needed(&checks) { - emit(checks.to_string()); + emit(domains_event()); + emit_docker_state(); + // Linux: Kiri checks it can run containers for this account + // first; until it can, the page shows the setup checklist and + // nothing starts (its Open Kiri sends "onbopen"). + #[cfg(target_os = "linux")] + { + let checks = linux::onboarding::checks(); + if linux::onboarding::needed(&checks) { + emit(checks.to_string()); + return; + } } - } - let _ = tx.send(Cmd::Refresh); - // Opening the window reaches the engine (starting its service if it - // isn't running) but doesn't wake it: asleep, it reads Ready, and the - // next docker command or action wakes it. One someone stopped waits - // for Start, unless quitting stopped it (stopOnQuit). - if (autostart || cfg!(target_os = "macos") || stop_on_quit()) && (!engine_stopped() || stop_on_quit()) { tx.send(Cmd::Connect) } else { Ok(()) } + // The Mac: the first launch's steps that failed wait in the same + // checklist, over a window that works (the engine starts anyway). + #[cfg(target_os = "macos")] + { + let checks = macsetup::checks(); + if macsetup::needed(&checks) { + emit(checks.to_string()); + } + } + let _ = tx.send(Cmd::Refresh); + // Opening the window reaches the engine (starting its service if it + // isn't running) but doesn't wake it: asleep, it reads Ready, and the + // next docker command or action wakes it. One someone stopped waits + // for Start, unless quitting stopped it (stopOnQuit). + if (autostart || cfg!(target_os = "macos") || stop_on_quit()) && (!engine_stopped() || stop_on_quit()) { + let _ = tx.send(Cmd::Connect); + } + }); + Ok(()) } // The Linux setup checklist: check again, fix one or "all", open the // window once it's ready, or sign in again for the group to apply. #[cfg(target_os = "linux")] "onbcheck" => { - emit(linux::onboarding::checks().to_string()); + std::thread::spawn(|| emit(linux::onboarding::checks().to_string())); Ok(()) } #[cfg(target_os = "linux")] diff --git a/tests/ui/searchselect.js b/tests/ui/searchselect.js index e38b72b59..be35b0fc3 100644 --- a/tests/ui/searchselect.js +++ b/tests/ui/searchselect.js @@ -116,7 +116,7 @@ t("a short list has no search box; letters jump, Tab closes and moves on", () => need(!pop() && document.activeElement === mbtn(), "Tab didn't close to the button"); }); t("near the bottom the list opens upwards, all of it in the window", () => { - const c = document.getElementById("content"); + const c = document.querySelector(".settings-body") || document.getElementById("content"); c.scrollTop = 0; const y = box(fbtn()).bottom; c.scrollTop = Math.max(0, y - innerHeight + 24); diff --git a/tests/ui/settings-scroll-and-perf.js b/tests/ui/settings-scroll-and-perf.js new file mode 100644 index 000000000..514d04437 --- /dev/null +++ b/tests/ui/settings-scroll-and-perf.js @@ -0,0 +1,138 @@ +// Settings keeps its left tab rail static while the pane body scrolls, preserves +// body scroll across live redraws on the same tab, resets on tab switch, and +// keeps UI responsiveness helpers (log counts, diag selection, floating tips) +// accurate without idle requestAnimationFrame loops. +const R = []; +const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; + +show("settings"); +document.querySelector('[data-stab="appearance"]').click(); + +t("Settings left tab rail stays static while the body scrolls", () => { + const tabs = document.querySelector(".settings .tabs"); + const body = document.querySelector(".settings-body"); + const heading = body?.querySelector(".pane h3"); + if (!tabs || !body || !heading) throw new Error("missing .settings .tabs or .settings-body"); + const tabsTop0 = tabs.getBoundingClientRect().top; + const headTop0 = heading.getBoundingClientRect().top; + body.scrollTop = 180; + if (body.scrollTop < 80) throw new Error(`Appearance body did not scroll (scrollTop=${body.scrollTop}, scrollHeight=${body.scrollHeight}, clientHeight=${body.clientHeight})`); + const tabsTop1 = tabs.getBoundingClientRect().top; + const headTop1 = heading.getBoundingClientRect().top; + if (Math.abs(tabsTop1 - tabsTop0) > 0.5) throw new Error(`tabs moved from ${tabsTop0} to ${tabsTop1}`); + if (headTop1 >= headTop0 - 40) throw new Error(`pane heading did not scroll (${headTop0} -> ${headTop1})`); +}); + +t("Settings preserves body scroll on live redraws and resets on tab switch", () => { + const body0 = document.querySelector(".settings-body"); + body0.scrollTop = 140; + const kept = body0.scrollTop; + // Trigger a live update on the same tab (Appearance). + kiri.on({ type: "shellpath", supported: true, enabled: true }); + const body1 = document.querySelector(".settings-body"); + if (Math.abs(body1.scrollTop - kept) > 1) throw new Error(`same-tab redraw lost scroll (${kept} -> ${body1.scrollTop})`); + // Switching tabs resets body scroll to 0. + document.querySelector('[data-stab="kubernetes"]').click(); + const body2 = document.querySelector(".settings-body"); + if (body2.scrollTop !== 0) throw new Error(`tab switch kept old scrollTop=${body2.scrollTop}`); +}); + +t("Settings RTL places static tabs on inline-start and body beside them", () => { + document.documentElement.dir = "rtl"; + try { + render(); + const tabs = document.querySelector(".settings .tabs").getBoundingClientRect(); + const pane = document.querySelector(".settings .pane").getBoundingClientRect(); + if (pane.right > tabs.left + 1) throw new Error(`RTL pane (${pane.left}..${pane.right}) overlaps tabs (${tabs.left}..${tabs.right})`); + } finally { + document.documentElement.dir = "ltr"; + render(); + } +}); + +t("Log console O(1) visible count stays exact across filters and LOG_MAX trims", () => { + const el = makeLogConsole(); + const countHost = document.createElement("span"); + countHost.id = "perf-log-count"; + document.body.append(countHost); + try { + let n = 0; + const partial = { false: "", true: "" }; + const state = { logFilter: "match", logLevel: "", follow: false }; + const lines = Array.from({ length: LOG_MAX + 25 }, (_, i) => (i % 5 === 0 ? `INFO match-${i}` : `INFO other-${i}`)).join("\n") + "\n"; + appendLogParts(el, "perf-log-count", state, partial, () => ++n, [{ e: false, t: lines }]); + const domVisible = [...el.children].filter((x) => !x.classList.contains("hide")).length; + if (el.childElementCount !== LOG_MAX) throw new Error(`expected ${LOG_MAX} children, got ${el.childElementCount}`); + if (el._shown !== domVisible) throw new Error(`_shown=${el._shown} !== domVisible=${domVisible}`); + state.logFilter = ""; + state.logLevel = "error"; + applyLogFilter(el, "perf-log-count", state); + if (el._shown !== 0) throw new Error(`expected 0 error lines, got ${el._shown}`); + clearLogConsole(el, "perf-log-count", state, partial, () => { n = 0; }); + if (el._shown !== 0 || el.childElementCount !== 0) throw new Error("clearLogConsole did not reset _shown"); + } finally { + countHost.remove(); + } +}); + +t("Diagnostics log preserves active text selection across background polls and morphs unchanged rows", () => { + show("settings"); + document.querySelector('[data-stab="diagnostics"]').click(); + kiri.on({ + type: "diaglogs", + part: "", + op: "", + lines: [ + { time: "2026-11-26T07:00:01.000Z", level: "info", part: "daemon", msg: "first line" }, + { time: "2026-11-26T07:00:02.000Z", level: "warn", part: "ui", msg: "second line" }, + ], + }); + const log = document.getElementById("dg-log"); + const firstRow = log.firstElementChild; + if (!firstRow || log.childElementCount !== 2) throw new Error(`expected 2 initial diagnostics rows, got ${log.childElementCount}`); + const range = document.createRange(); + range.selectNodeContents(firstRow); + const sel = getSelection(); + sel.removeAllRanges(); + sel.addRange(range); + // While text is selected inside #dg-log, a background poll updates count without wiping selection. + kiri.on({ + type: "diaglogs", + part: "", + op: "", + lines: [ + { time: "2026-11-26T07:00:01.000Z", level: "info", part: "daemon", msg: "first line" }, + { time: "2026-11-26T07:00:02.000Z", level: "warn", part: "ui", msg: "second line" }, + { time: "2026-11-26T07:00:03.000Z", level: "error", part: "daemon", msg: "third line" }, + ], + }); + if (log.childElementCount !== 2 || !firstRow.isConnected || sel.isCollapsed) { + sel.removeAllRanges(); + throw new Error("selection or DOM rows were wiped during active selection"); + } + sel.removeAllRanges(); + drawDiagLog(); + if (log.childElementCount !== 3) throw new Error(`expected 3 rows after selection cleared, got ${log.childElementCount}`); + if (log.firstElementChild !== firstRow) throw new Error("unchanged first row was destroyed instead of morphed"); +}); + +t("Idle floating popovers do not spin requestAnimationFrame continuously", () => { + const nowS = Date.now() / 1000; + kiri.on({ type: "lists", containers: [], images: [{ Id: "sha256:" + "1".repeat(64), RepoTags: ["postgres:17"], Size: 1e8, Created: nowS }], volumes: [], networks: [] }); + show("images"); + let rafCalls = 0; + const origRaf = window.requestAnimationFrame; + window.requestAnimationFrame = (cb) => { rafCalls++; return origRaf(cb); }; + try { + document.querySelector('[data-run="postgres:17"]').click(); + if (!document.querySelector(".need")) throw new Error("need popover did not open"); + rafCalls = 0; + needPlace(); + if (rafCalls !== 0) throw new Error(`needPlace scheduled ${rafCalls} recursive rAF calls`); + needClose(); + } finally { + window.requestAnimationFrame = origRaf; + } +}); + +report(R); From 175f04ad5a0d51b3097ec33ef48f7a03655ddac3 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 10:45:29 +0100 Subject: [PATCH 146/157] UI: always offer Restart now and Restart VM to apply when engine is on --- crates/kiri-win/src/wslconfig.rs | 5 +++-- crates/kiri/src/ui/index.html | 16 ++++++++++------ crates/kiri/src/ui/mod.rs | 9 +++++---- tests/ui/restartnow.js | 26 +++++++++++++++++++++++++- 4 files changed, 43 insertions(+), 13 deletions(-) diff --git a/crates/kiri-win/src/wslconfig.rs b/crates/kiri-win/src/wslconfig.rs index ab5a7a92b..0ce3a4aef 100644 --- a/crates/kiri-win/src/wslconfig.rs +++ b/crates/kiri-win/src/wslconfig.rs @@ -321,9 +321,10 @@ pub fn resources(body: Option) { } let saved = body.map(|b| save(&b)); let ev = event(); + let running = ev["awake"] == true || !crate::serve::is_stopped(); match saved { - // While Kiri's engine runs, the toast offers to restart WSL now. - Some(Ok(())) => emit(json!({"type": "notice", "kind": "ok", "text": tr("Saved in .wslconfig. WSL uses these from its next start"), "act": if ev["awake"] == true { "restartvm" } else { "" }}).to_string()), + // While Kiri's engine is on, the toast offers to restart WSL now. + Some(Ok(())) => emit(json!({"type": "notice", "kind": "ok", "text": tr("Saved in .wslconfig. WSL uses these from its next start"), "act": if running { "restartvm" } else { "" }}).to_string()), Some(Err(e)) => emit(notice("error", &trf("Could not save .wslconfig: {error}", &[("error", &e)]))), None => {} } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 6a0dab62c..df1611a16 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -4718,8 +4718,9 @@

${tr("Use {app} for docker?", { app: esc(app) })}

function vmNetRow() { const v = ui.vmnet; if (!v || v.supported === false) return ""; - const nat = v.shared_nat !== false; - const pending = v.awake && v.running_shared_nat != null && v.running_shared_nat !== nat; + const nat = v.shared_nat !== false, on = v.awake || engineShown().on; + if (v.awake && v.running_shared_nat === nat) ui.vmNetSaved = false; + const pending = on && ((v.awake && v.running_shared_nat != null && v.running_shared_nat !== nat) || (!v.awake && ui.vmNetSaved)); const desc = nat ? tr("macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.") : tr("Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart."); @@ -4809,7 +4810,9 @@

${tr("Use {app} for docker?", { app: esc(app) })}

const hasSwap = r.swap_mib != null; const maxSwap = r.max_swap_mib ?? 16384; const swapVal = hasSwap ? Math.min(d.swap_mib ?? r.swap_mib, maxSwap) : 0; - const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64 || (hasDisk && r.running_disk_gb != null && r.running_disk_gb !== r.disk_gb) || (hasSwap && r.running_swap_mib != null && r.running_swap_mib !== r.swap_mib)); + const diff = r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64 || (hasDisk && r.running_disk_gb != null && r.running_disk_gb !== r.disk_gb) || (hasSwap && r.running_swap_mib != null && r.running_swap_mib !== r.swap_mib); + if (r.awake && !diff) ui.resSaved = false; + const pending = (r.awake || engineShown().on) && (diff || (!r.awake && ui.resSaved)); return `

${tr("Resources")}

${tr("CPUs")}${LINUX ? tr("Shared with Linux: containers only use them while busy.") : tr("Shared with {os}: the VM only uses them while containers are busy.", { os: OS })}
${cpuText(d.cpus)}
@@ -7667,7 +7670,7 @@

${tr("What's new in Kiri {version}", { version: esc(u.version) if (ui.view === "settings" && prefs.tab === "resources") render(); // Asleep, the VM holds no memory and the vm event says so (0 MB); off, there's nothing to read. if (state === "stopped" || state === "stopping") ["vm-mem"].forEach((id) => ($(id).textContent = "—")), ($("vm-meter").style.width = "0"); - if (state === "stopped") { ui.volSizesInFlight = 0; ui.volSizesLoading = false; ui.volSizesAt = 0; } + if (state === "stopped") { ui.volSizesInFlight = 0; ui.volSizesLoading = false; ui.volSizesAt = 0; ui.resSaved = false; ui.vmNetSaved = false; } if (state === "running" && was !== "running") { ui.volSizesAt = 0; if (ui.view === "volumes") { requestVolumeSizes(); render(); } } if (state === "stopped" || was === "stopped") render(); } @@ -8838,7 +8841,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r case "textsize": if (htHasFocus()) htStep(e.step); else stepTextSize(e.step); break; case "term": htOn(e); break; case "closekey": htCloseKey(); break; - case "vmrestarted": if (ui.restarting?.kind === "vm") stopRestartOverlay(); break; + case "vmrestarted": if (e.ok) { ui.resSaved = false; ui.vmNetSaved = false; } if (ui.restarting?.kind === "vm") stopRestartOverlay(); if (ui.view === "settings") render(); break; case "enginerestarted": if (ui.restarting?.kind === "engine") stopRestartOverlay(); if (!e.error) engineToast(e); break; case "view": if (empty[e.view] || e.view === "settings") show(e.view); break; case "prefs": { const was = prefs.lang; Object.assign(prefs, e.prefs || {}); prefsIn = true; if (prefs.lang !== was) relang(); applyPrefs(); render(); paintEngine(); renderStatus(); break; } @@ -9133,6 +9136,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-vmnat]"))) { const shared_nat = el.dataset.vmnat === "1"; if (ui.vmnet && !ui.vmnet.env && !!ui.vmnet.shared_nat !== shared_nat) { + if (engineShown().on) ui.vmNetSaved = true; ui.vmnet = { ...ui.vmnet, shared_nat }; send("setvmnet", { value: { shared_nat } }); render(); @@ -9168,7 +9172,7 @@

${send_ ? tr("Send a report to Kiri") : tr("Create a diagnostics r else if ((el = t("[data-regdel]"))) { const [k, i] = el.dataset.regdel.split(":"); ui.regDraft[k].splice(+i, 1); render(); } else if ((el = t("[data-regsave]"))) { ui.regSaving = el.dataset.regsave; send("setregistryconfig", { value: { [REG_KEY[el.dataset.regsave]]: ui.regDraft[el.dataset.regsave] } }); } else if ((el = t("[data-saverp]")) && ui.rports && !ui.rports.error) send("setrouterports", { value: { http: +(ui.rpDraft.http ?? ui.rports.http.port), https: +(ui.rpDraft.https ?? ui.rports.https.port) } }); - else if ((el = t("[data-saveres]"))) send("setresources", { value: ui.resDraft }); + else if ((el = t("[data-saveres]"))) { if (engineShown().on) ui.resSaved = true; send("setresources", { value: ui.resDraft }); render(); } else if ((el = t("[data-watchbinds]"))) { const on = el.dataset.watchbinds === "1"; if (!!(prefs.watchBindMounts ?? ui.res?.watch_bind_mounts) !== on) setPref("watchBindMounts", on); diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 31e521d90..02e8cfc19 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -1021,9 +1021,10 @@ fn vm_net(save: Option) { let effective = env_override.or(configured).unwrap_or(true); let info = client::get_background("/info").ok(); let awake = info.as_ref().is_some_and(|i| i["KiriVmAwake"] == true); + let running = info.as_ref().is_some_and(|i| awake || i["KiriStopped"] != true); let running_shared_nat = awake.then(|| info.as_ref().and_then(|i| i["KiriVmUplink"]["mode"].as_str()).is_none_or(|m| m != "host-egress")); match saved { - Some(Ok(())) => emit(serde_json::json!({"type": "notice", "kind": "ok", "text": tr("Outbound VM traffic setting saved. Restart the VM to apply."), "act": if awake { "restartvm" } else { "" }}).to_string()), + Some(Ok(())) => emit(serde_json::json!({"type": "notice", "kind": "ok", "text": tr("Outbound VM traffic setting saved. Restart the VM to apply."), "act": if running { "restartvm" } else { "" }}).to_string()), Some(Err(e)) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), None => {} } @@ -1089,14 +1090,14 @@ fn resources(save: Option) { let saved = save.map(|body| client::request("POST", "/kiri/resources", Some(&body))); let now = client::get("/kiri/resources"); match saved { - // While the VM runs, the toast offers to restart it now. + // While the engine is on (awake or resting), the toast offers to restart it now. Some(Ok(r)) if r.ok() => { - let awake = now.as_ref().is_ok_and(|v| v["awake"] == true); + let running = now.as_ref().is_ok_and(|v| v["awake"] == true || !engine_stopped()); #[cfg(target_os = "linux")] let text = tr("Saved. The engine uses these from its next start"); #[cfg(not(target_os = "linux"))] let text = tr("Saved. The VM uses these from its next start"); - emit(serde_json::json!({"type": "notice", "kind": "ok", "text": text, "act": if awake { "restartvm" } else { "" }}).to_string()); + emit(serde_json::json!({"type": "notice", "kind": "ok", "text": text, "act": if running { "restartvm" } else { "" }}).to_string()); } Some(Ok(r)) => emit(notice("error", &r.error())), Some(Err(e)) => emit(notice("error", &e.to_string())), diff --git a/tests/ui/restartnow.js b/tests/ui/restartnow.js index d4cbd889b..2dc1126e1 100644 --- a/tests/ui/restartnow.js +++ b/tests/ui/restartnow.js @@ -34,11 +34,35 @@ t("toast Restart now opens universal Restarting overlay with .rspin and syncs VM eq(document.body.dataset.vm, "running", "restored to running"); }); -t("no Restart now link while the VM is asleep", () => { +t("no Restart now link while the engine is off", () => { kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "" }); if (document.querySelector("#toasts [data-trestart]")) throw new Error("link shown"); }); +t("Saving resources or VM traffic while the VM is resting (engine on, awake false) still offers Restart VM to apply", () => { + kiri.on({ type: "state", state: "asleep" }); + kiri.on({ + type: "resources", cpus: 2, memory_mib: 12288, disk_gb: 64, + running_cpus: 2, running_memory_mib: 12288, running_disk_gb: 64, + awake: false, max_cpus: 12, max_memory_mib: 32768, min_disk_gb: 64, max_disk_gb: 1024, overridden: false, + }); + prefs.tab = "resources"; + show("settings"); + const cpuSlider = document.getElementById("res-cpus"); + cpuSlider.value = "4"; + cpuSlider.dispatchEvent(new Event("input", { bubbles: true })); + document.getElementById("res-save").click(); + kiri.on({ + type: "resources", cpus: 4, memory_mib: 12288, disk_gb: 64, + running_cpus: 4, running_memory_mib: 12288, running_disk_gb: 64, + awake: false, max_cpus: 12, max_memory_mib: 32768, min_disk_gb: 64, max_disk_gb: 1024, overridden: false, + }); + if (!document.getElementById("res-restart")) throw new Error("missing #res-restart after saving while VM is resting"); + kiri.on({ type: "vmrestarted", ok: true }); + if (document.getElementById("res-restart")) throw new Error("#res-restart stayed after vmrestarted"); + kiri.on({ type: "state", state: "running" }); +}); + t("Resources Restart VM to apply and Network Restart VM to apply open Restarting overlay", () => { kiri.on({ type: "resources", cpus: 4, memory_mib: 11264, disk_gb: 160, From 1b57526f84e1984b25f47690da787b5a84653c2a Mon Sep 17 00:00:00 2001 From: Karthik P Date: Thu, 26 Nov 2026 12:03:22 +0530 Subject: [PATCH 147/157] Engine: docker container prune and system prune keep stopped machines (#975) A `kiri machine` keeps its work in its container's writable layer, so a routine `docker system prune` with the machine stopped deleted it and everything in it. container_prune now leaves containers labelled dev.kiri.machine out, as OrbStack's prunes leave its machines alone; `kiri machine delete` and `docker rm machine-NAME` still remove one. The window's prune goes through the same endpoint. Unit test in daemon/ops.rs, e2e check machine-prune-keeps, listed in tests/regressions.tsv; docs/features.md says prunes keep machines. --- crates/kiri/src/daemon/ops.rs | 37 ++++++++++++++++++++++++++++++++++- crates/kiri/src/machine.rs | 2 +- docs/features.md | 4 +++- tests/e2e.sh | 4 +++- tests/regressions.tsv | 1 + 5 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index c266c1d04..e7bf3a122 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -383,7 +383,10 @@ fn container_prune(req: &Request, engine: &Engine) -> Result { let doomed = engine.each(|c| { let labels = if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }; let created = c.created.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0); - (c.status != Status::Running && f.labels(&labels) && before(until, created)).then(|| c.id.clone()) + // A `kiri machine` keeps its work in its writable layer: a stopped one + // stays, as on OrbStack; `kiri machine delete` or `docker rm` removes it. + let machine = labels.get(crate::machine::LABEL).is_some(); + (c.status != Status::Running && !machine && f.labels(&labels) && before(until, created)).then(|| c.id.clone()) }); let mut deleted = Vec::new(); for id in doomed { @@ -835,6 +838,38 @@ mod disk_usage_tests { let _ = std::fs::remove_dir_all(root); } + /// `docker container prune` (and `system prune`) keeps a stopped + /// `kiri machine` and removes a stopped plain container (#975). + #[test] + fn container_prune_keeps_machines() { + use super::Request; + use serde_json::json; + let root = std::env::temp_dir().join(format!("kiri-container-prune-machines-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + let image = kiri_image::Image { mirror: None, + name: "local:1".into(), digest: "sha256:0123".into(), index_digest: None, config_digest: "sha256:0123".into(), + layers: Vec::new(), size: 0, platform: "linux/arm64".into(), created: String::new(), pulled_at: 0, config: Default::default(), + }; + let spec = |labels| -> super::super::engine::Spec { + serde_json::from_value(json!({ + "image": "local:1", "image_id": "sha256:0123", "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": labels, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap() + }; + let machine = engine.create(Some("machine-dev".into()), spec(json!({crate::machine::LABEL: "dev"})), &image).unwrap(); + let plain = engine.create(Some("plain".into()), spec(json!({})), &image).unwrap(); + let out = super::container_prune(&Request::internal("POST", "/containers/prune", &[], Vec::new()), &engine).unwrap(); + assert_eq!(out["ContainersDeleted"], json!([plain])); + let left: Vec = engine.each(|c| Some(c.id.clone())); + assert_eq!(left, [machine]); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// Image prune keeps what Docker keeps: an image's config labels must /// match `label` and not `label!`, and `until` keeps newer images. #[test] diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index 7433bd1d5..ebede90d3 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -13,7 +13,7 @@ use serde_json::json; use crate::client; -const LABEL: &str = "dev.kiri.machine"; +pub(crate) const LABEL: &str = "dev.kiri.machine"; /// `kiri machine create NAME --distro ubuntu` picks one of these. const DISTROS: [(&str, &str); 7] = [ diff --git a/docs/features.md b/docs/features.md index 6e05d4c39..cef9333b0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -138,7 +138,9 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr - **Kubernetes**: `kiri k8s start` — a single-node k3s cluster in one container, ready in ~20 s, as the `kiri` kubectl context - **Linux machines**: `kiri machine create dev --distro ubuntu` and - `kiri machine shell dev` — your user, sudo, and `/Users` at the same path + `kiri machine shell dev` — your user, sudo, and `/Users` at the same path; + `docker container prune` and `docker system prune` leave a stopped machine + alone (`kiri machine delete` removes it) - **The app**: `cargo xtask app` builds `Kiri.app` with the `docker` CLI, Compose and buildx inside; opening it runs `kiri setup` (docker context, LaunchAgent, build builder) and the window; `kiri update` installs new diff --git a/tests/e2e.sh b/tests/e2e.sh index 28d3e2ed8..fa69170a2 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2480,7 +2480,7 @@ code udp-port-free-after 0 bash -c "python3 -c 'import socket; s=socket.socket(s section "Linux machines" # The `kiri` CLI is $KIRI, found at the top. -MACHINE_TESTS="machine-create machine-list machine-user machine-mac-files machine-cwd machine-hostname machine-sudo machine-stop machine-stop-again machine-start machine-start-again machine-delete machine-bad-name" +MACHINE_TESTS="machine-create machine-list machine-user machine-mac-files machine-cwd machine-hostname machine-sudo machine-stop machine-prune-keeps machine-stop-again machine-start machine-start-again machine-delete machine-bad-name" # The binary as one shell word, for commands passed to bash -c (app paths have spaces). KQ=$(printf %q "$KIRI") if [ -x "$KIRI" ]; then @@ -2502,6 +2502,8 @@ needs homes-dir t machine-cwd "$MD" bash -c "cd $MD && $KQ machine shell e2e-m - t machine-hostname "e2e-m" bash -c "$KQ machine shell e2e-m -- hostname < /dev/null" t machine-sudo "root" bash -c "for i in \$(seq 30); do out=\$($KQ machine shell e2e-m -- sudo -n whoami < /dev/null 2>/dev/null); [ \"\$out\" = root ] && break; sleep 1; done; echo \$out" t machine-stop "Exited" bash -c "$KQ machine stop e2e-m && $KQ machine list" +# A stopped machine survives a prune, even one aimed at its label (#975). +t machine-prune-keeps "Exited" bash -c "$D container prune -f --filter label=dev.kiri.machine >/dev/null && $KQ machine list" # Stopped already, or running already: done, not an empty `kiri: ` and a failure. code machine-stop-again 0 "$KIRI" machine stop e2e-m t machine-start "Up" bash -c "$KQ machine start e2e-m && $KQ machine list" diff --git a/tests/regressions.tsv b/tests/regressions.tsv index b3146ef38..921592fb0 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -367,3 +367,4 @@ tests/ui/builds-running.js #923 the Builds view asked for a running build's step 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 crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit +machine-prune-keeps #975 docker container prune and docker system prune deleted a stopped kiri machine and everything in its writable layer From c863fd06335ac6739922e6917de043a650753728 Mon Sep 17 00:00:00 2001 From: Karthik P Date: Thu, 26 Nov 2026 12:04:08 +0530 Subject: [PATCH 148/157] Fix registry: #981 keeps stopped machines out of container and system prune (#975) --- docs/fix-registry.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 088b94acd..9f5413541 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 +### #981 Engine: docker container prune and system prune keep stopped machines (unreleased) +- Fixes: #975 A stopped machine is deleted by docker container prune / docker system prune, with everything in it +- Caused: none known +- Caused by: - +- Check: `machine-prune-keeps`, `crates/kiri/src/daemon/ops.rs` + ### #936 Volumes view: show each volume's disk size loaded asynchronously with daemon caching (unreleased) - Fixes: #936 Volumes view: show each volume's size, loaded asynchronously - Caused: none known From ab6221abb05b1d0c61eb8b11ef87a4f8c21065dc Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:15:29 +0100 Subject: [PATCH 149/157] Engine & Guest: bound VmLink and kiri-init TTY waits and refuse paused exec_start (#948) --- crates/kiri-init/src/linux/container.rs | 160 +++++++- crates/kiri/src/daemon/engine.rs | 56 ++- crates/kiri/src/daemon/vmlink.rs | 514 ++++++++++++++++++++---- tests/regressions.tsv | 2 + 4 files changed, 633 insertions(+), 99 deletions(-) diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 3b9c8e014..a49526523 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -475,21 +475,68 @@ fn stdio(p: &Prepared) -> io::Result<(ParentStdio, ChildStdio)> { )) } +/// Maximum wait for a spawned/exec'd TTY child to open `/dev/ptmx` and send +/// its master fd back over the control socket. Prevents a child cloned into a +/// frozen cgroup or wedged before `open_pty` from blocking single-threaded +/// `kiri-init` forever (#948). +const TTY_READY_WAIT: std::time::Duration = std::time::Duration::from_secs(10); + /// After clone: collect the agent's ends. For a TTY this waits for the child /// to send the pty master, or the reason it could not. fn finish_stdio(parent: ParentStdio, child: ChildStdio) -> io::Result<(Option, Option, Option)> { + finish_stdio_timeout(parent, child, TTY_READY_WAIT) +} + +fn finish_stdio_timeout( + parent: ParentStdio, + child: ChildStdio, + wait: std::time::Duration, +) -> io::Result<(Option, Option, Option)> { drop(child); match parent { ParentStdio::Pipes { stdin, stdout, stderr } => Ok((stdin, Some(stdout), Some(stderr))), - ParentStdio::Tty { sock } => match sys::recv_fd(sock.as_raw_fd())? { - Received::Fd(master) => { - sys::set_nonblocking(master.as_raw_fd())?; - let input = master.try_clone()?; - Ok((Some(input), Some(master), None)) + ParentStdio::Tty { sock } => { + sys::set_nonblocking(sock.as_raw_fd())?; + let deadline = std::time::Instant::now() + wait; + let received = loop { + let timeout = deadline + .saturating_duration_since(std::time::Instant::now()) + .as_micros() + .div_ceil(1000) + .min(i32::MAX as u128) as i32; + let mut pfd = libc::pollfd { fd: sock.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + // SAFETY: one valid pollfd. + let n = unsafe { libc::poll(&mut pfd, 1, timeout) }; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container terminal")); + } + if n < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(e); + } + match sys::recv_fd(sock.as_raw_fd()) { + Ok(r) => break r, + Err(e) if e.kind() == io::ErrorKind::Interrupted || e.kind() == io::ErrorKind::WouldBlock => { + if std::time::Instant::now() >= deadline { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container terminal")); + } + } + Err(e) => return Err(e), + } + }; + match received { + Received::Fd(master) => { + sys::set_nonblocking(master.as_raw_fd())?; + let input = master.try_clone()?; + Ok((Some(input), Some(master), None)) + } + Received::Message(m) if m.is_empty() => Err(io::Error::other("container exited before its terminal was ready")), + Received::Message(m) => Err(io::Error::other(m)), } - Received::Message(m) if m.is_empty() => Err(io::Error::other("container exited before its terminal was ready")), - Received::Message(m) => Err(io::Error::other(m)), - }, + } } } @@ -760,11 +807,23 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

{} Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))), - Ok(RootWord::NotYet) if prepared.tty => match root_word(root_ready.as_raw_fd(), None, &mut began_fill) { - Ok(RootWord::Ready) => {} - Ok(_) => return Err(kill_child(io::Error::other(NOT_READY))), - Err(e) => return Err(kill_child(e)), - }, + Ok(RootWord::NotYet) if prepared.tty => { + let word = if began_fill { + root_word(root_ready.as_raw_fd(), None, &mut began_fill) + } else { + match root_word(root_ready.as_raw_fd(), Some(TTY_READY_WAIT), &mut began_fill) { + Ok(RootWord::NotYet) if began_fill => root_word(root_ready.as_raw_fd(), None, &mut began_fill), + other => other, + } + }; + filling.set(began_fill); + match word { + Ok(RootWord::Ready) => {} + Ok(RootWord::NotYet) => return Err(kill_child(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container root"))), + Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))), + Err(e) => return Err(kill_child(e)), + } + } Ok(RootWord::NotYet) => starting.set(true), Err(e) => return Err(kill_child(e)), } @@ -1158,8 +1217,12 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile drop(cgroup_go); drop(cgroup_fd); let (stdin, stdout, stderr) = finish_stdio(parent_io, child_io).map_err(|e| { - // SAFETY: killing the child we just cloned. - unsafe { libc::kill(pid, libc::SIGKILL) }; + // SAFETY: killing and reaping the child we just cloned so a failed or + // timed-out TTY setup never leaks a stuck or zombie process (#948). + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } e })?; Ok(Process { @@ -4693,4 +4756,71 @@ mod tests { prepared.cgroupns_host = parsed.cgroupns_host; assert!(prepared.cgroupns_host); } + + #[test] + fn finish_stdio_times_out_when_tty_child_never_sends_pty_and_reaps_child() { + use std::os::fd::AsRawFd; + use std::time::{Duration, Instant}; + + // 1. Stuck child holding its socket end open: times out promptly instead of blocking forever. + let (p_sock, hold_child) = super::sys::socketpair().unwrap(); + let dup_child = hold_child.try_clone().unwrap(); + let began = Instant::now(); + let err = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: dup_child }, + Duration::from_millis(30), + ) + .unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2)); + drop(hold_child); + + // 2. Child exits without sending an fd: reports premature exit. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + let err = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_secs(1), + ) + .unwrap_err(); + assert!(err.to_string().contains("exited before its terminal was ready"), "{err}"); + + // 3. Child sends a valid fd: returns non-blocking input + master fds. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + let (r_pipe, _w_pipe) = super::sys::pipe().unwrap(); + super::sys::send_fd(c_sock.as_raw_fd(), r_pipe.as_raw_fd()).unwrap(); + let (stdin, stdout, stderr) = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_secs(1), + ) + .unwrap(); + assert!(stdin.is_some() && stdout.is_some() && stderr.is_none()); + + // 4. Real forked child that pauses before sending pty: timeout + SIGKILL + waitpid leaves no zombie. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + // SAFETY: child only calls pause() and _exit(0), both async-signal-safe. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0); + if pid == 0 { + unsafe { + libc::pause(); + libc::_exit(0); + } + } + let res = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_millis(25), + ); + assert_eq!(res.unwrap_err().kind(), std::io::ErrorKind::TimedOut); + // SAFETY: killing and reaping the child we just forked. + unsafe { + assert_eq!(libc::kill(pid, libc::SIGKILL), 0); + assert_eq!(libc::waitpid(pid, std::ptr::null_mut(), 0), pid); + assert_eq!(libc::kill(pid, 0), -1); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH)); + } + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index ec99457eb..5a274ebf7 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -5993,14 +5993,26 @@ impl Engine { let exec_security; let (container_id, config, env) = { let mut st = self.lock(); - let e = st.execs.get_mut(exec_id).ok_or_else(|| Error::NotFound(format!("No such exec instance: {exec_id}")))?; - if e.running || e.exit_code.is_some() { + let (already_ran, container_id) = { + let e = st.execs.get(exec_id).ok_or_else(|| Error::NotFound(format!("No such exec instance: {exec_id}")))?; + (e.running || e.exit_code.is_some(), e.container_id.clone()) + }; + if already_ran { return Err(Error::Conflict("exec has already run".into())); } + match st.containers.get(&container_id) { + None => return Err(Error::Conflict(format!("container {} is not running", &container_id[..12]))), + Some(c) if c.status != Status::Running => return Err(Error::Conflict(format!("container {} is not running", &container_id[..12]))), + Some(c) if c.paused && !is_builder(c) => { + return Err(Error::Conflict(format!("Container {} is paused, unpause the container before exec", &container_id[..12]))); + } + _ => {} + } + let e = st.execs.get_mut(exec_id).expect("checked above"); e.running = true; // Subscribe before the process exists, so no output is missed. e.attached.push(tx); - let (container_id, config) = (e.container_id.clone(), e.config.clone()); + let config = e.config.clone(); let (security, caps) = st.containers.get(&container_id).map(|c| (c.spec.security_flags() & !run_flags::READONLY_ROOTFS, c.spec.caps)).unwrap_or_default(); // Execs get the container's ulimits and groups, as with runc. let opts = st.containers.get(&container_id).map(|c| c.spec.guest_opts(false).unwrap_or_default()).unwrap_or_default(); @@ -10497,4 +10509,42 @@ mod exit_forwards_tests { drop(engine); let _ = std::fs::remove_dir_all(dir); } + + /// Refusing `exec_create` and `exec_start` on a paused non-builder container + /// returns 409 Conflict instead of cloning a child into a frozen cgroup (#948). + #[test] + fn exec_create_and_start_refuse_paused_non_builder_container() { + let (engine, id, dir) = engine_running("exec-paused-conflict"); + let cfg = || ExecConfig { + console_size: None, + argv: vec!["true".into()], + env: Vec::new(), + cwd: "/".into(), + user: String::new(), + tty: true, + stdin: false, + privileged: false, + internal: false, + }; + + engine.lock().containers.get_mut(&id).unwrap().paused = true; + match engine.exec_create(&id, cfg()) { + Err(Error::Conflict(msg)) => assert!(msg.contains("is paused, unpause the container before exec"), "{msg}"), + other => panic!("expected Conflict on paused exec_create, got {other:?}"), + } + + engine.lock().containers.get_mut(&id).unwrap().paused = false; + let exec_id = engine.exec_create(&id, cfg()).unwrap(); + engine.lock().containers.get_mut(&id).unwrap().paused = true; + let attempts_before = engine.boot_attempts.load(Ordering::SeqCst); + match engine.exec_start(&exec_id) { + Err(Error::Conflict(msg)) => assert!(msg.contains("is paused, unpause the container before exec"), "{msg}"), + other => panic!("expected Conflict on paused exec_start, got {other:?}"), + } + assert_eq!(engine.boot_attempts.load(Ordering::SeqCst), attempts_before, "paused exec_start must not touch VM"); + assert!(engine.with_exec(&exec_id, |e| !e.running && e.exit_code.is_none()).unwrap()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index f6eca08ac..8ecc4afdd 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -10,7 +10,7 @@ use std::collections::{HashMap, VecDeque}; use std::fs::File; -use std::io::{self, Read, Write}; +use std::io::{self, Read}; use std::path::Path; use std::sync::mpsc::{self, SyncSender}; use std::sync::{Arc, Condvar, Mutex}; @@ -72,13 +72,12 @@ pub enum Event<'a> { Lost, } +const WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +const FAST_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +const LONG_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); + pub struct VmLink { - writer: Mutex, - /// Stdin credit per running process; see `input`. - windows: Arc, - /// The guest's latest `Usage` lines, for `usage`. - usage: Arc, - pending: Arc>>>, + rpc: Channel, /// Layer digests confirmed unpacked in this guest instance, avoiding /// repeated `LayerQuery` round-trips across `create` and `start`. layers: Mutex>, @@ -87,10 +86,6 @@ pub struct VmLink { _vm: Mutex, /// Opens vsock streams without that mutex, so connects run side by side. connector: kiri_vmm::Connector, - /// A copy of the connection, shut down when the agent process exits - /// (see `new`); only while the link lives. - #[cfg(target_os = "linux")] - _stop_conn: Arc, /// The agent's folder on a Linux host, where it leaves what `docker /// info` should warn about (`host_warnings`). #[cfg(target_os = "linux")] @@ -103,13 +98,74 @@ impl std::fmt::Debug for VmLink { } } +/// Transport state and reader loop for the single guest control stream, +/// separated from `kiri_vmm::Vm` so socket timeout and FIFO loss invariants +/// can be unit-tested over a `UnixStream` pair. +struct Channel { + writer: Mutex, + /// Duplicate of the stream socket used to `shutdown(SHUT_RDWR)` without + /// acquiring `writer` when a call times out or (on Linux) the agent exits. + abort_conn: Arc, + /// Stdin credit per running process; see `input`. + windows: Arc, + /// The guest's latest `Usage` lines, for `usage`. + usage: Arc, + pending: Arc>>>, + fast_timeout: std::time::Duration, + long_timeout: std::time::Duration, + /// Count of long RPCs (`send_layer`, `run`, `AwaitStart`, `trim_disk`) + /// currently in flight so concurrent fast RPCs queued behind them on the + /// single-threaded guest do not time out prematurely. + long_in_flight: std::sync::atomic::AtomicUsize, +} + +struct LongCallGuard<'a>(&'a std::sync::atomic::AtomicUsize); + +impl Drop for LongCallGuard<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Release); + } +} + struct Writer { conn: File, out: Vec, blob: Vec, + write_timeout: std::time::Duration, } impl Writer { + fn new(conn: File, write_timeout: std::time::Duration) -> Writer { + use std::os::fd::AsRawFd; + let fd = conn.as_raw_fd(); + // SAFETY: setting O_NONBLOCK on the stream socket so `write_all_timeout` + // never blocks indefinitely in the kernel (macOS XNU ignores MSG_DONTWAIT + // on blocking AF_UNIX/AF_VSOCK sockets); `read_frame` polls POLLIN on + // the reader's dup. + unsafe { + let flags = libc::fcntl(fd, libc::F_GETFL); + if flags >= 0 { + libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK); + } + } + #[cfg(target_os = "macos")] + { + let one: libc::c_int = 1; + // SAFETY: sets SO_NOSIGPIPE on a descriptor we own so writes return + // EPIPE instead of raising SIGPIPE when the peer is gone. + unsafe { + libc::setsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_NOSIGPIPE, + (&one as *const libc::c_int).cast(), + std::mem::size_of::() as libc::socklen_t, + ); + } + } + Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024], write_timeout } + } + /// Whether the encoded request is within the agent's frame limit: one /// over it ends the agent, and every container with it, so it fails /// here alone, before anything is queued or sent. @@ -135,7 +191,9 @@ impl Writer { } fn write_request(&mut self, body: Option<(File, u64)>) -> io::Result<()> { - self.conn.write_all(&self.out)?; + use std::os::fd::AsRawFd; + let fd = self.conn.as_raw_fd(); + write_all_timeout(fd, &self.out, self.write_timeout)?; if let Some((mut file, size)) = body { let mut left = size; while left > 0 { @@ -144,7 +202,7 @@ impl Writer { if n == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "layer blob shrank while sending")); } - self.conn.write_all(&self.blob[..n])?; + write_all_timeout(fd, &self.blob[..n], self.write_timeout)?; left -= n as u64; } } @@ -152,6 +210,68 @@ impl Writer { } } +/// Writes `buf` to non-blocking stream socket `fd`, bounding any single stall +/// with `chunk_timeout` so `Writer`'s mutex can never be held forever when the +/// guest agent wedges (#948). +fn write_all_timeout(fd: std::os::fd::RawFd, mut buf: &[u8], chunk_timeout: std::time::Duration) -> io::Result<()> { + let mut deadline = std::time::Instant::now() + chunk_timeout; + let mut polled_would_block = false; + while !buf.is_empty() { + let step = buf.len().min(64 * 1024); + #[cfg(target_os = "linux")] + // SAFETY: `fd` is a live stream socket owned by `Writer`; `buf` is valid. + let n = unsafe { libc::send(fd, buf.as_ptr().cast(), step, libc::MSG_NOSIGNAL) }; + #[cfg(not(target_os = "linux"))] + // SAFETY: `fd` is a live non-blocking socket owned by `Writer`; `buf` is valid. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), step) }; + if n > 0 { + buf = &buf[n as usize..]; + polled_would_block = false; + if !buf.is_empty() { + deadline = std::time::Instant::now() + chunk_timeout; + } + continue; + } + if n == 0 { + return Err(io::Error::new(io::ErrorKind::WriteZero, "failed to write whole buffer")); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::Interrupted => continue, + io::ErrorKind::WouldBlock => { + let now = std::time::Instant::now(); + if now >= deadline { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out writing to guest agent")); + } + if polled_would_block { + std::thread::sleep((deadline - now).min(std::time::Duration::from_millis(1))); + } + let timeout_ms = deadline + .saturating_duration_since(std::time::Instant::now()) + .as_micros() + .div_ceil(1000) + .min(i32::MAX as u128) as i32; + let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; + // SAFETY: one valid pollfd. + let ready = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; + if ready == 0 { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out writing to guest agent")); + } + if ready < 0 { + let pe = io::Error::last_os_error(); + if pe.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(pe); + } + polled_would_block = true; + } + _ => return Err(e), + } + } + Ok(()) +} + /// How much stdin each running process may still be sent before the guest /// reports some of it consumed. An entry exists from `run`/`exec` until /// `Exited`; `input` for a process without one is discarded. @@ -233,21 +353,17 @@ struct UsageSlot { arrived: Condvar, } -impl VmLink { - pub fn is_lost(&self) -> bool { - self.windows.is_lost() - } - - /// Observes disconnection without waiting for the reader's cleanup. - pub fn is_disconnected(&self) -> bool { - self.windows.lock().lost - } - - /// Starts the reader thread. `on_event` runs on that thread, so it must - /// not block for long: it holds up every reply behind it. - pub fn new(vm: Vm, conn: File, on_event: impl Fn(Event<'_>) + Send + 'static) -> io::Result { +impl Channel { + fn new( + conn: File, + write_timeout: std::time::Duration, + fast_timeout: std::time::Duration, + long_timeout: std::time::Duration, + on_event: impl Fn(Event<'_>) + Send + 'static, + ) -> io::Result { let pending: Arc>>> = Arc::new(Mutex::new(VecDeque::new())); let mut reader = conn.try_clone()?; + let abort_conn = Arc::new(conn.try_clone()?); let queue = pending.clone(); let windows = Arc::new(Windows::default()); let wins = windows.clone(); @@ -322,6 +438,120 @@ impl VmLink { on_event(Event::Lost); wins.finish_loss(); })?; + Ok(Channel { + writer: Mutex::new(Writer::new(conn, write_timeout)), + abort_conn, + windows, + usage, + pending, + fast_timeout, + long_timeout, + long_in_flight: std::sync::atomic::AtomicUsize::new(0), + }) + } + + /// Marks the link lost and shuts down the socket without locking `writer`, + /// waking `kiri-vm-reader` (and any stalled writer) so `pending` drains and + /// `Event::Lost` fires. + fn disconnect(&self) { + self.windows.lose(); + use std::os::fd::AsRawFd; + // SAFETY: `abort_conn` owns a live stream socket for the lifetime of `Channel`. + unsafe { + libc::shutdown(self.abort_conn.as_raw_fd(), libc::SHUT_RDWR); + } + } + + fn call_with( + &self, + timeout: std::time::Duration, + is_long: bool, + encode: impl FnOnce(&mut Vec), + body: Option<(File, u64)>, + ) -> io::Result { + let _long = is_long.then(|| { + self.long_in_flight.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + LongCallGuard(&self.long_in_flight) + }); + let (tx, rx) = mpsc::sync_channel(1); + { + let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); + if self.windows.lock().lost { + return Err(io::Error::other("the VM stopped")); + } + w.out.clear(); + encode(&mut w.out); + // Too large: refused before a reply slot is queued for it. + w.fits()?; + // Queue the slot before writing, so the reply can never arrive first. + { + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + if self.windows.lock().lost { + return Err(io::Error::other("the VM stopped")); + } + pending.push_back(tx); + } + w.write(&self.windows, body)?; + } + let began = std::time::Instant::now(); + let mut deadline = began + timeout; + loop { + let wait = deadline.saturating_duration_since(std::time::Instant::now()); + match rx.recv_timeout(wait) { + Ok(Reply::Error(e)) => return Err(io::Error::other(e)), + Ok(r) => return Ok(r), + Err(mpsc::RecvTimeoutError::Disconnected) => return Err(io::Error::other("the VM stopped")), + Err(mpsc::RecvTimeoutError::Timeout) => { + let extended = began + self.long_timeout; + if !is_long + && self.long_in_flight.load(std::sync::atomic::Ordering::Acquire) > 0 + && std::time::Instant::now() < extended + { + deadline = deadline.max(extended); + continue; + } + // `pending` is a positional FIFO: never leave the stream + // open after abandoning a reply slot (#948). + self.disconnect(); + return Err(io::Error::new(io::ErrorKind::TimedOut, "guest agent timed out")); + } + } + } + } + + fn call(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.call_with(self.fast_timeout, false, encode, body) + } + + fn call_long(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.call_with(self.long_timeout, true, encode, body) + } + + fn send(&self, encode: impl FnOnce(&mut Vec)) -> io::Result<()> { + let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); + if self.windows.lock().lost { + return Err(io::Error::other("the VM stopped")); + } + w.out.clear(); + encode(&mut w.out); + w.write(&self.windows, None) + } +} + +impl VmLink { + pub fn is_lost(&self) -> bool { + self.rpc.windows.is_lost() + } + + /// Observes disconnection without waiting for the reader's cleanup. + pub fn is_disconnected(&self) -> bool { + self.rpc.windows.lock().lost + } + + /// Starts the reader thread. `on_event` runs on that thread, so it must + /// not block for long: it holds up every reply behind it. + pub fn new(vm: Vm, conn: File, on_event: impl Fn(Event<'_>) + Send + 'static) -> io::Result { + let rpc = Channel::new(conn, WRITE_TIMEOUT, FAST_CALL_TIMEOUT, LONG_CALL_TIMEOUT, on_event)?; // On a Linux host the connection is a socket the agent process // shares with its children: one that hung before closing its copy // kept it open after the agent was gone, so the reader never saw @@ -329,9 +559,8 @@ impl VmLink { // was never restarted. Its exit ends the connection here instead. // (A VM's vsock ends with the VM.) #[cfg(target_os = "linux")] - let stop_conn = { - let stop_conn = Arc::new(conn.try_clone()?); - let weak = Arc::downgrade(&stop_conn); + { + let weak = Arc::downgrade(&rpc.abort_conn); vm.on_stop(Box::new(move || { if let Some(c) = weak.upgrade() { use std::os::fd::AsRawFd; @@ -339,68 +568,44 @@ impl VmLink { unsafe { libc::shutdown(c.as_raw_fd(), libc::SHUT_RDWR) }; } })); - stop_conn - }; + } Ok(VmLink { - #[cfg(target_os = "linux")] - _stop_conn: stop_conn, #[cfg(target_os = "linux")] agent_dir: vm.agent_dir().to_owned(), - writer: Mutex::new(Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024] }), - pending, + rpc, layers: Mutex::new(std::collections::HashSet::new()), - windows, - usage, connector: vm.connector(), _vm: Mutex::new(vm), }) } - /// Sends one request and waits for its reply. + /// Sends one fast request and waits up to `FAST_CALL_TIMEOUT` for its reply. /// A body is opened by the caller, before anything is sent: a blob that /// can't be read fails this call alone, not the connection (a request /// cut off after its header can't be taken back, and loses the VM). fn call(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { - let (tx, rx) = mpsc::sync_channel(1); - { - let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); - w.out.clear(); - encode(&mut w.out); - // Too large: refused before a reply slot is queued for it. - w.fits()?; - // Queue the slot before writing, so the reply can never arrive first. - { - let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - if self.windows.lock().lost { - return Err(io::Error::other("the VM stopped")); - } - pending.push_back(tx); - } - w.write(&self.windows, body)?; - } - match rx.recv() { - Ok(Reply::Error(e)) => Err(io::Error::other(e)), - Ok(r) => Ok(r), - Err(_) => Err(io::Error::other("the VM stopped")), - } + self.rpc.call(encode, body) + } + + /// Sends a potentially long-running request (`send_layer`, `run`, + /// `AwaitStart`, `trim_disk`) with `LONG_CALL_TIMEOUT`. + fn call_long(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.rpc.call_long(encode, body) } /// Sends a message that has no reply. fn send(&self, encode: impl FnOnce(&mut Vec)) -> io::Result<()> { - let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); - w.out.clear(); - encode(&mut w.out); - w.write(&self.windows, None) + self.rpc.send(encode) } /// What the guest's layers, containers and volumes take on disk: the /// `KIND NAME BYTES` lines of `Msg::Usage`, or None if they don't come /// within `wait` or the VM stops. pub fn usage(&self, wait: std::time::Duration) -> Option> { - let asked = self.usage.lines.lock().unwrap_or_else(|e| e.into_inner()).0; + let asked = self.rpc.usage.lines.lock().unwrap_or_else(|e| e.into_inner()).0; self.send(|o| Msg::UsageQuery.encode(o)).ok()?; - let g = self.usage.lines.lock().unwrap_or_else(|e| e.into_inner()); - let (g, _) = self.usage.arrived.wait_timeout_while(g, wait, |g| g.0 == asked).unwrap_or_else(|e| e.into_inner()); + let g = self.rpc.usage.lines.lock().unwrap_or_else(|e| e.into_inner()); + let (g, _) = self.rpc.usage.arrived.wait_timeout_while(g, wait, |g| g.0 == asked).unwrap_or_else(|e| e.into_inner()); if g.0 == asked { None } else { g.1.clone() } } @@ -424,7 +629,7 @@ impl VmLink { // fails here rather than half-way through the request. let file = File::open(blob)?; let size = file.metadata()?.len(); - self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))?; + self.call_long(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))?; self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned()); Ok(()) } @@ -448,13 +653,13 @@ impl VmLink { seccomp: &[u8], cancel: &std::sync::atomic::AtomicBool, ) -> io::Result { - self.windows.open(id); + self.rpc.windows.open(id); // Its process runs, but its root may not be in place yet (a new // volume is being filled): the agent answered at once rather than // stall every other container meanwhile. The start is reported only // once an exec can enter it (#311), or fails as a start. let r = self - .call(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None) + .call_long(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None) .and_then(started) .and_then(|(pid, starting)| { if starting { @@ -467,14 +672,14 @@ impl VmLink { told = true; self.cancel_start(id)?; } - self.call(|o| Msg::AwaitStart { id }.encode(o), None) + self.call_long(|o| Msg::AwaitStart { id }.encode(o), None) }; wait_started(ask, std::thread::sleep)?; } Ok(pid) }); if r.is_err() { - self.windows.close(id); + self.rpc.windows.close(id); } r } @@ -554,10 +759,10 @@ impl VmLink { #[allow(clippy::too_many_arguments)] pub fn exec(&self, container_id: &str, exec_id: &str, argv: &[String], env: &[String], cwd: &str, user: &str, flags: u32, caps: u64, opts: &[String]) -> io::Result { - self.windows.open(exec_id); + self.rpc.windows.open(exec_id); let r = self.call(|o| kiri_proto::encode_exec(o, container_id, exec_id, argv, env, cwd, user, flags, caps, opts), None).and_then(started).map(|(pid, _)| pid); if r.is_err() { - self.windows.close(exec_id); + self.rpc.windows.close(exec_id); } r } @@ -568,7 +773,7 @@ impl VmLink { pub fn input(&self, id: &str, data: &[u8]) -> io::Result<()> { // Frames are bounded, so large writes go in pieces. for piece in data.chunks(kiri_proto::MAX_OUTPUT_CHUNK) { - if !self.windows.take(id, piece.len())? { + if !self.rpc.windows.take(id, piece.len())? { return Ok(()); } self.send(|o| Msg::Input { id, data: piece }.encode(o))?; @@ -739,7 +944,7 @@ impl VmLink { } pub fn trim_disk(&self) -> io::Result<(u64, u64, u64)> { - match self.call(|o| Msg::TrimDisk.encode(o), None)? { + match self.call_long(|o| Msg::TrimDisk.encode(o), None)? { Reply::DiskTrimmed { trimmed, in_use, capacity } => Ok((trimmed, in_use, capacity)), other => Err(io::Error::other(format!("expected DiskTrimmed, got {other:?}"))), } @@ -841,13 +1046,46 @@ fn wait_started(mut ask: impl FnMut() -> io::Result, mut sleep: impl FnMu unreachable!("the backoff never ends") } +fn read_exact_blocking(fd: std::os::fd::RawFd, mut buf: &mut [u8]) -> io::Result<()> { + while !buf.is_empty() { + // SAFETY: `fd` is a valid descriptor and `buf` is owned mutable memory. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + buf = &mut buf[n as usize..]; + continue; + } + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::Interrupted => continue, + io::ErrorKind::WouldBlock => { + let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; + // SAFETY: one valid pollfd; wakes on incoming bytes or SHUT_RDWR/EOF. + let ready = unsafe { libc::poll(&mut pfd, 1, -1) }; + if ready < 0 { + let pe = io::Error::last_os_error(); + if pe.kind() != io::ErrorKind::Interrupted { + return Err(pe); + } + } + } + _ => return Err(e), + } + } + Ok(()) +} + fn read_frame(conn: &mut File, buf: &mut Vec) -> io::Result<()> { + use std::os::fd::AsRawFd; + let fd = conn.as_raw_fd(); buf.resize(4, 0); - conn.read_exact(&mut buf[..4])?; + read_exact_blocking(fd, &mut buf[..4])?; let len = kiri_proto::frame_len(buf[..4].try_into().expect("4 bytes")) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{e:?}")))?; buf.resize(len.max(HEADER), 0); - conn.read_exact(&mut buf[4..]) + read_exact_blocking(fd, &mut buf[4..]) } #[cfg(test)] @@ -877,7 +1115,8 @@ mod tests { fn a_failed_write_disconnects_before_the_reader_accounts_loss() { let (socket, peer) = UnixStream::pair().unwrap(); socket.shutdown(std::net::Shutdown::Write).unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![1], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![1]; let windows = Windows::default(); assert!(writer.write(&windows, None).is_err()); assert!(windows.lock().lost, "a writer failure must publish loss before a start can record an ordinary failure"); @@ -896,7 +1135,8 @@ mod tests { // Never blocks on a peer that does not read: a request that were // sent fills the socket and fails with WouldBlock instead. socket.set_nonblocking(true).unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![0; kiri_proto::MAX_FRAME + 1], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![0; kiri_proto::MAX_FRAME + 1]; let windows = Windows::default(); let e = writer.write(&windows, None).unwrap_err(); assert!(e.to_string().contains("too large"), "{e}"); @@ -914,9 +1154,121 @@ mod tests { #[test] fn a_request_at_the_agents_frame_limit_fits() { let (socket, _peer) = UnixStream::pair().unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![0; kiri_proto::MAX_FRAME], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![0; kiri_proto::MAX_FRAME]; assert!(writer.fits().is_ok()); writer.out.push(0); assert!(writer.fits().is_err()); } + + /// Regression test for #948(a): when the peer reads a request frame and + /// never replies, `call` times out instead of blocking forever, shuts down + /// the socket (preserving the positional `pending` FIFO invariant), marks + /// `windows.lost`, wakes `kiri-vm-reader` to emit `Event::Lost`, and wakes + /// any concurrent callers without deadlocking. + #[test] + fn wedged_peer_that_never_replies_times_out_and_closes_transport() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, Instant}; + + let (socket, peer) = UnixStream::pair().unwrap(); + let mut peer_file: File = std::os::fd::OwnedFd::from(peer).into(); + let lost_events = Arc::new(AtomicUsize::new(0)); + let lost_events_cb = lost_events.clone(); + let channel = Arc::new( + Channel::new( + std::os::fd::OwnedFd::from(socket).into(), + Duration::from_millis(200), + Duration::from_millis(60), + Duration::from_millis(250), + move |ev| { + if matches!(ev, Event::Lost) { + lost_events_cb.fetch_add(1, Ordering::SeqCst); + } + }, + ) + .unwrap(), + ); + + let reader_peer = std::thread::spawn(move || { + let mut frame = Vec::new(); + read_frame(&mut peer_file, &mut frame).unwrap(); + assert!(matches!(kiri_proto::decode(&frame), Ok(Msg::Ping(0)))); + let mut sink = [0u8; 64]; + while peer_file.read(&mut sink).unwrap() > 0 {} + }); + + let ch2 = channel.clone(); + let second = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(10)); + ch2.call_with(Duration::from_secs(5), false, |o| Msg::StatsRequest.encode(o), None) + }); + + let began = Instant::now(); + let err = channel.call(|o| Msg::Ping(0).encode(o), None).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2)); + assert!(channel.windows.lock().lost, "timeout must mark windows.lost immediately"); + + let second_err = second.join().unwrap().unwrap_err(); + assert!( + second_err.to_string().contains("the VM stopped"), + "second caller woken by pending drain without waiting 5s: {second_err}" + ); + assert!(began.elapsed() < Duration::from_secs(2)); + reader_peer.join().unwrap(); + assert!(channel.windows.is_lost(), "reader finished loss accounting without deadlock"); + assert_eq!(lost_events.load(Ordering::SeqCst), 1, "Event::Lost emitted exactly once"); + } + + /// Regression test for #948(b): when the socket send buffer is full and + /// the peer never reads, `Writer::write` fails within `write_timeout` + /// instead of holding `Channel::writer` mutex forever and piling up + /// hundreds of `kiri-api` threads. + #[test] + fn full_socket_buffer_times_out_write_and_releases_writer_mutex() { + use std::time::{Duration, Instant}; + + let (socket, _peer) = UnixStream::pair().unwrap(); + let channel = Arc::new( + Channel::new( + std::os::fd::OwnedFd::from(socket).into(), + Duration::from_millis(50), + Duration::from_millis(200), + Duration::from_millis(400), + |_| {}, + ) + .unwrap(), + ); + + { + use std::os::fd::AsRawFd; + let fd = channel.abort_conn.as_raw_fd(); + let chunk = [0xabu8; 4096]; + loop { + // SAFETY: valid buffer and non-blocking stream socket fd. + let n = unsafe { libc::write(fd, chunk.as_ptr().cast(), chunk.len()) }; + if n <= 0 { + break; + } + } + } + + let ch2 = channel.clone(); + let contender = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(10)); + ch2.send(|o| Msg::Ping(1).encode(o)) + }); + + let began = Instant::now(); + let big = vec![b'x'; 256 * 1024]; + let err = channel.send(|o| Msg::Input { id: "c1", data: &big }.encode(o)).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2), "writer mutex released promptly"); + assert!(channel.windows.lock().lost, "stalled write marks link lost"); + + let contender_err = contender.join().unwrap().unwrap_err(); + 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"); + } } diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 921592fb0..2cd199e95 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -368,3 +368,5 @@ vm-swap-as-set #326 the VM had no swap, so a container that outgrew the VM's mem 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 crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit 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 From e8aa1c17da561b47648cb47a0e9341dd7bd331e1 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:15:29 +0100 Subject: [PATCH 150/157] Volumes: persist measured volume sizes across VM sleep and restarts (#936) --- crates/kiri/src/daemon/engine.rs | 190 ++++++++++++++++++++++++++----- crates/kiri/src/daemon/ops.rs | 153 +++++++++++++++++-------- 2 files changed, 267 insertions(+), 76 deletions(-) diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 5a274ebf7..2e858e732 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -5,7 +5,7 @@ //! ps -a` survives a daemon restart. Every state change notifies one //! condition variable, which is what `wait` blocks on. -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::io; use std::path::PathBuf; use std::sync::mpsc::{self, Receiver, Sender}; @@ -1751,17 +1751,52 @@ pub struct Engine { image_labels: Mutex>, /// The running VM's uplink status for `/info` and `kiri diag report` (#435). uplink: Mutex, - /// Short-lived cache of guest-measured volume sizes (`GET /kiri/volumes/sizes`), - /// invalidated on volume create/remove and container remove while leaving - /// `GET /system/df` live. + /// Persisted and short-TTL cached volume byte sizes (`GET /kiri/volumes/sizes` + /// and `/volume-sizes.json`), tracking volumes dirtied since the + /// last guest disk measurement while leaving `GET /system/df` live. volume_sizes_cache: Mutex, } -#[derive(Default)] struct VolumeSizesCache { + path: PathBuf, generation: u64, measured_at: Option, sizes: HashMap, + dirty: HashSet, +} + +pub(super) struct VolumeSizesSnapshot { + pub generation: u64, + pub fresh_ttl: bool, + pub sizes: HashMap, + pub dirty: HashSet, +} + +impl VolumeSizesCache { + fn load(root: &std::path::Path, current: &[super::volumes::Volume]) -> VolumeSizesCache { + let path = root.join("volume-sizes.json"); + let mut sizes: HashMap = match std::fs::read(&path) { + Ok(b) => serde_json::from_slice(&b).unwrap_or_default(), + Err(_) => HashMap::new(), + }; + sizes.retain(|k, _| current.iter().any(|v| v.name == *k && v.options.is_empty())); + VolumeSizesCache { + path, + generation: 0, + measured_at: None, + sizes, + dirty: HashSet::new(), + } + } + + fn save(&self) { + if let Ok(json) = serde_json::to_vec(&self.sizes) { + let tmp = self.path.with_extension("json.tmp"); + if let Err(e) = std::fs::write(&tmp, json).and_then(|()| std::fs::rename(&tmp, &self.path)) { + crate::diag::error!("saving volume sizes failed", error = e); + } + } + } } /// k3s's pod and service ranges, which `kiri k8s` leaves at their defaults. @@ -1850,7 +1885,9 @@ impl Engine { let records = store.root().join("containers.json"); let ceiling = memory_ceiling(); let networks = Mutex::new(Networks::load(store.root())?); - let volumes = Mutex::new(super::volumes::Volumes::load(store.root())?); + let loaded_volumes = super::volumes::Volumes::load(store.root())?; + let volume_sizes_cache = Mutex::new(VolumeSizesCache::load(store.root(), loaded_volumes.all())); + let volumes = Mutex::new(loaded_volumes); let engine = Arc::new(Engine { volumes, link: Mutex::new(None), @@ -1897,7 +1934,7 @@ impl Engine { k8s_fwd: Mutex::new(HashMap::new()), image_labels: Mutex::new(HashMap::new()), uplink: Mutex::new(serde_json::Value::Null), - volume_sizes_cache: Mutex::default(), + volume_sizes_cache, }); let _ = engine.me.set(Arc::downgrade(&engine)); engine.start_syncer(); @@ -2463,6 +2500,11 @@ impl Engine { return false; } let Some(vm) = self.link.lock().unwrap_or_else(|e| e.into_inner()).clone() else { return false }; + if self.volume_list().iter().any(|v| v.options.is_empty()) + && let Some(lines) = vm.usage(Duration::from_secs(15)) + { + self.cache_volume_sizes(None, super::ops::parse_volume_usage(&lines)); + } self.sleeping.store(true, std::sync::atomic::Ordering::SeqCst); self.memory_used.store(0, std::sync::atomic::Ordering::Relaxed); self.mem_available_kib.store(0, std::sync::atomic::Ordering::Relaxed); @@ -2774,38 +2816,104 @@ impl Engine { self.awake() } - /// Cached guest volume disk usage if younger than `ttl`, plus the cache - /// generation so an in-flight measurement does not overwrite an invalidation. - pub(super) fn volume_sizes_cached(&self, ttl: Duration) -> (u64, Option>) { + /// Snapshot of persisted + cached volume disk usage, TTL freshness, dirty + /// set, and generation counter. + pub(super) fn volume_sizes_snapshot(&self, ttl: Duration) -> VolumeSizesSnapshot { let c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); - let hit = c.measured_at.is_some_and(|at| at.elapsed() < ttl).then(|| c.sizes.clone()); - (c.generation, hit) + VolumeSizesSnapshot { + generation: c.generation, + fresh_ttl: c.measured_at.is_some_and(|at| at.elapsed() < ttl), + sizes: c.sizes.clone(), + dirty: c.dirty.clone(), + } } - /// Stores freshly measured volume sizes. When `expected_gen` is `Some(g)`, - /// skips writing if the cache was invalidated since generation `g`. - pub(super) fn cache_volume_sizes(&self, expected_gen: Option, sizes: HashMap) { + /// Stores freshly measured volume sizes and persists `/volume-sizes.json`. + /// When `expected_gen` is `Some(g)`, skips writing if invalidated since `g`. + pub(super) fn cache_volume_sizes(&self, expected_gen: Option, du_volumes: HashMap) { + let volumes = self.volume_list(); let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); if expected_gen.is_some_and(|g| g != c.generation) { return; } + let mut next = HashMap::with_capacity(volumes.len()); + for v in &volumes { + if v.options.is_empty() { + next.insert(v.name.clone(), du_volumes.get(&v.name).copied().unwrap_or(0)); + } + } c.measured_at = Some(std::time::Instant::now()); - c.sizes = sizes; + c.sizes = next; + c.dirty.clear(); + c.save(); } - /// Drops cached volume sizes and advances the generation counter. - pub(super) fn invalidate_volume_sizes(&self) { + /// Initializes a newly created local volume's persisted size to `0` (unless + /// already measured) while bumping generation so an earlier in-flight scan + /// cannot clobber it. + fn record_new_volume(&self, v: &super::volumes::Volume) { let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); c.generation = c.generation.wrapping_add(1); c.measured_at = None; - c.sizes.clear(); + c.dirty.remove(&v.name); + if v.options.is_empty() { + c.sizes.entry(v.name.clone()).or_insert(0); + c.save(); + } + } + + /// Removes a deleted volume from the persisted size map and bumps generation. + fn forget_volume_size(&self, name: &str) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + c.dirty.remove(name); + if c.sizes.remove(name).is_some() { + c.save(); + } + } + + /// Marks mounted local volumes dirty when a container using them starts, + /// exits, is removed, or receives `docker cp` writes. + pub(super) fn mark_volumes_dirty<'a>(&self, names: impl IntoIterator) { + let names: Vec = names.into_iter().cloned().collect(); + if names.is_empty() { + return; + } + let local_set: HashSet = self + .volume_list() + .into_iter() + .filter(|v| v.options.is_empty()) + .map(|v| v.name) + .collect(); + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + let mut any = false; + for name in names { + if local_set.contains(&name) { + c.dirty.insert(name); + any = true; + } + } + if any { + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + } } #[cfg(test)] - pub(super) fn set_volume_sizes_cache_at(&self, at: std::time::Instant, sizes: HashMap) { + pub(super) fn set_volume_sizes_cache_at(&self, at: std::time::Instant, du_volumes: HashMap) { + let volumes = self.volume_list(); let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + let mut next = HashMap::with_capacity(volumes.len()); + for v in &volumes { + if v.options.is_empty() { + next.insert(v.name.clone(), du_volumes.get(&v.name).copied().unwrap_or(0)); + } + } c.measured_at = Some(at); - c.sizes = sizes; + c.sizes = next; + c.dirty.clear(); + c.save(); } /// Queries `(in_use, capacity)` of the guest data disk while the VM is @@ -3092,7 +3200,7 @@ impl Engine { // rules wiped by a delayed `Forwards::drop` -> `Unpublish` // (#649). Loop in case a concurrent `start`/`connect`/ // `set_ports` installed forwards while the lock was released. - let (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers) = loop { + let (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers, touched_volumes) = loop { let mut st = self.lock(); if let Some(e) = st.execs.get_mut(id) { e.running = false; @@ -3123,8 +3231,10 @@ impl Engine { if let Some(h) = st.health.get_mut(id) { close_monitor(h); } + let mut touched_volumes = Vec::new(); let remove = match st.containers.get_mut(id) { Some(c) => { + touched_volumes = c.spec.volumes.iter().chain(&c.spec.anon_volumes).cloned().collect(); c.status = Status::Exited; c.exit_code = code; c.pid = 0; @@ -3180,7 +3290,7 @@ impl Engine { note_removed(&mut st, id, code); } drop(st); - break (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers); + break (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers, touched_volumes); }; // Relieve the balloon and log the exit outside `self.state` so // neither `memory_target`, `link` nor `stopping_ops` is ever @@ -3207,6 +3317,7 @@ impl Engine { // reader), since that asks the VM, and vm() waits for this // reader when the VM was just lost. let forgotten: Vec = self.unshared(anon).into_iter().filter(|v| self.forget_volume(v)).collect(); + self.mark_volumes_dirty(&touched_volumes); if !forgotten.is_empty() && let Some(me) = self.me.get().and_then(Weak::upgrade) { let _ = std::thread::Builder::new().name("kiri-volume-rm".into()).spawn(move || { if let Ok(vm) = me.vm() { @@ -3998,6 +4109,7 @@ impl Engine { (out.0, out.1, out.2, out.3, out.4, (out.5.0, out.5.1, earlier, halted)) }; self.clear_stopping_op(&id); + self.mark_volumes_dirty(spec.volumes.iter().chain(&spec.anon_volumes)); let (gate, exits, earlier, halted_at_claim) = gate; // A bind source that is a link is followed again at every start, as // Docker does: re-pointing it between runs (a `current` release @@ -4856,6 +4968,9 @@ impl Engine { let mut out = Vec::new(); kiri_proto::encode_copy(&mut out, op, &id, path, flags, &layers, &mounts); std::io::Write::write_all(&mut std::fs::File::from(stream.fd.try_clone()?), &out)?; + if op == kiri_proto::copy_op::IN { + self.mark_volumes_dirty(spec.volumes.iter().chain(&spec.anon_volumes)); + } Ok(stream) } @@ -5854,7 +5969,9 @@ impl Engine { self.delete_volume_data(&v); } } - self.invalidate_volume_sizes(); + if let Some(c) = &removed { + self.mark_volumes_dirty(c.spec.volumes.iter().chain(&c.spec.anon_volumes)); + } Ok(()) } @@ -5868,7 +5985,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure(name, labels, anonymous).map_err(Error::BadRequest)?; if new { - self.invalidate_volume_sizes(); + self.record_new_volume(&v); self.emit_volume("create", name); } Ok(v) @@ -5880,7 +5997,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure_with(name, labels, false, options).map_err(Error::BadRequest)?; if new { - self.invalidate_volume_sizes(); + self.record_new_volume(&v); self.emit_volume("create", name); } Ok(v) @@ -5945,7 +6062,7 @@ impl Engine { fn forget_volume(&self, name: &str) -> bool { let forgot = self.lock_volumes().forget(name); if forgot { - self.invalidate_volume_sizes(); + self.forget_volume_size(name); self.emit_volume("destroy", name); } forgot @@ -6047,6 +6164,25 @@ impl Engine { flags |= exec_security.0; let console = config.console_size; self.wait_for_start(&container_id); + let conflict = { + let st = self.lock(); + match st.containers.get(&container_id) { + None => Some(format!("container {} is not running", &container_id[..12])), + Some(c) if c.status != Status::Running => Some(format!("container {} is not running", &container_id[..12])), + Some(c) if c.paused && !is_builder(c) => Some(format!("Container {} is paused, unpause the container before exec", &container_id[..12])), + _ => None, + } + }; + if let Some(msg) = conflict { + let mut st = self.lock(); + if let Some(x) = st.execs.get_mut(exec_id) { + x.running = false; + x.attached.clear(); + } + drop(st); + self.changed.notify_all(); + return Err(Error::Conflict(msg)); + } let started = self.vm()?.exec(&container_id, exec_id, &config.argv, &env, &config.cwd, &config.user, flags, exec_security.1, &exec_security.2); if let Ok(pid) = started { if let Some(x) = self.lock().execs.get_mut(exec_id).filter(|x| x.exit_code.is_none()) { diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index e7bf3a122..c5067350c 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -556,29 +556,50 @@ fn system_df(engine: &Engine) -> Result { Ok(json!({"LayersSize": layers_size, "Images": image_rows, "Containers": containers, "Volumes": volumes, "BuildCache": super::builder::cache(engine)})) } -/// How long `GET /kiri/volumes/sizes` reuses guest-measured volume sizes so -/// tab switches do not re-walk the guest disk (`GET /system/df` stays live). +/// How long `GET /kiri/volumes/sizes` reuses guest-measured volume sizes while +/// the VM is awake so tab switches do not re-walk the guest disk (`GET /system/df` +/// stays live). const VOLUME_SIZES_TTL: Duration = Duration::from_secs(30); -fn volume_sizes_map(volumes: &[super::volumes::Volume], du: &HashMap) -> serde_json::Map { +pub(super) fn parse_volume_usage(lines: &[String]) -> HashMap { + DiskUsage::parse(lines).volumes +} + +fn volume_sizes_map( + volumes: &[super::volumes::Volume], + du: &HashMap, + dirty: &HashSet, + complete_scan: bool, +) -> serde_json::Map { let mut out = serde_json::Map::with_capacity(volumes.len()); for v in volumes { - let size = match du.get(&v.name) { - Some(&b) => i64::try_from(b).unwrap_or(i64::MAX), + if !v.options.is_empty() { + // Backed by driver options (NFS/bind/tmpfs): not on the guest data disk. + out.insert(v.name.clone(), json!(-1)); + continue; + } + if !complete_scan && dirty.contains(&v.name) { + continue; + } + match du.get(&v.name) { + Some(&b) => { + out.insert(v.name.clone(), json!(i64::try_from(b).unwrap_or(i64::MAX))); + } // A plain local volume never mounted yet has no directory in the - // guest and takes 0 bytes; one backed by driver options (NFS/bind/ - // tmpfs) is not measured on the guest data disk. - None if v.options.is_empty() => 0, - None => -1, - }; - out.insert(v.name.clone(), json!(size)); + // guest and takes 0 bytes. + None if complete_scan => { + out.insert(v.name.clone(), json!(0)); + } + None => {} + } } out } /// Each volume's size in bytes for the Volumes view (`GET /kiri/volumes/sizes`). -/// Uses a short cache invalidated on volume/container changes and never wakes -/// a sleeping or stopped VM. +/// Uses persisted `/volume-sizes.json` across VM sleep and daemon +/// restarts without waking the VM unless an active (`!is_stopped()`) engine has +/// dirty or unmeasured local volumes. fn volume_sizes(engine: &Engine) -> Result { volume_sizes_with_ttl(engine, VOLUME_SIZES_TTL) } @@ -588,20 +609,43 @@ fn volume_sizes_with_ttl(engine: &Engine, ttl: Duration) -> Result if volumes.is_empty() { return Ok(json!({"sizes": {}})); } - let (generation, cached) = engine.volume_sizes_cached(ttl); - if let Some(du) = cached { - return Ok(json!({"sizes": volume_sizes_map(&volumes, &du)})); + let snap = engine.volume_sizes_snapshot(ttl); + let any_missing_or_dirty = volumes + .iter() + .any(|v| v.options.is_empty() && (snap.dirty.contains(&v.name) || !snap.sizes.contains_key(&v.name))); + + if let Some(vm) = engine.awake_link() { + if snap.fresh_ttl && !any_missing_or_dirty { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + let Some(measured) = vm.usage(Duration::from_secs(120)) else { + return Ok(json!({"sizes": {}})); + }; + let du = DiskUsage::parse(&measured); + engine.cache_volume_sizes(Some(snap.generation), du.volumes.clone()); + let current = engine.volume_list(); + return Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes, &HashSet::new(), true)})); } - let Some(vm) = engine.awake_link() else { - return Ok(json!({"sizes": {}})); - }; - let Some(measured) = vm.usage(Duration::from_secs(120)) else { - return Ok(json!({"sizes": {}})); - }; - let du = DiskUsage::parse(&measured); - engine.cache_volume_sizes(Some(generation), du.volumes.clone()); - let current = engine.volume_list(); - Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes)})) + + if !any_missing_or_dirty { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + if !engine.is_stopped() + && let Some(measured) = engine.vm().ok().and_then(|vm| vm.usage(Duration::from_secs(120))) + { + let du = DiskUsage::parse(&measured); + engine.cache_volume_sizes(Some(snap.generation), du.volumes.clone()); + let current = engine.volume_list(); + return Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes, &HashSet::new(), true)})); + } + + let has_any_clean_local = volumes + .iter() + .any(|v| v.options.is_empty() && !snap.dirty.contains(&v.name) && snap.sizes.contains_key(&v.name)); + if has_any_clean_local { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + Ok(json!({"sizes": {}})) } /// `docker history`: the config's history, newest first, with each @@ -950,7 +994,7 @@ mod disk_usage_tests { } #[test] - fn volume_sizes_never_wakes_asleep_vm_and_honors_cache_and_invalidation() { + fn volume_sizes_persists_across_sleep_and_restart_without_waking_vm() { use serde_json::json; use std::collections::{BTreeMap, HashMap}; use std::time::{Duration, Instant}; @@ -967,42 +1011,53 @@ mod disk_usage_tests { nfs_opts.insert("device".into(), ":/export".into()); engine.volume_ensure_with("nfs_vol", json!({}), nfs_opts).unwrap(); - // With no awake VM and an empty cache, returns {} without attempting to boot a VM. - let unmeasured = super::volume_sizes(&engine).unwrap(); - assert_eq!(unmeasured, json!({"sizes": {}})); + let initial = super::volume_sizes(&engine).unwrap(); + assert_eq!(initial, json!({"sizes": {"pg_data": 0, "empty_vol": 0, "nfs_vol": -1}})); assert!(!engine.is_awake()); - // Populate cache as if an awake measurement just completed. let mut measured = HashMap::new(); measured.insert("pg_data".into(), 807_700_000u64); - let (gen_before, _) = engine.volume_sizes_cached(Duration::from_secs(30)); + let gen_before = engine.volume_sizes_snapshot(Duration::from_secs(30)).generation; engine.cache_volume_sizes(Some(gen_before), measured.clone()); + assert!(root.join("volume-sizes.json").is_file(), "volume-sizes.json persisted"); - let hit = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); - assert_eq!(hit, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); - - // Stale cache entry (> TTL) misses and still does not wake the VM. engine.set_volume_sizes_cache_at(Instant::now() - Duration::from_secs(31), measured.clone()); - let expired = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); - assert_eq!(expired, json!({"sizes": {}})); + let after_ttl = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); + assert_eq!(after_ttl, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); - // Creating a new volume invalidates the cache and bumps generation so - // an in-flight measurement from before creation cannot repopulate it. engine.cache_volume_sizes(None, measured.clone()); - let (old_gen, cached) = engine.volume_sizes_cached(Duration::from_secs(30)); - assert!(cached.is_some()); + let old_gen = engine.volume_sizes_snapshot(Duration::from_secs(30)).generation; engine.volume_ensure("new_vol", json!({}), false).unwrap(); - assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none()); - engine.cache_volume_sizes(Some(old_gen), measured.clone()); - assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none(), "stale generation write ignored"); + assert!(!engine.volume_sizes_snapshot(Duration::from_secs(30)).fresh_ttl); + let mut stale = HashMap::new(); + stale.insert("pg_data".into(), 1u64); + engine.cache_volume_sizes(Some(old_gen), stale); + assert_eq!( + super::volume_sizes(&engine).unwrap(), + json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "new_vol": 0, "nfs_vol": -1}}), + "stale generation write ignored and new_vol initialized to 0" + ); - // Removing a volume also invalidates the cache. - engine.cache_volume_sizes(None, measured); - assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_some()); engine.volume_remove("new_vol", false).unwrap(); - assert!(engine.volume_sizes_cached(Duration::from_secs(30)).1.is_none()); + let saved_raw: HashMap = + serde_json::from_slice(&std::fs::read(root.join("volume-sizes.json")).unwrap()).unwrap(); + assert!(!saved_raw.contains_key("new_vol")); + assert_eq!(saved_raw.get("pg_data"), Some(&807_700_000)); + engine.mark_volumes_dirty([&"pg_data".to_owned()]); + assert_eq!(super::volume_sizes(&engine).unwrap(), json!({"sizes": {"empty_vol": 0, "nfs_vol": -1}})); + + engine.cache_volume_sizes(None, measured); drop(engine); + + let asleep_engine = super::super::engine::Engine::boot(kiri_image::store::Store::open(&root).unwrap()).unwrap(); + assert!(!asleep_engine.is_stopped(), "engine is asleep, not stopped"); + assert!(!asleep_engine.is_awake(), "VM starts asleep"); + let asleep_sizes = super::volume_sizes(&asleep_engine).unwrap(); + assert_eq!(asleep_sizes, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); + assert!(!asleep_engine.is_awake(), "persisted volume sizes returned without waking asleep VM"); + + drop(asleep_engine); let _ = std::fs::remove_dir_all(root); } } From a14d63948ddfb5639f4f0530a24e24cf25c28fd4 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:15:29 +0100 Subject: [PATCH 151/157] macOS: spawn daemon directly when LaunchAgent kickstart leaves engine down (#602) --- crates/kiri/src/ui/mod.rs | 2 +- crates/kiri/src/update.rs | 104 +++++++++++++++++++++++++++++++++++--- docs/fix-registry.md | 20 +++++++- 3 files changed, 116 insertions(+), 10 deletions(-) diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 02e8cfc19..18e3dd92a 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -1546,7 +1546,7 @@ fn ensure_daemon() -> io::Result<()> { if client::alive() { if stop_on_quit() && engine_stopped() { clear_stopped_marker(); - let _ = client::request("POST", "/kiri/wake", None); + expect_ok(client::request("POST", "/kiri/wake", None))?; } return Ok(()); } diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 3d3a679c5..723aab89d 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -265,24 +265,49 @@ pub fn restart_engine(expect: &str) -> io::Result { } /// Starts the engine if it is not running: through the LaunchAgent when it -/// starts this copy of Kiri, so launchd owns the one engine there is, else -/// as a child of its own session. Returns once it answers. +/// starts this copy of Kiri, so launchd owns the one engine there is, falling +/// back to spawning the daemon directly when `launchctl kickstart` exits 0 +/// without bringing the engine up (#602). Returns once it answers. #[cfg(target_os = "macos")] pub fn start_engine() -> io::Result<()> { - if crate::client::alive() { + start_engine_with( + crate::client::alive, + crate::setup::start_agent, + spawn_daemon, + std::thread::sleep, + || log_path().display().to_string(), + ) +} + +#[cfg(any(target_os = "macos", test))] +fn start_engine_with( + mut alive: impl FnMut() -> bool, + start_agent: impl FnOnce() -> io::Result, + spawn_daemon: impl FnOnce() -> io::Result<()>, + mut sleep: impl FnMut(std::time::Duration), + log_display: impl FnOnce() -> String, +) -> io::Result<()> { + if alive() { return Ok(()); } crate::diag::info!("starting the engine"); - if !crate::setup::start_agent().unwrap_or(false) { - spawn_daemon()?; + if start_agent().unwrap_or(false) { + for _ in 0..50 { + if alive() { + return Ok(()); + } + sleep(std::time::Duration::from_millis(50)); + } + crate::diag::warn!("LaunchAgent kickstart did not bring up engine; starting daemon directly"); } + spawn_daemon()?; for _ in 0..200 { - if crate::client::alive() { + if alive() { return Ok(()); } - std::thread::sleep(std::time::Duration::from_millis(50)); + sleep(std::time::Duration::from_millis(50)); } - Err(io::Error::other(format!("kiri daemon did not start; see {}", log_path().display()))) + Err(io::Error::other(format!("kiri daemon did not start; see {}", log_display()))) } #[cfg(target_os = "macos")] @@ -681,4 +706,67 @@ mod tests { assert!(!crate::docker::is_container_update(&a(&["-h"]))); assert!(!crate::docker::is_container_update(&a(&[]))); } + + /// Regression test for #602: when `launchctl kickstart` exits 0 without + /// actually starting the daemon, `start_engine` waits 2.5s (`50 * 50ms`), + /// then spawns the daemon directly and polls for up to 10s (`200 * 50ms`). + #[test] + fn start_engine_falls_back_to_direct_spawn_when_kickstart_leaves_daemon_down() { + use std::cell::Cell; + use std::time::Duration; + + let polls = Cell::new(0usize); + let spawned = Cell::new(false); + let sleeps = Cell::new(0usize); + super::start_engine_with( + || { + let n = polls.get() + 1; + polls.set(n); + n >= 4 + }, + || Ok(true), + || { + spawned.set(true); + Ok(()) + }, + |_| sleeps.set(sleeps.get() + 1), + || "/tmp/daemon.log".into(), + ) + .unwrap(); + assert!(!spawned.get(), "healthy LaunchAgent must not spawn a second daemon"); + assert_eq!(sleeps.get(), 2); + + let polls = Cell::new(0usize); + let spawned = Cell::new(false); + let total_ms = Cell::new(0u64); + super::start_engine_with( + || { + let n = polls.get() + 1; + polls.set(n); + spawned.get() && n >= 55 + }, + || Ok(true), + || { + assert_eq!(total_ms.get(), 2500, "fallback runs after 50 * 50ms"); + spawned.set(true); + Ok(()) + }, + |d: Duration| total_ms.set(total_ms.get() + d.as_millis() as u64), + || "/tmp/daemon.log".into(), + ) + .unwrap(); + assert!(spawned.get()); + + let total_ms = Cell::new(0u64); + let err = super::start_engine_with( + || false, + || Ok(true), + || Ok(()), + |d: Duration| total_ms.set(total_ms.get() + d.as_millis() as u64), + || "/custom/daemon.log".into(), + ) + .unwrap_err(); + assert_eq!(total_ms.get(), 12_500); + assert!(err.to_string().contains("/custom/daemon.log"), "{err}"); + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 9f5413541..2d72f27cb 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,24 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ## Fixes +### #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 +- Caused by: - +- Check: `crates/kiri/src/update.rs` + +### #936 follow-up Volumes: persist measured volume byte sizes across VM sleep and restarts (unreleased) +- Fixes: #936 Volumes view shows `—` whenever the Linux VM is asleep or more than 30s after idle sleep +- Caused: none known +- Caused by: #936 +- Check: `crates/kiri/src/daemon/ops.rs`, `tests/ui/volumes-size.js` + +### #948 Engine & Guest: bound `VmLink` write/RPC waits and `kiri-init` TTY `recv_fd`, and refuse `exec_start` on paused containers (unreleased) +- Fixes: #948 macOS/guest `VmLink` deadlock where hundreds of `kiri-api` threads block forever on a wedged guest or frozen TTY child +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/daemon/vmlink.rs`, `crates/kiri-init/src/linux/container.rs`, `crates/kiri/src/daemon/engine.rs` + ### #981 Engine: docker container prune and system prune keep stopped machines (unreleased) - Fixes: #975 A stopped machine is deleted by docker container prune / docker system prune, with everything in it - Caused: none known @@ -21,7 +39,7 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug ### #936 Volumes view: show each volume's disk size loaded asynchronously with daemon caching (unreleased) - Fixes: #936 Volumes view: show each volume's size, loaded asynchronously -- Caused: none known +- Caused: Volume sizes were cached only in memory with a 30s TTL and skipped asleep VMs, causing the Volumes tab to show `—` whenever the VM was asleep (fixed in #936 follow-up) - Caused by: - - Check: `tests/ui/volumes-size.js`, `crates/kiri/src/daemon/ops.rs` From ba09bde5a7800ffdbdab6ec8e5f814f66e36c4a0 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:16:33 +0100 Subject: [PATCH 152/157] Fix CLI --help/-h and --version flags, Windows setup/import/build-with, and Docker config healing (#982, #984) --- crates/kiri-win/src/client.rs | 15 ++ crates/kiri-win/src/engine.rs | 65 +++++- crates/kiri-win/src/main.rs | 7 +- crates/kiri-win/src/setup.rs | 1 + crates/kiri/src/bench.rs | 6 + crates/kiri/src/boot.rs | 8 + crates/kiri/src/bridge.rs | 27 ++- crates/kiri/src/builds.rs | 40 +++- crates/kiri/src/buildwith.rs | 22 +- crates/kiri/src/client.rs | 259 ++++++++++++++++++-- crates/kiri/src/diag/report.rs | 12 + crates/kiri/src/docker.rs | 1 + crates/kiri/src/dockerctx.rs | 303 ++++++++++++++++++++++++ crates/kiri/src/domains_cli.rs | 13 ++ crates/kiri/src/hostaccess.rs | 13 +- crates/kiri/src/images.rs | 29 ++- crates/kiri/src/import.rs | 149 +++++++++--- crates/kiri/src/k8s.rs | 4 + crates/kiri/src/machine.rs | 43 +++- crates/kiri/src/main.rs | 403 +++++++++++++++++++++++++++----- crates/kiri/src/registry_cli.rs | 10 +- crates/kiri/src/run.rs | 54 ++++- crates/kiri/src/setup.rs | 16 ++ crates/kiri/src/setup_win.rs | 310 ++++++++++++++++++++++++ crates/kiri/src/share.rs | 8 +- crates/kiri/src/usb.rs | 6 + crates/kiri/src/wsl.rs | 101 ++++++++ docs/fix-registry.md | 6 + tests/regressions.tsv | 2 + 29 files changed, 1789 insertions(+), 144 deletions(-) create mode 100644 crates/kiri/src/setup_win.rs diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index 2ecc259ae..7c7599a58 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -426,6 +426,21 @@ pub fn alive() -> bool { alive_within(PING_WAIT) } +/// Probes the engine pipe for CLI-shared callers (`import.rs`), surfacing the +/// pipe's refusal message when Kiri is stopped or setup is unfinished. +#[allow(dead_code)] +pub fn check_alive() -> io::Result<()> { + match request_within("GET", "/_ping", None, true, Some(PING_WAIT)) { + Ok(r) if r.ok() => Ok(()), + Ok(r) => { + let err = r.error(); + let msg = if err.trim().is_empty() { "Kiri isn't running. Open Kiri, or start it with `kiri start`" } else { err.trim() }; + Err(io::Error::new(io::ErrorKind::NotConnected, msg.to_owned())) + } + Err(_) => Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri isn't running. Open Kiri, or start it with `kiri start`")), + } +} + /// `alive`, for the event watcher: false after QUICK without an answer. pub fn alive_quick() -> bool { alive_within(QUICK) diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 11b171510..deed95313 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -962,6 +962,40 @@ fn emit_docker_state_if_changed() { } } +/// Ensures Kiri's `cliPluginsExtraDirs` and `kiri` context in +/// `%USERPROFILE%\.docker`, repairing `config.json` if another engine's +/// uninstaller (such as Docker Desktop's) removed it (#984). +pub fn heal_docker_config(pipe: &str) { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = npipe_host(pipe); + match crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ) { + Ok(r) if r.context_written || r.plugins_added || r.current_context_set => { + crate::serve::log(&format!( + "docker config self-healed (context={}, plugins={}, current={})", + r.context_written, r.plugins_added, r.current_context_set + )); + } + Ok(_) => {} + Err(e) => crate::serve::log(&format!("docker config: could not self-heal ({e})")), + } +} + /// Ensures the `kiri` context exists and is plain `docker`'s current context, /// keeping logins, credential helpers and plugin folders untouched (#369). pub fn use_kiri_context() -> io::Result<()> { @@ -1169,7 +1203,27 @@ fn set_pref(name: &str, value: Value) { /// A page link: only Kiri's own addresses, as on the Mac. fn allowed_url(url: &str) -> bool { - if url == "https://kiri.canestack.com" || url == "https://learn.microsoft.com/windows/wsl/about" || url == "https://github.com/libracoder/kiri/issues/new" || url == "https://github.com/libracoder/kiri" || url == "https://login.docker.com/activate" || url == "https://github.com/login/device" { + if matches!( + url, + "https://kiri.canestack.com" + | "https://runkiri.com" + | "https://runkiri.com/releases/" + | "https://runkiri.com/share/notice" + | "https://canestack.com" + | "https://learn.microsoft.com/windows/wsl/about" + | "https://github.com/libracoder/kiri/issues/new" + | "https://github.com/libracoder/kiri" + | "https://github.com/anchore/grype" + | "https://login.docker.com/activate" + | "https://github.com/login/device" + ) { + return true; + } + // A build warning's rule page (docs.docker.com/go/dockerfile/rule/…). + if url + .strip_prefix("https://docs.docker.com/go/") + .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"-/".contains(&b))) + { return true; } let Some(rest) = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://")) else { return false }; @@ -1239,8 +1293,17 @@ mod tests { assert!(allowed_url("http://localhost:8080/app")); assert!(allowed_url("https://web.kiri.localhost/")); assert!(allowed_url("http://api.kiri.local")); + assert!(allowed_url("https://runkiri.com")); + assert!(allowed_url("https://runkiri.com/releases/")); + assert!(allowed_url("https://runkiri.com/share/notice")); + assert!(allowed_url("https://canestack.com")); + assert!(allowed_url("https://kiri.canestack.com")); assert!(allowed_url("https://github.com/libracoder/kiri")); + assert!(allowed_url("https://github.com/libracoder/kiri/issues/new")); + assert!(allowed_url("https://github.com/anchore/grype")); + assert!(allowed_url("https://docs.docker.com/go/dockerfile/rule/from-as-casing/")); assert!(!allowed_url("http://evil.example/")); + assert!(!allowed_url("https://runkiri.com.evil.com")); // Bypass attempts the audit found. assert!(!allowed_url("http://localhost:1@evil.example/")); assert!(!allowed_url("http://evil.example\\x.kiri.localhost")); diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index 8beace596..9f5737ba3 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -44,7 +44,8 @@ mod relay; #[cfg(windows)] #[path = "../../kiri/src/hostrelay.rs"] mod hostrelay; -#[cfg(windows)] +#[cfg(any(windows, test))] +#[cfg_attr(not(windows), allow(dead_code))] #[path = "../../kiri/src/dockerctx.rs"] mod dockerctx; #[cfg(windows)] @@ -73,6 +74,7 @@ mod builds; // and Linux's own crates/kiri/src/buildwith.rs. #[cfg(windows)] #[path = "../../kiri/src/buildwith.rs"] +#[allow(dead_code)] mod buildwith; // Kiri's program moved or deleted from where it started: the Mac's and // Linux's own crates/kiri/src/appwatch.rs. @@ -217,6 +219,9 @@ fn main() -> std::process::ExitCode { return std::process::ExitCode::FAILURE; } client::set_pipe(&cfg.pipe); + if !setup { + engine::heal_docker_config(&cfg.pipe); + } ports::start(); if let Err(e) = dns::start() { serve::log(&format!("dns on 127.0.0.1:53: {e}")); diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index 717710ef2..84bed560a 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -996,6 +996,7 @@ fn tools() -> io::Result<()> { /// Ready → Open Kiri: remember setup is done, start at sign-in if asked. fn finish() { let autostart = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_none_or(|s| s.autostart); + crate::engine::heal_docker_config(&crate::client::pipe()); // Apply "Make Kiri the default for docker" on finish too (e.g. if checked after tools finished). if STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default) && let Err(e) = crate::engine::use_kiri_context() diff --git a/crates/kiri/src/bench.rs b/crates/kiri/src/bench.rs index da98e208c..9985ff568 100644 --- a/crates/kiri/src/bench.rs +++ b/crates/kiri/src/bench.rs @@ -39,6 +39,12 @@ const ENGINES: [(&str, &str, &str); 3] = [ ]; pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut o = Opts { runs: 50, image: "alpine:latest".into(), bridge: false, only: None }; let mut it = args.iter(); while let Some(a) = it.next() { diff --git a/crates/kiri/src/boot.rs b/crates/kiri/src/boot.rs index 81b811df2..eca6a2f91 100644 --- a/crates/kiri/src/boot.rs +++ b/crates/kiri/src/boot.rs @@ -5,7 +5,15 @@ use std::time::Duration; use crate::guest::{BootOptions, Guest}; +const USAGE: &str = "usage: kiri boot [--console] [--pings N]"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut opts = BootOptions::default(); let mut pings = 1000usize; let mut it = args.iter(); diff --git a/crates/kiri/src/bridge.rs b/crates/kiri/src/bridge.rs index a9dbd8682..3833a9e56 100644 --- a/crates/kiri/src/bridge.rs +++ b/crates/kiri/src/bridge.rs @@ -103,9 +103,32 @@ const LOG: &str = "/var/log/kiri.log"; type Out = Arc>; +const USAGE: &str = "usage: kiri bridge [--socket PATH]"; + pub fn run(args: &[String]) -> io::Result<()> { - let socket = match args.iter().position(|a| a == "--socket").and_then(|i| args.get(i + 1)) { - Some(s) => PathBuf::from(s), + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut socket_opt = None; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--socket" => { + socket_opt = Some( + it.next() + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?, + ); + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let socket = match socket_opt { + Some(s) => s, None => crate::daemon::socket_path()?, }; let out: Out = Arc::new(Mutex::new(BufWriter::with_capacity(64 * 1024, io::stdout()))); diff --git a/crates/kiri/src/builds.rs b/crates/kiri/src/builds.rs index e8a7c070f..7f94573ac 100644 --- a/crates/kiri/src/builds.rs +++ b/crates/kiri/src/builds.rs @@ -462,25 +462,32 @@ pub fn builder() -> io::Result { std::thread::sleep(std::time::Duration::from_millis(200)); } let quiet = || std::process::Stdio::null(); - if !Command::new(&docker).args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { + let new_docker = || { + #[allow(unused_mut)] + let mut cmd = Command::new(&docker); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if !new_docker().args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { println!("docker build: no buildx plugin here, so docker builds with Kiri's classic builder API (the same BuildKit, run by the daemon)"); return Ok(false); } - let inspect = Command::new(&docker).args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; + let inspect = new_docker().args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; let mut exists = inspect.status.success(); // Without default-load a docker-container builder keeps what it builds // to itself: `docker build -t x .` builds and `docker run x` finds // nothing. One made without it is made again; --keep-state keeps its // cache volume, which the daemon's builder container reuses. if exists && !String::from_utf8_lossy(&inspect.stdout).contains("default-load") { - exists = !Command::new(&docker).args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); + exists = !new_docker().args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); } if !exists { // buildx create takes the Kiri context's name; without that context // (Linux makes it only in the optional "docker uses Kiri" step) buildx // reads the name as a host and fails on tcp://kiri:2375. ensure_context(&docker)?; - let made = Command::new(&docker) + let made = new_docker() .args(["buildx", "create", "--name", BUILDER.get(), "--driver", "docker-container", "--driver-opt", "default-load=true", CONTEXT.get()]) .stdout(quiet()) .output()?; @@ -496,13 +503,24 @@ pub fn builder() -> io::Result { Ok(true) } -/// The docker context named CONTEXT, pointing at Kiri's socket, made when -/// missing. It is only made, never made current: which engine plain docker -/// uses stays the user's choice. -/// On Windows, setup (kiri.ps1) makes the context, on the pipe. -#[cfg(not(unix))] -fn ensure_context(_docker: impl AsRef) -> io::Result<()> { - Ok(()) +/// The docker context named CONTEXT, pointing at Kiri's socket or Windows +/// named pipe, made when missing. It is only made, never made current: which +/// engine plain docker uses stays the user's choice. +#[cfg(windows)] +fn ensure_context(docker: impl AsRef) -> io::Result<()> { + let docker = docker.as_ref(); + let quiet = || std::process::Stdio::null(); + let new_cmd = || { + let mut cmd = Command::new(docker); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if new_cmd().args(["context", "inspect", CONTEXT.get()]).stdout(quiet()).stderr(quiet()).status()?.success() { + return Ok(()); + } + let host = format!("host=npipe://{}", crate::client::pipe().replace('\\', "/")); + let out = new_cmd().args(["context", "create", CONTEXT.get(), "--description", "Kiri (WSL2)", "--docker", &host]).stdout(quiet()).output()?; + if out.status.success() { Ok(()) } else { Err(io::Error::other(failure("docker context create failed", &out.stderr))) } } #[cfg(unix)] diff --git a/crates/kiri/src/buildwith.rs b/crates/kiri/src/buildwith.rs index 4bf796aff..68a927ee3 100644 --- a/crates/kiri/src/buildwith.rs +++ b/crates/kiri/src/buildwith.rs @@ -437,13 +437,27 @@ pub fn ask() -> Option<&'static str> { places().ok().filter(|p| p.ask(other)).and(other) } -/// `kiri build-with [docker|kiri]`: says which, or switches. -#[cfg(unix)] +const USAGE: &str = "usage: kiri build-with [docker|kiri|status]"; + +/// `kiri build-with [docker|kiri|status]`: says which, or switches. +#[cfg(any(unix, windows))] pub fn cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + if args.len() > 1 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + let choice = match args.first().map(String::as_str) { + None | Some("status") => None, + Some(a) => Some(With::parse(a).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?), + }; let p = places()?; let other = other_engine(); - if let Some(a) = args.first() { - let with = With::parse(a).ok_or_else(|| io::Error::other("usage: kiri build-with [docker|kiri]"))?; + if let Some(with) = choice { p.choose(with)?; if with == With::Kiri && !p.ready() { crate::builds::ensure_builder(); diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index 7adcc1263..494794ec5 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -1,18 +1,37 @@ //! The window and `kiri` subcommands talk to `kiri daemon` the way the docker CLI does: HTTP over -//! the daemon's unix socket. One short connection per request, and one -//! long-lived one for `/events`. +//! the daemon's unix socket (or `\\.\pipe\kiri` on Windows). One short connection per request, +//! and one long-lived one for `/events`. // Parts of this serve only the Mac (the window, boot timings). #![cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[cfg(any(unix, test))] use std::ffi::OsStr; use std::io::{self, BufRead, BufReader, Read, Write}; +#[cfg(unix)] use std::os::unix::net::UnixStream; -use std::path::{Component, Path, PathBuf}; +#[cfg(any(unix, test))] +use std::path::Component; +use std::path::PathBuf; +#[cfg(any(unix, test))] +use std::path::Path; use std::time::Duration; use serde_json::Value; +#[cfg(windows)] +pub const DEFAULT_PIPE: &str = r"\\.\pipe\kiri"; + +/// The Windows named pipe `kiri-win` serves the Docker API on. +#[cfg(windows)] +pub fn pipe() -> String { + std::env::var("KIRI_PIPE") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| DEFAULT_PIPE.to_owned()) +} + +#[cfg(unix)] pub fn socket() -> io::Result { let kiri_socket = std::env::var_os("KIRI_SOCKET"); let home = std::env::var_os("HOME"); @@ -35,10 +54,21 @@ pub fn socket() -> io::Result { } } +#[cfg(any(unix, test))] fn safe_wsl_distro(name: &str) -> bool { - crate::daemon::binds::valid_distro_name(name) && !name.contains("..") + #[cfg(unix)] + { + crate::daemon::binds::valid_distro_name(name) && !name.contains("..") + } + #[cfg(not(unix))] + { + !name.is_empty() + && !name.contains("..") + && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + } } +#[cfg(any(unix, test))] fn is_wsl_socket_path(target: &Path, wsl_sockets_dir: &Path) -> bool { let Ok(rel) = target.strip_prefix(wsl_sockets_dir) else { return false; @@ -56,6 +86,7 @@ fn is_wsl_socket_path(target: &Path, wsl_sockets_dir: &Path) -> bool { /// directory (such as a `0750` WSL integration socket directory) as present so /// `check_alive` surfaces a clear permission-denied error instead of falling /// back to a missing home socket. +#[cfg(any(unix, test))] fn socket_present(path: &Path) -> bool { match std::fs::metadata(path) { Ok(_) => true, @@ -63,6 +94,7 @@ fn socket_present(path: &Path) -> bool { } } +#[cfg(any(unix, test))] fn socket_for( kiri_socket: Option<&OsStr>, service_socket: Option<&Path>, @@ -129,16 +161,106 @@ impl Response { } } +#[cfg(unix)] +fn op_header() -> String { + crate::diag::op_header() +} + +#[cfg(windows)] +fn op_header() -> String { + String::new() +} + +#[cfg(unix)] fn connect_to(sock: &Path, timeout: Option) -> io::Result { let s = UnixStream::connect(sock)?; s.set_read_timeout(timeout)?; Ok(s) } +#[cfg(unix)] fn connect(timeout: Option) -> io::Result { connect_to(&socket()?, timeout) } +#[cfg(windows)] +struct WinPipe(std::fs::File); + +#[cfg(windows)] +impl WinPipe { + fn open(name: &str) -> io::Result { + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + const ERROR_PIPE_BUSY: i32 = 231; + const SECURITY_IDENTIFICATION: u32 = 0x0001_0000; + const PIPE_READMODE_MESSAGE: u32 = 0x0000_0002; + unsafe extern "system" { + fn SetNamedPipeHandleState( + hNamedPipe: *mut core::ffi::c_void, + lpMode: *const u32, + lpMaxCollectionCount: *const u32, + lpCollectDataTimeout: *const u32, + ) -> i32; + } + for _ in 0..20 { + match std::fs::OpenOptions::new() + .read(true) + .write(true) + .share_mode(0) + .security_qos_flags(SECURITY_IDENTIFICATION) + .open(name) + { + Ok(file) => { + // `kiri-win` serves `\\.\pipe\kiri` in message mode and ends + // unframed HTTP responses with a 0-byte message. + let mode = PIPE_READMODE_MESSAGE; + // SAFETY: `file` owns a valid handle for the duration of the call. + unsafe { + SetNamedPipeHandleState( + file.as_raw_handle(), + &mode, + std::ptr::null(), + std::ptr::null(), + ); + } + return Ok(Self(file)); + } + Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) => { + std::thread::sleep(Duration::from_millis(50)); + } + Err(e) => return Err(e), + } + } + Err(io::Error::new(io::ErrorKind::TimedOut, format!("pipe {name} stayed busy"))) + } +} + +#[cfg(windows)] +impl Read for WinPipe { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + const ERROR_BROKEN_PIPE: i32 = 109; + const ERROR_PIPE_NOT_CONNECTED: i32 = 233; + const ERROR_MORE_DATA: i32 = 234; + match self.0.read(buf) { + Ok(n) => Ok(n), + Err(e) if e.raw_os_error() == Some(ERROR_MORE_DATA) => Ok(buf.len()), + Err(e) if matches!(e.raw_os_error(), Some(ERROR_BROKEN_PIPE | ERROR_PIPE_NOT_CONNECTED)) => Ok(0), + Err(e) => Err(e), + } + } +} + +#[cfg(windows)] +impl Write for WinPipe { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool)> { let mut line = String::new(); r.read_line(&mut line)?; @@ -195,15 +317,17 @@ pub fn get_background(path: &str) -> io::Result { Ok(r.json()) } +#[cfg(unix)] fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { send_to(&socket()?, method, path, body, extra) } +#[cfg(unix)] fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { let mut s = connect_to(sock, Some(Duration::from_secs(120)))?; let payload = body.map(Value::to_string).unwrap_or_default(); // The window's action this is part of, for the engine's log lines. - let op = crate::diag::op_header(); + let op = op_header(); write!( s, "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", @@ -212,6 +336,25 @@ fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: & answer(s) } +#[cfg(windows)] +fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + send_to_pipe(&pipe(), method, path, body, extra) +} + +#[cfg(windows)] +fn send_to_pipe(name: &str, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + let mut s = WinPipe::open(name)?; + let payload = body.map(Value::to_string).unwrap_or_default(); + let op = op_header(); + write!( + s, + "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", + payload.len() + )?; + s.flush()?; + answer(s) +} + /// The answer to a request just sent; the whole body is read, chunked or not. fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); @@ -239,9 +382,10 @@ fn answer(s: impl Read) -> io::Result { /// body `write` gives up on is never ended, so the daemon sees it cut /// short, not as a whole one; if the daemon stopped reading first (it /// refused the request), its answer is returned, which says why. +#[cfg(unix)] pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { let s = connect(Some(Duration::from_secs(300)))?; - let op = crate::diag::op_header(); + let op = op_header(); (&s).write_all(format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes())?; match stream_body(&s, write) { Ok(()) => answer(&s), @@ -253,6 +397,24 @@ pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn W } } +#[cfg(windows)] +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + let mut s = WinPipe::open(&pipe())?; + let op = op_header(); + write!( + s, + "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n" + )?; + match stream_body(&mut s, write) { + Ok(()) => answer(s), + Err(e) if refused(&e) => match answer(s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + /// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when /// `write` succeeds. pub(crate) fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { @@ -325,16 +487,24 @@ fn not_running_message_for(is_linux: bool, is_wsl: bool) -> &'static str { /// Actionable OS-specific error text when the engine is not running. pub fn not_running_message() -> &'static str { - #[cfg(target_os = "linux")] - let wsl = is_wsl_env( - std::env::var_os("WSL_DISTRO_NAME").as_deref(), - &[Path::new("/proc/sys/fs/binfmt_misc/WSLInterop"), Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late")], - ); - #[cfg(not(target_os = "linux"))] - let wsl = false; - not_running_message_for(cfg!(target_os = "linux"), wsl) + #[cfg(windows)] + { + "Kiri isn't running. Open Kiri, or start it with `kiri start`" + } + #[cfg(not(windows))] + { + #[cfg(target_os = "linux")] + let wsl = is_wsl_env( + std::env::var_os("WSL_DISTRO_NAME").as_deref(), + &[Path::new("/proc/sys/fs/binfmt_misc/WSLInterop"), Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late")], + ); + #[cfg(not(target_os = "linux"))] + let wsl = false; + not_running_message_for(cfg!(target_os = "linux"), wsl) + } } +#[cfg(any(unix, test))] fn permission_denied_error(sock: &Path, is_linux: bool) -> io::Error { let msg = if is_linux { format!( @@ -347,6 +517,7 @@ fn permission_denied_error(sock: &Path, is_linux: bool) -> io::Error { io::Error::new(io::ErrorKind::PermissionDenied, msg) } +#[cfg(unix)] fn check_alive_at(sock: &Path, not_running: &str) -> io::Result<()> { match send_to(sock, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { Ok(r) if r.ok() => Ok(()), @@ -362,16 +533,31 @@ pub fn check_alive() -> io::Result<()> { } /// Like [`check_alive`], using `not_running` when the daemon is not running. +#[cfg(unix)] pub fn check_alive_with(not_running: &str) -> io::Result<()> { let sock = socket()?; check_alive_at(&sock, not_running) } +#[cfg(windows)] +pub fn check_alive_with(not_running: &str) -> io::Result<()> { + let p = pipe(); + match send_to_pipe(&p, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { + Ok(r) if r.ok() => Ok(()), + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("cannot connect to Kiri's pipe ({p}): permission denied"), + )), + _ => Err(io::Error::new(io::ErrorKind::NotConnected, not_running)), + } +} + /// A POST whose answer is JSON lines arriving over time (a pull's /// progress): `on_line` sees each as it comes. Returns the HTTP status. /// `auth` is a registry sign-in for a pull (`X-Registry-Auth`, base64url). /// `opened` gets the connection once it is made, so another thread can /// shut it down to stop the request (Cancel on a pull). +#[cfg(unix)] pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), on_line: impl FnMut(Value)) -> io::Result { post_lines_inner(path, auth, Some(Duration::from_secs(120)), opened, on_line) } @@ -383,6 +569,7 @@ pub fn post_lines_unbounded(path: &str, on_line: impl FnMut(Value)) -> io::Resul post_lines_inner(path, None, None, |_| {}, on_line) } +#[cfg(unix)] fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { if auth.is_some_and(|a| a.contains(['\r', '\n'])) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); @@ -390,7 +577,7 @@ fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, o let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); let mut s = connect(timeout)?; opened(&s); - write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", crate::diag::op_header())?; + write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", op_header())?; let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut pending = Vec::new(); @@ -420,6 +607,7 @@ fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, o } /// Calls `on_event` for each event until the connection ends or it returns false. +#[cfg(unix)] pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { let mut s = connect(None)?; write!(s, "GET /events HTTP/1.1\r\nHost: kiri\r\nX-Kiri-Background: 1\r\n\r\n")?; @@ -445,10 +633,12 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { /// A long-lived streamed response, such as `logs?follow=1`, read chunk by /// chunk. `closer` ends it from another thread. +#[cfg(unix)] pub struct Stream { reader: BufReader, } +#[cfg(unix)] impl Stream { pub fn open(path: &str) -> io::Result { let mut s = connect(None)?; @@ -473,6 +663,7 @@ impl Stream { /// Runs `cmd` in a running container and returns (exit code, output), /// through the exec API with a terminal, so output arrives unframed. +#[cfg(unix)] pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let created = request("POST", &format!("/containers/{container}/exec"), Some(&serde_json::json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": true})))?; if !created.ok() { @@ -497,7 +688,8 @@ pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { Ok((code, String::from_utf8_lossy(&out).replace("\r\n", "\n"))) } -/// A docker CLI: on PATH, else the one bundled in Kiri.app. +/// A docker CLI: on PATH, else the one bundled in Kiri.app (or Kiri's bin folder on Windows). +#[cfg(unix)] pub fn docker_cli() -> Option { let on_path = std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker")).find(|d| d.is_file())); on_path @@ -508,6 +700,29 @@ pub fn docker_cli() -> Option { .or_else(lite_cli) } +#[cfg(windows)] +pub fn docker_cli() -> Option { + let beside = std::env::current_exe() + .ok() + .and_then(|e| e.parent().map(|d| d.join("docker.exe"))) + .filter(|d| d.is_file()); + let local = || { + let base = PathBuf::from(std::env::var_os("LOCALAPPDATA")?); + [ + base.join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("docker.exe"), + ] + .into_iter() + .find(|d| d.is_file()) + }; + let on_path = || { + std::env::var_os("PATH") + .and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker.exe")).find(|d| d.is_file())) + }; + beside.or_else(local).or_else(on_path) +} + /// Kiri Lite's downloaded CLI. #[cfg(target_os = "macos")] fn lite_cli() -> Option { @@ -521,13 +736,21 @@ fn lite_cli() -> Option { #[cfg(test)] mod tests { + #[cfg(unix)] use std::ffi::OsStr; - use std::io::{self, Read, Write}; + #[cfg(unix)] + use std::io::{Read, Write}; + use std::io; + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; + #[cfg(unix)] use std::os::unix::net::UnixListener; + #[cfg(unix)] use std::path::{Path, PathBuf}; + #[cfg(unix)] use std::sync::atomic::{AtomicU64, Ordering}; + #[cfg(unix)] fn temp_dir(tag: &str) -> PathBuf { static SEQ: AtomicU64 = AtomicU64::new(0); let dir = std::env::temp_dir().join(format!("kiri-client-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); @@ -559,6 +782,7 @@ mod tests { assert!(super::refused(&io::Error::from(io::ErrorKind::BrokenPipe)) && !super::refused(&io::Error::other("x"))); } + #[cfg(unix)] #[test] fn socket_for_discovers_wsl_integration_sockets_and_symlinks() { let root = temp_dir("wsl-sock"); @@ -637,6 +861,7 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + #[cfg(unix)] #[test] fn check_alive_distinguishes_alive_not_running_and_permission_denied() { let dir = temp_dir("alive"); diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index 4fc55599b..82af388ca 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -69,6 +69,10 @@ const MAC_REPORT_BUDGET: usize = 24 << 10; pub fn run(args: &[String]) -> io::Result<()> { match args.first().map(String::as_str) { + Some("-h" | "--help" | "help") => { + println!("{USAGE}"); + Ok(()) + } Some("logs") => logs_cli(&args[1..]), Some("report") => report_cli(&args[1..]), _ => Err(io::Error::other(USAGE)), @@ -175,6 +179,10 @@ pub fn render(v: &Value, utc: bool, color: bool) -> String { } fn logs_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut parts, mut follow, mut errors, mut n, mut op) = (Vec::new(), false, false, 50usize, None); let mut it = args.iter(); while let Some(a) = it.next() { @@ -556,6 +564,10 @@ pub fn reveal(path: &Path) { } fn report_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut out, mut send_it) = (None, false); let mut it = args.iter(); while let Some(a) = it.next() { diff --git a/crates/kiri/src/docker.rs b/crates/kiri/src/docker.rs index 10ea4b3de..53d7fce00 100644 --- a/crates/kiri/src/docker.rs +++ b/crates/kiri/src/docker.rs @@ -55,6 +55,7 @@ pub fn run(args: &[String]) -> io::Result<()> { /// Exits with docker's exit code. #[cfg(windows)] pub fn run(args: &[String]) -> io::Result<()> { + crate::setup_win::heal_quietly(); let beside = std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join("docker.exe"))).filter(|d| d.is_file()); let status = std::process::Command::new(beside.unwrap_or_else(|| "docker.exe".into())) .args(["--context", crate::flavor::CONTEXT.get()]) diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs index 19d600ee2..b77850b7b 100644 --- a/crates/kiri/src/dockerctx.rs +++ b/crates/kiri/src/dockerctx.rs @@ -274,6 +274,181 @@ pub fn switch(dir: &Path, meta: &Path, name: &str, ours: &str, description: &str set_current(&dir.join("config.json"), name) } +/// Lowercase hex SHA-256 of `data`, using `std` only so `dockerctx` stays +/// dependency-free across `kiri`, `kiri-win`, and host-side tests. +pub fn sha256_hex(data: &[u8]) -> String { + const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ]; + let mut h: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]; + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut msg = Vec::with_capacity((data.len() + 9).next_multiple_of(64)); + msg.extend_from_slice(data); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_be_bytes()); + for chunk in msg.as_chunks::<64>().0 { + let mut w = [0u32; 64]; + for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let temp1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + for (dst, add) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *dst = dst.wrapping_add(add); + } + } + let mut out = String::with_capacity(64); + for word in h { + use std::fmt::Write as _; + let _ = write!(out, "{word:08x}"); + } + out +} + +/// The docker CLI's directory for a named context (`contexts/meta/`). +pub fn context_meta(dir: &Path, name: &str) -> PathBuf { + dir.join("contexts/meta").join(sha256_hex(name.as_bytes())) +} + +/// Candidate Windows `cli-plugins` folders for Kiri (`cli-plugins` beside +/// `kiri.exe`, `bin\cli-plugins` beside `kiri-win.exe`, `%LOCALAPPDATA%\Kiri\bin\cli-plugins`, +/// and `%LOCALAPPDATA%\Programs\Kiri\cli-plugins`), returning the first existing directory. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn find_windows_cli_plugins(exe: Option<&Path>, local_app_data: Option<&Path>) -> Option { + let mut candidates = Vec::new(); + if let Some(exe_dir) = exe.and_then(Path::parent) { + candidates.push(exe_dir.join("cli-plugins")); + candidates.push(exe_dir.join("bin").join("cli-plugins")); + } + if let Some(local) = local_app_data { + candidates.push(local.join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Kiri").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("cli-plugins")); + } + candidates.into_iter().find(|p| p.is_dir()) +} + +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +fn same_windows_dir(a: &str, b: &str) -> bool { + let norm = |s: &str| s.replace('\\', "/").trim_end_matches('/').to_ascii_lowercase(); + norm(a) == norm(b) +} + +/// What [`repair_windows_config`] changed in `%USERPROFILE%\.docker`. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Default, PartialEq, Eq)] +pub struct WindowsRepair { + pub context_written: bool, + pub plugins_added: bool, + pub current_context_set: bool, +} + +/// Options for [`repair_windows_config`]. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Clone, Copy)] +pub struct WindowsRepairOpts<'a> { + pub ours: &'a str, + pub description: &'a str, + pub host: &'a str, + pub plugins_dir: Option<&'a Path>, + /// Always rewrite `contexts/meta//meta.json` (used by `kiri setup`). + pub force_context_write: bool, + /// Set `currentContext` to `ours` whenever `currentContext` is empty (`kiri setup`). + pub set_current_if_empty: bool, + /// Unconditionally set `currentContext` to `ours` (`kiri setup --use`). + pub force_use: bool, + /// Whether Docker Desktop (`Docker Desktop.exe`) is still installed on this PC. + pub desktop_installed: bool, +} + +/// Ensures Kiri's Windows Docker configuration in `dir` (`%USERPROFILE%\.docker`): +/// - writes `contexts/meta//meta.json` when missing (or when `force_context_write`), +/// - ensures `cliPluginsExtraDirs` in `config.json` includes `plugins_dir` (preserving logins, +/// credential helpers, aliases, and other plugin dirs), and +/// - sets `currentContext` to `ours` when `force_use` is set, when `currentContext` names a +/// non-existent context (such as a removed `desktop-linux`), when `currentContext` is empty and +/// `set_current_if_empty` is set, or when `config.json` was missing and Docker Desktop is not +/// installed (#984). +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn repair_windows_config(dir: &Path, opts: WindowsRepairOpts<'_>) -> io::Result { + let config_path = dir.join("config.json"); + let config_existed = config_path.exists(); + let mut cfg = read_json(&config_path)?; + if !cfg.is_object() { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", config_path.display()))); + } + let mut out = WindowsRepair::default(); + let meta = context_meta(dir, opts.ours); + if opts.force_context_write || !meta.join("meta.json").is_file() { + write_context(&meta, opts.ours, opts.description, opts.host)?; + out.context_written = true; + } + let mut cfg_changed = false; + if let Some(plugins) = opts.plugins_dir { + let want = plugins.to_string_lossy().into_owned(); + let mut dirs: Vec = cfg.get("cliPluginsExtraDirs").and_then(Value::as_array).cloned().unwrap_or_default(); + if !dirs.iter().any(|d| d.as_str().is_some_and(|s| same_windows_dir(s, &want))) { + dirs.push(Value::String(want)); + cfg["cliPluginsExtraDirs"] = Value::Array(dirs); + out.plugins_added = true; + cfg_changed = true; + } + } + let cur = cfg.get("currentContext").and_then(Value::as_str).map(str::trim).unwrap_or("").to_owned(); + let dangling = !cur.is_empty() + && cur != "default" + && cur != opts.ours + && (!valid_name(&cur) + || !context_meta(dir, &cur).join("meta.json").is_file() + || (cur == "desktop-linux" && !opts.desktop_installed)); + let want_ours = opts.force_use + || dangling + || (cur.is_empty() && (opts.set_current_if_empty || (!config_existed && !opts.desktop_installed))); + if want_ours && cur != opts.ours { + cfg["currentContext"] = Value::String(opts.ours.to_owned()); + out.current_context_set = true; + cfg_changed = true; + } + if cfg_changed { + write_json(&config_path, &cfg)?; + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -499,6 +674,134 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn sha256_hex_matches_known_vectors_and_docker_context_dir() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + assert_eq!( + sha256_hex(b"kiri"), + "80d7688032dda428a5d1e0eea7ad434d219b770b7d3a0646fd58695e40107755" + ); + } + + #[test] + fn windows_config_repair_heals_wiped_config_plugins_and_dangling_desktop_context() { + let root = scratch_home("win-repair"); + let docker = root.join(".docker"); + let exe_dir = root.join("Kiri/bin"); + let plugins = exe_dir.join("cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + let exe = exe_dir.join("kiri.exe"); + std::fs::write(&exe, b"").unwrap(); + assert_eq!(find_windows_cli_plugins(Some(&exe), None).as_deref(), Some(plugins.as_path())); + + // 1. Docker Desktop uninstalled and wiped `%USERPROFILE%\.docker\config.json`: + // startup self-heal restores `kiri` context, `cliPluginsExtraDirs`, and `currentContext = "kiri"`. + let r = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { context_written: true, plugins_added: true, current_context_set: true } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!(cfg["cliPluginsExtraDirs"], json!([plugins.to_string_lossy()])); + // Idempotent on subsequent starts (no redundant writes). + let r2 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!(r2, WindowsRepair::default()); + + // 2. Dangling `desktop-linux` context (meta removed or Docker Desktop uninstalled) is healed, + // preserving registry logins, credHelpers, and aliases. + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "c2VjcmV0"}}, + "credHelpers": {"ecr": "ecr-login"}, + "aliases": {"builder": "buildx"}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let r3 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert!(r3.plugins_added && r3.current_context_set); + let after = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(after["currentContext"], "kiri"); + assert_eq!(after["auths"]["ghcr.io"]["auth"], "c2VjcmV0"); + assert_eq!(after["credHelpers"]["ecr"], "ecr-login"); + assert_eq!(after["aliases"]["builder"], "buildx"); + + // 3. Corrupt config.json is never overwritten. + std::fs::write(docker.join("config.json"), "{broken").unwrap(); + assert_eq!( + repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: true, + set_current_if_empty: true, + force_use: true, + desktop_installed: false, + }, + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert_eq!(std::fs::read_to_string(docker.join("config.json")).unwrap(), "{broken"); + let _ = std::fs::remove_dir_all(&root); + } + #[cfg(unix)] #[test] fn sock_at_detects_kiri_taken_and_free() { diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index 2f6f613b1..a077c0b17 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -81,6 +81,12 @@ pub fn run(args: &[String]) -> io::Result<()> { } fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } 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))?; @@ -147,6 +153,13 @@ mod tests { assert_eq!(format(&moved), "HTTP 18780 on, a container has the port for now (set by KIRI_HTTP_PORT)\nHTTPS 18743 on\n"); } + #[test] + fn help_succeeds_without_touching_the_socket() { + for h in ["--help", "-h", "help", "set --help", "reset -h"] { + run_with(&args(h), || panic!("help must not check daemon: {h}")).unwrap(); + } + } + #[test] fn bad_arguments_fail_before_touching_the_socket() { for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown", "--json show"] { diff --git a/crates/kiri/src/hostaccess.rs b/crates/kiri/src/hostaccess.rs index e847d83f8..01cbc08ad 100644 --- a/crates/kiri/src/hostaccess.rs +++ b/crates/kiri/src/hostaccess.rs @@ -127,12 +127,23 @@ fn run_with( } } +const USAGE: &str = "usage: kiri host-access [--restart] USER"; + pub fn run(args: &[String]) -> io::Result { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(0); + } let (restart, args) = match args { [flag, rest @ ..] if flag == "--restart" => (true, rest), _ => (false, args), }; - let [user] = args else { return Err(io::Error::other("usage: kiri host-access [--restart] USER")) }; + let [user] = args else { return Err(io::Error::other(USAGE)) }; + if user.starts_with('-') { + return Err(io::Error::other(USAGE)); + } // SAFETY: geteuid has no preconditions. if unsafe { libc::geteuid() } != 0 { return Err(io::Error::other(format!("needs root: sudo kiri host-access {}{user}", if restart { "--restart " } else { "" }))); diff --git a/crates/kiri/src/images.rs b/crates/kiri/src/images.rs index 0c9ef1b16..9973df841 100644 --- a/crates/kiri/src/images.rs +++ b/crates/kiri/src/images.rs @@ -15,7 +15,15 @@ fn invalid(msg: impl Into) -> io::Error { } pub fn pull(args: &[String]) -> io::Result<()> { - let name = args.first().ok_or_else(|| invalid("usage: kiri raw pull "))?; + const USAGE: &str = "usage: kiri raw pull "; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.len() != 1 || args[0].starts_with('-') { + return Err(invalid(USAGE)); + } + let name = &args[0]; let reference = Reference::parse(name).map_err(|e| invalid(e.to_string()))?; let store = store()?; let platform = Platform::host_linux(); @@ -54,7 +62,15 @@ pub fn pull(args: &[String]) -> io::Result<()> { Ok(()) } -pub fn list(_args: &[String]) -> io::Result<()> { +pub fn list(args: &[String]) -> io::Result<()> { + const USAGE: &str = "usage: kiri raw images"; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if !args.is_empty() { + return Err(invalid(USAGE)); + } let mut images = store()?.images()?; images.sort_by(|a, b| a.name.cmp(&b.name)); let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); @@ -74,8 +90,13 @@ pub fn list(_args: &[String]) -> io::Result<()> { } pub fn remove(args: &[String]) -> io::Result<()> { - if args.is_empty() { - return Err(invalid("usage: kiri raw rmi ...")); + const USAGE: &str = "usage: kiri raw rmi ..."; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() || args.iter().any(|a| a.starts_with('-')) { + return Err(invalid(USAGE)); } let store = store()?; for name in args { diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index 754332cc4..097f16606 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -34,6 +34,7 @@ fn cli() -> io::Result { let mut cmd = Command::new(docker()?); #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd.env_remove("DOCKER_HOST").env_remove("DOCKER_CONTEXT"); Ok(cmd) } @@ -1698,13 +1699,28 @@ fn pick(given: Option<&str>, answers: impl Fn(&str) -> bool) -> io::Result<&'sta } const KINDS: [&str; 3] = ["image", "volume", "container"]; -const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(windows)] +const USAGE: &str = "usage: kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(not(windows))] +const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; + +/// Which resource kinds a bulk `kiri import` or `kiri import --list` includes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct KindFilter { + images: bool, + volumes: bool, + containers: bool, +} + +impl KindFilter { + const ALL: Self = Self { images: true, volumes: true, containers: true }; +} /// What `kiri import` was asked to do. #[derive(Debug, PartialEq)] enum Ask<'a> { - Everything, - List, + Everything(KindFilter), + List(KindFilter), One(&'a str, &'a str), } @@ -1715,38 +1731,80 @@ enum Ask<'a> { fn parse<'a>(args: &[&'a str]) -> io::Result<(Option<&'a str>, Ask<'a>, bool)> { let usage = || io::Error::other(USAGE); let (mut list, mut force) = (false, false); + let (mut f_images, mut f_volumes, mut f_containers) = (false, false, false); let mut words = Vec::new(); for a in args { match *a { "--list" => list = true, "--force" => force = true, + "--images" => f_images = true, + "--volumes" => f_volumes = true, + "--containers" => f_containers = true, f if f.starts_with('-') => return Err(usage()), w => words.push(w), } } + let explicit_filter = f_images || f_volumes || f_containers; + let filter = if explicit_filter { + KindFilter { images: f_images, volumes: f_volumes, containers: f_containers } + } else { + KindFilter::ALL + }; let (given, rest) = match words.split_first() { Some((first, rest)) if !KINDS.contains(first) => (Some(*first), rest), _ => (None, &words[..]), }; let ask = match (rest, list) { - ([], false) => Ask::Everything, - ([], true) if !force => Ask::List, - ([kind, name], false) if KINDS.contains(kind) => Ask::One(kind, name), + ([], false) => Ask::Everything(filter), + ([], true) if !force => Ask::List(filter), + ([kind, name], false) if !explicit_filter && KINDS.contains(kind) => Ask::One(kind, name), _ => return Err(usage()), }; Ok((given, ask, force)) } -/// `kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]`: +#[cfg(windows)] +fn ensure_windows_kiri_context() { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles") + .is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = format!("npipe:{}", client::pipe().replace('\\', "/")); + let _ = crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +/// `kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]`: /// one item, or every image, named volume and container Kiri lacks. +#[cfg_attr(not(any(target_os = "macos", windows)), allow(dead_code))] pub fn run(args: &[String]) -> io::Result<()> { - if args.iter().any(|a| a == "-h" || a == "--help") { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } let args: Vec<&str> = args.iter().map(String::as_str).collect(); let (given, ask, force) = parse(&args)?; + #[cfg(windows)] + ensure_windows_kiri_context(); let source = pick(given, answers)?; + if !matches!(ask, Ask::List(_)) { + client::check_alive()?; + } if given.is_none() { println!("from {} ({source})", label(source)); } @@ -1760,8 +1818,11 @@ pub fn run(args: &[String]) -> io::Result<()> { } let inv = inventory(source)?; let list = |k: &str| inv[k].as_array().cloned().unwrap_or_default(); - if ask == Ask::List { - for k in ["images", "volumes", "containers"] { + if let Ask::List(filter) = ask { + for (k, on) in [("images", filter.images), ("volumes", filter.volumes), ("containers", filter.containers)] { + if !on { + continue; + } println!("{k}:"); for v in list(k) { println!(" {}{}", v["name"].as_str().unwrap_or(""), if v["have"] == true { " (already in Kiri)" } else { "" }); @@ -1769,6 +1830,7 @@ pub fn run(args: &[String]) -> io::Result<()> { } return Ok(()); } + let Ask::Everything(filter) = ask else { unreachable!() }; let mut failures: Vec<(&str, String, String)> = Vec::new(); let mut step = |what: &'static str, name: &str, r: io::Result<()>| match r { Ok(()) => println!("{what} {name}: done"), @@ -1779,23 +1841,29 @@ pub fn run(args: &[String]) -> io::Result<()> { failures.push((what, name.to_owned(), why.to_owned())); } }; - for v in list("images").iter().filter(|v| v["have"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("image", n, image(source, n)); - } - for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("volume", n, volume_with(source, n, force)); - } - for v in list("containers") { - let n = v["name"].as_str().unwrap_or(""); - let already_had = v["have"] == true; - let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); - if let Some(why) = container_skip_reason(already_had, already_imported) { - println!("container {n}: skipped ({why})"); - continue; + if filter.images { + for v in list("images").iter().filter(|v| v["have"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("image", n, image(source, n)); + } + } + if filter.volumes { + for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("volume", n, volume_with(source, n, force)); + } + } + if filter.containers { + for v in list("containers") { + let n = v["name"].as_str().unwrap_or(""); + let already_had = v["have"] == true; + let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); + if let Some(why) = container_skip_reason(already_had, already_imported) { + println!("container {n}: skipped ({why})"); + continue; + } + step("container", n, container_with(source, n, force, &[])); } - step("container", n, container_with(source, n, force, &[])); } if !failures.is_empty() { Err(io::Error::other(format_failures(&failures))) } else { Ok(()) } } @@ -1990,17 +2058,31 @@ mod tests { // everything"; the source may be left out before a kind. #[test] fn parses_what_to_import() { - use super::{Ask, parse}; - assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything, false)); - assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything, false)); - assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List, false)); - assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List, false)); + use super::{Ask, KindFilter, parse}; + let all = KindFilter::ALL; + assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything(all), false)); + assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything(all), false)); + assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List(all), false)); + assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List(all), false)); assert_eq!(parse(&["image", "nginx"]).unwrap(), (None, Ask::One("image", "nginx"), false)); assert_eq!(parse(&["desktop-linux", "volume", "pg"]).unwrap(), (Some("desktop-linux"), Ask::One("volume", "pg"), false)); // #345: --force copies volumes running containers use, one or all. assert_eq!(parse(&["orbstack", "volume", "pg", "--force"]).unwrap(), (Some("orbstack"), Ask::One("volume", "pg"), true)); assert_eq!(parse(&["--force", "container", "db"]).unwrap(), (None, Ask::One("container", "db"), true)); - assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything, true)); + assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything(all), true)); + // #984: --images, --volumes, --containers filter bulk import and --list. + assert_eq!( + parse(&["desktop-linux", "--images"]).unwrap(), + (Some("desktop-linux"), Ask::Everything(KindFilter { images: true, volumes: false, containers: false }), false) + ); + assert_eq!( + parse(&["--volumes", "--containers"]).unwrap(), + (None, Ask::Everything(KindFilter { images: false, volumes: true, containers: true }), false) + ); + assert_eq!( + parse(&["--list", "--containers"]).unwrap(), + (None, Ask::List(KindFilter { images: false, volumes: false, containers: true }), false) + ); for bad in [ &["orbstack", "image"][..], &["image"], @@ -2010,13 +2092,14 @@ mod tests { &["--list", "image", "nginx"], &["image", "nginx", "--list"], &["--list", "--force"], + &["--images", "image", "nginx"], // An unknown flag must not start a full import. &["--dry-run"], &["orbstack", "-l"], ] { assert!(parse(bad).unwrap_err().to_string().starts_with("usage:"), "{bad:?}"); } - assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything, false)); + assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything(all), false)); } // Volume helpers run only an image the engine pulled from an official diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 7f9998356..7f1eef43a 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -504,6 +504,10 @@ fn ok(r: io::Result) -> io::Result { pub fn run(args: &[String]) -> io::Result<()> { let what = args.first().map(String::as_str).unwrap_or(""); + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) || what == "help" { + println!("{}", if what == "set" { USAGE_SET } else { USAGE_K8S }); + return Ok(()); + } let logged = matches!(what, "start" | "stop" | "delete" | "set"); // A recreate from the command line (`kiri k8s set`) is attributed to this // op, so the node's stop is logged as `k8s set`, not as a memory kill. A diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index ebede90d3..ec15973b3 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -35,12 +35,35 @@ fn ok(r: io::Result) -> io::Result { if r.ok() { Ok(r) } else { Err(io::Error::other(r.error())) } } +pub(crate) const USAGE: &str = "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME"; + +/// True when `args` asks for `kiri machine`'s own help rather than passing +/// `--help` to a command inside `kiri machine shell NAME -- --help`. +pub(crate) fn wants_help(args: &[String]) -> bool { + if matches!(args.first().map(String::as_str), Some("help")) { + return true; + } + let scan_end = if args.first().map(String::as_str) == Some("shell") { + args.iter().position(|a| a == "--").unwrap_or(args.len()) + } else { + args.len() + }; + args[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")) +} + pub fn run(args: &[String]) -> io::Result<()> { + if wants_help(args) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() { + return Err(io::Error::other(USAGE)); + } if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri.app or run `kiri daemon`")); } let name = args.get(1).map(String::as_str).unwrap_or_default(); - let need_name = || if name.is_empty() { Err(io::Error::other("name a machine")) } else { Ok(()) }; + let need_name = || if name.is_empty() || name.starts_with('-') { Err(io::Error::other("name a machine")) } else { Ok(()) }; match args.first().map(String::as_str) { Some("create") => { need_name()?; @@ -69,9 +92,7 @@ pub fn run(args: &[String]) -> io::Result<()> { println!("deleted machine {name}"); Ok(()) } - _ => Err(io::Error::other( - "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME", - )), + _ => Err(io::Error::other(USAGE)), } } @@ -565,6 +586,20 @@ mod tests { } } + #[test] + fn wants_help_stops_at_double_dash_for_shell_commands() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert!(super::wants_help(&s(&["--help"]))); + assert!(super::wants_help(&s(&["-h"]))); + assert!(super::wants_help(&s(&["help"]))); + assert!(super::wants_help(&s(&["create", "--help"]))); + assert!(super::wants_help(&s(&["shell", "--help"]))); + assert!(super::wants_help(&s(&["shell", "dev", "-h"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "ls", "--help"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "-h"]))); + assert!(!super::wants_help(&s(&[]))); + } + #[test] fn list_json_has_each_machines_name_image_and_state() { let rows = json!([{"Labels": {(super::LABEL): "dev"}, "Image": "ubuntu:24.04", "State": "running", "Status": "Up 2 hours"}]); diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 064ca6645..be25bd26c 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -13,7 +13,7 @@ mod boot; // builds, cli_pins, scan and tools on Linux too: the daemon reads an // image's layers and scans it for kiri-win, whose window can't reach the // store inside WSL (daemon/api.rs). -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod builds; // The engine stops when its app is deleted under it (kiri-win includes it @@ -21,7 +21,7 @@ mod builds; #[cfg(unix)] mod appwatch; // Which builder plain `docker build` uses: Docker's or Kiri's. -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod buildwith; // Linux only, but its tests run anywhere with unix sockets. @@ -33,15 +33,23 @@ mod bridge; mod hostrelay; #[cfg(unix)] mod cli_pins; -#[cfg(unix)] +#[cfg(any(unix, windows))] mod client; #[cfg(unix)] mod daemon; +#[cfg(windows)] +#[path = "daemon/time.rs"] +#[allow(dead_code)] +mod daemon_time; +#[cfg(windows)] +mod daemon { + pub(crate) use super::daemon_time as time; +} #[cfg(unix)] mod diag; #[cfg(any(unix, windows))] mod docker; -#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), test))] +#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), windows, test))] #[cfg_attr(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))), allow(dead_code))] mod dockerctx; // `kiri doctor`: whether this installation works (Windows: docker here, the engine in WSL). @@ -51,12 +59,14 @@ mod doctor; #[cfg(unix)] mod domains_cli; mod flavor; +#[cfg(unix)] mod images; #[cfg(unix)] mod guest; #[cfg(target_os = "linux")] mod hostaccess; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", windows))] +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod import; #[cfg(unix)] mod k8s; @@ -77,6 +87,8 @@ mod scan; mod scan_cli; #[cfg(target_os = "macos")] mod setup; +#[cfg(any(windows, test))] +mod setup_win; #[cfg(unix)] mod usb; #[cfg(unix)] @@ -109,8 +121,10 @@ const USAGE_LINES: &[&str] = &[ " kiri ui [--start] [--view containers|images|volumes|networks|builds]", #[cfg(target_os = "macos")] " kiri setup [--use] [--no-agent] [--no-profiles] | kiri setup --uninstall", - #[cfg(unix)] - " kiri build-with [docker|kiri] which builder docker build uses", + #[cfg(windows)] + " kiri setup [--use] ensure Kiri's docker context and CLI plugins in ~/.docker", + #[cfg(any(unix, windows))] + " kiri build-with [docker|kiri|status] which builder docker build uses", " kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports", " kiri storage [status | reclaim] storage location, disk usage, and reclaiming VM disk space", " kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors", @@ -130,7 +144,9 @@ const USAGE_LINES: &[&str] = &[ #[cfg(target_os = "macos")] " kiri vm [status | set --shared-nat on|off] VM networking (off avoids macOS InternetSharing)", #[cfg(target_os = "macos")] - " kiri import [orbstack | desktop-linux] [--list | [--force] [image|volume|container NAME]]", + " kiri import [orbstack | desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", + #[cfg(windows)] + " kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", #[cfg(target_os = "macos")] " kiri bench [--runs N] [--image IMAGE] [--network none|bridge]", #[cfg(target_os = "macos")] @@ -148,19 +164,56 @@ fn usage() -> String { #[cfg(any(windows, test))] const WINDOWS_DAEMON_ERROR: &str = "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri"; +const START_USAGE: &str = "usage: kiri start start Kiri after a Stop (the window's Start)"; +#[cfg(unix)] +const DAEMON_USAGE: &str = "usage: kiri daemon"; +#[cfg(unix)] +const RAW_USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w DIR] [--timings] IMAGE [COMMAND...]\n kiri raw pull | raw images | raw rmi ..."; +#[cfg(any(target_os = "macos", target_os = "linux", test))] +const UI_USAGE: &str = "usage: kiri ui [--start] [--view containers|images|volumes|networks|builds]"; + +#[cfg(any(target_os = "macos", target_os = "linux", test))] +fn parse_ui_args(rest: &[String]) -> std::io::Result)>> { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + return Ok(None); + } + let mut start = false; + let mut view = None; + let mut it = rest.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--start" => start = true, + "--view" => { + let v = it + .next() + .filter(|s| !s.is_empty() && !s.starts_with('-')) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE))?; + view = Some(v.clone()); + } + _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE)), + } + } + Ok(Some((start, view))) +} + #[derive(Debug, PartialEq, Eq)] enum Command<'a> { - #[cfg(unix)] + Help, + Version, Daemon(&'a [String]), - #[cfg(windows)] - Daemon, #[cfg(target_os = "linux")] Bridge(&'a [String]), #[cfg(target_os = "linux")] - HostRelay, + HostRelay(&'a [String]), #[cfg(target_os = "linux")] HostAccess(&'a [String]), #[cfg(unix)] + RawHelp, + #[cfg(unix)] + RawInvalid, + #[cfg(unix)] RawRun(&'a [String]), #[cfg(unix)] RawPull(&'a [String]), @@ -172,15 +225,12 @@ enum Command<'a> { Bench(&'a [String]), #[cfg(target_os = "macos")] Boot(&'a [String]), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Setup(&'a [String]), #[cfg(any(unix, windows))] Share(&'a [String]), - #[cfg(unix)] - Start, - #[cfg(windows)] Start(&'a [String]), - #[cfg(unix)] + #[cfg(any(unix, windows))] BuildWith(&'a [String]), #[cfg(unix)] Domains(&'a [String]), @@ -198,7 +248,7 @@ enum Command<'a> { Machine(&'a [String]), #[cfg(unix)] Usb(&'a [String]), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Import(&'a [String]), #[cfg(target_os = "macos")] Vm(&'a [String]), @@ -217,14 +267,13 @@ enum Command<'a> { impl<'a> Command<'a> { fn parse(args: &'a [String]) -> Option> { match args.first().map(String::as_str) { - #[cfg(unix)] + Some("-h" | "--help" | "help") => Some(Command::Help), + Some("--version" | "-V" | "-v") if args.len() == 1 => Some(Command::Version), Some("daemon") => Some(Command::Daemon(&args[1..])), - #[cfg(windows)] - Some("daemon") => Some(Command::Daemon), #[cfg(target_os = "linux")] Some("bridge") => Some(Command::Bridge(&args[1..])), #[cfg(target_os = "linux")] - Some("hostrelay") => Some(Command::HostRelay), + Some("hostrelay") => Some(Command::HostRelay(&args[1..])), #[cfg(target_os = "linux")] Some("host-access") => Some(Command::HostAccess(&args[1..])), #[cfg(unix)] @@ -233,26 +282,27 @@ impl<'a> Command<'a> { Some("pull") => Some(Command::RawPull(&args[2..])), Some("images") => Some(Command::RawImages(&args[2..])), Some("rmi") => Some(Command::RawRmi(&args[2..])), - _ => None, + Some("-h" | "--help" | "help") => Some(Command::RawHelp), + _ => Some(Command::RawInvalid), }, #[cfg(target_os = "macos")] Some("bench") => Some(Command::Bench(&args[1..])), #[cfg(target_os = "macos")] Some("boot") => Some(Command::Boot(&args[1..])), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some("setup") => Some(Command::Setup(&args[1..])), #[cfg(any(unix, windows))] Some("share") => Some(Command::Share(&args[1..])), // `kiri 3000`: share a port straight away. #[cfg(any(unix, windows))] Some(a) if share::is_shorthand(a) => Some(Command::Share(args)), - // Bare: the window's Start (`kiri start NAME` is docker's start). + // Bare (or `-h`/`--help`): the window's Start (`kiri start NAME` is docker's start). #[cfg(unix)] - Some("start") if args.len() == 1 => Some(Command::Start), + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(&args[1..])), // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. #[cfg(windows)] - Some("start") if args.len() == 1 => Some(Command::Start(args)), - #[cfg(unix)] + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(args)), + #[cfg(any(unix, windows))] Some("build-with") => Some(Command::BuildWith(&args[1..])), #[cfg(unix)] Some("domains") => Some(Command::Domains(&args[1..])), @@ -270,7 +320,7 @@ impl<'a> Command<'a> { Some("machine") => Some(Command::Machine(&args[1..])), #[cfg(unix)] Some("usb") => Some(Command::Usb(&args[1..])), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some("import") => Some(Command::Import(&args[1..])), #[cfg(target_os = "macos")] Some("vm") => Some(Command::Vm(&args[1..])), @@ -293,27 +343,76 @@ impl<'a> Command<'a> { fn main() -> ExitCode { flavor::init(); let args: Vec = std::env::args().skip(1).collect(); + let parsed = Command::parse(&args); + match parsed { + Some(Command::Help) => { + println!("{}", usage()); + return ExitCode::SUCCESS; + } + Some(Command::Version) => { + println!("kiri {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + _ => {} + } // Which process this is, for its log and crash reports. #[cfg(unix)] - diag::init(match args.first().map(String::as_str) { - Some("daemon") => diag::Part::Daemon, - // Only a build with the window: elsewhere `kiri ui` is a plain - // command whose message must reach the terminal, not the log's pipe. - #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some("ui") => diag::Part::Ui, - #[cfg(target_os = "macos")] - None if setup::launched_from_app() => diag::Part::Ui, - _ => diag::Part::Cli, - }); - let result: std::io::Result<()> = match Command::parse(&args) { + { + let asking_help = args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.get(1).map(String::as_str), Some("help")); + diag::init(match args.first().map(String::as_str) { + Some("daemon") if !asking_help && args.len() == 1 => diag::Part::Daemon, + // Only a build with the window: elsewhere `kiri ui` is a plain + // command whose message must reach the terminal, not the log's pipe. + #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] + Some("ui") if !asking_help => diag::Part::Ui, + #[cfg(target_os = "macos")] + None if setup::launched_from_app() => diag::Part::Ui, + _ => diag::Part::Cli, + }); + } + let result: std::io::Result<()> = match parsed { + Some(Command::Help | Command::Version) => unreachable!(), #[cfg(unix)] - Some(Command::Daemon(rest)) => daemon::run(rest), + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{DAEMON_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, DAEMON_USAGE)) + } else { + daemon::run(rest) + } + } #[cfg(windows)] - Some(Command::Daemon) => Err(std::io::Error::other(WINDOWS_DAEMON_ERROR)), + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{START_USAGE}"); + Ok(()) + } else { + Err(std::io::Error::other(WINDOWS_DAEMON_ERROR)) + } + } #[cfg(target_os = "linux")] Some(Command::Bridge(rest)) => bridge::run(rest), #[cfg(target_os = "linux")] - Some(Command::HostRelay) => hostrelay::run(), + Some(Command::HostRelay(rest)) => { + const HOSTRELAY_USAGE: &str = "usage: kiri hostrelay"; + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{HOSTRELAY_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, HOSTRELAY_USAGE)) + } else { + hostrelay::run() + } + } // Linux hosts: what the window's onboarding needs root for (through pkexec). #[cfg(target_os = "linux")] Some(Command::HostAccess(rest)) => match hostaccess::run(rest) { @@ -321,6 +420,13 @@ fn main() -> ExitCode { Err(e) => Err(e), }, #[cfg(unix)] + Some(Command::RawHelp) => { + println!("{RAW_USAGE}"); + Ok(()) + } + #[cfg(unix)] + Some(Command::RawInvalid) => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, RAW_USAGE)), + #[cfg(unix)] Some(Command::RawRun(rest)) => run::run(rest), #[cfg(unix)] Some(Command::RawPull(rest)) => images::pull(rest), @@ -334,13 +440,22 @@ fn main() -> ExitCode { Some(Command::Boot(rest)) => boot::run(rest), #[cfg(target_os = "macos")] Some(Command::Setup(rest)) => setup::run(rest), + #[cfg(windows)] + Some(Command::Setup(rest)) => setup_win::run(rest), #[cfg(any(unix, windows))] Some(Command::Share(rest)) => share::run(rest), #[cfg(unix)] - Some(Command::Start) => engine_start(), + Some(Command::Start(rest)) => { + if !rest.is_empty() { + println!("{START_USAGE}"); + Ok(()) + } else { + engine_start() + } + } #[cfg(windows)] Some(Command::Start(all)) => wsl::run(all), - #[cfg(unix)] + #[cfg(any(unix, windows))] Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] Some(Command::Domains(rest)) => domains_cli::run(rest), @@ -358,7 +473,7 @@ fn main() -> ExitCode { Some(Command::Machine(rest)) => machine::run(rest), #[cfg(unix)] Some(Command::Usb(rest)) => usb::run(rest), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some(Command::Import(rest)) => import::run(rest), #[cfg(target_os = "macos")] Some(Command::Vm(rest)) => vm_cli::run(rest), @@ -367,13 +482,24 @@ fn main() -> ExitCode { #[cfg(unix)] Some(Command::Diag(rest)) => diag::run(rest), #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some(Command::Ui(all)) => ui::run( - all.iter().any(|a| a == "--start"), - all.iter().position(|a| a == "--view").and_then(|i| all.get(i + 1)).cloned(), - ), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some((start, view))) => ui::run(start, view), + Err(e) => Err(e), + }, // The static engine has no window: the package's own build of it. #[cfg(all(target_os = "linux", not(feature = "window")))] - Some(Command::Ui(all)) => window(all), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some(_)) => window(all), + Err(e) => Err(e), + }, #[cfg(any(unix, windows))] Some(Command::Docker(all)) => { engine_version_check(); @@ -545,7 +671,14 @@ mod tests { } #[cfg(windows)] { - for unix_or_mac in ["daemon", "bridge", "ui", "setup", "build-with", "update", "vm", "import", "bench", "boot", "raw"] { + for win_cmd in ["setup", "build-with", "import"] { + assert!(cmds.contains(&win_cmd), "Windows help missing `{win_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri import [desktop-linux] [--images] [--volumes] [--containers]"), + "Windows help missing `kiri import [desktop-linux] [--images] [--volumes] [--containers]`:\n{help}" + ); + for unix_or_mac in ["daemon", "bridge", "ui", "update", "vm", "bench", "boot", "raw"] { assert!(!cmds.contains(&unix_or_mac), "Windows help must not list `{unix_or_mac}`:\n{help}"); } } @@ -596,8 +729,28 @@ mod tests { } } assert!(count > 0); - assert!(parse(&["--help"]).is_none()); - assert!(parse(&["-h"]).is_none()); + for h in ["--help", "-h", "help"] { + assert_eq!(Command::parse(&[h.to_owned()]), Some(Command::Help), "{h}"); + } + for v in ["--version", "-V", "-v"] { + assert_eq!(Command::parse(&[v.to_owned()]), Some(Command::Version), "{v}"); + } + // `kiri version` (without leading dash) remains Docker's `version` passthrough. + assert!(matches!(Command::parse(&["version".to_owned()]), Some(Command::Docker(_)))); + // `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(&["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(_)))); + + #[cfg(unix)] + { + assert_eq!(Command::parse(&["raw".to_owned(), "--help".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned(), "-h".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned()]), Some(Command::RawInvalid)); + } + #[cfg(any(target_os = "macos", target_os = "linux"))] for args in [ vec!["update".to_owned()], @@ -617,15 +770,153 @@ mod tests { } #[cfg(windows)] { - for unix_cmd in ["bridge", "ui", "setup", "build-with", "vm", "import", "bench", "boot", "raw"] { + for unix_cmd in ["bridge", "ui", "vm", "bench", "boot", "raw"] { assert!(parse(&[unix_cmd]).is_none(), "`kiri {unix_cmd}` should not dispatch on Windows"); } + for win_cmd in ["setup", "build-with", "import"] { + assert!(parse(&[win_cmd]).is_some(), "`kiri {win_cmd}` must dispatch on Windows"); + } let daemon_args = ["daemon".to_owned()]; - assert_eq!(Command::parse(&daemon_args), Some(Command::Daemon)); + assert_eq!(Command::parse(&daemon_args), Some(Command::Daemon(&[]))); } assert_eq!( super::WINDOWS_DAEMON_ERROR, "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri" ); } + + #[test] + fn parse_ui_args_handles_help_views_and_invalid_flags() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert_eq!(super::parse_ui_args(&s(&["--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["-h"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["--start", "--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&[])).unwrap(), Some((false, None))); + assert_eq!( + super::parse_ui_args(&s(&["--start", "--view", "containers"])).unwrap(), + Some((true, Some("containers".into()))) + ); + assert!(super::parse_ui_args(&s(&["--view"])).is_err()); + assert!(super::parse_ui_args(&s(&["--bogus"])).is_err()); + } + + #[test] + fn cli_help_and_version_exit_zero_on_stdout_without_side_effects() { + let Some(bin) = option_env!("CARGO_BIN_EXE_kiri").map(std::path::PathBuf::from).or_else(|| { + // In `cargo test --bin kiri`, the `kiri` binary sits in the parent of `deps/`. + let test_exe = std::env::current_exe().ok()?; + let dir = test_exe.parent()?.parent()?; + let name = if cfg!(windows) { "kiri.exe" } else { "kiri" }; + Some(dir.join(name)).filter(|p| p.is_file()) + }) else { + return; + }; + let run_kiri = |args: &[&str]| { + std::process::Command::new(&bin) + .args(args) + .env("KIRI_SOCKET", "/nonexistent/kiri-test.sock") + .output() + .expect("spawn kiri") + }; + + // Bare `kiri` prints usage to stderr and exits 1. + let bare = run_kiri(&[]); + assert!(!bare.status.success()); + assert!(bare.stdout.is_empty()); + assert!(String::from_utf8_lossy(&bare.stderr).starts_with("usage: kiri COMMAND")); + + // Top-level help flags print usage to stdout and exit 0. + for flag in ["--help", "-h", "help"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed: {:?}", String::from_utf8_lossy(&out.stderr)); + assert!(out.stderr.is_empty(), "`kiri {flag}` wrote stderr: {:?}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim_end(), usage()); + } + + // Top-level version flags print `kiri ` to stdout and exit 0. + for flag in ["--version", "-V", "-v"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed"); + assert!(out.stderr.is_empty()); + assert_eq!(String::from_utf8_lossy(&out.stdout), format!("kiri {}\n", env!("CARGO_PKG_VERSION"))); + } + + // Every Kiri subcommand prints usage to stdout and exits 0 on `--help` and `-h` with zero side effects. + let mut subcommands: Vec<&[&str]> = vec![ + &["daemon"], + &["start"], + &["share"], + &["3000"], + &["build-with"], + &["domains"], + &["doctor"], + &["storage"], + &["storage", "reclaim"], + &["registry"], + &["registry", "insecure"], + &["scan"], + &["k8s"], + &["k8s", "set"], + &["machine"], + &["machine", "create"], + &["machine", "shell"], + &["usb"], + &["usb", "attach"], + &["diag"], + &["diag", "logs"], + &["diag", "report"], + ]; + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + subcommands.extend([&["ui"][..], &["update"]]); + } + #[cfg(unix)] + { + subcommands.extend([ + &["raw"][..], + &["raw", "run"], + &["raw", "pull"], + &["raw", "images"], + &["raw", "rmi"], + ]); + } + #[cfg(any(target_os = "macos", windows))] + { + subcommands.extend([&["setup"][..], &["import"]]); + } + #[cfg(target_os = "macos")] + { + subcommands.extend([&["vm"][..], &["vm", "set"], &["bench"], &["boot"]]); + } + #[cfg(target_os = "linux")] + { + subcommands.extend([&["bridge"][..], &["hostrelay"], &["host-access"]]); + } + for sub in subcommands { + for flag in ["--help", "-h"] { + let mut argv: Vec<&str> = sub.to_vec(); + argv.push(flag); + let out = run_kiri(&argv); + assert!( + out.status.success(), + "`kiri {}` exited {:?}, stderr: {}", + argv.join(" "), + out.status.code(), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + out.stderr.is_empty(), + "`kiri {}` wrote unexpected stderr: {}", + argv.join(" "), + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + stdout.starts_with("usage: kiri "), + "`kiri {}` stdout did not start with usage: {stdout:?}", + argv.join(" ") + ); + } + } + } } diff --git a/crates/kiri/src/registry_cli.rs b/crates/kiri/src/registry_cli.rs index 913722bec..74432d17d 100644 --- a/crates/kiri/src/registry_cli.rs +++ b/crates/kiri/src/registry_cli.rs @@ -37,13 +37,15 @@ const INSECURE: &str = "insecure-registries"; const MIRRORS: &str = "registry-mirrors"; pub fn run(args: &[String]) -> io::Result<()> { - let json = args.iter().any(|a| a == "--json"); - let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); - let arg = |i: usize| args.get(i).map(String::as_str); - if matches!(arg(0), Some("-h" | "--help" | "help")) { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } + let json = args.iter().any(|a| a == "--json"); + let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); + let arg = |i: usize| args.get(i).map(String::as_str); if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); } diff --git a/crates/kiri/src/run.rs b/crates/kiri/src/run.rs index 77a8e8938..b86b2a51e 100644 --- a/crates/kiri/src/run.rs +++ b/crates/kiri/src/run.rs @@ -14,7 +14,7 @@ const USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w Containers get their own network namespace with only loopback for now (like docker run --network none); bridged networking comes next."; -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq, Eq)] struct Options { remove: bool, env: Vec, @@ -25,7 +25,7 @@ struct Options { command: Vec, } -fn parse(args: &[String]) -> io::Result { +fn parse(args: &[String]) -> io::Result> { let bad = |m: String| io::Error::new(io::ErrorKind::InvalidInput, format!("{m}\n\n{USAGE}")); let mut o = Options::default(); let mut it = args.iter(); @@ -43,7 +43,14 @@ fn parse(args: &[String]) -> io::Result { return Err(bad(format!("--network {v} is not supported yet; only none"))); } } - "-h" | "--help" => return Err(bad(String::new())), + "-h" | "--help" => return Ok(None), + "--" => { + if let Some(img) = it.next() { + o.image = img.clone(); + o.command = it.cloned().collect(); + } + break; + } s if s.starts_with('-') => return Err(bad(format!("unknown option {s}"))), _ => { o.image = a.clone(); @@ -55,7 +62,7 @@ fn parse(args: &[String]) -> io::Result { if o.image.is_empty() { return Err(bad("no image given".into())); } - Ok(o) + Ok(Some(o)) } /// Finds the image locally, pulling it first if needed, and holds every blob @@ -109,7 +116,10 @@ pub fn new_id() -> String { } pub fn run(args: &[String]) -> io::Result<()> { - let o = parse(args)?; + let Some(o) = parse(args)? else { + println!("{USAGE}"); + return Ok(()); + }; let t0 = Instant::now(); let store = Store::open(Store::default_root()?)?; let (image, _blob_pins) = image(&store, &o.image)?; @@ -163,3 +173,37 @@ pub fn run(args: &[String]) -> io::Result<()> { } std::process::exit(r.code); } + +#[cfg(test)] +mod tests { + use super::{Options, parse}; + + fn s(words: &[&str]) -> Vec { + words.iter().map(|w| (*w).to_owned()).collect() + } + + #[test] + fn help_before_image_returns_none_while_help_after_image_stays_in_command() { + assert_eq!(parse(&s(&["--help"])).unwrap(), None); + assert_eq!(parse(&s(&["-h"])).unwrap(), None); + assert_eq!(parse(&s(&["--rm", "--help"])).unwrap(), None); + + let with_cmd_help = parse(&s(&["--rm", "alpine:latest", "ls", "--help"])).unwrap().unwrap(); + assert!(with_cmd_help.remove); + assert_eq!(with_cmd_help.image, "alpine:latest"); + assert_eq!(with_cmd_help.command, s(&["ls", "--help"])); + + let direct_help = parse(&s(&["alpine", "--help"])).unwrap().unwrap(); + assert_eq!(direct_help.image, "alpine"); + assert_eq!(direct_help.command, s(&["--help"])); + + let double_dash = parse(&s(&["--", "alpine", "-h"])).unwrap().unwrap(); + assert_eq!( + double_dash, + Options { image: "alpine".into(), command: s(&["-h"]), ..Options::default() } + ); + + assert!(parse(&[]).is_err()); + assert!(parse(&s(&["--unknown", "alpine"])).is_err()); + } +} diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index 41e616dac..c98c3886a 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -170,7 +170,23 @@ fn step(what: &'static str) -> impl Fn(io::Error) -> io::Error { move |e| io::Error::new(e.kind(), format!("{what}: {e}")) } +const USAGE: &str = "usage: kiri setup [--use] [--no-agent] [--no-profiles] [--no-domains]\n kiri setup --domains | --docker-socket | --uninstall"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + for a in args { + if !matches!( + a.as_str(), + "--uninstall" | "--domains" | "--docker-socket" | "--use" | "--no-profiles" | "--no-agent" | "--no-domains" + ) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + } let flag = |f: &str| args.iter().any(|a| a == f); if flag("--uninstall") { return uninstall(); diff --git a/crates/kiri/src/setup_win.rs b/crates/kiri/src/setup_win.rs new file mode 100644 index 000000000..4b3266471 --- /dev/null +++ b/crates/kiri/src/setup_win.rs @@ -0,0 +1,310 @@ +//! `kiri setup` on Windows: ensures `%USERPROFILE%\.docker\config.json` has +//! Kiri's `cli-plugins` folder (`docker compose`, `docker buildx`), writes the +//! `kiri` Docker context (`npipe:////./pipe/kiri`), and sets `currentContext` +//! to `kiri` when `--use` is given or when `currentContext` is empty or points +//! at a removed engine such as `desktop-linux` after uninstalling Docker +//! Desktop (#984). + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::io; +use std::path::{Path, PathBuf}; + +use crate::dockerctx::{ + WindowsRepair, WindowsRepairOpts, find_windows_cli_plugins, repair_windows_config, +}; + +const USAGE: &str = "usage: kiri setup [--use]"; + +fn npipe_host(pipe: &str) -> String { + format!("npipe:{}", pipe.replace('\\', "/")) +} + +/// Best-effort background self-heal of `%USERPROFILE%\.docker\config.json` and +/// Kiri's `kiri` Docker context before invoking `docker.exe --context kiri` on +/// Windows (#984). +#[cfg(windows)] +pub fn heal_quietly() { + let Some(dir) = crate::dockerctx::docker_dir() else { + return; + }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + let host = npipe_host(&crate::client::pipe()); + let _ = repair_windows_config( + &dir, + WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut force_use = false; + for a in args { + match a.as_str() { + "--use" => force_use = true, + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let dir = + crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + #[cfg(windows)] + let host = npipe_host(&crate::client::pipe()); + #[cfg(not(windows))] + let host = "npipe:////./pipe/kiri".to_owned(); + + let mut out = Vec::new(); + run_in( + &dir, + &host, + plugins.as_deref(), + force_use, + desktop, + &mut out, + )?; + print!("{}", String::from_utf8_lossy(&out)); + + #[cfg(windows)] + if crate::client::alive() { + match crate::builds::builder() { + Ok(true) => match crate::buildwith::places().map(|p| p.saved()) { + Ok(Some(crate::buildwith::With::Kiri)) => { + println!( + "docker build uses BuildKit in Kiri (builder `{}`)", + crate::builds::BUILDER + ); + } + _ => println!( + "docker build follows docker's context, and builds on Kiri when docker uses Kiri (`kiri build-with kiri` sends every build to Kiri)" + ), + }, + Ok(false) => {} + Err(e) => println!( + "docker build: the `{}` builder comes later ({e})", + crate::builds::BUILDER + ), + } + } + Ok(()) +} + +fn run_in( + dir: &Path, + host: &str, + plugins: Option<&Path>, + force_use: bool, + desktop_installed: bool, + out: &mut impl io::Write, +) -> io::Result { + let ours = crate::flavor::CONTEXT.get(); + let r = repair_windows_config( + dir, + WindowsRepairOpts { + ours, + description: "Kiri (WSL2)", + host, + plugins_dir: plugins, + force_context_write: true, + set_current_if_empty: true, + force_use, + desktop_installed, + }, + )?; + writeln!(out, "docker context `{ours}` → {host}")?; + if r.current_context_set || force_use { + writeln!( + out, + "docker now uses Kiri by default (`docker context use default` to switch back)" + )?; + } + if let Some(p) = plugins { + writeln!(out, "docker cli-plugins → {}", p.display())?; + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dockerctx::{context_meta, read_json, write_context, write_json}; + use serde_json::json; + + fn scratch(tag: &str) -> PathBuf { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let d = std::env::temp_dir().join(format!( + "kiri-setup-win-{tag}-{}-{}", + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn help_and_invalid_flags_have_no_side_effects() { + for h in [&["--help"][..], &["-h"], &["help"], &["--use", "--help"]] { + let v: Vec = h.iter().map(|s| (*s).to_owned()).collect(); + run(&v).unwrap(); + } + for bad in [&["--bogus"][..], &["--uninstall"], &["extra"]] { + let v: Vec = bad.iter().map(|s| (*s).to_owned()).collect(); + let err = run(&v).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput); + assert_eq!(err.to_string(), USAGE); + } + } + + #[test] + fn repairs_wiped_docker_config_and_dangling_desktop_linux_context() { + let root = scratch("repair"); + let docker = root.join(".docker"); + let plugins = root.join("Kiri/bin/cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + + // 1. Fresh / wiped config.json after Docker Desktop uninstall: creates `kiri` context, + // registers cliPluginsExtraDirs, and sets currentContext = "kiri". + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { + context_written: true, + plugins_added: true, + current_context_set: true + } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + let meta = read_json(&context_meta(&docker, "kiri").join("meta.json")).unwrap(); + assert_eq!(meta["Endpoints"]["docker"]["Host"], "npipe:////./pipe/kiri"); + let printed = String::from_utf8(out).unwrap(); + assert!( + printed.contains("docker context `kiri` → npipe:////./pipe/kiri"), + "{printed}" + ); + assert!( + printed.contains("docker now uses Kiri by default"), + "{printed}" + ); + assert!(printed.contains("docker cli-plugins →"), "{printed}"); + + // 2. Existing config with logins and an active `desktop-linux` context while Docker Desktop + // is still installed: keeps `desktop-linux` without `--use`, switches with `--use`. + write_context( + &context_meta(&docker, "desktop-linux"), + "desktop-linux", + "Docker Desktop", + "npipe:////./pipe/dockerDesktopLinuxEngine", + ) + .unwrap(); + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "dG9rZW4="}}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + true, + &mut out, + ) + .unwrap(); + assert!(!r.current_context_set); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "desktop-linux"); + assert_eq!(cfg["auths"]["ghcr.io"]["auth"], "dG9rZW4="); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + + // Docker Desktop uninstalled (`desktop_installed = false`), leaving stale `desktop-linux`: + // `kiri setup` heals `currentContext` to `kiri` automatically! + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + // With Docker Desktop installed and `--use`: explicitly switches to `kiri`. + write_json( + &docker.join("config.json"), + &json!({"currentContext": "desktop-linux"}), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + true, + true, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri/src/share.rs b/crates/kiri/src/share.rs index ea854e4f2..009faf769 100644 --- a/crates/kiri/src/share.rs +++ b/crates/kiri/src/share.rs @@ -2043,8 +2043,14 @@ fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { } pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } match args.first().map(String::as_str) { - None | Some("-h" | "--help" | "help") => Err(io::Error::other(USAGE)), + None => Err(io::Error::other(USAGE)), Some("login") => login_cli(&args[1..]), Some("logout") => { logout()?; diff --git a/crates/kiri/src/usb.rs b/crates/kiri/src/usb.rs index 4507f3fc1..6085e95b5 100644 --- a/crates/kiri/src/usb.rs +++ b/crates/kiri/src/usb.rs @@ -29,6 +29,12 @@ const USAGE: &str = "usage: kiri usb [list [--json]] | attach DEVICE | detach DE DEVICE is a location (0x02114000), vendor:product (1532:00d7) or part of the name"; pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } match (args.first().map(String::as_str), args.get(1)) { // The window's own list: each device's key, name, id, state, paths… (None | Some("list" | "ls" | "--json"), _) if args.iter().any(|a| a == "--json") => list_json(), diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 42079ab3e..79ffac731 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -294,8 +294,63 @@ fn wake_via_pipe(_pipe_name: &str) -> Option> { None } +/// Usage text for WSL-forwarded commands when `-h` / `--help` is passed on +/// Windows, so asking for help never wakes WSL or executes side effects (#982). +/// For `kiri machine shell NAME -- --help`, stops scanning at `--` so +/// `--help` meant for the container command passes through untouched. +pub(crate) fn help_for(args: &[String]) -> Option<&'static str> { + let cmd = args.first()?.as_str(); + let sub = &args[1..]; + let scan_end = if cmd == "machine" && sub.first().map(String::as_str) == Some("shell") { + sub.iter().position(|a| a == "--").unwrap_or(sub.len()) + } else { + sub.len() + }; + let has_flag = sub[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")); + let help_word = sub.first().map(String::as_str) == Some("help") + && matches!(cmd, "k8s" | "machine" | "diag" | "usb" | "domains" | "registry" | "storage"); + if !has_flag && !help_word { + return None; + } + match cmd { + "start" => Some("usage: kiri start start Kiri after a Stop (the window's Start)"), + "k8s" if sub.first().map(String::as_str) == Some("set") => Some( + "usage: kiri k8s set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]", + ), + "k8s" => Some( + "usage: kiri k8s start [--use] | stop | status [--json] | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]", + ), + "machine" => Some( + "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME", + ), + "diag" => Some( + "usage: kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [--op ID] [-n N]\n kiri diag report [--out PATH] [--send]", + ), + "usb" => Some( + "usage: kiri usb [list [--json]] | attach DEVICE | detach DEVICE\n DEVICE is a location (0x02114000), vendor:product (1532:00d7) or part of the name", + ), + "domains" => Some( + "usage: kiri domains the routers' ports, and whether each runs\n kiri domains set [--http N] [--https N] move them (no restart)\n kiri domains reset back to the ports a start gives (a test copy's: off)\n --json, with any of them, prints the engine's answer as one line of JSON", + ), + "registry" => Some( + "usage: kiri registry both lists and the file they are in\n kiri registry insecure [list] | add HOST... | remove HOST...\n kiri registry mirror [list] | add URL... | remove URL...\n --json, with any of them: one line of JSON", + ), + "scan" => Some( + "usage: kiri scan [--json] [--history] \n --json the full report, as JSON\n --history the image's kept scans, newest first, without scanning again", + ), + "storage" => Some( + "usage: kiri storage [status] show storage location, disk usage, and reclaimable space\n kiri storage reclaim reclaim unused VM disk space back to the host", + ), + _ => None, + } +} + /// Runs `kiri ` in WSL and exits with its exit code. pub fn run(args: &[String]) -> io::Result<()> { + if let Some(help) = help_for(args) { + println!("{help}"); + return Ok(()); + } if let [m, verb, name, rest @ ..] = args && m == "machine" && verb == "shell" @@ -508,4 +563,50 @@ mod tests { assert_eq!(parse_diag_report_args(&s(&["--out"])), None); assert_eq!(parse_diag_report_args(&s(&["--unknown"])), None); } + + #[test] + fn help_for_intercepts_wsl_commands_without_intercepting_container_help() { + use super::help_for; + let s = |list: &[&str]| list.iter().map(|x| (*x).to_owned()).collect::>(); + for cmd in [ + &["start", "--help"][..], + &["start", "-h"], + &["k8s", "--help"], + &["k8s", "-h"], + &["k8s", "help"], + &["k8s", "set", "--help"], + &["machine", "--help"], + &["machine", "create", "-h"], + &["machine", "shell", "--help"], + &["machine", "shell", "dev", "--help"], + &["diag", "--help"], + &["diag", "report", "--help"], + &["diag", "logs", "-h"], + &["usb", "--help"], + &["usb", "attach", "-h"], + &["domains", "--help"], + &["registry", "--help"], + &["scan", "--help"], + &["storage", "--help"], + &["storage", "reclaim", "-h"], + ] { + let text = help_for(&s(cmd)).unwrap_or_else(|| panic!("expected help for {cmd:?}")); + assert!(text.starts_with("usage: kiri "), "{cmd:?}: {text}"); + } + assert!(help_for(&s(&["k8s", "set", "--help"])).unwrap().contains("kiri k8s set")); + + // Must NOT intercept container commands after `--` or non-help invocations. + for pass_through in [ + &["start"][..], + &["k8s", "status"], + &["machine", "list"], + &["machine", "shell", "dev", "--", "uname", "--help"], + &["machine", "shell", "dev", "--", "-h"], + &["scan", "alpine"], + &["scan", "help"], + &["diag", "report"], + ] { + assert_eq!(help_for(&s(pass_through)), None, "must not intercept {pass_through:?}"); + } + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 2d72f27cb..ca598cdfa 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -43,6 +43,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug - Caused by: - - Check: `tests/ui/volumes-size.js`, `crates/kiri/src/daemon/ops.rs` +### #982, #984 CLI & Windows: exit 0 without side effects on `--help` / `-h` and `--version` / `-V` / `-v`, enable Windows `kiri import` / `setup` / `build-with`, self-heal `~/.docker/config.json`, and allow `runkiri.com` / `canestack.com` About links (unreleased) +- Fixes: #982 `--help` / `-h` executes commands instead of printing usage, #984 Windows 0.2.2: `kiri import` missing from Windows CLI, uninstalling Docker Desktop wipes `~/.docker/config.json`, and `kiri setup` / `kiri build-with` / `kiri --version` fail +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/main.rs`, `crates/kiri/src/setup_win.rs`, `crates/kiri/src/dockerctx.rs`, `crates/kiri-win/src/engine.rs` + ### #932 Networking: return `NODATA` for external `AAAA` queries on IPv4-only networks and relay enterprise macOS VPN tunnels through the host (unreleased) - Fixes: #932 Containers and the Kubernetes node fail to reach Docker Hub with IPv6 `Network unreachable` and `TLS handshake timeout` under macOS VPN / packet-tunnel extensions - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 2cd199e95..148531385 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -364,6 +364,8 @@ 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-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 crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit From f59e53ebce76b9c7cc4f20cf584c5dfa0a8ea85b Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:18:52 +0100 Subject: [PATCH 153/157] UI: allowlist Discord and X community links across macOS, Linux, and Windows --- crates/kiri-win/src/engine.rs | 4 ++++ crates/kiri/src/ui/mod.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index deed95313..51f9e83a6 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -1210,6 +1210,8 @@ fn allowed_url(url: &str) -> bool { | "https://runkiri.com/releases/" | "https://runkiri.com/share/notice" | "https://canestack.com" + | "https://discord.gg/K5A8wuqcC" + | "https://x.com/runkiri" | "https://learn.microsoft.com/windows/wsl/about" | "https://github.com/libracoder/kiri/issues/new" | "https://github.com/libracoder/kiri" @@ -1297,6 +1299,8 @@ mod tests { assert!(allowed_url("https://runkiri.com/releases/")); assert!(allowed_url("https://runkiri.com/share/notice")); assert!(allowed_url("https://canestack.com")); + assert!(allowed_url("https://discord.gg/K5A8wuqcC")); + assert!(allowed_url("https://x.com/runkiri")); assert!(allowed_url("https://kiri.canestack.com")); assert!(allowed_url("https://github.com/libracoder/kiri")); assert!(allowed_url("https://github.com/libracoder/kiri/issues/new")); diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index 18e3dd92a..fe636625a 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -2856,7 +2856,7 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { let local = msg.name.strip_prefix("http://").or_else(|| msg.name.strip_prefix("https://")).and_then(|r| r.split(['/', ':']).next()).is_some_and(|h| h == "localhost" || h.ends_with(".kiri.localhost") || h.ends_with(".kiri.local")); // A build warning's rule page (docs.docker.com/go/dockerfile/rule/…). let docs = msg.name.strip_prefix("https://docs.docker.com/go/").is_some_and(|rest| rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"-/".contains(&b))); - if local || docs || msg.name == "https://runkiri.com" || msg.name == "https://runkiri.com/share/notice" || msg.name == "https://canestack.com" || msg.name == "https://github.com/libracoder/kiri/issues/new" || msg.name == "https://github.com/libracoder/kiri" || msg.name == "https://github.com/anchore/grype" || msg.name == "https://login.docker.com/activate" || msg.name == "https://github.com/login/device" { + if local || docs || msg.name == "https://runkiri.com" || msg.name == "https://runkiri.com/releases/" || msg.name == "https://runkiri.com/share/notice" || msg.name == "https://canestack.com" || msg.name == "https://discord.gg/K5A8wuqcC" || msg.name == "https://x.com/runkiri" || msg.name == "https://github.com/libracoder/kiri/issues/new" || msg.name == "https://github.com/libracoder/kiri" || msg.name == "https://github.com/anchore/grype" || msg.name == "https://login.docker.com/activate" || msg.name == "https://github.com/login/device" { open(&msg.name); } Ok(()) From 28276ba2d14f1b5b650860cabf592411bd00b08e Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 12:46:23 +0100 Subject: [PATCH 154/157] =?UTF-8?q?UI:=20Settings=20=E2=86=92=20Appearance?= =?UTF-8?q?=20=E2=80=94=20Uzbek=20(O=CA=BBzbekcha)=20and=20Nepali=20(?= =?UTF-8?q?=E0=A4=A8=E0=A5=87=E0=A4=AA=E0=A4=BE=E0=A4=B2=E0=A5=80)=20(#568?= =?UTF-8?q?,=20#538)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kiri's window, menus and Windows setup now come in Uzbek (Oʻzbekcha, in standard official Uzbek Latin) and Nepali (नेपाली), bringing Kiri to 40 languages (39 translation files, 2,037 keys each). - lang/uz.json: all 2,037 keys in official Uzbek Latin (Oʻ/oʻ, Gʻ/gʻ with U+02BB, tutuq belgisi U+02BC, Sh/sh, Ch/ch). - lang/ne.json: all 2,037 keys in everyday Nepali developer register, with Noto Sans Devanagari first in index.html and Nirmala UI in setup.html. - lang.rs & langstep.js: uz (uz, uz-UZ, uz-Latn-UZ, uz_UZ) and ne (ne, ne-NP, ne_NP) resolution, native names, greetings and Uzbek search aliases. - UI tests & README: updated for 40 languages. Co-authored-by: Behruz Bahodirov Co-authored-by: sundarshahi --- README.md | 4 +- crates/kiri-win/src/setup.html | 2 +- crates/kiri/src/ui/index.html | 1 + crates/kiri/src/ui/lang.rs | 11 +- crates/kiri/src/ui/lang/ne.json | 2039 +++++++++++++++++++++++++++++++ crates/kiri/src/ui/lang/uz.json | 2039 +++++++++++++++++++++++++++++++ crates/kiri/src/ui/langstep.js | 12 +- tests/ui/langpick.js | 6 +- tests/ui/langstep.js | 14 +- tests/ui/langswitch.js | 12 +- tests/ui/nav-beta-tag.js | 2 +- tests/ui/setup-langstep.js | 6 +- 12 files changed, 4120 insertions(+), 28 deletions(-) create mode 100644 crates/kiri/src/ui/lang/ne.json create mode 100644 crates/kiri/src/ui/lang/uz.json diff --git a/README.md b/README.md index d7d3080d7..60c359be7 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Latest release Apache 2.0 License Discord - 38 languages + 40 languages

@@ -103,7 +103,7 @@ comes from the Igbo word *ntakịrị*, "small". - **Local domains**: `http://.kiri.local`, with HTTPS from Kiri's own certificate authority. - **More than containers**: a one-command Kubernetes cluster and Linux machines. - **A native window** for containers, images, volumes and networks, plus a menu bar item. -- **In your language**: the window comes in 38 languages, on macOS, Windows and Linux alike. +- **In your language**: the window comes in 40 languages, on macOS, Windows and Linux alike. --- diff --git a/crates/kiri-win/src/setup.html b/crates/kiri-win/src/setup.html index 63b960564..213f19572 100644 --- a/crates/kiri-win/src/setup.html +++ b/crates/kiri-win/src/setup.html @@ -30,7 +30,7 @@ /* India's scripts in Nirmala UI, Windows' face for them; Thai and Lao in Leelawadee UI; Ethiopic in Ebrima. */ [lang|=am]{--f-text:"Segoe UI Variable Text","Segoe UI","Ebrima","Nyala",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Ebrima","Nyala",sans-serif} [lang|=th],[lang|=lo]{--f-text:"Segoe UI Variable Text","Segoe UI","Leelawadee UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Leelawadee UI",sans-serif} -[lang|=hi],[lang|=bn],[lang|=ta],[lang|=te]{--f-text:"Segoe UI Variable Text","Segoe UI","Nirmala UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Nirmala UI",sans-serif} +[lang|=hi],[lang|=ne],[lang|=bn],[lang|=ta],[lang|=te]{--f-text:"Segoe UI Variable Text","Segoe UI","Nirmala UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Nirmala UI",sans-serif} *{box-sizing:border-box} html,body{margin:0;height:100%;background:var(--bg)} body{color:var(--ink);font:15px/1.4 var(--f-text);overflow:hidden;-webkit-font-smoothing:antialiased} diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index df1611a16..9791bc0d3 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -2810,6 +2810,7 @@

Containers

.json maps /// English to it. English itself has no file. -pub const FILES: [(&str, &str); 37] = [ +pub const FILES: [(&str, &str); 39] = [ ("id", include_str!("lang/id.json")), ("ca", include_str!("lang/ca.json")), ("cs", include_str!("lang/cs.json")), @@ -32,6 +32,7 @@ pub const FILES: [(&str, &str); 37] = [ ("lt", include_str!("lang/lt.json")), ("hu", include_str!("lang/hu.json")), ("nb", include_str!("lang/nb.json")), + ("uz", include_str!("lang/uz.json")), ("pl", include_str!("lang/pl.json")), ("pt-BR", include_str!("lang/pt-BR.json")), ("ro", include_str!("lang/ro.json")), @@ -50,6 +51,7 @@ pub const FILES: [(&str, &str); 37] = [ ("ckb", include_str!("lang/ckb.json")), ("am", include_str!("lang/am.json")), ("hi", include_str!("lang/hi.json")), + ("ne", include_str!("lang/ne.json")), ("bn", include_str!("lang/bn.json")), ("ta", include_str!("lang/ta.json")), ("te", include_str!("lang/te.json")), @@ -384,6 +386,9 @@ mod tests { ("arz", None), ("hi", Some("hi")), ("hi-IN", Some("hi")), + ("ne", Some("ne")), + ("ne-NP", Some("ne")), + ("ne_NP", Some("ne")), ("bn-IN", Some("bn")), ("bn-BD", Some("bn")), ("ta-IN", Some("ta")), @@ -403,6 +408,10 @@ mod tests { ("el-GR", Some("el")), ("bg-BG", Some("bg")), ("kk-KZ", Some("kk")), + ("uz", Some("uz")), + ("uz-UZ", Some("uz")), + ("uz-Latn-UZ", Some("uz")), + ("uz_UZ", Some("uz")), ("fa-IR", Some("fa")), ("fa", Some("fa")), ("ckb", Some("ckb")), diff --git a/crates/kiri/src/ui/lang/ne.json b/crates/kiri/src/ui/lang/ne.json new file mode 100644 index 000000000..5a2c2d2d9 --- /dev/null +++ b/crates/kiri/src/ui/lang/ne.json @@ -0,0 +1,2039 @@ +{ + " (current step)": " (अहिलेको चरण)", + " (done)": " (सकियो)", + " ({port} was in use)": " ({port} प्रयोगमा थियो)", + " That's {count} crashes since Kiri last opened.": " Kiri पछिल्लो पटक खुलेयता {count} पटक क्र्यास भयो।", + " and ": " र ", + " or ": " वा ", + "(no description)": "(विवरण छैन)", + "(no message)": "(कुनै सन्देश छैन)", + "(read-only)": "(पढ्न मात्र)", + "(was {value})": "(पहिले {value})", + "* Estimates until measured on a clean PC.": "* सफा PC मा नापिएसम्म अनुमान मात्र।", + "+ A complete Linux you can open from Start": "+ Start बाट खोल्न मिल्ने पूरा Linux", + "+ Already have Ubuntu? Kiri uses it: nothing to download": "+ Ubuntu पहिल्यै छ? Kiri ले त्यही प्रयोग गर्छ: केही डाउनलोड गर्नु पर्दैन", + "+ No Microsoft Store, no username or password": "+ Microsoft Store चाहिँदैन, युजरनेम वा पासवर्ड पनि चाहिँदैन", + "+ Removed completely when you remove Kiri": "+ Kiri हटाउँदा पूरै हट्छ", + "+ Uses the Ubuntu you already have: nothing to download": "+ तपाईंसँग भएकै Ubuntu प्रयोग गर्छ: केही डाउनलोड गर्नु पर्दैन", + "+{n} more": "+{n} थप", + ", ": ", ", + "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Kiri मा बिल्ड गर्नुहोस्। docker build र docker compose build Kiri मा चल्छन्, र इमेजहरू Kiri मा हुन्छन्। {engine} ले ती देख्दैन। सेटिङ → बिल्डमा जुनसुकै बेला बदल्न सक्नुहुन्छ।", + "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Docker मै बिल्ड गरिरहनुहोस्। केही बदलिँदैन: docker build अहिले जहाँ बिल्ड गर्छ त्यहीँ गर्छ, र इमेजहरू {engine} मै रहन्छन्।", + "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "जस्ताको तस्तै: कन्टेनर आफैं, यसका फाइल, इमेज, पोर्ट, भोल्युम, नेटवर्क र रिस्टार्ट नीति।", + "docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.": "docker ले अझै {engine} नै प्रयोग गर्छ, त्यसैले टर्मिनलमा चलाएको कुरा यहाँ देखिँदैन। तपाईंका इमेजहरू पनि यता ल्याउन सकिन्छ।", + "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node kind को node इमेज हो, kind चाहिँ Docker मा Kubernetes चलाउने टुल हो। kind ले यसलाई privileged मोड र चाहिने सेटिङसहित आफैं सुरु गर्छ। आफैं सुरु गर्दा यो यही {mount} मा रोकिन्छ।", + "{name} has {list} that aren't in Kiri yet.": "{name} मा {list} छन् जुन अझै Kiri मा छैनन्।", + "{name} isn't answering on {addr}, so visitors get an error page. Is the app inside it running?": "{name} ले जवाफ दिइरहेको छैन {addr} मा, त्यसैले भिजिटरले एरर पेज पाउँछन्। यसभित्रको एप चलिरहेको छ?", + "{name} isn't answering, so visitors get an error page. Is the app inside it running?": "{name} ले जवाफ दिइरहेको छैन, त्यसैले भिजिटरले एरर पेज पाउँछन्। यसभित्रको एप चलिरहेको छ?", + "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "यीमध्ये कुनै पोर्ट पब्लिस गर्ने कन्टेनरले त्यो पोर्ट पाउँछ; उसले नछोडेसम्म त्यो पोर्टका नामहरू रोकिन्छन्।", + "A couple more steps: set them up, or skip.": "केही चरण बाँकी: सेटअप गर्नुहोस् वा छोड्नुहोस्।", + "A deployment (its ReplicaSet)": "एउटा डिप्लोयमेन्ट (यसको ReplicaSet)", + "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri मा राखिएको डिभाइस तपाईंले निकाल्नुभएसम्म Windows मा देखिँदैन। कन्टेनरमा: --device /dev/ttyUSB0 (serial), /dev/input (HID) वा /dev/bus/usb (raw)।", + "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri मा राखिएको डिभाइस तपाईंले निकाल्नुभएसम्म Mac मा देखिँदैन। कन्टेनरमा: --device /dev/ttyUSB0 (serial), /dev/input (HID) वा /dev/bus/usb (raw)।", + "A few things need fixing before Kiri can run containers.": "Kiri ले कन्टेनर चलाउनुअघि केही कुरा मिलाउनुपर्छ।", + "A kiri command": "kiri कमान्ड", + "A kiri command crashed": "एउटा kiri कमान्ड क्र्यास भयो", + "A proxy on this Mac is reached as {host}.": "यो Mac को प्रोक्सी {host} बाट पुगिन्छ।", + "A service sends traffic to this pod": "एउटा सर्भिसले यो पोडमा ट्राफिक पठाउँछ", + "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "kubectl को {context} context का लागि एउटै कन्टेनरमा एउटै नोडको क्लस्टर (k3s)। अफ गर्दा यो रोकिन्छ र यसको अवस्था राखिन्छ।", + "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "एउटै कन्टेनरमा एउटै नोडको क्लस्टर (k3s)। करिब 20 सेकेन्ड लाग्छ, पहिलो पटक k3s डाउनलोड हुँदा बढी।", + "A small, fast container runtime.": "सानो र छिटो कन्टेनर रनटाइम।", + "A tiny Linux made only for Kiri, built from Alpine. It stays out of sight and leaves with Kiri.": "Kiri का लागि मात्र बनेको सानो Linux, Alpine बाट बनाइएको। यो लुकेर बस्छ र Kiri हटाउँदा सँगै जान्छ।", + "API on {addr}": "API {addr} मा", + "API server": "API सर्भर", + "API server port": "API सर्भर पोर्ट", + "AWS didn't accept that code. Wait for the next one and try again.": "AWS ले त्यो कोड मानेन। अर्को कोड आउन पर्खेर फेरि गर्नुहोस्।", + "AWS profile": "AWS प्रोफाइल", + "About": "बारेमा", + "Accent": "एक्सेन्ट रङ", + "Accept the SQL Server licence": "SQL Server को लाइसेन्स स्वीकार गर्नुहोस्", + "Access token": "एक्सेस टोकन", + "Access token or password": "एक्सेस टोकन वा पासवर्ड", + "Action {op}": "काम {op}", + "Actions": "कामहरू", + "Actual Size": "असली साइज", + "Add": "थप्नुहोस्", + "Add it to WSL": "यसलाई WSL मा थप्ने", + "Add port": "पोर्ट थप्नुहोस्", + "Added by this build": "यो बिल्डले थपेको", + "Added in this image": "यो इमेजमा थपिएको", + "Additional certificate names": "सर्टिफिकेटका थप नाम", + "Administrator approval": "एडमिनको स्वीकृति", + "After the restart": "रिस्टार्टपछि", + "Age": "उमेर", + "All": "सबै", + "All languages · {n}": "सबै भाषा · {n}", + "All levels": "सबै लेभल", + "All statuses": "सबै स्टेटस", + "All steps": "सबै स्टेप", + "All {kind}": "सबै {kind}", + "Allow access": "एक्सेस दिनुहोस्", + "Allow an empty password": "खाली पासवर्ड चल्न दिनुहोस्", + "Already there": "पहिल्यै छ", + "Always send crash reports": "क्र्यास रिपोर्ट सधैं पठाउने", + "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR ले पासवर्ड होइन, टोकन लिन्छ: युजरनेम {user} हो र टोकन {cmd} बाट आउँछ। यो 12 घण्टा चल्छ।", + "Anchore, open source": "Anchore को, ओपन सोर्स", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "त्यसयता {build} का लागि अर्कै बिल्डर छानिएको छ ({use})। Kiri मा बिल्ड गर्न फेरि Kiri छान्नुहोस्।", + "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "अर्को प्रोग्रामले 127.0.0.1:53 ओगटेको छ, त्यसैले Kiri ले .kiri.local मा जवाफ दिन सक्दैन; कन्टेनरहरू .kiri.localhost मै रहन्छन्", + "Answers on /run/kiri/docker.sock": "/run/kiri/docker.sock मा जवाफ दिन्छ", + "Anyone who can reach the port signs in as root.": "पोर्टसम्म पुग्ने जो कोही पनि root भएर साइन इन हुन्छ।", + "Anyone with this link can open it while Kiri is running.": "Kiri चलिरहँदा यो लिङ्क भएका जो कोहीले यसलाई खोल्न सक्छन्।", + "Appearance": "देखावट", + "Applies after you log out and back in": "लग आउट गरेर फेरि लग इन गरेपछि लागू हुन्छ", + "Apply…": "लागू गर्नुहोस्…", + "Asking {host} for {ref}…": "{host} सँग {ref} माग्दै…", + "Asks for your password once": "एक पटक पासवर्ड सोध्छ", + "Asleep": "स्लिपमा", + "Attach": "जोड्नुहोस्", + "Attach it to see where it shows up in Linux.": "Linux मा कहाँ देखिन्छ हेर्न यसलाई जोड्नुहोस्।", + "Attached": "जोडिएको", + "Attaching…": "जोड्दै…", + "Audio": "अडियो", + "Back": "पछाडि", + "Back (Esc)": "पछाडि (Esc)", + "Back to Share": "सेयरमा फर्कनुहोस्", + "Back to editing": "एडिटमा फर्कनुहोस्", + "Base image": "बेस इमेज", + "Beta": "बिटा", + "Bigger": "ठूलो", + "Blue": "निलो", + "Bring all my {engine} images to {app}": "मेरा सबै {engine} इमेज {app} मा ल्याउनुहोस्", + "Bring images, volumes and containers over to Kiri.": "इमेज, भोल्युम र कन्टेनर Kiri मा ल्याउनुहोस्।", + "Bring your {name} things to Kiri": "तपाईंका {name} का कुराहरू Kiri मा ल्याउनुहोस्", + "Bringing your images over from {engine}: {done} of {total}.": "{engine} बाट तपाईंका इमेज ल्याउँदै: {total} मध्ये {done}।", + "Brought {n} item over from {engine}.": "{engine} बाट {n} वटा ल्याइयो।", + "Brought {n} item over from {engine}; {failed} failed (Settings → Import says why).": "{engine} बाट {n} वटा ल्याइयो; {failed} वटा फेल भए (किन भनेर सेटिङ → इम्पोर्टमा हेर्नुहोस्)।", + "Brought {n} items over from {engine}.": "{engine} बाट {n} वटा ल्याइयो।", + "Brought {n} items over from {engine}; {failed} failed (Settings → Import says why).": "{engine} बाट {n} वटा ल्याइयो; {failed} वटा फेल भए (किन भनेर सेटिङ → इम्पोर्टमा हेर्नुहोस्)।", + "Browsers see a short Kiri Cloud notice page first.": "ब्राउजरले पहिले छोटो Kiri Cloud सूचना पेज देख्छ।", + "Build cache cleared": "बिल्ड क्यास खाली भयो", + "Build cache cleared: freed {size}": "बिल्ड क्यास खाली भयो: {size} खाली भयो", + "Build context": "बिल्ड context", + "Build record": "बिल्ड रेकर्ड", + "Build with": "बिल्ड गर्ने", + "Build with Kiri": "Kiri मा बिल्ड गर्नुहोस्", + "Build with Kiri.": "Kiri मा बिल्ड गर्नुहोस्।", + "BuildKit starts if it's asleep.": "BuildKit स्लिपमा भए सुरु हुन्छ।", + "BuildKit {size}": "BuildKit {size}", + "BuildKit {size} and its build cache": "BuildKit {size} र यसको बिल्ड क्यास", + "Building": "बिल्ड हुँदैछ", + "Builds": "बिल्ड", + "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build ले चलाएका बिल्ड यहाँ देखिन्छन्, हरेक स्टेपको समय, क्यास र आउटपुटसहित।", + "Built from source": "सोर्सबाट बिल्ड गरिएको", + "Bus {bus} · Device {dev}": "बस {bus} · डिभाइस {dev}", + "By name, no ports.": "नामबाट, पोर्ट चाहिँदैन।", + "By port. Nothing to set up.": "पोर्टबाट। केही सेटअप गर्नु पर्दैन।", + "Bypass for": "यिनमा प्रोक्सी नलगाउने", + "CLI": "CLI", + "CPU": "CPU", + "CPU is a share of all {n} cores: 100% would be every core busy.": "CPU सबै {n} कोरको हिस्सा हो: 100% भनेको सबै कोर व्यस्त।", + "CPUs": "CPU", + "Cached": "क्यासबाट", + "Camera": "क्यामेरा", + "Can't be shared": "सेयर गर्न मिल्दैन", + "Can't be shared yet": "अझै सेयर गर्न मिल्दैन", + "Can't reach Docker Hub right now.": "अहिले Docker Hub सम्म पुग्न सकिएन।", + "Cancel": "रद्द गर्नुहोस्", + "Cancel download": "डाउनलोड रद्द गर्नुहोस्", + "Cancel pull": "पुल रद्द गर्नुहोस्", + "Canceled": "रद्द भयो", + "Cancelled": "रद्द भयो", + "Cancelled. Nothing was added; layers that finished are kept for the next pull.": "रद्द भयो। केही थपिएन; पूरा भएका लेयर अर्को पुलका लागि राखिएका छन्।", + "Change ports": "पोर्ट बदल्नुहोस्", + "Changing it restarts the cluster.": "यो बदल्दा क्लस्टर रिस्टार्ट हुन्छ।", + "Changing this asks Windows for an administrator's approval, since it adds or removes a DNS rule for {local}.": "यो बदल्दा Windows ले एडमिनको स्वीकृति माग्छ, किनकि यसले {local} का लागि DNS नियम थप्छ वा हटाउँछ।", + "Changing this needs admin rights (an administrator password), since it adds or removes {path}.": "यो बदल्न एडमिन अधिकार (एडमिन पासवर्ड) चाहिन्छ, किनकि यसले {path} थप्छ वा हटाउँछ।", + "Check for Updates…": "अपडेट छ कि हेर्नुहोस्…", + "Check for updates automatically": "अपडेट आफैं हेर्ने", + "Check now": "अहिले हेर्नुहोस्", + "Check the spelling, or paste a full reference like {ref}.": "हिज्जे जाँच्नुहोस्, वा {ref} जस्तो पूरा रेफरेन्स पेस्ट गर्नुहोस्।", + "Checked once the engine runs": "इन्जिन चलेपछि जाँचिन्छ", + "Checked once your account can use Kiri": "तपाईंको अकाउन्टले Kiri चलाउन सकेपछि जाँचिन्छ", + "Checking the code with AWS…": "AWS सँग कोड जाँच्दै…", + "Checking your plan…": "तपाईंको प्लान हेर्दै…", + "Checking…": "हेर्दै…", + "Choose a Linux": "Linux छान्नुहोस्", + "Choose and install": "छानेर इन्स्टल गर्नुहोस्", + "Choose what to bring…": "के ल्याउने छान्नुहोस्…", + "Choose your language": "आफ्नो भाषा छान्नुहोस्", + "Clear": "खाली गर्नुहोस्", + "Clear build cache": "बिल्ड क्यास खाली गर्नुहोस्", + "Clear the selection": "छानेको हटाउनुहोस्", + "Clear the selection (Esc)": "छानेको हटाउनुहोस् (Esc)", + "Clear {n} failed": "फेल भएका {n} खाली गर्नुहोस्", + "Clearing…": "खाली गर्दै…", + "Close": "बन्द गर्नुहोस्", + "Close ({keys})": "बन्द गर्नुहोस् ({keys})", + "Close Window": "विन्डो बन्द गर्नुहोस्", + "Close find": "खोज बन्द गर्नुहोस्", + "Close pane": "प्यान बन्द गर्नुहोस्", + "Close tab": "ट्याब बन्द गर्नुहोस्", + "Close this scan": "यो स्क्यान बन्द गर्नुहोस्", + "Close to your plan's speed limit": "तपाईंको प्लानको स्पिड सीमा नजिक", + "Cluster IP": "क्लस्टर IP", + "Collapse all": "सबै बन्द गर्नुहोस्", + "Command": "कमान्ड", + "Command to run in the container": "कन्टेनरमा चलाउने कमान्ड", + "Completed": "सकियो", + "Compose project {project} made it: {cmd} puts back what the compose file says, so change it there too.": "यो Compose प्रोजेक्ट {project} ले बनाएको हो: {cmd} ले compose फाइलमा जे छ त्यही फर्काउँछ, त्यसैले त्यहाँ पनि बदल्नुहोस्।", + "Compose services answer at {addr}.": "Compose सर्भिसहरू {addr} मा खुल्छन्।", + "Connect Windows to it": "Windows लाई यससँग जोड्ने", + "Connecting…": "कनेक्ट हुँदैछ…", + "Connection lost.": "कनेक्सन टुट्यो।", + "Container": "कन्टेनर", + "Container files are not on Windows' disk: use Save to Downloads": "कन्टेनरका फाइलहरू Windows को डिस्कमा छैनन्: Downloads मा सेभ गर्नुहोस् प्रयोग गर्नुहोस्", + "Container list": "कन्टेनरको सूची", + "Container port {q}{port}{q} is not a port number (1–65535).": "कन्टेनरको पोर्ट {q}{port}{q} सही पोर्ट नम्बर होइन (1–65535)।", + "Container traffic leaves through WSL's network.": "कन्टेनरको ट्राफिक WSL को नेटवर्क हुँदै बाहिर जान्छ।", + "Container, Kubernetes and diagnostics logs.": "कन्टेनर, Kubernetes र डायग्नोस्टिक्सका लग।", + "Containers": "कन्टेनर", + "Containers answer at .kiri.localhost": "कन्टेनरहरू .kiri.localhost मा भेटिन्छन्", + "Containers now answer at .kiri.local": "कन्टेनरहरू अब .kiri.local मा भेटिन्छन्", + "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "कन्टेनरहरू यही कम्प्युटरको कर्नेलमा चल्छन्, त्यसैले यसका USB डिभाइस जस्ताको तस्तै देख्छन्: देखाइएको पाथसहित docker run --device।", + "Containers see it": "कन्टेनरले देख्छन्", + "Containers you start with docker run or Compose show up here, with the {context} context.": "docker run वा Compose ले सुरु गरेका कन्टेनर {context} context सहित यहाँ देखिन्छन्।", + "Continue": "अगाडि बढ्नुहोस्", + "Continue with GitHub": "GitHub बाट अगाडि बढ्नुहोस्", + "Controlled by": "कसले चलाउँछ", + "Copied": "कपी भयो", + "Copied {text}": "{text} कपी भयो", + "Copy": "कपी गर्नुहोस्", + "Copy ID": "ID कपी गर्नुहोस्", + "Copy link": "लिङ्क कपी गर्नुहोस्", + "Copy {what}": "{what} कपी गर्नुहोस्", + "Could not change container names: {error}": "कन्टेनरको नाम बदल्न सकिएन: {error}", + "Could not change the certificate's trust: {error}": "सर्टिफिकेटको भरोसा बदल्न सकिएन: {error}", + "Could not change the ports: {error}": "पोर्ट बदल्न सकिएन: {error}", + "Could not open Terminal: {error}": "Terminal खोल्न सकिएन: {error}", + "Could not open a terminal: {error}": "टर्मिनल खोल्न सकिएन: {error}", + "Could not restart WSL: {error}": "WSL रिस्टार्ट गर्न सकिएन: {error}", + "Could not restart the VM: {error}": "VM रिस्टार्ट गर्न सकिएन: {error}", + "Could not restart the engine: {error}": "इन्जिन रिस्टार्ट गर्न सकिएन: {error}", + "Could not save .wslconfig: {error}": ".wslconfig सेभ गर्न सकिएन: {error}", + "Could not save the SBOM: {error}": "SBOM सेभ गर्न सकिएन: {error}", + "Could not save the file: {error}": "फाइल सेभ गर्न सकिएन: {error}", + "Could not save the proxy settings: {error}": "प्रोक्सी सेटिङ सेभ गर्न सकिएन: {error}", + "Could not save the registry settings: {error}": "Registry सेटिङ सेभ गर्न सकिएन: {error}", + "Could not save the setting to {path}": "सेटिङ {path} मा सेभ गर्न सकिएन", + "Could not save the setting to ~/.kiri/ui.json": "सेटिङ ~/.kiri/ui.json मा सेभ गर्न सकिएन", + "Could not save: {error}": "सेभ गर्न सकिएन: {error}", + "Couldn't change which builder docker build uses: {error}": "docker build ले कुन बिल्डर चलाउने भनेर बदल्न सकिएन: {error}", + "Couldn't check for updates: {error}": "अपडेट छ कि हेर्न सकिएन: {error}", + "Couldn't check: {error}": "हेर्न सकिएन: {error}", + "Couldn't clear the build cache: {error}": "बिल्ड क्यास खाली गर्न सकिएन: {error}", + "Couldn't copy to the clipboard": "क्लिपबोर्डमा कपी गर्न सकिएन", + "Couldn't download it: {error}": "डाउनलोड गर्न सकिएन: {error}", + "Couldn't list the tags": "ट्यागहरू ल्याउन सकिएन", + "Couldn't read the USB devices": "USB डिभाइसहरू पढ्न सकिएन", + "Couldn't read the build history": "बिल्डको इतिहास पढ्न सकिएन", + "Couldn't remove the build: {error}": "बिल्ड हटाउन सकिएन: {error}", + "Couldn't save it: {error}": "सेभ गर्न सकिएन: {error}", + "Couldn't save the report: {error}": "रिपोर्ट सेभ गर्न सकिएन: {error}", + "Couldn't send it: {error}": "पठाउन सकिएन: {error}", + "Couldn't send the crash report: {error}": "क्र्यास रिपोर्ट पठाउन सकिएन: {error}", + "Couldn't set up the Docker tools": "Docker टुलहरू सेटअप गर्न सकिएन", + "Couldn't share": "सेयर गर्न सकिएन", + "Couldn't share service {name}: it's gone": "सर्भिस {name} सेयर गर्न सकिएन: यो हटिसकेको छ", + "Couldn't share {name}": "{name} सेयर गर्न सकिएन", + "Couldn't share {name}: Kiri couldn't tell which port it listens on. Publish one from its page.": "{name} सेयर गर्न सकिएन: यो कुन पोर्टमा सुन्छ Kiri ले थाहा पाउन सकेन। यसको पेजबाट एउटा पब्लिस गर्नुहोस्।", + "Couldn't share {name}: it stopped": "{name} सेयर गर्न सकिएन: यो रोकियो", + "Couldn't share {name}: it's gone": "{name} सेयर गर्न सकिएन: यो हटिसकेको छ", + "Couldn't share {name}: {reason}": "{name} सेयर गर्न सकिएन: {reason}", + "Couldn't start {shell}: {error}": "{shell} सुरु गर्न सकिएन: {error}", + "Couldn't stop {name}: {error}": "{name} रोक्न सकिएन: {error}", + "Couldn't switch docker: {error}": "docker स्विच गर्न सकिएन: {error}", + "Crash reports": "क्र्यास रिपोर्ट", + "Crashed (139)": "क्र्यास भयो (139)", + "Create a diagnostics report": "डायग्नोस्टिक्स रिपोर्ट बनाउनुहोस्", + "Create report…": "रिपोर्ट बनाउनुहोस्…", + "Created": "बनाएको", + "Critical": "गम्भीर", + "Custom": "आफ्नै", + "Cut": "कट गर्नुहोस्", + "Dark": "डार्क", + "Database": "डेटाबेस", + "Debug": "डिबग", + "Delete": "डिलिट गर्नुहोस्", + "Delete cluster": "क्लस्टर डिलिट गर्नुहोस्", + "Delete pod {name}?": "पोड {name} डिलिट गर्ने?", + "Delete the Kubernetes cluster?": "Kubernetes क्लस्टर डिलिट गर्ने?", + "Delete {what}?": "{what} डिलिट गर्ने?", + "Deleting": "डिलिट हुँदैछ", + "Deleting Kubernetes": "Kubernetes डिलिट हुँदैछ", + "Deleting pod {pod}": "पोड {pod} डिलिट हुँदैछ", + "Deleting…": "डिलिट हुँदैछ…", + "Deployment {name} runs this pod": "Deployment {name} ले यो पोड चलाउँछ", + "Detach": "छुटाउनुहोस्", + "Detaching…": "छुटाउँदै…", + "Details": "विवरण", + "Device": "डिभाइस", + "Diagnostics": "डायग्नोस्टिक्स", + "Diagnostics report": "डायग्नोस्टिक्स रिपोर्ट", + "Did you mean {name}?": "तपाईंले {name} भन्न खोज्नुभएको हो?", + "Didn't pull": "पुल भएन", + "Didn't pull.": "पुल भएन।", + "Disconnect": "डिस्कनेक्ट गर्नुहोस्", + "Disconnecting…": "डिस्कनेक्ट हुँदैछ…", + "Dismiss": "हटाउनुहोस्", + "Docker Desktop": "Docker Desktop", + "Docker Hub can't be reached": "Docker Hub सम्म पुग्न सकिएन", + "Docker Hub has no image called {name}.": "Docker Hub मा {name} नामको इमेज छैन।", + "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub का इमेज यी मिररबाट पालैपालो पुल हुन्छन्; इमेज भएको पहिलो मिररले जवाफ दिन्छ, नभए Docker Hub आफैं प्रयोग हुन्छ। अरू registry बाट सिधै पुल गरिन्छ।", + "Docker tools": "Docker टुलहरू", + "Docker tools are ready": "Docker टुलहरू तयार छन्", + "Docker's default engine": "Docker को डिफल्ट इन्जिन", + "Docker's own page signs you in. Check that it shows this code:": "Docker कै पेजले तपाईंलाई साइन इन गराउँछ। त्यहाँ यही कोड देखिएको छ कि हेर्नुहोस्:", + "Docs": "डकुमेन्टेसन", + "Domains": "डोमेन", + "Done": "भयो", + "Download": "डाउनलोड गर्नुहोस्", + "Download Ubuntu": "Ubuntu डाउनलोड गर्ने", + "Download WSL": "WSL डाउनलोड गर्ने", + "Download the new .deb or .rpm": "नयाँ .deb वा .rpm डाउनलोड गर्नुहोस्", + "Downloading Grype, the scanner (about 30 MB, once)": "स्क्यानर Grype डाउनलोड हुँदैछ (करिब 30 MB, एक पटक)", + "Downloading Ubuntu 26.04": "Ubuntu 26.04 डाउनलोड हुँदैछ", + "Downloading {name} from {source}": "{source} बाट {name} डाउनलोड हुँदैछ", + "Downloading {version}": "{version} डाउनलोड हुँदैछ", + "Downloading…": "डाउनलोड हुँदैछ…", + "Drag to resize": "साइज बदल्न तान्नुहोस्", + "Drag to resize, double-click to reset": "साइज बदल्न तान्नुहोस्, पहिलेजस्तै बनाउन डबल-क्लिक गर्नुहोस्", + "Driver": "ड्राइभर", + "Duration": "समय", + "Edit": "एडिट गर्नुहोस्", + "Ended: pod deleted": "बन्द भयो: पोड डिलिट भयो", + "Ended: pod restarted · share the service to keep a link": "बन्द भयो: पोड रिस्टार्ट भयो · लिङ्क राखिराख्न सर्भिस सेयर गर्नुहोस्", + "Ended: service deleted": "बन्द भयो: सर्भिस डिलिट भयो", + "Engine": "इन्जिन", + "Engine running": "इन्जिन चलिरहेको छ", + "Engine updated": "इन्जिन अपडेट भयो", + "Enter the port the app in the pod listens on, 1 to 65535": "पोडभित्रको एपले सुन्ने पोर्ट हाल्नुहोस्, 1 देखि 65535 सम्म", + "Enter this code on GitHub": "यो कोड GitHub मा हाल्नुहोस्", + "Enter your MFA code": "तपाईंको MFA कोड हाल्नुहोस्", + "Environment": "इन्भाइरनमेन्ट", + "Error": "एरर", + "Errors": "एरर", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "यसभित्रको सबै जान्छ: यसका पोड, सर्भिस, भोल्युम र अरू रिसोर्स, र {context} kubectl context। अर्को पटक सुरु गर्दा नयाँ, खाली क्लस्टर बन्छ।", + "Everything in the window.": "विन्डोको सबै कुरा।", + "Everything is in Kiri.": "सबै Kiri मा छ।", + "Exit code": "एक्जिट कोड", + "Exited with code {code}, {when}": "{when} कोड {code} सँग बन्द भयो", + "Expand all": "सबै खोल्नुहोस्", + "Expose services to LAN": "सर्भिसहरू LAN मा खोल्ने", + "External": "बाहिरी", + "Failed": "फेल भयो", + "Failed ({code})": "फेल भयो ({code})", + "Failing": "फेल हुँदैछ", + "Feedback": "सुझाव", + "Files": "फाइल", + "Find": "खोज्नुहोस्", + "Find ({keys})": "खोज्नुहोस् ({keys})", + "Find a path, method or status": "पाथ, मेथड वा स्टेटस खोज्नुहोस्", + "Find in logs": "लगमा खोज्नुहोस्", + "Find in the terminal": "टर्मिनलमा खोज्नुहोस्", + "Finish updating to Kiri {version}": "Kiri {version} मा अपडेट पूरा गर्नुहोस्", + "Finished": "सकिएको", + "Fix all": "सबै मिलाउनुहोस्", + "Fixed in": "फिक्स भएको भर्सन", + "Fold the sidebar": "साइडबार लुकाउनुहोस्", + "Follow": "फलो गर्ने", + "Follow {os} (now {lang}), or always use one language.": "{os} कै भाषा (अहिले {lang}), वा सधैं एउटै भाषा।", + "Follow {os}, or always use the dark or light theme.": "{os} कै थिम, वा सधैं डार्क वा लाइट थिम।", + "Font": "फन्ट", + "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "यो {host} मा Kubernetes का लागि Kiri को आफ्नै छ। साइडबारमा Kubernetes मुनिको स्विच त्यही हो।", + "For pulling and pushing images.": "इमेज पुल र पुस गर्न।", + "Forward": "अगाडि", + "Found": "भेटिएको", + "Freed {size}": "{size} खाली भयो", + "Frees {size}": "{size} खाली हुन्छ", + "From": "कहाँबाट", + "From its base image": "यसको बेस इमेजबाट", + "From the base image": "बेस इमेजबाट", + "From ubuntu.com, through Microsoft's WSL list.": "ubuntu.com बाट, Microsoft को WSL सूची हुँदै।", + "Generate": "बनाउनुहोस्", + "Getting a link…": "लिङ्क लिँदै…", + "GitHub opened in your browser. Approve there and you're signed in straight away.": "तपाईंको ब्राउजरमा GitHub खुल्यो। त्यहाँ स्वीकृत गर्नुहोस्, अनि तुरुन्तै साइन इन हुनुहुन्छ।", + "GitHub opened in your browser. Approve there and {what} is shared straight away.": "तपाईंको ब्राउजरमा GitHub खुल्यो। त्यहाँ स्वीकृत गर्नुहोस्, अनि {what} तुरुन्तै सेयर हुन्छ।", + "GitHub's page asks you to let Kiri read your packages. Check that it shows this code:": "GitHub को पेजले Kiri लाई तपाईंका प्याकेज पढ्ने अनुमति माग्छ। त्यहाँ यही कोड देखिएको छ कि हेर्नुहोस्:", + "Give it back to this computer": "यसलाई यही कम्प्युटरलाई फिर्ता दिनुहोस्", + "Give the VM more memory": "VM लाई बढी मेमोरी दिनुहोस्", + "Give {name} a public https link": "{name} लाई पब्लिक https लिङ्क दिनुहोस्", + "Given back to Windows": "Windows लाई फिर्ता दिइयो", + "Given back to the Mac": "Mac लाई फिर्ता दिइयो", + "Go to Containers": "कन्टेनरमा जानुहोस्", + "Gone from Kiri": "Kiri बाट हट्यो", + "Graphics|process": "ग्राफिक्स", + "Green": "हरियो", + "Grype, the open-source scanner from Anchore": "Grype, Anchore को ओपन सोर्स स्क्यानर", + "HTTP proxy": "HTTP प्रोक्सी", + "HTTPS proxy": "HTTPS प्रोक्सी", + "Hand it to Kiri's containers": "यसलाई Kiri का कन्टेनरलाई दिनुहोस्", + "Has a fix": "फिक्स भएका", + "Have": "भएको", + "Headless: there's no cluster address to share. Share one of its pods.": "हेडलेस: सेयर गर्ने क्लस्टर ठेगाना छैन। यसको कुनै पोड सेयर गर्नुहोस्।", + "Health check": "हेल्थ चेक", + "Helpers|process": "हेल्पर", + "Hide": "लुकाउनुहोस्", + "Hide ({keys})": "लुकाउनुहोस् ({keys})", + "Hide password": "पासवर्ड लुकाउनुहोस्", + "Hide the crash report": "क्र्यास रिपोर्ट लुकाउनुहोस्", + "Hide the terminal ({keys})": "टर्मिनल लुकाउनुहोस् ({keys})", + "Hide until Kiri next opens": "Kiri अर्को पटक नखुलेसम्म लुकाउनुहोस्", + "Hide until {name} has more": "{name} मा अझै थपिएसम्म लुकाउनुहोस्", + "Hide {app}": "{app} लुकाउनुहोस्", + "High": "उच्च", + "Host or network": "होस्ट वा नेटवर्क", + "How it runs": "यो कसरी चल्छ", + "How should you reach your containers?": "कन्टेनरसम्म कसरी पुग्ने?", + "ID": "ID", + "IDs, commands and code.": "ID, कमान्ड र कोड।", + "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "API सर्भरको सर्टिफिकेटले थप समेट्ने IP ठेगाना वा डोमेन नाम, कमाले छुट्याएर, जस्तै तपाईंको नेटवर्कमा यो {host} को ठेगाना। सेभ गर्दा क्लस्टर रिस्टार्ट हुन्छ।", + "If Kiri's useful, a star on GitHub helps others find it.": "Kiri काम लाग्यो भने GitHub मा एउटा स्टार दिनुहोस्, अरूलाई भेट्न सजिलो हुन्छ।", + "If it's private, run {cmd} first.": "प्राइभेट हो भने पहिले {cmd} चलाउनुहोस्।", + "If it's private, sign in first:": "प्राइभेट हो भने पहिले साइन इन गर्नुहोस्:", + "If it's private, {link} first.": "प्राइभेट हो भने पहिले {link}।", + "If it's private, {link}.": "प्राइभेट हो भने {link}।", + "Image": "इमेज", + "Image to pull": "पुल गर्ने इमेज", + "Images": "इमेज", + "Images you pull or build show up here: docker pull alpine, or search above.": "तपाईंले पुल वा बिल्ड गरेका इमेज यहाँ देखिन्छन्: docker pull alpine, वा माथि सर्च गर्नुहोस्।", + "Import": "इम्पोर्ट", + "Import from": "कहाँबाट इम्पोर्ट गर्ने", + "Import {n} item": "{n} वटा इम्पोर्ट गर्नुहोस्", + "Import {n} items": "{n} वटा इम्पोर्ट गर्नुहोस्", + "Imported": "इम्पोर्ट भयो", + "Imported {done}; {failed} failed (hover “Failed” for why).": "{done} इम्पोर्ट भयो; {failed} फेल भयो (किन भनेर “फेल भयो” मा माउस राख्नुहोस्)।", + "Imported {n} item.": "{n} वटा इम्पोर्ट भयो।", + "Imported {n} items.": "{n} वटा इम्पोर्ट भयो।", + "Importing…": "इम्पोर्ट हुँदैछ…", + "In Kiri": "Kiri मा छ", + "In a container": "कन्टेनरमा", + "In a week": "एक हप्तामा", + "In use": "प्रयोगमा", + "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "{used} प्रयोगमा। VM ले अहिले {target} सम्म लिन सक्छ, र कन्टेनरलाई बढी चाहिँदा बढ्छ।", + "In use: {proxy}, except {hosts}.": "प्रयोगमा: {proxy}, {hosts} बाहेक।", + "In use: {proxy}.": "प्रयोगमा: {proxy}।", + "Included": "साथमै आउँछ", + "Info": "जानकारी", + "Info and up": "जानकारी र माथि", + "Insecure registries": "असुरक्षित registry हरू", + "Inside Linux": "Linux भित्र", + "Install Kiri's engine in it": "यसमा Kiri को इन्जिन इन्स्टल गर्ने", + "Install WSL": "WSL इन्स्टल गर्नुहोस्", + "Install usbipd-win": "usbipd-win इन्स्टल गर्नुहोस्", + "Installed": "इन्स्टल भयो", + "Installing": "इन्स्टल हुँदैछ", + "Installing Windows Subsystem for Linux": "Windows Subsystem for Linux इन्स्टल हुँदैछ", + "Installing…": "इन्स्टल हुँदैछ…", + "Installs when you quit Kiri": "Kiri बन्द गर्दा इन्स्टल हुन्छ", + "Interface font": "इन्टरफेसको फन्ट", + "Internal steps": "भित्री स्टेप", + "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "यसले Linux VM नै बदल्न माग्छ, जुन “चलाउनुहोस्” ले दिँदैन। {image} मा भरोसा छ भने {cmd} ले आफैं सुरु गर्नुहोस्।", + "It has no selector, so it picks no pods.": "यसमा सेलेक्टर छैन, त्यसैले यसले कुनै पोड छान्दैन।", + "It restarts, so open connections drop.": "यो रिस्टार्ट हुन्छ, त्यसैले खुला कनेक्सनहरू टुट्छन्।", + "It stays up while Kiri is running.": "Kiri चलिरहेसम्म यो खुला रहन्छ।", + "It takes effect when it next starts.": "यो अर्को पटक सुरु हुँदा लागू हुन्छ।", + "It works with serial adapters, Zigbee sticks, mice and keyboards; webcams and audio aren't supported yet.": "यो सिरियल एड्याप्टर, Zigbee स्टिक, माउस र किबोर्डसँग चल्छ; वेबक्याम र अडियो अझै चल्दैनन्।", + "It wrote nothing to its log.": "यसले लगमा केही लेखेन।", + "It's a network interface inside Linux, not a device file.": "यो Linux भित्रको नेटवर्क इन्टरफेस हो, डिभाइस फाइल होइन।", + "It's deleted, with its files and unnamed volumes. Named volumes stay.": "यो डिलिट हुन्छ, यसका फाइल र नाम नभएका भोल्युमसहित। नाम भएका भोल्युम रहन्छन्।", + "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "यो रोकिन्छ र डिलिट हुन्छ, यसका फाइल र नाम नभएका भोल्युमसहित। नाम भएका भोल्युम रहन्छन्।", + "Its API server stalls or stops answering · {free}": "यसको API सर्भर अड्किन्छ वा जवाफ दिन छोड्छ · {free}", + "Its container is stopped and deleted, with their files. Named volumes stay.": "यसका कन्टेनर रोकिन्छन् र डिलिट हुन्छन्, तिनका फाइलसहित। नाम भएका भोल्युम रहन्छन्।", + "Its containers stop and their files go.": "यसका कन्टेनर रोकिन्छन् र तिनका फाइल जान्छन्।", + "Its data is deleted for good.": "यसको डेटा सधैंका लागि डिलिट हुन्छ।", + "Its deployment starts a new pod in its place.": "यसको डिप्लोयमेन्टले यसको ठाउँमा नयाँ पोड सुरु गर्छ।", + "Its job may start it again.": "यसको job ले यसलाई फेरि सुरु गर्न सक्छ।", + "Its last container stopped because {name} wasn't set.": "{name} सेट नभएकाले यसको पछिल्लो कन्टेनर रोकियो।", + "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "यसको नोड चलिरहेको छ, तर API सर्भरले जवाफ दिँदैन। VM व्यस्त भए वा मेमोरी नपुगे यस्तो हुन सक्छ; Kiri सोधिरहन्छ।", + "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "यसको नोड चलिरहेको छ, तर API सर्भरले जवाफ दिँदैन: {error}। VM व्यस्त भए वा मेमोरी नपुगे यस्तो हुन सक्छ; Kiri सोधिरहन्छ।", + "Its start script stops when {name} isn't set.": "{name} सेट नहुँदा यसको स्टार्ट स्क्रिप्ट रोकिन्छ।", + "Its start script stops without it: “{why}”.": "यो बिना यसको स्टार्ट स्क्रिप्ट रोकिन्छ: “{why}”।", + "Its value": "यसको मान", + "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "यसका {n} कन्टेनर रोकिन्छन् र डिलिट हुन्छन्, तिनका फाइलसहित। नाम भएका भोल्युम रहन्छन्।", + "Its {owner} starts a new pod in its place.": "यसको {owner} ले यसको ठाउँमा नयाँ पोड सुरु गर्छ।", + "KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.": "daemon का लागि KIRI_CPUS वा KIRI_MEMORY_MIB सेट गरिएको छ, र त्यो यीभन्दा पहिले लागू हुन्छ।", + "Keep": "राख्नुहोस्", + "Keep building with Docker": "Docker मै बिल्ड गरिरहनुहोस्", + "Keep building with Docker.": "Docker मै बिल्ड गरिरहनुहोस्।", + "Keep typing to search Docker Hub.": "Docker Hub मा सर्च गर्न टाइप गरिरहनुहोस्।", + "Keep using your PC meanwhile.": "यता PC चलाइरहनुहोस्।", + "Kept in Credential Manager": "Credential Manager मा राखिएको", + "Kept in the Keychain": "Keychain मा राखिएको", + "Kept in {path} with Docker's names, for docker pull, push, login and build. Docker Desktop's file is left alone.": "docker pull, push, login र build का लागि Docker कै नाममा {path} भित्र राखिन्छ। Docker Desktop को फाइल चलाइँदैन।", + "Kept {name}: {container} couldn't be removed ({error})": "{name} राखियो: {container} हटाउन सकिएन ({error})", + "Kept {name}: {error}": "{name} राखियो: {error}", + "Key": "Key", + "Keyboard": "किबोर्ड", + "Killed (137)": "किल गरियो (137)", + "Kiri Cloud gives it a public https link through a secure tunnel from this {host}. You sign in with GitHub, so every link traces back to a person. Kiri never sees your password.": "Kiri Cloud ले यसलाई यो {host} बाट सुरक्षित टनेल हुँदै पब्लिक https लिङ्क दिन्छ। तपाईं GitHub बाट साइन इन गर्नुहुन्छ, त्यसैले हरेक लिङ्क कुनै व्यक्तिसम्म पुग्छ। Kiri ले तपाईंको पासवर्ड कहिल्यै देख्दैन।", + "Kiri Setup": "Kiri सेटअप", + "Kiri and this Mac": "Kiri र यो Mac", + "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri ले अझै आवाज वा भिडियो पठाउन सक्दैन: कन्टेनरले यसबाट केही पाउँदैनन्।", + "Kiri engine installed": "Kiri इन्जिन इन्स्टल भयो", + "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri ले इमेजका सबै प्याकेज (OS प्याकेज, भाषाका लाइब्रेरी र बाइनरी) भेट्छ र हरेकलाई कमजोरीको डेटाबेससँग जाँच्छ। अझै कुनै स्क्यान छैन: पहिलो चलाउनुहोस्।", + "Kiri is not running": "Kiri चलिरहेको छैन", + "Kiri is ready": "Kiri तयार छ", + "Kiri is set up.": "Kiri सेटअप भयो।", + "Kiri quit unexpectedly last time": "पोहोर पटक Kiri अचानक बन्द भयो", + "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri ले Grype यहीँ तपाईंको Mac मा Kiri को स्टोरमा भएको इमेजमाथि चलाउँछ। इमेज कतै अपलोड हुँदैन।", + "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri ले Linux कन्टेनरहरू WSL भित्र, आफ्नै Linux मा चलाउँछ। दुवै विकल्पमा उही कन्टेनर उही स्पिडमा चल्छन्; फरक साइज र अरू के-के पाइन्छ भन्नेमा मात्र हो।", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri ले Docker Desktop बिना Windows मा Linux कन्टेनर चलाउँछ। यसलाई Windows Subsystem for Linux (WSL) चाहिन्छ, Linux चलाउने Microsoft कै तरिका, जुन यो PC मा अझै छैन।", + "Kiri sets itself up for your Windows account only.": "Kiri ले आफूलाई तपाईंको Windows अकाउन्टका लागि मात्र सेटअप गर्छ।", + "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "इन्जिन चलेपछि Kiri ले आफ्नो बिल्डर सेटअप गर्छ, र त्यसपछि बिल्डहरू त्यहीँ जान्छन्।", + "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri ले docker कमान्डबाट Docker Hub मा साइन इन गर्छ, जुन इन्स्टल भएको छैन। इन्स्टल गरेर फेरि गर्नुहोस्।", + "Kiri signs in to GitHub with the GitHub CLI (gh), which isn't installed. Install it, then try again.": "Kiri ले GitHub CLI (gh) बाट GitHub मा साइन इन गर्छ, जुन इन्स्टल भएको छैन। इन्स्टल गरेर फेरि गर्नुहोस्।", + "Kiri started your container.": "Kiri ले तपाईंको कन्टेनर सुरु गर्यो।", + "Kiri started {name} in {time}.": "Kiri ले {name} {time} मा सुरु गर्यो।", + "Kiri started {name}.": "Kiri ले {name} सुरु गर्यो।", + "Kiri uses your AWS profile through the AWS CLI, which isn't installed. Public images still pull.": "Kiri ले AWS CLI बाट तपाईंको AWS प्रोफाइल प्रयोग गर्छ, जुन इन्स्टल भएको छैन। पब्लिक इमेजहरू भने पुल हुन्छन्।", + "Kiri will reuse the Ubuntu already installed on this PC. Kiri runs in it, and you keep opening it as your own Linux.": "Kiri ले यो PC मा पहिल्यै इन्स्टल भएको Ubuntu नै प्रयोग गर्छ। Kiri त्यसैभित्र चल्छ, र तपाईं यसलाई आफ्नै Linux जस्तै खोलिरहन सक्नुहुन्छ।", + "Kiri {version} is a test build: it doesn't update itself": "Kiri {version} टेस्ट बिल्ड हो: यो आफैं अपडेट हुँदैन", + "Kiri {version} is available": "Kiri {version} आएको छ", + "Kiri {version} is downloaded": "Kiri {version} डाउनलोड भयो", + "Kiri {version} is ready to install": "Kiri {version} इन्स्टल गर्न तयार छ", + "Kiri {version} is the newest version": "Kiri {version} नै सबैभन्दा नयाँ भर्सन हो", + "Kiri's Kubernetes cluster": "Kiri को Kubernetes क्लस्टर", + "Kiri's builder": "Kiri को बिल्डर", + "Kiri's certificate is no longer trusted": "Kiri को सर्टिफिकेटमा अब भरोसा छैन", + "Kiri's certificate is trusted: containers open over HTTPS": "Kiri को सर्टिफिकेटमा भरोसा गरियो: कन्टेनरहरू HTTPS मा खुल्छन्", + "Kiri's containers and engine use {used}, of the {total} this computer has.": "यो कम्प्युटरको {total} मध्ये Kiri का कन्टेनर र इन्जिनले {used} प्रयोग गर्छन्।", + "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "WSL सँग भएको {total} मध्ये Kiri का कन्टेनर, इन्जिन र एजेन्टले {used} लिएका छन् (.wslconfig ले यो तोक्छ)।", + "Kiri's log": "Kiri को लग", + "Kiri's logs": "Kiri का लग", + "Kiri's own, {name}, is on, so another copy isn't needed.": "Kiri कै {name} अन छ, त्यसैले अर्को कपी चाहिँदैन।", + "Kiri: {state}": "Kiri: {state}", + "Kiri’s engine": "Kiri को इन्जिन", + "Kubernetes cluster": "Kubernetes क्लस्टर", + "Kubernetes deleted, with its state": "Kubernetes यसको अवस्थासहित डिलिट भयो", + "Kubernetes is busy with another change; try again in a moment": "Kubernetes अर्कै काममा व्यस्त छ; एकछिनपछि फेरि गर्नुहोस्", + "Kubernetes is managed in Settings → Kubernetes": "Kubernetes सेटिङ → Kubernetes बाट चलाइन्छ", + "Kubernetes is off": "Kubernetes अफ छ", + "Kubernetes is out of memory": "Kubernetes को मेमोरी सकियो", + "Kubernetes is running · API on {addr}": "Kubernetes चलिरहेको छ · API {addr} मा", + "Kubernetes is running.": "Kubernetes चलिरहेको छ।", + "Kubernetes is running: {cmd}": "Kubernetes चलिरहेको छ: {cmd}", + "Kubernetes is short of memory.": "Kubernetes लाई मेमोरी पुगेको छैन।", + "Kubernetes is starting": "Kubernetes सुरु हुँदैछ", + "Kubernetes is stopping": "Kubernetes रोकिँदैछ", + "Kubernetes isn't answering": "Kubernetes ले जवाफ दिइरहेको छैन", + "Kubernetes isn't running": "Kubernetes चलिरहेको छैन", + "Kubernetes needs about {need}, and this VM can use {max}, of which {used} is in use.": "Kubernetes लाई करिब {need} चाहिन्छ, र यो VM ले {max} सम्म प्रयोग गर्न सक्छ, जसमध्ये {used} प्रयोगमा छ।", + "Kubernetes needs about {need}, and this VM can use {max}.": "Kubernetes लाई करिब {need} चाहिन्छ, र यो VM ले {max} सम्म प्रयोग गर्न सक्छ।", + "Kubernetes settings": "Kubernetes सेटिङ", + "Kubernetes settings saved. They apply when it next starts.": "Kubernetes सेटिङ सेभ भयो। अर्को पटक सुरु हुँदा लागू हुन्छ।", + "Kubernetes stopped it: it used more memory than it may, or the VM ran out": "Kubernetes ले यसलाई रोक्यो: यसले आफ्नो लिमिटभन्दा बढी मेमोरी प्रयोग गर्‍यो, वा VM को मेमोरी सकियो", + "Kubernetes stopped. Its state is kept for the next start.": "Kubernetes रोकियो। यसको अवस्था अर्को पटक सुरु गर्न राखिएको छ।", + "Kubernetes: {error}": "Kubernetes: {error}", + "Labels": "लेबल", + "Language": "भाषा", + "Large": "ठूलो", + "Later": "पछि", + "Later installs it when you quit Kiri.": "“पछि” छान्दा Kiri बन्द गर्दा इन्स्टल हुन्छ।", + "Later: Kiri waits in the tray and picks up after your next restart.": "पछि: Kiri ट्रेमा पर्खिन्छ र अर्को रिस्टार्टपछि बाँकी काम गर्छ।", + "Layer": "लेयर", + "Layers": "लेयर", + "Let it pick a random one": "यसैलाई र्‍यान्डम पासवर्ड छान्न दिनुहोस्", + "Lets {user} run containers without sudo": "{user} लाई sudo बिना कन्टेनर चलाउन दिन्छ", + "Level": "लेभल", + "Light": "लाइट", + "Linux VM": "Linux VM", + "Linux VM: {state}": "Linux VM: {state}", + "Linux account": "Linux अकाउन्ट", + "Linux for Kiri": "Kiri का लागि Linux", + "Linux hasn't made a device for it yet.": "Linux ले यसको डिभाइस अझै बनाएको छैन।", + "Linux stopped a process for memory": "मेमोरी नपुगेर Linux ले एउटा प्रोसेस रोक्यो", + "Listening on {ports}": "{ports} मा सुनिरहेको", + "Live": "लाइभ", + "Live · waiting for the first visitor": "लाइभ · पहिलो भिजिटर पर्खँदै", + "Live|stream": "लाइभ", + "Loading tags…": "ट्याग लोड हुँदैछन्…", + "Loading the steps…": "स्टेपहरू लोड हुँदैछन्…", + "Loading…": "लोड हुँदैछ…", + "Local names": "लोकल नाम", + "Location": "ठाउँ", + "Log lines for this action": "यो कामका लग लाइन", + "Log out now": "अहिले लग आउट गर्नुहोस्", + "Log out to finish": "पूरा गर्न लग आउट गर्नुहोस्", + "Log text": "लगको अक्षर साइज", + "Logs": "लग", + "Logs: {error}": "लग: {error}", + "Looking for Kubernetes…": "Kubernetes खोज्दै…", + "Looking for OrbStack and Docker Desktop…": "OrbStack र Docker Desktop खोज्दै…", + "Looking for USB devices…": "USB डिभाइस खोज्दै…", + "Looking for crash reports…": "क्र्यास रिपोर्ट खोज्दै…", + "Looking for shells…": "शेल खोज्दै…", + "Low": "कम", + "MFA code": "MFA कोड", + "Mac": "Mac", + "Made by": "बनाउने", + "Make Kiri the default": "Kiri लाई डिफल्ट बनाउने", + "Make Kiri the default for docker": "docker का लागि Kiri लाई डिफल्ट बनाउनुहोस्", + "Make a new one": "नयाँ बनाउनुहोस्", + "Manufacturer": "बनाउने कम्पनी", + "MariaDB won't start until you choose how its root account signs in.": "root अकाउन्ट कसरी साइन इन हुन्छ नछानेसम्म MariaDB सुरु हुँदैन।", + "Maximise": "ठूलो बनाउनुहोस्", + "Medium": "मध्यम", + "Memory": "मेमोरी", + "Memory full · {mem}": "मेमोरी भरियो · {mem}", + "Method": "मेथड", + "Mirror address": "मिरर ठेगाना", + "Modified": "बदलिएको", + "Monospace font": "मोनोस्पेस फन्ट", + "More": "थप", + "More actions for {name}": "{name} का थप काम", + "More memory": "मेमोरी बढाउनुहोस्", + "More settings": "थप सेटिङ", + "Mounts": "माउन्ट", + "Mouse": "माउस", + "MySQL won't start until you choose how its root account signs in.": "root अकाउन्ट कसरी साइन इन हुन्छ नछानेसम्म MySQL सुरु हुँदैन।", + "Name": "नाम", + "Named volumes from docker volume create or -v name:/path show up here.": "docker volume create वा -v name:/path बाट बनेका नाम भएका भोल्युम यहाँ देखिन्छन्।", + "Names answer on {http} and {https}. Pick other ports when another app needs these; links then carry the port, like {url}.": "नामहरू {http} र {https} मा खुल्छन्। अर्को एपलाई यी चाहिएमा अरू पोर्ट छान्नुहोस्; त्यसपछि लिङ्कमा पोर्ट पनि आउँछ, जस्तै {url}।", + "Names, images and status. Not their files, logs or environment.": "नाम, इमेज र स्टेटस। तिनका फाइल, लग वा इन्भाइरनमेन्ट होइन।", + "Namespace": "नेमस्पेस", + "Namespace · {up} of {all} running": "नेमस्पेस · {all} मध्ये {up} चलिरहेका", + "Needs a restart": "रिस्टार्ट चाहिन्छ", + "Needs an administrator password once.": "एक पटक एडमिन पासवर्ड चाहिन्छ।", + "Needs upper and lower case, a digit and a symbol, 8 or more": "ठूला र साना अक्षर, एउटा अंक र एउटा चिन्ह, 8 वा बढी चाहिन्छ", + "Negligible": "नगण्य", + "Network": "नेटवर्क", + "Networks": "नेटवर्क", + "Networks you create with docker network create show up here.": "docker network create ले बनाएका नेटवर्क यहाँ देखिन्छन्।", + "Network|process": "नेटवर्क", + "New containers get {http}, {https} and {no}.": "नयाँ कन्टेनरले {http}, {https} र {no} पाउँछन्।", + "New tab": "नयाँ ट्याब", + "New tab ({keys})": "नयाँ ट्याब ({keys})", + "Next match": "अर्को मिल्ने", + "No Linux username is needed now: Kiri runs inside Ubuntu on its own. Ubuntu asks for one only the first time you open it yourself. * Estimate.": "अहिले Linux युजरनेम चाहिँदैन: Kiri Ubuntu भित्र आफैं चल्छ। तपाईंले पहिलो पटक आफैं खोल्दा मात्र Ubuntu ले युजरनेम सोध्छ। * अनुमान।", + "No USB devices": "कुनै USB डिभाइस छैन", + "No build matches.": "कुनै बिल्ड मिलेन।", + "No builds yet": "अझै कुनै बिल्ड छैन", + "No changes": "केही बदलिएको छैन", + "No containers running": "कुनै कन्टेनर चलिरहेको छैन", + "No containers yet": "अझै कुनै कन्टेनर छैन", + "No crashes. Kiri keeps a report here if one of its parts ever stops unexpectedly.": "कुनै क्र्यास छैन। Kiri को कुनै भाग अचानक रोकियो भने Kiri ले यहाँ रिपोर्ट राख्छ।", + "No fix yet": "अझै फिक्स छैन", + "No images yet": "अझै कुनै इमेज छैन", + "No known vulnerabilities in {n} packages": "{n} प्याकेजमा कुनै थाहा भएको कमजोरी छैन", + "No language matches. Try its English name.": "कुनै भाषा भेटिएन। अंग्रेजी नामले सर्च गरेर हेर्नुहोस्।", + "No languages match": "कुनै भाषा भेटिएन", + "No lines match.": "कुनै लाइन मिलेन।", + "No mirrors yet: Docker Hub images come from Docker Hub itself.": "अझै कुनै मिरर छैन: Docker Hub का इमेज सिधै Docker Hub बाट आउँछन्।", + "No networks yet": "अझै कुनै नेटवर्क छैन", + "No password, no login and no TLS. Fine on this Mac, not for anything shared.": "पासवर्ड, लग इन र TLS केही हुँदैन। यो Mac मा ठिक छ, सेयर गरिने कुनै कुराका लागि होइन।", + "No password, no login and no TLS. Fine on this PC, not for anything shared.": "पासवर्ड, लग इन र TLS केही हुँदैन। यो PC मा ठिक छ, सेयर गरिने कुनै कुराका लागि होइन।", + "No password, no login and no TLS. Fine on this computer, not for anything shared.": "पासवर्ड, लग इन र TLS केही हुँदैन। यो कम्प्युटरमा ठिक छ, सेयर गरिने कुनै कुराका लागि होइन।", + "No pods": "कुनै पोड छैन", + "No pods match its selector.": "यसको सेलेक्टरसँग कुनै पोड मिलेन।", + "No ports to share": "सेयर गर्ने पोर्ट छैन", + "No proxy is in use.": "कुनै प्रोक्सी प्रयोगमा छैन।", + "No requests match.": "कुनै रिक्वेस्ट मिलेन।", + "No requests yet": "अझै कुनै रिक्वेस्ट छैन", + "No results": "केही भेटिएन", + "No service points at it, so the link goes straight to the pod.": "कुनै सर्भिस यससँग जोडिएको छैन, त्यसैले लिङ्क सिधै पोडमा जान्छ।", + "No services": "कुनै सर्भिस छैन", + "No steps here.": "यहाँ कुनै स्टेप छैन।", + "No visitors in the last 2 minutes": "पछिल्लो 2 मिनेटमा कोही आएन", + "No volumes yet": "अझै कुनै भोल्युम छैन", + "No {label}": "{label} छैन", + "Node": "नोड", + "None": "छैन", + "None (headless)": "None (हेडलेस)", + "None found": "केही भेटिएन", + "None match these filters.": "यी फिल्टरसँग केही मिलेन।", + "None: every registry is checked over HTTPS.": "कुनै छैन: हरेक registry HTTPS बाट जाँचिन्छ।", + "Not a web port, so it isn't shared": "वेब पोर्ट होइन, त्यसैले सेयर गरिँदैन", + "Not an image name: {reference}": "इमेजको नाम होइन: {reference}", + "Not answering · visitors get an error": "जवाफ दिँदैन · भिजिटरले एरर पाउँछन्", + "Not created yet": "अझै बनेको छैन", + "Not found.": "भेटिएन।", + "Not in use: no container was made from it": "प्रयोगमा छैन: यसबाट कुनै कन्टेनर बनेको छैन", + "Not now": "अहिले होइन", + "Not now: ask again in a week": "अहिले होइन: एक हप्तापछि फेरि सोध्ने", + "Not running": "चलिरहेको छैन", + "Not sent": "पठाइएको छैन", + "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "अझै सेटअप भएको छैन। यो तपाईंको पहिलो बिल्डमा बन्छ, जसले BuildKit (करिब 110 MB) एक पटक डाउनलोड गर्छ।", + "Not signed in": "साइन इन गरिएको छैन", + "Not signed in to any registry": "कुनै registry मा साइन इन गरिएको छैन", + "Nothing called “{q}” on Docker Hub": "Docker Hub मा “{q}” नामको केही छैन", + "Nothing changes: {build} builds where it does now, and the images stay in {engine}.": "केही बदलिँदैन: {build} अहिले जहाँ बिल्ड गर्छ त्यहीँ गर्छ, र इमेजहरू {engine} मै रहन्छन्।", + "Nothing here.": "यहाँ केही छैन।", + "Nothing is deleted. You can switch back any time from the status bar.": "केही डिलिट हुँदैन। स्टेटस बारबाट जुनसुकै बेला फर्कन सक्नुहुन्छ।", + "Nothing logged yet.": "अझै केही लग भएको छैन।", + "Nothing matches “{q}” in {tab}.": "{tab} मा “{q}” सँग मिल्ने केही भेटिएन।", + "Nothing matches “{q}”.": "“{q}” सँग मिल्ने केही भेटिएन।", + "Nothing restarts it either: when the pod is deleted or restarts, the link ends.": "यसलाई कसैले रिस्टार्ट पनि गर्दैन: पोड डिलिट वा रिस्टार्ट हुँदा लिङ्क बन्द हुन्छ।", + "Nothing shared yet": "अझै केही सेयर गरिएको छैन", + "Nothing shared. Press the globe beside a running container to give it a public link.": "केही सेयर गरिएको छैन। चलिरहेको कन्टेनरलाई पब्लिक लिङ्क दिन त्यसको छेउको ग्लोब थिच्नुहोस्।", + "Nothing starts it again: no deployment or other controller owns it.": "यसलाई फेरि कसैले सुरु गर्दैन: कुनै डिप्लोयमेन्ट वा अरू कन्ट्रोलर यसको मालिक होइन।", + "Nothing to download": "केही डाउनलोड गर्नु पर्दैन", + "Nothing to download: it came inside Kiri.": "केही डाउनलोड गर्नु पर्दैन: यो Kiri भित्रै आएको हो।", + "Nothing to import from: OrbStack and Docker Desktop aren't on this {host}.": "इम्पोर्ट गर्ने ठाउँ छैन: यो {host} मा OrbStack र Docker Desktop छैनन्।", + "Nothing to pass to a container yet.": "कन्टेनरलाई दिने केही अझै छैन।", + "Nothing to type: it uses the AWS sign-in already on this computer.": "केही टाइप गर्नु पर्दैन: यसले यो कम्प्युटरमा भएकै AWS साइन इन प्रयोग गर्छ।", + "Now": "अहिले", + "OK": "ठिक छ", + "Off": "अफ", + "Off: Kiri checks only when you click Check now.": "अफ: तपाईंले “अहिले हेर्नुहोस्” थिच्दा मात्र Kiri ले हेर्छ।", + "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "अफ: कन्टेनर <name>.kiri.localhost मा खुल्छन्, जसका लागि केही सेटअप चाहिँदैन।", + "Off: press Start engine to run containers. It stays off after a restart until you start it.": "अफ: कन्टेनर चलाउन “इन्जिन सुरु गर्नुहोस्” थिच्नुहोस्। तपाईंले सुरु नगरेसम्म रिस्टार्टपछि पनि यो अफ नै रहन्छ।", + "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "अफ: API सर्भर र LoadBalancer सर्भिसहरू यो {host} मा मात्र खुल्छन् (127.0.0.1)।", + "Official": "अफिसियल", + "On": "अन", + "On disk": "डिस्कमा", + "On this Mac": "यो Mac मा", + "On this PC": "यो PC मा", + "On {registry} an image is named owner/image, such as {example}. Type one to choose its tag, or paste a full reference.": "{registry} मा इमेजको नाम owner/image हुन्छ, जस्तै {example}। ट्याग छान्न एउटा टाइप गर्नुहोस्, वा पूरा रेफरेन्स पेस्ट गर्नुहोस्।", + "On {targets}": "{targets} मा", + "On: Kiri checks each time it opens. It never updates without asking.": "अन: Kiri खुल्दा हरेक पटक हेर्छ। नसोधी कहिल्यै अपडेट गर्दैन।", + "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "अन: कन्टेनरहरू Kiri कै सर्टिफिकेटसहित https:// मा खुल्छन्, जसले .kiri.local र .kiri.localhost नामको मात्र ग्यारेन्टी दिन्छ।", + "On: running containers answer at <name>.kiri.local.": "अन: चलिरहेका कन्टेनर <name>.kiri.local मा खुल्छन्।", + "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "अन: API सर्भर र LoadBalancer सर्भिसहरू सबै नेटवर्क इन्टरफेसमा खुल्छन्, त्यसैले तपाईंको नेटवर्कका अरू डिभाइसले पनि पुग्न सक्छन्।", + "One more step: log out and back in.": "एउटा चरण बाँकी: लग आउट गरेर फेरि लग इन गर्नुहोस्।", + "One more step: set it up, or skip.": "एउटा चरण बाँकी: सेटअप गर्नुहोस् वा छोड्नुहोस्।", + "One restart to finish WSL": "WSL पूरा गर्न एक पटक रिस्टार्ट", + "One text file, redacted, saved to your Desktop and shown in Finder. Read it before you share it.": "गोप्य कुरा हटाइएको एउटा टेक्स्ट फाइल, तपाईंको Desktop मा सेभ भएर Finder मा देखाइन्छ। सेयर गर्नुअघि पढेर हेर्नुहोस्।", + "Only from {what}": "{what} बाट मात्र", + "Only {size} left this month. When it runs out, the link stops until next month.": "यो महिना {size} मात्र बाँकी छ। सकिएपछि अर्को महिनासम्म लिङ्क बन्द हुन्छ।", + "Open": "खोल्नुहोस्", + "Open Kiri": "Kiri खोल्नुहोस्", + "Open Pods": "पोड खोल्नुहोस्", + "Open Share": "सेयर खोल्नुहोस्", + "Open in Terminal": "टर्मिनलमा खोल्नुहोस्", + "Open logs folder": "लग फोल्डर खोल्नुहोस्", + "Open the page again": "पेज फेरि खोल्नुहोस्", + "Open {addr}": "{addr} खोल्नुहोस्", + "Open {name}": "{name} खोल्नुहोस्", + "Open {site}": "{site} खोल्नुहोस्", + "Open {url}": "{url} खोल्नुहोस्", + "OpenSearch won't start without a strong admin password.": "बलियो एडमिन पासवर्ड बिना OpenSearch सुरु हुँदैन।", + "Opening the scan…": "स्क्यान खोल्दै…", + "Optional": "चाहे राख्नुहोस्", + "Or allow an empty password": "वा खाली पासवर्ड चल्न दिनुहोस्", + "Or let it pick a random password": "वा यसैलाई र्‍यान्डम पासवर्ड छान्न दिनुहोस्", + "Or set {names} instead.": "वा बरु {names} सेट गर्नुहोस्।", + "Or turn security off for local use": "वा लोकल प्रयोगका लागि सुरक्षा अफ गर्नुहोस्", + "Orange": "सुन्तला", + "OrbStack": "OrbStack", + "Out of memory": "मेमोरी सकियो", + "Overview": "ओभरभ्यु", + "PC": "PC", + "Package": "प्याकेज", + "Packages": "प्याकेज", + "Page|process": "पेज", + "Pane restored": "प्यान पहिलेजस्तै भयो", + "Pane zoomed": "प्यान ठूलो भयो", + "Part": "भाग", + "Part of Kiri": "Kiri को एउटा भाग", + "Part of the cluster itself (kube-system). Not shared.": "क्लस्टर आफैंको भाग (kube-system)। सेयर गरिँदैन।", + "Pass to containers": "कन्टेनरलाई पनि दिने", + "Paste": "पेस्ट गर्नुहोस्", + "Paste NAME=value lines, or a .env file, into a name.": "NAME=value लाइनहरू, वा .env फाइल, नाममा पेस्ट गर्नुहोस्।", + "Paste {n} lines? Each line runs as a command.": "{n} लाइन पेस्ट गर्ने? हरेक लाइन कमान्डको रूपमा चल्छ।", + "Path": "पाथ", + "Pause": "पज गर्नुहोस्", + "Paused": "पज गरिएको", + "Paused · nobody can open the link": "पज गरिएको · कसैले लिङ्क खोल्न सक्दैन", + "Paused: nobody can open the link until you resume.": "पज गरिएको: तपाईंले फेरि नचलाएसम्म कसैले लिङ्क खोल्न सक्दैन।", + "Peak {rate}": "सबैभन्दा बढी {rate}", + "Pin tab": "ट्याब पिन गर्नुहोस्", + "Pink": "गुलाबी", + "Pinned": "पिन गरिएको", + "Pinned: right-click to unpin": "पिन गरिएको: अनपिन गर्न राइट-क्लिक गर्नुहोस्", + "Pinned: unpin the tab to close it": "पिन गरिएको: बन्द गर्न पहिले ट्याब अनपिन गर्नुहोस्", + "Plug one in: a serial adapter, a Zigbee stick, a microcontroller. It shows up here.": "एउटा जोड्नुहोस्: सिरियल एड्याप्टर, Zigbee स्टिक, माइक्रोकन्ट्रोलर। यहाँ देखिन्छ।", + "Pod IP": "पोड IP", + "Pod in {ns}": "{ns} मा पोड", + "Pod in {ns} · on {node}": "{ns} मा पोड · {node} मा", + "Pods": "पोड", + "Pods you create with kubectl show up here, grouped by namespace.": "kubectl ले बनाएका पोड यहाँ नेमस्पेस अनुसार देखिन्छन्।", + "Port": "पोर्ट", + "Port in the container": "कन्टेनर भित्रको पोर्ट", + "Port on your {host}": "तपाईंको {host} को पोर्ट", + "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "तपाईंको {host} को पोर्ट (localhost) → कन्टेनर भित्रको पोर्ट। {host} तिरको पोर्ट खाली छोडे Kiri आफैं फ्री पोर्ट छान्छ।", + "Port {port} is already in use on this {host}": "पोर्ट {port} यो {host} मा पहिल्यै प्रयोगमा छ", + "Port {port}. The link keeps working when pods restart.": "पोर्ट {port}। पोड रिस्टार्ट हुँदा पनि लिङ्क चलिरहन्छ।", + "Ports": "पोर्ट", + "Ports changed": "पोर्ट बदलियो", + "Ports for {name}": "{name} का पोर्ट", + "Ports removed": "पोर्ट हटाइए", + "Ports saved: {ports}": "पोर्ट सेभ भयो: {ports}", + "Ports…": "पोर्ट…", + "Postgres won't start without a superuser password.": "superuser पासवर्ड बिना Postgres सुरु हुँदैन।", + "Powered by": "प्रविधि", + "Press Share on a running container to give it a public https link anyone can open.": "जो कोहीले खोल्न मिल्ने पब्लिक https लिङ्क दिन चलिरहेको कन्टेनरमा सेयर थिच्नुहोस्।", + "Press to see it, or disconnect it.": "हेर्न थिच्नुहोस्, वा डिस्कनेक्ट गर्नुहोस्।", + "Press to try again": "फेरि गर्न थिच्नुहोस्", + "Previous match": "अघिल्लो मिल्ने", + "Previous run": "अघिल्लो रन", + "Printed once in the container's log.": "कन्टेनरको लगमा एक पटक देखाइन्छ।", + "Private images won't pull until you sign in again.": "फेरि साइन इन नगरेसम्म प्राइभेट इमेज पुल हुँदैनन्।", + "Processes": "प्रोसेस", + "Progress": "प्रगति", + "Protocol": "प्रोटोकल", + "Proxy": "प्रोक्सी", + "Proxy settings saved": "प्रोक्सी सेटिङ सेभ भयो", + "Public images need no sign-in": "पब्लिक इमेजका लागि साइन इन चाहिँदैन", + "Public images on public.ecr.aws need nothing. For your own account's registry, Kiri runs {cmd} with this profile.": "public.ecr.aws का पब्लिक इमेजलाई केही चाहिँदैन। तपाईंको आफ्नै अकाउन्टको registry का लागि Kiri ले यो प्रोफाइलसँग {cmd} चलाउँछ।", + "Public images pull without signing in.": "पब्लिक इमेज साइन इन बिना पुल हुन्छन्।", + "Publish": "पब्लिस गर्नुहोस्", + "Publish on {targets}": "{targets} मा पब्लिस गर्नुहोस्", + "Publish the port {name} listens on, and give it a public https link": "{name} ले सुन्ने पोर्ट पब्लिस गर्नुहोस्, र यसलाई पब्लिक https लिङ्क दिनुहोस्", + "Pull": "पुल गर्नुहोस्", + "Pull again": "फेरि पुल गर्नुहोस्", + "Pull an image": "इमेज पुल गर्नुहोस्", + "Pull an image ({key})": "इमेज पुल गर्नुहोस् ({key})", + "Pull exactly this": "ठ्याक्कै यही पुल गर्नुहोस्", + "Pull from": "कहाँबाट पुल गर्ने", + "Pull image": "इमेज पुल गर्नुहोस्", + "Pull {tag}": "{tag} पुल गर्नुहोस्", + "Pulled": "पुल गरेको", + "Pulled {name}": "{name} पुल भयो", + "Pulled {name} in {time}.": "{name} {time} मा पुल भयो।", + "Pulled {when}": "{when} पुल गरेको", + "Pulling": "पुल हुँदैछ", + "Pulling {n}": "{n} पुल हुँदैछ", + "Purple": "बैजनी", + "Quit": "बन्द गर्नुहोस्", + "Quit Kiri": "Kiri बन्द गर्नुहोस्", + "Quit {app}": "{app} बन्द गर्नुहोस्", + "Quote {id} if you write to us about this crash.": "यो क्र्यासबारे हामीलाई लेख्दा {id} उल्लेख गर्नुहोस्।", + "Radio": "रेडियो", + "Ran": "चलेका", + "Reachable at {addr}": "{addr} मा खुल्छ", + "Reachable at {url}": "{url} मा खुल्छ", + "Read more on runkiri.com ↗": "runkiri.com मा थप पढ्नुहोस् ↗", + "Reading build history…": "बिल्डको इतिहास पढ्दै…", + "Reading the image…": "इमेज पढ्दै…", + "Reading the log…": "लग पढ्दै…", + "Reading the scans…": "स्क्यानहरू पढ्दै…", + "Reading what {name} has…": "{name} मा के-के छ हेर्दै…", + "Ready": "तयार", + "Recent crashes": "हालैका क्र्यास", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "केही बिग्रँदा काम लाग्ने, हालैका लग, क्र्यास रिपोर्ट र भर्सनहरू एउटै फाइलमा, गोप्य कुरा हटाएर।", + "Recent pulls": "हालैका पुल", + "Recommended": "सिफारिस", + "Reconnecting": "फेरि कनेक्ट हुँदैछ", + "Reconnecting {name}…": "{name} फेरि कनेक्ट हुँदैछ…", + "Reconnecting · {reason}": "फेरि कनेक्ट हुँदैछ · {reason}", + "Reconnecting…": "फेरि कनेक्ट हुँदैछ…", + "Redo": "रिडु गर्नुहोस्", + "Registries": "Registry", + "Registries reached without a verified certificate (self-signed, or plain HTTP). Kiri tries HTTPS without checking the certificate, then HTTP. Only the hosts and networks listed; every other registry is checked as usual.": "प्रमाणित सर्टिफिकेट बिना पुगिने registry हरू (सेल्फ-साइन गरिएको, वा सादा HTTP)। Kiri ले पहिले सर्टिफिकेट नजाँची HTTPS प्रयास गर्छ, अनि HTTP। सूचीमा राखिएका होस्ट र नेटवर्क मात्र; अरू सबै registry सधैंझैं जाँचिन्छन्।", + "Registry": "Registry", + "Registry mirrors": "Registry मिरर", + "Registry settings saved": "Registry सेटिङ सेभ भयो", + "Reload": "रिलोड गर्नुहोस्", + "Remove": "हटाउनुहोस्", + "Remove Kubernetes' container?": "Kubernetes को कन्टेनर हटाउने?", + "Remove all": "सबै हटाउनुहोस्", + "Remove both": "दुवै हटाउनुहोस्", + "Remove network {name}?": "नेटवर्क {name} हटाउने?", + "Remove project": "प्रोजेक्ट हटाउनुहोस्", + "Remove this build from the history?": "यो बिल्ड इतिहासबाट हटाउने?", + "Remove this port": "यो पोर्ट हटाउनुहोस्", + "Remove volume {name}?": "भोल्युम {name} हटाउने?", + "Remove {name} and {image}?": "{name} र {image} हटाउने?", + "Remove {name}?": "{name} हटाउने?", + "Remove {n} containers and {image}?": "{n} कन्टेनर र {image} हटाउने?", + "Remove {n} untagged": "ट्याग नभएका {n} हटाउनुहोस्", + "Removed {gone} of {n} {what}": "{n} {what} मध्ये {gone} हटाइयो", + "Removed {name}": "{name} हटाइयो", + "Removed {n} {what}": "{n} {what} हटाइयो", + "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "{cmd} ले जस्तै क्लस्टरको कन्टेनर, त्यसभित्रको सबै ({volume} भोल्युम) र {context} kubectl context हटाउँछ।", + "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "एरर सहित बन्द भएको {n} कन्टेनर, यसका फाइलसहित हटाउँछ। नाम भएका भोल्युम रहन्छन्।", + "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "एरर सहित बन्द भएका {n} कन्टेनर, तिनका फाइलसहित हटाउँछ। नाम भएका भोल्युम रहन्छन्।", + "Removes the {n} failed build from the history.": "फेल भएको {n} बिल्ड इतिहासबाट हटाउँछ।", + "Removes the {n} failed builds from the history.": "फेल भएका {n} बिल्ड इतिहासबाट हटाउँछ।", + "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "रिबिल्डले छोडेको ट्याग नभएको {n} इमेज हटाउँछ। यसलाई कसैले प्रयोग गर्दैन। {size} खाली हुन्छ।", + "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "रिबिल्डले छोडेका ट्याग नभएका {n} इमेज हटाउँछ। तिनलाई कसैले प्रयोग गर्दैन। {size} खाली हुन्छ।", + "Removing {gone} of {n}…": "हटाउँदै {n} मध्ये {gone}…", + "Report ID": "रिपोर्ट ID", + "Report sent": "रिपोर्ट पठाइयो", + "Repository": "रिपोजिटरी", + "Requests to {name}": "{name} मा आएका रिक्वेस्ट", + "Resources": "रिसोर्स", + "Restart": "रिस्टार्ट गर्नुहोस्", + "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "पूरा गर्न Kiri रिस्टार्ट गर्नुहोस्। चलिरहेका कन्टेनर रोकिन्छन्, र रिस्टार्ट नीति भएकाहरू फेरि सुरु हुन्छन्।", + "Restart VM to apply": "लागू गर्न VM रिस्टार्ट गर्नुहोस्", + "Restart all": "सबै रिस्टार्ट गर्नुहोस्", + "Restart engine": "इन्जिन रिस्टार्ट गर्नुहोस्", + "Restart engine to finish": "पूरा गर्न इन्जिन रिस्टार्ट गर्नुहोस्", + "Restart later": "पछि रिस्टार्ट गर्ने", + "Restart now": "अहिले रिस्टार्ट गर्नुहोस्", + "Restart to update": "अपडेट गर्न रिस्टार्ट गर्नुहोस्", + "Restart {name} with the new environment?": "{name} लाई नयाँ इन्भाइरनमेन्टसँग रिस्टार्ट गर्ने?", + "Restarting stops the running containers; start them again afterwards.": "रिस्टार्ट गर्दा चलिरहेका कन्टेनर रोकिन्छन्; पछि फेरि सुरु गर्नुहोस्।", + "Restarting…": "रिस्टार्ट हुँदैछ…", + "Restarts": "रिस्टार्ट", + "Restore": "पहिलेजस्तै बनाउनुहोस्", + "Resume": "फेरि चलाउनुहोस्", + "Retry": "फेरि गर्नुहोस्", + "Retry starts it again; the layers already here are kept.": "“फेरि गर्नुहोस्” ले फेरि सुरु गर्छ; यहाँ आइसकेका लेयर राखिन्छन्।", + "Review": "हेर्नुहोस्", + "Run": "चलाउनुहोस्", + "Run a test container": "टेस्ट कन्टेनर चलाउने", + "Run {cmd}, then Retry.": "{cmd} चलाउनुहोस्, अनि “फेरि गर्नुहोस्” थिच्नुहोस्।", + "Running": "चलिरहेको", + "Running Kiri {version} · back in {time}": "Kiri {version} चलिरहेको · {time} मा फर्कियो", + "Running containers answer at <name>.kiri.localhost, which needs no setup.": "चलिरहेका कन्टेनर <name>.kiri.localhost मा खुल्छन्, जसका लागि केही सेटअप चाहिँदैन।", + "Running now with {cpus} and up to {mem}.": "अहिले {cpus} र {mem} सम्म लिएर चलिरहेको छ।", + "Running, not ready": "चलिरहेको, तयार छैन", + "Running: it rests by itself when nothing runs and wakes when you use it.": "चलिरहेको: केही नचल्दा आफैं आराम गर्छ र प्रयोग गर्दा ब्युँझिन्छ।", + "Running: {cmd}": "चलिरहेको: {cmd}", + "Runs": "चलाउँछ", + "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "हरेक कमान्ड {name} मा {sh} ले चलाउँछ; {cd} अर्को कमान्डसम्म रहन्छ। ↑ र ↓ ले अघिल्ला कमान्डहरू देखाउँछ।", + "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "यहीँ तपाईंको Mac मा Kiri को इमेज कपीमाथि चल्छ; केही अपलोड हुँदैन।", + "Runs your containers": "तपाईंका कन्टेनर चलाउँछ", + "SQL Server won't start without a strong password for its sa account, and its licence accepted.": "sa अकाउन्टको बलियो पासवर्ड र लाइसेन्स स्वीकार नगरी SQL Server सुरु हुँदैन।", + "Same as the window ({font})": "विन्डोकै जस्तो ({font})", + "Same as {os}": "{os} कै जस्तो", + "Save": "सेभ गर्नुहोस्", + "Save SBOM": "SBOM सेभ गर्नुहोस्", + "Save and start": "सेभ गरेर सुरु गर्नुहोस्", + "Save to Desktop": "Desktop मा सेभ गर्नुहोस्", + "Save to Downloads": "Downloads मा सेभ गर्नुहोस्", + "Save {name}'s new environment?": "{name} को नयाँ इन्भाइरनमेन्ट सेभ गर्ने?", + "Saved in .wslconfig. WSL uses these from its next start": ".wslconfig मा सेभ भयो। WSL ले अर्को पटक सुरु हुँदा यी प्रयोग गर्छ", + "Saved in the container's environment. Kiri doesn't keep a copy.": "कन्टेनरको इन्भाइरनमेन्टमा सेभ हुन्छ। Kiri ले कपी राख्दैन।", + "Saved in this container's environment. Kiri doesn't keep a copy.": "यो कन्टेनरको इन्भाइरनमेन्टमा सेभ हुन्छ। Kiri ले कपी राख्दैन।", + "Saved the SBOM to Downloads as {file}": "SBOM Downloads मा {file} नामले सेभ भयो", + "Saved the report to {path}": "रिपोर्ट {path} मा सेभ भयो", + "Saved to Downloads as {file}": "Downloads मा {file} नामले सेभ भयो", + "Saved. The VM uses these from its next start": "सेभ भयो। VM ले अर्को पटक सुरु हुँदा यी प्रयोग गर्छ", + "Saving…": "सेभ हुँदैछ…", + "Scan again": "फेरि स्क्यान गर्नुहोस्", + "Scan image": "इमेज स्क्यान गर्नुहोस्", + "Scan of {when}": "{when} को स्क्यान", + "Scan with": "स्क्यान गर्ने टुल", + "Scan {image}": "{image} स्क्यान गर्नुहोस्", + "Scan {image} for known vulnerabilities": "{image} मा थाहा भएका सुरक्षा कमजोरी स्क्यान गर्नुहोस्", + "Scanned": "स्क्यान गरेको", + "Scanning the image's packages": "इमेजका प्याकेजहरू स्क्यान हुँदैछन्", + "Scans": "स्क्यान", + "Search Docker Hub, or paste an image reference": "Docker Hub मा सर्च गर्नुहोस्, वा इमेज रेफरेन्स पेस्ट गर्नुहोस्", + "Search Kiri": "Kiri मा सर्च गर्नुहोस्", + "Search Kiri…": "Kiri मा सर्च गर्नुहोस्…", + "Search containers, images…": "कन्टेनर, इमेज… सर्च गर्नुहोस्", + "Search languages": "भाषा सर्च गर्नुहोस्", + "Search {view}…": "{view} सर्च गर्नुहोस्…", + "Searching Docker Hub": "Docker Hub मा सर्च हुँदैछ", + "Security": "सुरक्षा", + "See it ↗": "हेर्नुहोस् ↗", + "See its tags": "यसका ट्याग हेर्नुहोस्", + "See what it looks like ↗": "कस्तो देखिन्छ हेर्नुहोस् ↗", + "See why": "किन भयो हेर्नुहोस्", + "Select": "छान्नुहोस्", + "Select All": "सबै छान्नुहोस्", + "Select all": "सबै छान्नुहोस्", + "Select all {n}": "सबै {n} छान्नुहोस्", + "Select none": "छानेको हटाउनुहोस्", + "Select {name}": "{name} छान्नुहोस्", + "Selected {what}": "छानिएका {what}", + "Selection, focus rings and primary buttons.": "छानिएको कुरा, फोकस रिङ र मुख्य बटनहरू।", + "Selector": "सेलेक्टर", + "Send": "पठाउनुहोस्", + "Send a report to Kiri": "Kiri लाई रिपोर्ट पठाउनुहोस्", + "Send an idea or report a bug on GitHub": "GitHub मा आइडिया पठाउनुहोस् वा बग रिपोर्ट गर्नुहोस्", + "Send crash reports automatically": "क्र्यास रिपोर्ट आफैं पठाउने", + "Send report": "रिपोर्ट पठाउनुहोस्", + "Send to Kiri": "Kiri लाई पठाउनुहोस्", + "Sending…": "पठाउँदै…", + "Sent": "पठाइयो", + "Sent as {id}": "{id} नामले पठाइयो", + "Sent. Quote {id} if you write to us.": "पठाइयो। हामीलाई लेख्दा {id} उल्लेख गर्नुहोस्।", + "Serial": "सिरियल", + "Serial number": "सिरियल नम्बर", + "Services": "सर्भिस", + "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "kubectl expose ले बनाएका सर्भिस यहाँ देखिन्छन्। LoadBalancer सर्भिसहरू localhost मा खुल्छन्।", + "Session": "सेसन", + "Set it and start": "सेट गरेर सुरु गर्नुहोस्", + "Set up": "सेटअप गर्नुहोस्", + "Set up Kiri": "Kiri सेटअप गर्नुहोस्", + "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "docker build यहीँ चलोस् भनेर Kiri को बिल्डर सेटअप गर्नुहोस्। पहिलो बिल्ड नगरेसम्म केही डाउनलोड हुँदैन", + "Set up with Kiri Linux": "Kiri Linux छानेर सेटअप गर्नुहोस्", + "Set up with Ubuntu": "Ubuntu छानेर सेटअप गर्नुहोस्", + "Set {what}": "{what} सेट गर्नुहोस्", + "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Microsoft को इमेजले मागेजस्तै ACCEPT_EULA=Y सेट गर्छ।", + "Setting up": "सेटअप हुँदैछ", + "Setting up Docker tools…": "Docker टुलहरू सेटअप हुँदैछन्…", + "Setting up Docker tools… {pct}%": "Docker टुलहरू सेटअप हुँदैछन्… {pct}%", + "Setting up Kiri Linux": "Kiri Linux सेटअप हुँदैछ", + "Setting up Ubuntu 26.04": "Ubuntu 26.04 सेटअप हुँदैछ", + "Setting up the Docker tools": "Docker टुलहरू सेटअप हुँदैछन्", + "Settings": "सेटिङ", + "Settings…": "सेटिङ…", + "Setup log": "सेटअपको लग", + "Setup steps": "सेटअपका चरणहरू", + "Setup time": "सेटअप समय", + "Severity": "गम्भीरता", + "Share": "सेयर", + "Share again": "फेरि सेयर गर्नुहोस्", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "सेयरले कन्टेनर वा Kubernetes सर्भिसलाई Kiri Cloud सम्मको सुरक्षित टनेलबाट पब्लिक https लिङ्क दिन्छ।", + "Share pod {name}?": "पोड {name} सेयर गर्ने?", + "Share service {name}": "सर्भिस {name} सेयर गर्नुहोस्", + "Share this pod on a port…": "यो पोड कुनै पोर्टमा सेयर गर्नुहोस्…", + "Share this pod's port {port}": "यो पोडको पोर्ट {port} सेयर गर्नुहोस्", + "Share which port?": "कुन पोर्ट सेयर गर्ने?", + "Share {name}": "{name} सेयर गर्नुहोस्", + "Shared": "सेयर गरिएको", + "Shared by {who}": "{who} ले सेयर गरेको", + "Shared now": "अहिले सेयर भएका", + "Shared with {os}: the VM only uses them while containers are busy.": "{os} सँग बाँडिएको: कन्टेनर व्यस्त हुँदा मात्र VM ले यी प्रयोग गर्छ।", + "Shared · {url}": "सेयर गरिएको · {url}", + "Shares": "सेयर", + "Sharing…": "सेयर हुँदैछ…", + "Short of memory, its API server slows down or stops answering.": "मेमोरी नपुग्दा यसको API सर्भर ढिलो हुन्छ वा जवाफ दिन छोड्छ।", + "Show": "देखाउनुहोस्", + "Show Images": "इमेज देखाउनुहोस्", + "Show all actions": "सबै काम देखाउनुहोस्", + "Show containers": "कन्टेनर देखाउनुहोस्", + "Show full log": "पूरा लग देखाउनुहोस्", + "Show in Diagnostics": "डायग्नोस्टिक्समा देखाउनुहोस्", + "Show in Finder": "Finder मा देखाउनुहोस्", + "Show its requests": "यसका रिक्वेस्ट देखाउनुहोस्", + "Show password": "पासवर्ड देखाउनुहोस्", + "Show shares": "सेयरहरू देखाउनुहोस्", + "Show the crash report": "क्र्यास रिपोर्ट देखाउनुहोस्", + "Show the pulls in Images": "पुलहरू इमेजमा देखाउनुहोस्", + "Show the sidebar": "साइडबार देखाउनुहोस्", + "Show the terminal ({keys})": "टर्मिनल देखाउनुहोस् ({keys})", + "Show the update": "अपडेट हेर्नुहोस्", + "Sign in": "साइन इन गर्नुहोस्", + "Sign in and pull": "साइन इन गरेर पुल गर्नुहोस्", + "Sign in to a registry": "registry मा साइन इन गर्नुहोस्", + "Sign in to a registry…": "registry मा साइन इन गर्नुहोस्…", + "Sign in to see your plan": "प्लान हेर्न साइन इन गर्नुहोस्", + "Sign in to share {what}": "{what} सेयर गर्न साइन इन गर्नुहोस्", + "Sign in to {registry}": "{registry} मा साइन इन गर्नुहोस्", + "Sign in with AWS": "AWS बाट साइन इन गर्नुहोस्", + "Sign in with GitHub": "GitHub बाट साइन इन गर्नुहोस्", + "Sign out": "साइन आउट गर्नुहोस्", + "Sign out of {registry}": "{registry} बाट साइन आउट गर्नुहोस्", + "Sign out of {registry}?": "{registry} बाट साइन आउट गर्ने?", + "Sign-in failed: {error}": "साइन इन फेल भयो: {error}", + "Sign-in needed.": "साइन इन चाहिन्छ।", + "Signed in": "साइन इन गरिएको", + "Signed in as {name}": "{name} भएर साइन इन गरिएको", + "Signed in as {name}.": "{name} भएर साइन इन गरिएको।", + "Signed in to Kiri Cloud with GitHub as {login}": "GitHub बाट {login} भएर Kiri Cloud मा साइन इन गरिएको", + "Signed in to a registry, Kiri pulls its private images, and docker uses the same sign-in.": "registry मा साइन इन भएपछि Kiri ले त्यसका प्राइभेट इमेज पुल गर्छ, र docker ले पनि उही साइन इन प्रयोग गर्छ।", + "Signed in with GitHub": "GitHub बाट साइन इन गरिएको", + "Signing in again uses your AWS profile.": "फेरि साइन इन गर्दा तपाईंको AWS प्रोफाइल प्रयोग हुन्छ।", + "Signing in…": "साइन इन हुँदैछ…", + "Signing out…": "साइन आउट हुँदैछ…", + "Size": "साइज", + "Skip": "छोड्नुहोस्", + "Skip this version": "यो भर्सन छोड्नुहोस्", + "Skipped: docker build builds where docker points": "छोडियो: docker जुन इन्जिनमा जोडिएको छ, docker build त्यहीँ बिल्ड गर्छ", + "Skipped: docker keeps using the engine it has now": "छोडियो: docker ले अहिलेकै इन्जिन चलाइरहन्छ", + "Skipped: {problem}": "छोडियो: {problem}", + "Slow because the VM is out of memory": "VM को मेमोरी सकिएकाले ढिलो छ", + "Small": "सानो", + "Smaller": "सानो", + "Snooze ▾": "पछि सम्झाउनुहोस् ▾", + "Something else on this {host} has it. Give {name} another port.": "यो {host} मा अरू केहीले यो लिएको छ। {name} लाई अर्को पोर्ट दिनुहोस्।", + "Something went wrong": "केही गडबड भयो", + "Soon": "छिट्टै", + "Speed": "स्पिड", + "Split down": "तल स्प्लिट गर्नुहोस्", + "Split down ({keys})": "तल स्प्लिट गर्नुहोस् ({keys})", + "Split right": "दायाँ स्प्लिट गर्नुहोस्", + "Split right ({keys})": "दायाँ स्प्लिट गर्नुहोस् ({keys})", + "Start": "सुरु गर्नुहोस्", + "Start Kiri": "Kiri सुरु गर्नुहोस्", + "Start Kiri to change its network settings. ({error})": "नेटवर्क सेटिङ बदल्न Kiri सुरु गर्नुहोस्। ({error})", + "Start Kiri to change its registry settings. ({error})": "Registry सेटिङ बदल्न Kiri सुरु गर्नुहोस्। ({error})", + "Start Kiri to change its resources. ({error})": "रिसोर्स बदल्न Kiri सुरु गर्नुहोस्। ({error})", + "Start Kiri to change the ports names answer on.": "नामहरू कुन पोर्टमा खुल्छन् बदल्न Kiri सुरु गर्नुहोस्।", + "Start Kiri when I sign in (in the tray)": "साइन इन गर्दा Kiri सुरु गर्ने (ट्रेमा)", + "Start Kubernetes": "Kubernetes सुरु गर्नुहोस्", + "Start Linux VM": "Linux VM सुरु गर्नुहोस्", + "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "एउटा Kiri कन्टेनरमा एउटै नोडको क्लस्टर (k3s) सुरु गर्नुहोस्। यसको API {api} मा (वा अर्को खाली पोर्टमा) हुन्छ, र kubectl ले {context} context पाउँछ, kiri k8s start मा जस्तै।", + "Start again": "फेरि सुरु गर्नुहोस्", + "Start all": "सबै सुरु गर्नुहोस्", + "Start engine": "इन्जिन सुरु गर्नुहोस्", + "Start it": "यसलाई सुरु गर्ने", + "Start it to restart it": "रिस्टार्ट गर्न पहिले सुरु गर्नुहोस्", + "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "कन्टेनर चलाउन यसलाई सुरु गर्नुहोस्। यो एक सेकेन्डभन्दा कममा सुरु हुन्छ र काम नहुँदा स्लिपमा जान्छ।", + "Start it to share it": "सेयर गर्न पहिले सुरु गर्नुहोस्", + "Start scan": "स्क्यान सुरु गर्नुहोस्", + "Start the container to run commands in it.": "यसमा कमान्ड चलाउन पहिले कन्टेनर सुरु गर्नुहोस्।", + "Start the engine": "इन्जिन सुरु गर्ने", + "Start {engine} to bring its images over now, or later from Settings → Import.": "इमेजहरू अहिले ल्याउन {engine} सुरु गर्नुहोस्, वा पछि सेटिङ → इम्पोर्टबाट ल्याउनुहोस्।", + "Started": "सुरु भएको", + "Started with {name} set": "{name} सेट गरेर सुरु भयो", + "Started {name}": "{name} सुरु भयो", + "Started {name} on {ports}": "{name} {ports} मा सुरु भयो", + "Starting": "सुरु हुँदैछ", + "Starting Kiri’s engine": "Kiri को इन्जिन सुरु हुँदैछ", + "Starting Kubernetes…": "Kubernetes सुरु हुँदैछ…", + "Starting the scan": "स्क्यान सुरु हुँदैछ", + "Starting…": "सुरु हुँदैछ…", + "State": "स्टेटस", + "Status": "स्टेटस", + "Step 1 of 5": "चरण 1/5", + "Step 2 of 5": "चरण 2/5", + "Step 2 of 5. Nothing else on this PC changes: Kiri sets itself up for your Windows account only.": "चरण 2/5। यो PC मा अरू केही बदलिँदैन: Kiri ले आफूलाई तपाईंको Windows अकाउन्टका लागि मात्र सेटअप गर्छ।", + "Step 3 of 5": "चरण 3/5", + "Step 4 of 5": "चरण 4/5", + "Steps": "स्टेप", + "Stop": "रोक्नुहोस्", + "Stop Kubernetes?": "Kubernetes रोक्ने?", + "Stop Linux VM": "Linux VM रोक्नुहोस्", + "Stop all": "सबै रोक्नुहोस्", + "Stop on {host}": "{host} मा रोक्नुहोस्", + "Stop sharing": "सेयर बन्द गर्नुहोस्", + "Stop signal": "स्टप सिग्नल", + "Stop {name}": "{name} रोक्नुहोस्", + "Stop {name} on {host}?": "{host} मा {name} रोक्ने?", + "Stopped": "रोकिएको", + "Stopped {when}": "{when} रोकियो", + "Stopped {when}, when the {vm} stopped. Start it again whenever you like.": "{when} रोकियो, {vm} रोकिँदा। जुनसुकै बेला फेरि सुरु गर्न सक्नुहुन्छ।", + "Stopped {when}: its memory ran out": "{when} रोकियो: यसको मेमोरी सकियो", + "Stopped {when}: its memory ran out (the VM has {mem})": "{when} रोकियो: यसको मेमोरी सकियो (VM मा {mem} छ)", + "Stopped: out of memory": "रोकियो: मेमोरी सकियो", + "Stopping": "रोकिँदैछ", + "Stopping…": "रोकिँदैछ…", + "Stop…": "रोक्नुहोस्…", + "Storage": "स्टोरेज", + "Strong enough": "पर्याप्त बलियो", + "Subnet": "सबनेट", + "Suggested": "सुझाव", + "Switch and import": "स्विच गरेर इम्पोर्ट गर्नुहोस्", + "Switch and import {n} item": "स्विच गरेर {n} वटा इम्पोर्ट गर्नुहोस्", + "Switch and import {n} items": "स्विच गरेर {n} वटा इम्पोर्ट गर्नुहोस्", + "Switch back": "फिर्ता स्विच गर्नुहोस्", + "Switch to the dark theme": "डार्क थिममा जानुहोस्", + "Switch to the light theme": "लाइट थिममा जानुहोस्", + "Switch to {app}": "{app} मा स्विच गर्नुहोस्", + "System": "सिस्टम", + "System Mono|font": "सिस्टम मोनोस्पेस", + "System|font": "सिस्टम", + "Tab pinned": "ट्याब पिन भयो", + "Tab unpinned": "ट्याब अनपिन भयो", + "Tables, the sidebar and headings.": "टेबल, साइडबार र हेडिङ।", + "Tag": "ट्याग", + "Teal": "टिल", + "Tell us how it goes": "कस्तो भयो हामीलाई भन्नुहोस्", + "Terminal": "टर्मिनल", + "Terminal ({keys})": "टर्मिनल ({keys})", + "Terminated": "बन्द भयो", + "Test build": "टेस्ट बिल्ड", + "Text size": "अक्षरको साइज", + "Text size {n} px": "अक्षरको साइज {n} px", + "That's a lot to copy and can take a long time; choosing what you need is quicker.": "यो कपी गर्न धेरै छ र धेरै समय लाग्न सक्छ; चाहिने मात्र छान्दा छिटो हुन्छ।", + "The 5 newest, and macOS's own crash reports for Kiri from the last 30 days": "सबैभन्दा नयाँ 5, र पछिल्ला 30 दिनमा Kiri का लागि macOS कै क्र्यास रिपोर्ट", + "The API server port must be a number from 1024 to 65535": "API सर्भर पोर्ट 1024 देखि 65535 सम्मको नम्बर हुनुपर्छ", + "The AWS CLI has no profiles yet. Set one up with {cmd}.": "AWS CLI मा अझै कुनै प्रोफाइल छैन। {cmd} ले एउटा सेटअप गर्नुहोस्।", + "The GitHub CLI stays signed in.": "GitHub CLI भने साइन इन नै रहन्छ।", + "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes को API सर्भर। यो कहिल्यै सेयर गरिँदैन: लिङ्क पाउने जो कोहीले क्लस्टर चलाउन खोज्न सक्छ।", + "The Linux VM restarted with the new resources": "Linux VM नयाँ रिसोर्ससँग रिस्टार्ट भयो", + "The VM has {mem}; {free}.": "VM मा {mem} छ; {free}।", + "The VM is asleep; it starts with these next time.": "VM स्लिपमा छ; अर्को पटक यी सेटिङसँग सुरु हुन्छ।", + "The VM's memory is nearly full: {used} of {max}.": "VM को मेमोरी लगभग भरियो: {max} मध्ये {used}।", + "The app on {host} keeps running, and {program} there shows the share as stopped from another computer.": "{host} को एप चलिरहन्छ, र त्यहाँको {program} ले यो सेयर अर्को कम्प्युटरबाट रोकिएको देखाउँछ।", + "The build failed": "बिल्ड फेल भयो", + "The build was canceled": "बिल्ड रद्द भयो", + "The code goes straight to the AWS CLI; Kiri doesn't keep it.": "कोड सिधै AWS CLI मा जान्छ; Kiri ले राख्दैन।", + "The container keeps running.": "कन्टेनर चलिरहन्छ।", + "The docker command is signed out too.": "docker कमान्ड पनि साइन आउट हुन्छ।", + "The docker command uses {app}": "docker कमान्डले {app} प्रयोग गर्छ", + "The docker command uses {engine}. Switch it to {app}": "docker कमान्डले {engine} प्रयोग गर्छ। यसलाई {app} मा बदल्नुहोस्", + "The engine": "इन्जिन", + "The engine is running but not answering": "इन्जिन चलिरहेको छ तर जवाफ दिँदैन", + "The engine is stopped": "इन्जिन रोकिएको छ", + "The engine isn't here: reinstall the kiri package": "इन्जिन यहाँ छैन: kiri प्याकेज फेरि इन्स्टल गर्नुहोस्", + "The engine still runs Kiri {version}": "इन्जिनमा अझै Kiri {version} नै चलिरहेको छ", + "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "इन्जिनमा अझै {version} चलिरहेको छ। यसलाई रिस्टार्ट गर्दा चलिरहेका कन्टेनर रोकिन्छन्, र रिस्टार्ट नीति भएकाहरू फेरि सुरु हुन्छन्।", + "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "पहिलो स्क्यानले Grype र यसको डेटाबेस डाउनलोड गर्छ, करिब 230 MB (खोलेपछि 3 GB)।", + "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Microsoft को WSL सूचीको पूरा Ubuntu। Kiri यसैभित्र चल्छ, र तपाईं यसलाई आफ्नै Linux जस्तै पनि खोल्न सक्नुहुन्छ।", + "The image's own way to start without it.": "यो बिना सुरु हुने इमेजकै आफ्नो तरिका।", + "The kiri share there stops.": "त्यहाँको kiri share रोकिन्छ।", + "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "विन्डो, इन्जिन र kiri कमान्डका पछिल्ला 300 लाइन, र इन्जिनको आफ्नै आउटपुट", + "The last {n} seconds": "पछिल्लो {n} सेकेन्ड", + "The link ends when the pod does.": "पोड सकिँदा लिङ्क पनि बन्द हुन्छ।", + "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "VM ले लिन सक्ने सबैभन्दा बढी। कन्टेनरलाई जति चाहिन्छ उति मात्र मेमोरी प्रयोग गर्छ र बाँकी {os} लाई फिर्ता दिन्छ।", + "The name comes from the Igbo word ntakịrị, “small”.": "यो नाम Igbo भाषाको ntakịrị शब्दबाट आएको हो, जसको अर्थ “सानो” हो।", + "The part that runs your containers, inside {linux}.": "तपाईंका कन्टेनर चलाउने भाग, {linux} भित्र।", + "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "यो {host} मा API सर्भरको पोर्ट, 1024 देखि 65535 सम्म (डिफल्ट 6443)। क्लस्टर सुरु हुँदा यो प्रयोगमा भए अर्को खाली पोर्ट लिइन्छ। सेभ गर्दा क्लस्टर रिस्टार्ट हुन्छ र {context} context अपडेट हुन्छ।", + "The profile {profile} asks for a code from your MFA device {device}.": "{profile} प्रोफाइलले तपाईंको MFA डिभाइस {device} बाट कोड माग्छ।", + "The profile {profile} asks for a code from your MFA device.": "{profile} प्रोफाइलले तपाईंको MFA डिभाइसबाट कोड माग्छ।", + "The profile {profile} signs in through AWS IAM Identity Center. Kiri runs {cmd}, which opens AWS's page.": "{profile} प्रोफाइल AWS IAM Identity Center बाट साइन इन हुन्छ। Kiri ले {cmd} चलाउँछ, जसले AWS को पेज खोल्छ।", + "The run before the container's last restart": "कन्टेनरको पछिल्लो रिस्टार्टअघिको रन", + "The same docker commands you know, talking to Kiri. Each file is checked against its pinned SHA-256.": "तपाईंले चलाउने उही docker कमान्ड, अब Kiri मा चल्छन्। हरेक फाइल यसको पिन गरिएको SHA-256 सँग जाँचिन्छ।", + "The window": "विन्डो", + "The {n} packages as CycloneDX JSON, saved to Downloads": "{n} प्याकेज CycloneDX JSON मा, Downloads मा सेभ हुन्छ", + "The {vm} is asleep: it holds no memory": "{vm} स्लिपमा छ: यसले कुनै मेमोरी लिएको छैन", + "Theme": "थिम", + "They appear in Images as they arrive.": "आइपुग्दै जाँदा इमेज ट्याबमा देखिन्छन्।", + "This action left no log lines.": "यो कामले कुनै लग लाइन छोडेन।", + "This build made no image to scan: it failed before exporting, or its output was the cache only.": "यो बिल्डले स्क्यान गर्ने इमेज बनाएन: एक्सपोर्ट गर्नुअघि नै फेल भयो, वा यसको आउटपुट क्यास मात्र थियो।", + "This build made no image: it failed before exporting, or its output was the cache only.": "यो बिल्डले कुनै इमेज बनाएन: एक्सपोर्ट गर्नुअघि नै फेल भयो, वा यसको आउटपुट क्यास मात्र थियो।", + "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "यो बिल्डको इमेज Kiri मा छैन, त्यसैले यहाँ स्क्यान गर्ने केही छैन। यो अन्तै पुस वा एक्सपोर्ट भयो, वा पछि हटाइयो। यहाँ स्क्यान गर्न --load सँग बिल्ड गर्नुहोस्।", + "This can't be undone.": "यो फर्काउन मिल्दैन।", + "This closes that tunnel on {host}, from here. The link stops working for everyone.": "यसले {host} को त्यो टनेल यहीँबाट बन्द गर्छ। लिङ्क सबैका लागि चल्न छोड्छ।", + "This computer can't use it while it's in Kiri: detach it to get it back.": "यो Kiri मा हुँदा यो कम्प्युटरले चलाउन सक्दैन: फिर्ता पाउन छुटाउनुहोस्।", + "This file is binary or larger than 256 KB.": "यो फाइल बाइनरी हो वा 256 KB भन्दा ठूलो छ।", + "This folder is empty.": "यो फोल्डर खाली छ।", + "This image": "यो इमेज", + "This image needs privileged mode": "यो इमेजलाई privileged मोड चाहिन्छ", + "This is Kubernetes. Kiri runs it for you": "यो Kubernetes हो। Kiri ले यो तपाईंका लागि चलाउँछ", + "This lists every link on your account, on any computer.": "यसले तपाईंको अकाउन्टका सबै लिङ्क देखाउँछ, जुनसुकै कम्प्युटरको।", + "This month": "यो महिना", + "This pod's name changes when it restarts, and the link would end.": "रिस्टार्ट हुँदा यो पोडको नाम बदलिन्छ, र लिङ्क बन्द हुन्छ।", + "This sign-in's ID: a hash of its token, safe to quote when asking for help": "यो साइन इनको ID: यसको टोकनको ह्यास, मद्दत माग्दा उल्लेख गर्न सुरक्षित", + "This system applies your new access when you sign in again. Kiri opens ready after that.": "तपाईंले फेरि साइन इन गरेपछि यो सिस्टमले नयाँ एक्सेस लागू गर्छ। त्यसपछि Kiri तयार भएर खुल्छ।", + "Time": "समय", + "To make names like {name} work, Kiri adds one small settings file to your Mac ({path}), and changing system settings always needs an administrator. Kiri uses the password only for that, once. It never sees the password: macOS handles it.": "{name} जस्ता नाम चलाउन Kiri ले तपाईंको Mac मा एउटा सानो सेटिङ फाइल ({path}) थप्छ, र सिस्टम सेटिङ बदल्न जहिले पनि एडमिन चाहिन्छ। Kiri ले पासवर्ड त्यही कामका लागि एक पटक मात्र प्रयोग गर्छ। पासवर्ड Kiri ले कहिल्यै देख्दैन: त्यो macOS ले सम्हाल्छ।", + "Today {time}": "आज {time}", + "Token": "टोकन", + "Token or password": "टोकन वा पासवर्ड", + "Tomorrow": "भोलि", + "Took": "लागेको समय", + "Traffic over the last two minutes": "पछिल्लो दुई मिनेटको ट्राफिक", + "Traffic served": "पठाइएको ट्राफिक", + "Trust Kiri's certificate so {url} works. macOS asks for your password. The certificate can only vouch for Kiri's own names.": "{url} चलाउन Kiri को सर्टिफिकेटमा भरोसा गर्नुहोस्। macOS ले तपाईंको पासवर्ड माग्छ। यो सर्टिफिकेटले Kiri कै नामको मात्र ग्यारेन्टी दिन सक्छ।", + "Try again": "फेरि गर्नुहोस्", + "Turn off engine": "इन्जिन अफ गर्नुहोस्", + "Turn on Kiri's in Settings → Kubernetes instead of starting a copy.": "कपी सुरु गर्नुको सट्टा सेटिङ → Kubernetes मा Kiri कै अन गर्नुहोस्।", + "Turn on Kubernetes": "Kubernetes अन गर्नुहोस्", + "Turn on WSL's Windows components": "WSL का Windows कम्पोनेन्टहरू अन गर्ने", + "Turn security off for local use": "लोकल प्रयोगका लागि सुरक्षा अफ गर्नुहोस्", + "Type": "किसिम", + "Type one, or generate it": "आफैं लेख्नुहोस्, वा बनाउन दिनुहोस्", + "Type to search Docker Hub, or paste a full reference such as {a} or {b} to pull exactly that.": "Docker Hub मा सर्च गर्न टाइप गर्नुहोस्, वा ठ्याक्कै त्यही पुल गर्न {a} वा {b} जस्तो पूरा रेफरेन्स पेस्ट गर्नुहोस्।", + "USB": "USB", + "USB device": "USB डिभाइस", + "USB needs usbipd-win": "USB का लागि usbipd-win चाहिन्छ", + "USB passthrough is in beta.": "USB passthrough बिटामा छ।", + "USB passthrough is new: tell us how it works with your devices": "USB passthrough नयाँ हो: तपाईंका डिभाइससँग कस्तो चल्छ हामीलाई भन्नुहोस्", + "Ubuntu is already on this PC, so choosing it downloads nothing.": "Ubuntu यो PC मा पहिल्यै छ, त्यसैले यो छान्दा केही डाउनलोड हुँदैन।", + "Undo": "अन्डु गर्नुहोस्", + "Undo brings it back": "अन्डु गर्दा फिर्ता आउँछ", + "Undo brings them back": "अन्डु गर्दा फिर्ता आउँछन्", + "Unknown": "थाहा नभएको", + "Unpack Kiri Linux": "Kiri Linux खोल्ने", + "Unpack it into WSL": "यसलाई WSL मा खोल्ने", + "Unpin tab": "ट्याब अनपिन गर्नुहोस्", + "Untagged": "ट्याग नभएको", + "Untagged; another tag still uses it": "ट्याग हटाइयो; अर्को ट्यागले अझै यो प्रयोग गर्छ", + "Unused": "प्रयोग नभएको", + "Up to date": "अपडेट छ", + "Up {time}": "{time} देखि चलिरहेको", + "Up {time} (Paused)": "{time} देखि चलिरहेको (पज गरिएको)", + "Updating": "अपडेट हुँदैछ", + "Updating the vulnerability database (about 200 MB the first time)": "कमजोरीको डेटाबेस अपडेट हुँदैछ (पहिलो पटक करिब 200 MB)", + "Upper and lower case, a digit and a symbol, 8 or more": "ठूला र साना अक्षर, एउटा अंक र एउटा चिन्ह, 8 वा बढी", + "Use AWS profile": "AWS प्रोफाइल प्रयोग गर्नुहोस्", + "Use Kiri": "Kiri प्रयोग गर्नुहोस्", + "Use Kiri Linux instead": "बरु Kiri Linux प्रयोग गर्नुहोस्", + "Use Kiri's Kubernetes": "Kiri कै Kubernetes प्रयोग गर्नुहोस्", + "Use Save to Downloads to open it.": "खोल्न “Downloads मा सेभ गर्नुहोस्” प्रयोग गर्नुहोस्।", + "Use Show in Finder to open it.": "खोल्न “Finder मा देखाउनुहोस्” प्रयोग गर्नुहोस्।", + "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Docker Hub को personal access token प्रयोग गर्नुहोस् (Account settings → Personal access tokens)।", + "Use a GitHub personal access token (classic) with the {scope} scope.": "{scope} scope भएको GitHub personal access token (classic) प्रयोग गर्नुहोस्।", + "Use a personal or deploy token with the {scope} scope.": "{scope} scope भएको personal वा deploy टोकन प्रयोग गर्नुहोस्।", + "Use another port": "अर्को पोर्ट प्रयोग गर्नुहोस्", + "Use the Ubuntu already here": "यहाँ भएकै Ubuntu प्रयोग गर्ने", + "Use this profile": "यो प्रोफाइल प्रयोग गर्नुहोस्", + "Use your AWS profile": "तपाईंको AWS प्रोफाइल प्रयोग गर्नुहोस्", + "Use your password, or a robot account's name and token.": "तपाईंको पासवर्ड, वा robot अकाउन्टको नाम र टोकन प्रयोग गर्नुहोस्।", + "Use {app} for docker?": "docker का लागि {app} प्रयोग गर्ने?", + "Use {name} instead": "बरु {name} प्रयोग गर्नुहोस्", + "Used by": "प्रयोग गर्ने", + "User": "युजर", + "Username": "युजरनेम", + "Using the Ubuntu already on this PC: nothing to download.": "यो PC मा भएकै Ubuntu प्रयोग हुँदैछ: केही डाउनलोड गर्नु पर्दैन।", + "VPNs need no setting: container traffic leaves through macOS.": "VPN का लागि कुनै सेटिङ चाहिँदैन: कन्टेनरको ट्राफिक macOS हुँदै बाहिर जान्छ।", + "Value": "मान", + "Version {version}": "भर्सन {version}", + "Versions, macOS, whether the engine runs, how many containers and images": "भर्सन, macOS, इन्जिन चलेको छ कि छैन, कति कन्टेनर र इमेज छन्", + "View": "हेर्नुहोस्", + "View container": "कन्टेनर हेर्नुहोस्", + "Visitors": "भिजिटर", + "Visitors' browsers see a short Kiri Cloud notice page first, then your app.": "भिजिटरको ब्राउजरले पहिले छोटो Kiri Cloud सूचना पेज देख्छ, अनि तपाईंको एप।", + "Volumes": "भोल्युम", + "Vulnerabilities": "कमजोरी", + "Vulnerability": "कमजोरी", + "WSL restarted with the new resources": "WSL नयाँ रिसोर्ससँग रिस्टार्ट भयो", + "WSL, downloaded from Microsoft": "WSL, Microsoft बाट डाउनलोड गरिएको", + "Waiting": "पर्खँदै", + "Waiting for GitHub…": "GitHub पर्खँदै…", + "Waiting for Windows' approval": "Windows को स्वीकृति पर्खँदै", + "Waiting for the API server…": "API सर्भर पर्खँदै…", + "Waiting for the first sample…": "पहिलो डेटा आउन पर्खँदै…", + "Waiting for the first visitor…": "पहिलो भिजिटर पर्खँदै…", + "Waiting for you to approve {code} in the browser…": "ब्राउजरमा तपाईंले {code} स्वीकृत गर्ने पर्खँदै…", + "Waiting for you to sign in in the browser…": "ब्राउजरमा तपाईंले साइन इन गर्ने पर्खँदै…", + "Warn": "चेतावनी", + "Warnings": "चेतावनी", + "Warnings and errors": "चेतावनी र एरर", + "We get the file below, redacted, and you get an ID to quote when you write to us. If you're signed in to Kiri Cloud, it says it's from you, so we can reply.": "हामीले तलको फाइल गोप्य कुरा हटाएर पाउँछौं, र तपाईंले हामीलाई लेख्दा उल्लेख गर्ने ID पाउनुहुन्छ। तपाईं Kiri Cloud मा साइन इन हुनुहुन्छ भने, यो तपाईंबाट आएको भनेर देखिन्छ, ताकि हामी जवाफ दिन सकौं।", + "Website": "वेबसाइट", + "Welcome to Kiri": "Kiri मा स्वागत छ", + "What Kiri's window uses on this {host}, not counting the {vm}:": "{vm} बाहेक, यो {host} मा Kiri को विन्डोले प्रयोग गर्ने:", + "What is WSL?": "WSL भनेको के हो?", + "What to import": "के इम्पोर्ट गर्ने", + "What's new": "नयाँ के छ", + "What's new in Kiri {version}": "Kiri {version} मा नयाँ के छ", + "What's new in {version}": "{version} मा नयाँ के छ", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Kiri को कुनै भाग क्र्यास हुँदा, स्ट्याक ट्रेस र त्यसअघिका पछिल्ला 200 लग लाइन Kiri Cloud मा जान्छन्, साथमा Kiri र सिस्टमको भर्सन, कम्प्युटरको मोडल र यो इन्स्टलको र्‍यान्डम ID। तपाईंको Kiri Cloud अकाउन्ट कहिल्यै जाँदैन, कन्टेनर भित्रको केही पनि जाँदैन। तपाईंको होम फोल्डर, इमेज र कन्टेनरका नाम, टोकन र पासवर्ड हटाइन्छन्।", + "When the pod restarts, it gets a new name and the link ends.": "पोड रिस्टार्ट हुँदा यसले नयाँ नाम पाउँछ र लिङ्क बन्द हुन्छ।", + "Where should your containers run?": "तपाईंका कन्टेनर कहाँ चलाउने?", + "Which steps": "कुन स्टेप", + "Window": "विन्डो", + "Windows Subsystem for Linux": "Windows Subsystem for Linux", + "Windows asks for an administrator's approval once.": "Windows ले एक पटक एडमिनको स्वीकृति माग्छ।", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows ले USB डिभाइसहरू WSL लाई दिन्छ, जहाँ Kiri का कन्टेनर चल्छन्, Microsoft ले सिफारिस गरेको usbipd-win टुल मार्फत।", + "Windows is asking": "Windows ले सोध्दैछ", + "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows सुरु हुँदा Virtual Machine Platform अन गर्छ। त्यसपछि Kiri आफैं फेरि खुल्छ र चरण 2 बाट अगाडि बढ्छ। पहिले आफ्नो काम सेभ गर्नुहोस्।", + "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "यो सकिएपछि Windows एक पटक रिस्टार्ट गर्नुपर्छ। रिस्टार्ट गर्नुअघि Kiri ले सोध्छ, त्यसैले पहिले आफ्नो काम सेभ गर्न सक्नुहुन्छ।", + "With a fix": "फिक्स भएका", + "Working dir": "वर्किङ डिरेक्टरी", + "Yesterday {time}": "हिजो {time}", + "You already have {engine}. Which should build your images?": "तपाईंसँग पहिल्यै {engine} छ। तपाईंका इमेज कसले बिल्ड गर्ने?", + "You can change it later in Settings → Appearance.": "यो पछि सेटिङ → देखावटमा बदल्न सक्नुहुन्छ।", + "You can change this later in Settings → Domains.": "यो पछि सेटिङ → डोमेनमा बदल्न सक्नुहुन्छ।", + "You can keep working while they copy.": "कपी हुँदै गर्दा तपाईं काम गरिरहन सक्नुहुन्छ।", + "You can pull it again later.": "पछि फेरि पुल गर्न सक्नुहुन्छ।", + "You can still pull the name as typed.": "टाइप गरेजस्तै नाम भने पुल गर्न सक्नुहुन्छ।", + "You can switch any time in Settings → Builds.": "सेटिङ → बिल्डमा जुनसुकै बेला बदल्न सक्नुहुन्छ।", + "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "तपाईंसँग {ref} छ, {when}। अपडेट पाउन फेरि पुल गर्नुहोस्; बदलिएका लेयर मात्र डाउनलोड हुन्छन्।", + "You have {ref}. Pull again to get any updates; only changed layers download.": "तपाईंसँग {ref} छ। अपडेट पाउन फेरि पुल गर्नुहोस्; बदलिएका लेयर मात्र डाउनलोड हुन्छन्।", + "You have {tags}": "तपाईंसँग {tags} छ", + "You have {version}": "तपाईंसँग {version} छ", + "You have {version}.": "तपाईंसँग {version} छ।", + "You sign in on github.com. Kiri gets a token that can only read packages.": "तपाईं github.com मा साइन इन गर्नुहुन्छ। Kiri ले प्याकेज पढ्न मात्र मिल्ने टोकन पाउँछ।", + "You're sharing {name}": "तपाईं {name} सेयर गर्दै हुनुहुन्छ", + "Your AWS sign-in expired": "तपाईंको AWS साइन इनको म्याद सकियो", + "Your account can use Kiri": "तपाईंको अकाउन्टले Kiri चलाउन सक्छ", + "Your containers keep running while it downloads.": "डाउनलोड हुँदा पनि तपाईंका कन्टेनर चलिरहन्छन्।", + "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "केही लेख्नुअघि तपाईंको होम फोल्डरको पाथ, टोकन, पासवर्ड र अरू गोप्य कुरा खाली गरिन्छन्।", + "Your link for {name} is live.": "{name} को लिङ्क लाइभ छ।", + "Your other Docker": "तपाईंको अर्को Docker", + "Your own registry…": "तपाईंको आफ्नै registry…", + "Your password and two-step code go to Docker, not Kiri.": "तपाईंको पासवर्ड र दुई-चरणको कोड Docker मा जान्छ, Kiri मा होइन।", + "Your password, or an access token if the registry offers them.": "तपाईंको पासवर्ड, वा registry ले दिन्छ भने एक्सेस टोकन।", + "Your plan allows {limit} tunnels at once, and all {limit} are in use: {slots}.": "तपाईंको प्लानमा एकै पटक {limit} टनेल चल्छन्, र सबै {limit} प्रयोगमा छन्: {slots}।", + "Your plan allows {limit} tunnels at once. In use: {slots}.": "तपाईंको प्लानमा एकै पटक {limit} टनेल चल्छन्। प्रयोगमा: {slots}।", + "Your plan allows {limit} tunnels at once; close one first.": "तपाईंको प्लानमा एकै पटक {limit} टनेल मात्र चल्छन्; पहिले एउटा बन्द गर्नुहोस्।", + "Your plan allows {n} at once": "तपाईंको प्लानमा एकै पटक {n} चल्छन्", + "Your test container said hello. Open a new terminal and try it yourself:": "तपाईंको टेस्ट कन्टेनरले नमस्ते भन्यो। नयाँ टर्मिनल खोलेर आफैं चलाएर हेर्नुहोस्:", + "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "तपाईंका {engine} इमेज र कन्टेनर {engine} मै रहन्छन्। यता नल्याएसम्म {app} ले ती देख्दैन।", + "Your {engine} images stay there. Bring them over any time from Settings → Import.": "तपाईंका {engine} इमेज त्यहीँ रहन्छन्। सेटिङ → इम्पोर्टबाट जुनसुकै बेला ल्याउन सक्नुहुन्छ।", + "Yours": "तपाईंकै", + "Zoom In": "जुम इन", + "Zoom Out": "जुम आउट", + "a container": "एउटा कन्टेनर", + "a free port": "खाली पोर्ट", + "a password": "पासवर्ड", + "a root password": "root पासवर्ड", + "a saved token": "सेभ गरिएको टोकन", + "about {min} min left": "करिब {min} मिनेट बाँकी", + "about {n} min left": "करिब {n} मिनेट बाँकी", + "about {n} s left": "करिब {n} सेकेन्ड बाँकी", + "about {sec} s left": "करिब {sec} सेकेन्ड बाँकी", + "about {time} left": "करिब {time} बाँकी", + "address": "ठेगाना", + "an admin password": "एडमिन पासवर्ड", + "and was stopped. The VM has {mem}.": "र रोकियो। VM मा {mem} छ।", + "and {n} more…": "र {n} थप…", + "anonymous": "बेनामी", + "another computer": "अर्को कम्प्युटर", + "answered in {ms} ms": "{ms} ms मा जवाफ आयो", + "approved": "स्वीकृत भयो", + "auto": "अटो", + "back": "पछाडि", + "build ID": "बिल्ड ID", + "builds": "बिल्ड", + "cached": "क्यासबाट", + "checked {ago}": "{ago} हेरिएको", + "choose tag": "ट्याग छान्नुहोस्", + "close": "बन्द", + "compose lines": "compose लाइनहरू", + "compressed": "कम्प्रेस गरिएको", + "computer": "कम्प्युटर", + "container ID": "कन्टेनर ID", + "containers": "कन्टेनर", + "couldn't pull alpine: {why}": "alpine पुल गर्न सकिएन: {why}", + "created {date}": "{date} मा बनेको", + "database from {date}": "{date} को डेटाबेस", + "digest": "डाइजेस्ट", + "disk": "डिस्क", + "disk read {read} · write {write}": "डिस्क रिड {read} · राइट {write}", + "docker build on Kiri": "Kiri मा docker build", + "docker build runs on Kiri's builder": "docker build Kiri को बिल्डरमा चल्छ", + "docker flag": "docker फ्ल्याग", + "docker now uses {app}": "docker ले अब {app} प्रयोग गर्छ", + "docker run, from any terminal": "docker run, जुनसुकै टर्मिनलबाट", + "docker talks to another engine now": "docker अहिले अर्कै इन्जिनसँग कुरा गर्छ", + "docker uses Kiri": "docker ले Kiri प्रयोग गर्छ", + "docker, Compose and Docker-socket tools reach Kiri": "docker, Compose र Docker-socket टुलहरू Kiri सम्म पुग्छन्", + "docker, docker compose and docker build use Kiri in every new terminal. Another Docker was found on this PC; leave this off to keep using it as the default.": "हरेक नयाँ टर्मिनलमा docker, docker compose र docker build ले Kiri प्रयोग गर्छन्। यो PC मा अर्को Docker भेटियो; त्यसलाई नै डिफल्ट राख्न यो अफ राख्नुहोस्।", + "docker, docker compose and docker build use Kiri in every new terminal. No other Docker was found on this PC.": "हरेक नयाँ टर्मिनलमा docker, docker compose र docker build ले Kiri प्रयोग गर्छन्। यो PC मा अरू कुनै Docker भेटिएन।", + "doesn't update itself": "आफैं अपडेट हुँदैन", + "done": "सकियो", + "downloading": "डाउनलोड हुँदैछ", + "failed": "फेल भयो", + "failed builds": "फेल भएका बिल्ड", + "failed containers": "फेल भएका कन्टेनर", + "for that user": "त्यो युजरका लागि", + "from any page": "जुनसुकै पेजबाट", + "from the container's log": "कन्टेनरको लगबाट", + "from the engine, when it tried to start it": "इन्जिनबाट, यसलाई सुरु गर्न खोज्दा", + "from the engine, when it tried to start {name}": "इन्जिनबाट, {name} सुरु गर्न खोज्दा", + "idle": "खाली", + "idle · nobody is visiting": "खाली · कोही आएको छैन", + "image ID": "इमेज ID", + "images": "इमेज", + "in": "भित्र", + "in config.json": "config.json मा", + "in progress": "हुँदैछ", + "in {time}": "{time} मा", + "input events": "इनपुट इभेन्ट", + "installed": "इन्स्टल गरिएको", + "its build cache": "यसको बिल्ड क्यास", + "just now": "भर्खरै", + "kept in {v}": "{v} मा राखिएको", + "kernel {version}": "कर्नेल {version}", + "kiri.service and the engine are in place": "kiri.service र इन्जिन इन्स्टल भइसकेका छन्", + "kubectl context": "kubectl context", + "latest": "पछिल्लो", + "layers": "लेयर", + "line {n}": "लाइन {n}", + "links open in this app": "यो एपमा खुलेका लिङ्क", + "live": "लाइभ", + "live {time}": "{time} देखि लाइभ", + "macOS will ask for an administrator password next.": "अब macOS ले एडमिन पासवर्ड माग्छ।", + "made {ago}": "{ago} बनेको", + "move": "सार्नुहोस्", + "needs privileged mode": "privileged मोड चाहिन्छ", + "needs {name}": "{name} चाहिन्छ", + "network interface": "नेटवर्क इन्टरफेस", + "networks": "नेटवर्क", + "no layer: this line only changes the image's settings": "लेयर छैन: यो लाइनले इमेजको सेटिङ मात्र बदल्छ", + "no monthly cap": "मासिक सीमा छैन", + "no speed limit": "स्पिडको सीमा छैन", + "none": "छैन", + "not in use": "प्रयोगमा छैन", + "not running": "चलिरहेको छैन", + "now": "अहिले", + "of all {cpus} CPUs · peak {peak}": "जम्मा {cpus} CPU मध्ये · सबैभन्दा बढी {peak}", + "of {cap}": "{cap} मध्ये", + "of {limit} · peak {peak}": "{limit} मध्ये · सबैभन्दा बढी {peak}", + "on other computers": "अरू कम्प्युटरमा", + "on {date} at {time}": "{date} मा {time} बजे", + "or hold {mod} and scroll": "वा {mod} थिचेर स्क्रोल गर्नुहोस्", + "out": "बाहिर", + "owner/image on {registry}, such as {example}": "{registry} मा owner/image, जस्तै {example}", + "peak {rate}": "सबैभन्दा बढी {rate}", + "pinned digest": "पिन गरिएको डाइजेस्ट", + "pods": "पोड", + "port {port}": "पोर्ट {port}", + "port {port} is in use": "पोर्ट {port} प्रयोगमा छ", + "pull": "पुल", + "pulled {when}": "{when} पुल गरेको", + "pulling alpine": "alpine पुल हुँदैछ", + "pulls now": "अहिले पुल गर्छ", + "raw HID": "raw HID", + "raw USB": "raw USB", + "received from visitors": "भिजिटरबाट आएको", + "reconnected {n}×": "{n}× फेरि कनेक्ट भयो", + "report ID": "रिपोर्ट ID", + "running on other computers on your account": "तपाईंको अकाउन्टका अरू कम्प्युटरमा चलिरहेका", + "running…": "चल्दैछ…", + "same as the user": "युजरकै जस्तो", + "saved with {v}": "{v} सँग सेभ गरिएको", + "sent to visitors": "भिजिटरलाई पठाएको", + "serial port": "सिरियल पोर्ट", + "services": "सर्भिस", + "sets {var}, for local use only.": "{var} सेट गर्छ, लोकल प्रयोगका लागि मात्र।", + "sets {var}, so it runs without a login or TLS.": "{var} सेट गर्छ, त्यसैले यो लग इन वा TLS बिना चल्छ।", + "sets {var}; it prints the password once in its log.": "{var} सेट गर्छ; यसले पासवर्ड आफ्नो लगमा एक पटक देखाउँछ।", + "settings": "सेटिङ", + "sign in to {host}": "{host} मा साइन इन गर्नुहोस्", + "skipped": "छोडियो", + "sound card": "साउन्ड कार्ड", + "tag": "ट्याग", + "the image's settings": "इमेजको सेटिङ", + "the last error lines in the container's log": "कन्टेनरको लगका पछिल्ला एरर लाइनहरू", + "the last lines in the container's log": "कन्टेनरको लगका पछिल्ला लाइनहरू", + "the link didn't open": "लिङ्क खुलेन", + "the only web port": "एउटै मात्र वेब पोर्ट", + "the port the app in it listens on": "यसभित्रको एपले सुन्ने पोर्ट", + "the saved sign-in": "सेभ गरिएको साइन इन", + "the test container did not run": "टेस्ट कन्टेनर चलेन", + "the test container did not run: {why}": "टेस्ट कन्टेनर चलेन: {why}", + "this Mac": "यो Mac", + "this PC": "यो PC", + "this build": "यो बिल्ड", + "this image": "यो इमेज", + "to do": "बाँकी", + "today at {time}": "आज {time} बजे", + "total ↓ {rx} · ↑ {tx}": "जम्मा ↓ {rx} · ↑ {tx}", + "tunnels in use": "प्रयोगमा भएका टनेल", + "untagged": "ट्याग नभएको", + "untagged images": "ट्याग नभएका इमेज", + "up": "चलेको", + "up to {size}": "{size} सम्म", + "up {time}": "{time} देखि चलेको", + "usbipd-win is installed": "usbipd-win इन्स्टल भएको छ", + "used by {names}": "{names} ले प्रयोग गरेको", + "value": "मान", + "video": "भिडियो", + "volumes": "भोल्युम", + "when the VM's {mem} ran out.": "VM को {mem} मेमोरी सकिँदा।", + "yesterday": "हिजो", + "yesterday at {time}": "हिजो {time} बजे", + "you": "तपाईं", + "your account": "तपाईंको अकाउन्ट", + "your other Docker": "तपाईंको अर्को Docker", + "{all} lines": "{all} लाइन", + "{app} doesn't update itself: rebuild it with cargo xtask app-dev": "{app} आफैं अपडेट हुँदैन: cargo xtask app-dev ले फेरि बिल्ड गर्नुहोस्", + "{app} needs a password to start": "{app} सुरु हुन पासवर्ड चाहिन्छ", + "{app} needs an admin password to start": "{app} सुरु हुन एडमिन पासवर्ड चाहिन्छ", + "{app}: its own engine, containers and settings": "{app}: यसको आफ्नै इन्जिन, कन्टेनर र सेटिङ", + "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "docker ले जुनसुकै इन्जिन प्रयोग गरे पनि {build} र {compose} Kiri मा चल्छन्, र इमेजहरू Kiri मा हुन्छन्।", + "{build} and {compose} run on Kiri, and the images are in Kiri. {engine} won't see them; run them with Kiri.": "{build} र {compose} Kiri मा चल्छन्, र इमेजहरू Kiri मा हुन्छन्। {engine} ले ती देख्दैन; तिनलाई Kiri मै चलाउनुहोस्।", + "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "docker जुन इन्जिनमा जोडिएको छ, {build} त्यहीँ बिल्ड गर्छ, त्यसैले {engine} का बिल्ड {engine} मै रहन्छन्। docker ले Kiri प्रयोग गर्दा बिल्ड Kiri मा चल्छन्।", + "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "docker जुन इन्जिनमा जोडिएको छ, {build} त्यहीँ बिल्ड गर्छ। docker ले Kiri प्रयोग गर्दा बिल्ड Kiri मा चल्छन्।", + "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} सधैं Kiri मै बिल्ड गर्छ। स्विच तुरुन्तै लागू हुन्छ, खुलिसकेका टर्मिनलमा पनि। Docker मा फर्किँदा docker का बिल्ड सेटिङ Kiri ले बदल्नुअघि जस्तै हुन्छन्।", + "{docker}, {compose} and your tools run on {app} from now on.": "अबदेखि {docker}, {compose} र तपाईंका टुलहरू {app} मा चल्छन्।", + "{done} of {total}": "{total} मध्ये {done}", + "{engine} doesn't see them.": "{engine} ले ती देख्दैन।", + "{file} ({i} of {n})": "{file} ({n} मध्ये {i})", + "{free} free of {total}": "{total} मध्ये {free} खाली", + "{got} of {total}": "{total} मध्ये {got}", + "{got} of {total} MB": "{total} MB मध्ये {got}", + "{host} isn't searchable from here, so Kiri pulls the reference as typed.": "{host} यहाँबाट सर्च गर्न मिल्दैन, त्यसैले Kiri ले टाइप गरेजस्तै रेफरेन्स पुल गर्छ।", + "{host} port {q}{port}{q} is not a port number (1–65535).": "{host} को पोर्ट {q}{port}{q} सही पोर्ट नम्बर होइन (1–65535)।", + "{host} wants a sign-in for {path}, and {user} can't pull it.": "{path} का लागि {host} ले साइन इन माग्छ, र {user} ले यो पुल गर्न सक्दैन।", + "{host} wants a sign-in for {path}.": "{path} का लागि {host} ले साइन इन माग्छ।", + "{h} h": "{h} घण्टा", + "{h} h {m} min": "{h} घण्टा {m} मिनेट", + "{image} is a whole Kubernetes cluster in a container.": "{image} कन्टेनरभित्र पूरै Kubernetes क्लस्टर हो।", + "{image} needs {what} to start": "{image} सुरु हुन {what} चाहिन्छ", + "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s} Kiri को Kubernetes क्लस्टर हो। यसलाई हटाउँदा Kubernetes अफ हुन्छ। क्लस्टरको डेटा {k8s} भोल्युममा रहन्छ; सेटिङ → Kubernetes मा “क्लस्टर डिलिट गर्नुहोस्” ले सबै हटाउँछ।", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} Kiri को Kubernetes क्लस्टर हो। यसलाई रोक्दा Kubernetes अफ हुन्छ, र फेरि सुरु नभएसम्म यसका पोडहरू रोकिन्छन्।", + "{kind} names are off: port {port} is in use. Pick another.": "{kind} नामहरू अफ छन्: पोर्ट {port} अर्कैले प्रयोग गरिरहेको छ। अर्को छान्नुहोस्।", + "{kind} names are paused: a container has port {port}.": "{kind} नामहरू रोकिएका छन्: एउटा कन्टेनरले पोर्ट {port} लिएको छ।", + "{label}, last minute": "{label}, पछिल्लो एक मिनेट", + "{list} and {last}": "{list} र {last}", + "{list} are running from this image. Stop them first, then remove the image.": "यो इमेजबाट {list} चलिरहेका छन्। पहिले तिनलाई रोक्नुहोस्, अनि इमेज हटाउनुहोस्।", + "{list} is running from this image. Stop it first, then remove the image.": "यो इमेजबाट {list} चलिरहेको छ। पहिले त्यसलाई रोक्नुहोस्, अनि इमेज हटाउनुहोस्।", + "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "{list} यही इमेजबाट बनेको हो र यो बिना फेरि सुरु हुन सक्दैन, त्यसैले त्यो पनि यसका फाइलसहित हट्छ। भोल्युम रहन्छन्।", + "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "{list} यही इमेजबाट बनेका हुन् र यो बिना फेरि सुरु हुन सक्दैनन्, त्यसैले ती पनि तिनका फाइलसहित हट्छन्। भोल्युम रहन्छन्।", + "{list}, and {last}": "{list} र {last}", + "{live} for {time}": "{time} देखि {live}", + "{live} live, {starting} starting": "{live} लाइभ, {starting} सुरु हुँदै", + "{local} names and HTTPS aren't on Linux yet.": "{local} नाम र HTTPS अझै Linux मा छैनन्।", + "{ms} average": "औसत {ms}", + "{m} min": "{m} मिनेट", + "{m} of the {n} picked": "छानिएका {n} मध्ये {m}", + "{m} of the {n} picked can't be deleted and stay.": "छानिएका {n} मध्ये {m} डिलिट गर्न मिल्दैन, ती रहन्छन्।", + "{names} on {host}": "{host} मा {names}", + "{name} didn't start": "{name} सुरु भएन", + "{name} has no tag {tag}.": "{name} मा {tag} ट्याग छैन।", + "{name} has the new environment": "{name} मा अब नयाँ इन्भाइरनमेन्ट छ", + "{name} is in Kiri": "{name} Kiri मा छ", + "{name} is in use": "{name} प्रयोगमा छ", + "{name} is listening on {ports}": "{name} {ports} मा सुनिरहेको छ", + "{name} is shared": "{name} सेयर गरिएको छ", + "{name} is shared by {who}": "{name} {who} ले सेयर गरेको छ", + "{name} is still used by the container {container}. Remove the container first.": "{name} अझै {container} कन्टेनरले प्रयोग गरिरहेको छ। पहिले कन्टेनर हटाउनुहोस्।", + "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} मा केही बदलिँदैन: इमेजहरू कपी हुन्छन्, र भोल्युमहरू पढ्न मात्र मिल्ने अस्थायी हेल्परबाट पढिन्छन्, जुन पछि हटाइन्छ। कन्टेनरहरू रोकिएकै अवस्थामा आउँछन्।", + "{name} isn't listening on a port yet, so there's nothing to share. Try again once it's up.": "{name} अझै कुनै पोर्टमा सुनिरहेको छैन, त्यसैले सेयर गर्ने केही छैन। चलेपछि फेरि गर्नुहोस्।", + "{name} isn't running. Start it to import from it; it doesn't need to stay open afterwards.": "{name} चलिरहेको छैन। त्यसबाट इम्पोर्ट गर्न सुरु गर्नुहोस्; त्यसपछि खुला राखिरहनु पर्दैन।", + "{name} needs {var} to start": "{name} सुरु हुन {var} चाहिन्छ", + "{name} ran and finished": "{name} चल्यो र सकियो", + "{name} ran out of memory": "{name} को मेमोरी सकियो", + "{name} restarted with the new environment": "{name} नयाँ इन्भाइरनमेन्टसँग रिस्टार्ट भयो", + "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} जस्ताको तस्तै रहन्छ: Kiri ले कपी मात्र गर्छ। कन्टेनरहरू रोकिएकै अवस्थामा आउँछन्।", + "{name} stays: Kubernetes is turned off or deleted in Settings → Kubernetes.": "{name} रहन्छ: Kubernetes सेटिङ → Kubernetes बाट अफ वा डिलिट गरिन्छ।", + "{name} stopped": "{name} रोकियो", + "{name} stopped after {n} s": "{name} {n} सेकेन्डपछि रोकियो", + "{name} stopped after {n} second": "{name} {n} सेकेन्डपछि रोकियो", + "{name} stopped after {n} seconds": "{name} {n} सेकेन्डपछि रोकियो", + "{name} stopped: {why}": "{name} रोकियो: {why}", + "{n} CPU": "{n} CPU", + "{n} CPUs": "{n} CPU", + "{n} added": "{n} थपियो", + "{n} cached": "{n} क्यासबाट", + "{n} change": "{n} परिवर्तन", + "{n} changed": "{n} बदलियो", + "{n} changes": "{n} परिवर्तन", + "{n} container": "{n} कन्टेनर", + "{n} containers": "{n} कन्टेनर", + "{n} d ago": "{n} दिन अघि", + "{n} days ago": "{n} दिन अघि", + "{n} device": "{n} डिभाइस", + "{n} devices": "{n} डिभाइस", + "{n} error": "{n} एरर", + "{n} errors": "{n} एरर", + "{n} external": "{n} बाहिरी", + "{n} failed container": "{n} फेल भएको कन्टेनर", + "{n} failed containers": "{n} फेल भएका कन्टेनर", + "{n} from {what}": "{what} बाट {n}", + "{n} h ago": "{n} घण्टा अघि", + "{n} image": "{n} इमेज", + "{n} image, {size}.": "{n} इमेज, {size}।", + "{n} image.": "{n} इमेज।", + "{n} images": "{n} इमेज", + "{n} images, {size}.": "{n} इमेज, {size}।", + "{n} images.": "{n} इमेज।", + "{n} in Kiri": "{n} Kiri मा", + "{n} item isn't in Kiri yet. Pick what to copy over.": "{n} वटा अझै Kiri मा छैन। के कपी गर्ने छान्नुहोस्।", + "{n} items aren't in Kiri yet. Pick what to copy over.": "{n} वटा अझै Kiri मा छैनन्। के कपी गर्ने छान्नुहोस्।", + "{n} layer": "{n} लेयर", + "{n} layers": "{n} लेयर", + "{n} line": "{n} लाइन", + "{n} lines": "{n} लाइन", + "{n} live": "{n} लाइभ", + "{n} log line": "{n} लग लाइन", + "{n} log line from the {parts}": "{parts} बाट {n} लग लाइन", + "{n} log lines": "{n} लग लाइन", + "{n} log lines from the {parts}": "{parts} बाट {n} लग लाइन", + "{n} min ago": "{n} मिनेट अघि", + "{n} of this image, newest first": "यो इमेजका {n}, नयाँ पहिले", + "{n} of {limit} tunnels in use": "{limit} मध्ये {n} टनेल प्रयोगमा", + "{n} of {total}": "{total} मध्ये {n}", + "{n} of {total} running": "{total} मध्ये {n} चलिरहेका", + "{n} on {where}": "{where} मा {n}", + "{n} optional": "{n} चाहे भर्ने", + "{n} processes": "{n} प्रोसेस", + "{n} removed": "{n} हटाइयो", + "{n} request": "{n} रिक्वेस्ट", + "{n} requests": "{n} रिक्वेस्ट", + "{n} requests · {size} served": "{n} रिक्वेस्ट · {size} पठाइयो", + "{n} result": "{n} नतिजा", + "{n} results": "{n} नतिजा", + "{n} running container": "{n} चलिरहेको कन्टेनर", + "{n} running containers": "{n} चलिरहेका कन्टेनर", + "{n} selected": "{n} छानियो", + "{n} shared": "{n} सेयर भएका", + "{n} shared · {where}": "{n} सेयर भएका · {where}", + "{n} shared, on {where}": "{n} सेयर भएका, {where} मा", + "{n} shared, {where}": "{n} सेयर भएका, {where}", + "{n} shown": "{n} देखाइएको", + "{n} stopped container": "{n} रोकिएको कन्टेनर", + "{n} stopped containers": "{n} रोकिएका कन्टेनर", + "{n} total": "जम्मा {n}", + "{n} variable": "{n} भेरिएबल", + "{n} variables": "{n} भेरिएबल", + "{n} volume": "{n} भोल्युम", + "{n} volumes": "{n} भोल्युम", + "{n} vulnerabilities in {packages} packages": "{packages} प्याकेजमा {n} कमजोरी", + "{n} vulnerability in {packages} packages": "{packages} प्याकेजमा {n} कमजोरी", + "{n} with a fix": "{n} को फिक्स छ", + "{n} {noun}": "{n} {noun}", + "{n}s ago": "{n} सेकेन्ड अघि", + "{os} settings": "{os} को सेटिङ", + "{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.": "{os} ले अटोमेटिक प्रोक्सी कन्फिगरेसन (PAC) फाइल प्रयोग गर्छ, जुन Kiri ले पछ्याउन सक्दैन। “आफ्नै” छानेर प्रोक्सी हाल्नुहोस्।", + "{owner} runs this pod": "{owner} ले यो पोड चलाउँछ", + "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}। इमेज वा भोल्युममा देखिँदैन: यो docker build भित्रको मेसिनरी हो।", + "{path} comes first on your PATH, so terminals run it instead of this Kiri. If it's an older Kiri, remove it: rm {path}": "{path} तपाईंको PATH मा पहिले आउँछ, त्यसैले टर्मिनलले यो Kiri को सट्टा त्यही चलाउँछ। पुरानो Kiri हो भने हटाउनुहोस्: rm {path}", + "{pct}% of this month's cap": "यो महिनाको सीमाको {pct}%", + "{ports} aren't web ports, so they aren't listed.": "{ports} वेब पोर्ट होइनन्, त्यसैले सूचीमा छैनन्।", + "{ports} isn't a web port, so it isn't listed.": "{ports} वेब पोर्ट होइन, त्यसैले सूचीमा छैन।", + "{program} on {host}": "{host} मा {program}", + "{q}{name}{q} can't be a name: names have no spaces or {q}={q}.": "{q}{name}{q} नाम हुन सक्दैन: नाममा स्पेस वा {q}={q} हुँदैन।", + "{rate} limit": "{rate} सीमा", + "{rate}/s limit": "{rate}/s सीमा", + "{ready} containers": "{ready} कन्टेनर", + "{running} of {all} running": "{all} मध्ये {running} चलिरहेका", + "{running} running · {total}": "{running} चलिरहेका · {total}", + "{showing} of {all} lines": "{all} मध्ये {showing} लाइन", + "{size} MB in {secs} s": "{secs} सेकेन्डमा {size} MB", + "{size} MB · already here": "{size} MB · पहिल्यै छ", + "{size} is Ubuntu's download today.": "आज Ubuntu को डाउनलोड {size} छ।", + "{size} left": "{size} बाँकी", + "{size} left this month": "यो महिना {size} बाँकी", + "{size} received": "{size} आयो", + "{size} served": "{size} पठाइयो", + "{s} s": "{s} सेकेन्ड", + "{text} with an error.": "{text}, एरर सहित।", + "{time} ago": "{time} अघि", + "{time} ago, when the VM's {mem} ran out.": "{time} अघि, VM को {mem} मेमोरी सकिँदा।", + "{used} of {total}": "{total} मध्ये {used}", + "{user} can run containers without sudo": "{user} ले sudo बिना कन्टेनर चलाउन सक्नुहुन्छ", + "{user}'s sign-in is forgotten on this computer.": "यो कम्प्युटरमा {user} को साइन इन बिर्सिन्छ।", + "{var} sets the {kind} port, so it can't be changed here.": "{var} ले {kind} पोर्ट तोक्छ, त्यसैले यहाँबाट बदल्न मिल्दैन।", + "{version} available": "{version} आएको छ", + "{version} ready": "{version} तयार छ", + "{vm} off": "{vm} अफ", + "{vm} running": "{vm} चलिरहेको", + "{what}?": "{what}?", + "{who} has it. Give {name} another port on this {host}, or stop {holder} first.": "{who} ले यो लिएको छ। {name} लाई यो {host} मा अर्को पोर्ट दिनुहोस्, वा पहिले {holder} रोक्नुहोस्।", + "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who} {when} रोकियो।{more} रिपोर्टले हामीलाई यो ठिक गर्न मद्दत गर्छ: स्ट्याक ट्रेस र त्यसअघिका पछिल्ला 200 लग लाइन, तपाईंको होम फोल्डर र टोकन खाली गरेर।", + "{who} stopped {when}.{more} Crash reports are sent automatically, so this one goes to Kiri too.": "{who} {when} रोकियो।{more} क्र्यास रिपोर्ट आफैं पठाइन्छ, त्यसैले यो पनि Kiri मा जान्छ।", + "{why}. Give the VM more memory in Settings → Resources": "{why}। सेटिङ → रिसोर्समा VM लाई बढी मेमोरी दिनुहोस्", + "{zout} smaller · {zin} bigger · {z0} reset": "{zout} सानो · {zin} ठूलो · {z0} पहिलेजस्तै", + "· the newest 500 · up to 15 MB a part is kept": "· सबैभन्दा नयाँ 500 · हरेक भागको 15 MB सम्म राखिन्छ", + "– About {ratio}× the download of Kiri Linux": "– Kiri Linux भन्दा करिब {ratio}× ठूलो डाउनलोड", + "– Kiri shares it with your own Linux work": "– Kiri ले यसलाई तपाईंको आफ्नै Linux कामसँग बाँड्छ", + "– Not a Linux to use yourself": "– आफैं चलाउने Linux होइन", + "— the end of the run before the last restart —": "— पछिल्लो रिस्टार्टअघिको रनको अन्त्य —", + "— the log stream ended —": "— लग स्ट्रिम सकियो —", + "‹ Back": "‹ पछाडि", + "★ Star on GitHub": "★ GitHub मा स्टार दिनुहोस्", + "✓ Installed": "✓ इन्स्टल भयो", + "Waiting to come back": "फर्कन पर्खँदै", + "Stop waiting": "पर्खन छोड्नुहोस्", + "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "यो फर्केपछि Kiri ले फेरि जोड्छ। यही कम्प्युटरमा राख्न “पर्खन छोड्नुहोस्” थिच्नुहोस्।", + "Fit the whole project": "पूरै प्रोजेक्ट अटाउनुहोस्", + "Find a service": "सर्भिस खोज्नुहोस्", + "docker compose up failed": "docker compose up चलेन", + "Not applied": "लागू भएन", + "Saved, but the file has an error": "सेभ भयो, तर फाइलमा एरर छ", + "Your edits stay here. Apply waits until the file is back.": "तपाईंले गरेका परिवर्तन यहीँ रहन्छन्। फाइल फिर्ता नआएसम्म «लागू गर्नुहोस्» पर्खिन्छ।", + "build": "बिल्ड", + "Queue": "क्यु", + "The file changed outside Kiri since Apply saved it": "«लागू गर्नुहोस्» ले सेभ गरेपछि फाइल Kiri बाहिरबाट बदलियो", + "Couldn't apply {name}: {error}": "{name} लागू गर्न सकिएन: {error}", + "Saved, not started yet": "सेभ भयो, अझै सुरु भएको छैन", + "image": "इमेज", + "Overwrite their changes": "उनीहरूको परिवर्तनमाथि लेख्नुहोस्", + "Recreating…": "फेरि बन्दै छ…", + "Service": "सर्भिस", + "{n} need it": "{n} लाई यो चाहिन्छ", + "CHANGES": "परिवर्तन", + "Applied {name}": "{name} लागू भयो", + "Overwrite": "माथि लेख्नुहोस्", + "Restarting": "रिस्टार्ट हुँदै छ", + "depends on": "मा निर्भर", + "{svc} stopped after Apply": "«लागू गर्नुहोस्» पछि {svc} रोकियो", + "Apply cancelled. {svc} had already changed; the rest were not changed.": "लागू गर्ने काम रद्द भयो। {svc} पहिल्यै बदलिइसकेको थियो; बाँकी बदलिएनन्।", + "Fix the file first.": "पहिले फाइल ठिक गर्नुहोस्।", + "Open a compose file": "compose फाइल खोल्नुहोस्", + "Worker": "वर्कर", + "Saved {name}, not applied: {error}": "{name} सेभ भयो, लागू भएन: {error}", + "Show in file": "फाइलमा देखाउनुहोस्", + "needs {n}": "{n} चाहिन्छ", + "Apply cancelled. No service was changed.": "लागू गर्ने काम रद्द भयो। कुनै सर्भिस बदलिएन।", + "Arrows point at what a service needs; Compose starts those first.": "तीरले सर्भिसलाई चाहिने कुरा देखाउँछ; Compose ले ती पहिले सुरु गर्छ।", + "Starts on line {n} · click to jump there": "लाइन {n} बाट सुरु हुन्छ · त्यहाँ जान क्लिक गर्नुहोस्", + "Not in the file any more: stopped and removed. Its volumes stay.": "अब फाइलमा छैन: रोकेर हटाइयो। यसका भोल्युम रहन्छन्।", + "the file changed outside Kiri": "फाइल Kiri बाहिरबाट बदलियो", + "Overwrite their changes?": "उनीहरूको परिवर्तनमाथि लेख्ने?", + "No Compose projects yet": "अहिलेसम्म कुनै Compose प्रोजेक्ट छैन", + "Saved, not applied": "सेभ भयो, लागू भएन", + "New service, built from its folder.": "नयाँ सर्भिस, आफ्नै फोल्डरबाट बिल्ड भएको।", + "The compose file isn't on this computer: {error}": "compose फाइल यो कम्प्युटरमा छैन: {error}", + "Saved, matches what runs": "सेभ भएको छ, चलिरहेकोसँग मिल्छ", + "Line {n}.": "लाइन {n}।", + "{name} is already being applied. Wait for it to finish, or cancel it.": "{name} पहिल्यै लागू हुँदै छ। यो सकिएसम्म पर्खनुहोस्, वा रद्द गर्नुहोस्।", + "{n} recreated": "{n} फेरि बने", + "Zoom out": "जुम आउट", + "That project is gone": "त्यो प्रोजेक्ट अब छैन", + "Couldn't run docker compose: {error}": "docker compose चलाउन सकिएन: {error}", + "No logs yet.": "अहिलेसम्म कुनै लग छैन।", + "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "{name} नामको प्रोजेक्ट पहिल्यै {dir} बाट चलिरहेको छ। त्यही खोल्नुहोस्, वा यो फाइललाई आफ्नै name: लाइन दिनुहोस्।", + "{n} needs it": "{n} लाई यो चाहिन्छ", + "File": "फाइल", + "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "{name} लुकाइएको बेला Kiri ले योजना देखाउन सक्दैन। {apply} ले docker compose up चलाउँछ।", + "REMOVED": "हटाइएको", + "The file changed outside Kiri. Apply writes your edits over it, and those changes are lost.": "फाइल Kiri बाहिरबाट बदलियो। «लागू गर्नुहोस्» ले तपाईंका परिवर्तन त्यसमाथि लेख्छ, र ती परिवर्तन हराउँछन्।", + "The other Apply of {name} finished. Your edit isn't applied yet.": "{name} को अर्को लागू गर्ने काम सकियो। तपाईंको परिवर्तन अझै लागू भएको छैन।", + "The file changed outside Kiri.": "फाइल Kiri बाहिरबाट बदलियो।", + "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "{name} लुकाइएको बेला Kiri ले यो फाइल जाँच्न सक्दैन। Compose ले यसलाई मान्छ, त्यसैले «लागू गर्नुहोस्» अझै चल्छ।", + "Compose rejects this file with its real values. Kiri can't show why with secrets hidden.": "Compose ले यो फाइल यसका वास्तविक मानसहित मान्दैन। गोप्य कुरा लुकाइएको बेला Kiri ले कारण देखाउन सक्दैन।", + "docker compose took longer than {secs} seconds": "docker compose लाई {secs} सेकेन्डभन्दा बढी लाग्यो", + "Discard": "छोड्नुहोस्", + "Refresh": "रिफ्रेस गर्नुहोस्", + "Names Docker shows may contain secret values.": "Docker ले देखाउने नाममा गोप्य मान हुन सक्छन्।", + "a newer image": "नयाँ इमेज", + "docker compose up stopped": "docker compose up रोकियो", + "Applying…": "लागू हुँदै छ…", + "Cache": "क्यास", + "New service from {image}.": "{image} बाट नयाँ सर्भिस।", + "{n} new": "{n} नयाँ", + "Apply cancelled. {n} services had already changed; the rest were not changed.": "लागू गर्ने काम रद्द भयो। {n} सर्भिस पहिल्यै बदलिइसकेका थिए; बाँकी बदलिएनन्।", + "Compose rejects this file: YAML error on line {n}": "Compose ले यो फाइल मान्दैन: लाइन {n} मा YAML एरर", + "Saved, not applied: {error}": "सेभ भयो, लागू भएन: {error}", + "Kiri has no state folder": "Kiri सँग स्टेट फोल्डर छैन", + "{n} services": "{n} सर्भिस", + "Reload (lose your edits)": "रिलोड गर्नुहोस् (तपाईंका परिवर्तन हराउँछन्)", + "Not started": "सुरु भएको छैन", + "Couldn't open the compose file: {error}": "compose फाइल खोल्न सकिएन: {error}", + "Projects you start with {cmd} show up here once they have run on Kiri.": "{cmd} ले सुरु गरेका प्रोजेक्ट Kiri मा एकपटक चलेपछि यहाँ देखिन्छन्।", + "Saved": "सेभ भयो", + "a variable it uses changed": "यसले प्रयोग गर्ने एउटा भेरिएबल बदलियो", + "Not created": "बनेको छैन", + "Saves the file, then runs {cmd}. Unchanged services keep running.": "फाइल सेभ गर्छ, अनि {cmd} चलाउँछ। नबदलिएका सर्भिस चलिरहन्छन्।", + "NEW": "नयाँ", + "needs {list}": "{list} चाहिन्छ", + "Removing…": "हटाउँदै…", + "Creating…": "बन्दै छ…", + "Metrics": "मेट्रिक्स", + "Apply cancelled": "लागू गर्ने काम रद्द भयो", + "The compose file is gone from its folder.": "compose फाइल आफ्नो फोल्डरमा छैन।", + "Zoom in": "जुम इन", + "The image name from {name} isn't valid": "{name} बाट बनेको इमेजको नाम मिलेन", + "Kiri can't show this service's details with its secrets hidden": "गोप्य कुरा लुकाइएको बेला Kiri ले यो सर्भिसको विवरण देखाउन सक्दैन", + "The file changed outside Kiri": "फाइल Kiri बाहिरबाट बदलियो", + "Recreate": "फेरि बनाउनुहोस्", + "Applied {name}, but {svc} stopped": "{name} लागू भयो, तर {svc} रोकियो", + "Web": "वेब", + "See its logs": "यसको लग हेर्नुहोस्", + "Remove from the list": "सूचीबाट हटाउनुहोस्", + "Compose rejects this file. A required variable may not be set: {name}.": "Compose ले यो फाइल मान्दैन। चाहिने कुनै भेरिएबल सेट नभएको हुन सक्छ: {name}।", + "environment": "इन्भाइरनमेन्ट", + "Search": "सर्च", + "Couldn't save the compose file: {error}": "compose फाइल सेभ गर्न सकिएन: {error}", + "Compose files": "Compose फाइल", + "Scheduler": "सेड्युलर", + "Kiri has nothing to put back": "Kiri सँग फिर्ता राख्ने केही छैन", + "Put back the file as it was before Apply saved over it": "«लागू गर्नुहोस्» ले माथि सेभ गर्नुअघि फाइल जस्तो थियो त्यस्तै फिर्ता राख्नुहोस्", + "Kiri can't check this file's variables, so it manages this project by name. Apply changes from a terminal.": "Kiri ले यो फाइलका भेरिएबल जाँच्न सक्दैन, त्यसैले यो प्रोजेक्टलाई नामबाट चलाउँछ। परिवर्तन टर्मिनलबाट लागू गर्नुहोस्।", + "Edited, not applied": "एडिट भयो, लागू भएन", + "This file isn't a compose file: it has no services": "यो फाइल compose फाइल होइन: यसमा कुनै सर्भिस छैन", + "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri ले docker CLI भेटेन। फेरि सेटअप गर्न Kiri रिस्टार्ट गर्नुहोस्।", + "Fit": "अटाउनुहोस्", + "Compose rejects this file: YAML error in an included file, line {n}": "Compose ले यो फाइल मान्दैन: समावेश गरिएको फाइलमा YAML एरर, लाइन {n}", + "Open a compose file…": "compose फाइल खोल्नुहोस्…", + "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "यो फाइलको नाममा {vars} प्रयोग भएको छ। Kiri ले फोल्डरको नाम, {name}, प्रयोग गर्छ, त्यसैले कुनै नाममा गोप्य कुरा कहिल्यै पर्दैन।", + "Kiri doesn't know that action": "Kiri लाई त्यो काम थाहा छैन", + "Kiri can't find this project's compose file.": "Kiri ले यो प्रोजेक्टको compose फाइल भेटेन।", + "ports": "पोर्ट", + "Newest container created {time}": "सबैभन्दा नयाँ कन्टेनर {time} बनेको", + "Compose file": "Compose फाइल", + "Not started yet. Apply on the Compose file tab brings every service up.": "अझै सुरु भएको छैन। «Compose फाइल» ट्याबको «लागू गर्नुहोस्» ले सबै सर्भिस चलाउँछ।", + "Couldn't change {name}: {error}": "{name} बदल्न सकिएन: {error}", + "{n} unchanged": "{n} नबदलिएको", + "Create": "बनाउनुहोस्", + "Structure": "संरचना", + "YAML files": "YAML फाइल", + "{n} service": "{n} सर्भिस", + "{name} are used in a name or folder path. Docker shows those in plain text.": "{name} कुनै नाम वा फोल्डरको पाथमा प्रयोग भएका छन्। Docker ले ती सादा टेक्स्टमा देखाउँछ।", + "Its logs, Start, Stop and Remove still work.": "यसका लग, सुरु गर्नुहोस्, रोक्नुहोस् र हटाउनुहोस् अझै चल्छन्।", + "Showing the file as edited, not applied yet.": "फाइल एडिट गरिएको रूपमा देखाइएको छ, अझै लागू भएको छैन।", + "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "अहिले केही छैन: फाइल चलिरहेकोसँग मिल्छ। यसलाई बदल्नुहोस्, अनि हरेक सर्भिसलाई के हुन्छ भनेर यहाँ देखिन्छ।", + "Kiri can't read the compose file: {error}": "Kiri ले compose फाइल पढ्न सकेन: {error}", + "Pick a .yaml or .yml compose file": ".yaml वा .yml compose फाइल छान्नुहोस्", + "Applied {name}, but {svcs} stopped": "{name} लागू भयो, तर {svcs} रोकिए", + "Compose rejects this file: YAML error in {file}, line {n}": "Compose ले यो फाइल मान्दैन: {file} मा YAML एरर, लाइन {n}", + "What Apply does": "«लागू गर्नुहोस्» ले के गर्छ", + "Saved, but an included file has an error": "सेभ भयो, तर समावेश गरिएको फाइलमा एरर छ", + "{name} is used in a name or folder path. Docker shows those in plain text.": "{name} कुनै नाम वा फोल्डरको पाथमा प्रयोग भएको छ। Docker ले ती सादा टेक्स्टमा देखाउँछ।", + "Apply": "लागू गर्नुहोस्", + "Couldn't read env file {file}: it isn't a local regular file": "env फाइल {file} पढ्न सकिएन: यो यही कम्प्युटरको साधारण फाइल होइन", + "Keep editing": "एडिट गरिरहनुहोस्", + "The compose file is read-only, so Kiri can't save it. Make it writable, then Apply again.": "compose फाइल पढ्न मात्र मिल्छ, त्यसैले Kiri ले यसलाई सेभ गर्न सक्दैन। यसलाई लेख्न मिल्ने बनाउनुहोस्, अनि फेरि लागू गर्नुहोस्।", + "There's no Compose project {name} on Kiri": "Kiri मा {name} नामको कुनै Compose प्रोजेक्ट छैन", + "The compose file is back, and differs from your edits.": "compose फाइल फिर्ता आयो, र तपाईंका परिवर्तनभन्दा फरक छ।", + "{n} more": "{n} थप", + "Unchanged": "नबदलिएको", + "Saved, but line {n} has an error": "सेभ भयो, तर लाइन {n} मा एरर छ", + "Actual size": "वास्तविक साइज", + "Show in compose file": "compose फाइलमा देखाउनुहोस्", + "Open project": "प्रोजेक्ट खोल्नुहोस्", + "not started": "सुरु भएको छैन", + "Apply the compose file to create it": "यो बनाउन compose फाइल लागू गर्नुहोस्", + "Hide {name}'s containers": "{name} का कन्टेनर लुकाउनुहोस्", + "Show {name}'s containers": "{name} का कन्टेनर देखाउनुहोस्", + "Hide {name}'s pods": "{name} का पोड लुकाउनुहोस्", + "Show {name}'s pods": "{name} का पोड देखाउनुहोस्", + "{n} more in a Compose project": "{n} थप एउटा Compose प्रोजेक्ट मा", + "{n} more in Compose projects": "{n} थप Compose प्रोजेक्ट मा", + "Your only container is in a Compose project": "तपाईंको एउटै मात्र कन्टेनर Compose प्रोजेक्ट मा छ", + "All {n} containers are in Compose projects": "सबै {n} कन्टेनर Compose प्रोजेक्ट मा छन्", + "Skipped until Kiri next opens": "Kiri अर्कोपटक नखुलेसम्म छोडियो", + "Couldn't add the kiri docker context": "kiri docker कन्टेक्स्ट थप्न सकिएन", + "The kiri and docker commands": "kiri र docker कमान्ड", + "Ready in any new terminal": "जुनसुकै नयाँ टर्मिनलमा तयार", + "Couldn't add them to your shell": "यी तपाईंको शेलमा थप्न सकिएन", + "Starts at login": "लग इन गर्दा सुरु हुन्छ", + "The engine starts when you log in": "तपाईंले लग इन गर्दा इन्जिन सुरु हुन्छ", + "The engine runs from the app for now": "अहिलेलाई इन्जिन एपबाट चल्छ", + "Show log": "लग देखाउनुहोस्", + "Continue anyway": "तैपनि अगाडि बढ्नुहोस्", + "One step didn't work. Everything else is ready.": "एउटा चरण चलेन। अरू सबै तयार छ।", + "Some steps didn't work. Everything else is ready.": "केही चरण चलेनन्। अरू सबै तयार छ।", + "No matches": "केही भेटिएन", + "Disk image size": "डिस्क इमेजको साइज", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "daemon का लागि KIRI_CPUS, KIRI_MEMORY_MIB वा KIRI_DISK_GB सेट गरिएको छ, र त्यो यीभन्दा पहिले लागू हुन्छ।", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "अहिले {cpus}, {mem} सम्म मेमोरी, र {disk} डिस्क लिएर चलिरहेको छ।", + "No other WSL distros installed.": "अन्य कुनै WSL डिस्ट्रो इन्स्टल छैन।", + "WSL integration": "WSL इन्टिग्रेसन", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "बन्द गर्नुहोस्: विन्डोले लिएको मेमोरी खाली हुन्छ। फेरि खुल्न एकछिन लाग्छ, र खुला टर्मिनलहरू बन्द हुन्छन्।", + "Closing the window": "विन्डो बन्द गर्दा", + "Hide: the window stays ready and opens again at once.": "लुकाउनुहोस्: विन्डो तयार रहन्छ र तुरुन्तै फेरि खुल्छ।", + "Start Kiri at sign-in": "साइन इन गर्दा Kiri सुरु गर्ने", + "Start Kiri in the background when you sign in.": "तपाईंले साइन इन गर्दा Kiri लाई ब्याकग्राउन्डमा सुरु गर्छ।", + "Stop the engine when Kiri quits": "Kiri बन्द गर्दा इन्जिन रोक्ने", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri बन्द गर्दा चलिरहेका कन्टेनर र इन्जिन रोकिन्छन्। Kiri खोल्दा फेरि सुरु हुन्छ।", + "{env} is set, so docker uses another engine instead of {app}": "{env} सेट छ, त्यसैले docker ले {app} को सट्टा अर्को इन्जिन प्रयोग गर्छ", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} सेट छ, त्यसैले {docker} ले {app} को सट्टा अर्को इन्जिन प्रयोग गर्छ। {app} प्रयोग गर्न यसलाई आफ्नो शेलबाट अनसेट गर्नुहोस्।", + "{env} is set": "{env} सेट छ", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "यो सेसनमा {env} ले docker को कन्टेक्स्ट ओभरराइड गर्छ, त्यसैले कन्टेक्स्ट बदल्दा {docker} {app} तिर सर्दैन। {cmd} ले हटाउनुहोस् वा आफ्नो प्रोफाइलबाट निकाल्नुहोस्।", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} सिधै {app} मा पुग्छ। Testcontainers, IDE प्लगइन र SDK जस्ता टुलले यो सिधै प्रयोग गर्छन्।", + "another engine": "अर्को इन्जिन", + "{path} belongs to {engine} and stays so.": "{path} {engine} कै हो र त्यहीँ रहन्छ।", + "Tools that ignore docker contexts can use {hint}": "docker कन्टेक्स्ट नहेर्ने टुलले {hint} प्रयोग गर्न सक्छन्", + "command": "कमान्ड", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} खाली छ। docker कन्टेक्स्ट नहेर्ने टुलले त्यहाँ {app} भेटून् भनेर यसलाई {app} सँग लिंक गर्नुहोस्।", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} खाली छ। अरू कुनै Docker इन्जिन नचलेको बेला {app} चल्दा यसलाई सर्भ गर्छ।", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} खाली छ। अरू कुनै Docker इन्जिनले नलिएको बेला Kiri सुरु हुँदा {service} ले यसलाई लिंक गर्छ।", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} खाली छ। {app} ले यो इन्स्टल भएको Kiri का लागि छोडिदिन्छ।", + "Linking…": "लिंक हुँदैछ…", + "Use {app}": "{app} प्रयोग गर्नुहोस्", + "Free": "खाली", + "Docker socket": "Docker सकेट", + "The {docker} command uses {app}.": "{docker} कमान्डले {app} प्रयोग गर्छ।", + "{env} is set in this session, so {docker} uses another engine.": "यो सेसनमा {env} सेट छ, त्यसैले {docker} ले अर्को इन्जिन प्रयोग गर्छ।", + "The {docker} command uses {engine}.": "{docker} कमान्डले {engine} प्रयोग गर्छ।", + "Switching…": "बदल्दै…", + "{docker} command": "{docker} कमान्ड", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock अब Kiri तिर देखाइएको छ", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock लिंक गर्न सकिएन: {error}", + "Stopping containers…": "कन्टेनर रोकिँदै…", + "Copying data…": "डेटा कपी हुँदैछ…", + "Verifying copy…": "कपी जाँचिँदै…", + "Switching storage…": "स्टोरेज बदलिँदै…", + "Restarting engine…": "इन्जिन रिस्टार्ट हुँदैछ…", + "Moving data…": "डेटा सार्दै…", + "Storage location unavailable": "स्टोरेज ठाउँ उपलब्ध छैन", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri ले {path} मा आफ्नो डेटा भेट्टाएन। ड्राइभ जोडेर फेरि प्रयास गर्नुहोस्, अर्को फोल्डर छान्नुहोस्, वा डिफल्ट ठाउँमा रिसेट गर्नुहोस्।", + "Change…": "बदल्नुहोस्…", + "Reset to default": "डिफल्टमा रिसेट गर्नुहोस्", + "Open storage settings": "स्टोरेज सेटिङ खोल्नुहोस्", + "Start Kiri to change its storage location. ({error})": "स्टोरेज ठाउँ बदल्न Kiri सुरु गर्नुहोस्। ({error})", + "{size} used": "{size} प्रयोगमा", + "{size} free": "{size} खाली", + "Default": "डिफल्ट", + "Moving Kiri's data to {path}.": "Kiri को डेटा {path} मा सारिँदैछ।", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri ले डेटा कपी गर्दा चलिरहेका कन्टेनर एकछिन रोकिन्छन् र काम सकिएपछि फेरि सुरु हुन्छन्।", + "Couldn't change storage location": "स्टोरेज ठाउँ बदल्न सकिएन", + "Old data": "पुरानो डेटा", + "Previous data is still in {path}. Remove it once everything works in the new location.": "पुरानो डेटा अझै {path} मै छ। नयाँ ठाउँमा सबै ठीकसँग चलेपछि यसलाई हटाउनुहोस्।", + "Remove old data": "पुरानो डेटा हटाउनुहोस्", + "Storage location": "स्टोरेज ठाउँ", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} ले Kiri को स्टोरेज ठाउँ तोक्छ, त्यसैले यहाँबाट बदल्न मिल्दैन।", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "इमेज, कन्टेनर र भोल्युम यही फोल्डरमा बस्छन्। बाहिरी ड्राइभमा नेटिभ फाइलसिस्टम हुनुपर्छ (macOS मा APFS, Linux मा ext4/xfs/btrfs, Windows मा NTFS); FAT र exFAT ड्राइभ चल्दैनन्।", + "Reset storage location to default?": "स्टोरेज ठाउँलाई डिफल्टमा रिसेट गर्ने?", + "Change storage location?": "स्टोरेज ठाउँ बदल्ने?", + "Destination: {path} ({free} free).": "गन्तव्य: {path} ({free} खाली)।", + "Destination: {path}.": "गन्तव्य: {path}।", + "Existing Kiri data in this folder will be replaced.": "यो फोल्डरमा पहिलेदेखि रहेको Kiri डेटा बदलिनेछ।", + "Migration mode": "सार्ने तरिका", + "Move existing images, containers, and volumes": "भएका इमेज, कन्टेनर र भोल्युम सार्नुहोस्", + "Stops running containers, copies your data, and starts them again.": "चलिरहेका कन्टेनर रोक्छ, तपाईंको डेटा कपी गर्छ, र फेरि सुरु गर्छ।", + "Start fresh": "नयाँबाट सुरु गर्नुहोस्", + "Starts empty in the new folder. Your old folder stays until you remove it.": "नयाँ फोल्डरमा खालीबाट सुरु हुन्छ। पुरानो फोल्डर तपाईंले नहटाएसम्म रहिरहन्छ।", + "Kiri will switch to this folder and restart the engine.": "Kiri यो फोल्डरमा स्विच हुन्छ र इन्जिन रिस्टार्ट गर्छ।", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri ले डेटा सार्दा चलिरहेका कन्टेनर रोकिन्छन् र काम सकिएपछि फेरि सुरु हुन्छन्।", + "Move data": "डेटा सार्नुहोस्", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri आफ्नो डिफल्ट फोल्डरमा फर्कन्छ र इन्जिन रिस्टार्ट गर्छ। छुटाइएको ड्राइभको डेटा डिलिट हुँदैन।", + "Remove old data?": "पुरानो डेटा हटाउने?", + "Everything in {path} will be deleted for good.": "{path} भित्रको सबै कुरा सधैंका लागि डिलिट हुनेछ।", + "Choose a storage folder": "स्टोरेज फोल्डर छान्नुहोस्", + "Kiri's data is moving already": "Kiri को डेटा पहिल्यै सारिँदैछ", + "Kiri's data moved to {path}": "Kiri को डेटा {path} मा सारियो", + "Storage is available again": "स्टोरेज फेरि उपलब्ध छ", + "Old data removed": "पुरानो डेटा हटाइयो", + "A proxy on this computer is reached as {host}.": "यो कम्प्युटरको प्रोक्सी {host} बाट पुगिन्छ।", + "VPNs need no setting: container traffic leaves through Linux.": "VPN का लागि कुनै सेटिङ चाहिँदैन: कन्टेनरको ट्राफिक Linux हुँदै बाहिर जान्छ।", + "Shared with Linux: containers only use them while busy.": "Linux सँग बाँडिएको: कन्टेनर व्यस्त हुँदा मात्र यी प्रयोग गर्छन्।", + "The most containers and the engine may take. Unused memory stays free on Linux.": "कन्टेनर र इन्जिनले लिन सक्ने अधिकतम मेमोरी। प्रयोग नभएको मेमोरी Linux मा खाली नै रहन्छ।", + "The engine is off; it starts with these next time.": "इन्जिन बन्द छ; अर्को पटक यी सेटिङसँग सुरु हुन्छ।", + "Restart engine to apply": "लागू गर्न इन्जिन रिस्टार्ट गर्नुहोस्", + "Windows bind-mount file events": "Windows बाइन्ड-माउन्ट फाइल इभेन्ट", + "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "लाइभ रिलोडका लागि Windows ड्राइभ (जस्तै {path}) का फाइल बदलिएको सूचना कन्टेनरमा पठाउँछ। खाली बस्दा CPU प्रयोग हुँदैन।", + "One text file, redacted, saved to your Desktop. Read it before you share it.": "गोप्य कुरा हटाइएको एउटा टेक्स्ट फाइल तपाईंको Desktop मा सेभ हुन्छ। सेयर गर्नुअघि पढेर हेर्नुहोस्।", + "The 5 newest crash reports for Kiri": "Kiri का सबैभन्दा नयाँ 5 क्र्यास रिपोर्ट", + "Kiri and this PC": "Kiri र यो PC", + "Kiri and this computer": "Kiri र यो कम्प्युटर", + "Versions, {os}, whether the engine runs, how many containers and images": "भर्सन, {os}, इन्जिन चलेको छ कि छैन, कति कन्टेनर र इमेज छन्", + "Saved. The engine uses these from its next start": "सेभ भयो। इन्जिनले अर्को पटक सुरु हुँदा यी प्रयोग गर्छ", + "5 min": "5 मिनेट", + "10 min": "10 मिनेट", + "30 min": "30 मिनेट", + "Never": "कहिल्यै नाइँ", + "Build cache limit": "बिल्ड क्यास सीमा", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit को क्यास यो साइजभन्दा माथि गएपछि सबैभन्दा पुराना क्यास लेयरहरू आफैं हटाइन्छन्।", + "Stop builder when idle": "खाली बस्दा बिल्डर रोक्ने", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "खाली बस्दा मेमोरी नलिओस् भनेर बिल्डहरूको बीचमा BuildKit रोक्छ; अर्को बिल्डले एक सेकेन्डभन्दा कममै ब्युँझाउँछ।", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "daemon का लागि KIRI_BUILD_CACHE_GB वा KIRI_BUILDER_IDLE_SECS सेट गरिएको छ, र त्यो यीभन्दा पहिले लागू हुन्छ।", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: सबैभन्दा छिटो। Cloudflare WARP वा अफिसको फायरवालले कन्टेनरको HTTPS रोकेमा होस्ट रिलेमा बदल्नुहोस्। VM रिस्टार्ट गर्दा लागू हुन्छ।", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "होस्ट रिले: कनेक्सनहरू Virtualization.framework NAT को सट्टा macOS मा रहेको Kiri हुँदै बाहिर जान्छन्। VM रिस्टार्ट गर्दा लागू हुन्छ।", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "इन्भाइरोन्मेन्टमा KIRI_SHARED_NAT सेट छ र त्यो पहिले लागू हुन्छ।", + "Outbound VM traffic": "बाहिर जाने VM ट्राफिक", + "macOS NAT": "macOS NAT", + "Host relay": "होस्ट रिले", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM डिस्क बढ्न सक्ने अधिकतम साइज। डेटा लेखिँदै जाँदा मात्र {os} मा ठाउँ प्रयोग हुन्छ, र खाली ठाउँ {storage} बाट फिर्ता लिन सकिन्छ। रिस्टार्ट गर्दा लागू हुन्छ।", + "Settings → Storage": "सेटिङ → स्टोरेज", + "VM disk space": "VM डिस्क स्पेस", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "नेटिभ Linux ले सिधै होस्टको फाइलसिस्टम प्रयोग गर्छ — डिलिट गरिएका इमेज र भोल्युमले तुरुन्तै ठाउँ खाली गर्छन्।", + "Compact disk…": "डिस्क कम्प्याक्ट…", + "Reclaim space": "ठाउँ फिर्ता लिने", + "Compacting…": "कम्प्याक्ट हुँदैछ…", + "Reclaiming…": "फिर्ता लिँदै…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} कम्प्याक्ट गरी इन्जिन रिस्टार्ट हुँदैछ…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} मा {host}, VM भित्र {inUse} प्रयोगमा · प्रयोग नभएका ब्लक खाली गर्दै…", + "Trimming unused blocks inside the VM disk…": "VM डिस्कभित्र प्रयोग नभएका ब्लक खाली गर्दै…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows मा {host} ({vhdx}), {inUse} प्रयोगमा · {freed}।", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} मा {host}, VM भित्र {inUse} प्रयोगमा · {freed}।", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows मा {host} ({vhdx}), {inUse} प्रयोगमा · फिर्ता लिने ठाउँ छैन।", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} मा {host}, VM भित्र {inUse} प्रयोगमा · फिर्ता लिने ठाउँ छैन।", + "Nothing to reclaim.": "फिर्ता लिने ठाउँ छैन।", + "{size} can be given back": "{size} फिर्ता दिन सकिन्छ", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows मा {host} ({vhdx}), {inUse} प्रयोगमा · {can}। कम्प्याक्ट गर्दा इन्जिन रिस्टार्ट हुन्छ।", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} मा {host}, VM भित्र {inUse} प्रयोगमा · कन्टेनर नरोकी {can}।", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows मा {host} ({vhdx})। कम्प्याक्ट गर्दा खाली ठाउँ फिर्ता हुन्छ र इन्जिन रिस्टार्ट हुन्छ।", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} मा {host}। ठाउँ फिर्ता लिँदा कन्टेनर नरोकी VM डिस्कका खाली ब्लक सफा हुन्छन्।", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} भित्रको खाली ठाउँ Windows लाई फिर्ता दिन्छ। कम्प्याक्ट गर्दा इन्जिन रिस्टार्ट हुन्छ।", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "कन्टेनर नरोकी VM डिस्कका खाली ब्लक {os} लाई फिर्ता दिन्छ।", + "Cleaning up stopped containers, untagged images, and build cache…": "रोकिएका कन्टेनर, ट्याग नभएका इमेज र बिल्ड क्यास सफा गर्दै…", + "{count} ({size})": "{count} ({size})", + "build cache": "बिल्ड क्यास", + "No stopped containers, untagged images or build cache · {freed}.": "रोकिएका कन्टेनर, ट्याग नभएका इमेज वा बिल्ड क्यास छैनन् · {freed}।", + "No stopped containers, untagged images or build cache.": "रोकिएका कन्टेनर, ट्याग नभएका इमेज वा बिल्ड क्यास छैनन्।", + "Cleaning up…": "सफा गर्दै…", + "Clean up…": "सफा गर्नुहोस्…", + "Unused Docker data": "प्रयोग नभएको Docker डेटा", + "Command-line tools in shell": "शेलमा कमान्ड-लाइन टुलहरू", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "नयाँ टर्मिनलमा {docker}, {kubectl} र {kiri} चलून् भनेर {zshrc} र {zprofile} मा {bin} थप्नुहोस्।", + "Uninstall Kiri": "Kiri अनइन्स्टल गर्नुहोस्", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "इन्जिन रोक्छ, Kiri को ब्याकग्राउन्ड सर्भिस, CLI लिंक र शेल प्रोफाइल इन्ट्री हटाउँछ, र अघिल्लो Docker कन्टेक्स्ट ({cmd}) फर्काउँछ।", + "Uninstall Kiri…": "Kiri अनइन्स्टल…", + "Couldn't reclaim disk space: {error}": "डिस्क स्पेस फिर्ता लिन सकिएन: {error}", + "Reclaimed {size} on {os}": "{os} मा {size} फिर्ता लिइयो", + "Nothing to reclaim": "फिर्ता लिने ठाउँ छैन", + "Couldn't clean up unused Docker data: {error}": "प्रयोग नभएको Docker डेटा सफा गर्न सकिएन: {error}", + "Cleaned up {size} of unused Docker data": "{size} प्रयोग नभएको Docker डेटा सफा गरियो", + "Cleaned up unused Docker data": "प्रयोग नभएको Docker डेटा सफा गरियो", + "Compact WSL disk?": "WSL डिस्क कम्प्याक्ट गर्ने?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} कम्प्याक्ट गर्दा खाली ठाउँ Windows लाई फिर्ता हुन्छ र Kiri को इन्जिन तथा चलिरहेका कन्टेनर एकछिन रिस्टार्ट हुन्छन्।", + "Compact disk": "डिस्क कम्प्याक्ट", + "Clean up unused Docker data?": "प्रयोग नभएको Docker डेटा सफा गर्ने?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "रोकिएका कन्टेनर, ट्याग नभएका इमेज र BuildKit को बिल्ड क्यास हटाउँछ। चलिरहेका कन्टेनर र ट्याग भएका इमेज राखिन्छन्।", + "Clean up": "सफा गर्नुहोस्", + "Uninstall Kiri?": "Kiri अनइन्स्टल गर्ने?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "इन्जिन रोक्छ, Kiri को ब्याकग्राउन्ड सर्भिस, CLI लिंक र शेल प्रोफाइल इन्ट्री हटाउँछ, र अघिल्लो Docker कन्टेक्स्ट फर्काउँछ। तपाईंका इमेज र भोल्युम Kiri को डेटा फोल्डर डिलिट नगरेसम्म त्यहीँ रहन्छन्।", + "Cluster": "क्लस्टर", + "default": "डिफल्ट", + "k3s version": "k3s भर्सन", + "Image version for the cluster node ({cmd}). Applies when recreated.": "क्लस्टर नोडको इमेज भर्सन ({cmd})। फेरि बनाउँदा लागू हुन्छ।", + "Extra server flags": "थप सर्भर फ्ल्यागहरू", + "Passed to {srv} ({flag}), separated by spaces.": "स्पेसले छुट्याएर {srv} ({flag}) मा पठाइन्छ।", + "Startup manifests": "स्टार्टअप म्यानिफेस्ट", + "YAML files in {path} are applied whenever the cluster starts.": "क्लस्टर सुरु हुँदा प्रत्येक पटक {path} भित्रका YAML फाइल लागू हुन्छन्।", + "Open folder": "फोल्डर खोल्नुहोस्", + "{n} untagged image": "ट्याग नभएको {n} इमेज", + "{n} untagged images": "ट्याग नभएका {n} इमेज", + "Uninstall Kiri from Windows Settings → Apps": "Windows सेटिङ → Apps बाट Kiri अनइन्स्टल गर्नुहोस्", + "Builder settings saved": "बिल्डर सेटिङ सेभ भयो", + "Could not save builder settings: {error}": "बिल्डर सेटिङ सेभ गर्न सकिएन: {error}", + "Disk reclaim is already running": "डिस्क स्पेस फिर्ता लिने काम पहिल्यै चल्दैछ", + "Outbound VM traffic setting saved. Restart the VM to apply.": "बाहिर जाने VM ट्राफिक सेटिङ सेभ भयो। लागू गर्न VM रिस्टार्ट गर्नुहोस्।", + "Could not save VM networking setting: {error}": "VM नेटवर्क सेटिङ सेभ गर्न सकिएन: {error}", + "Added Kiri command-line tools to shell profiles": "शेल प्रोफाइलमा Kiri कमान्ड-लाइन टुलहरू थपिए", + "Removed Kiri command-line tools from shell profiles": "शेल प्रोफाइलबाट Kiri कमान्ड-लाइन टुलहरू हटाइए", + "Could not update shell profiles: {error}": "शेल प्रोफाइल अपडेट गर्न सकिएन: {error}", + "Uninstalling Kiri…": "Kiri अनइन्स्टल हुँदैछ…", + "Could not uninstall Kiri: {error}": "Kiri अनइन्स्टल गर्न सकिएन: {error}", + "Uninstall Kiri using your system package manager": "आफ्नो सिस्टमको प्याकेज म्यानेजरबाट Kiri अनइन्स्टल गर्नुहोस्", + "Swap": "स्व्याप", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "मेमोरी सकिएपछि VM ले प्रयोग गर्न सक्ने डिस्क स्पेस, जसले गर्दा कन्टेनर रोकिनुको सट्टा सुस्त हुन्छन्। रिस्टार्ट गर्दा लागू हुन्छ।" +} diff --git a/crates/kiri/src/ui/lang/uz.json b/crates/kiri/src/ui/lang/uz.json new file mode 100644 index 000000000..9bf2c95fa --- /dev/null +++ b/crates/kiri/src/ui/lang/uz.json @@ -0,0 +1,2039 @@ +{ + " (current step)": " (joriy qadam)", + " (done)": " (tayyor)", + " ({port} was in use)": " ({port} band edi)", + " That's {count} crashes since Kiri last opened.": " Kiri oxirgi marta ochilganidan beri {count} marta ishdan chiqdi.", + " and ": " va ", + " or ": " yoki ", + "(no description)": "(tavsif yoʻq)", + "(no message)": "(xabar yoʻq)", + "(read-only)": "(faqat oʻqish uchun)", + "(was {value})": "(avval {value} edi)", + "* Estimates until measured on a clean PC.": "* Toza kompyuterda oʻlchanmaguncha taxminiy qiymatlar.", + "+ A complete Linux you can open from Start": "+ Start menyusidan ochish mumkin boʻlgan toʻliq Linux", + "+ Already have Ubuntu? Kiri uses it: nothing to download": "+ Ubuntu allaqachon bormi? Kiri undan foydalanadi: hech narsa yuklab olish shart emas", + "+ No Microsoft Store, no username or password": "+ Microsoft Store, foydalanuvchi nomi va parol kerak emas", + "+ Removed completely when you remove Kiri": "+ Kirini oʻchirganingizda butunlay oʻchiriladi", + "+ Uses the Ubuntu you already have: nothing to download": "+ Oʻrnatilgan Ubuntudan foydalanadi: hech narsa yuklab olish shart emas", + "+{n} more": "yana +{n}", + ", ": ", ", + "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Kiri bilan yigʻish. docker build va docker compose build Kirida ishlaydi, obrazlar ham Kirida boʻladi. {engine} ularni koʻrmaydi. Buni istalgan vaqtda Sozlamalar → Yigʻishlar boʻlimida oʻzgartirishingiz mumkin.", + "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Docker bilan yigʻishda davom etish. Hech narsa oʻzgarmaydi: docker build hozir qayerda yigʻayotgan boʻlsa, oʻsha yerda yigʻadi, obrazlar esa {engine}da qoladi.", + "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "Saqlanadi: konteynerning oʻzi, uning fayllari, obrazi, portlari, tomlari, tarmogʻi va qayta ishga tushirish siyosati.", + "docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.": "docker hali ham {engine}dan foydalanadi, shuning uchun terminalda ishga tushirganlaringiz bu yerda koʻrinmaydi. Obrazlaringizni koʻchirib olish mumkin.", + "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node — kind vositasining tugun obrazi; kind Kubernetesni Docker ichida ishga tushiradi. kind uni siz uchun imtiyozli rejimda va kerakli sozlamalar bilan ishga tushiradi. Alohida ishga tushirilsa, u shu yerda toʻxtab qoladi: {mount}.", + "{name} has {list} that aren't in Kiri yet.": "{name}da {list} bor, ular hali Kirida yoʻq.", + "{name} isn't answering on {addr}, so visitors get an error page. Is the app inside it running?": "{name} {addr} manzilida javob bermayapti, shuning uchun tashrif buyuruvchilar xato sahifasini koʻradi. Uning ichidagi ilova ishlayaptimi?", + "{name} isn't answering, so visitors get an error page. Is the app inside it running?": "{name} javob bermayapti, shuning uchun tashrif buyuruvchilar xato sahifasini koʻradi. Uning ichidagi ilova ishlayaptimi?", + "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "Ushbu portlardan birini tashqariga ochadigan konteyner uni egallaydi; u portni boʻshatmaguncha shu portdagi nomlar pauzada boʻladi.", + "A couple more steps: set them up, or skip.": "Yana bir-ikki qadam qoldi: ularni sozlang yoki oʻtkazib yuboring.", + "A deployment (its ReplicaSet)": "Deployment (uning ReplicaSet obyekti)", + "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiriga ulangan qurilma siz uni uzmaguningizcha Windowsda koʻrinmaydi. Konteynerda: --device /dev/ttyUSB0 (serial), /dev/input (HID) yoki /dev/bus/usb (raw).", + "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiriga ulangan qurilma siz uni uzmaguningizcha Macda koʻrinmaydi. Konteynerda: --device /dev/ttyUSB0 (serial), /dev/input (HID) yoki /dev/bus/usb (raw).", + "A few things need fixing before Kiri can run containers.": "Kiri konteynerlarni ishga tushira olishi uchun bir nechta narsani tuzatish kerak.", + "A kiri command": "kiri buyrugʻi", + "A kiri command crashed": "kiri buyrugʻi ishdan chiqdi", + "A proxy on this Mac is reached as {host}.": "Bu Macdagi proksiga {host} orqali murojaat qilinadi.", + "A service sends traffic to this pod": "Servis ushbu podga trafik yuboradi", + "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "kubectl {context} konteksti uchun bitta konteynerdagi bir tugunli klaster (k3s). Oʻchirilganda u toʻxtaydi, holati esa saqlanib qoladi.", + "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "Bitta konteynerdagi bir tugunli klaster (k3s). Ishga tushishi taxminan 20 s oladi, birinchi marta esa k3s yuklab olinayotgani uchun uzoqroq.", + "A small, fast container runtime.": "Kichik va tezkor konteyner ishga tushirish muhiti.", + "A tiny Linux made only for Kiri, built from Alpine. It stays out of sight and leaves with Kiri.": "Faqat Kiri uchun Alpine asosida yaratilgan kichkina Linux. U koʻzga tashlanmaydi va Kiri bilan birga oʻchiriladi.", + "API on {addr}": "API {addr} manzilida", + "API server": "API serveri", + "API server port": "API server porti", + "AWS didn't accept that code. Wait for the next one and try again.": "AWS bu kodni qabul qilmadi. Keyingisini kuting va qayta urinib koʻring.", + "AWS profile": "AWS profili", + "About": "Dastur haqida", + "Accent": "Urgʻu rangi", + "Accept the SQL Server licence": "SQL Server litsenziyasini qabul qilish", + "Access token": "Kirish tokeni", + "Access token or password": "Kirish tokeni yoki parol", + "Action {op}": "{op} amali", + "Actions": "Amallar", + "Actual Size": "Haqiqiy oʻlcham", + "Add": "Qoʻshish", + "Add it to WSL": "Uni WSLga qoʻshish", + "Add port": "Port qoʻshish", + "Added by this build": "Shu yigʻish tomonidan qoʻshilgan", + "Added in this image": "Shu obrazda qoʻshilgan", + "Additional certificate names": "Qoʻshimcha sertifikat nomlari", + "Administrator approval": "Administrator ruxsati", + "After the restart": "Qayta ishga tushirilgandan keyin", + "Age": "Yoshi", + "All": "Hammasi", + "All languages · {n}": "Barcha tillar · {n}", + "All levels": "Barcha darajalar", + "All statuses": "Barcha holatlar", + "All steps": "Barcha qadamlar", + "All {kind}": "Barcha {kind}", + "Allow access": "Ruxsat berish", + "Allow an empty password": "Boʻsh parolga ruxsat berish", + "Already there": "Allaqachon mavjud", + "Always send crash reports": "Nosozlik hisobotlarini doim yuborish", + "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR parol emas, token qabul qiladi: foydalanuvchi nomi {user}, token esa {cmd} orqali olinadi. U 12 soat amal qiladi.", + "Anchore, open source": "Anchore, ochiq kodli", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "Shundan beri {build} uchun boshqa yigʻuvchi tanlangan ({use}). Kirida yigʻish uchun Kirini qayta tanlang.", + "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "127.0.0.1:53 manzilini boshqa dastur band qilgan, shuning uchun Kiri .kiri.local uchun javob bera olmaydi; konteynerlar .kiri.localhost manzilida qoladi", + "Answers on /run/kiri/docker.sock": "/run/kiri/docker.sock orqali javob beradi", + "Anyone who can reach the port signs in as root.": "Portga ulana oladigan har kim root sifatida kiradi.", + "Anyone with this link can open it while Kiri is running.": "Bu havolaga ega har kim Kiri ishlab turganida uni ochishi mumkin.", + "Appearance": "Koʻrinish", + "Applies after you log out and back in": "Tizimdan chiqib, qayta kirganingizdan keyin kuchga kiradi", + "Apply…": "Qoʻllash…", + "Asking {host} for {ref}…": "{host}dan {ref} soʻralmoqda…", + "Asks for your password once": "Parolingiz bir marta soʻraladi", + "Asleep": "Uyqu rejimida", + "Attach": "Ulash", + "Attach it to see where it shows up in Linux.": "Linuxda qayerda paydo boʻlishini koʻrish uchun uni ulang.", + "Attached": "Ulangan", + "Attaching…": "Ulanmoqda…", + "Audio": "Audio", + "Back": "Orqaga", + "Back (Esc)": "Orqaga (Esc)", + "Back to Share": "Ulashishga qaytish", + "Back to editing": "Tahrirlashga qaytish", + "Base image": "Asosiy obraz", + "Beta": "Beta", + "Bigger": "Kattaroq", + "Blue": "Koʻk", + "Bring all my {engine} images to {app}": "Barcha {engine} obrazlarimni {app}ga koʻchirish", + "Bring images, volumes and containers over to Kiri.": "Obrazlar, tomlar va konteynerlarni Kiriga koʻchiring.", + "Bring your {name} things to Kiri": "{name}dagi narsalaringizni Kiriga koʻchiring", + "Bringing your images over from {engine}: {done} of {total}.": "Obrazlaringiz {engine}dan koʻchirilmoqda: {total} tadan {done} tasi.", + "Brought {n} item over from {engine}.": "{engine}dan {n} ta element koʻchirildi.", + "Brought {n} item over from {engine}; {failed} failed (Settings → Import says why).": "{engine}dan {n} ta element koʻchirildi; {failed} tasi muvaffaqiyatsiz (sababi Sozlamalar → Import boʻlimida).", + "Brought {n} items over from {engine}.": "{engine}dan {n} ta element koʻchirildi.", + "Brought {n} items over from {engine}; {failed} failed (Settings → Import says why).": "{engine}dan {n} ta element koʻchirildi; {failed} tasi muvaffaqiyatsiz (sababi Sozlamalar → Import boʻlimida).", + "Browsers see a short Kiri Cloud notice page first.": "Brauzerlar avval Kiri Cloudning qisqa ogohlantirish sahifasini koʻradi.", + "Build cache cleared": "Yigʻish keshi tozalandi", + "Build cache cleared: freed {size}": "Yigʻish keshi tozalandi: {size} boʻshatildi", + "Build context": "Yigʻish konteksti", + "Build record": "Yigʻish yozuvi", + "Build with": "Yigʻuvchi", + "Build with Kiri": "Kiri bilan yigʻish", + "Build with Kiri.": "Kiri bilan yigʻish.", + "BuildKit starts if it's asleep.": "BuildKit uyqu holatida boʻlsa, ishga tushadi.", + "BuildKit {size}": "BuildKit {size}", + "BuildKit {size} and its build cache": "BuildKit {size} va uning yigʻish keshi", + "Building": "Yigʻilmoqda", + "Builds": "Yigʻishlar", + "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build orqali bajargan yigʻishlaringiz shu yerda har bir qadamning vaqti, keshi va chiqishi bilan koʻrsatiladi.", + "Built from source": "Manba koddan yigʻilgan", + "Bus {bus} · Device {dev}": "Shina {bus} · Qurilma {dev}", + "By name, no ports.": "Nom orqali, portlarsiz.", + "By port. Nothing to set up.": "Port orqali. Hech narsa sozlash shart emas.", + "Bypass for": "Proksisiz ulanish", + "CLI": "CLI", + "CPU": "CPU", + "CPU is a share of all {n} cores: 100% would be every core busy.": "CPU barcha {n} yadroning ulushi sifatida koʻrsatiladi: 100% — barcha yadrolar band degani.", + "CPUs": "Protsessorlar", + "Cached": "Keshlangan", + "Camera": "Kamera", + "Can't be shared": "Ulashib boʻlmaydi", + "Can't be shared yet": "Hozircha ulashib boʻlmaydi", + "Can't reach Docker Hub right now.": "Hozir Docker Hubga ulanib boʻlmayapti.", + "Cancel": "Bekor qilish", + "Cancel download": "Yuklab olishni bekor qilish", + "Cancel pull": "Yuklab olishni bekor qilish", + "Canceled": "Bekor qilindi", + "Cancelled": "Bekor qilindi", + "Cancelled. Nothing was added; layers that finished are kept for the next pull.": "Bekor qilindi. Hech narsa qoʻshilmadi; tugallangan qatlamlar keyingi yuklab olish uchun saqlab qolindi.", + "Change ports": "Portlarni oʻzgartirish", + "Changing it restarts the cluster.": "Buni oʻzgartirish klasterni qayta ishga tushiradi.", + "Changing this asks Windows for an administrator's approval, since it adds or removes a DNS rule for {local}.": "Buni oʻzgartirish uchun Windows administrator ruxsatini soʻraydi, chunki {local} uchun DNS qoidasi qoʻshiladi yoki olib tashlanadi.", + "Changing this needs admin rights (an administrator password), since it adds or removes {path}.": "Buni oʻzgartirish uchun administrator huquqlari (administrator paroli) kerak, chunki {path} qoʻshiladi yoki olib tashlanadi.", + "Check for Updates…": "Yangilanishlarni tekshirish…", + "Check for updates automatically": "Yangilanishlarni avtomatik tekshirish", + "Check now": "Hozir tekshirish", + "Check the spelling, or paste a full reference like {ref}.": "Imloni tekshiring yoki {ref} kabi toʻliq havolani qoʻying.", + "Checked once the engine runs": "Dvijok ishga tushgach tekshiriladi", + "Checked once your account can use Kiri": "Hisobingiz Kiridan foydalana olgach tekshiriladi", + "Checking the code with AWS…": "Kod AWS orqali tekshirilmoqda…", + "Checking your plan…": "Tarifingiz tekshirilmoqda…", + "Checking…": "Tekshirilmoqda…", + "Choose a Linux": "Linux tanlang", + "Choose and install": "Tanlash va oʻrnatish", + "Choose what to bring…": "Nimani olib oʻtishni tanlang…", + "Choose your language": "Tilni tanlang", + "Clear": "Tozalash", + "Clear build cache": "Yigʻish keshini tozalash", + "Clear the selection": "Tanlovni bekor qilish", + "Clear the selection (Esc)": "Tanlovni bekor qilish (Esc)", + "Clear {n} failed": "{n} ta muvaffaqiyatsizni tozalash", + "Clearing…": "Tozalanmoqda…", + "Close": "Yopish", + "Close ({keys})": "Yopish ({keys})", + "Close Window": "Oynani yopish", + "Close find": "Qidiruvni yopish", + "Close pane": "Panelni yopish", + "Close tab": "Varaqni yopish", + "Close this scan": "Bu skanerlashni yopish", + "Close to your plan's speed limit": "Tarifingiz tezlik chegarasiga yaqin", + "Cluster IP": "Klaster IP", + "Collapse all": "Hammasini yigʻish", + "Command": "Buyruq", + "Command to run in the container": "Konteynerda bajariladigan buyruq", + "Completed": "Yakunlandi", + "Compose project {project} made it: {cmd} puts back what the compose file says, so change it there too.": "Uni {project} Compose loyihasi yaratgan: {cmd} compose faylidagi holatni qaytaradi, shuning uchun uni u yerda ham oʻzgartiring.", + "Compose services answer at {addr}.": "Compose xizmatlari {addr} manzilida javob beradi.", + "Connect Windows to it": "Windowsni unga ulash", + "Connecting…": "Ulanilmoqda…", + "Connection lost.": "Aloqa uzildi.", + "Container": "Konteyner", + "Container files are not on Windows' disk: use Save to Downloads": "Konteyner fayllari Windows diskida emas: “Yuklanmalarga saqlash”dan foydalaning", + "Container list": "Konteynerlar roʻyxati", + "Container port {q}{port}{q} is not a port number (1–65535).": "Konteyner porti {q}{port}{q} port raqami emas (1–65535).", + "Container traffic leaves through WSL's network.": "Konteyner trafigi WSL tarmogʻi orqali chiqadi.", + "Container, Kubernetes and diagnostics logs.": "Konteyner, Kubernetes va diagnostika jurnallari.", + "Containers": "Konteynerlar", + "Containers answer at .kiri.localhost": "Konteynerlar .kiri.localhost manzilida javob beradi", + "Containers now answer at .kiri.local": "Konteynerlar endi .kiri.local manzilida javob beradi", + "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "Konteynerlar shu kompyuterning oʻz yadrosida ishlaydi, shuning uchun uning USB qurilmalarini oʻz holicha koʻradi: koʻrsatilgan yoʻl bilan docker run --device dan foydalaning.", + "Containers see it": "Konteynerlar uni koʻradi", + "Containers you start with docker run or Compose show up here, with the {context} context.": "{context} kontekstida docker run yoki Compose bilan ishga tushirgan konteynerlaringiz shu yerda koʻrsatiladi.", + "Continue": "Davom etish", + "Continue with GitHub": "GitHub orqali davom etish", + "Controlled by": "Boshqaruvchi", + "Copied": "Nusxa olindi", + "Copied {text}": "{text} nusxalandi", + "Copy": "Nusxa olish", + "Copy ID": "IDdan nusxa olish", + "Copy link": "Havoladan nusxa olish", + "Copy {what}": "{what}dan nusxa olish", + "Could not change container names: {error}": "Konteyner nomlarini oʻzgartirib boʻlmadi: {error}", + "Could not change the certificate's trust: {error}": "Sertifikatga ishonchni oʻzgartirib boʻlmadi: {error}", + "Could not change the ports: {error}": "Portlarni oʻzgartirib boʻlmadi: {error}", + "Could not open Terminal: {error}": "Terminalni ochib boʻlmadi: {error}", + "Could not open a terminal: {error}": "Terminalni ochib boʻlmadi: {error}", + "Could not restart WSL: {error}": "WSLni qayta ishga tushirib boʻlmadi: {error}", + "Could not restart the VM: {error}": "VMni qayta ishga tushirib boʻlmadi: {error}", + "Could not restart the engine: {error}": "Dvijokni qayta ishga tushirib boʻlmadi: {error}", + "Could not save .wslconfig: {error}": ".wslconfig faylini saqlab boʻlmadi: {error}", + "Could not save the SBOM: {error}": "SBOMni saqlab boʻlmadi: {error}", + "Could not save the file: {error}": "Faylni saqlab boʻlmadi: {error}", + "Could not save the proxy settings: {error}": "Proksi sozlamalarini saqlab boʻlmadi: {error}", + "Could not save the registry settings: {error}": "Reyestr sozlamalarini saqlab boʻlmadi: {error}", + "Could not save the setting to {path}": "Sozlamani {path} fayliga saqlab boʻlmadi", + "Could not save the setting to ~/.kiri/ui.json": "Sozlamani ~/.kiri/ui.json fayliga saqlab boʻlmadi", + "Could not save: {error}": "Saqlab boʻlmadi: {error}", + "Couldn't change which builder docker build uses: {error}": "docker build foydalanadigan yigʻuvchini oʻzgartirib boʻlmadi: {error}", + "Couldn't check for updates: {error}": "Yangilanishlarni tekshirib boʻlmadi: {error}", + "Couldn't check: {error}": "Tekshirib boʻlmadi: {error}", + "Couldn't clear the build cache: {error}": "Yigʻish keshini tozalab boʻlmadi: {error}", + "Couldn't copy to the clipboard": "Almashuv buferiga nusxalab boʻlmadi", + "Couldn't download it: {error}": "Yuklab olib boʻlmadi: {error}", + "Couldn't list the tags": "Teglar roʻyxatini olib boʻlmadi", + "Couldn't read the USB devices": "USB qurilmalarini oʻqib boʻlmadi", + "Couldn't read the build history": "Yigʻishlar tarixini oʻqib boʻlmadi", + "Couldn't remove the build: {error}": "Yigʻishni oʻchirib boʻlmadi: {error}", + "Couldn't save it: {error}": "Saqlab boʻlmadi: {error}", + "Couldn't save the report: {error}": "Hisobotni saqlab boʻlmadi: {error}", + "Couldn't send it: {error}": "Yuborib boʻlmadi: {error}", + "Couldn't send the crash report: {error}": "Nosozlik hisobotini yuborib boʻlmadi: {error}", + "Couldn't set up the Docker tools": "Docker vositalarini sozlab boʻlmadi", + "Couldn't share": "Ulashib boʻlmadi", + "Couldn't share service {name}: it's gone": "{name} xizmatini ulashib boʻlmadi: u mavjud emas", + "Couldn't share {name}": "{name}ni ulashib boʻlmadi", + "Couldn't share {name}: Kiri couldn't tell which port it listens on. Publish one from its page.": "{name}ni ulashib boʻlmadi: Kiri u qaysi portni tinglashini aniqlay olmadi. Uning sahifasidan portni eʼlon qiling.", + "Couldn't share {name}: it stopped": "{name}ni ulashib boʻlmadi: u toʻxtadi", + "Couldn't share {name}: it's gone": "{name}ni ulashib boʻlmadi: u mavjud emas", + "Couldn't share {name}: {reason}": "{name}ni ulashib boʻlmadi: {reason}", + "Couldn't start {shell}: {error}": "{shell}ni ishga tushirib boʻlmadi: {error}", + "Couldn't stop {name}: {error}": "{name}ni toʻxtatib boʻlmadi: {error}", + "Couldn't switch docker: {error}": "dockerni almashtirib boʻlmadi: {error}", + "Crash reports": "Nosozlik hisobotlari", + "Crashed (139)": "Ishdan chiqdi (139)", + "Create a diagnostics report": "Diagnostika hisobotini yaratish", + "Create report…": "Hisobot yaratish…", + "Created": "Yaratilgan", + "Critical": "Kritik", + "Custom": "Maxsus", + "Cut": "Kesib olish", + "Dark": "Qorongʻi", + "Database": "Maʼlumotlar bazasi", + "Debug": "Debug", + "Delete": "Oʻchirish", + "Delete cluster": "Klasterni oʻchirish", + "Delete pod {name}?": "{name} podini oʻchirasizmi?", + "Delete the Kubernetes cluster?": "Kubernetes klasterini oʻchirasizmi?", + "Delete {what}?": "{what} oʻchirilsinmi?", + "Deleting": "Oʻchirilmoqda", + "Deleting Kubernetes": "Kubernetes oʻchirilmoqda", + "Deleting pod {pod}": "{pod} podi oʻchirilmoqda", + "Deleting…": "Oʻchirilmoqda…", + "Deployment {name} runs this pod": "Bu podni {name} deploymenti ishga tushiradi", + "Detach": "Ajratish", + "Detaching…": "Ajratilmoqda…", + "Details": "Tafsilotlar", + "Device": "Qurilma", + "Diagnostics": "Diagnostika", + "Diagnostics report": "Diagnostika hisoboti", + "Did you mean {name}?": "{name} demoqchimisiz?", + "Didn't pull": "Yuklab olinmadi", + "Didn't pull.": "Yuklab olinmadi.", + "Disconnect": "Uzish", + "Disconnecting…": "Uzilmoqda…", + "Dismiss": "Yopish", + "Docker Desktop": "Docker Desktop", + "Docker Hub can't be reached": "Docker Hubga ulanib boʻlmadi", + "Docker Hub has no image called {name}.": "Docker Hubda {name} nomli obraz yoʻq.", + "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub obrazlari ushbu koʻzgular orqali tartib bilan tortib olinadi; obraz bor birinchi koʻzgu javob beradi, aks holda Docker Hubning oʻzidan olinadi. Boshqa reyestrlar toʻgʻridan-toʻgʻri tortib olinadi.", + "Docker tools": "Docker vositalari", + "Docker tools are ready": "Docker vositalari tayyor", + "Docker's default engine": "Dockerning standart dvijogi", + "Docker's own page signs you in. Check that it shows this code:": "Kirish Dockerning oʻz sahifasida amalga oshiriladi. Unda ushbu kod koʻrsatilganini tekshiring:", + "Docs": "Hujjatlar", + "Domains": "Domenlar", + "Done": "Tayyor", + "Download": "Yuklab olish", + "Download Ubuntu": "Ubuntuni yuklab olish", + "Download WSL": "WSLni yuklab olish", + "Download the new .deb or .rpm": "Yangi .deb yoki .rpm faylini yuklab oling", + "Downloading Grype, the scanner (about 30 MB, once)": "Grype skaneri yuklab olinmoqda (taxminan 30 MB, bir marta)", + "Downloading Ubuntu 26.04": "Ubuntu 26.04 yuklab olinmoqda", + "Downloading {name} from {source}": "{name} {source}dan yuklab olinmoqda", + "Downloading {version}": "{version} yuklab olinmoqda", + "Downloading…": "Yuklab olinmoqda…", + "Drag to resize": "Oʻlchamini oʻzgartirish uchun torting", + "Drag to resize, double-click to reset": "Oʻlchamini oʻzgartirish uchun torting, asliga qaytarish uchun ikki marta bosing", + "Driver": "Drayver", + "Duration": "Davomiylik", + "Edit": "Tahrirlash", + "Ended: pod deleted": "Tugadi: pod oʻchirildi", + "Ended: pod restarted · share the service to keep a link": "Tugadi: pod qayta ishga tushirildi · havolani saqlab qolish uchun servisni ulashing", + "Ended: service deleted": "Tugadi: servis oʻchirildi", + "Engine": "Dvijok", + "Engine running": "Dvijok ishlamoqda", + "Engine updated": "Dvijok yangilandi", + "Enter the port the app in the pod listens on, 1 to 65535": "Poddagi ilova tinglayotgan portni kiriting, 1 dan 65535 gacha", + "Enter this code on GitHub": "Ushbu kodni GitHubda kiriting", + "Enter your MFA code": "MFA kodingizni kiriting", + "Environment": "Muhit", + "Error": "Xato", + "Errors": "Xatolar", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "Undagi hamma narsa oʻchiriladi: podlar, servislar, tomlar va boshqa resurslar, shuningdek {context} kubectl konteksti. Keyingi ishga tushirishda yangi, boʻsh klaster yaratiladi.", + "Everything in the window.": "Oynadagi hamma narsa.", + "Everything is in Kiri.": "Hammasi allaqachon Kirida.", + "Exit code": "Chiqish kodi", + "Exited with code {code}, {when}": "{code} kodi bilan chiqdi, {when}", + "Expand all": "Hammasini yoyish", + "Expose services to LAN": "Servislarni mahalliy tarmoqqa ochish", + "External": "Tashqi", + "Failed": "Muvaffaqiyatsiz", + "Failed ({code})": "Muvaffaqiyatsiz ({code})", + "Failing": "Xato bermoqda", + "Feedback": "Fikr-mulohaza", + "Files": "Fayllar", + "Find": "Qidirish", + "Find ({keys})": "Qidirish ({keys})", + "Find a path, method or status": "Yoʻl, metod yoki holatni qidirish", + "Find in logs": "Jurnallardan qidirish", + "Find in the terminal": "Terminaldan qidirish", + "Finish updating to Kiri {version}": "Kiri {version}ga yangilashni yakunlang", + "Finished": "Yakunlandi", + "Fix all": "Hammasini tuzatish", + "Fixed in": "Tuzatilgan versiya", + "Fold the sidebar": "Yon panelni yigʻish", + "Follow": "Kuzatish", + "Follow {os} (now {lang}), or always use one language.": "{os} tiliga moslashish (hozir {lang}) yoki doim bitta tildan foydalanish.", + "Follow {os}, or always use the dark or light theme.": "{os} mavzusiga moslashish yoki doim qorongʻi yoxud yorugʻ mavzudan foydalanish.", + "Font": "Shrift", + "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "Ushbu {host}dagi Kubernetes uchun Kirining oʻz klasteri bor. Bu yon paneldagi Kubernetes ostidagi almashtirgich.", + "For pulling and pushing images.": "Obrazlarni yuklab olish va yuborish uchun.", + "Forward": "Oldinga", + "Found": "Topildi", + "Freed {size}": "{size} boʻshatildi", + "Frees {size}": "{size} boʻshatadi", + "From": "Qayerdan", + "From its base image": "Uning asosiy obrazidan", + "From the base image": "Asosiy obrazdan", + "From ubuntu.com, through Microsoft's WSL list.": "ubuntu.com saytidan, Microsoftning WSL roʻyxati orqali.", + "Generate": "Yaratish", + "Getting a link…": "Havola olinmoqda…", + "GitHub opened in your browser. Approve there and you're signed in straight away.": "GitHub brauzeringizda ochildi. Oʻsha yerda tasdiqlang va darhol tizimga kirasiz.", + "GitHub opened in your browser. Approve there and {what} is shared straight away.": "GitHub brauzeringizda ochildi. Oʻsha yerda tasdiqlang va {what} darhol ulashiladi.", + "GitHub's page asks you to let Kiri read your packages. Check that it shows this code:": "GitHub sahifasi Kiriga paketlaringizni oʻqishga ruxsat berishingizni soʻraydi. Unda ushbu kod koʻrsatilganini tekshiring:", + "Give it back to this computer": "Uni ushbu kompyuterga qaytarish", + "Give the VM more memory": "VMga koʻproq xotira ajratish", + "Give {name} a public https link": "{name} uchun ommaviy https havola berish", + "Given back to Windows": "Windowsga qaytarildi", + "Given back to the Mac": "Macga qaytarildi", + "Go to Containers": "Konteynerlarga oʻtish", + "Gone from Kiri": "Kiridan oʻchirilgan", + "Graphics|process": "Grafika", + "Green": "Yashil", + "Grype, the open-source scanner from Anchore": "Grype, Anchore kompaniyasining ochiq kodli skaneri", + "HTTP proxy": "HTTP proksi", + "HTTPS proxy": "HTTPS proksi", + "Hand it to Kiri's containers": "Uni Kiri konteynerlariga berish", + "Has a fix": "Tuzatish mavjud", + "Have": "Mavjud", + "Headless: there's no cluster address to share. Share one of its pods.": "Headless: ulashish uchun klaster manzili yoʻq. Uning podlaridan birini ulashing.", + "Health check": "Holat tekshiruvi", + "Helpers|process": "Yordamchilar", + "Hide": "Yashirish", + "Hide ({keys})": "Yashirish ({keys})", + "Hide password": "Parolni yashirish", + "Hide the crash report": "Nosozlik hisobotini yashirish", + "Hide the terminal ({keys})": "Terminalni yashirish ({keys})", + "Hide until Kiri next opens": "Kiri keyingi safar ochilguncha yashirish", + "Hide until {name} has more": "{name}da koʻproq narsa paydo boʻlguncha yashirish", + "Hide {app}": "{app}ni yashirish", + "High": "Yuqori", + "Host or network": "Xost yoki tarmoq", + "How it runs": "Qanday ishlaydi", + "How should you reach your containers?": "Konteynerlaringizga qanday murojaat qilasiz?", + "ID": "ID", + "IDs, commands and code.": "ID, buyruqlar va kod.", + "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "API server sertifikati qoʻshimcha ravishda qamrab oladigan, vergul bilan ajratilgan IP manzillar yoki domen nomlari, masalan, ushbu {host}ning tarmogʻingizdagi manzili. Saqlash klasterni qayta ishga tushiradi.", + "If Kiri's useful, a star on GitHub helps others find it.": "Agar Kiri foydali boʻlsa, GitHubdagi yulduzcha boshqalarga uni topishga yordam beradi.", + "If it's private, run {cmd} first.": "Agar u shaxsiy boʻlsa, avval {cmd} buyrugʻini bajaring.", + "If it's private, sign in first:": "Agar u shaxsiy boʻlsa, avval tizimga kiring:", + "If it's private, {link} first.": "Agar u shaxsiy boʻlsa, avval {link}.", + "If it's private, {link}.": "Agar u shaxsiy boʻlsa, {link}.", + "Image": "Obraz", + "Image to pull": "Yuklab olinadigan obraz", + "Images": "Obrazlar", + "Images you pull or build show up here: docker pull alpine, or search above.": "Siz yuklab olgan yoki yigʻgan obrazlar shu yerda koʻrinadi: docker pull alpine yoki yuqorida qidiring.", + "Import": "Import", + "Import from": "Qayerdan import qilish", + "Import {n} item": "{n} ta elementni import qilish", + "Import {n} items": "{n} ta elementni import qilish", + "Imported": "Import qilindi", + "Imported {done}; {failed} failed (hover “Failed” for why).": "Import qilindi: {done}; muvaffaqiyatsiz: {failed} (sababini bilish uchun kursorni “Muvaffaqiyatsiz” ustiga olib boring).", + "Imported {n} item.": "{n} ta element import qilindi.", + "Imported {n} items.": "{n} ta element import qilindi.", + "Importing…": "Import qilinmoqda…", + "In Kiri": "Kirida", + "In a container": "Konteynerda", + "In a week": "Bir haftadan keyin", + "In use": "Foydalanilmoqda", + "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "Foydalanilmoqda: {used}. Hozir VM {target}gacha joy egallashi mumkin va konteynerlarga koʻproq kerak boʻlganda kengayadi.", + "In use: {proxy}, except {hosts}.": "Foydalanilmoqda: {proxy}, {hosts} bundan mustasno.", + "In use: {proxy}.": "Foydalanilmoqda: {proxy}.", + "Included": "Kiritilgan", + "Info": "Maʼlumot", + "Info and up": "Maʼlumot va undan yuqori", + "Insecure registries": "Xavfsiz boʻlmagan reyestrlar", + "Inside Linux": "Linux ichida", + "Install Kiri's engine in it": "Unga Kiri dvijogini oʻrnatish", + "Install WSL": "WSLni oʻrnatish", + "Install usbipd-win": "usbipd-winni oʻrnatish", + "Installed": "Oʻrnatilgan", + "Installing": "Oʻrnatilmoqda", + "Installing Windows Subsystem for Linux": "Linux uchun Windows quyi tizimi oʻrnatilmoqda", + "Installing…": "Oʻrnatilmoqda…", + "Installs when you quit Kiri": "Kiridan chiqqaningizda oʻrnatiladi", + "Interface font": "Interfeys shrifti", + "Internal steps": "Ichki qadamlar", + "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "U Linux VMning oʻzini oʻzgartirishni talab qiladi, “Ishga tushirish” esa bunga ruxsat bermaydi. Agar {image}ga ishonsangiz, uni {cmd} buyrugʻi bilan oʻzingiz ishga tushiring.", + "It has no selector, so it picks no pods.": "Unda selektor yoʻq, shuning uchun u hech qanday podni tanlamaydi.", + "It restarts, so open connections drop.": "U qayta ishga tushadi, shuning uchun ochiq ulanishlar uziladi.", + "It stays up while Kiri is running.": "Kiri ishlayotgan vaqtda u ishlab turadi.", + "It takes effect when it next starts.": "Bu keyingi ishga tushirilganda kuchga kiradi.", + "It works with serial adapters, Zigbee sticks, mice and keyboards; webcams and audio aren't supported yet.": "U ketma-ket port adapterlari, Zigbee stiklari, sichqonchalar va klaviaturalar bilan ishlaydi; veb-kameralar va audio hozircha qoʻllab-quvvatlanmaydi.", + "It wrote nothing to its log.": "U jurnaliga hech narsa yozmadi.", + "It's a network interface inside Linux, not a device file.": "Bu Linux ichidagi tarmoq interfeysi, qurilma fayli emas.", + "It's deleted, with its files and unnamed volumes. Named volumes stay.": "U fayllari va nomsiz tomlari bilan birga oʻchiriladi. Nomli tomlar saqlanib qoladi.", + "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "U toʻxtatiladi va fayllari hamda nomsiz tomlari bilan birga oʻchiriladi. Nomli tomlar saqlanib qoladi.", + "Its API server stalls or stops answering · {free}": "Uning API serveri qotib qoladi yoki javob bermay qoʻyadi · {free}", + "Its container is stopped and deleted, with their files. Named volumes stay.": "Uning konteyneri toʻxtatiladi va fayllari bilan birga oʻchiriladi. Nomli tomlar saqlanib qoladi.", + "Its containers stop and their files go.": "Uning konteynerlari toʻxtaydi va ularning fayllari oʻchiriladi.", + "Its data is deleted for good.": "Uning maʼlumotlari butunlay oʻchiriladi.", + "Its deployment starts a new pod in its place.": "Uning deploymenti oʻrniga yangi pod ishga tushiradi.", + "Its job may start it again.": "Uning job vazifasi uni yana ishga tushirishi mumkin.", + "Its last container stopped because {name} wasn't set.": "Uning oxirgi konteyneri {name} oʻzgaruvchisi belgilanmagani uchun toʻxtadi.", + "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "Tugun ishlamoqda, lekin API server javob bermayapti. VM band boʻlsa yoki xotirasi yetmasa, shunday boʻlishi mumkin; Kiri soʻrashda davom etmoqda.", + "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "Tugun ishlamoqda, lekin API server javob bermayapti: {error}. VM band boʻlsa yoki xotirasi yetmasa, shunday boʻlishi mumkin; Kiri soʻrashda davom etmoqda.", + "Its start script stops when {name} isn't set.": "{name} oʻzgaruvchisi belgilanmasa, uning ishga tushirish skripti toʻxtaydi.", + "Its start script stops without it: “{why}”.": "Usiz uning ishga tushirish skripti toʻxtaydi: “{why}”.", + "Its value": "Uning qiymati", + "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "Uning {n} ta konteyneri toʻxtatiladi va fayllari bilan birga oʻchiriladi. Nomli tomlar saqlanib qoladi.", + "Its {owner} starts a new pod in its place.": "Uning {owner} egasi oʻrniga yangi pod ishga tushiradi.", + "KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.": "Demon uchun KIRI_CPUS yoki KIRI_MEMORY_MIB belgilangan va u ushbu sozlamalardan ustun turadi.", + "Keep": "Qoldirish", + "Keep building with Docker": "Docker bilan yigʻishda davom etish", + "Keep building with Docker.": "Docker bilan yigʻishda davom eting.", + "Keep typing to search Docker Hub.": "Docker Hubda qidirish uchun yozishda davom eting.", + "Keep using your PC meanwhile.": "Bu orada kompyuteringizdan foydalanishingiz mumkin.", + "Kept in Credential Manager": "Hisob maʼlumotlari menejerida saqlanadi", + "Kept in the Keychain": "Keychainda saqlanadi", + "Kept in {path} with Docker's names, for docker pull, push, login and build. Docker Desktop's file is left alone.": "docker pull, push, login va build uchun Docker nomlari bilan {path} faylida saqlanadi. Docker Desktop fayliga tegilmaydi.", + "Kept {name}: {container} couldn't be removed ({error})": "{name} saqlab qolindi: {container} oʻchirilmadi ({error})", + "Kept {name}: {error}": "{name} saqlab qolindi: {error}", + "Key": "Kalit", + "Keyboard": "Klaviatura", + "Killed (137)": "Majburan toʻxtatildi (137)", + "Kiri Cloud gives it a public https link through a secure tunnel from this {host}. You sign in with GitHub, so every link traces back to a person. Kiri never sees your password.": "Kiri Cloud unga ushbu {host}dan xavfsiz tunnel orqali ommaviy https havola beradi. Siz GitHub orqali kirasiz, shuning uchun har bir havola aniq bir shaxsga bogʻlanadi. Kiri parolingizni hech qachon koʻrmaydi.", + "Kiri Setup": "Kiri oʻrnatish", + "Kiri and this Mac": "Kiri va ushbu Mac", + "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri hozircha ovoz yoki videoni uzata olmaydi: konteynerlar undan hech narsa olmaydi.", + "Kiri engine installed": "Kiri dvijogi oʻrnatildi", + "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri obrazdagi har bir paketni (OT paketlari, dasturlash tili kutubxonalari va binar fayllar) topadi va har birini zaifliklar bazasi boʻyicha tekshiradi. Hali skanerlash yoʻq: birinchisini ishga tushiring.", + "Kiri is not running": "Kiri ishlamayapti", + "Kiri is ready": "Kiri tayyor", + "Kiri is set up.": "Kiri sozlandi.", + "Kiri quit unexpectedly last time": "Oxirgi marta Kiri kutilmaganda yopilgan", + "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri Grypeni shu yerda, Macingizda Kiri omboridagi obraz uchun ishga tushiradi. Obraz hech qayerga yuklanmaydi.", + "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri Linux konteynerlarini WSL ichida, oʻzining alohida Linuxida ishga tushiradi. Ikkala variant ham bir xil konteynerlarni bir xil tezlikda ishga tushiradi; ular hajmi va qoʻshimcha nimalar olishingiz bilan farq qiladi.", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri Linux konteynerlarini Windowsda Docker Desktopsiz ishga tushiradi. Buning uchun Windows Subsystem for Linux (WSL) — Microsoftning Linuxni ishga tushirish usuli kerak, u esa bu kompyuterda hali yoʻq.", + "Kiri sets itself up for your Windows account only.": "Kiri faqat sizning Windows hisobingiz uchun sozlanadi.", + "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Dvijok ishga tushgach, Kiri oʻz yigʻuvchisini sozlaydi va shundan keyin yigʻishlar unda bajariladi.", + "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri Docker Hubga docker buyrugʻi orqali kiradi, lekin u oʻrnatilmagan. Uni oʻrnating va qaytadan urinib koʻring.", + "Kiri signs in to GitHub with the GitHub CLI (gh), which isn't installed. Install it, then try again.": "Kiri GitHubga GitHub CLI (gh) orqali kiradi, lekin u oʻrnatilmagan. Uni oʻrnating va qaytadan urinib koʻring.", + "Kiri started your container.": "Kiri konteyneringizni ishga tushirdi.", + "Kiri started {name} in {time}.": "Kiri {name}ni {time} ichida ishga tushirdi.", + "Kiri started {name}.": "Kiri {name}ni ishga tushirdi.", + "Kiri uses your AWS profile through the AWS CLI, which isn't installed. Public images still pull.": "Kiri AWS profilingizdan AWS CLI orqali foydalanadi, lekin u oʻrnatilmagan. Ommaviy obrazlar baribir yuklab olinadi.", + "Kiri will reuse the Ubuntu already installed on this PC. Kiri runs in it, and you keep opening it as your own Linux.": "Kiri bu kompyuterda allaqachon oʻrnatilgan Ubuntudan foydalanadi. Kiri unda ishlaydi, siz esa uni avvalgidek oʻz Linuxingiz sifatida ochaverasiz.", + "Kiri {version} is a test build: it doesn't update itself": "Kiri {version} — sinov yigʻmasi: u oʻzini oʻzi yangilamaydi", + "Kiri {version} is available": "Kiri {version} mavjud", + "Kiri {version} is downloaded": "Kiri {version} yuklab olindi", + "Kiri {version} is ready to install": "Kiri {version} oʻrnatishga tayyor", + "Kiri {version} is the newest version": "Kiri {version} — eng soʻnggi versiya", + "Kiri's Kubernetes cluster": "Kiri Kubernetes klasteri", + "Kiri's builder": "Kiri yigʻuvchisi", + "Kiri's certificate is no longer trusted": "Kiri sertifikatiga endi ishonilmaydi", + "Kiri's certificate is trusted: containers open over HTTPS": "Kiri sertifikatiga ishoniladi: konteynerlar HTTPS orqali ochiladi", + "Kiri's containers and engine use {used}, of the {total} this computer has.": "Kiri konteynerlari va dvijogi bu kompyuterdagi {total} dan {used} ishlatmoqda.", + "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "Kiri konteynerlari, dvijogi va agenti WSLdagi {total} dan {used} egallagan (buni .wslconfig belgilaydi).", + "Kiri's log": "Kiri jurnali", + "Kiri's logs": "Kiri jurnallari", + "Kiri's own, {name}, is on, so another copy isn't needed.": "Kirining oʻz {name} vositasi yoqilgan, shuning uchun yana bir nusxa kerak emas.", + "Kiri: {state}": "Kiri: {state}", + "Kiri’s engine": "Kiri dvijogi", + "Kubernetes cluster": "Kubernetes klasteri", + "Kubernetes deleted, with its state": "Kubernetes holati bilan birga oʻchirildi", + "Kubernetes is busy with another change; try again in a moment": "Kubernetes boshqa oʻzgarish bilan band; birozdan keyin qaytadan urinib koʻring", + "Kubernetes is managed in Settings → Kubernetes": "Kubernetes Sozlamalar → Kubernetes boʻlimida boshqariladi", + "Kubernetes is off": "Kubernetes oʻchiq", + "Kubernetes is out of memory": "Kubernetesga xotira yetmayapti", + "Kubernetes is running · API on {addr}": "Kubernetes ishlamoqda · API: {addr}", + "Kubernetes is running.": "Kubernetes ishlamoqda.", + "Kubernetes is running: {cmd}": "Kubernetes ishlamoqda: {cmd}", + "Kubernetes is short of memory.": "Kubernetesga xotira yetishmayapti.", + "Kubernetes is starting": "Kubernetes ishga tushmoqda", + "Kubernetes is stopping": "Kubernetes toʻxtamoqda", + "Kubernetes isn't answering": "Kubernetes javob bermayapti", + "Kubernetes isn't running": "Kubernetes ishlamayapti", + "Kubernetes needs about {need}, and this VM can use {max}, of which {used} is in use.": "Kubernetesga taxminan {need} kerak, bu VM esa {max} ishlata oladi, shundan {used} band.", + "Kubernetes needs about {need}, and this VM can use {max}.": "Kubernetesga taxminan {need} kerak, bu VM esa {max} ishlata oladi.", + "Kubernetes settings": "Kubernetes sozlamalari", + "Kubernetes settings saved. They apply when it next starts.": "Kubernetes sozlamalari saqlandi. Ular keyingi ishga tushirishda qoʻllaniladi.", + "Kubernetes stopped it: it used more memory than it may, or the VM ran out": "Kubernetes uni toʻxtatdi: u ruxsat etilganidan koʻproq xotira ishlatdi yoki VMda xotira tugadi", + "Kubernetes stopped. Its state is kept for the next start.": "Kubernetes toʻxtatildi. Uning holati keyingi ishga tushirish uchun saqlanadi.", + "Kubernetes: {error}": "Kubernetes: {error}", + "Labels": "Yorliqlar", + "Language": "Til", + "Large": "Katta", + "Later": "Keyinroq", + "Later installs it when you quit Kiri.": "Keyinroq: Kiridan chiqqaningizda oʻrnatiladi.", + "Later: Kiri waits in the tray and picks up after your next restart.": "Keyinroq: Kiri tizim tepsisida kutib turadi va keyingi qayta ishga tushirishdan soʻng davom etadi.", + "Layer": "Qatlam", + "Layers": "Qatlamlar", + "Let it pick a random one": "Tasodifiy tanlash", + "Lets {user} run containers without sudo": "{user}ga konteynerlarni sudosiz ishga tushirish imkonini beradi", + "Level": "Daraja", + "Light": "Yorugʻ", + "Linux VM": "Linux VM", + "Linux VM: {state}": "Linux VM: {state}", + "Linux account": "Linux hisobi", + "Linux for Kiri": "Kiri uchun Linux", + "Linux hasn't made a device for it yet.": "Linux hali u uchun qurilma yaratmadi.", + "Linux stopped a process for memory": "Linux xotira yetishmagani uchun jarayonni toʻxtatdi", + "Listening on {ports}": "{ports} tinglanmoqda", + "Live": "Faol", + "Live · waiting for the first visitor": "Faol · birinchi tashrif buyuruvchi kutilmoqda", + "Live|stream": "Jonli", + "Loading tags…": "Teglar yuklanmoqda…", + "Loading the steps…": "Qadamlar yuklanmoqda…", + "Loading…": "Yuklanmoqda…", + "Local names": "Mahalliy nomlar", + "Location": "Joylashuv", + "Log lines for this action": "Ushbu amal uchun jurnal yozuvlari", + "Log out now": "Hozir tizimdan chiqish", + "Log out to finish": "Yakunlash uchun tizimdan chiqing", + "Log text": "Jurnal matni", + "Logs": "Jurnallar", + "Logs: {error}": "Jurnallar: {error}", + "Looking for Kubernetes…": "Kubernetes qidirilmoqda…", + "Looking for OrbStack and Docker Desktop…": "OrbStack va Docker Desktop qidirilmoqda…", + "Looking for USB devices…": "USB qurilmalar qidirilmoqda…", + "Looking for crash reports…": "Nosozlik hisobotlari qidirilmoqda…", + "Looking for shells…": "Qobiqlar qidirilmoqda…", + "Low": "Past", + "MFA code": "MFA kodi", + "Mac": "Mac", + "Made by": "Muallif", + "Make Kiri the default": "Kirini asosiy qilish", + "Make Kiri the default for docker": "Kirini docker uchun asosiy qilish", + "Make a new one": "Yangisini yaratish", + "Manufacturer": "Ishlab chiqaruvchi", + "MariaDB won't start until you choose how its root account signs in.": "MariaDB root hisobi qanday kirishini tanlamaguningizcha ishga tushmaydi.", + "Maximise": "Yoyish", + "Medium": "Oʻrtacha", + "Memory": "Xotira", + "Memory full · {mem}": "Xotira toʻldi · {mem}", + "Method": "Usul", + "Mirror address": "Koʻzgu manzili", + "Modified": "Oʻzgartirilgan", + "Monospace font": "Bir xil kenglikdagi shrift", + "More": "Yana", + "More actions for {name}": "{name} uchun boshqa amallar", + "More memory": "Koʻproq xotira", + "More settings": "Boshqa sozlamalar", + "Mounts": "Ulanishlar", + "Mouse": "Sichqoncha", + "MySQL won't start until you choose how its root account signs in.": "MySQL root hisobi qanday kirishini tanlamaguningizcha ishga tushmaydi.", + "Name": "Nom", + "Named volumes from docker volume create or -v name:/path show up here.": "docker volume create yoki -v name:/path orqali yaratilgan nomli tomlar shu yerda koʻrinadi.", + "Names answer on {http} and {https}. Pick other ports when another app needs these; links then carry the port, like {url}.": "Nomlar {http} va {https} portlarida javob beradi. Agar bu portlar boshqa ilovaga kerak boʻlsa, boshqa portlarni tanlang; unda havolalarda port koʻrsatiladi, masalan, {url}.", + "Names, images and status. Not their files, logs or environment.": "Nomlar, obrazlar va holat. Ularning fayllari, jurnallari yoki muhiti emas.", + "Namespace": "Nomlar fazosi", + "Namespace · {up} of {all} running": "Nomlar fazosi · {all} tadan {up} tasi ishlamoqda", + "Needs a restart": "Qayta ishga tushirish kerak", + "Needs an administrator password once.": "Bir marta administrator paroli talab qilinadi.", + "Needs upper and lower case, a digit and a symbol, 8 or more": "Katta va kichik harflar, raqam va belgi kerak, kamida 8 ta", + "Negligible": "Ahamiyatsiz", + "Network": "Tarmoq", + "Networks": "Tarmoqlar", + "Networks you create with docker network create show up here.": "docker network create orqali yaratgan tarmoqlaringiz shu yerda koʻrinadi.", + "Network|process": "Tarmoq", + "New containers get {http}, {https} and {no}.": "Yangi konteynerlar {http}, {https} va {no} oladi.", + "New tab": "Yangi varaq", + "New tab ({keys})": "Yangi varaq ({keys})", + "Next match": "Keyingi moslik", + "No Linux username is needed now: Kiri runs inside Ubuntu on its own. Ubuntu asks for one only the first time you open it yourself. * Estimate.": "Hozir Linux foydalanuvchi nomi kerak emas: Kiri Ubuntu ichida mustaqil ishlaydi. Ubuntu uni faqat siz birinchi marta oʻzingiz ochganingizda soʻraydi. * Taxminiy.", + "No USB devices": "USB qurilmalar yoʻq", + "No build matches.": "Mos yigʻish topilmadi.", + "No builds yet": "Hali yigʻishlar yoʻq", + "No changes": "Oʻzgarishlar yoʻq", + "No containers running": "Ishlayotgan konteynerlar yoʻq", + "No containers yet": "Hali konteynerlar yoʻq", + "No crashes. Kiri keeps a report here if one of its parts ever stops unexpectedly.": "Nosozliklar yoʻq. Agar Kirining biror qismi kutilmaganda toʻxtasa, Kiri bu yerda hisobot saqlaydi.", + "No fix yet": "Hali tuzatish yoʻq", + "No images yet": "Hali obrazlar yoʻq", + "No known vulnerabilities in {n} packages": "{n} ta paketda maʼlum zaifliklar yoʻq", + "No language matches. Try its English name.": "Mos til topilmadi. Inglizcha nomini sinab koʻring.", + "No languages match": "Mos tillar yoʻq", + "No lines match.": "Mos qatorlar yoʻq.", + "No mirrors yet: Docker Hub images come from Docker Hub itself.": "Hali koʻzgular yoʻq: Docker Hub obrazlari bevosita Docker Hubning oʻzidan olinadi.", + "No networks yet": "Hali tarmoqlar yoʻq", + "No password, no login and no TLS. Fine on this Mac, not for anything shared.": "Parolsiz, loginsiz va TLSsiz. Bu Macda ishlatish uchun mos, lekin umumiy foydalanish uchun emas.", + "No password, no login and no TLS. Fine on this PC, not for anything shared.": "Parolsiz, loginsiz va TLSsiz. Bu kompyuterda ishlatish uchun mos, lekin umumiy foydalanish uchun emas.", + "No password, no login and no TLS. Fine on this computer, not for anything shared.": "Parolsiz, loginsiz va TLSsiz. Bu kompyuterda ishlatish uchun mos, lekin umumiy foydalanish uchun emas.", + "No pods": "Podlar yoʻq", + "No pods match its selector.": "Uning selektoriga mos podlar yoʻq.", + "No ports to share": "Ulashiladigan portlar yoʻq", + "No proxy is in use.": "Proksi ishlatilmayapti.", + "No requests match.": "Mos soʻrovlar yoʻq.", + "No requests yet": "Hali soʻrovlar yoʻq", + "No results": "Natija yoʻq", + "No service points at it, so the link goes straight to the pod.": "Unga hech qaysi servis yoʻnaltirilmagan, shuning uchun havola toʻgʻridan-toʻgʻri podga olib boradi.", + "No services": "Servislar yoʻq", + "No steps here.": "Bu yerda qadamlar yoʻq.", + "No visitors in the last 2 minutes": "Oxirgi 2 daqiqada tashrif buyuruvchilar boʻlmadi", + "No volumes yet": "Hali tomlar yoʻq", + "No {label}": "{label} yoʻq", + "Node": "Tugun", + "None": "Yoʻq", + "None (headless)": "Yoʻq (headless)", + "None found": "Hech narsa topilmadi", + "None match these filters.": "Bu filtrlarga hech narsa mos kelmaydi.", + "None: every registry is checked over HTTPS.": "Yoʻq: har bir reyestr HTTPS orqali tekshiriladi.", + "Not a web port, so it isn't shared": "Bu veb-port emas, shuning uchun ulashilmaydi", + "Not an image name: {reference}": "Obraz nomi emas: {reference}", + "Not answering · visitors get an error": "Javob bermayapti · tashrif buyuruvchilar xato koʻrmoqda", + "Not created yet": "Hali yaratilmagan", + "Not found.": "Topilmadi.", + "Not in use: no container was made from it": "Ishlatilmayapti: undan hech qanday konteyner yaratilmagan", + "Not now": "Hozir emas", + "Not now: ask again in a week": "Hozir emas: bir haftadan soʻng yana soʻrash", + "Not running": "Ishlamayapti", + "Not sent": "Yuborilmagan", + "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "Hali sozlanmagan. U birinchi yigʻishingizda yaratiladi va bunda BuildKit (taxminan 110 MB) bir marta yuklab olinadi.", + "Not signed in": "Hisobga kirilmagan", + "Not signed in to any registry": "Hech qaysi reyestrga kirilmagan", + "Nothing called “{q}” on Docker Hub": "Docker Hubda “{q}” nomli hech narsa yoʻq", + "Nothing changes: {build} builds where it does now, and the images stay in {engine}.": "Hech narsa oʻzgarmaydi: {build} hozirgi joyida yigʻishda davom etadi, obrazlar esa {engine}da qoladi.", + "Nothing here.": "Bu yerda hech narsa yoʻq.", + "Nothing is deleted. You can switch back any time from the status bar.": "Hech narsa oʻchirilmaydi. Istalgan vaqtda holat satridan ortga qaytishingiz mumkin.", + "Nothing logged yet.": "Jurnalda hali hech narsa yoʻq.", + "Nothing matches “{q}” in {tab}.": "{tab} boʻlimida “{q}” boʻyicha hech narsa topilmadi.", + "Nothing matches “{q}”.": "“{q}” boʻyicha hech narsa topilmadi.", + "Nothing restarts it either: when the pod is deleted or restarts, the link ends.": "Uni qayta ishga tushiradigan narsa ham yoʻq: pod oʻchirilsa yoki qayta ishga tushsa, havola ishlamay qoladi.", + "Nothing shared yet": "Hali hech narsa ulashilmagan", + "Nothing shared. Press the globe beside a running container to give it a public link.": "Hech narsa ulashilmagan. Ishlayotgan konteynerga ochiq havola berish uchun uning yonidagi globus belgisini bosing.", + "Nothing starts it again: no deployment or other controller owns it.": "Uni hech narsa qayta ishga tushirmaydi: u hech qanday deployment yoki boshqa kontrollerga tegishli emas.", + "Nothing to download": "Yuklab olinadigan narsa yoʻq", + "Nothing to download: it came inside Kiri.": "Yuklab olinadigan narsa yoʻq: u Kiri tarkibida keladi.", + "Nothing to import from: OrbStack and Docker Desktop aren't on this {host}.": "Import qilish uchun manba yoʻq: bu {host}da OrbStack va Docker Desktop yoʻq.", + "Nothing to pass to a container yet.": "Hozircha konteynerga uzatiladigan hech narsa yoʻq.", + "Nothing to type: it uses the AWS sign-in already on this computer.": "Hech narsa kiritish shart emas: bu kompyuterdagi mavjud AWS kirishidan foydalaniladi.", + "Now": "Hozir", + "OK": "OK", + "Off": "Oʻchiq", + "Off: Kiri checks only when you click Check now.": "Oʻchiq: Kiri faqat “Hozir tekshirish” tugmasini bosganingizda tekshiradi.", + "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "Oʻchiq: konteynerlar <name>.kiri.localhost manzilida javob beradi, buning uchun sozlash kerak emas.", + "Off: press Start engine to run containers. It stays off after a restart until you start it.": "Oʻchiq: konteynerlarni ishga tushirish uchun “Dvijokni ishga tushirish” tugmasini bosing. Qayta ishga tushirilgandan keyin ham uni oʻzingiz yoqmaguningizcha oʻchiq qoladi.", + "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "Oʻchiq: API server va LoadBalancer xizmatlari faqat shu {host} qurilmasida (127.0.0.1) javob beradi.", + "Official": "Rasmiy", + "On": "Yoqilgan", + "On disk": "Diskda", + "On this Mac": "Shu Mac kompyuterida", + "On this PC": "Shu kompyuterda", + "On {registry} an image is named owner/image, such as {example}. Type one to choose its tag, or paste a full reference.": "{registry} reyestrida obraz owner/image koʻrinishida nomlanadi, masalan, {example}. Tegini tanlash uchun nomini kiriting yoki toʻliq havolani qoʻying.", + "On {targets}": "{targets}da", + "On: Kiri checks each time it opens. It never updates without asking.": "Yoqilgan: Kiri har safar ochilganda tekshiradi. U hech qachon soʻramasdan yangilanmaydi.", + "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "Yoqilgan: konteynerlar https:// orqali Kirining oʻz sertifikati bilan ochiladi; bu sertifikat faqat .kiri.local va .kiri.localhost nomlari uchun amal qiladi.", + "On: running containers answer at <name>.kiri.local.": "Yoqilgan: ishlab turgan konteynerlar <name>.kiri.local manzilida javob beradi.", + "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "Yoqilgan: API server va LoadBalancer xizmatlari barcha tarmoq interfeyslarida javob beradi, shuning uchun tarmogʻingizdagi boshqa qurilmalar ularga ulana oladi.", + "One more step: log out and back in.": "Yana bir qadam: tizimdan chiqib, qayta kiring.", + "One more step: set it up, or skip.": "Yana bir qadam: uni sozlang yoki oʻtkazib yuboring.", + "One restart to finish WSL": "WSL oʻrnatilishini yakunlash uchun bitta qayta ishga tushirish", + "One text file, redacted, saved to your Desktop and shown in Finder. Read it before you share it.": "Shaxsiy maʼlumotlari olib tashlangan bitta matn fayli Ish stolingizga saqlanadi va Finderda koʻrsatiladi. Uni ulashishdan oldin oʻqib chiqing.", + "Only from {what}": "Faqat {what} manbasidan", + "Only {size} left this month. When it runs out, the link stops until next month.": "Bu oy faqat {size} qoldi. U tugagach, havola keyingi oygacha ishlamay qoladi.", + "Open": "Ochish", + "Open Kiri": "Kirini ochish", + "Open Pods": "Podlarni ochish", + "Open Share": "Ulashishni ochish", + "Open in Terminal": "Terminalda ochish", + "Open logs folder": "Jurnallar jildini ochish", + "Open the page again": "Sahifani qayta ochish", + "Open {addr}": "{addr} manzilini ochish", + "Open {name}": "{name}ni ochish", + "Open {site}": "{site} saytini ochish", + "Open {url}": "{url} manzilini ochish", + "OpenSearch won't start without a strong admin password.": "OpenSearch kuchli administrator parolisiz ishga tushmaydi.", + "Opening the scan…": "Skanerlash natijasi ochilmoqda…", + "Optional": "Ixtiyoriy", + "Or allow an empty password": "Yoki boʻsh parolga ruxsat berish", + "Or let it pick a random password": "Yoki tasodifiy parol tanlansin", + "Or set {names} instead.": "Yoki uning oʻrniga {names} qiymatini belgilang.", + "Or turn security off for local use": "Yoki mahalliy foydalanish uchun himoyani oʻchirib qoʻyish", + "Orange": "Toʻq sariq", + "OrbStack": "OrbStack", + "Out of memory": "Xotira yetarli emas", + "Overview": "Umumiy koʻrinish", + "PC": "Kompyuter", + "Package": "Paket", + "Packages": "Paketlar", + "Page|process": "Sahifa", + "Pane restored": "Panel tiklandi", + "Pane zoomed": "Panel kattalashtirildi", + "Part": "Qism", + "Part of Kiri": "Kiri tarkibiy qismi", + "Part of the cluster itself (kube-system). Not shared.": "Klasterning oʻz qismi (kube-system). Ulashilmaydi.", + "Pass to containers": "Konteynerlarga uzatish", + "Paste": "Qoʻyish", + "Paste NAME=value lines, or a .env file, into a name.": "NAME=value qatorlarini yoki .env faylini nom maydoniga qoʻying.", + "Paste {n} lines? Each line runs as a command.": "{n} ta qator qoʻyilsinmi? Har bir qator buyruq sifatida bajariladi.", + "Path": "Yoʻl", + "Pause": "Pauza qilish", + "Paused": "Pauzada", + "Paused · nobody can open the link": "Pauzada · havolani hech kim ocha olmaydi", + "Paused: nobody can open the link until you resume.": "Pauzada: davom ettirmaguningizcha havolani hech kim ocha olmaydi.", + "Peak {rate}": "Eng yuqori: {rate}", + "Pin tab": "Varaqni qadash", + "Pink": "Pushti", + "Pinned": "Qadalgan", + "Pinned: right-click to unpin": "Qadalgan: qadashni bekor qilish uchun oʻng tugmani bosing", + "Pinned: unpin the tab to close it": "Qadalgan: varaqni yopish uchun avval qadashni bekor qiling", + "Plug one in: a serial adapter, a Zigbee stick, a microcontroller. It shows up here.": "Biror qurilmani ulang: ketma-ket port adapteri, Zigbee stik, mikrokontroller. U shu yerda koʻrinadi.", + "Pod IP": "Pod IP manzili", + "Pod in {ns}": "{ns} ichidagi pod", + "Pod in {ns} · on {node}": "{ns} ichidagi pod · {node} tugunida", + "Pods": "Podlar", + "Pods you create with kubectl show up here, grouped by namespace.": "kubectl orqali yaratgan podlaringiz nomlar fazosi boʻyicha guruhlangan holda shu yerda koʻrinadi.", + "Port": "Port", + "Port in the container": "Konteynerdagi port", + "Port on your {host}": "{host} qurilmangizdagi port", + "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "{host} qurilmangizdagi port (localhost) → konteyner ichidagi port. Boʻsh portni tanlash uchun {host} tomonini boʻsh qoldiring.", + "Port {port} is already in use on this {host}": "{port} porti bu {host} qurilmasida allaqachon band", + "Port {port}. The link keeps working when pods restart.": "{port} porti. Podlar qayta ishga tushganda ham havola ishlashda davom etadi.", + "Ports": "Portlar", + "Ports changed": "Portlar oʻzgartirildi", + "Ports for {name}": "{name} portlari", + "Ports removed": "Portlar oʻchirildi", + "Ports saved: {ports}": "Portlar saqlandi: {ports}", + "Ports…": "Portlar…", + "Postgres won't start without a superuser password.": "Postgres superfoydalanuvchi parolisiz ishga tushmaydi.", + "Powered by": "Asosida ishlaydi:", + "Press Share on a running container to give it a public https link anyone can open.": "Ishlab turgan konteynerga istalgan kishi ocha oladigan ommaviy https havolasini berish uchun undagi Ulashish tugmasini bosing.", + "Press to see it, or disconnect it.": "Koʻrish yoki uzish uchun bosing.", + "Press to try again": "Qayta urinish uchun bosing", + "Previous match": "Oldingi moslik", + "Previous run": "Oldingi ishga tushirish", + "Printed once in the container's log.": "Konteyner jurnaliga bir marta chiqariladi.", + "Private images won't pull until you sign in again.": "Qayta kirmaguningizcha shaxsiy obrazlar yuklab olinmaydi.", + "Processes": "Jarayonlar", + "Progress": "Jarayon", + "Protocol": "Protokol", + "Proxy": "Proksi", + "Proxy settings saved": "Proksi sozlamalari saqlandi", + "Public images need no sign-in": "Ommaviy obrazlar uchun kirish shart emas", + "Public images on public.ecr.aws need nothing. For your own account's registry, Kiri runs {cmd} with this profile.": "public.ecr.aws saytidagi ommaviy obrazlar uchun hech narsa kerak emas. Oʻz hisobingiz reyestri uchun Kiri ushbu profil bilan {cmd} buyrugʻini bajaradi.", + "Public images pull without signing in.": "Ommaviy obrazlar kirmasdan yuklab olinadi.", + "Publish": "Eʼlon qilish", + "Publish on {targets}": "{targets}da eʼlon qilish", + "Publish the port {name} listens on, and give it a public https link": "{name} tinglayotgan portni eʼlon qilish va unga ommaviy https havolasini berish", + "Pull": "Yuklab olish", + "Pull again": "Qayta yuklab olish", + "Pull an image": "Obrazni yuklab olish", + "Pull an image ({key})": "Obrazni yuklab olish ({key})", + "Pull exactly this": "Aynan shuni yuklab olish", + "Pull from": "Qayerdan yuklab olish", + "Pull image": "Obrazni yuklab olish", + "Pull {tag}": "{tag}ni yuklab olish", + "Pulled": "Yuklab olindi", + "Pulled {name}": "{name} yuklab olindi", + "Pulled {name} in {time}.": "{name} {time} ichida yuklab olindi.", + "Pulled {when}": "Yuklab olingan: {when}", + "Pulling": "Yuklab olinmoqda", + "Pulling {n}": "Yuklab olinmoqda: {n}", + "Purple": "Binafsha", + "Quit": "Chiqish", + "Quit Kiri": "Kiridan chiqish", + "Quit {app}": "{app}dan chiqish", + "Quote {id} if you write to us about this crash.": "Bu nosozlik haqida bizga yozsangiz, {id} raqamini koʻrsating.", + "Radio": "Radio", + "Ran": "Bajarildi", + "Reachable at {addr}": "{addr} manzilida mavjud", + "Reachable at {url}": "{url} manzilida mavjud", + "Read more on runkiri.com ↗": "Batafsil runkiri.com saytida ↗", + "Reading build history…": "Yigʻishlar tarixi oʻqilmoqda…", + "Reading the image…": "Obraz oʻqilmoqda…", + "Reading the log…": "Jurnal oʻqilmoqda…", + "Reading the scans…": "Skanerlash natijalari oʻqilmoqda…", + "Reading what {name} has…": "{name} tarkibi oʻqilmoqda…", + "Ready": "Tayyor", + "Recent crashes": "Soʻnggi nosozliklar", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Biror narsa notoʻgʻri ketganda foydalanish uchun soʻnggi jurnallar, nosozlik hisobotlari va versiyalar shaxsiy maʼlumotlari olib tashlangan bitta faylda.", + "Recent pulls": "Soʻnggi yuklab olishlar", + "Recommended": "Tavsiya etiladi", + "Reconnecting": "Qayta ulanmoqda", + "Reconnecting {name}…": "{name} qayta ulanmoqda…", + "Reconnecting · {reason}": "Qayta ulanmoqda · {reason}", + "Reconnecting…": "Qayta ulanmoqda…", + "Redo": "Qaytadan bajarish", + "Registries": "Reyestrlar", + "Registries reached without a verified certificate (self-signed, or plain HTTP). Kiri tries HTTPS without checking the certificate, then HTTP. Only the hosts and networks listed; every other registry is checked as usual.": "Tasdiqlangan sertifikatsiz ulaniladigan reyestrlar (oʻzi imzolangan yoki oddiy HTTP). Kiri avval sertifikatni tekshirmasdan HTTPSni, soʻng HTTPni sinab koʻradi. Faqat roʻyxatdagi xost va tarmoqlar uchun; qolgan barcha reyestrlar odatdagidek tekshiriladi.", + "Registry": "Reyestr", + "Registry mirrors": "Reyestr koʻzgulari", + "Registry settings saved": "Reyestr sozlamalari saqlandi", + "Reload": "Qayta yuklash", + "Remove": "Oʻchirish", + "Remove Kubernetes' container?": "Kubernetes konteyneri oʻchirilsinmi?", + "Remove all": "Hammasini oʻchirish", + "Remove both": "Ikkalasini oʻchirish", + "Remove network {name}?": "{name} tarmogʻi oʻchirilsinmi?", + "Remove project": "Loyihani oʻchirish", + "Remove this build from the history?": "Bu yigʻish tarixdan oʻchirilsinmi?", + "Remove this port": "Bu portni oʻchirish", + "Remove volume {name}?": "{name} tomi oʻchirilsinmi?", + "Remove {name} and {image}?": "{name} va {image} oʻchirilsinmi?", + "Remove {name}?": "{name} oʻchirilsinmi?", + "Remove {n} containers and {image}?": "{n} konteyner va {image} oʻchirilsinmi?", + "Remove {n} untagged": "Tegsizlarni oʻchirish ({n})", + "Removed {gone} of {n} {what}": "{n} tadan {gone} ta oʻchirildi ({what})", + "Removed {name}": "{name} oʻchirildi", + "Removed {n} {what}": "Oʻchirildi ({what}): {n}", + "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "Klaster konteynerini, undagi hamma narsani ({volume} tomi) va {context} kubectl kontekstini {cmd} kabi oʻchiradi.", + "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "Xato bilan chiqqan {n} konteynerni fayllari bilan birga oʻchiradi. Nomli tomlar saqlanib qoladi.", + "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "Xato bilan chiqqan {n} konteynerni fayllari bilan birga oʻchiradi. Nomli tomlar saqlanib qoladi.", + "Removes the {n} failed build from the history.": "{n} muvaffaqiyatsiz yigʻishni tarixdan oʻchiradi.", + "Removes the {n} failed builds from the history.": "{n} muvaffaqiyatsiz yigʻishni tarixdan oʻchiradi.", + "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "Qayta yigʻishlardan qolgan {n} tegsiz obrazni oʻchiradi. Ulardan hech narsa foydalanmaydi. {size} boʻshatiladi.", + "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "Qayta yigʻishlardan qolgan {n} tegsiz obrazni oʻchiradi. Ulardan hech narsa foydalanmaydi. {size} boʻshatiladi.", + "Removing {gone} of {n}…": "Oʻchirilmoqda: {n} tadan {gone} ta…", + "Report ID": "Hisobot ID", + "Report sent": "Hisobot yuborildi", + "Repository": "Repozitoriy", + "Requests to {name}": "{name}ga soʻrovlar", + "Resources": "Resurslar", + "Restart": "Qayta ishga tushirish", + "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "Yakunlash uchun Kirini qayta ishga tushiring. Ishlayotgan konteynerlar toʻxtaydi, qayta ishga tushirish siyosati borlari esa yana ishga tushadi.", + "Restart VM to apply": "Qoʻllash uchun VMni qayta ishga tushirish", + "Restart all": "Hammasini qayta ishga tushirish", + "Restart engine": "Dvijokni qayta ishga tushirish", + "Restart engine to finish": "Yakunlash uchun dvijokni qayta ishga tushiring", + "Restart later": "Keyinroq qayta ishga tushirish", + "Restart now": "Hozir qayta ishga tushirish", + "Restart to update": "Yangilash uchun qayta ishga tushirish", + "Restart {name} with the new environment?": "{name} yangi muhit bilan qayta ishga tushirilsinmi?", + "Restarting stops the running containers; start them again afterwards.": "Qayta ishga tushirish ishlayotgan konteynerlarni toʻxtatadi; keyin ularni yana ishga tushiring.", + "Restarting…": "Qayta ishga tushirilmoqda…", + "Restarts": "Qayta ishga tushishlar", + "Restore": "Tiklash", + "Resume": "Davom ettirish", + "Retry": "Qayta urinish", + "Retry starts it again; the layers already here are kept.": "“Qayta urinish” uni yana boshlaydi; bu yerdagi qatlamlar saqlanib qoladi.", + "Review": "Koʻrib chiqish", + "Run": "Ishga tushirish", + "Run a test container": "Sinov konteynerini ishga tushirish", + "Run {cmd}, then Retry.": "{cmd} buyrugʻini bajaring, soʻng “Qayta urinish”ni bosing.", + "Running": "Ishlamoqda", + "Running Kiri {version} · back in {time}": "Kiri {version} ishlamoqda · {time}dan keyin qaytadi", + "Running containers answer at <name>.kiri.localhost, which needs no setup.": "Ishlayotgan konteynerlar <name>.kiri.localhost manzilida javob beradi, sozlash shart emas.", + "Running now with {cpus} and up to {mem}.": "Hozir {cpus} va {mem}gacha xotira bilan ishlamoqda.", + "Running, not ready": "Ishlamoqda, tayyor emas", + "Running: it rests by itself when nothing runs and wakes when you use it.": "Ishlamoqda: hech narsa ishlamaganda oʻzi dam oladi va undan foydalanganingizda uygʻonadi.", + "Running: {cmd}": "Ishlamoqda: {cmd}", + "Runs": "Ishga tushiradi", + "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "Har bir buyruqni {name} ichida {sh} orqali bajaradi; {cd} saqlanib qoladi. ↑ va ↓ oldingi buyruqlar boʻylab oʻtadi.", + "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "Shu yerda, Mac kompyuteringizda, obrazning Kiridagi nusxasi uchun bajariladi; hech narsa yuklanmaydi.", + "Runs your containers": "Konteynerlaringizni ishga tushiradi", + "SQL Server won't start without a strong password for its sa account, and its licence accepted.": "SQL Server sa hisobi uchun kuchli parol va litsenziya qabul qilinmaguncha ishga tushmaydi.", + "Same as the window ({font})": "Oynadagidek ({font})", + "Same as {os}": "{os}dagidek", + "Save": "Saqlash", + "Save SBOM": "SBOMni saqlash", + "Save and start": "Saqlash va ishga tushirish", + "Save to Desktop": "Ish stoliga saqlash", + "Save to Downloads": "Yuklanmalarga saqlash", + "Save {name}'s new environment?": "{name}ning yangi muhiti saqlansinmi?", + "Saved in .wslconfig. WSL uses these from its next start": ".wslconfig faylida saqlandi. WSL ularni keyingi ishga tushishdan boshlab qoʻllaydi", + "Saved in the container's environment. Kiri doesn't keep a copy.": "Konteyner muhitida saqlandi. Kiri nusxasini saqlamaydi.", + "Saved in this container's environment. Kiri doesn't keep a copy.": "Shu konteyner muhitida saqlandi. Kiri nusxasini saqlamaydi.", + "Saved the SBOM to Downloads as {file}": "SBOM Yuklanmalarga {file} sifatida saqlandi", + "Saved the report to {path}": "Hisobot {path}ga saqlandi", + "Saved to Downloads as {file}": "Yuklanmalarga {file} sifatida saqlandi", + "Saved. The VM uses these from its next start": "Saqlandi. VM ularni keyingi ishga tushishdan boshlab qoʻllaydi", + "Saving…": "Saqlanmoqda…", + "Scan again": "Qayta skanerlash", + "Scan image": "Obrazni skanerlash", + "Scan of {when}": "{when}dagi skanerlash", + "Scan with": "Skanerlash vositasi", + "Scan {image}": "{image}ni skanerlash", + "Scan {image} for known vulnerabilities": "{image}ni maʼlum zaifliklarga tekshirish", + "Scanned": "Skanerlandi", + "Scanning the image's packages": "Obraz paketlari skanerlanmoqda", + "Scans": "Skanerlashlar", + "Search Docker Hub, or paste an image reference": "Docker Hubdan qidiring yoki obraz havolasini qoʻying", + "Search Kiri": "Kiridan qidirish", + "Search Kiri…": "Kiridan qidirish…", + "Search containers, images…": "Konteynerlar, obrazlarni qidirish…", + "Search languages": "Tillarni qidirish", + "Search {view}…": "Qidirish: {view}…", + "Searching Docker Hub": "Docker Hubdan qidirilmoqda", + "Security": "Xavfsizlik", + "See it ↗": "Koʻrish ↗", + "See its tags": "Teglarini koʻrish", + "See what it looks like ↗": "Qanday koʻrinishini koʻring ↗", + "See why": "Nima uchun?", + "Select": "Tanlash", + "Select All": "Hammasini tanlash", + "Select all": "Hammasini tanlash", + "Select all {n}": "Hammasini tanlash ({n})", + "Select none": "Tanlovni bekor qilish", + "Select {name}": "{name}ni tanlash", + "Selected {what}": "Tanlangan: {what}", + "Selection, focus rings and primary buttons.": "Belgilash, fokus ramkalari va asosiy tugmalar.", + "Selector": "Selektor", + "Send": "Yuborish", + "Send a report to Kiri": "Kiriga hisobot yuborish", + "Send an idea or report a bug on GitHub": "GitHubda gʻoya yuboring yoki xato haqida xabar bering", + "Send crash reports automatically": "Nosozlik hisobotlarini avtomatik yuborish", + "Send report": "Hisobot yuborish", + "Send to Kiri": "Kiriga yuborish", + "Sending…": "Yuborilmoqda…", + "Sent": "Yuborildi", + "Sent as {id}": "{id} sifatida yuborildi", + "Sent. Quote {id} if you write to us.": "Yuborildi. Bizga yozsangiz, {id}ni koʻrsating.", + "Serial": "Ketma-ket port", + "Serial number": "Seriya raqami", + "Services": "Servislar", + "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "kubectl expose bilan yaratgan servislaringiz shu yerda koʻrinadi. LoadBalancer servislari localhost da javob beradi.", + "Session": "Seans", + "Set it and start": "Belgilash va ishga tushirish", + "Set up": "Sozlash", + "Set up Kiri": "Kirini sozlash", + "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "docker build shu yerda bajarilishi uchun Kiri yigʻuvchisini sozlang. Birinchi yigʻishgacha hech narsa yuklab olinmaydi", + "Set up with Kiri Linux": "Kiri Linux bilan sozlash", + "Set up with Ubuntu": "Ubuntu bilan sozlash", + "Set {what}": "{what}ni belgilash", + "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Microsoft obrazi talab qilganidek, ACCEPT_EULA=Y ni belgilaydi.", + "Setting up": "Sozlanmoqda", + "Setting up Docker tools…": "Docker vositalari sozlanmoqda…", + "Setting up Docker tools… {pct}%": "Docker vositalari sozlanmoqda… {pct}%", + "Setting up Kiri Linux": "Kiri Linux sozlanmoqda", + "Setting up Ubuntu 26.04": "Ubuntu 26.04 sozlanmoqda", + "Setting up the Docker tools": "Docker vositalari sozlanmoqda", + "Settings": "Sozlamalar", + "Settings…": "Sozlamalar…", + "Setup log": "Oʻrnatish jurnali", + "Setup steps": "Oʻrnatish bosqichlari", + "Setup time": "Oʻrnatish vaqti", + "Severity": "Jiddiylik", + "Share": "Ulashish", + "Share again": "Qayta ulashish", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "Ulashish konteyner yoki Kubernetes servisiga Kiri Cloudga xavfsiz tunnel orqali ommaviy https havola beradi.", + "Share pod {name}?": "{name} podi ulashilsinmi?", + "Share service {name}": "{name} servisini ulashish", + "Share this pod on a port…": "Bu podni portda ulashish…", + "Share this pod's port {port}": "Bu podning {port} portini ulashish", + "Share which port?": "Qaysi port ulashilsin?", + "Share {name}": "{name}ni ulashish", + "Shared": "Ulashilgan", + "Shared by {who}": "{who} ulashgan", + "Shared now": "Hozir ulashilgan", + "Shared with {os}: the VM only uses them while containers are busy.": "{os} bilan umumiy: VM ulardan faqat konteynerlar band boʻlganda foydalanadi.", + "Shared · {url}": "Havola orqali ochiq · {url}", + "Shares": "Ulashishlar", + "Sharing…": "Ulashilmoqda…", + "Short of memory, its API server slows down or stops answering.": "Xotira yetishmasa, uning API serveri sekinlashadi yoki javob bermay qoʻyadi.", + "Show": "Koʻrsatish", + "Show Images": "Obrazlarni koʻrsatish", + "Show all actions": "Barcha amallarni koʻrsatish", + "Show containers": "Konteynerlarni koʻrsatish", + "Show full log": "Toʻliq jurnalni koʻrsatish", + "Show in Diagnostics": "Diagnostikada koʻrsatish", + "Show in Finder": "Finderda koʻrsatish", + "Show its requests": "Uning soʻrovlarini koʻrsatish", + "Show password": "Parolni koʻrsatish", + "Show shares": "Ulashilganlarni koʻrsatish", + "Show the crash report": "Nosozlik hisobotini koʻrsatish", + "Show the pulls in Images": "Yuklab olishlarni Obrazlar boʻlimida koʻrsatish", + "Show the sidebar": "Yon panelni koʻrsatish", + "Show the terminal ({keys})": "Terminalni koʻrsatish ({keys})", + "Show the update": "Yangilanishni koʻrsatish", + "Sign in": "Kirish", + "Sign in and pull": "Kirish va yuklab olish", + "Sign in to a registry": "Reyestrga kirish", + "Sign in to a registry…": "Reyestrga kirish…", + "Sign in to see your plan": "Tarifingizni koʻrish uchun tizimga kiring", + "Sign in to share {what}": "Ulashish uchun tizimga kiring: {what}", + "Sign in to {registry}": "{registry} reyestriga kirish", + "Sign in with AWS": "AWS orqali kirish", + "Sign in with GitHub": "GitHub orqali kirish", + "Sign out": "Chiqish", + "Sign out of {registry}": "{registry} reyestridan chiqish", + "Sign out of {registry}?": "{registry} reyestridan chiqilsinmi?", + "Sign-in failed: {error}": "Kirib boʻlmadi: {error}", + "Sign-in needed.": "Tizimga kirish kerak.", + "Signed in": "Tizimga kirilgan", + "Signed in as {name}": "{name} sifatida kirilgan", + "Signed in as {name}.": "{name} sifatida kirilgan.", + "Signed in to Kiri Cloud with GitHub as {login}": "Kiri Cloudga GitHub orqali {login} sifatida kirilgan", + "Signed in to a registry, Kiri pulls its private images, and docker uses the same sign-in.": "Reyestrga kirilgach, Kiri uning shaxsiy obrazlarini yuklab oladi, docker esa xuddi shu kirishdan foydalanadi.", + "Signed in with GitHub": "GitHub orqali kirilgan", + "Signing in again uses your AWS profile.": "Qayta kirishda AWS profilingiz ishlatiladi.", + "Signing in…": "Kirilmoqda…", + "Signing out…": "Chiqilmoqda…", + "Size": "Hajm", + "Skip": "Oʻtkazib yuborish", + "Skip this version": "Bu versiyani oʻtkazib yuborish", + "Skipped: docker build builds where docker points": "Oʻtkazib yuborildi: docker build docker koʻrsatgan joyda yigʻadi", + "Skipped: docker keeps using the engine it has now": "Oʻtkazib yuborildi: docker hozirgi dvijokdan foydalanishda davom etadi", + "Skipped: {problem}": "Oʻtkazib yuborildi: {problem}", + "Slow because the VM is out of memory": "VM xotirasi tugagani uchun sekin ishlamoqda", + "Small": "Kichik", + "Smaller": "Kichikroq", + "Snooze ▾": "Kechiktirish ▾", + "Something else on this {host} has it. Give {name} another port.": "Bu {host}dagi boshqa dastur uni band qilgan. {name} uchun boshqa port belgilang.", + "Something went wrong": "Nimadir notoʻgʻri ketdi", + "Soon": "Tez orada", + "Speed": "Tezlik", + "Split down": "Pastga boʻlish", + "Split down ({keys})": "Pastga boʻlish ({keys})", + "Split right": "Oʻngga boʻlish", + "Split right ({keys})": "Oʻngga boʻlish ({keys})", + "Start": "Ishga tushirish", + "Start Kiri": "Kirini ishga tushirish", + "Start Kiri to change its network settings. ({error})": "Tarmoq sozlamalarini oʻzgartirish uchun Kirini ishga tushiring. ({error})", + "Start Kiri to change its registry settings. ({error})": "Reyestr sozlamalarini oʻzgartirish uchun Kirini ishga tushiring. ({error})", + "Start Kiri to change its resources. ({error})": "Resurslarini oʻzgartirish uchun Kirini ishga tushiring. ({error})", + "Start Kiri to change the ports names answer on.": "Nomlar javob beradigan portlarni oʻzgartirish uchun Kirini ishga tushiring.", + "Start Kiri when I sign in (in the tray)": "Tizimga kirganimda Kirini ishga tushirish (tizim tepsisida)", + "Start Kubernetes": "Kubernetesni ishga tushirish", + "Start Linux VM": "Linux VMni ishga tushirish", + "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "Bitta Kiri konteynerida bir tugunli klasterni (k3s) ishga tushirish. Uning API manzili {api} (yoki keyingi boʻsh port), kubectl esa {context} kontekstini oladi, xuddi kiri k8s start buyrugʻidagidek.", + "Start again": "Yana ishga tushirish", + "Start all": "Hammasini ishga tushirish", + "Start engine": "Dvijokni ishga tushirish", + "Start it": "Ishga tushirish", + "Start it to restart it": "Qayta ishga tushirish uchun uni ishga tushiring", + "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "Konteynerlarni ishlatish uchun uni ishga tushiring. U soniyaning bir ulushida ishga tushadi va boʻsh turganda uyquga ketadi.", + "Start it to share it": "Ulashish uchun uni ishga tushiring", + "Start scan": "Skanerlashni boshlash", + "Start the container to run commands in it.": "Unda buyruqlarni bajarish uchun konteynerni ishga tushiring.", + "Start the engine": "Dvijokni ishga tushirish", + "Start {engine} to bring its images over now, or later from Settings → Import.": "Obrazlarini hozir koʻchirib oʻtkazish uchun {engine}ni ishga tushiring yoki buni keyinroq Sozlamalar → Import boʻlimida bajaring.", + "Started": "Ishga tushirildi", + "Started with {name} set": "{name} oʻrnatilgan holda ishga tushirildi", + "Started {name}": "{name} ishga tushirildi", + "Started {name} on {ports}": "{name} ishga tushirildi: {ports}", + "Starting": "Ishga tushirilmoqda", + "Starting Kiri’s engine": "Kiri dvijoki ishga tushirilmoqda", + "Starting Kubernetes…": "Kubernetes ishga tushirilmoqda…", + "Starting the scan": "Skanerlash boshlanmoqda", + "Starting…": "Ishga tushirilmoqda…", + "State": "Holat", + "Status": "Status", + "Step 1 of 5": "1-qadam (jami 5)", + "Step 2 of 5": "2-qadam (jami 5)", + "Step 2 of 5. Nothing else on this PC changes: Kiri sets itself up for your Windows account only.": "2-qadam (jami 5). Bu kompyuterda boshqa hech narsa oʻzgarmaydi: Kiri faqat sizning Windows hisobingiz uchun oʻrnatiladi.", + "Step 3 of 5": "3-qadam (jami 5)", + "Step 4 of 5": "4-qadam (jami 5)", + "Steps": "Qadamlar", + "Stop": "Toʻxtatish", + "Stop Kubernetes?": "Kubernetes toʻxtatilsinmi?", + "Stop Linux VM": "Linux VMni toʻxtatish", + "Stop all": "Hammasini toʻxtatish", + "Stop on {host}": "{host}da toʻxtatish", + "Stop sharing": "Ulashishni toʻxtatish", + "Stop signal": "Toʻxtatish signali", + "Stop {name}": "{name}ni toʻxtatish", + "Stop {name} on {host}?": "{name} {host}da toʻxtatilsinmi?", + "Stopped": "Toʻxtatilgan", + "Stopped {when}": "{when} toʻxtatilgan", + "Stopped {when}, when the {vm} stopped. Start it again whenever you like.": "{vm} toʻxtaganda, {when} toʻxtatilgan. Uni istalgan vaqtda qayta ishga tushiring.", + "Stopped {when}: its memory ran out": "{when} toʻxtatilgan: xotirasi tugadi", + "Stopped {when}: its memory ran out (the VM has {mem})": "{when} toʻxtatilgan: xotirasi tugadi (VMda {mem} bor)", + "Stopped: out of memory": "Toʻxtatilgan: xotira yetmadi", + "Stopping": "Toʻxtatilmoqda", + "Stopping…": "Toʻxtatilmoqda…", + "Stop…": "Toʻxtatish…", + "Storage": "Xotira qurilmasi", + "Strong enough": "Yetarlicha kuchli", + "Subnet": "Quyi tarmoq", + "Suggested": "Tavsiya etilgan", + "Switch and import": "Almashtirish va import qilish", + "Switch and import {n} item": "Almashtirish va {n} ta elementni import qilish", + "Switch and import {n} items": "Almashtirish va {n} ta elementni import qilish", + "Switch back": "Avvalgisiga qaytish", + "Switch to the dark theme": "Qorongʻi mavzuga oʻtish", + "Switch to the light theme": "Yorugʻ mavzuga oʻtish", + "Switch to {app}": "{app}ga oʻtish", + "System": "Tizim", + "System Mono|font": "Tizim monoshrifti", + "System|font": "Tizim shrifti", + "Tab pinned": "Varaq mahkamlandi", + "Tab unpinned": "Varaq mahkamlashdan chiqarildi", + "Tables, the sidebar and headings.": "Jadvallar, yon panel va sarlavhalar.", + "Tag": "Teg", + "Teal": "Firuzarang", + "Tell us how it goes": "Qanday ketayotganini bizga aytib bering", + "Terminal": "Terminal", + "Terminal ({keys})": "Terminal ({keys})", + "Terminated": "Tugatilgan", + "Test build": "Sinov yigʻishi", + "Text size": "Matn oʻlchami", + "Text size {n} px": "Matn oʻlchami {n} px", + "That's a lot to copy and can take a long time; choosing what you need is quicker.": "Bu nusxalash uchun juda koʻp va uzoq vaqt olishi mumkin; keraklisini tanlash tezroq.", + "The 5 newest, and macOS's own crash reports for Kiri from the last 30 days": "Eng yangi 5 tasi hamda macOSning soʻnggi 30 kundagi Kiri nosozlik hisobotlari", + "The API server port must be a number from 1024 to 65535": "API server porti 1024 dan 65535 gacha boʻlgan son boʻlishi kerak", + "The AWS CLI has no profiles yet. Set one up with {cmd}.": "AWS CLIda hali profillar yoʻq. {cmd} buyrugʻi bilan bittasini sozlang.", + "The GitHub CLI stays signed in.": "GitHub CLI tizimda qoladi.", + "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes API serveri. U hech qachon ulashilmaydi: havolaga ega har kim klasterni boshqarishga urinishi mumkin.", + "The Linux VM restarted with the new resources": "Linux VM yangi resurslar bilan qayta ishga tushirildi", + "The VM has {mem}; {free}.": "VMda {mem} bor; {free}.", + "The VM is asleep; it starts with these next time.": "VM uxlamoqda; keyingi safar shu sozlamalar bilan ishga tushadi.", + "The VM's memory is nearly full: {used} of {max}.": "VM xotirasi deyarli toʻla: {used} / {max}.", + "The app on {host} keeps running, and {program} there shows the share as stopped from another computer.": "{host}dagi ilova ishlashda davom etadi, u yerdagi {program} esa ulashish boshqa kompyuterdan toʻxtatilganini koʻrsatadi.", + "The build failed": "Yigʻish muvaffaqiyatsiz tugadi", + "The build was canceled": "Yigʻish bekor qilindi", + "The code goes straight to the AWS CLI; Kiri doesn't keep it.": "Kod toʻgʻridan-toʻgʻri AWS CLIga uzatiladi; Kiri uni saqlamaydi.", + "The container keeps running.": "Konteyner ishlashda davom etadi.", + "The docker command is signed out too.": "docker buyrugʻi ham hisobdan chiqadi.", + "The docker command uses {app}": "docker buyrugʻi {app}dan foydalanadi", + "The docker command uses {engine}. Switch it to {app}": "docker buyrugʻi {engine}dan foydalanadi. Uni {app}ga almashtirish", + "The engine": "Dvijok", + "The engine is running but not answering": "Dvijok ishlamoqda, lekin javob bermayapti", + "The engine is stopped": "Dvijok toʻxtatilgan", + "The engine isn't here: reinstall the kiri package": "Dvijok topilmadi: kiri paketini qayta oʻrnating", + "The engine still runs Kiri {version}": "Dvijokda hali ham Kiri {version} ishlamoqda", + "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Dvijokda hali ham {version} ishlamoqda. Uni qayta ishga tushirish ishlayotgan konteynerlarni toʻxtatadi, qayta ishga tushirish siyosati borlari esa yana ishga tushadi.", + "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "Birinchi skanerlash Grype va uning maʼlumotlar bazasini yuklab oladi, taxminan 230 MB (ochilgandan keyin 3 GB).", + "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Microsoftning WSL roʻyxatidagi toʻliq Ubuntu. Kiri unda ishlaydi, siz uni oʻz Linuxingiz sifatida ham ochishingiz mumkin.", + "The image's own way to start without it.": "Obrazning usiz ishga tushishning oʻz usuli.", + "The kiri share there stops.": "U yerdagi kiri share toʻxtaydi.", + "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "Oyna, dvijok va kiri buyruqlarining oxirgi 300 qatori hamda dvijokning oʻz chiqishi", + "The last {n} seconds": "Oxirgi {n} soniya", + "The link ends when the pod does.": "Havola pod bilan birga tugaydi.", + "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "VM egallashi mumkin boʻlgan eng koʻp miqdor. U xotiradan faqat konteynerlarga kerak boʻlganda foydalanadi, qolganini {os}ga qaytaradi.", + "The name comes from the Igbo word ntakịrị, “small”.": "Nomi igbo tilidagi ntakịrị (“kichik”) soʻzidan olingan.", + "The part that runs your containers, inside {linux}.": "{linux} ichida konteynerlaringizni ishga tushiradigan qism.", + "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "Ushbu {host}dagi API server porti, 1024 dan 65535 gacha (standart 6443). Klaster ishga tushganda u band boʻlsa, keyingi boʻsh port olinadi. Saqlash klasterni qayta ishga tushiradi va {context} kontekstini yangilaydi.", + "The profile {profile} asks for a code from your MFA device {device}.": "{profile} profili {device} MFA qurilmangizdan kod soʻraydi.", + "The profile {profile} asks for a code from your MFA device.": "{profile} profili MFA qurilmangizdan kod soʻraydi.", + "The profile {profile} signs in through AWS IAM Identity Center. Kiri runs {cmd}, which opens AWS's page.": "{profile} profili AWS IAM Identity Center orqali kiradi. Kiri {cmd}ni ishga tushiradi, u AWS sahifasini ochadi.", + "The run before the container's last restart": "Konteyner oxirgi marta qayta ishga tushirilishidan oldingi ishga tushirish", + "The same docker commands you know, talking to Kiri. Each file is checked against its pinned SHA-256.": "Siz biladigan oʻsha docker buyruqlari, faqat Kiri bilan ishlaydi. Har bir fayl qayd etilgan SHA-256 boʻyicha tekshiriladi.", + "The window": "Oyna", + "The {n} packages as CycloneDX JSON, saved to Downloads": "{n} ta paket CycloneDX JSON koʻrinishida, Yuklanmalar jildiga saqlandi", + "The {vm} is asleep: it holds no memory": "{vm} uyqu holatida: xotira egallamaydi", + "Theme": "Mavzu", + "They appear in Images as they arrive.": "Ular kelishi bilan Obrazlar boʻlimida paydo boʻladi.", + "This action left no log lines.": "Bu amal jurnalda hech qanday yozuv qoldirmadi.", + "This build made no image to scan: it failed before exporting, or its output was the cache only.": "Bu yigʻish skanerlash uchun obraz yaratmadi: u eksportdan oldin muvaffaqiyatsiz tugadi yoki natijasi faqat kesh boʻldi.", + "This build made no image: it failed before exporting, or its output was the cache only.": "Bu yigʻish obraz yaratmadi: u eksportdan oldin muvaffaqiyatsiz tugadi yoki natijasi faqat kesh boʻldi.", + "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "Bu yigʻish obrazi Kirida yoʻq, shuning uchun bu yerda skanerlanadigan narsa yoʻq. U boshqa joyga yuborilgan yoki eksport qilingan yoxud keyin oʻchirilgan. Bu yerda skanerlash uchun uni --load bilan yigʻing.", + "This can't be undone.": "Buni ortga qaytarib boʻlmaydi.", + "This closes that tunnel on {host}, from here. The link stops working for everyone.": "Bu {host}dagi oʻsha tunnelni shu yerdan yopadi. Havola hamma uchun ishlamay qoladi.", + "This computer can't use it while it's in Kiri: detach it to get it back.": "U Kirida ekan, bu kompyuter undan foydalana olmaydi: qaytarib olish uchun uni uzing.", + "This file is binary or larger than 256 KB.": "Bu fayl ikkilik yoki 256 KB dan katta.", + "This folder is empty.": "Bu jild boʻsh.", + "This image": "Bu obraz", + "This image needs privileged mode": "Bu obrazga imtiyozli rejim kerak", + "This is Kubernetes. Kiri runs it for you": "Bu Kubernetes. Kiri uni siz uchun ishga tushiradi", + "This lists every link on your account, on any computer.": "Bu yerda hisobingizdagi barcha havolalar, istalgan kompyuterdagi, roʻyxati keltirilgan.", + "This month": "Shu oy", + "This pod's name changes when it restarts, and the link would end.": "Bu podning nomi qayta ishga tushganda oʻzgaradi va havola tugab qoladi.", + "This sign-in's ID: a hash of its token, safe to quote when asking for help": "Bu kirishning ID raqami: tokenining xeshi, yordam soʻraganda bemalol koʻrsatish mumkin", + "This system applies your new access when you sign in again. Kiri opens ready after that.": "Tizim yangi ruxsatlaringizni qayta kirganingizda qoʻllaydi. Shundan soʻng Kiri ishga tayyor holda ochiladi.", + "Time": "Vaqt", + "To make names like {name} work, Kiri adds one small settings file to your Mac ({path}), and changing system settings always needs an administrator. Kiri uses the password only for that, once. It never sees the password: macOS handles it.": "{name} kabi nomlar ishlashi uchun Kiri Macingizga bitta kichik sozlamalar faylini ({path}) qoʻshadi, tizim sozlamalarini oʻzgartirish esa doim administratorni talab qiladi. Kiri paroldan faqat shu uchun, bir marta foydalanadi. U parolni hech qachon koʻrmaydi: uni macOS boshqaradi.", + "Today {time}": "Bugun {time}", + "Token": "Token", + "Token or password": "Token yoki parol", + "Tomorrow": "Ertaga", + "Took": "Davomiyligi", + "Traffic over the last two minutes": "Oxirgi ikki daqiqadagi trafik", + "Traffic served": "Uzatilgan trafik", + "Trust Kiri's certificate so {url} works. macOS asks for your password. The certificate can only vouch for Kiri's own names.": "{url} ishlashi uchun Kiri sertifikatiga ishoning. macOS parolingizni soʻraydi. Sertifikat faqat Kirining oʻz nomlarini tasdiqlay oladi.", + "Try again": "Qayta urinish", + "Turn off engine": "Dvijokni oʻchirib qoʻyish", + "Turn on Kiri's in Settings → Kubernetes instead of starting a copy.": "Nusxasini ishga tushirish oʻrniga Sozlamalar → Kubernetes boʻlimida Kirinikini yoqing.", + "Turn on Kubernetes": "Kubernetesni yoqish", + "Turn on WSL's Windows components": "WSL uchun Windows komponentlarini yoqish", + "Turn security off for local use": "Mahalliy foydalanish uchun xavfsizlikni oʻchirib qoʻyish", + "Type": "Turi", + "Type one, or generate it": "Kiriting yoki yarating", + "Type to search Docker Hub, or paste a full reference such as {a} or {b} to pull exactly that.": "Docker Hubda qidirish uchun yozing yoki aynan oʻshani yuklab olish uchun {a} yoki {b} kabi toʻliq havolani qoʻying.", + "USB": "USB", + "USB device": "USB qurilma", + "USB needs usbipd-win": "USB uchun usbipd-win kerak", + "USB passthrough is in beta.": "USB uzatish beta holatida.", + "USB passthrough is new: tell us how it works with your devices": "USB uzatish yangi: qurilmalaringiz bilan qanday ishlashini bizga aytib bering", + "Ubuntu is already on this PC, so choosing it downloads nothing.": "Ubuntu bu kompyuterda allaqachon bor, shuning uchun uni tanlash hech narsa yuklab olmaydi.", + "Undo": "Ortga qaytarish", + "Undo brings it back": "Ortga qaytarish uni tiklaydi", + "Undo brings them back": "Ortga qaytarish ularni tiklaydi", + "Unknown": "Nomaʼlum", + "Unpack Kiri Linux": "Kiri Linuxni ochish", + "Unpack it into WSL": "WSLga ochish", + "Unpin tab": "Varaqni boʻshatish", + "Untagged": "Tegsiz", + "Untagged; another tag still uses it": "Teg olib tashlandi; uni hali boshqa teg ishlatadi", + "Unused": "Ishlatilmagan", + "Up to date": "Eng soʻnggi versiya", + "Up {time}": "{time}dan beri ishlamoqda", + "Up {time} (Paused)": "{time}dan beri ishlamoqda (pauzada)", + "Updating": "Yangilanmoqda", + "Updating the vulnerability database (about 200 MB the first time)": "Zaifliklar bazasi yangilanmoqda (birinchi marta taxminan 200 MB)", + "Upper and lower case, a digit and a symbol, 8 or more": "Katta va kichik harflar, raqam va belgi, kamida 8 ta", + "Use AWS profile": "AWS profilidan foydalanish", + "Use Kiri": "Kiridan foydalanish", + "Use Kiri Linux instead": "Oʻrniga Kiri Linuxdan foydalanish", + "Use Kiri's Kubernetes": "Kiri Kubernetesidan foydalanish", + "Use Save to Downloads to open it.": "Uni ochish uchun “Yuklanmalarga saqlash”dan foydalaning.", + "Use Show in Finder to open it.": "Uni ochish uchun “Finderda koʻrsatish”dan foydalaning.", + "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Docker Hub shaxsiy kirish tokenidan foydalaning (Account settings → Personal access tokens).", + "Use a GitHub personal access token (classic) with the {scope} scope.": "{scope} doirasiga ega GitHub shaxsiy kirish tokenidan (classic) foydalaning.", + "Use a personal or deploy token with the {scope} scope.": "{scope} doirasiga ega shaxsiy yoki joylashtirish tokenidan foydalaning.", + "Use another port": "Boshqa portdan foydalanish", + "Use the Ubuntu already here": "Mavjud Ubuntudan foydalanish", + "Use this profile": "Ushbu profildan foydalanish", + "Use your AWS profile": "AWS profilingizdan foydalaning", + "Use your password, or a robot account's name and token.": "Parolingizdan yoki robot hisobining nomi va tokenidan foydalaning.", + "Use {app} for docker?": "docker uchun {app}dan foydalanilsinmi?", + "Use {name} instead": "Oʻrniga {name}dan foydalanish", + "Used by": "Foydalanuvchilar", + "User": "Foydalanuvchi", + "Username": "Foydalanuvchi nomi", + "Using the Ubuntu already on this PC: nothing to download.": "Ushbu kompyuterdagi mavjud Ubuntudan foydalanilmoqda: hech narsa yuklab olinmaydi.", + "VPNs need no setting: container traffic leaves through macOS.": "VPN uchun sozlash shart emas: konteyner trafigi macOS orqali chiqadi.", + "Value": "Qiymat", + "Version {version}": "Versiya {version}", + "Versions, macOS, whether the engine runs, how many containers and images": "Versiyalar, macOS, dvijok ishlayotgani, konteyner va obrazlar soni", + "View": "Koʻrinish", + "View container": "Konteynerni koʻrish", + "Visitors": "Tashrif buyuruvchilar", + "Visitors' browsers see a short Kiri Cloud notice page first, then your app.": "Tashrif buyuruvchilar brauzerida avval qisqa Kiri Cloud ogohlantirish sahifasi, soʻng ilovangiz ochiladi.", + "Volumes": "Tomlar", + "Vulnerabilities": "Zaifliklar", + "Vulnerability": "Zaiflik", + "WSL restarted with the new resources": "WSL yangi resurslar bilan qayta ishga tushirildi", + "WSL, downloaded from Microsoft": "WSL, Microsoftdan yuklab olinadi", + "Waiting": "Kutilmoqda", + "Waiting for GitHub…": "GitHub kutilmoqda…", + "Waiting for Windows' approval": "Windows tasdigʻi kutilmoqda", + "Waiting for the API server…": "API server kutilmoqda…", + "Waiting for the first sample…": "Birinchi namuna kutilmoqda…", + "Waiting for the first visitor…": "Birinchi tashrif buyuruvchi kutilmoqda…", + "Waiting for you to approve {code} in the browser…": "Brauzerda {code} kodini tasdiqlashingiz kutilmoqda…", + "Waiting for you to sign in in the browser…": "Brauzerda kirishingiz kutilmoqda…", + "Warn": "Ogohlantirish", + "Warnings": "Ogohlantirishlar", + "Warnings and errors": "Ogohlantirish va xatolar", + "We get the file below, redacted, and you get an ID to quote when you write to us. If you're signed in to Kiri Cloud, it says it's from you, so we can reply.": "Biz quyidagi faylni maxfiy maʼlumotlari olib tashlangan holda olamiz, siz esa bizga yozganingizda koʻrsatish uchun ID olasiz. Agar Kiri Cloudga kirgan boʻlsangiz, unda sizdan ekani koʻrsatiladi, shunda javob bera olamiz.", + "Website": "Veb-sayt", + "Welcome to Kiri": "Kiriga xush kelibsiz", + "What Kiri's window uses on this {host}, not counting the {vm}:": "Kiri oynasi ushbu {host}da ishlatadigan resurslar ({vm} hisobga olinmagan):", + "What is WSL?": "WSL nima?", + "What to import": "Nimani import qilish", + "What's new": "Yangiliklar", + "What's new in Kiri {version}": "Kiri {version} yangiliklari", + "What's new in {version}": "{version} yangiliklari", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Kirining biror qismi ishdan chiqqanda, stek izi va undan oldingi oxirgi 200 ta jurnal yozuvi Kiri va tizim versiyalari, kompyuter modeli hamda ushbu oʻrnatish uchun tasodifiy ID bilan birga Kiri Cloudga yuboriladi. Kiri Cloud hisobingiz va konteynerlaringiz ichidagi hech narsa hech qachon yuborilmaydi. Uy jildingiz, obraz va konteyner nomlari, tokenlar va parollar olib tashlanadi.", + "When the pod restarts, it gets a new name and the link ends.": "Pod qayta ishga tushganda yangi nom oladi va havola amal qilmay qoladi.", + "Where should your containers run?": "Konteynerlaringiz qayerda ishlasin?", + "Which steps": "Qaysi qadamlar", + "Window": "Oyna", + "Windows Subsystem for Linux": "Windows Subsystem for Linux", + "Windows asks for an administrator's approval once.": "Windows bir marta administrator tasdigʻini soʻraydi.", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows USB qurilmalarni Microsoft tavsiya etgan usbipd-win vositasi orqali Kiri konteynerlari ishlaydigan WSLga uzatadi.", + "Windows is asking": "Windows soʻramoqda", + "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows ishga tushish vaqtida Virtual Machine Platformni yoqadi. Shundan soʻng Kiri oʻzi qayta ochiladi va 2-qadamdan davom etadi. Avval ishingizni saqlang.", + "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "Bu tugagach, Windowsni bir marta qayta ishga tushirish kerak boʻladi. Kiri qayta ishga tushirishdan oldin soʻraydi, shunda avval ishingizni saqlashingiz mumkin.", + "With a fix": "Tuzatishi bor", + "Working dir": "Ishchi jild", + "Yesterday {time}": "Kecha {time}", + "You already have {engine}. Which should build your images?": "Sizda allaqachon {engine} bor. Obrazlaringizni qaysi biri yigʻsin?", + "You can change it later in Settings → Appearance.": "Buni keyinroq Sozlamalar → Koʻrinish boʻlimida oʻzgartirishingiz mumkin.", + "You can change this later in Settings → Domains.": "Buni keyinroq Sozlamalar → Domenlar boʻlimida oʻzgartirishingiz mumkin.", + "You can keep working while they copy.": "Ular nusxalanayotganda ishlashda davom etishingiz mumkin.", + "You can pull it again later.": "Uni keyinroq yana yuklab olishingiz mumkin.", + "You can still pull the name as typed.": "Nomni yozilganidek yuklab olishingiz baribir mumkin.", + "You can switch any time in Settings → Builds.": "Istalgan vaqtda Sozlamalar → Yigʻishlar boʻlimida almashtirishingiz mumkin.", + "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "Sizda {ref} bor, {when}. Yangilanishlarni olish uchun qayta yuklab oling; faqat oʻzgargan qatlamlar yuklanadi.", + "You have {ref}. Pull again to get any updates; only changed layers download.": "Sizda {ref} bor. Yangilanishlarni olish uchun qayta yuklab oling; faqat oʻzgargan qatlamlar yuklanadi.", + "You have {tags}": "Sizda bor: {tags}", + "You have {version}": "Sizda {version} versiyasi", + "You have {version}.": "Sizda {version} versiyasi.", + "You sign in on github.com. Kiri gets a token that can only read packages.": "Siz github.com saytida kirasiz. Kiri faqat paketlarni oʻqiy oladigan token oladi.", + "You're sharing {name}": "Siz {name}ni ulashmoqdasiz", + "Your AWS sign-in expired": "AWS seansingiz muddati tugadi", + "Your account can use Kiri": "Hisobingiz Kiridan foydalana oladi", + "Your containers keep running while it downloads.": "Yuklab olinayotganda konteynerlaringiz ishlashda davom etadi.", + "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "Biror narsa yozilishidan oldin uy jildingiz yoʻli, tokenlar, parollar va boshqa maxfiy maʼlumotlar olib tashlanadi.", + "Your link for {name} is live.": "{name} uchun havolangiz faol.", + "Your other Docker": "Boshqa Dockeringiz", + "Your own registry…": "Oʻz reyestringiz…", + "Your password and two-step code go to Docker, not Kiri.": "Parolingiz va ikki bosqichli kod Kiriga emas, Dockerga yuboriladi.", + "Your password, or an access token if the registry offers them.": "Parolingiz yoki, reyestr taklif qilsa, kirish tokeni.", + "Your plan allows {limit} tunnels at once, and all {limit} are in use: {slots}.": "Tarifingiz bir vaqtda {limit} ta tunnelga ruxsat beradi va {limit} tasining hammasi band: {slots}.", + "Your plan allows {limit} tunnels at once. In use: {slots}.": "Tarifingiz bir vaqtda {limit} ta tunnelga ruxsat beradi. Band: {slots}.", + "Your plan allows {limit} tunnels at once; close one first.": "Tarifingiz bir vaqtda {limit} ta tunnelga ruxsat beradi; avval bittasini yoping.", + "Your plan allows {n} at once": "Tarifingiz bir vaqtda {n} taga ruxsat beradi", + "Your test container said hello. Open a new terminal and try it yourself:": "Sinov konteyneringiz salom berdi. Yangi terminal oching va oʻzingiz sinab koʻring:", + "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "{engine} obraz va konteynerlaringiz {engine}da qoladi. Ularni koʻchirib oʻtkazmaguningizcha {app} ularni koʻrmaydi.", + "Your {engine} images stay there. Bring them over any time from Settings → Import.": "{engine} obrazlaringiz oʻsha yerda qoladi. Ularni istalgan vaqtda Sozlamalar → Import orqali koʻchirib oʻtkazing.", + "Yours": "Sizniki", + "Zoom In": "Kattalashtirish", + "Zoom Out": "Kichraytirish", + "a container": "konteyner", + "a free port": "boʻsh port", + "a password": "parol", + "a root password": "root paroli", + "a saved token": "saqlangan token", + "about {min} min left": "taxminan {min} daqiqa qoldi", + "about {n} min left": "taxminan {n} daqiqa qoldi", + "about {n} s left": "taxminan {n} s qoldi", + "about {sec} s left": "taxminan {sec} s qoldi", + "about {time} left": "taxminan {time} qoldi", + "address": "manzil", + "an admin password": "administrator paroli", + "and was stopped. The VM has {mem}.": "va toʻxtatildi. VMda {mem} bor.", + "and {n} more…": "va yana {n} ta…", + "anonymous": "anonim", + "another computer": "boshqa kompyuter", + "answered in {ms} ms": "{ms} ms da javob berdi", + "approved": "tasdiqlandi", + "auto": "avto", + "back": "orqaga", + "build ID": "yigʻish ID", + "builds": "yigʻishlar", + "cached": "keshlangan", + "checked {ago}": "tekshirildi: {ago}", + "choose tag": "tegni tanlang", + "close": "yopish", + "compose lines": "compose qatorlari", + "compressed": "siqilgan", + "computer": "kompyuter", + "container ID": "konteyner ID", + "containers": "konteynerlar", + "couldn't pull alpine: {why}": "alpine yuklab olinmadi: {why}", + "created {date}": "yaratilgan: {date}", + "database from {date}": "{date} sanali baza", + "digest": "digest", + "disk": "disk", + "disk read {read} · write {write}": "disk oʻqish {read} · yozish {write}", + "docker build on Kiri": "Kirida docker build", + "docker build runs on Kiri's builder": "docker build Kiri yigʻuvchisida ishlaydi", + "docker flag": "docker parametri", + "docker now uses {app}": "docker endi {app}dan foydalanadi", + "docker run, from any terminal": "docker run — istalgan terminaldan", + "docker talks to another engine now": "docker endi boshqa dvijok bilan ishlaydi", + "docker uses Kiri": "docker Kiridan foydalanadi", + "docker, Compose and Docker-socket tools reach Kiri": "docker, Compose va Docker-socket vositalari Kiriga ulanadi", + "docker, docker compose and docker build use Kiri in every new terminal. Another Docker was found on this PC; leave this off to keep using it as the default.": "docker, docker compose va docker build har bir yangi terminalda Kiridan foydalanadi. Bu kompyuterda boshqa Docker topildi; uni standart sifatida ishlatishda davom etish uchun buni oʻchiq qoldiring.", + "docker, docker compose and docker build use Kiri in every new terminal. No other Docker was found on this PC.": "docker, docker compose va docker build har bir yangi terminalda Kiridan foydalanadi. Bu kompyuterda boshqa Docker topilmadi.", + "doesn't update itself": "oʻzini oʻzi yangilamaydi", + "done": "tayyor", + "downloading": "yuklab olinmoqda", + "failed": "muvaffaqiyatsiz", + "failed builds": "muvaffaqiyatsiz yigʻishlar", + "failed containers": "muvaffaqiyatsiz konteynerlar", + "for that user": "oʻsha foydalanuvchi uchun", + "from any page": "istalgan sahifadan", + "from the container's log": "konteyner jurnalidan", + "from the engine, when it tried to start it": "dvijokdan, uni ishga tushirishga uringanda", + "from the engine, when it tried to start {name}": "dvijokdan, {name}ni ishga tushirishga uringanda", + "idle": "boʻsh", + "idle · nobody is visiting": "boʻsh · hech kim kirmayapti", + "image ID": "obraz ID", + "images": "obrazlar", + "in": "kiruvchi", + "in config.json": "config.json faylida", + "in progress": "bajarilmoqda", + "in {time}": "{time} ichida", + "input events": "kiritish hodisalari", + "installed": "oʻrnatilgan", + "its build cache": "uning yigʻish keshi", + "just now": "hozirgina", + "kept in {v}": "{v} ichida saqlanadi", + "kernel {version}": "yadro {version}", + "kiri.service and the engine are in place": "kiri.service va dvijok joyida", + "kubectl context": "kubectl konteksti", + "latest": "eng soʻnggi", + "layers": "qatlamlar", + "line {n}": "{n}-qator", + "links open in this app": "havolalar shu ilovada ochiladi", + "live": "jonli", + "live {time}": "jonli {time}", + "macOS will ask for an administrator password next.": "Keyin macOS administrator parolini soʻraydi.", + "made {ago}": "{ago} yaratilgan", + "move": "koʻchirish", + "needs privileged mode": "imtiyozli rejim kerak", + "needs {name}": "{name} kerak", + "network interface": "tarmoq interfeysi", + "networks": "tarmoqlar", + "no layer: this line only changes the image's settings": "qatlam yoʻq: bu qator faqat obraz sozlamalarini oʻzgartiradi", + "no monthly cap": "oylik cheklov yoʻq", + "no speed limit": "tezlik cheklovi yoʻq", + "none": "yoʻq", + "not in use": "ishlatilmayapti", + "not running": "ishlamayapti", + "now": "hozir", + "of all {cpus} CPUs · peak {peak}": "jami {cpus} ta CPU dan · choʻqqi {peak}", + "of {cap}": "/ {cap}", + "of {limit} · peak {peak}": "/ {limit} · choʻqqi {peak}", + "on other computers": "boshqa kompyuterlarda", + "on {date} at {time}": "{date}, soat {time}", + "or hold {mod} and scroll": "yoki {mod} tugmasini bosib turib aylantiring", + "out": "chiquvchi", + "owner/image on {registry}, such as {example}": "{registry} dagi egasi/obraz, masalan, {example}", + "peak {rate}": "choʻqqi {rate}", + "pinned digest": "qadalgan digest", + "pods": "podlar", + "port {port}": "port {port}", + "port {port} is in use": "{port} porti band", + "pull": "yuklab olish", + "pulled {when}": "{when} yuklab olingan", + "pulling alpine": "alpine yuklab olinmoqda", + "pulls now": "hozir yuklab oladi", + "raw HID": "xom HID", + "raw USB": "xom USB", + "received from visitors": "tashrifchilardan qabul qilingan", + "reconnected {n}×": "{n}× qayta ulandi", + "report ID": "hisobot ID", + "running on other computers on your account": "hisobingizdagi boshqa kompyuterlarda ishlamoqda", + "running…": "ishlamoqda…", + "same as the user": "foydalanuvchi bilan bir xil", + "saved with {v}": "{v} bilan saqlangan", + "sent to visitors": "tashrifchilarga yuborilgan", + "serial port": "ketma-ket port", + "services": "xizmatlar", + "sets {var}, for local use only.": "{var}ni oʻrnatadi, faqat mahalliy foydalanish uchun.", + "sets {var}, so it runs without a login or TLS.": "{var}ni oʻrnatadi, shuning uchun u login yoki TLSsiz ishlaydi.", + "sets {var}; it prints the password once in its log.": "{var}ni oʻrnatadi; u parolni jurnaliga bir marta chiqaradi.", + "settings": "sozlamalar", + "sign in to {host}": "{host}ga kirish", + "skipped": "oʻtkazib yuborildi", + "sound card": "ovoz kartasi", + "tag": "teg", + "the image's settings": "obraz sozlamalari", + "the last error lines in the container's log": "konteyner jurnalidagi soʻnggi xato qatorlari", + "the last lines in the container's log": "konteyner jurnalidagi soʻnggi qatorlar", + "the link didn't open": "havola ochilmadi", + "the only web port": "yagona veb-port", + "the port the app in it listens on": "undagi ilova tinglaydigan port", + "the saved sign-in": "saqlangan kirish maʼlumotlari", + "the test container did not run": "sinov konteyneri ishlamadi", + "the test container did not run: {why}": "sinov konteyneri ishlamadi: {why}", + "this Mac": "bu Mac", + "this PC": "bu kompyuter", + "this build": "bu yigʻish", + "this image": "bu obraz", + "to do": "bajarilishi kerak", + "today at {time}": "bugun soat {time}", + "total ↓ {rx} · ↑ {tx}": "jami ↓ {rx} · ↑ {tx}", + "tunnels in use": "ishlatilayotgan tunnellar", + "untagged": "tegsiz", + "untagged images": "tegsiz obrazlar", + "up": "ishlamoqda", + "up to {size}": "{size} gacha", + "up {time}": "{time} dan beri ishlamoqda", + "usbipd-win is installed": "usbipd-win oʻrnatilgan", + "used by {names}": "{names} foydalanmoqda", + "value": "qiymat", + "video": "video", + "volumes": "tomlar", + "when the VM's {mem} ran out.": "VM ning {mem} xotirasi tugaganda.", + "yesterday": "kecha", + "yesterday at {time}": "kecha soat {time}", + "you": "siz", + "your account": "hisobingiz", + "your other Docker": "boshqa Dockeringiz", + "{all} lines": "{all} qator", + "{app} doesn't update itself: rebuild it with cargo xtask app-dev": "{app} oʻzini oʻzi yangilamaydi: uni cargo xtask app-dev bilan qayta yigʻing", + "{app} needs a password to start": "{app}ni ishga tushirish uchun parol kerak", + "{app} needs an admin password to start": "{app}ni ishga tushirish uchun administrator paroli kerak", + "{app}: its own engine, containers and settings": "{app}: oʻz dvijogi, konteynerlari va sozlamalari", + "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "docker qaysi dvijokdan foydalanmasin, {build} va {compose} Kirida ishlaydi va obrazlar Kirida boʻladi.", + "{build} and {compose} run on Kiri, and the images are in Kiri. {engine} won't see them; run them with Kiri.": "{build} va {compose} Kirida ishlaydi va obrazlar Kirida boʻladi. {engine} ularni koʻrmaydi; ularni Kiri bilan ishga tushiring.", + "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "{build} docker qayerga yoʻnaltirilgan boʻlsa, oʻsha yerda yigʻadi, shuning uchun {engine} yigʻishlari {engine} ichida qoladi. docker Kiridan foydalanganda yigʻishlar Kirida bajariladi.", + "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "{build} docker qayerga yoʻnaltirilgan boʻlsa, oʻsha yerda yigʻadi. docker Kiridan foydalanganda yigʻishlar Kirida bajariladi.", + "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} har doim Kirida yigʻadi. Almashtirish darhol, allaqachon ochiq terminallarda ham kuchga kiradi. Dockerga qaytish docker yigʻish sozlamalarini Kiri oʻzgartirishidan oldingi holatiga qaytaradi.", + "{docker}, {compose} and your tools run on {app} from now on.": "Bundan buyon {docker}, {compose} va vositalaringiz {app}da ishlaydi.", + "{done} of {total}": "{done} / {total}", + "{engine} doesn't see them.": "{engine} ularni koʻrmaydi.", + "{file} ({i} of {n})": "{file} ({i} / {n})", + "{free} free of {total}": "{total} dan {free} boʻsh", + "{got} of {total}": "{got} / {total}", + "{got} of {total} MB": "{got} / {total} MB", + "{host} isn't searchable from here, so Kiri pulls the reference as typed.": "{host} da bu yerdan qidirib boʻlmaydi, shuning uchun Kiri havolani yozilganidek yuklab oladi.", + "{host} port {q}{port}{q} is not a port number (1–65535).": "{host} porti {q}{port}{q} port raqami emas (1–65535).", + "{host} wants a sign-in for {path}, and {user} can't pull it.": "{host} {path} uchun kirishni talab qiladi va {user} uni yuklab ololmaydi.", + "{host} wants a sign-in for {path}.": "{host} {path} uchun kirishni talab qiladi.", + "{h} h": "{h} soat", + "{h} h {m} min": "{h} soat {m} daq", + "{image} is a whole Kubernetes cluster in a container.": "{image} — bitta konteynerdagi toʻliq Kubernetes klasteri.", + "{image} needs {what} to start": "{image}ni ishga tushirish uchun {what} kerak", + "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s} — Kirining Kubernetes klasteri. Uni oʻchirish Kubernetesni oʻchirib qoʻyadi. Klaster maʼlumotlari {k8s} tomida qoladi; Sozlamalar → Kubernetes boʻlimidagi “Klasterni oʻchirish” hammasini oʻchiradi.", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} — Kirining Kubernetes klasteri. Uni toʻxtatish Kubernetesni oʻchirib qoʻyadi va u qayta ishga tushmaguncha podlari toʻxtaydi.", + "{kind} names are off: port {port} is in use. Pick another.": "{kind} nomlari oʻchiq: {port} porti band. Boshqasini tanlang.", + "{kind} names are paused: a container has port {port}.": "{kind} nomlari pauzada: {port} portini konteyner egallagan.", + "{label}, last minute": "{label}, soʻnggi daqiqa", + "{list} and {last}": "{list} va {last}", + "{list} are running from this image. Stop them first, then remove the image.": "{list} shu obrazdan ishlamoqda. Avval ularni toʻxtating, soʻng obrazni oʻchiring.", + "{list} is running from this image. Stop it first, then remove the image.": "{list} shu obrazdan ishlamoqda. Avval uni toʻxtating, soʻng obrazni oʻchiring.", + "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "{list} shu obrazdan yaratilgan va usiz qayta ishga tusha olmaydi, shuning uchun u ham fayllari bilan birga oʻchiriladi. Tomlar qoladi.", + "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "{list} shu obrazdan yaratilgan va usiz qayta ishga tusha olmaydi, shuning uchun ular ham fayllari bilan birga oʻchiriladi. Tomlar qoladi.", + "{list}, and {last}": "{list} va {last}", + "{live} for {time}": "{time} davomida {live}", + "{live} live, {starting} starting": "{live} ta faol, {starting} ta ishga tushirilmoqda", + "{local} names and HTTPS aren't on Linux yet.": "{local} nomlari va HTTPS hozircha Linuxda mavjud emas.", + "{ms} average": "oʻrtacha {ms}", + "{m} min": "{m} daq", + "{m} of the {n} picked": "tanlangan {n} tadan {m} tasi", + "{m} of the {n} picked can't be deleted and stay.": "Tanlangan {n} tadan {m} tasini oʻchirib boʻlmaydi, ular qoladi.", + "{names} on {host}": "{host}dagi {names}", + "{name} didn't start": "{name} ishga tushmadi", + "{name} has no tag {tag}.": "{name} uchun {tag} tegi yoʻq.", + "{name} has the new environment": "{name} yangi muhitga ega", + "{name} is in Kiri": "{name} Kirida", + "{name} is in use": "{name} band", + "{name} is listening on {ports}": "{name} tinglayotgan portlar: {ports}", + "{name} is shared": "{name} ulashilgan", + "{name} is shared by {who}": "{name}ni {who} ulashgan", + "{name} is still used by the container {container}. Remove the container first.": "{name} hali ham {container} konteyneri tomonidan ishlatilmoqda. Avval konteynerni oʻchiring.", + "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} oʻzgartirilmaydi: obrazlar nusxalanadi, tomlar esa vaqtinchalik, faqat oʻqish uchun moʻljallangan yordamchi orqali oʻqiladi va u keyin oʻchiriladi. Konteynerlar toʻxtatilgan holda koʻchiriladi.", + "{name} isn't listening on a port yet, so there's nothing to share. Try again once it's up.": "{name} hali hech bir portni tinglamayapti, shuning uchun ulashadigan narsa yoʻq. U ishga tushgach, qayta urinib koʻring.", + "{name} isn't running. Start it to import from it; it doesn't need to stay open afterwards.": "{name} ishlamayapti. Undan import qilish uchun uni ishga tushiring; keyin u ochiq qolishi shart emas.", + "{name} needs {var} to start": "{name} ishga tushishi uchun {var} kerak", + "{name} ran and finished": "{name} ishladi va yakunlandi", + "{name} ran out of memory": "{name} uchun xotira yetmadi", + "{name} restarted with the new environment": "{name} yangi muhit bilan qayta ishga tushirildi", + "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} oʻz holicha qoladi: Kiri faqat nusxa oladi. Konteynerlar toʻxtatilgan holda koʻchiriladi.", + "{name} stays: Kubernetes is turned off or deleted in Settings → Kubernetes.": "{name} qoladi: Kubernetes Sozlamalar → Kubernetes boʻlimida oʻchirib qoʻyiladi yoki oʻchiriladi.", + "{name} stopped": "{name} toʻxtadi", + "{name} stopped after {n} s": "{name} {n} s oʻtib toʻxtadi", + "{name} stopped after {n} second": "{name} {n} soniya oʻtib toʻxtadi", + "{name} stopped after {n} seconds": "{name} {n} soniya oʻtib toʻxtadi", + "{name} stopped: {why}": "{name} toʻxtadi: {why}", + "{n} CPU": "{n} CPU", + "{n} CPUs": "{n} CPU", + "{n} added": "{n} ta qoʻshildi", + "{n} cached": "{n} ta keshdan", + "{n} change": "{n} ta oʻzgarish", + "{n} changed": "{n} ta oʻzgartirildi", + "{n} changes": "{n} ta oʻzgarish", + "{n} container": "{n} konteyner", + "{n} containers": "{n} konteyner", + "{n} d ago": "{n} kun oldin", + "{n} days ago": "{n} kun oldin", + "{n} device": "{n} qurilma", + "{n} devices": "{n} qurilma", + "{n} error": "{n} xato", + "{n} errors": "{n} xato", + "{n} external": "{n} ta tashqi", + "{n} failed container": "{n} muvaffaqiyatsiz konteyner", + "{n} failed containers": "{n} muvaffaqiyatsiz konteyner", + "{n} from {what}": "{what}dan {n} ta", + "{n} h ago": "{n} soat oldin", + "{n} image": "{n} obraz", + "{n} image, {size}.": "{n} obraz, {size}.", + "{n} image.": "{n} obraz.", + "{n} images": "{n} obraz", + "{n} images, {size}.": "{n} obraz, {size}.", + "{n} images.": "{n} obraz.", + "{n} in Kiri": "Kirida {n} ta", + "{n} item isn't in Kiri yet. Pick what to copy over.": "{n} ta element hali Kirida yoʻq. Nimani koʻchirishni tanlang.", + "{n} items aren't in Kiri yet. Pick what to copy over.": "{n} ta element hali Kirida yoʻq. Nimani koʻchirishni tanlang.", + "{n} layer": "{n} qatlam", + "{n} layers": "{n} qatlam", + "{n} line": "{n} qator", + "{n} lines": "{n} qator", + "{n} live": "{n} ta faol", + "{n} log line": "{n} jurnal yozuvi", + "{n} log line from the {parts}": "{parts}dan {n} jurnal yozuvi", + "{n} log lines": "{n} jurnal yozuvi", + "{n} log lines from the {parts}": "{parts}dan {n} jurnal yozuvi", + "{n} min ago": "{n} daq oldin", + "{n} of this image, newest first": "bu obraz boʻyicha {n} ta, eng yangilari avval", + "{n} of {limit} tunnels in use": "{limit} ta tunneldan {n} tasi ishlatilmoqda", + "{n} of {total}": "{n} / {total}", + "{n} of {total} running": "{total} tadan {n} tasi ishlamoqda", + "{n} on {where}": "{where}: {n}", + "{n} optional": "{n} ta ixtiyoriy", + "{n} processes": "{n} jarayon", + "{n} removed": "{n} ta oʻchirildi", + "{n} request": "{n} soʻrov", + "{n} requests": "{n} soʻrov", + "{n} requests · {size} served": "{n} soʻrov · {size} uzatildi", + "{n} result": "{n} natija", + "{n} results": "{n} natija", + "{n} running container": "{n} ishlayotgan konteyner", + "{n} running containers": "{n} ishlayotgan konteyner", + "{n} selected": "{n} ta tanlandi", + "{n} shared": "{n} ta ulashilgan", + "{n} shared · {where}": "{n} ta ulashilgan · {where}", + "{n} shared, on {where}": "{n} ta ulashilgan, {where}", + "{n} shared, {where}": "{n} ta ulashilgan, {where}", + "{n} shown": "{n} ta koʻrsatilgan", + "{n} stopped container": "{n} toʻxtatilgan konteyner", + "{n} stopped containers": "{n} toʻxtatilgan konteyner", + "{n} total": "jami {n}", + "{n} variable": "{n} oʻzgaruvchi", + "{n} variables": "{n} oʻzgaruvchi", + "{n} volume": "{n} tom", + "{n} volumes": "{n} tom", + "{n} vulnerabilities in {packages} packages": "{packages} ta paketda {n} zaiflik", + "{n} vulnerability in {packages} packages": "{packages} ta paketda {n} zaiflik", + "{n} with a fix": "{n} tasida tuzatish bor", + "{n} {noun}": "{n} {noun}", + "{n}s ago": "{n} s oldin", + "{os} settings": "{os} sozlamalari", + "{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.": "{os} avtomatik proksi sozlash (PAC) faylidan foydalanadi, Kiri esa unga amal qila olmaydi. Maxsus variantini tanlang va proksini kiriting.", + "{owner} runs this pod": "Bu podni {owner} ishga tushiradi", + "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}. Obrazlar yoki Tomlar boʻlimida koʻrsatilmaydi: bu docker build ichki mexanizmi.", + "{path} comes first on your PATH, so terminals run it instead of this Kiri. If it's an older Kiri, remove it: rm {path}": "{path} PATHda birinchi turadi, shuning uchun terminallar bu Kiri oʻrniga uni ishga tushiradi. Agar bu eski Kiri boʻlsa, uni oʻchiring: rm {path}", + "{pct}% of this month's cap": "bu oylik limitning {pct}%", + "{ports} aren't web ports, so they aren't listed.": "{ports} veb-portlar emas, shuning uchun ular roʻyxatda yoʻq.", + "{ports} isn't a web port, so it isn't listed.": "{ports} veb-port emas, shuning uchun u roʻyxatda yoʻq.", + "{program} on {host}": "{host}dagi {program}", + "{q}{name}{q} can't be a name: names have no spaces or {q}={q}.": "{q}{name}{q} nom boʻla olmaydi: nomlarda boʻsh joy yoki {q}={q} boʻlmaydi.", + "{rate} limit": "{rate} cheklov", + "{rate}/s limit": "{rate}/s cheklov", + "{ready} containers": "{ready} konteyner", + "{running} of {all} running": "{all} tadan {running} tasi ishlamoqda", + "{running} running · {total}": "{running} tasi ishlamoqda · {total}", + "{showing} of {all} lines": "{all} qatordan {showing} tasi", + "{size} MB in {secs} s": "{size} MB, {secs} s ichida", + "{size} MB · already here": "{size} MB · allaqachon mavjud", + "{size} is Ubuntu's download today.": "Hozir Ubuntuni yuklab olish hajmi {size}.", + "{size} left": "{size} qoldi", + "{size} left this month": "bu oy {size} qoldi", + "{size} received": "{size} qabul qilindi", + "{size} served": "{size} uzatildi", + "{s} s": "{s} s", + "{text} with an error.": "{text} xato bilan.", + "{time} ago": "{time} oldin", + "{time} ago, when the VM's {mem} ran out.": "{time} oldin, VMning {mem} xotirasi tugaganda.", + "{used} of {total}": "{used} / {total}", + "{user} can run containers without sudo": "{user} konteynerlarni sudo ishlatmasdan ishga tushira oladi", + "{user}'s sign-in is forgotten on this computer.": "{user} uchun kirish maʼlumotlari bu kompyuterda unutiladi.", + "{var} sets the {kind} port, so it can't be changed here.": "{var} {kind} portini belgilaydi, shuning uchun uni bu yerda oʻzgartirib boʻlmaydi.", + "{version} available": "{version} versiyasi mavjud", + "{version} ready": "{version} versiyasi tayyor", + "{vm} off": "{vm} oʻchiq", + "{vm} running": "{vm} ishlamoqda", + "{what}?": "{what}?", + "{who} has it. Give {name} another port on this {host}, or stop {holder} first.": "U {who} tomonidan band. {name} uchun bu {host}da boshqa port belgilang yoki avval {holder}ni toʻxtating.", + "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who} {when} toʻxtadi.{more} Hisobot uni tuzatishimizga yordam beradi: stek izi va undan oldingi soʻnggi 200 ta jurnal yozuvi, uy jildingiz va tokenlar yashirilgan holda.", + "{who} stopped {when}.{more} Crash reports are sent automatically, so this one goes to Kiri too.": "{who} {when} toʻxtadi.{more} Nosozlik hisobotlari avtomatik yuboriladi, shuning uchun bu hisobot ham Kiriga yuboriladi.", + "{why}. Give the VM more memory in Settings → Resources": "{why}. Sozlamalar → Resurslar boʻlimida VMga koʻproq xotira ajrating", + "{zout} smaller · {zin} bigger · {z0} reset": "{zout} kichraytirish · {zin} kattalashtirish · {z0} asl holat", + "· the newest 500 · up to 15 MB a part is kept": "· eng yangi 500 ta · har bir qism uchun 15 MB gacha saqlanadi", + "– About {ratio}× the download of Kiri Linux": "– Kiri Linuxdan taxminan {ratio}× kattaroq yuklab olish", + "– Kiri shares it with your own Linux work": "– Kiri uni Linuxdagi oʻz ishlaringiz bilan baham koʻradi", + "– Not a Linux to use yourself": "– Oʻzingiz foydalanadigan Linux emas", + "— the end of the run before the last restart —": "— oxirgi qayta ishga tushirishdan oldingi ishning oxiri —", + "— the log stream ended —": "— jurnal oqimi tugadi —", + "‹ Back": "‹ Orqaga", + "★ Star on GitHub": "★ GitHubda yulduzcha qoʻying", + "✓ Installed": "✓ Oʻrnatilgan", + "Waiting to come back": "Qayta ulanish kutilmoqda", + "Stop waiting": "Kutishni toʻxtatish", + "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "U qaytganda Kiri uni yana ulaydi. Uni ushbu kompyuterda qoldirish uchun kutishni toʻxtating.", + "Fit the whole project": "Butun loyihani sigʻdirish", + "Find a service": "Servisni qidirish", + "docker compose up failed": "docker compose up muvaffaqiyatsiz tugadi", + "Not applied": "Qoʻllanilmagan", + "Saved, but the file has an error": "Saqlandi, lekin faylda xato bor", + "Your edits stay here. Apply waits until the file is back.": "Tahrirlaringiz shu yerda qoladi. Qoʻllash fayl qaytguncha kutadi.", + "build": "yigʻish", + "Queue": "Navbat", + "The file changed outside Kiri since Apply saved it": "“Qoʻllash” saqlaganidan keyin fayl Kiridan tashqarida oʻzgartirildi", + "Couldn't apply {name}: {error}": "{name}ni qoʻllab boʻlmadi: {error}", + "Saved, not started yet": "Saqlandi, hali ishga tushirilmagan", + "image": "obraz", + "Overwrite their changes": "Ularning oʻzgarishlari ustidan yozish", + "Recreating…": "Qayta yaratilmoqda…", + "Service": "Servis", + "{n} need it": "{n} ta xizmatga kerak", + "CHANGES": "OʻZGARISHLAR", + "Applied {name}": "{name} qoʻllandi", + "Overwrite": "Ustidan yozish", + "Restarting": "Qayta ishga tushirilmoqda", + "depends on": "bogʻliq", + "{svc} stopped after Apply": "{svc} Qoʻllashdan keyin toʻxtadi", + "Apply cancelled. {svc} had already changed; the rest were not changed.": "Qoʻllash bekor qilindi. {svc} allaqachon oʻzgartirilgan edi; qolganlari oʻzgartirilmadi.", + "Fix the file first.": "Avval faylni tuzating.", + "Open a compose file": "Compose faylini ochish", + "Worker": "Ishchi", + "Saved {name}, not applied: {error}": "{name} saqlandi, lekin qoʻllanmadi: {error}", + "Show in file": "Faylda koʻrsatish", + "needs {n}": "{n} kerak", + "Apply cancelled. No service was changed.": "Qoʻllash bekor qilindi. Hech bir servis oʻzgartirilmadi.", + "Arrows point at what a service needs; Compose starts those first.": "Strelkalar servisga nima kerakligini koʻrsatadi; Compose ularni birinchi boʻlib ishga tushiradi.", + "Starts on line {n} · click to jump there": "{n}-qatordan boshlanadi · oʻtish uchun bosing", + "Not in the file any more: stopped and removed. Its volumes stay.": "Endi faylda yoʻq: toʻxtatildi va oʻchirildi. Uning tomlari saqlanib qoladi.", + "the file changed outside Kiri": "fayl Kiridan tashqarida oʻzgartirildi", + "Overwrite their changes?": "Ularning oʻzgarishlari ustidan yozilsinmi?", + "No Compose projects yet": "Hali Compose loyihalari yoʻq", + "Saved, not applied": "Saqlandi, qoʻllanmadi", + "New service, built from its folder.": "Yangi servis, oʻz jildidan yigʻiladi.", + "The compose file isn't on this computer: {error}": "Compose fayli bu kompyuterda yoʻq: {error}", + "Saved, matches what runs": "Saqlandi, ishlayotgani bilan mos", + "Line {n}.": "{n}-qator.", + "{name} is already being applied. Wait for it to finish, or cancel it.": "{name} allaqachon qoʻllanmoqda. Tugashini kuting yoki uni bekor qiling.", + "{n} recreated": "{n} ta qayta yaratildi", + "Zoom out": "Kichraytirish", + "That project is gone": "Bu loyiha endi yoʻq", + "Couldn't run docker compose: {error}": "docker compose ni ishga tushirib boʻlmadi: {error}", + "No logs yet.": "Hali jurnallar yoʻq.", + "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "{name} nomli loyiha allaqachon {dir} jildidan ishlamoqda. Oʻshani oching yoki bu faylga alohida name: qatorini yozing.", + "{n} needs it": "{n} ta xizmatga kerak", + "File": "Fayl", + "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "{name} yashirin boʻlganda Kiri rejani koʻrsata olmaydi. “{apply}” docker compose up buyrugʻini ishga tushiradi.", + "REMOVED": "OʻCHIRILDI", + "The file changed outside Kiri. Apply writes your edits over it, and those changes are lost.": "Fayl Kiridan tashqarida oʻzgartirildi. Qoʻllash tahrirlaringizni uning ustidan yozadi va oʻsha oʻzgarishlar yoʻqoladi.", + "The other Apply of {name} finished. Your edit isn't applied yet.": "{name} uchun boshqa qoʻllash tugadi. Tahriringiz hali qoʻllanmagan.", + "The file changed outside Kiri.": "Fayl Kiridan tashqarida oʻzgartirildi.", + "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "{name} yashirin boʻlganda Kiri bu faylni tekshira olmaydi. Compose uni qabul qiladi, shuning uchun “Qoʻllash” baribir ishlaydi.", + "Compose rejects this file with its real values. Kiri can't show why with secrets hidden.": "Compose bu faylni haqiqiy qiymatlari bilan rad etmoqda. Maxfiy maʼlumotlar yashirilganda Kiri sababini koʻrsata olmaydi.", + "docker compose took longer than {secs} seconds": "docker compose {secs} soniyadan uzoq davom etdi", + "Discard": "Voz kechish", + "Refresh": "Yangilash", + "Names Docker shows may contain secret values.": "Docker koʻrsatadigan nomlarda maxfiy qiymatlar boʻlishi mumkin.", + "a newer image": "yangiroq obraz", + "docker compose up stopped": "docker compose up toʻxtadi", + "Applying…": "Qoʻllanmoqda…", + "Cache": "Kesh", + "New service from {image}.": "{image} obrazidan yangi servis.", + "{n} new": "{n} ta yangi", + "Apply cancelled. {n} services had already changed; the rest were not changed.": "Qoʻllash bekor qilindi. {n} ta servis allaqachon oʻzgartirilgan edi; qolganlari oʻzgartirilmadi.", + "Compose rejects this file: YAML error on line {n}": "Compose bu faylni rad etmoqda: {n}-qatorda YAML xatosi", + "Saved, not applied: {error}": "Saqlandi, qoʻllanmadi: {error}", + "Kiri has no state folder": "Kirida holat jildi yoʻq", + "{n} services": "{n} xizmat", + "Reload (lose your edits)": "Qayta yuklash (tahrirlaringiz yoʻqoladi)", + "Not started": "Ishga tushirilmagan", + "Couldn't open the compose file: {error}": "Compose faylini ochib boʻlmadi: {error}", + "Projects you start with {cmd} show up here once they have run on Kiri.": "{cmd} bilan ishga tushirgan loyihalaringiz Kirida ishlagandan keyin shu yerda koʻrinadi.", + "Saved": "Saqlandi", + "a variable it uses changed": "u ishlatadigan oʻzgaruvchi oʻzgardi", + "Not created": "Yaratilmagan", + "Saves the file, then runs {cmd}. Unchanged services keep running.": "Faylni saqlaydi, soʻng {cmd}ni bajaradi. Oʻzgarmagan servislar ishlashda davom etadi.", + "NEW": "YANGI", + "needs {list}": "{list} kerak", + "Removing…": "Oʻchirilmoqda…", + "Creating…": "Yaratilmoqda…", + "Metrics": "Metrikalar", + "Apply cancelled": "Qoʻllash bekor qilindi", + "The compose file is gone from its folder.": "Compose fayli oʻz jildida yoʻq.", + "Zoom in": "Kattalashtirish", + "The image name from {name} isn't valid": "{name}dagi obraz nomi yaroqsiz", + "Kiri can't show this service's details with its secrets hidden": "Sirlari yashirin boʻlganda Kiri bu xizmat tafsilotlarini koʻrsata olmaydi", + "The file changed outside Kiri": "Fayl Kiridan tashqarida oʻzgartirildi", + "Recreate": "Qayta yaratish", + "Applied {name}, but {svc} stopped": "{name} qoʻllandi, lekin {svc} toʻxtadi", + "Web": "Veb", + "See its logs": "Jurnallarini koʻrish", + "Remove from the list": "Roʻyxatdan olib tashlash", + "Compose rejects this file. A required variable may not be set: {name}.": "Compose bu faylni rad etmoqda. Majburiy oʻzgaruvchi oʻrnatilmagan boʻlishi mumkin: {name}.", + "environment": "muhit", + "Search": "Qidirish", + "Couldn't save the compose file: {error}": "Compose faylini saqlab boʻlmadi: {error}", + "Compose files": "Compose fayllari", + "Scheduler": "Rejalashtiruvchi", + "Kiri has nothing to put back": "Kirida qaytaradigan hech narsa yoʻq", + "Put back the file as it was before Apply saved over it": "Faylni “Qoʻllash” ustidan yozishidan oldingi holatiga qaytarish", + "Kiri can't check this file's variables, so it manages this project by name. Apply changes from a terminal.": "Kiri bu faylning oʻzgaruvchilarini tekshira olmaydi, shuning uchun loyihani nomi boʻyicha boshqaradi. Oʻzgarishlarni terminaldan qoʻllang.", + "Edited, not applied": "Tahrirlangan, qoʻllanmagan", + "This file isn't a compose file: it has no services": "Bu fayl compose fayli emas: unda xizmatlar yoʻq", + "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri docker CLI ni topa olmayapti. Uni qayta sozlash uchun Kirini qayta ishga tushiring.", + "Fit": "Sigʻdirish", + "Compose rejects this file: YAML error in an included file, line {n}": "Compose bu faylni rad etmoqda: qoʻshilgan faylda YAML xatosi, {n}-qator", + "Open a compose file…": "Compose faylini ochish…", + "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "Bu fayl nomida {vars} ishlatilgan. Kiri jild nomidan ({name}) foydalanadi, shunda nomga hech qachon maxfiy maʼlumot tushmaydi.", + "Kiri doesn't know that action": "Kiri bu amalni bilmaydi", + "Kiri can't find this project's compose file.": "Kiri bu loyihaning compose faylini topa olmayapti.", + "ports": "portlar", + "Newest container created {time}": "Eng yangi konteyner {time} yaratilgan", + "Compose file": "Compose fayli", + "Not started yet. Apply on the Compose file tab brings every service up.": "Hali ishga tushirilmagan. Compose fayli varagʻidagi Qoʻllash tugmasi barcha servislarni ishga tushiradi.", + "Couldn't change {name}: {error}": "{name}ni oʻzgartirib boʻlmadi: {error}", + "{n} unchanged": "{n} ta oʻzgarishsiz", + "Create": "Yaratish", + "Structure": "Tuzilma", + "YAML files": "YAML fayllar", + "{n} service": "{n} xizmat", + "{name} are used in a name or folder path. Docker shows those in plain text.": "{name} nom yoki jild yoʻlida ishlatilgan. Docker ularni ochiq matnda koʻrsatadi.", + "Its logs, Start, Stop and Remove still work.": "Jurnallar, “Ishga tushirish”, “Toʻxtatish” va “Oʻchirish” ishlashda davom etadi.", + "Showing the file as edited, not applied yet.": "Fayl tahrirlangan holda koʻrsatilmoqda, hali qoʻllanilmagan.", + "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "Hozircha hech narsa yoʻq: fayl ishlab turgan holatga mos keladi. Uni oʻzgartirsangiz, bu yerda har bir xizmat bilan nima boʻlishi koʻrsatiladi.", + "Kiri can't read the compose file: {error}": "Kiri compose faylini oʻqiy olmadi: {error}", + "Pick a .yaml or .yml compose file": ".yaml yoki .yml Compose faylini tanlang", + "Applied {name}, but {svcs} stopped": "{name} qoʻllandi, lekin {svcs} toʻxtadi", + "Compose rejects this file: YAML error in {file}, line {n}": "Compose bu faylni rad etmoqda: {file} faylida YAML xatosi, {n}-qator", + "What Apply does": "Qoʻllash nima qiladi", + "Saved, but an included file has an error": "Saqlandi, lekin ulangan faylda xato bor", + "{name} is used in a name or folder path. Docker shows those in plain text.": "{name} nom yoki jild yoʻlida ishlatilgan. Docker ularni ochiq matnda koʻrsatadi.", + "Apply": "Qoʻllash", + "Couldn't read env file {file}: it isn't a local regular file": "{file} env faylini oʻqib boʻlmadi: u mahalliy oddiy fayl emas", + "Keep editing": "Tahrirlashda davom etish", + "The compose file is read-only, so Kiri can't save it. Make it writable, then Apply again.": "Compose fayli faqat oʻqish uchun, shuning uchun Kiri uni saqlay olmaydi. Unga yozish ruxsatini bering, soʻng yana Qoʻllashni bosing.", + "There's no Compose project {name} on Kiri": "Kirida {name} Compose loyihasi yoʻq", + "The compose file is back, and differs from your edits.": "Compose fayli qaytdi va sizning tahrirlaringizdan farq qiladi.", + "{n} more": "yana {n} ta", + "Unchanged": "Oʻzgarmagan", + "Saved, but line {n} has an error": "Saqlandi, lekin {n}-qatorda xato bor", + "Actual size": "Asl oʻlcham", + "Show in compose file": "Compose faylida koʻrsatish", + "Open project": "Loyihani ochish", + "not started": "ishga tushirilmagan", + "Apply the compose file to create it": "Uni yaratish uchun compose faylini qoʻllang", + "Hide {name}'s containers": "{name} konteynerlarini yashirish", + "Show {name}'s containers": "{name} konteynerlarini koʻrsatish", + "Hide {name}'s pods": "{name} podlarini yashirish", + "Show {name}'s pods": "{name} podlarini koʻrsatish", + "{n} more in a Compose project": "Compose loyihasida yana {n} ta", + "{n} more in Compose projects": "Compose loyihalarida yana {n} ta", + "Your only container is in a Compose project": "Yagona konteyneringiz Compose loyihasi ichida", + "All {n} containers are in Compose projects": "Barcha {n} ta konteyner Compose loyihalarida", + "Skipped until Kiri next opens": "Kiri keyingi safar ochilguncha oʻtkazib yuborildi", + "Couldn't add the kiri docker context": "kiri docker kontekstini qoʻshib boʻlmadi", + "The kiri and docker commands": "kiri va docker buyruqlari", + "Ready in any new terminal": "Har qanday yangi terminalda tayyor", + "Couldn't add them to your shell": "Ularni qobiqqa qoʻshib boʻlmadi", + "Starts at login": "Tizimga kirishda ishga tushadi", + "The engine starts when you log in": "Tizimga kirganingizda dvijok ishga tushadi", + "The engine runs from the app for now": "Hozircha dvijok ilovadan ishlaydi", + "Show log": "Jurnalni koʻrsatish", + "Continue anyway": "Baribir davom etish", + "One step didn't work. Everything else is ready.": "Bitta qadam bajarilmadi. Qolgan hammasi tayyor.", + "Some steps didn't work. Everything else is ready.": "Baʼzi qadamlar bajarilmadi. Qolgan hammasi tayyor.", + "No matches": "Mosliklar yoʻq", + "Disk image size": "Disk obrazi hajmi", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Demon uchun KIRI_CPUS, KIRI_MEMORY_MIB yoki KIRI_DISK_GB belgilangan va u ushbu sozlamalardan ustun turadi.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Hozir {cpus}, {mem}gacha xotira va {disk} disk bilan ishlamoqda.", + "No other WSL distros installed.": "Boshqa WSL distributivlari oʻrnatilmagan.", + "WSL integration": "WSL integratsiyasi", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Yopish: oyna band qilgan xotira boʻshatiladi. Qayta ochilishi biroz vaqt oladi va ochiq terminallar yopiladi.", + "Closing the window": "Oynani yopishda", + "Hide: the window stays ready and opens again at once.": "Yashirish: oyna tayyor turadi va darhol qayta ochiladi.", + "Start Kiri at sign-in": "Tizimga kirishda Kirini ishga tushirish", + "Start Kiri in the background when you sign in.": "Tizimga kirganingizda Kirini orqa fonda ishga tushiradi.", + "Stop the engine when Kiri quits": "Kiridan chiqilganda dvijokni toʻxtatish", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiridan chiqish ishlayotgan konteynerlar va dvijokni toʻxtatadi. Kirini ochish uni yana ishga tushiradi.", + "{env} is set, so docker uses another engine instead of {app}": "{env} belgilangan, shuning uchun docker {app} oʻrniga boshqa dvijokdan foydalanadi", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} belgilangan, shuning uchun {docker} {app} oʻrniga boshqa dvijokdan foydalanadi. {app}dan foydalanish uchun uni qobiqda bekor qiling.", + "{env} is set": "{env} belgilangan", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "{env} ushbu seansda docker kontekstini ustidan bosadi, shuning uchun kontekstni almashtirish {docker}ni {app}ga oʻtkazmaydi. Uni {cmd} bilan tozalang yoki profilingizdan olib tashlang.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} {app}ga olib boradi. Testcontainers, IDE plaginlari va SDK kabi vositalar undan bevosita foydalanadi.", + "another engine": "boshqa dvijok", + "{path} belongs to {engine} and stays so.": "{path} {engine}ga tegishli va shundayligicha qoladi.", + "Tools that ignore docker contexts can use {hint}": "docker kontekstlarini eʼtiborsiz qoldiradigan vositalar {hint}dan foydalanishi mumkin", + "command": "buyruq", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} boʻsh. docker kontekstlarini eʼtiborsiz qoldiradigan vositalar u yerda {app}ni topishi uchun uni {app}ga bogʻlang.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} boʻsh. Boshqa Docker dvijogi band qilmagan boʻlsa, {app} ishlaganida unga xizmat koʻrsatadi.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} boʻsh. Boshqa Docker dvijogi band qilmagan boʻlsa, Kiri ishga tushganda {service} uni bogʻlaydi.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} boʻsh. {app} uni oʻrnatilgan Kiri uchun qoldiradi.", + "Linking…": "Bogʻlanmoqda…", + "Use {app}": "{app}dan foydalanish", + "Free": "Boʻsh", + "Docker socket": "Docker soketi", + "The {docker} command uses {app}.": "{docker} buyrugʻi {app}dan foydalanadi.", + "{env} is set in this session, so {docker} uses another engine.": "Ushbu seansda {env} belgilangan, shuning uchun {docker} boshqa dvijokdan foydalanadi.", + "The {docker} command uses {engine}.": "{docker} buyrugʻi {engine}dan foydalanadi.", + "Switching…": "Almashtirilmoqda…", + "{docker} command": "{docker} buyrugʻi", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock endi Kiriga yoʻnaltirilgan", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock soketini bogʻlab boʻlmadi: {error}", + "Stopping containers…": "Konteynerlar toʻxtatilmoqda…", + "Copying data…": "Maʼlumotlar nusxalanmoqda…", + "Verifying copy…": "Nusxa tekshirilmoqda…", + "Switching storage…": "Xotira joyi almashtirilmoqda…", + "Restarting engine…": "Dvijok qayta ishga tushirilmoqda…", + "Moving data…": "Maʼlumotlar koʻchirilmoqda…", + "Storage location unavailable": "Maʼlumotlar joyi mavjud emas", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri {path} ichidan oʻz maʼlumotlarini topa olmadi. Diskni ulab qayta urinib koʻring, boshqa jild tanlang yoki standart joyga qaytaring.", + "Change…": "Oʻzgartirish…", + "Reset to default": "Standart holatga qaytarish", + "Open storage settings": "Xotira sozlamalarini ochish", + "Start Kiri to change its storage location. ({error})": "Maʼlumotlar joyini oʻzgartirish uchun Kirini ishga tushiring. ({error})", + "{size} used": "{size} band", + "{size} free": "{size} boʻsh", + "Default": "Standart", + "Moving Kiri's data to {path}.": "Kiri maʼlumotlari {path}ga koʻchirilmoqda.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri maʼlumotlarni nusxalayotganda ishlayotgan konteynerlar toʻxtab turadi va jarayon tugagach yana ishga tushadi.", + "Couldn't change storage location": "Maʼlumotlar joyini oʻzgartirib boʻlmadi", + "Old data": "Eski maʼlumotlar", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Avvalgi maʼlumotlar hali ham {path} ichida. Yangi joyda hammasi ishlashiga ishonch hosil qilgach, ularni oʻchirib tashlang.", + "Remove old data": "Eski maʼlumotlarni oʻchirish", + "Storage location": "Maʼlumotlar joyi", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri maʼlumotlar joyini belgilaydi, shuning uchun uni bu yerda oʻzgartirib boʻlmaydi.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Obrazlar, konteynerlar va tomlar shu jildda saqlanadi. Tashqi disklar mahalliy fayl tizimida boʻlishi kerak (macOSda APFS, Linuxda ext4/xfs/btrfs, Windowsda NTFS); FAT va exFAT disklari qoʻllab-quvvatlanmaydi.", + "Reset storage location to default?": "Maʼlumotlar joyi standart holatga qaytarilsinmi?", + "Change storage location?": "Maʼlumotlar joyi oʻzgartirilsinmi?", + "Destination: {path} ({free} free).": "Manzil: {path} ({free} boʻsh).", + "Destination: {path}.": "Manzil: {path}.", + "Existing Kiri data in this folder will be replaced.": "Ushbu jilddagi mavjud Kiri maʼlumotlari almashtiriladi.", + "Migration mode": "Koʻchirish rejimi", + "Move existing images, containers, and volumes": "Mavjud obrazlar, konteynerlar va tomlarni koʻchirish", + "Stops running containers, copies your data, and starts them again.": "Ishlayotgan konteynerlarni toʻxtatadi, maʼlumotlaringizni nusxalaydi va ularni yana ishga tushiradi.", + "Start fresh": "Yangi boshlash", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Yangi jildda boʻsh holatda boshlanadi. Eski jildingiz uni oʻchirguningizcha saqlanib qoladi.", + "Kiri will switch to this folder and restart the engine.": "Kiri ushbu jildga oʻtadi va dvijokni qayta ishga tushiradi.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri maʼlumotlaringizni koʻchirayotganda ishlayotgan konteynerlar toʻxtaydi va tugagach yana ishga tushadi.", + "Move data": "Maʼlumotlarni koʻchirish", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri oʻzining standart jildiga qaytadi va dvijokni qayta ishga tushiradi. Uzilgan diskdagi maʼlumotlar oʻchirilmaydi.", + "Remove old data?": "Eski maʼlumotlar oʻchirilsinmi?", + "Everything in {path} will be deleted for good.": "{path} ichidagi barcha narsa butunlay oʻchiriladi.", + "Choose a storage folder": "Saqlash jildini tanlang", + "Kiri's data is moving already": "Kiri maʼlumotlari allaqachon koʻchirilmoqda", + "Kiri's data moved to {path}": "Kiri maʼlumotlari {path}ga koʻchirildi", + "Storage is available again": "Xotira qurilmasi yana mavjud", + "Old data removed": "Eski maʼlumotlar oʻchirildi", + "A proxy on this computer is reached as {host}.": "Bu kompyuterdagi proksiga {host} orqali murojaat qilinadi.", + "VPNs need no setting: container traffic leaves through Linux.": "VPN uchun sozlash shart emas: konteyner trafigi Linux orqali chiqadi.", + "Shared with Linux: containers only use them while busy.": "Linux bilan umumiy: konteynerlar ulardan faqat band boʻlganda foydalanadi.", + "The most containers and the engine may take. Unused memory stays free on Linux.": "Konteynerlar va dvijok olishi mumkin boʻlgan eng koʻp hajm. Ishlatilmagan xotira Linuxda boʻsh qoladi.", + "The engine is off; it starts with these next time.": "Dvijok oʻchiq; keyingi safar shu sozlamalar bilan ishga tushadi.", + "Restart engine to apply": "Qoʻllash uchun dvijokni qayta ishga tushirish", + "Windows bind-mount file events": "Windows ulangan jild fayl hodisalari", + "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "Jonli yangilash uchun Windows disklaridagi ({path} kabi) fayl oʻzgarishlarini konteynerlarga uzatadi. Boʻsh turganda CPU ishlatmaydi.", + "One text file, redacted, saved to your Desktop. Read it before you share it.": "Shaxsiy maʼlumotlari olib tashlangan bitta matn fayli Ish stolingizga saqlanadi. Uni ulashishdan oldin oʻqib chiqing.", + "The 5 newest crash reports for Kiri": "Kiri uchun eng yangi 5 ta nosozlik hisoboti", + "Kiri and this PC": "Kiri va ushbu kompyuter", + "Kiri and this computer": "Kiri va ushbu kompyuter", + "Versions, {os}, whether the engine runs, how many containers and images": "Versiyalar, {os}, dvijok ishlayotgani, konteyner va obrazlar soni", + "Saved. The engine uses these from its next start": "Saqlandi. Dvijok ularni keyingi ishga tushishdan boshlab qoʻllaydi", + "5 min": "5 daq", + "10 min": "10 daq", + "30 min": "30 daq", + "Never": "Hech qachon", + "Build cache limit": "Yigʻish keshi chegarasi", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit keshi ushbu hajmdan oshganda, eng eski keshlangan qatlamlar avtomatik tozalanadi.", + "Stop builder when idle": "Boʻsh turganda yigʻuvchini toʻxtatish", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Boʻsh turganda xotira band qilmasligi uchun yigʻishlar orasida BuildKitni toʻxtatadi; keyingi yigʻish uni bir soniyadan kam vaqtda uygʻotadi.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Demon uchun KIRI_BUILD_CACHE_GB yoki KIRI_BUILDER_IDLE_SECS belgilangan va u ushbu sozlamalardan ustun turadi.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: eng tezi. Agar Cloudflare WARP yoki korporativ xavfsizlik devori konteyner HTTPS trafigini toʻssa, Xost uzatmasiga oʻting. VM qayta ishga tushganda qoʻllanadi.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Xost uzatmasi: ulanishlar Virtualization.framework NAT oʻrniga macOSdagi Kiri orqali chiqadi. VM qayta ishga tushganda qoʻllanadi.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Muhitda KIRI_SHARED_NAT belgilangan va u ustun turadi.", + "Outbound VM traffic": "Chiquvchi VM trafigi", + "macOS NAT": "macOS NAT", + "Host relay": "Xost uzatmasi", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM diski kengayishi mumkin boʻlgan eng katta hajm. {os}da joy faqat maʼlumot yozilgani sayin band qilinadi, boʻshagan joyni esa {storage} boʻlimida qaytarib olish mumkin. Qayta ishga tushganda qoʻllanadi.", + "Settings → Storage": "Sozlamalar → Xotira qurilmasi", + "VM disk space": "VM disk joyi", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux tizimi xost fayl tizimidan bevosita foydalanadi — oʻchirilgan obrazlar va tomlar joyni darhol boʻshatadi.", + "Compact disk…": "Diskni zichlash…", + "Reclaim space": "Joyni qaytarish", + "Compacting…": "Zichlanmoqda…", + "Reclaiming…": "Qaytarilmoqda…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} zichlanmoqda va dvijok qayta ishga tushirilmoqda…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os}da {host}, VM ichida {inUse} band · ishlatilmayotgan bloklar tozalanmoqda…", + "Trimming unused blocks inside the VM disk…": "VM diski ichidagi ishlatilmayotgan bloklar tozalanmoqda…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windowsda {host} ({vhdx}), {inUse} band · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os}da {host}, VM ichida {inUse} band · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windowsda {host} ({vhdx}), {inUse} band · qaytariladigan joy yoʻq.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os}da {host}, VM ichida {inUse} band · qaytariladigan joy yoʻq.", + "Nothing to reclaim.": "Qaytariladigan joy yoʻq.", + "{size} can be given back": "{size} qaytarilishi mumkin", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windowsda {host} ({vhdx}), {inUse} band · {can}. Zichlash dvijokni qayta ishga tushiradi.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os}da {host}, VM ichida {inUse} band · konteynerlarni toʻxtatmasdan {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windowsda {host} ({vhdx}). Zichlash ishlatilmayotgan joyni qaytaradi va dvijokni qayta ishga tushiradi.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os}da {host}. Joyni qaytarish konteynerlarni toʻxtatmasdan VM diskidagi ishlatilmayotgan bloklarni boʻshatadi.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} ichidagi ishlatilmayotgan joyni Windowsga qaytaradi. Zichlash dvijokni qayta ishga tushiradi.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Konteynerlarni toʻxtatmasdan VM diskidagi ishlatilmayotgan bloklarni {os}ga qaytaradi.", + "Cleaning up stopped containers, untagged images, and build cache…": "Toʻxtatilgan konteynerlar, tegsiz obrazlar va yigʻish keshi tozalanmoqda…", + "{count} ({size})": "{count} ({size})", + "build cache": "yigʻish keshi", + "No stopped containers, untagged images or build cache · {freed}.": "Toʻxtatilgan konteynerlar, tegsiz obrazlar va yigʻish keshi yoʻq · {freed}.", + "No stopped containers, untagged images or build cache.": "Toʻxtatilgan konteynerlar, tegsiz obrazlar va yigʻish keshi yoʻq.", + "Cleaning up…": "Tozalanmoqda…", + "Clean up…": "Tozalash…", + "Unused Docker data": "Ishlatilmayotgan Docker maʼlumotlari", + "Command-line tools in shell": "Qobiqdagi buyruq satri vositalari", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Yangi terminallarda {docker}, {kubectl} va {kiri} ishlashi uchun {zshrc} hamda {zprofile} fayllariga {bin} yoʻlini qoʻshing.", + "Uninstall Kiri": "Kirini oʻchirib tashlash", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Dvijokni toʻxtatadi, Kirining fon xizmati, CLI havolalari va qobiq profili yozuvlarini olib tashlaydi hamda avvalgi Docker kontekstingizni ({cmd}) tiklaydi.", + "Uninstall Kiri…": "Kirini oʻchirib tashlash…", + "Couldn't reclaim disk space: {error}": "Disk joyini qaytarib boʻlmadi: {error}", + "Reclaimed {size} on {os}": "{os}da {size} joy qaytarildi", + "Nothing to reclaim": "Qaytariladigan joy yoʻq", + "Couldn't clean up unused Docker data: {error}": "Ishlatilmayotgan Docker maʼlumotlarini tozalab boʻlmadi: {error}", + "Cleaned up {size} of unused Docker data": "{size} ishlatilmayotgan Docker maʼlumotlari tozalandi", + "Cleaned up unused Docker data": "Ishlatilmayotgan Docker maʼlumotlari tozalandi", + "Compact WSL disk?": "WSL diski zichlansinmi?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} faylini zichlash ishlatilmayotgan joyni Windowsga qaytaradi hamda Kiri dvijoki va ishlayotgan konteynerlarni qisqa muddatga qayta ishga tushiradi.", + "Compact disk": "Diskni zichlash", + "Clean up unused Docker data?": "Ishlatilmayotgan Docker maʼlumotlari tozalansinmi?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Toʻxtatilgan konteynerlar, tegsiz obrazlar va BuildKit yigʻish keshini oʻchiradi. Ishlayotgan konteynerlar va teglangan obrazlar saqlanib qoladi.", + "Clean up": "Tozalash", + "Uninstall Kiri?": "Kiri oʻchirib tashlansinmi?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Dvijokni toʻxtatadi, Kirining fon xizmati, CLI havolalari va qobiq profili yozuvlarini olib tashlaydi hamda avvalgi Docker kontekstingizni tiklaydi. Obrazlar va tomlaringiz Kiri maʼlumotlar jildini oʻzingiz oʻchirguningizcha saqlanib qoladi.", + "Cluster": "Klaster", + "default": "standart", + "k3s version": "k3s versiyasi", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Klaster tuguni uchun obraz versiyasi ({cmd}). Qayta yaratilganda qoʻllanadi.", + "Extra server flags": "Qoʻshimcha server bayroqlari", + "Passed to {srv} ({flag}), separated by spaces.": "Boʻsh joy bilan ajratilgan holda {srv} ({flag}) ga uzatiladi.", + "Startup manifests": "Ishga tushish manifestlari", + "YAML files in {path} are applied whenever the cluster starts.": "{path} ichidagi YAML fayllar klaster har safar ishga tushganda qoʻllanadi.", + "Open folder": "Jildni ochish", + "{n} untagged image": "{n} tegsiz obraz", + "{n} untagged images": "{n} tegsiz obraz", + "Uninstall Kiri from Windows Settings → Apps": "Kirini Windows Sozlamalari → Ilovalar boʻlimidan oʻchirib tashlang", + "Builder settings saved": "Yigʻuvchi sozlamalari saqlandi", + "Could not save builder settings: {error}": "Yigʻuvchi sozlamalarini saqlab boʻlmadi: {error}", + "Disk reclaim is already running": "Disk joyini qaytarish allaqachon bajarilmoqda", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Chiquvchi VM trafigi sozlamasi saqlandi. Qoʻllash uchun VMni qayta ishga tushiring.", + "Could not save VM networking setting: {error}": "VM tarmoq sozlamasini saqlab boʻlmadi: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri buyruq satri vositalari qobiq profillariga qoʻshildi", + "Removed Kiri command-line tools from shell profiles": "Kiri buyruq satri vositalari qobiq profillaridan olib tashlandi", + "Could not update shell profiles: {error}": "Qobiq profillarini yangilab boʻlmadi: {error}", + "Uninstalling Kiri…": "Kiri oʻchirib tashlanmoqda…", + "Could not uninstall Kiri: {error}": "Kirini oʻchirib tashlab boʻlmadi: {error}", + "Uninstall Kiri using your system package manager": "Kirini tizimingiz paket menejeri orqali oʻchirib tashlang", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM xotirasi tugaganda ishlatishi mumkin boʻlgan disk joyi — shunda konteynerlar toʻxtab qolish oʻrniga sekinlashadi. Qayta ishga tushganda qoʻllanadi." +} diff --git a/crates/kiri/src/ui/langstep.js b/crates/kiri/src/ui/langstep.js index 8106000d3..e5373f1ab 100644 --- a/crates/kiri/src/ui/langstep.js +++ b/crates/kiri/src/ui/langstep.js @@ -8,17 +8,19 @@ /* Each language in its own name, by script: the Latin alphabet (A to Z by that name), Greek, Cyrillic, the Arabic script, Ethiopic, the Indian scripts, Thai and Lao, then Japanese, Korean and Chinese. */ -const LANGS = [["en", "English"], ["id", "Bahasa Indonesia"], ["ca", "Català"], ["cs", "Čeština"], ["de", "Deutsch"], ["es", "Español"], ["fr", "Français"], ["it", "Italiano"], ["lt", "Lietuvių"], ["hu", "Magyar"], ["nb", "Norsk bokmål"], ["pl", "Polski"], ["pt-BR", "Português (Brasil)"], ["ro", "Română"], ["sq", "Shqip"], ["sl", "Slovenščina"], ["fi", "Suomi"], ["vi", "Tiếng Việt"], ["tr", "Türkçe"], ["el", "Ελληνικά"], ["bg", "Български"], ["ru", "Русский"], ["uk", "Українська"], ["kk", "Қазақша"], ["ar", "العربية"], ["fa", "فارسی"], ["ckb", "کوردیی ناوەندی"], ["am", "አማርኛ"], ["hi", "हिन्दी"], ["bn", "বাংলা"], ["ta", "தமிழ்"], ["te", "తెలుగు"], ["th", "ไทย"], ["lo", "ລາວ"], ["ja", "日本語"], ["ko", "한국어"], ["zh-Hans", "简体中文"], ["zh-Hant", "繁體中文"]]; +const LANGS = [["en", "English"], ["id", "Bahasa Indonesia"], ["ca", "Català"], ["cs", "Čeština"], ["de", "Deutsch"], ["es", "Español"], ["fr", "Français"], ["it", "Italiano"], ["lt", "Lietuvių"], ["hu", "Magyar"], ["nb", "Norsk bokmål"], ["uz", "Oʻzbekcha"], ["pl", "Polski"], ["pt-BR", "Português (Brasil)"], ["ro", "Română"], ["sq", "Shqip"], ["sl", "Slovenščina"], ["fi", "Suomi"], ["vi", "Tiếng Việt"], ["tr", "Türkçe"], ["el", "Ελληνικά"], ["bg", "Български"], ["ru", "Русский"], ["uk", "Українська"], ["kk", "Қазақша"], ["ar", "العربية"], ["fa", "فارسی"], ["ckb", "کوردیی ناوەندی"], ["am", "አማርኛ"], ["hi", "हिन्दी"], ["ne", "नेपाली"], ["bn", "বাংলা"], ["ta", "தமிழ்"], ["te", "తెలుగు"], ["th", "ไทย"], ["lo", "ລາວ"], ["ja", "日本語"], ["ko", "한국어"], ["zh-Hans", "简体中文"], ["zh-Hant", "繁體中文"]]; /* Each language's English name: the language step shows it beside the own name and finds a language by it ("German" for Deutsch). One for each in LANGS; one missing shows and sorts by its own name (langEn). */ -const LANG_EN = { en: "English", id: "Indonesian", ca: "Catalan", cs: "Czech", de: "German", es: "Spanish", fr: "French", it: "Italian", lt: "Lithuanian", hu: "Hungarian", nb: "Norwegian Bokmål", pl: "Polish", "pt-BR": "Portuguese (Brazil)", ro: "Romanian", sq: "Albanian", sl: "Slovenian", fi: "Finnish", vi: "Vietnamese", tr: "Turkish", el: "Greek", bg: "Bulgarian", ru: "Russian", uk: "Ukrainian", kk: "Kazakh", ar: "Arabic", fa: "Persian", ckb: "Kurdish (Sorani)", am: "Amharic", hi: "Hindi", bn: "Bengali", ta: "Tamil", te: "Telugu", th: "Thai", lo: "Lao", ja: "Japanese", ko: "Korean", "zh-Hans": "Chinese (Simplified)", "zh-Hant": "Chinese (Traditional)" }; +const LANG_EN = { en: "English", id: "Indonesian", ca: "Catalan", cs: "Czech", de: "German", es: "Spanish", fr: "French", it: "Italian", lt: "Lithuanian", hu: "Hungarian", nb: "Norwegian Bokmål", uz: "Uzbek", pl: "Polish", "pt-BR": "Portuguese (Brazil)", ro: "Romanian", sq: "Albanian", sl: "Slovenian", fi: "Finnish", vi: "Vietnamese", tr: "Turkish", el: "Greek", bg: "Bulgarian", ru: "Russian", uk: "Ukrainian", kk: "Kazakh", ar: "Arabic", fa: "Persian", ckb: "Kurdish (Sorani)", am: "Amharic", hi: "Hindi", ne: "Nepali", bn: "Bengali", ta: "Tamil", te: "Telugu", th: "Thai", lo: "Lao", ja: "Japanese", ko: "Korean", "zh-Hans": "Chinese (Simplified)", "zh-Hant": "Chinese (Traditional)" }; /* Hello in each, in its own script. */ -const HELLO = { en: "Hello", id: "Halo", ca: "Hola", cs: "Ahoj", de: "Hallo", es: "Hola", fr: "Bonjour", it: "Ciao", lt: "Labas", hu: "Szia", nb: "Hei", pl: "Cześć", "pt-BR": "Olá", ro: "Salut", sq: "Përshëndetje", sl: "Živjo", fi: "Hei", vi: "Xin chào", tr: "Merhaba", el: "Γεια σου", bg: "Здравей", ru: "Привет", uk: "Привіт", kk: "Сәлем", ar: "مرحبًا", fa: "سلام", ckb: "سڵاو", am: "ሰላም", hi: "नमस्ते", bn: "নমস্কার", ta: "வணக்கம்", te: "నమస్కారం", th: "สวัสดี", lo: "ສະບາຍດີ", ja: "こんにちは", ko: "안녕하세요", "zh-Hans": "你好", "zh-Hant": "你好" }; +const HELLO = { en: "Hello", id: "Halo", ca: "Hola", cs: "Ahoj", de: "Hallo", es: "Hola", fr: "Bonjour", it: "Ciao", lt: "Labas", hu: "Szia", nb: "Hei", uz: "Salom", pl: "Cześć", "pt-BR": "Olá", ro: "Salut", sq: "Përshëndetje", sl: "Živjo", fi: "Hei", vi: "Xin chào", tr: "Merhaba", el: "Γεια σου", bg: "Здравей", ru: "Привет", uk: "Привіт", kk: "Сәлем", ar: "مرحبًا", fa: "سلام", ckb: "سڵاو", am: "ሰላም", hi: "नमस्ते", ne: "नमस्ते", bn: "নমস্কার", ta: "வணக்கம்", te: "నమస్కారం", th: "สวัสดี", lo: "ສະບາຍດີ", ja: "こんにちは", ko: "안녕하세요", "zh-Hans": "你好", "zh-Hant": "你好" }; /* Other names people search by: what a language is also called in English - ("Farsi"), in itself ("Castellano") or spelled another way (हिंदी). */ + ("Farsi"), in itself ("Castellano") or spelled another way (हिंदी, Uzbek in + other Latin spellings or Cyrillic). */ const LANG_ALIAS = { farsi: ["fa"], mandarin: ["zh-Hans", "zh-Hant"], chinese: ["zh-Hans", "zh-Hant"], putonghua: ["zh-Hans"], cantonese: ["zh-Hant"], - castellano: ["es"], castilian: ["es"], "हिंदी": ["hi"], bangla: ["bn"], brazilian: ["pt-BR"], norwegian: ["nb"], sorani: ["ckb"], bahasa: ["id"] }; + castellano: ["es"], castilian: ["es"], "हिंदी": ["hi"], bangla: ["bn"], brazilian: ["pt-BR"], norwegian: ["nb"], sorani: ["ckb"], bahasa: ["id"], + "o'zbekcha": ["uz"], "oʻzbekcha": ["uz"], "o‘zbekcha": ["uz"], ozbekcha: ["uz"], "ōzbekça": ["uz"], "ўзбекча": ["uz"] }; const langEn = (id, own) => LANG_EN[id] || own; const langOwn = (id) => (LANGS.find(([l]) => l === id) || [id, id])[1]; /* Languages offered after the system's own, until Suggested holds five. */ diff --git a/tests/ui/langpick.js b/tests/ui/langpick.js index 9302088b3..e26b49d2f 100644 --- a/tests/ui/langpick.js +++ b/tests/ui/langpick.js @@ -13,10 +13,10 @@ const saved = (name) => sent.filter((m) => m.type === "setpref" && m.name === na const rail = () => document.querySelector("nav [data-view=containers] .lbl").textContent; kiri.on({ type: "langpick" }); -t("a langpick event opens the language step with a row for each of the 38 languages", () => { +t("a langpick event opens the language step with a row for each of the 40 languages", () => { if (!dlg()) throw new Error("no dialog"); const ids = tilesNow().map((b) => b.dataset.lang).sort().join(" "); - if (ids !== LANGS.map(([id]) => id).sort().join(" ") || tilesNow().length !== 38) throw new Error("rows: " + ids); + if (ids !== LANGS.map(([id]) => id).sort().join(" ") || tilesNow().length !== 40) throw new Error("rows: " + ids); }); t("one column, a line each", () => { const lefts = new Set(tilesNow().map((b) => Math.round(b.getBoundingClientRect().left))); @@ -26,7 +26,7 @@ t("one column, a line each", () => { t("each row is in its own language, with its own Hello", () => { if (pickTile("de").querySelector(".ln").getAttribute("lang") !== "de" || !pickTile("de").textContent.includes("Deutsch") || !pickTile("de").textContent.includes("Hallo")) throw new Error(pickTile("de").textContent); if (!pickTile("zh-Hans").textContent.includes("简体中文") || !pickTile("zh-Hans").textContent.includes("你好")) throw new Error(pickTile("zh-Hans").textContent); - for (const [id, name, hello] of [["ja", "日本語", "こんにちは"], ["ko", "한국어", "안녕하세요"], ["zh-Hant", "繁體中文", "你好"], ["ru", "Русский", "Привет"], ["uk", "Українська", "Привіт"], ["hi", "हिन्दी", "नमस्ते"], ["fa", "فارسی", "سلام"], ["ckb", "کوردیی ناوەندی", "سڵاو"], ["el", "Ελληνικά", "Γεια σου"], ["kk", "Қазақша", "Сәлем"], ["te", "తెలుగు", "నమస్కారం"], ["am", "አማርኛ", "ሰላም"], ["th", "ไทย", "สวัสดี"], ["lo", "ລາວ", "ສະບາຍດີ"], ["nb", "Norsk bokmål", "Hei"], ["bn", "বাংলা", "নমস্কার"], ["ta", "தமிழ்", "வணக்கம்"], ["ar", "العربية", "مرحبًا"], ["vi", "Tiếng Việt", "Xin chào"], ["id", "Bahasa Indonesia", "Halo"]]) + for (const [id, name, hello] of [["ja", "日本語", "こんにちは"], ["ko", "한국어", "안녕하세요"], ["zh-Hant", "繁體中文", "你好"], ["ru", "Русский", "Привет"], ["uk", "Українська", "Привіт"], ["hi", "हिन्दी", "नमस्ते"], ["ne", "नेपाली", "नमस्ते"], ["fa", "فارسی", "سلام"], ["ckb", "کوردیی ناوەندی", "سڵاو"], ["el", "Ελληνικά", "Γεια σου"], ["kk", "Қазақша", "Сәлем"], ["te", "తెలుగు", "నమస్కారం"], ["am", "አማርኛ", "ሰላም"], ["th", "ไทย", "สวัสดี"], ["lo", "ລາວ", "ສະບາຍດີ"], ["nb", "Norsk bokmål", "Hei"], ["uz", "Oʻzbekcha", "Salom"], ["bn", "বাংলা", "নমস্কার"], ["ta", "தமிழ்", "வணக்கம்"], ["ar", "العربية", "مرحبًا"], ["vi", "Tiếng Việt", "Xin chào"], ["id", "Bahasa Indonesia", "Halo"]]) if (pickTile(id).querySelector(".ln").getAttribute("lang") !== id || !pickTile(id).textContent.includes(name) || !pickTile(id).textContent.includes(hello)) throw new Error(pickTile(id).textContent); }); t("the system's language is marked and picked", () => { diff --git a/tests/ui/langstep.js b/tests/ui/langstep.js index c1e806c14..23d7dfe0b 100644 --- a/tests/ui/langstep.js +++ b/tests/ui/langstep.js @@ -41,12 +41,12 @@ t("Suggested: the system's language first, its other languages, then up to five" if (sug?.querySelector(".lsect")?.textContent !== "Suggested") throw new Error("first section: " + sug?.querySelector(".lsect")?.textContent); const got = ids(`#${sug.id}`).join(" "); if (got !== "en de pt-BR es fr") throw new Error("suggested: " + got); - if (all?.querySelector(".lsect")?.textContent !== "All languages · 38") throw new Error("second section: " + all?.querySelector(".lsect")?.textContent); + if (all?.querySelector(".lsect")?.textContent !== "All languages · 40") throw new Error("second section: " + all?.querySelector(".lsect")?.textContent); }); t("All languages: every one, by its English name", () => { const all = groups()[1]; const got = rows(`#${all.id}`); - if (got.length !== 38 || new Set(got.map((r) => r.dataset.lang)).size !== 38) throw new Error(got.length + " rows"); + if (got.length !== 40 || new Set(got.map((r) => r.dataset.lang)).size !== 40) throw new Error(got.length + " rows"); const names = got.map((r) => (r.querySelector(".le") || r.querySelector(".ln")).textContent); const sorted = [...names].sort((a, b) => a.localeCompare(b, "en")); if (names.join() !== sorted.join()) throw new Error("not sorted: " + names.join(", ")); @@ -100,7 +100,7 @@ t("nothing found says so", () => { }); t("clearing the search brings the sections back", () => { type(""); - if (groups().length !== 2 || rows().length !== 43) throw new Error(`${groups().length} sections, ${rows().length} rows`); + if (groups().length !== 2 || rows().length !== 45) throw new Error(`${groups().length} sections, ${rows().length} rows`); }); t("Up and Down move through the rows, from the one picked", () => { @@ -166,7 +166,7 @@ t("clearing the search after a pick keeps the highlight on the row picked", () = }); t("Up and Down from a picked row further down move from it", () => { key("ArrowDown"); - if (active() !== "nb") throw new Error("Down from Lithuanian is " + active()); + if (active() !== "ne") throw new Error("Down from Lithuanian is " + active()); key("ArrowUp"); key("ArrowUp"); if (active() !== "lo") throw new Error("two up is " + active()); }); @@ -329,8 +329,8 @@ t("Page Down, Page Up, Home and End move the highlight", () => { type(""); }); -t("other names: farsi, mandarin, chinese, castellano, हिंदी", () => { - for (const [s, want] of [["farsi", "fa"], ["Farsi", "fa"], ["mandarin", "zh-Hans zh-Hant"], ["chinese", "zh-Hans zh-Hant"], ["castellano", "es"], ["हिंदी", "hi"], ["हिन्दी", "hi"]]) { +t("other names: farsi, mandarin, chinese, castellano, हिंदी, Uzbek spellings, नेपाली", () => { + for (const [s, want] of [["farsi", "fa"], ["Farsi", "fa"], ["mandarin", "zh-Hans zh-Hant"], ["chinese", "zh-Hans zh-Hant"], ["castellano", "es"], ["हिंदी", "hi"], ["हिन्दी", "hi"], ["ozbek", "uz"], ["o'zbek", "uz"], ["oʻzbekcha", "uz"], ["ōzbekça", "uz"], ["ўзбекча", "uz"], ["uz", "uz"], ["नेपाली", "ne"], ["nepali", "ne"]]) { type(s); const got = ids().slice(0, want.split(" ").length).join(" "); if (got !== want) throw new Error(`"${s}" found ${ids().join(" ")}`); @@ -364,7 +364,7 @@ t("a language without an English name or a hello still shows, by its own name", if (!opened) throw new Error("the step didn't open"); const xx = list().querySelector('#lg-a [data-lang="xx"]'); if (!xx || xx.querySelector(".ln").textContent !== "Xxish" || xx.querySelector(".le")) throw new Error(xx?.outerHTML || "no row"); - if (list().querySelector("#lg-a .lsect").textContent !== "All languages · 39") throw new Error(list().querySelector("#lg-a .lsect").textContent); + if (list().querySelector("#lg-a .lsect").textContent !== "All languages · 41") throw new Error(list().querySelector("#lg-a .lsect").textContent); type("xxi"); if (ids().join() !== "xx") throw new Error("found " + ids()); type(""); diff --git a/tests/ui/langswitch.js b/tests/ui/langswitch.js index 1b1a3d551..3b36ea73f 100644 --- a/tests/ui/langswitch.js +++ b/tests/ui/langswitch.js @@ -62,11 +62,13 @@ t("every language comes from the host when picked, and shows", () => { if (document.documentElement.dir !== (rtlLang ? "rtl" : "ltr")) throw new Error(`${id}: dir is ${document.documentElement.dir}`); if (getComputedStyle(document.documentElement).getPropertyValue("--ui-font").includes("Geeza Pro") !== rtlLang) throw new Error(`${id}: Arabic script's fonts`); const font = getComputedStyle(document.documentElement).getPropertyValue("--ui-font"); - const want = { ja: "Hiragino Sans", ko: "Malgun Gothic", "zh-Hant": "PingFang TC", "zh-Hans": "PingFang SC", hi: "Kohinoor Devanagari", bn: "Kohinoor Bangla", ta: "Tamil Sangam MN", am: "Kefa", te: "Kohinoor Telugu", th: "Thonburi", lo: "Lao Sangam MN" }[id] || "PingFang SC"; - // Hindi, Bengali and Tamil each with their own script's fonts, and only them. - if (/^(hi|bn|ta|te)$/.test(id) && !font.includes("Nirmala UI")) throw new Error(`${id}: no Nirmala UI in ${font}`); - if (!/^(hi|bn|ta|te)$/.test(id) && font.includes("Nirmala UI")) throw new Error(`${id}: Indian fonts in ${font}`); + const want = { ja: "Hiragino Sans", ko: "Malgun Gothic", "zh-Hant": "PingFang TC", "zh-Hans": "PingFang SC", hi: "Kohinoor Devanagari", ne: "Kohinoor Devanagari", bn: "Kohinoor Bangla", ta: "Tamil Sangam MN", am: "Kefa", te: "Kohinoor Telugu", th: "Thonburi", lo: "Lao Sangam MN" }[id] || "PingFang SC"; + // Hindi, Nepali, Bengali and Tamil each with their own script's fonts, and only them. + if (/^(hi|ne|bn|ta|te)$/.test(id) && !font.includes("Nirmala UI")) throw new Error(`${id}: no Nirmala UI in ${font}`); + if (!/^(hi|ne|bn|ta|te)$/.test(id) && font.includes("Nirmala UI")) throw new Error(`${id}: Indian fonts in ${font}`); if (!font.includes(want)) throw new Error(`${id}: the font is ${font}`); + // Noto first: the only one of these fonts that draws Nepali's own झ. + if (id === "ne" && font.indexOf("Noto Sans Devanagari") > font.indexOf("Kohinoor Devanagari")) throw new Error(`ne: Noto Sans Devanagari isn't first in ${font}`); } pick("en"); const now = (visit(PLACES[0]), words()); @@ -81,7 +83,7 @@ t("an answer for a language no longer picked changes nothing", () => { }); t("tags map to the languages Kiri has, as lang.rs maps them", () => { const want = { zh: "zh-Hans", "zh-CN": "zh-Hans", "zh-SG": "zh-Hans", "zh-Hans-HK": "zh-Hans", zh_TW: "zh-Hant", "zh-TW": "zh-Hant", "zh-HK": "zh-Hant", "zh-MO": "zh-Hant", "zh-Hant": "zh-Hant", "zh-Hant-CN": "zh-Hant", - zhx: "", in: "id", "in-ID": "id", "id-ID": "id", iw: "", "iw-IL": "", "ja-JP": "ja", "ko-KR": "ko", "ru-RU": "ru", uk: "uk", "uk-UA": "uk", uk_UA: "uk", hi: "hi", "hi-IN": "hi", "bn-IN": "bn", "bn-BD": "bn", "ta-IN": "ta", "ta-LK": "ta", "te-IN": "te", am: "am", "am-ET": "am", "th-TH": "th", "lo-LA": "lo", "ca-ES": "ca", "cs-CZ": "cs", "lt-LT": "lt", "hu-HU": "hu", "nb-NO": "nb", no: "nb", "nn-NO": "nb", "ro-RO": "ro", "sq-AL": "sq", "sl-SI": "sl", "fi-FI": "fi", "el-GR": "el", "bg-BG": "bg", "kk-KZ": "kk", "fa-IR": "fa", ckb: "ckb", "ku-Arab-IQ": "ckb", ku: "", "pl-PL": "pl", "tr-TR": "tr", "vi-VN": "vi", "it-CH": "it", "pt-PT": "pt-BR", "fr-CA": "fr", "en-GB": "en", nl: "", ar: "ar", "ar-SA": "ar", "ar-EG": "ar", ar_AE: "ar", arz: "", he: "" }; + zhx: "", in: "id", "in-ID": "id", "id-ID": "id", iw: "", "iw-IL": "", "ja-JP": "ja", "ko-KR": "ko", "ru-RU": "ru", uk: "uk", "uk-UA": "uk", uk_UA: "uk", hi: "hi", "hi-IN": "hi", ne: "ne", "ne-NP": "ne", ne_NP: "ne", "bn-IN": "bn", "bn-BD": "bn", "ta-IN": "ta", "ta-LK": "ta", "te-IN": "te", am: "am", "am-ET": "am", "th-TH": "th", "lo-LA": "lo", "ca-ES": "ca", "cs-CZ": "cs", "lt-LT": "lt", "hu-HU": "hu", "nb-NO": "nb", no: "nb", "nn-NO": "nb", "ro-RO": "ro", "sq-AL": "sq", "sl-SI": "sl", "fi-FI": "fi", "el-GR": "el", "bg-BG": "bg", "kk-KZ": "kk", uz: "uz", "uz-UZ": "uz", "uz-Latn-UZ": "uz", uz_UZ: "uz", "fa-IR": "fa", ckb: "ckb", "ku-Arab-IQ": "ckb", ku: "", "pl-PL": "pl", "tr-TR": "tr", "vi-VN": "vi", "it-CH": "it", "pt-PT": "pt-BR", "fr-CA": "fr", "en-GB": "en", nl: "", ar: "ar", "ar-SA": "ar", "ar-EG": "ar", ar_AE: "ar", arz: "", he: "" }; const bad = Object.entries(want).filter(([tag, id]) => langFor(tag) !== id).map(([tag, id]) => `${tag} → ${langFor(tag)}, not ${id}`); if (bad.length) throw new Error(bad.join("; ")); }); diff --git a/tests/ui/nav-beta-tag.js b/tests/ui/nav-beta-tag.js index d99e1e90a..68b0e12f0 100644 --- a/tests/ui/nav-beta-tag.js +++ b/tests/ui/nav-beta-tag.js @@ -1,5 +1,5 @@ // parity: macos windows linux -// The sidebar's Compose and USB entries, each with a two-digit count, in each of the 38 languages: both carry +// The sidebar's Compose and USB entries, each with a two-digit count, in each of the 40 languages: both carry // the plain outlined Beta tag in the language's word; the name is never cut by it; the tag is whole or hidden, // never clipped; no New tag is left. const R = []; diff --git a/tests/ui/setup-langstep.js b/tests/ui/setup-langstep.js index 23cc3f523..b2e715140 100644 --- a/tests/ui/setup-langstep.js +++ b/tests/ui/setup-langstep.js @@ -41,13 +41,13 @@ t("the setup window asks with a search field, focused, and one list, not tiles", if (main().querySelector(".lhello").textContent !== "Hello!") throw new Error("hello: " + main().querySelector(".lhello").textContent); if (!(box(q()).bottom <= box(list()).top && box(list()).bottom <= box(document.getElementById("lang-go")).top)) throw new Error("not search, list, Continue"); }); -t("Suggested, then All languages · 38 by English name, as in the main window", () => { +t("Suggested, then All languages · 40 by English name, as in the main window", () => { const [sug, all] = groups(); if (sug?.querySelector(".lsect").textContent !== "Suggested") throw new Error(sug?.textContent.slice(0, 40)); if (ids(`#${sug.id}`).join(" ") !== "en de pt-BR es fr") throw new Error("suggested: " + ids(`#${sug.id}`).join(" ")); - if (all?.querySelector(".lsect").textContent !== "All languages · 38") throw new Error(all?.querySelector(".lsect").textContent); + if (all?.querySelector(".lsect").textContent !== "All languages · 40") throw new Error(all?.querySelector(".lsect").textContent); const got = rows(`#${all.id}`), names = got.map((r) => (r.querySelector(".le") || r.querySelector(".ln")).textContent); - if (got.length !== 38 || names.join() !== [...names].sort((a, b) => a.localeCompare(b, "en")).join()) throw new Error(names.join(", ")); + if (got.length !== 40 || names.join() !== [...names].sort((a, b) => a.localeCompare(b, "en")).join()) throw new Error(names.join(", ")); const de = list().querySelector('[data-lang="de"]'); if (de.querySelector(".ln").textContent !== "Deutsch" || de.querySelector(".le").textContent !== "German" || de.querySelector(".lh").textContent !== "Hallo") throw new Error(de.textContent); if (picked().join() !== "en") throw new Error("picked " + picked()); From 7df2881e47f19d263e2b5442904fc19e8f1672d8 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:46:30 +0100 Subject: [PATCH 155/157] UI: add Armenian & Azerbaijani (42 languages), About Community links, and hide off/paused local domains (#386, #401) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lang/hy.json & lang/az.json: add Armenian (Հայերեն, #386) and Azerbaijani (Azərbaycanca, #401) at 100% key parity (2,038 keys across 41 translation files), tightening verbose Azerbaijani labels so narrow cards and tabs fit. - lang.rs, langstep.js, index.html, setup.html: register hy (hy, hy-AM, hy_AM) and az (az, az-AZ, az-Latn-AZ, az_AZ), Armenian font fallbacks (Noto Sans Armenian, Mshtakan, Sylfaen), and Latin search aliases (azeri, azerbaycanca, hayeren). - Settings → About: add Community row (Discord + @runkiri on X) with .soc-i icons and idiomatic 'Community' translations across all 41 language files. - Domains: return empty string from localUrl() when the active router reports running: false or serving: false so dead .kiri.local/.kiri.localhost links are hidden while published host ports remain clickable. Co-authored-by: Shahen Hovhannisyan Co-authored-by: Míng hàn --- README.md | 4 +- crates/kiri-win/src/setup.html | 3 +- crates/kiri/src/ui/index.html | 6 +- crates/kiri/src/ui/lang.rs | 11 +- crates/kiri/src/ui/lang/am.json | 3 +- crates/kiri/src/ui/lang/ar.json | 3 +- crates/kiri/src/ui/lang/az.json | 2040 ++++++++++++++++++++++++++ crates/kiri/src/ui/lang/bg.json | 3 +- crates/kiri/src/ui/lang/bn.json | 3 +- crates/kiri/src/ui/lang/ca.json | 3 +- crates/kiri/src/ui/lang/ckb.json | 3 +- crates/kiri/src/ui/lang/cs.json | 3 +- crates/kiri/src/ui/lang/de.json | 3 +- crates/kiri/src/ui/lang/el.json | 3 +- crates/kiri/src/ui/lang/es.json | 3 +- crates/kiri/src/ui/lang/fa.json | 3 +- crates/kiri/src/ui/lang/fi.json | 3 +- crates/kiri/src/ui/lang/fr.json | 3 +- crates/kiri/src/ui/lang/hi.json | 3 +- crates/kiri/src/ui/lang/hu.json | 3 +- crates/kiri/src/ui/lang/hy.json | 2040 ++++++++++++++++++++++++++ crates/kiri/src/ui/lang/id.json | 3 +- crates/kiri/src/ui/lang/it.json | 3 +- crates/kiri/src/ui/lang/ja.json | 3 +- crates/kiri/src/ui/lang/kk.json | 3 +- crates/kiri/src/ui/lang/ko.json | 3 +- crates/kiri/src/ui/lang/lo.json | 3 +- crates/kiri/src/ui/lang/lt.json | 3 +- crates/kiri/src/ui/lang/nb.json | 3 +- crates/kiri/src/ui/lang/ne.json | 3 +- crates/kiri/src/ui/lang/pl.json | 3 +- crates/kiri/src/ui/lang/pt-BR.json | 3 +- crates/kiri/src/ui/lang/ro.json | 3 +- crates/kiri/src/ui/lang/ru.json | 3 +- crates/kiri/src/ui/lang/sl.json | 3 +- crates/kiri/src/ui/lang/sq.json | 3 +- crates/kiri/src/ui/lang/ta.json | 3 +- crates/kiri/src/ui/lang/te.json | 3 +- crates/kiri/src/ui/lang/th.json | 3 +- crates/kiri/src/ui/lang/tr.json | 3 +- crates/kiri/src/ui/lang/uk.json | 3 +- crates/kiri/src/ui/lang/uz.json | 3 +- crates/kiri/src/ui/lang/vi.json | 3 +- crates/kiri/src/ui/lang/zh-Hans.json | 3 +- crates/kiri/src/ui/lang/zh-Hant.json | 3 +- crates/kiri/src/ui/langstep.js | 13 +- tests/ui/langmenu-search.js | 2 +- tests/ui/langpick.js | 6 +- tests/ui/langstep.js | 12 +- tests/ui/langswitch.js | 4 +- tests/ui/nav-beta-tag.js | 2 +- tests/ui/routerports.js | 16 + tests/ui/setup-langstep.js | 6 +- 53 files changed, 4216 insertions(+), 66 deletions(-) create mode 100644 crates/kiri/src/ui/lang/az.json create mode 100644 crates/kiri/src/ui/lang/hy.json diff --git a/README.md b/README.md index 60c359be7..d25a53d3e 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Latest release Apache 2.0 License Discord - 40 languages + 42 languages

@@ -103,7 +103,7 @@ comes from the Igbo word *ntakịrị*, "small". - **Local domains**: `http://.kiri.local`, with HTTPS from Kiri's own certificate authority. - **More than containers**: a one-command Kubernetes cluster and Linux machines. - **A native window** for containers, images, volumes and networks, plus a menu bar item. -- **In your language**: the window comes in 40 languages, on macOS, Windows and Linux alike. +- **In your language**: the window comes in 42 languages, on macOS, Windows and Linux alike. --- diff --git a/crates/kiri-win/src/setup.html b/crates/kiri-win/src/setup.html index 213f19572..55d5884e6 100644 --- a/crates/kiri-win/src/setup.html +++ b/crates/kiri-win/src/setup.html @@ -27,7 +27,8 @@ [lang|=ja]{--f-text:"Segoe UI Variable Text","Segoe UI","Yu Gothic UI","Meiryo UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Yu Gothic UI","Meiryo UI",sans-serif} [lang|=ko]{--f-text:"Segoe UI Variable Text","Segoe UI","Malgun Gothic",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Malgun Gothic",sans-serif} [lang|=ko]{word-break:keep-all} -/* India's scripts in Nirmala UI, Windows' face for them; Thai and Lao in Leelawadee UI; Ethiopic in Ebrima. */ +/* India's scripts in Nirmala UI, Windows' face for them; Thai and Lao in Leelawadee UI; Ethiopic in Ebrima; Armenian in Sylfaen. */ +[lang|=hy]{--f-text:"Segoe UI Variable Text","Segoe UI","Noto Sans Armenian","Mshtakan","Sylfaen",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Noto Sans Armenian","Mshtakan","Sylfaen",sans-serif} [lang|=am]{--f-text:"Segoe UI Variable Text","Segoe UI","Ebrima","Nyala",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Ebrima","Nyala",sans-serif} [lang|=th],[lang|=lo]{--f-text:"Segoe UI Variable Text","Segoe UI","Leelawadee UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Leelawadee UI",sans-serif} [lang|=hi],[lang|=ne],[lang|=bn],[lang|=ta],[lang|=te]{--f-text:"Segoe UI Variable Text","Segoe UI","Nirmala UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Nirmala UI",sans-serif} diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index 9791bc0d3..1e2bcb969 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -1212,6 +1212,7 @@ .about dt { color: var(--muted); } .about dd { font-variant-numeric: tabular-nums; } .about a { color: var(--blue-light); cursor: pointer; text-decoration: none; } +.about .soc-i { width: 13px; height: 13px; vertical-align: -2px; margin-inline-end: 4px; opacity: .88; } /* The setup checklist: Linux opens on it until Kiri can run containers; the Mac shows it over a working window when a first-launch step failed (onboarding()). */ #onb { position: fixed; inset: 0; z-index: 30; background: var(--bg); overflow: auto; display: grid; place-items: start center; } @@ -2808,6 +2809,7 @@

Containers

Containers

${tr("Storage location unavailable")}

${tr("Memory")}
${a?.running ? tr("up to {size}", { size: mib(a.memory) }) : "—"}
${tr("Website")}
runkiri.com
${tr("Made by")}
Canestack Labs
+
${tr("Community")}
Discord · @runkiri

${tr("The name comes from the Igbo word ntakịrị, “small”.")}

${canUninstall ? `
${tr("Uninstall Kiri")} diff --git a/crates/kiri/src/ui/lang.rs b/crates/kiri/src/ui/lang.rs index a5b5fa4e0..8e32082c0 100644 --- a/crates/kiri/src/ui/lang.rs +++ b/crates/kiri/src/ui/lang.rs @@ -21,7 +21,8 @@ use std::sync::OnceLock; /// Every translation Kiri ships, by language tag, as lang/.json maps /// English to it. English itself has no file. -pub const FILES: [(&str, &str); 39] = [ +pub const FILES: [(&str, &str); 41] = [ + ("az", include_str!("lang/az.json")), ("id", include_str!("lang/id.json")), ("ca", include_str!("lang/ca.json")), ("cs", include_str!("lang/cs.json")), @@ -46,6 +47,7 @@ pub const FILES: [(&str, &str); 39] = [ ("ru", include_str!("lang/ru.json")), ("uk", include_str!("lang/uk.json")), ("kk", include_str!("lang/kk.json")), + ("hy", include_str!("lang/hy.json")), ("ar", include_str!("lang/ar.json")), ("fa", include_str!("lang/fa.json")), ("ckb", include_str!("lang/ckb.json")), @@ -412,6 +414,13 @@ mod tests { ("uz-UZ", Some("uz")), ("uz-Latn-UZ", Some("uz")), ("uz_UZ", Some("uz")), + ("az", Some("az")), + ("az-AZ", Some("az")), + ("az-Latn-AZ", Some("az")), + ("az_AZ", Some("az")), + ("hy", Some("hy")), + ("hy-AM", Some("hy")), + ("hy_AM", Some("hy")), ("fa-IR", Some("fa")), ("fa", Some("fa")), ("ckb", Some("ckb")), diff --git a/crates/kiri/src/ui/lang/am.json b/crates/kiri/src/ui/lang/am.json index effee4283..64e53c665 100644 --- a/crates/kiri/src/ui/lang/am.json +++ b/crates/kiri/src/ui/lang/am.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiriን ማራገፍ አልተቻለም፦ {error}", "Uninstall Kiri using your system package manager": "የሥርዓትዎን የጥቅል አስተዳዳሪ በመጠቀም Kiriን ያራግፉ", "Swap": "ስዋፕ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "የVM ማህደረ ትውስታ ሲያልቅ VM ሊጠቀምበት የሚችል የዲስክ ቦታ፣ ስለዚህ ኮንቴይነሮች ከመቆም ይልቅ ይዘገያሉ። ዳግም ሲጀመር ይተገበራል።" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "የVM ማህደረ ትውስታ ሲያልቅ VM ሊጠቀምበት የሚችል የዲስክ ቦታ፣ ስለዚህ ኮንቴይነሮች ከመቆም ይልቅ ይዘገያሉ። ዳግም ሲጀመር ይተገበራል።", + "Community": "ማኅበረሰብ" } diff --git a/crates/kiri/src/ui/lang/ar.json b/crates/kiri/src/ui/lang/ar.json index 3326dc3b5..5003bfcd7 100644 --- a/crates/kiri/src/ui/lang/ar.json +++ b/crates/kiri/src/ui/lang/ar.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "تعذرت إزالة تثبيت Kiri: {error}", "Uninstall Kiri using your system package manager": "أزِل تثبيت Kiri باستخدام مدير الحزم في نظامك", "Swap": "التبديل (Swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "مساحة على القرص يمكن للجهاز الافتراضي استخدامها عند نفاد ذاكرته، فتتباطأ الحاويات بدلًا من إيقافها. يُطبَّق عند إعادة التشغيل." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "مساحة على القرص يمكن للجهاز الافتراضي استخدامها عند نفاد ذاكرته، فتتباطأ الحاويات بدلًا من إيقافها. يُطبَّق عند إعادة التشغيل.", + "Community": "المجتمع" } diff --git a/crates/kiri/src/ui/lang/az.json b/crates/kiri/src/ui/lang/az.json new file mode 100644 index 000000000..ceb3ba1d5 --- /dev/null +++ b/crates/kiri/src/ui/lang/az.json @@ -0,0 +1,2040 @@ +{ + " (current step)": " (cari addım)", + " (done)": " (bitdi)", + " ({port} was in use)": " ({port} portu istifadədə idi)", + " That's {count} crashes since Kiri last opened.": " Kiri son dəfə açılandan bəri {count} çökmə baş verib.", + " and ": " və ", + " or ": " və ya ", + "(no description)": "(təsvir yoxdur)", + "(no message)": "(mesaj yoxdur)", + "(read-only)": "(yalnız oxumaq üçün)", + "(was {value})": "(əvvəlki: {value})", + "* Estimates until measured on a clean PC.": "* Yeni quraşdırılmış sistemli kompüterdə ölçülənədək göstəricilər təxminidir.", + "+ A complete Linux you can open from Start": "+ Başlat menyusundan aça biləcəyiniz tam funksional Linux", + "+ Already have Ubuntu? Kiri uses it: nothing to download": "+ Artıq Ubuntu quraşdırılıb? Kiri ondan istifadə edir: heç nə endirməyə ehtiyac yoxdur", + "+ No Microsoft Store, no username or password": "+ Microsoft Store-a ehtiyac yoxdur, istifadəçi adı və ya şifrə tələb olunmur", + "+ Removed completely when you remove Kiri": "+ Kiri silindikdə tamamilə silinir", + "+ Uses the Ubuntu you already have: nothing to download": "+ Mövcud Ubuntu-dan istifadə edir: heç nə endirməyə ehtiyac yoxdur", + "+{n} more": "+ daha {n}", + ", ": ", ", + "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Kiri ilə qurun. docker build və docker compose build Kiri-də işləyir və imiclər Kiri-də saxlanılır. {engine} onları görməyəcək. İstədiyiniz vaxt Tənzimləmələr → Qurmalar bölməsindən dəyişə bilərsiniz.", + "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Docker ilə qurmağa davam edin. Heç nə dəyişmir: docker build indi harada qurursa, orada da qurur və imiclər {engine} daxilində qalır.", + "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "Saxlanılanlar: konteynerin özü, faylları, imici, portları, verilənlər həcmləri, şəbəkəsi və yenidən başlatma siyasəti.", + "docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.": "docker hələ də {engine} ilə işləyir, buna görə terminalda işə saldıqlarınız burada görünməyəcək. İmiclərinizi buraya köçürə bilərsiniz.", + "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node, Kubernetes-i Docker daxilində işlədən kind alətinin düyün imicidir. kind onu imtiyazlı rejim və lazımi tənzimləmələrlə sizin üçün başladır. Təkbaşına başladılsa, bu {mount} nöqtəsində dayanır.", + "{name} has {list} that aren't in Kiri yet.": "{name} daxilində {list} var və onlar hələ Kiri-də yoxdur.", + "{name} isn't answering on {addr}, so visitors get an error page. Is the app inside it running?": "{name} cavab vermir (ünvan: {addr}), buna görə də ziyarətçilər xəta səhifəsi görür. Daxilindəki tətbiq işləyir?", + "{name} isn't answering, so visitors get an error page. Is the app inside it running?": "{name} cavab vermir, buna görə də ziyarətçilər xəta səhifəsi görür. Daxilindəki tətbiq işləyir?", + "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "Bu portlardan birini yayımlayan konteyner həmin portu tutur; port boşalanadək həmin port üzərindən adla müraciət dayandırılır.", + "A couple more steps: set them up, or skip.": "Daha bir neçə addım qalıb: quraşdırmanı tamamlayın və ya bu addımları ötürün.", + "A deployment (its ReplicaSet)": "Deployment (onun ReplicaSet-i)", + "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri-dəki cihaz siz onu ayırana qədər Windows-da görünmür. Konteynerdə: --device /dev/ttyUSB0 (serial), /dev/input (HID) və ya /dev/bus/usb (raw).", + "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri-dəki cihaz siz onu ayırana qədər Mac-da görünmür. Konteynerdə: --device /dev/ttyUSB0 (serial), /dev/input (HID) və ya /dev/bus/usb (raw).", + "A few things need fixing before Kiri can run containers.": "Kiri-nin konteynerləri işlədə bilməsi üçün bir neçə şey düzəldilməlidir.", + "A kiri command": "kiri komandası", + "A kiri command crashed": "kiri komandası çökdü", + "A proxy on this Mac is reached as {host}.": "Bu Mac-dakı proksiyə {host} ünvanından qoşulmaq olar.", + "A service sends traffic to this pod": "Bir xidmət bu pod-a trafik yönləndirir", + "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "kubectl-in {context} konteksti üçün bir konteyner daxilində tək düyünlü klaster (k3s). Söndürdükdə klaster dayanır, vəziyyəti isə saxlanılır.", + "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "Bir konteynerdə tək düyünlü klaster (k3s). Təxminən 20 san çəkir; ilk dəfə k3s endirildiyi üçün daha uzun çəkə bilər.", + "A small, fast container runtime.": "Kiçik və sürətli konteyner icra mühiti.", + "A tiny Linux made only for Kiri, built from Alpine. It stays out of sight and leaves with Kiri.": "Yalnız Kiri üçün hazırlanmış, Alpine əsaslı kiçik bir Linux. Gözə dəymir və Kiri silindikdə onunla birlikdə silinir.", + "API on {addr}": "API ünvanı: {addr}", + "API server": "API serveri", + "API server port": "API server portu", + "AWS didn't accept that code. Wait for the next one and try again.": "AWS bu kodu qəbul etmədi. Növbəti kodu gözləyin və yenidən cəhd edin.", + "AWS profile": "AWS profili", + "About": "Haqqında", + "Accent": "Vurğu rəngi", + "Accept the SQL Server licence": "SQL Server lisenziyasını qəbul et", + "Access token": "Giriş tokeni", + "Access token or password": "Giriş tokeni və ya şifrə", + "Action {op}": "Əməliyyat: {op}", + "Actions": "Əməliyyatlar", + "Actual Size": "Faktiki ölçü", + "Add": "Əlavə et", + "Add it to WSL": "WSL-ə əlavə et", + "Add port": "Port əlavə et", + "Added by this build": "Bu build tərəfindən əlavə edilib", + "Added in this image": "Bu imicdə əlavə edilib", + "Additional certificate names": "Əlavə sertifikat adları", + "Administrator approval": "Administrator təsdiqi", + "After the restart": "Yenidən başlatmadan sonra", + "Age": "Keçən vaxt", + "All": "Hamısı", + "All languages · {n}": "Bütün dillər · {n}", + "All levels": "Bütün səviyyələr", + "All statuses": "Bütün statuslar", + "All steps": "Bütün addımlar", + "All {kind}": "Bütün {kind}", + "Allow access": "Girişə icazə ver", + "Allow an empty password": "Boş şifrəyə icazə ver", + "Already there": "Artıq mövcuddur", + "Always send crash reports": "Çökmə hesabatlarını həmişə göndər", + "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR şifrə deyil, token tələb edir: istifadəçi adı {user} olur, token isə {cmd} əmrindən alınır. 12 saat etibarlıdır.", + "Anchore, open source": "Anchore, açıq mənbəli", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "Sonradan {build} üçün başqa qurucu seçilib ({use}). Kiri-də qurmaq üçün yenidən Kiri-ni seçin.", + "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "127.0.0.1:53 başqa proqram tərəfindən tutulub, ona görə də Kiri .kiri.local üçün cavab verə bilmir; konteynerlər .kiri.localhost ünvanında qalır", + "Answers on /run/kiri/docker.sock": "/run/kiri/docker.sock üzərindən cavab verir", + "Anyone who can reach the port signs in as root.": "Porta çıxışı olan hər kəs root kimi daxil olur.", + "Anyone with this link can open it while Kiri is running.": "Bu keçidə sahib olan hər kəs Kiri işlədiyi müddətdə onu aça bilər.", + "Appearance": "Görünüş", + "Applies after you log out and back in": "Hesabdan çıxıb yenidən daxil olduqdan sonra tətbiq edilir", + "Apply…": "Tətbiq et…", + "Asking {host} for {ref}…": "{host} serverindən {ref} sorğulanır…", + "Asks for your password once": "Şifrənizi bir dəfə soruşur", + "Asleep": "Yuxuda", + "Attach": "Qoş", + "Attach it to see where it shows up in Linux.": "Linux-da harada göründüyünü bilmək üçün onu qoşun.", + "Attached": "Qoşuldu", + "Attaching…": "Qoşulur…", + "Audio": "Səs", + "Back": "Geri", + "Back (Esc)": "Geri (Esc)", + "Back to Share": "Paylaşıma qayıt", + "Back to editing": "Redaktəyə qayıt", + "Base image": "Əsas imic", + "Beta": "Beta", + "Bigger": "Daha böyük", + "Blue": "Mavi", + "Bring all my {engine} images to {app}": "Bütün {engine} imiclərimi {app} tətbiqinə gətir", + "Bring images, volumes and containers over to Kiri.": "İmicləri, verilənlər həcmlərini və konteynerləri Kiri-yə köçürün.", + "Bring your {name} things to Kiri": "{name} elementlərinizi Kiri-yə gətirin", + "Bringing your images over from {engine}: {done} of {total}.": "İmicləriniz {engine} mühitindən köçürülür: {done} / {total}.", + "Brought {n} item over from {engine}.": "{engine} mühitindən {n} element köçürüldü.", + "Brought {n} item over from {engine}; {failed} failed (Settings → Import says why).": "{engine} mühitindən {n} element köçürüldü; {failed} uğursuz oldu (səbəbi Tənzimləmələr → İdxal bölməsindədir).", + "Brought {n} items over from {engine}.": "{engine} mühitindən {n} element köçürüldü.", + "Brought {n} items over from {engine}; {failed} failed (Settings → Import says why).": "{engine} mühitindən {n} element köçürüldü; {failed} uğursuz oldu (səbəbi Tənzimləmələr → İdxal bölməsindədir).", + "Browsers see a short Kiri Cloud notice page first.": "Brauzerdə əvvəlcə Kiri Cloud-un qısa bildiriş səhifəsi açılır.", + "Build cache cleared": "Qurma keşi təmizləndi", + "Build cache cleared: freed {size}": "Qurma keşi təmizləndi: {size} yer boşaldıldı", + "Build context": "Qurma konteksti", + "Build record": "Qurma qeydi", + "Build with": "Qurucu", + "Build with Kiri": "Kiri ilə qur", + "Build with Kiri.": "Kiri ilə qurun.", + "BuildKit starts if it's asleep.": "BuildKit yuxu rejimindədirsə, işə düşür.", + "BuildKit {size}": "BuildKit {size}", + "BuildKit {size} and its build cache": "BuildKit {size} və onun qurma keşi", + "Building": "Qurulur", + "Builds": "Qurmalar", + "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build ilə başlatdığınız qurmalar hər addımın müddəti, keşi və çıxışı ilə birlikdə burada görünür.", + "Built from source": "Mənbə kodundan qurulub", + "Bus {bus} · Device {dev}": "Şin {bus} · Cihaz {dev}", + "By name, no ports.": "Port göstərmədən, adla.", + "By port. Nothing to set up.": "Port vasitəsilə. Əlavə tənzimləmə tələb olunmur.", + "Bypass for": "Proksisiz ünvanlar", + "CLI": "CLI", + "CPU": "CPU", + "CPU is a share of all {n} cores: 100% would be every core busy.": "CPU istifadəsi bütün {n} nüvənin ümumi gücünə görə hesablanır: 100% bütün nüvələrin tam yüklənməsi deməkdir.", + "CPUs": "CPU-lar", + "Cached": "Keşlənmiş", + "Camera": "Kamera", + "Can't be shared": "Paylaşıla bilməz", + "Can't be shared yet": "Hələ paylaşıla bilməz", + "Can't reach Docker Hub right now.": "Hazırda Docker Hub ilə əlaqə yaratmaq mümkün deyil.", + "Cancel": "Ləğv et", + "Cancel download": "Endirməni ləğv et", + "Cancel pull": "Endirməni ləğv et", + "Canceled": "Ləğv edildi", + "Cancelled": "Ləğv edildi", + "Cancelled. Nothing was added; layers that finished are kept for the next pull.": "Ləğv edildi. Heç nə əlavə olunmadı; tamamlanmış təbəqələr növbəti endirmə üçün saxlanılır.", + "Change ports": "Portları dəyiş", + "Changing it restarts the cluster.": "Bunu dəyişmək klasteri yenidən başladır.", + "Changing this asks Windows for an administrator's approval, since it adds or removes a DNS rule for {local}.": "Bu tənzimləmə dəyişdirildikdə Windows administrator təsdiqi istəyir, çünki {local} üçün DNS qaydası əlavə olunur və ya silinir.", + "Changing this needs admin rights (an administrator password), since it adds or removes {path}.": "Bu tənzimləməni dəyişmək administrator hüquqları (administrator şifrəsi) tələb edir, çünki {path} faylı əlavə olunur və ya silinir.", + "Check for Updates…": "Yeniləmələri yoxla…", + "Check for updates automatically": "Yeniləmələri avtomatik yoxla", + "Check now": "İndi yoxla", + "Check the spelling, or paste a full reference like {ref}.": "Yazılışı yoxlayın və ya {ref} kimi tam istinad yapışdırın.", + "Checked once the engine runs": "Engine işə düşdükdə yoxlanılır", + "Checked once your account can use Kiri": "Hesabınız Kiri-dən istifadə edə bildikdə yoxlanılır", + "Checking the code with AWS…": "Kod AWS ilə yoxlanılır…", + "Checking your plan…": "Planınız yoxlanılır…", + "Checking…": "Yoxlanılır…", + "Choose a Linux": "Bir Linux seçin", + "Choose and install": "Seç və quraşdır", + "Choose what to bring…": "Köçürüləcəkləri seçin…", + "Choose your language": "Dilinizi seçin", + "Clear": "Təmizlə", + "Clear build cache": "Qurma keşini təmizlə", + "Clear the selection": "Seçimi təmizlə", + "Clear the selection (Esc)": "Seçimi təmizlə (Esc)", + "Clear {n} failed": "Uğursuz {n} elementi təmizlə", + "Clearing…": "Təmizlənir…", + "Close": "Bağla", + "Close ({keys})": "Bağla ({keys})", + "Close Window": "Pəncərəni bağla", + "Close find": "Axtarışı bağla", + "Close pane": "Paneli bağla", + "Close tab": "Vərəqi bağla", + "Close this scan": "Bu skanı bağla", + "Close to your plan's speed limit": "Planınızın sürət limitinə yaxındır", + "Cluster IP": "Klaster IP-si", + "Collapse all": "Hamısını yığ", + "Command": "Əmr", + "Command to run in the container": "Konteynerdə icra olunacaq əmr", + "Completed": "Tamamlandı", + "Compose project {project} made it: {cmd} puts back what the compose file says, so change it there too.": "Bunu {project} Compose layihəsi yaradıb: {cmd} əmri compose faylında yazılanları geri qaytarır, ona görə də dəyişikliyi orada da edin.", + "Compose services answer at {addr}.": "Compose xidmətləri {addr} ünvanında cavab verir.", + "Connect Windows to it": "Windows-u ona qoş", + "Connecting…": "Qoşulur…", + "Connection lost.": "Bağlantı kəsildi.", + "Container": "Konteyner", + "Container files are not on Windows' disk: use Save to Downloads": "Konteyner faylları Windows diskində deyil: “Endirilənlərə saxla” seçimini edin", + "Container list": "Konteyner siyahısı", + "Container port {q}{port}{q} is not a port number (1–65535).": "Konteyner portu {q}{port}{q} düzgün port nömrəsi deyil (1–65535).", + "Container traffic leaves through WSL's network.": "Konteyner trafiki WSL şəbəkəsi üzərindən çıxır.", + "Container, Kubernetes and diagnostics logs.": "Konteyner, Kubernetes və diaqnostika jurnalları.", + "Containers": "Konteynerlər", + "Containers answer at .kiri.localhost": "Konteynerlər .kiri.localhost ünvanında cavab verir", + "Containers now answer at .kiri.local": "Konteynerlər artıq .kiri.local ünvanında cavab verir", + "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "Konteynerlər bu kompüterin öz nüvəsində işləyir və USB cihazlarını birbaşa görür. Göstərilən yolu docker run --device əmrinə əlavə edin.", + "Containers see it": "Konteynerlər onu görür", + "Containers you start with docker run or Compose show up here, with the {context} context.": "{context} kontekstində docker run və ya Compose ilə başlatdığınız konteynerlər burada görünür.", + "Continue": "Davam et", + "Continue with GitHub": "GitHub ilə davam et", + "Controlled by": "İdarə edən", + "Copied": "Kopyalandı", + "Copied {text}": "Kopyalandı: {text}", + "Copy": "Kopyala", + "Copy ID": "ID-ni kopyala", + "Copy link": "Keçidi kopyala", + "Copy {what}": "Kopyala: {what}", + "Could not change container names: {error}": "Konteyner adları dəyişdirilə bilmədi: {error}", + "Could not change the certificate's trust: {error}": "Sertifikata etibar tənzimləməsi dəyişdirilə bilmədi: {error}", + "Could not change the ports: {error}": "Portlar dəyişdirilə bilmədi: {error}", + "Could not open Terminal: {error}": "Terminal açıla bilmədi: {error}", + "Could not open a terminal: {error}": "Terminal açıla bilmədi: {error}", + "Could not restart WSL: {error}": "WSL yenidən başladıla bilmədi: {error}", + "Could not restart the VM: {error}": "VM yenidən başladıla bilmədi: {error}", + "Could not restart the engine: {error}": "Mühərrik yenidən başladıla bilmədi: {error}", + "Could not save .wslconfig: {error}": ".wslconfig saxlanıla bilmədi: {error}", + "Could not save the SBOM: {error}": "SBOM saxlanıla bilmədi: {error}", + "Could not save the file: {error}": "Fayl saxlanıla bilmədi: {error}", + "Could not save the proxy settings: {error}": "Proksi tənzimləmələri saxlanıla bilmədi: {error}", + "Could not save the registry settings: {error}": "Reyestr tənzimləmələri saxlanıla bilmədi: {error}", + "Could not save the setting to {path}": "Tənzimləməni {path} yolunda saxlamaq mümkün olmadı", + "Could not save the setting to ~/.kiri/ui.json": "Tənzimləməni ~/.kiri/ui.json faylında saxlamaq mümkün olmadı", + "Could not save: {error}": "Saxlanıla bilmədi: {error}", + "Couldn't change which builder docker build uses: {error}": "docker build əmrinin istifadə etdiyi qurucu dəyişdirilə bilmədi: {error}", + "Couldn't check for updates: {error}": "Yeniləmələr yoxlanıla bilmədi: {error}", + "Couldn't check: {error}": "Yoxlanıla bilmədi: {error}", + "Couldn't clear the build cache: {error}": "Qurma keşi təmizlənə bilmədi: {error}", + "Couldn't copy to the clipboard": "Mübadilə buferinə kopyalana bilmədi", + "Couldn't download it: {error}": "Endirilə bilmədi: {error}", + "Couldn't list the tags": "Teqlər siyahılana bilmədi", + "Couldn't read the USB devices": "USB cihazları barədə məlumat oxuna bilmədi", + "Couldn't read the build history": "Qurma tarixçəsi oxuna bilmədi", + "Couldn't remove the build: {error}": "Qurma silinə bilmədi: {error}", + "Couldn't save it: {error}": "Saxlanıla bilmədi: {error}", + "Couldn't save the report: {error}": "Hesabat saxlanıla bilmədi: {error}", + "Couldn't send it: {error}": "Göndərilə bilmədi: {error}", + "Couldn't send the crash report: {error}": "Çökmə hesabatı göndərilə bilmədi: {error}", + "Couldn't set up the Docker tools": "Docker alətləri quraşdırıla bilmədi", + "Couldn't share": "Paylaşıla bilmədi", + "Couldn't share service {name}: it's gone": "{name} xidməti paylaşıla bilmədi: artıq mövcud deyil", + "Couldn't share {name}": "{name} paylaşıla bilmədi", + "Couldn't share {name}: Kiri couldn't tell which port it listens on. Publish one from its page.": "{name} paylaşıla bilmədi: Kiri onun hansı portu dinlədiyini müəyyən edə bilmədi. Səhifəsindən bir port yayımlayın.", + "Couldn't share {name}: it stopped": "{name} paylaşıla bilmədi: dayandı", + "Couldn't share {name}: it's gone": "{name} paylaşıla bilmədi: artıq mövcud deyil", + "Couldn't share {name}: {reason}": "{name} paylaşıla bilmədi: {reason}", + "Couldn't start {shell}: {error}": "{shell} başladıla bilmədi: {error}", + "Couldn't stop {name}: {error}": "{name} dayandırıla bilmədi: {error}", + "Couldn't switch docker: {error}": "docker dəyişdirilə bilmədi: {error}", + "Crash reports": "Çökmə hesabatları", + "Crashed (139)": "Çökdü (139)", + "Create a diagnostics report": "Diaqnostika hesabatı yarat", + "Create report…": "Hesabat yarat…", + "Created": "Yaradılıb", + "Critical": "Kritik", + "Custom": "Fərdi", + "Cut": "Kəs", + "Dark": "Tünd", + "Database": "Verilənlər bazası", + "Debug": "Sazlama", + "Delete": "Sil", + "Delete cluster": "Klasteri sil", + "Delete pod {name}?": "{name} pod-u silinsin?", + "Delete the Kubernetes cluster?": "Kubernetes klasteri silinsin?", + "Delete {what}?": "{what} silinsin?", + "Deleting": "Silinir", + "Deleting Kubernetes": "Kubernetes silinir", + "Deleting pod {pod}": "Pod silinir: {pod}", + "Deleting…": "Silinir…", + "Deployment {name} runs this pod": "Bu pod-u {name} deployment-i işlədir", + "Detach": "Ayır", + "Detaching…": "Ayrılır…", + "Details": "Təfərrüatlar", + "Device": "Cihaz", + "Diagnostics": "Diaqnostika", + "Diagnostics report": "Diaqnostika hesabatı", + "Did you mean {name}?": "Nəzərdə tutduğunuz {name} idi?", + "Didn't pull": "Endirilmədi", + "Didn't pull.": "Endirilmədi.", + "Disconnect": "Bağlantını kəs", + "Disconnecting…": "Bağlantı kəsilir…", + "Dismiss": "Bağla", + "Docker Desktop": "Docker Desktop", + "Docker Hub can't be reached": "Docker Hub ilə əlaqə yaratmaq olmur", + "Docker Hub has no image called {name}.": "Docker Hub-da {name} adlı imic yoxdur.", + "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub imicləri bu güzgülərdən ardıcıllıqla çəkilir; imicə sahib ilk güzgü cavab verir, əks halda Docker Hub-ın özü istifadə olunur. Digər reyestrlərdən birbaşa çəkilir.", + "Docker tools": "Docker alətləri", + "Docker tools are ready": "Docker alətləri hazırdır", + "Docker's default engine": "Docker-in standart mühərriki", + "Docker's own page signs you in. Check that it shows this code:": "Girişi Docker-in öz səhifəsi həyata keçirir. Orada bu kodun göstərildiyini yoxlayın:", + "Docs": "Sənədləşmə", + "Domains": "Domenlər", + "Done": "Bitdi", + "Download": "Endir", + "Download Ubuntu": "Ubuntu-nu endir", + "Download WSL": "WSL-i endir", + "Download the new .deb or .rpm": "Yeni .deb və ya .rpm faylını endir", + "Downloading Grype, the scanner (about 30 MB, once)": "Grype skaneri endirilir (təxminən 30 MB, yalnız bir dəfə)", + "Downloading Ubuntu 26.04": "Ubuntu 26.04 endirilir", + "Downloading {name} from {source}": "{name} endirilir (mənbə: {source})", + "Downloading {version}": "Endirilir: {version}", + "Downloading…": "Endirilir…", + "Drag to resize": "Ölçünü dəyişmək üçün dartın", + "Drag to resize, double-click to reset": "Ölçünü dəyişmək üçün dartın, ilkin ölçüyə qaytarmaq üçün iki dəfə klikləyin", + "Driver": "Drayver", + "Duration": "Müddət", + "Edit": "Redaktə et", + "Ended: pod deleted": "Bitdi: pod silindi", + "Ended: pod restarted · share the service to keep a link": "Bitdi: pod yenidən başladı · keçidi qorumaq üçün xidməti paylaşın", + "Ended: service deleted": "Bitdi: xidmət silindi", + "Engine": "Mühərrik", + "Engine running": "Mühərrik işləyir", + "Engine updated": "Mühərrik yeniləndi", + "Enter the port the app in the pod listens on, 1 to 65535": "Pod daxilindəki tətbiqin dinlədiyi portu daxil edin (1–65535)", + "Enter this code on GitHub": "Bu kodu GitHub-da daxil edin", + "Enter your MFA code": "MFA kodunuzu daxil edin", + "Environment": "Mühit dəyişənləri", + "Error": "Xəta", + "Errors": "Xətalar", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "İçindəki hər şey silinir: pod-lar, xidmətlər, verilənlər həcmləri və digər resurslar, həmçinin {context} kubectl konteksti. Növbəti başlatma yeni, boş bir klaster yaradır.", + "Everything in the window.": "Pəncərədəki hər şey.", + "Everything is in Kiri.": "Hər şey Kiri-dədir.", + "Exit code": "Çıxış kodu", + "Exited with code {code}, {when}": "{code} kodu ilə çıxdı, {when}", + "Expand all": "Hamısını genişləndir", + "Expose services to LAN": "Xidmətləri LAN şəbəkəsinə aç", + "External": "Xarici", + "Failed": "Uğursuz", + "Failed ({code})": "Uğursuz ({code})", + "Failing": "Xəta verir", + "Feedback": "Rəy", + "Files": "Fayllar", + "Find": "Tap", + "Find ({keys})": "Tap ({keys})", + "Find a path, method or status": "Yol, metod və ya status tap", + "Find in logs": "Jurnallarda tap", + "Find in the terminal": "Terminalda tap", + "Finish updating to Kiri {version}": "Kiri {version} yeniləməsini tamamla", + "Finished": "Tamamlandı", + "Fix all": "Hamısını düzəlt", + "Fixed in": "Düzəldildiyi versiya", + "Fold the sidebar": "Yan paneli yığ", + "Follow": "İzlə", + "Follow {os} (now {lang}), or always use one language.": "{os} sisteminin dilinə uyğunlaşdırın (hazırda {lang}) və ya sabit bir dil seçin.", + "Follow {os}, or always use the dark or light theme.": "{os} sisteminin temasına uyğunlaşdırın və ya həmişə tünd, yaxud açıq temadan istifadə edin.", + "Font": "Şrift", + "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "Bu {host} cihazında Kiri-nin öz Kubernetes klasteri var. Onu yan paneldəki Kubernetes bölməsində yerləşən keçidlə aktivləşdirə bilərsiniz.", + "For pulling and pushing images.": "İmicləri endirmək və göndərmək (push) üçün.", + "Forward": "İrəli", + "Found": "Tapılan", + "Freed {size}": "{size} boşaldıldı", + "Frees {size}": "{size} boşaldır", + "From": "Mənbə", + "From its base image": "Əsas imicindən", + "From the base image": "Əsas imicdən", + "From ubuntu.com, through Microsoft's WSL list.": "ubuntu.com saytından, Microsoft-un WSL siyahısı vasitəsilə.", + "Generate": "Yarat", + "Getting a link…": "Keçid alınır…", + "GitHub opened in your browser. Approve there and you're signed in straight away.": "GitHub brauzerinizdə açıldı. Orada təsdiqləyin və dərhal daxil olacaqsınız.", + "GitHub opened in your browser. Approve there and {what} is shared straight away.": "GitHub brauzerinizdə açıldı. Orada təsdiqləyin və {what} dərhal paylaşılacaq.", + "GitHub's page asks you to let Kiri read your packages. Check that it shows this code:": "GitHub səhifəsi Kiri-nin paketlərinizi oxumasına icazə verməyinizi istəyir. Orada bu kodun göstərildiyini yoxlayın:", + "Give it back to this computer": "Bu kompüterə geri qaytar", + "Give the VM more memory": "VM-ə daha çox yaddaş ayır", + "Give {name} a public https link": "{name} üçün açıq https keçidi yarat", + "Given back to Windows": "Windows-a geri qaytarıldı", + "Given back to the Mac": "Mac-a geri qaytarıldı", + "Go to Containers": "Konteynerlərə keç", + "Gone from Kiri": "Kiri-dən silindi", + "Graphics|process": "Qrafika", + "Green": "Yaşıl", + "Grype, the open-source scanner from Anchore": "Grype — Anchore tərəfindən hazırlanmış açıq mənbəli skaner", + "HTTP proxy": "HTTP proksi", + "HTTPS proxy": "HTTPS proksi", + "Hand it to Kiri's containers": "Kiri konteynerlərinə ötür", + "Has a fix": "Düzəlişi var", + "Have": "Mövcud", + "Headless: there's no cluster address to share. Share one of its pods.": "Headless: paylaşılacaq klaster ünvanı yoxdur. Onun pod-larından birini paylaşın.", + "Health check": "İşləkliyin yoxlanması", + "Helpers|process": "Köməkçilər", + "Hide": "Gizlət", + "Hide ({keys})": "Gizlət ({keys})", + "Hide password": "Şifrəni gizlət", + "Hide the crash report": "Çökmə hesabatını gizlət", + "Hide the terminal ({keys})": "Terminalı gizlət ({keys})", + "Hide until Kiri next opens": "Kiri növbəti dəfə açılana qədər gizlət", + "Hide until {name} has more": "{name} daxilində yeni element olana qədər gizlət", + "Hide {app}": "Gizlət: {app}", + "High": "Yüksək", + "Host or network": "Host və ya şəbəkə", + "How it runs": "Necə işləyir", + "How should you reach your containers?": "Konteynerlərinizə necə müraciət etmək istəyirsiniz?", + "ID": "ID", + "IDs, commands and code.": "ID-lər, əmrlər və kod.", + "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "API serverinin sertifikatına əlavə ediləcək IP ünvanlarını və ya domen adlarını vergüllə ayıraraq daxil edin (məsələn, bu {host} cihazının şəbəkənizdəki ünvanını). Saxladıqda klaster yenidən başladılır.", + "If Kiri's useful, a star on GitHub helps others find it.": "Kiri işinizə yarayırsa, GitHub-da ulduz vermək başqalarının onu tapmasına kömək edir.", + "If it's private, run {cmd} first.": "Əgər özəldirsə, əvvəlcə {cmd} əmrini işə salın.", + "If it's private, sign in first:": "Əgər özəldirsə, əvvəlcə daxil olun:", + "If it's private, {link} first.": "Əgər özəldirsə, əvvəlcə {link}.", + "If it's private, {link}.": "Əgər özəldirsə, {link}.", + "Image": "İmic", + "Image to pull": "Endiriləcək imic", + "Images": "İmiclər", + "Images you pull or build show up here: docker pull alpine, or search above.": "Endirdiyiniz və ya qurduğunuz imiclər burada görünür: docker pull alpine və ya yuxarıda axtarın.", + "Import": "İdxal et", + "Import from": "Mənbə", + "Import {n} item": "{n} elementi idxal et", + "Import {n} items": "{n} elementi idxal et", + "Imported": "İdxal edildi", + "Imported {done}; {failed} failed (hover “Failed” for why).": "İdxal edildi: {done}; uğursuz: {failed} (səbəbi üçün “Uğursuz” üzərinə gəlin).", + "Imported {n} item.": "{n} element idxal edildi.", + "Imported {n} items.": "{n} element idxal edildi.", + "Importing…": "İdxal edilir…", + "In Kiri": "Kiri-də", + "In a container": "Konteynerdə", + "In a week": "Bir həftə sonra", + "In use": "İstifadədədir", + "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "İstifadə olunur: {used}. VM hazırda ən çox {target} yaddaş tuta bilər; konteynerlərin ehtiyacı artdıqca ayrılan yaddaş da artır.", + "In use: {proxy}, except {hosts}.": "İstifadədədir: {proxy} ({hosts} istisna olmaqla).", + "In use: {proxy}.": "İstifadədədir: {proxy}.", + "Included": "Daxildir", + "Info": "Məlumat", + "Info and up": "Məlumat və üstü", + "Insecure registries": "Təhlükəsiz olmayan reyestrlər", + "Inside Linux": "Linux daxilində", + "Install Kiri's engine in it": "Kiri mühərrikini ora quraşdır", + "Install WSL": "WSL-i quraşdır", + "Install usbipd-win": "usbipd-win quraşdır", + "Installed": "Quraşdırıldı", + "Installing": "Quraşdırılır", + "Installing Windows Subsystem for Linux": "Linux üçün Windows Alt Sistemi (WSL) quraşdırılır", + "Installing…": "Quraşdırılır…", + "Installs when you quit Kiri": "Kiri-dən çıxdıqda quraşdırılır", + "Interface font": "İnterfeys şrifti", + "Internal steps": "Daxili addımlar", + "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "Bu imic Linux VM-in özündə dəyişiklik etməyi tələb edir. “İcra et” funksiyası buna icazə vermir. {image} imicinə etibar edirsinizsə, onu {cmd} əmri ilə özünüz başladın.", + "It has no selector, so it picks no pods.": "Seçicisi olmadığı üçün heç bir pod seçmir.", + "It restarts, so open connections drop.": "Yenidən başladılır, ona görə də açıq bağlantılar kəsilir.", + "It stays up while Kiri is running.": "Kiri işlədiyi müddətdə açıq qalır.", + "It takes effect when it next starts.": "Növbəti dəfə işə düşdükdə tətbiq olunur.", + "It works with serial adapters, Zigbee sticks, mice and keyboards; webcams and audio aren't supported yet.": "Ardıcıl port adapterləri, Zigbee adapterləri, siçanlar və klaviaturalarla işləyir; veb-kameralar və səs hələ dəstəklənmir.", + "It wrote nothing to its log.": "Jurnalına heç nə yazmayıb.", + "It's a network interface inside Linux, not a device file.": "Bu, cihaz faylı deyil, Linux daxilində şəbəkə interfeysidir.", + "It's deleted, with its files and unnamed volumes. Named volumes stay.": "Faylları və adsız verilənlər həcmləri ilə birlikdə silinir. Adlandırılmış verilənlər həcmləri qalır.", + "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "Dayandırılır, faylları və adsız verilənlər həcmləri ilə birlikdə silinir. Adlandırılmış verilənlər həcmləri qalır.", + "Its API server stalls or stops answering · {free}": "API serveri ləngiyir və ya cavab verməyi dayandırır · {free}", + "Its container is stopped and deleted, with their files. Named volumes stay.": "Onun konteyneri dayandırılır və faylları ilə birlikdə silinir. Adlandırılmış verilənlər həcmləri qalır.", + "Its containers stop and their files go.": "Konteynerləri dayanır və faylları silinir.", + "Its data is deleted for good.": "Məlumatları həmişəlik silinir.", + "Its deployment starts a new pod in its place.": "Onu idarə edən Deployment yerinə yeni pod başladır.", + "Its job may start it again.": "Onu idarə edən Job onu yenidən başlada bilər.", + "Its last container stopped because {name} wasn't set.": "Son konteyneri {name} təyin edilmədiyi üçün dayandı.", + "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "Düyünü işləyir, lakin API serveri cavab vermir. Məşğul və ya yaddaşı çatışmayan VM buna səbəb ola bilər; Kiri sorğulamağa davam edir.", + "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "Düyünü işləyir, lakin API serveri cavab vermir: {error}. Məşğul və ya yaddaşı çatışmayan VM buna səbəb ola bilər; Kiri sorğulamağa davam edir.", + "Its start script stops when {name} isn't set.": "Başlatma skripti {name} təyin edilmədikdə dayanır.", + "Its start script stops without it: “{why}”.": "Başlatma skripti onsuz dayanır: “{why}”.", + "Its value": "Dəyəri", + "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "{n} konteyneri dayandırılır və faylları ilə birlikdə silinir. Adlandırılmış verilənlər həcmləri qalır.", + "Its {owner} starts a new pod in its place.": "Onu idarə edən {owner} yerinə yeni pod başladır.", + "KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.": "Daemon üçün KIRI_CPUS və ya KIRI_MEMORY_MIB təyin edilib və onlar buradakı tənzimləmələrdən üstündür.", + "Keep": "Saxla", + "Keep building with Docker": "Docker ilə qurmağa davam et", + "Keep building with Docker.": "Docker ilə qurmağa davam edin.", + "Keep typing to search Docker Hub.": "Docker Hub-da axtarmaq üçün yazmağa davam edin.", + "Keep using your PC meanwhile.": "Bu müddətdə kompüterinizdən istifadə etməyə davam edə bilərsiniz.", + "Kept in Credential Manager": "Credential Manager-də saxlanılır", + "Kept in the Keychain": "Keychain-də saxlanılır", + "Kept in {path} with Docker's names, for docker pull, push, login and build. Docker Desktop's file is left alone.": "docker pull, push, login və build üçün Docker adları ilə {path} daxilində saxlanılır. Docker Desktop faylına toxunulmur.", + "Kept {name}: {container} couldn't be removed ({error})": "{name} saxlanıldı: {container} silinə bilmədi ({error})", + "Kept {name}: {error}": "{name} saxlanıldı: {error}", + "Key": "Açar", + "Keyboard": "Klaviatura", + "Killed (137)": "Dayandırıldı (137)", + "Kiri Cloud gives it a public https link through a secure tunnel from this {host}. You sign in with GitHub, so every link traces back to a person. Kiri never sees your password.": "Kiri Cloud bu {host} cihazından təhlükəsiz tunel vasitəsilə ona açıq https keçidi verir. GitHub ilə daxil olursunuz, beləliklə hər keçid bir şəxslə əlaqələndirilir. Kiri şifrənizi heç vaxt görmür.", + "Kiri Setup": "Kiri Quraşdırması", + "Kiri and this Mac": "Kiri və bu Mac", + "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri hələ səs və ya görüntünü ötürə bilmir: konteynerlər ondan heç nə almayacaq.", + "Kiri engine installed": "Kiri mühərriki quraşdırıldı", + "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri imicdəki bütün paketləri (əməliyyat sistemi paketlərini, proqramlaşdırma dili kitabxanalarını və ikili faylları) tapır və təhlükəsizlik boşluqları bazası ilə tutuşdurur. Hələ skan aparılmayıb: ilk skanı başladın.", + "Kiri is not running": "Kiri işləmir", + "Kiri is ready": "Kiri hazırdır", + "Kiri is set up.": "Kiri quraşdırıldı.", + "Kiri quit unexpectedly last time": "Kiri keçən dəfə gözlənilmədən bağlandı", + "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri Grype-ı birbaşa Mac-ınızda işə salaraq öz imic anbarındakı imici yoxlayır. İmic heç bir yerə göndərilmir.", + "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri Linux konteynerlərini WSL daxilində, öz Linux mühitində işlədir. Hər iki seçim eyni konteynerləri eyni sürətlə işlədir; onlar yalnız ölçülərinə və əlavə imkanlarına görə fərqlənir.", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri Linux konteynerlərini Windows-da Docker Desktop olmadan işlədir. Bunun üçün Microsoft-un Linux işlətmə vasitəsi olan Windows Subsystem for Linux (WSL) lazımdır və o, bu PC-də hələ yoxdur.", + "Kiri sets itself up for your Windows account only.": "Kiri yalnız sizin Windows hesabınız üçün quraşdırılır.", + "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Kiri mühərriki işə düşdükdə öz qurucusunu (builder) hazırlayır və həmin andan etibarən qurmalar ora yönləndirilir.", + "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri Docker Hub-a docker əmri ilə daxil olur, lakin bu əmr quraşdırılmayıb. Onu quraşdırın və yenidən cəhd edin.", + "Kiri signs in to GitHub with the GitHub CLI (gh), which isn't installed. Install it, then try again.": "Kiri GitHub-a GitHub CLI (gh) vasitəsilə daxil olur, lakin bu alət quraşdırılmayıb. Onu quraşdırın və yenidən cəhd edin.", + "Kiri started your container.": "Kiri konteynerinizi başlatdı.", + "Kiri started {name} in {time}.": "Kiri {name} konteynerini {time} ərzində başlatdı.", + "Kiri started {name}.": "Kiri {name} konteynerini başlatdı.", + "Kiri uses your AWS profile through the AWS CLI, which isn't installed. Public images still pull.": "Kiri AWS profilinizdən AWS CLI vasitəsilə istifadə edir, lakin AWS CLI quraşdırılmayıb. Açıq imicləri yenə də endirmək mümkündür.", + "Kiri will reuse the Ubuntu already installed on this PC. Kiri runs in it, and you keep opening it as your own Linux.": "Kiri bu kompüterdə artıq quraşdırılmış Ubuntu-dan istifadə edəcək. Kiri onun daxilində işləyəcək, siz də Ubuntu-nu öz Linux mühitiniz kimi açmağa davam edə biləcəksiniz.", + "Kiri {version} is a test build: it doesn't update itself": "Kiri {version} test qurmasıdır: özünü yeniləmir", + "Kiri {version} is available": "Kiri {version} mövcuddur", + "Kiri {version} is downloaded": "Kiri {version} endirildi", + "Kiri {version} is ready to install": "Kiri {version} quraşdırılmağa hazırdır", + "Kiri {version} is the newest version": "Kiri {version} ən yeni versiyadır", + "Kiri's Kubernetes cluster": "Kiri-nin Kubernetes klasteri", + "Kiri's builder": "Kiri-nin qurucusu", + "Kiri's certificate is no longer trusted": "Kiri-nin sertifikatına artıq etibar edilmir", + "Kiri's certificate is trusted: containers open over HTTPS": "Kiri-nin sertifikatına etibar edilir: konteynerlər HTTPS üzərindən açılır", + "Kiri's containers and engine use {used}, of the {total} this computer has.": "Bu kompüterdəki ümumi yaddaş: {total}. Kiri-nin konteynerləri və mühərriki bunun {used} hissəsindən istifadə edir.", + "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "Kiri-nin konteynerləri, mühərriki və agenti WSL-in malik olduğu {total} yaddaşın {used} hissəsini tutur (bunu .wslconfig təyin edir).", + "Kiri's log": "Kiri-nin jurnalı", + "Kiri's logs": "Kiri-nin jurnalları", + "Kiri's own, {name}, is on, so another copy isn't needed.": "Kiri-nin öz klasteri ({name}) aktivdir, buna görə başqa nüsxəyə ehtiyac yoxdur.", + "Kiri: {state}": "Kiri: {state}", + "Kiri’s engine": "Kiri-nin mühərriki", + "Kubernetes cluster": "Kubernetes klasteri", + "Kubernetes deleted, with its state": "Kubernetes öz vəziyyəti ilə birlikdə silindi", + "Kubernetes is busy with another change; try again in a moment": "Kubernetes başqa dəyişikliklə məşğuldur; bir az sonra yenidən cəhd edin", + "Kubernetes is managed in Settings → Kubernetes": "Kubernetes, Tənzimləmələr → Kubernetes bölməsindən idarə olunur", + "Kubernetes is off": "Kubernetes söndürülüb", + "Kubernetes is out of memory": "Kubernetes-in yaddaşı tükənib", + "Kubernetes is running · API on {addr}": "Kubernetes işləyir · API ünvanı: {addr}", + "Kubernetes is running.": "Kubernetes işləyir.", + "Kubernetes is running: {cmd}": "Kubernetes işləyir: {cmd}", + "Kubernetes is short of memory.": "Kubernetes-in yaddaşı çatışmır.", + "Kubernetes is starting": "Kubernetes başladılır", + "Kubernetes is stopping": "Kubernetes dayandırılır", + "Kubernetes isn't answering": "Kubernetes cavab vermir", + "Kubernetes isn't running": "Kubernetes işləmir", + "Kubernetes needs about {need}, and this VM can use {max}, of which {used} is in use.": "Kubernetes-ə təxminən {need} yaddaş lazımdır. Bu VM üçün yaddaş limiti {max} təşkil edir; hazırda {used} istifadə olunur.", + "Kubernetes needs about {need}, and this VM can use {max}.": "Kubernetes-ə təxminən {need} yaddaş lazımdır. Bu VM üçün yaddaş limiti {max} təşkil edir.", + "Kubernetes settings": "Kubernetes tənzimləmələri", + "Kubernetes settings saved. They apply when it next starts.": "Kubernetes tənzimləmələri saxlanıldı. Növbəti başlatmada tətbiq ediləcək.", + "Kubernetes stopped it: it used more memory than it may, or the VM ran out": "Kubernetes onu dayandırdı: icazə verilən yaddaş həddini aşdı və ya VM-in yaddaşı tükəndi", + "Kubernetes stopped. Its state is kept for the next start.": "Kubernetes dayandı. Vəziyyəti növbəti başlatma üçün saxlanılır.", + "Kubernetes: {error}": "Kubernetes: {error}", + "Labels": "Etiketlər", + "Language": "Dil", + "Large": "Böyük", + "Later": "Daha sonra", + "Later installs it when you quit Kiri.": "“Daha sonra” seçsəniz, yeniləmə Kiri-dən çıxdıqda quraşdırılacaq.", + "Later: Kiri waits in the tray and picks up after your next restart.": "Daha sonra: Kiri sistem treyində gözləyir və növbəti yenidən başlatmadan sonra davam edir.", + "Layer": "Təbəqə", + "Layers": "Təbəqələr", + "Let it pick a random one": "Təsadüfi birini seçsin", + "Lets {user} run containers without sudo": "{user} istifadəçisinə sudo olmadan konteyner işlətməyə imkan verir", + "Level": "Səviyyə", + "Light": "Açıq", + "Linux VM": "Linux VM", + "Linux VM: {state}": "Linux VM: {state}", + "Linux account": "Linux hesabı", + "Linux for Kiri": "Kiri üçün Linux", + "Linux hasn't made a device for it yet.": "Linux hələ onun üçün cihaz faylı yaratmayıb.", + "Linux stopped a process for memory": "Linux yaddaş çatışmazlığına görə bir prosesi dayandırdı", + "Listening on {ports}": "Dinlənilən portlar: {ports}", + "Live": "Aktiv", + "Live · waiting for the first visitor": "Aktiv · ilk ziyarətçi gözlənilir", + "Live|stream": "Canlı", + "Loading tags…": "Teqlər yüklənir…", + "Loading the steps…": "Addımlar yüklənir…", + "Loading…": "Yüklənir…", + "Local names": "Yerli adlar", + "Location": "Məkan", + "Log lines for this action": "Bu əməliyyat üçün jurnal sətirləri", + "Log out now": "İndi hesabdan çıx", + "Log out to finish": "Tamamlamaq üçün hesabdan çıxın", + "Log text": "Jurnal mətni", + "Logs": "Jurnallar", + "Logs: {error}": "Jurnallar: {error}", + "Looking for Kubernetes…": "Kubernetes axtarılır…", + "Looking for OrbStack and Docker Desktop…": "OrbStack və Docker Desktop axtarılır…", + "Looking for USB devices…": "USB cihazları axtarılır…", + "Looking for crash reports…": "Çökmə hesabatları axtarılır…", + "Looking for shells…": "Shell-lər axtarılır…", + "Low": "Aşağı", + "MFA code": "MFA kodu", + "Mac": "Mac", + "Made by": "Yaradan", + "Make Kiri the default": "Kiri-ni standart et", + "Make Kiri the default for docker": "Kiri-ni docker üçün standart et", + "Make a new one": "Yenisini yarat", + "Manufacturer": "İstehsalçı", + "MariaDB won't start until you choose how its root account signs in.": "root hesabı üçün giriş üsulu seçənədək MariaDB işə düşməyəcək.", + "Maximise": "Böyüt", + "Medium": "Orta", + "Memory": "Yaddaş", + "Memory full · {mem}": "Yaddaş doludur · {mem}", + "Method": "Metod", + "Mirror address": "Güzgü ünvanı", + "Modified": "Dəyişdirilib", + "Monospace font": "Bərabər enli şrift", + "More": "Daha çox", + "More actions for {name}": "{name} üçün digər əməliyyatlar", + "More memory": "Daha çox yaddaş", + "More settings": "Digər tənzimləmələr", + "Mounts": "Qoşulma nöqtələri", + "Mouse": "Siçan", + "MySQL won't start until you choose how its root account signs in.": "root hesabı üçün giriş üsulu seçənədək MySQL işə düşməyəcək.", + "Name": "Ad", + "Named volumes from docker volume create or -v name:/path show up here.": "docker volume create və ya -v name:/path ilə yaradılmış adlandırılmış verilənlər həcmləri burada görünür.", + "Names answer on {http} and {https}. Pick other ports when another app needs these; links then carry the port, like {url}.": "Adla müraciətlər {http} və {https} portlarında qəbul edilir. Bu portlar başqa tətbiqə lazım olduqda fərqli portlar seçin; keçidlərdə port da göstəriləcək, məsələn: {url}.", + "Names, images and status. Not their files, logs or environment.": "Adlar, imiclər və status. Onların faylları, jurnalları və ya mühit dəyişənləri deyil.", + "Namespace": "Ad məkanı", + "Namespace · {up} of {all} running": "Ad məkanı · {up} / {all} işləyir", + "Needs a restart": "Yenidən başlatma tələb olunur", + "Needs an administrator password once.": "Bir dəfə administrator şifrəsi tələb olunur.", + "Needs upper and lower case, a digit and a symbol, 8 or more": "Ən azı 8 simvol, o cümlədən böyük və kiçik hərf, rəqəm və xüsusi simvol tələb olunur", + "Negligible": "Cüzi", + "Network": "Şəbəkə", + "Networks": "Şəbəkələr", + "Networks you create with docker network create show up here.": "docker network create ilə yaratdığınız şəbəkələr burada görünür.", + "Network|process": "Şəbəkə", + "New containers get {http}, {https} and {no}.": "Yeni konteynerlər {http}, {https} və {no} alır.", + "New tab": "Yeni vərəq", + "New tab ({keys})": "Yeni vərəq ({keys})", + "Next match": "Növbəti uyğunluq", + "No Linux username is needed now: Kiri runs inside Ubuntu on its own. Ubuntu asks for one only the first time you open it yourself. * Estimate.": "İndi Linux istifadəçi adı tələb olunmur: Kiri Ubuntu daxilində müstəqil işləyir. Ubuntu yalnız onu ilk dəfə özünüz açdıqda istifadəçi adı istəyir. * Təxmini.", + "No USB devices": "USB cihazı yoxdur", + "No build matches.": "Uyğun qurma tapılmadı.", + "No builds yet": "Hələ qurma yoxdur", + "No changes": "Dəyişiklik yoxdur", + "No containers running": "İşləyən konteyner yoxdur", + "No containers yet": "Hələ konteyner yoxdur", + "No crashes. Kiri keeps a report here if one of its parts ever stops unexpectedly.": "Çökmə yoxdur. Kiri-nin hər hansı hissəsi gözlənilmədən dayanarsa, hesabatı burada saxlayır.", + "No fix yet": "Hələ düzəliş yoxdur", + "No images yet": "Hələ imic yoxdur", + "No known vulnerabilities in {n} packages": "{n} paketdə məlum təhlükəsizlik boşluğu yoxdur", + "No language matches. Try its English name.": "Uyğun dil tapılmadı. İngiliscə adını yoxlayın.", + "No languages match": "Uyğun dil tapılmadı", + "No lines match.": "Uyğun sətir tapılmadı.", + "No mirrors yet: Docker Hub images come from Docker Hub itself.": "Hələ güzgü yoxdur: Docker Hub imicləri birbaşa Docker Hub-dan gəlir.", + "No networks yet": "Hələ şəbəkə yoxdur", + "No password, no login and no TLS. Fine on this Mac, not for anything shared.": "Şifrə, giriş yoxlaması və TLS yoxdur. Yalnız bu Mac-da istifadə üçün uyğundur; paylaşım üçün uyğun deyil.", + "No password, no login and no TLS. Fine on this PC, not for anything shared.": "Şifrə, giriş yoxlaması və TLS yoxdur. Yalnız bu kompüterdə istifadə üçün uyğundur; paylaşım üçün uyğun deyil.", + "No password, no login and no TLS. Fine on this computer, not for anything shared.": "Şifrə, giriş yoxlaması və TLS yoxdur. Yalnız bu kompüterdə istifadə üçün uyğundur; paylaşım üçün uyğun deyil.", + "No pods": "Pod yoxdur", + "No pods match its selector.": "Seçicisinə uyğun pod yoxdur.", + "No ports to share": "Paylaşılacaq port yoxdur", + "No proxy is in use.": "İstifadə olunan proksi yoxdur.", + "No requests match.": "Uyğun sorğu tapılmadı.", + "No requests yet": "Hələ sorğu yoxdur", + "No results": "Nəticə yoxdur", + "No service points at it, so the link goes straight to the pod.": "Ona yönələn xidmət yoxdur, ona görə də keçid birbaşa pod-a gedir.", + "No services": "Xidmət yoxdur", + "No steps here.": "Burada addım yoxdur.", + "No visitors in the last 2 minutes": "Son 2 dəqiqədə ziyarətçi yoxdur", + "No volumes yet": "Hələ verilənlər həcmi yoxdur", + "No {label}": "{label} yoxdur", + "Node": "Düyün", + "None": "Yoxdur", + "None (headless)": "Yoxdur (headless)", + "None found": "Heç nə tapılmadı", + "None match these filters.": "Bu filtrlərə uyğun nəticə yoxdur.", + "None: every registry is checked over HTTPS.": "Yoxdur: hər bir reyestr HTTPS üzərindən yoxlanılır.", + "Not a web port, so it isn't shared": "Veb portu deyil, ona görə də paylaşılmır", + "Not an image name: {reference}": "İmic adı deyil: {reference}", + "Not answering · visitors get an error": "Cavab vermir · ziyarətçilər xəta görür", + "Not created yet": "Hələ yaradılmayıb", + "Not found.": "Tapılmadı.", + "Not in use: no container was made from it": "İstifadə olunmur: ondan heç bir konteyner yaradılmayıb", + "Not now": "İndi yox", + "Not now: ask again in a week": "İndi yox: bir həftə sonra yenidən soruş", + "Not running": "İşləmir", + "Not sent": "Göndərilmədi", + "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "Hələ quraşdırılmayıb. İlk qurmanız zamanı yaradılır və BuildKit (təxminən 110 MB) bir dəfə endirilir.", + "Not signed in": "Daxil olunmayıb", + "Not signed in to any registry": "Heç bir reyestrə daxil olunmayıb", + "Nothing called “{q}” on Docker Hub": "Docker Hub-da “{q}” adlı heç nə yoxdur", + "Nothing changes: {build} builds where it does now, and the images stay in {engine}.": "Heç nə dəyişmir: {build} indi harada qurursa, orada da qurur və imiclər {engine} daxilində qalır.", + "Nothing here.": "Burada heç nə yoxdur.", + "Nothing is deleted. You can switch back any time from the status bar.": "Heç nə silinmir. Status sətrindən istədiyiniz vaxt geri qayıda bilərsiniz.", + "Nothing logged yet.": "Hələ jurnala heç nə yazılmayıb.", + "Nothing matches “{q}” in {tab}.": "{tab} daxilində “{q}” üçün uyğunluq tapılmadı.", + "Nothing matches “{q}”.": "“{q}” üçün uyğunluq tapılmadı.", + "Nothing restarts it either: when the pod is deleted or restarts, the link ends.": "Onu avtomatik yenidən başladan mexanizm də yoxdur: pod silindikdə və ya yenidən başladıqda keçid işləməyi dayandırır.", + "Nothing shared yet": "Hələ paylaşılan heç nə yoxdur", + "Nothing shared. Press the globe beside a running container to give it a public link.": "Paylaşılan heç nə yoxdur. İşləyən konteynerə açıq keçid vermək üçün yanındakı qlobus işarəsinə basın.", + "Nothing starts it again: no deployment or other controller owns it.": "Onu avtomatik yenidən başladan mexanizm yoxdur: heç bir Deployment və ya digər kontroller onu idarə etmir.", + "Nothing to download": "Endiriləcək heç nə yoxdur", + "Nothing to download: it came inside Kiri.": "Endiriləcək heç nə yoxdur: Kiri-nin daxilində gəlib.", + "Nothing to import from: OrbStack and Docker Desktop aren't on this {host}.": "İdxal ediləcək mənbə yoxdur: OrbStack və Docker Desktop bu {host} üzərində yoxdur.", + "Nothing to pass to a container yet.": "Hələ konteynerə ötürüləcək heç nə yoxdur.", + "Nothing to type: it uses the AWS sign-in already on this computer.": "Heç nə yazmağa ehtiyac yoxdur: bu kompüterdəki mövcud AWS girişi istifadə olunur.", + "Now": "İndi", + "OK": "Oldu", + "Off": "Söndürülüb", + "Off: Kiri checks only when you click Check now.": "Söndürülüb: Kiri yalnız İndi yoxla düyməsinə kliklədikdə yoxlayır.", + "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "Söndürülüb: konteynerlər heç bir quraşdırma tələb etməyən <name>.kiri.localhost ünvanında cavab verir.", + "Off: press Start engine to run containers. It stays off after a restart until you start it.": "Söndürülüb: konteynerləri işlətmək üçün “Mühərriki başlat” düyməsinə basın. Yenidən başlatmadan sonra da siz işə salanadək söndürülmüş vəziyyətdə qalır.", + "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "Söndürülüb: API serveri və LoadBalancer xidmətləri yalnız bu {host} üzərində (127.0.0.1) cavab verir.", + "Official": "Rəsmi", + "On": "Aktiv", + "On disk": "Diskdə", + "On this Mac": "Bu Mac-da", + "On this PC": "Bu PC-də", + "On {registry} an image is named owner/image, such as {example}. Type one to choose its tag, or paste a full reference.": "{registry} üzərində imic owner/image formatında adlandırılır, məsələn: {example}. Teqini seçmək üçün bir ad yazın və ya tam istinad yapışdırın.", + "On {targets}": "Hədəf: {targets}", + "On: Kiri checks each time it opens. It never updates without asking.": "Aktiv: Kiri hər dəfə açılanda yoxlayır. Soruşmadan heç vaxt yeniləmir.", + "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "Aktiv: konteynerlər yalnız .kiri.local və .kiri.localhost adlarını təsdiqləyən Kiri sertifikatı ilə https:// üzərindən açılır.", + "On: running containers answer at <name>.kiri.local.": "Aktiv: işləyən konteynerlər <name>.kiri.local ünvanında cavab verir.", + "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "Aktiv: API serveri və LoadBalancer xidmətləri bütün şəbəkə interfeyslərində cavab verir, beləliklə şəbəkənizdəki digər cihazlar onlara qoşula bilər.", + "One more step: log out and back in.": "Bir addım da qalıb: hesabdan çıxıb yenidən daxil olun.", + "One more step: set it up, or skip.": "Bir addım da qalıb: quraşdırmanı tamamlayın və ya bu addımı ötürün.", + "One restart to finish WSL": "WSL quraşdırmasını tamamlamaq üçün sistemi bir dəfə yenidən başladın", + "One text file, redacted, saved to your Desktop and shown in Finder. Read it before you share it.": "Məxfi məlumatları çıxarılmış bir mətn faylı iş masasında saxlanılır və Finder-də göstərilir. Paylaşmazdan əvvəl onu oxuyun.", + "Only from {what}": "Yalnız {what} mənbəyindən", + "Only {size} left this month. When it runs out, the link stops until next month.": "Bu ay yalnız {size} qalıb. Bitdikdə keçid növbəti aya qədər dayanacaq.", + "Open": "Aç", + "Open Kiri": "Kiri-ni aç", + "Open Pods": "Pod-ları aç", + "Open Share": "Paylaşımı aç", + "Open in Terminal": "Terminalda aç", + "Open logs folder": "Jurnal qovluğunu aç", + "Open the page again": "Səhifəni yenidən aç", + "Open {addr}": "Aç: {addr}", + "Open {name}": "Aç: {name}", + "Open {site}": "{site} saytını aç", + "Open {url}": "Aç: {url}", + "OpenSearch won't start without a strong admin password.": "OpenSearch güclü administrator şifrəsi olmadan başlamayacaq.", + "Opening the scan…": "Skan açılır…", + "Optional": "İstəyə bağlı", + "Or allow an empty password": "Və ya boş şifrəyə icazə ver", + "Or let it pick a random password": "Və ya təsadüfi şifrə seçsin", + "Or set {names} instead.": "Və ya əvəzinə {names} təyin edin.", + "Or turn security off for local use": "Və ya lokal istifadə üçün təhlükəsizliyi söndürün", + "Orange": "Narıncı", + "OrbStack": "OrbStack", + "Out of memory": "Yaddaş tükəndi", + "Overview": "Ümumi baxış", + "PC": "PC", + "Package": "Paket", + "Packages": "Paketlər", + "Page|process": "Səhifə", + "Pane restored": "Panel bərpa edildi", + "Pane zoomed": "Panel böyüdüldü", + "Part": "Hissə", + "Part of Kiri": "Kiri-nin hissəsi", + "Part of the cluster itself (kube-system). Not shared.": "Klasterin öz hissəsidir (kube-system). Paylaşılmır.", + "Pass to containers": "Konteynerlərə ötür", + "Paste": "Yapışdır", + "Paste NAME=value lines, or a .env file, into a name.": "NAME=value sətirlərini və ya .env faylını ad sahəsinə yapışdırın.", + "Paste {n} lines? Each line runs as a command.": "{n} sətir yapışdırılsın? Hər sətir ayrı bir əmr kimi icra olunacaq.", + "Path": "Yol", + "Pause": "Fasilə ver", + "Paused": "Fasilədədir", + "Paused · nobody can open the link": "Fasilədədir · heç kim keçidi aça bilməz", + "Paused: nobody can open the link until you resume.": "Fasilədədir: siz davam etdirənə qədər heç kim keçidi aça bilməz.", + "Peak {rate}": "Pik: {rate}", + "Pin tab": "Vərəqi bərkit", + "Pink": "Çəhrayı", + "Pinned": "Bərkidildi", + "Pinned: right-click to unpin": "Bərkidilib: bərkitməni ləğv etmək üçün sağ düymə ilə klikləyin", + "Pinned: unpin the tab to close it": "Bərkidilib: bağlamaq üçün vərəqin bərkidilməsini ləğv edin", + "Plug one in: a serial adapter, a Zigbee stick, a microcontroller. It shows up here.": "Ardıcıl port adapteri, Zigbee adapteri və ya mikrokontroller qoşun. Cihaz burada görünəcək.", + "Pod IP": "Pod IP-si", + "Pod in {ns}": "{ns} daxilində pod", + "Pod in {ns} · on {node}": "{ns} daxilində pod · düyün: {node}", + "Pods": "Pod-lar", + "Pods you create with kubectl show up here, grouped by namespace.": "kubectl ilə yaratdığınız pod-lar ad məkanına görə qruplaşdırılmış şəkildə burada görünür.", + "Port": "Port", + "Port in the container": "Konteynerdəki port", + "Port on your {host}": "{host} cihazınızdakı port", + "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "{host} cihazınızdakı port (localhost) → konteynerin daxilindəki port. Boş port seçilməsi üçün {host} tərəfini boş saxlayın.", + "Port {port} is already in use on this {host}": "Bu {host} cihazında {port} portu artıq istifadədədir", + "Port {port}. The link keeps working when pods restart.": "Port {port}. Pod-lar yenidən başladıqda keçid işləməyə davam edir.", + "Ports": "Portlar", + "Ports changed": "Portlar dəyişdirildi", + "Ports for {name}": "{name} üçün portlar", + "Ports removed": "Portlar silindi", + "Ports saved: {ports}": "Portlar saxlanıldı: {ports}", + "Ports…": "Portlar…", + "Postgres won't start without a superuser password.": "Postgres superistifadəçi (superuser) şifrəsi olmadan başlamayacaq.", + "Powered by": "Texnologiya", + "Press Share on a running container to give it a public https link anyone can open.": "İşləyən konteynerə hər kəsin aça biləcəyi açıq https keçidi vermək üçün Paylaş düyməsinə basın.", + "Press to see it, or disconnect it.": "Görmək və ya bağlantını kəsmək üçün basın.", + "Press to try again": "Yenidən cəhd etmək üçün basın", + "Previous match": "Əvvəlki uyğunluq", + "Previous run": "Əvvəlki icra", + "Printed once in the container's log.": "Konteynerin jurnalına bir dəfə yazılır.", + "Private images won't pull until you sign in again.": "Yenidən daxil olana qədər özəl imiclər endirilməyəcək.", + "Processes": "Proseslər", + "Progress": "Gedişat", + "Protocol": "Protokol", + "Proxy": "Proksi", + "Proxy settings saved": "Proksi tənzimləmələri saxlanıldı", + "Public images need no sign-in": "Açıq imiclər üçün giriş tələb olunmur", + "Public images on public.ecr.aws need nothing. For your own account's registry, Kiri runs {cmd} with this profile.": "public.ecr.aws üzərindəki açıq imiclər üçün heç nə tələb olunmur. Öz hesabınızın reyestri üçün Kiri bu profillə {cmd} əmrini işə salır.", + "Public images pull without signing in.": "Açıq imiclər giriş etmədən endirilir.", + "Publish": "Yayımla", + "Publish on {targets}": "Yayımla: {targets}", + "Publish the port {name} listens on, and give it a public https link": "{name} tərəfindən dinlənilən portu yayımla və ona açıq https keçidi ver", + "Pull": "Endir", + "Pull again": "Yenidən endir", + "Pull an image": "İmic endir", + "Pull an image ({key})": "İmic endir ({key})", + "Pull exactly this": "Dəqiq bunu endir", + "Pull from": "Mənbə", + "Pull image": "İmici endir", + "Pull {tag}": "Endir: {tag}", + "Pulled": "Endirildi", + "Pulled {name}": "Endirildi: {name}", + "Pulled {name} in {time}.": "{name} {time} ərzində endirildi.", + "Pulled {when}": "Endirildi: {when}", + "Pulling": "Endirilir", + "Pulling {n}": "Endirilir: {n}", + "Purple": "Bənövşəyi", + "Quit": "Çıx", + "Quit Kiri": "Kiri-dən çıx", + "Quit {app}": "{app} tətbiqindən çıx", + "Quote {id} if you write to us about this crash.": "Bu çökmə barədə bizə yazsanız, {id} kodunu qeyd edin.", + "Radio": "Radio", + "Ran": "İşlədi", + "Reachable at {addr}": "Əlçatandır: {addr}", + "Reachable at {url}": "Əlçatandır: {url}", + "Read more on runkiri.com ↗": "runkiri.com saytında daha ətraflı oxuyun ↗", + "Reading build history…": "Qurma tarixçəsi oxunur…", + "Reading the image…": "İmic oxunur…", + "Reading the log…": "Jurnal oxunur…", + "Reading the scans…": "Skanlar oxunur…", + "Reading what {name} has…": "{name} məzmunu oxunur…", + "Ready": "Hazırdır", + "Recent crashes": "Son çökmələr", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Problem yarandıqda istifadə etmək üçün son jurnallar, çökmə hesabatları və versiya məlumatları məxfi məlumatları çıxarılmış bir faylda toplanır.", + "Recent pulls": "Son endirilənlər", + "Recommended": "Tövsiyə olunan", + "Reconnecting": "Yenidən qoşulur", + "Reconnecting {name}…": "Yenidən qoşulur: {name}…", + "Reconnecting · {reason}": "Yenidən qoşulur · {reason}", + "Reconnecting…": "Yenidən qoşulur…", + "Redo": "Təkrarla", + "Registries": "Reyestrlər", + "Registries reached without a verified certificate (self-signed, or plain HTTP). Kiri tries HTTPS without checking the certificate, then HTTP. Only the hosts and networks listed; every other registry is checked as usual.": "Təsdiqlənmiş sertifikat olmadan qoşulan reyestrlər (özü-imzalanmış və ya adi HTTP). Kiri əvvəlcə sertifikatı yoxlamadan HTTPS-i, sonra HTTP-ni sınayır. Yalnız siyahıdakı hostlar və şəbəkələr üçün; digər bütün reyestrlər həmişəki kimi yoxlanılır.", + "Registry": "Reyestr", + "Registry mirrors": "Reyestr güzgüləri", + "Registry settings saved": "Reyestr tənzimləmələri saxlanıldı", + "Reload": "Yenilə", + "Remove": "Sil", + "Remove Kubernetes' container?": "Kubernetes konteyneri silinsin?", + "Remove all": "Hamısını sil", + "Remove both": "Hər ikisini sil", + "Remove network {name}?": "{name} şəbəkəsi silinsin?", + "Remove project": "Layihəni sil", + "Remove this build from the history?": "Bu qurma tarixçədən silinsin?", + "Remove this port": "Bu portu sil", + "Remove volume {name}?": "{name} verilənlər həcmi silinsin?", + "Remove {name} and {image}?": "{name} və {image} silinsin?", + "Remove {name}?": "{name} silinsin?", + "Remove {n} containers and {image}?": "{n} konteyner və {image} silinsin?", + "Remove {n} untagged": "Teqsiz {n} imici sil", + "Removed {gone} of {n} {what}": "{n} {what} elementindən {gone} ədədi silindi", + "Removed {name}": "{name} silindi", + "Removed {n} {what}": "{n} {what} silindi", + "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "{cmd} əmrinin etdiyi kimi klasterin konteynerini, içindəki hər şeyi ({volume} verilənlər həcmi) və {context} kubectl kontekstini silir.", + "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "Xəta ilə çıxan {n} konteyneri faylları ilə birlikdə silir. Adlandırılmış verilənlər həcmləri qalır.", + "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "Xəta ilə çıxan {n} konteyneri faylları ilə birlikdə silir. Adlandırılmış verilənlər həcmləri qalır.", + "Removes the {n} failed build from the history.": "Uğursuz {n} qurmanı tarixçədən silir.", + "Removes the {n} failed builds from the history.": "Uğursuz {n} qurmanı tarixçədən silir.", + "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "Yenidən qurma əməliyyatlarından qalan {n} teqsiz imici silir. Bu imiclərdən istifadə olunmur. {size} yer boşaldır.", + "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "Yenidən qurma əməliyyatlarından qalan {n} teqsiz imici silir. Bu imiclərdən istifadə olunmur. {size} yer boşaldır.", + "Removing {gone} of {n}…": "Silinir: {gone} / {n}…", + "Report ID": "Hesabat ID-si", + "Report sent": "Hesabat göndərildi", + "Repository": "Repozitoriya", + "Requests to {name}": "{name} üçün sorğular", + "Resources": "Resurslar", + "Restart": "Yenidən başlat", + "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "Tamamlamaq üçün Kiri-ni yenidən başladın. İşləyən konteynerlər dayanır, yenidən başlatma siyasəti olanlar isə yenidən başlayır.", + "Restart VM to apply": "Tətbiq etmək üçün VM-i yenidən başlat", + "Restart all": "Hamısını yenidən başlat", + "Restart engine": "Mühərriki yenidən başlat", + "Restart engine to finish": "Tamamlamaq üçün mühərriki yenidən başladın", + "Restart later": "Daha sonra yenidən başlat", + "Restart now": "İndi yenidən başlat", + "Restart to update": "Yeniləmək üçün yenidən başlat", + "Restart {name} with the new environment?": "{name} yeni mühit dəyişənləri ilə yenidən başladılsın?", + "Restarting stops the running containers; start them again afterwards.": "Yenidən başlatma işləyən konteynerləri dayandırır; sonra onları yenidən başladın.", + "Restarting…": "Yenidən başladılır…", + "Restarts": "Yenidən başlatmalar", + "Restore": "Bərpa et", + "Resume": "Davam etdir", + "Retry": "Yenidən cəhd et", + "Retry starts it again; the layers already here are kept.": "“Yenidən cəhd et” əməliyyatı təkrar başladır; artıq endirilmiş təbəqələr saxlanılır.", + "Review": "Nəzərdən keçir", + "Run": "İcra et", + "Run a test container": "Test konteyneri işə sal", + "Run {cmd}, then Retry.": "{cmd} əmrini işə salın, sonra Yenidən cəhd et düyməsinə basın.", + "Running": "İşləyir", + "Running Kiri {version} · back in {time}": "Kiri {version} işləyir · {time} ərzində qayıdacaq", + "Running containers answer at <name>.kiri.localhost, which needs no setup.": "İşləyən konteynerlər heç bir quraşdırma tələb etməyən <name>.kiri.localhost ünvanında cavab verir.", + "Running now with {cpus} and up to {mem}.": "Hazırda {cpus} və ən çox {mem} ilə işləyir.", + "Running, not ready": "İşləyir, hazır deyil", + "Running: it rests by itself when nothing runs and wakes when you use it.": "İşləyir: heç nə işləmədikdə avtomatik yuxu rejiminə keçir, istifadə etdikdə yenidən işə düşür.", + "Running: {cmd}": "İşləyir: {cmd}", + "Runs": "İcra olunan", + "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "Hər əmri {name} daxilində {sh} ilə icra edir; {cd} qorunur. ↑ və ↓ əvvəlki əmrlər arasında keçid edir.", + "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "Birbaşa Mac-ınızda Kiri-dəki imic nüsxəsini yoxlayır; heç nə göndərilmir.", + "Runs your containers": "Konteynerlərinizi işlədir", + "SQL Server won't start without a strong password for its sa account, and its licence accepted.": "sa hesabı üçün güclü şifrə təyin edilmədən və lisenziyası qəbul olunmadan SQL Server işə düşməyəcək.", + "Same as the window ({font})": "Pəncərə ilə eyni ({font})", + "Same as {os}": "{os} ilə eyni", + "Save": "Yadda saxla", + "Save SBOM": "SBOM-u saxla", + "Save and start": "Saxla və başlat", + "Save to Desktop": "İş masasına saxla", + "Save to Downloads": "Endirilənlərə saxla", + "Save {name}'s new environment?": "{name} üçün yeni mühit dəyişənləri saxlanılsın?", + "Saved in .wslconfig. WSL uses these from its next start": ".wslconfig faylında saxlanıldı. WSL növbəti dəfə işə düşdükdə bu tənzimləmələri tətbiq edəcək", + "Saved in the container's environment. Kiri doesn't keep a copy.": "Konteynerin mühit dəyişənlərində saxlanıldı. Kiri nüsxəsini saxlamır.", + "Saved in this container's environment. Kiri doesn't keep a copy.": "Bu konteynerin mühit dəyişənlərində saxlanıldı. Kiri nüsxəsini saxlamır.", + "Saved the SBOM to Downloads as {file}": "SBOM “Endirilənlər” qovluğunda {file} adı ilə saxlanıldı", + "Saved the report to {path}": "Hesabat {path} yolunda saxlanıldı", + "Saved to Downloads as {file}": "“Endirilənlər” qovluğunda {file} adı ilə saxlanıldı", + "Saved. The VM uses these from its next start": "Saxlanıldı. VM növbəti dəfə işə düşdükdə bu tənzimləmələri tətbiq edəcək", + "Saving…": "Saxlanılır…", + "Scan again": "Yenidən skan et", + "Scan image": "İmici skan et", + "Scan of {when}": "Skan: {when}", + "Scan with": "Skan üçün istifadə et", + "Scan {image}": "Skan et: {image}", + "Scan {image} for known vulnerabilities": "{image} imicini məlum təhlükəsizlik boşluqlarına qarşı skan et", + "Scanned": "Skan edildi", + "Scanning the image's packages": "İmicin paketləri skan edilir", + "Scans": "Skanlar", + "Search Docker Hub, or paste an image reference": "Docker Hub-da axtarın və ya imic istinadını yapışdırın", + "Search Kiri": "Kiri-də axtar", + "Search Kiri…": "Kiri-də axtar…", + "Search containers, images…": "Konteynerlərdə, imiclərdə axtar…", + "Search languages": "Dilləri axtar", + "Search {view}…": "Axtar: {view}…", + "Searching Docker Hub": "Docker Hub-da axtarılır", + "Security": "Təhlükəsizlik", + "See it ↗": "Bax ↗", + "See its tags": "Teqlərinə bax", + "See what it looks like ↗": "Necə göründüyünə baxın ↗", + "See why": "Səbəbini gör", + "Select": "Seç", + "Select All": "Hamısını seç", + "Select all": "Hamısını seç", + "Select all {n}": "Bütün {n} elementi seç", + "Select none": "Heç birini seçmə", + "Select {name}": "Seç: {name}", + "Selected {what}": "Seçildi: {what}", + "Selection, focus rings and primary buttons.": "Seçim, fokus halqaları və əsas düymələr.", + "Selector": "Seçici", + "Send": "Göndər", + "Send a report to Kiri": "Kiri-yə hesabat göndər", + "Send an idea or report a bug on GitHub": "GitHub-da ideya göndərin və ya xəta bildirin", + "Send crash reports automatically": "Çökmə hesabatlarını avtomatik göndər", + "Send report": "Hesabat göndər", + "Send to Kiri": "Kiri-yə göndər", + "Sending…": "Göndərilir…", + "Sent": "Göndərildi", + "Sent as {id}": "{id} olaraq göndərildi", + "Sent. Quote {id} if you write to us.": "Göndərildi. Bizə yazsanız, {id} kodunu qeyd edin.", + "Serial": "Ardıcıl port", + "Serial number": "Seriya nömrəsi", + "Services": "Xidmətlər", + "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "kubectl expose ilə yaratdığınız xidmətlər burada görünür. LoadBalancer xidmətləri localhost üzərindən cavab verir.", + "Session": "Sessiya", + "Set it and start": "Təyin et və başlat", + "Set up": "Quraşdır", + "Set up Kiri": "Kiri-ni quraşdır", + "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "docker build əmrinin burada işləməsi üçün Kiri-nin qurucusunu quraşdırın. İlk qurmanıza qədər heç nə endirilmir", + "Set up with Kiri Linux": "Kiri Linux ilə quraşdır", + "Set up with Ubuntu": "Ubuntu ilə quraşdır", + "Set {what}": "Təyin et: {what}", + "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Microsoft imicinin tələb etdiyi kimi ACCEPT_EULA=Y təyin edir.", + "Setting up": "Quraşdırılır", + "Setting up Docker tools…": "Docker alətləri quraşdırılır…", + "Setting up Docker tools… {pct}%": "Docker alətləri quraşdırılır… {pct}%", + "Setting up Kiri Linux": "Kiri Linux quraşdırılır", + "Setting up Ubuntu 26.04": "Ubuntu 26.04 quraşdırılır", + "Setting up the Docker tools": "Docker alətləri quraşdırılır", + "Settings": "Tənzimləmələr", + "Settings…": "Tənzimləmələr…", + "Setup log": "Quraşdırma jurnalı", + "Setup steps": "Quraşdırma addımları", + "Setup time": "Quraşdırma müddəti", + "Severity": "Ciddilik dərəcəsi", + "Share": "Paylaş", + "Share again": "Yenidən paylaş", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "Paylaş funksiyası konteynerə və ya Kubernetes xidmətinə Kiri Cloud-a gedən təhlükəsiz tunel vasitəsilə açıq https keçidi verir.", + "Share pod {name}?": "{name} pod-u paylaşılsın?", + "Share service {name}": "{name} xidmətini paylaş", + "Share this pod on a port…": "Bu pod-u bir portda paylaş…", + "Share this pod's port {port}": "Bu pod-un {port} portunu paylaş", + "Share which port?": "Hansı port paylaşılsın?", + "Share {name}": "Paylaş: {name}", + "Shared": "Paylaşıldı", + "Shared by {who}": "Paylaşan: {who}", + "Shared now": "Hazırda paylaşılan", + "Shared with {os}: the VM only uses them while containers are busy.": "{os} ilə ortaq istifadə olunur: VM bu resurslardan yalnız konteynerlər işləyərkən istifadə edir.", + "Shared · {url}": "Paylaşıldı · {url}", + "Shares": "Paylaşımlar", + "Sharing…": "Paylaşılır…", + "Short of memory, its API server slows down or stops answering.": "Yaddaş çatışmadıqda API serveri yavaşlayır və ya cavab verməyi dayandırır.", + "Show": "Göstər", + "Show Images": "İmicləri göstər", + "Show all actions": "Bütün əməliyyatları göstər", + "Show containers": "Konteynerləri göstər", + "Show full log": "Tam jurnalı göstər", + "Show in Diagnostics": "Diaqnostikada göstər", + "Show in Finder": "Finder-də göstər", + "Show its requests": "Sorğularını göstər", + "Show password": "Şifrəni göstər", + "Show shares": "Paylaşımları göstər", + "Show the crash report": "Çökmə hesabatını göstər", + "Show the pulls in Images": "Endirilənləri İmiclərdə göstər", + "Show the sidebar": "Yan paneli göstər", + "Show the terminal ({keys})": "Terminalı göstər ({keys})", + "Show the update": "Yeniləməni göstər", + "Sign in": "Daxil ol", + "Sign in and pull": "Daxil ol və endir", + "Sign in to a registry": "Reyestrə daxil ol", + "Sign in to a registry…": "Reyestrə daxil ol…", + "Sign in to see your plan": "Planınızı görmək üçün daxil olun", + "Sign in to share {what}": "{what} paylaşmaq üçün daxil olun", + "Sign in to {registry}": "{registry} reyestrinə daxil ol", + "Sign in with AWS": "AWS ilə daxil ol", + "Sign in with GitHub": "GitHub ilə daxil ol", + "Sign out": "Çıxış et", + "Sign out of {registry}": "{registry} hesabından çıx", + "Sign out of {registry}?": "{registry} hesabından çıxılsın?", + "Sign-in failed: {error}": "Giriş uğursuz oldu: {error}", + "Sign-in needed.": "Giriş tələb olunur.", + "Signed in": "Daxil olundu", + "Signed in as {name}": "{name} kimi daxil olundu", + "Signed in as {name}.": "{name} kimi daxil olundu.", + "Signed in to Kiri Cloud with GitHub as {login}": "Kiri Cloud-a GitHub ilə {login} kimi daxil olundu", + "Signed in to a registry, Kiri pulls its private images, and docker uses the same sign-in.": "Reyestrə daxil olduqda Kiri oradakı özəl imicləri endirir və docker da eyni girişdən istifadə edir.", + "Signed in with GitHub": "GitHub ilə daxil olundu", + "Signing in again uses your AWS profile.": "Yenidən daxil olduqda AWS profiliniz istifadə olunur.", + "Signing in…": "Daxil olunur…", + "Signing out…": "Çıxış edilir…", + "Size": "Ölçü", + "Skip": "Ötür", + "Skip this version": "Bu versiyanı ötür", + "Skipped: docker build builds where docker points": "Ötürüldü: docker build, docker hara yönəlibsə orada qurur", + "Skipped: docker keeps using the engine it has now": "Ötürüldü: docker hazırkı mühərriklə işləməyə davam edir", + "Skipped: {problem}": "Ötürüldü: {problem}", + "Slow because the VM is out of memory": "VM-in yaddaşı tükəndiyi üçün yavaşdır", + "Small": "Kiçik", + "Smaller": "Daha kiçik", + "Snooze ▾": "Təxirə sal ▾", + "Something else on this {host} has it. Give {name} another port.": "Bu {host} cihazında port başqa proqram tərəfindən tutulub. {name} üçün başqa port seçin.", + "Something went wrong": "Nəsə düz getmədi", + "Soon": "Tezliklə", + "Speed": "Sürət", + "Split down": "Paneli aşağıya böl", + "Split down ({keys})": "Paneli aşağıya böl ({keys})", + "Split right": "Paneli sağa böl", + "Split right ({keys})": "Paneli sağa böl ({keys})", + "Start": "Başlat", + "Start Kiri": "Kiri-ni başlat", + "Start Kiri to change its network settings. ({error})": "Şəbəkə tənzimləmələrini dəyişmək üçün Kiri-ni başladın. ({error})", + "Start Kiri to change its registry settings. ({error})": "Reyestr tənzimləmələrini dəyişmək üçün Kiri-ni başladın. ({error})", + "Start Kiri to change its resources. ({error})": "Resurslarını dəyişmək üçün Kiri-ni başladın. ({error})", + "Start Kiri to change the ports names answer on.": "Adla müraciət üçün istifadə olunan portları dəyişmək üçün Kiri-ni başladın.", + "Start Kiri when I sign in (in the tray)": "Hesaba daxil olduqda Kiri-ni başlat (sistem treyində)", + "Start Kubernetes": "Kubernetes-i başlat", + "Start Linux VM": "Linux VM-i başlat", + "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "Bir Kiri konteynerində tək düyünlü klaster (k3s) başladın. Onun API-si {api} ünvanındadır (və ya növbəti boş portda) və kiri k8s start əmrində olduğu kimi kubectl {context} kontekstini alır.", + "Start again": "Yenidən başlat", + "Start all": "Hamısını başlat", + "Start engine": "Mühərriki başlat", + "Start it": "Başlat", + "Start it to restart it": "Yenidən başlatmaq üçün onu işə salın", + "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "Konteynerləri işlətmək üçün onu başladın. Bir saniyədən az müddətdə işə düşür və boş qaldıqda yuxu rejiminə keçir.", + "Start it to share it": "Paylaşmaq üçün onu başladın", + "Start scan": "Skanı başlat", + "Start the container to run commands in it.": "Daxilində əmrlər işlətmək üçün konteyneri başladın.", + "Start the engine": "Mühərriki başlat", + "Start {engine} to bring its images over now, or later from Settings → Import.": "İmiclərini indi köçürmək üçün {engine} mühərrikini başladın və ya daha sonra Tənzimləmələr → İdxal bölməsindən köçürün.", + "Started": "Başladıldı", + "Started with {name} set": "{name} təyin edilərək başladıldı", + "Started {name}": "{name} başladıldı", + "Started {name} on {ports}": "{name} {ports} portlarında başladıldı", + "Starting": "Başladılır", + "Starting Kiri’s engine": "Kiri-nin mühərriki başladılır", + "Starting Kubernetes…": "Kubernetes başladılır…", + "Starting the scan": "Skan başladılır", + "Starting…": "Başladılır…", + "State": "Vəziyyət", + "Status": "Status", + "Step 1 of 5": "Addım 1 / 5", + "Step 2 of 5": "Addım 2 / 5", + "Step 2 of 5. Nothing else on this PC changes: Kiri sets itself up for your Windows account only.": "Addım 2 / 5. Bu PC-də başqa heç nə dəyişmir: Kiri yalnız sizin Windows hesabınız üçün quraşdırılır.", + "Step 3 of 5": "Addım 3 / 5", + "Step 4 of 5": "Addım 4 / 5", + "Steps": "Addımlar", + "Stop": "Dayandır", + "Stop Kubernetes?": "Kubernetes dayandırılsın?", + "Stop Linux VM": "Linux VM-i dayandır", + "Stop all": "Hamısını dayandır", + "Stop on {host}": "{host} üzərində dayandır", + "Stop sharing": "Paylaşımı dayandır", + "Stop signal": "Dayandırma siqnalı", + "Stop {name}": "Dayandır: {name}", + "Stop {name} on {host}?": "{name} {host} üzərində dayandırılsın?", + "Stopped": "Dayandırıldı", + "Stopped {when}": "Dayandırıldı: {when}", + "Stopped {when}, when the {vm} stopped. Start it again whenever you like.": "Dayandırıldı: {when}, {vm} dayandıqda. İstədiyiniz vaxt yenidən başlada bilərsiniz.", + "Stopped {when}: its memory ran out": "Dayandırıldı: {when}, yaddaşı tükəndi", + "Stopped {when}: its memory ran out (the VM has {mem})": "Dayandırıldı: {when}, yaddaşı tükəndi (VM-də {mem} var)", + "Stopped: out of memory": "Dayandırıldı: yaddaş tükəndi", + "Stopping": "Dayandırılır", + "Stopping…": "Dayandırılır…", + "Stop…": "Dayandır…", + "Storage": "Saxlama sahəsi", + "Strong enough": "Kifayət qədər güclüdür", + "Subnet": "Alt şəbəkə", + "Suggested": "Təklif olunan", + "Switch and import": "Keç və idxal et", + "Switch and import {n} item": "Keç və {n} elementi idxal et", + "Switch and import {n} items": "Keç və {n} elementi idxal et", + "Switch back": "Geri qayıt", + "Switch to the dark theme": "Tünd temaya keç", + "Switch to the light theme": "Açıq temaya keç", + "Switch to {app}": "{app} tətbiqinə keç", + "System": "Sistem", + "System Mono|font": "Sistem şrifti (bərabər enli)", + "System|font": "Sistem şrifti", + "Tab pinned": "Vərəq bərkidildi", + "Tab unpinned": "Vərəqin bərkidilməsi ləğv edildi", + "Tables, the sidebar and headings.": "Cədvəllər, yan panel və başlıqlar.", + "Tag": "Teq", + "Teal": "Firuzəyi", + "Tell us how it goes": "Necə işlədiyini bizə bildirin", + "Terminal": "Terminal", + "Terminal ({keys})": "Terminal ({keys})", + "Terminated": "Sonlandırıldı", + "Test build": "Test qurması", + "Text size": "Mətn ölçüsü", + "Text size {n} px": "Mətn ölçüsü {n} px", + "That's a lot to copy and can take a long time; choosing what you need is quicker.": "Kopyalanacaq çox şey var və bu uzun çəkə bilər; yalnız lazım olanları seçmək daha sürətlidir.", + "The 5 newest, and macOS's own crash reports for Kiri from the last 30 days": "Ən yeni 5 hesabat və son 30 gündə macOS-un Kiri üçün öz çökmə hesabatları", + "The API server port must be a number from 1024 to 65535": "API serverinin portu 1024–65535 aralığında bir ədəd olmalıdır", + "The AWS CLI has no profiles yet. Set one up with {cmd}.": "AWS CLI-da hələ profil yoxdur. {cmd} əmri ilə birini quraşdırın.", + "The GitHub CLI stays signed in.": "GitHub CLI-da giriş sessiyası açıq qalır.", + "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes API serveri. Heç vaxt paylaşılmır: keçidə sahib olan hər kəs klasteri idarə etməyə cəhd edə bilər.", + "The Linux VM restarted with the new resources": "Linux VM yeni resurslarla yenidən başladıldı", + "The VM has {mem}; {free}.": "VM-də {mem} var; {free}.", + "The VM is asleep; it starts with these next time.": "VM yuxu rejimindədir; növbəti dəfə bu tənzimləmələrlə başlayacaq.", + "The VM's memory is nearly full: {used} of {max}.": "VM-in yaddaşı demək olar ki, doludur: {used} / {max}.", + "The app on {host} keeps running, and {program} there shows the share as stopped from another computer.": "{host} üzərindəki tətbiq işləməyə davam edir və oradakı {program} paylaşımın başqa kompüterdən dayandırıldığını göstərir.", + "The build failed": "Qurma uğursuz oldu", + "The build was canceled": "Qurma ləğv edildi", + "The code goes straight to the AWS CLI; Kiri doesn't keep it.": "Kod birbaşa AWS CLI-a gedir; Kiri onu saxlamır.", + "The container keeps running.": "Konteyner işləməyə davam edir.", + "The docker command is signed out too.": "docker əmrinin istifadə etdiyi giriş sessiyası da bağlanır.", + "The docker command uses {app}": "docker əmri {app} ilə işləyir", + "The docker command uses {engine}. Switch it to {app}": "docker əmri {engine} ilə işləyir. Onu {app} tətbiqinə yönləndirin", + "The engine": "Mühərrik", + "The engine is running but not answering": "Mühərrik işləyir, lakin cavab vermir", + "The engine is stopped": "Mühərrik dayandırılıb", + "The engine isn't here: reinstall the kiri package": "Mühərrik tapılmadı: kiri paketini yenidən quraşdırın", + "The engine still runs Kiri {version}": "Mühərrik hələ də Kiri {version} işlədir", + "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Mühərrik hələ də {version} işlədir. Onu yenidən başlatmaq işləyən konteynerləri dayandırır, yenidən başlatma siyasəti olanlar isə yenidən başlayır.", + "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "İlk skan Grype-ı və onun verilənlər bazasını endirir: təxminən 230 MB (açıldıqda 3 GB).", + "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Microsoft-un WSL siyahısındakı tam Ubuntu. Kiri onun daxilində işləyir və siz də onu öz Linux mühitiniz kimi aça bilərsiniz.", + "The image's own way to start without it.": "İmicin onsuz başlamaq üçün öz üsulu.", + "The kiri share there stops.": "Oradakı kiri share dayanır.", + "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "Pəncərədən, mühərrikdən və kiri əmrlərindən son 300 sətir, həmçinin mühərrikin öz çıxışı", + "The last {n} seconds": "Son {n} saniyə", + "The link ends when the pod does.": "Pod dayandıqda keçid də başa çatır.", + "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "VM üçün maksimum yaddaş həddi. VM yaddaşdan yalnız konteynerlərə lazım olduqca istifadə edir və qalanını {os} sisteminə qaytarır.", + "The name comes from the Igbo word ntakịrị, “small”.": "Ad İqbo dilində “kiçik” mənasını verən ntakịrị sözündən gəlir.", + "The part that runs your containers, inside {linux}.": "{linux} daxilində konteynerlərinizi işlədən hissə.", + "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "Bu {host} cihazında API serveri üçün 1024–65535 aralığında port seçin (standart: 6443). Klaster başladıqda bu port tutulubsa, növbəti boş port seçilir. Saxladıqda klaster yenidən başladılır və {context} konteksti yenilənir.", + "The profile {profile} asks for a code from your MFA device {device}.": "{profile} profili {device} MFA cihazınızdan kod tələb edir.", + "The profile {profile} asks for a code from your MFA device.": "{profile} profili MFA cihazınızdan kod tələb edir.", + "The profile {profile} signs in through AWS IAM Identity Center. Kiri runs {cmd}, which opens AWS's page.": "{profile} profili AWS IAM Identity Center vasitəsilə daxil olur. Kiri AWS səhifəsini açan {cmd} əmrini işə salır.", + "The run before the container's last restart": "Konteynerin son yenidən başladılmasından əvvəlki icra", + "The same docker commands you know, talking to Kiri. Each file is checked against its pinned SHA-256.": "Bildiyiniz docker əmrləri Kiri ilə işləyir. Hər faylın SHA-256 dəyəri əvvəlcədən müəyyən edilmiş dəyərlə tutuşdurulur.", + "The window": "Pəncərə", + "The {n} packages as CycloneDX JSON, saved to Downloads": "{n} paket haqqında məlumat CycloneDX JSON formatında “Endirilənlər” qovluğunda saxlanılır", + "The {vm} is asleep: it holds no memory": "{vm} yuxu rejimindədir: yaddaş tutmur", + "Theme": "Tema", + "They appear in Images as they arrive.": "Köçürüldükcə “İmiclər” bölməsində görünür.", + "This action left no log lines.": "Bu əməliyyat üçün jurnala heç nə yazılmayıb.", + "This build made no image to scan: it failed before exporting, or its output was the cache only.": "Bu qurma skan ediləcək imic yaratmadı: ixrac mərhələsindən əvvəl uğursuz oldu və ya nəticədə yalnız keş yaradıldı.", + "This build made no image: it failed before exporting, or its output was the cache only.": "Bu qurma imic yaratmadı: ixrac mərhələsindən əvvəl uğursuz oldu və ya nəticədə yalnız keş yaradıldı.", + "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "Bu qurmanın imici Kiri-də deyil, ona görə də burada skan ediləcək heç nə yoxdur. Başqa yerə göndərilib (push), ixrac edilib və ya sonradan silinib. Burada skan etmək üçün onu --load ilə qurun.", + "This can't be undone.": "Bu əməliyyat geri qaytarıla bilməz.", + "This closes that tunnel on {host}, from here. The link stops working for everyone.": "Bu, {host} üzərindəki həmin tuneli buradan bağlayır. Keçid hər kəs üçün işləməyi dayandırır.", + "This computer can't use it while it's in Kiri: detach it to get it back.": "Cihaz Kiri-yə qoşulu olduğu müddətdə bu kompüter ondan istifadə edə bilməz. Geri qaytarmaq üçün cihazı ayırın.", + "This file is binary or larger than 256 KB.": "Bu fayl ikili (binary) formatdadır və ya 256 KB-dan böyükdür.", + "This folder is empty.": "Bu qovluq boşdur.", + "This image": "Bu imic", + "This image needs privileged mode": "Bu imic imtiyazlı rejim (privileged mode) tələb edir", + "This is Kubernetes. Kiri runs it for you": "Bu, Kubernetes-dir. Kiri onu sizin üçün işlədir", + "This lists every link on your account, on any computer.": "Bu siyahıda bütün kompüterlərdə hesabınıza aid olan keçidlər göstərilir.", + "This month": "Bu ay", + "This pod's name changes when it restarts, and the link would end.": "Bu pod yenidən başladıqda adı dəyişir və keçid işləməyi dayandırır.", + "This sign-in's ID: a hash of its token, safe to quote when asking for help": "Bu girişin ID-si: tokenin heş dəyəridir, kömək istəyərkən qeyd etmək təhlükəsizdir", + "This system applies your new access when you sign in again. Kiri opens ready after that.": "Bu sistem yeni icazənizi yenidən daxil olduqda tətbiq edir. Bundan sonra Kiri hazır vəziyyətdə açılır.", + "Time": "Vaxt", + "To make names like {name} work, Kiri adds one small settings file to your Mac ({path}), and changing system settings always needs an administrator. Kiri uses the password only for that, once. It never sees the password: macOS handles it.": "{name} kimi adların işləməsi üçün Kiri Mac-ınıza kiçik bir tənzimləmə faylı əlavə edir ({path}), sistem tənzimləmələrini dəyişmək isə həmişə administrator icazəsi tələb edir. Kiri şifrəni yalnız bunun üçün bir dəfə istifadə edir. Şifrəni heç vaxt görmür: prosesi macOS idarə edir.", + "Today {time}": "Bu gün {time}", + "Token": "Token", + "Token or password": "Token və ya şifrə", + "Tomorrow": "Sabah", + "Took": "Müddət", + "Traffic over the last two minutes": "Son iki dəqiqədəki trafik", + "Traffic served": "Ötürülən trafik", + "Trust Kiri's certificate so {url} works. macOS asks for your password. The certificate can only vouch for Kiri's own names.": "{url} ünvanının işləməsi üçün Kiri-nin sertifikatına etibar edin. macOS şifrənizi soruşacaq. Sertifikat yalnız Kiri-nin öz adlarını təsdiqləyə bilər.", + "Try again": "Yenidən cəhd et", + "Turn off engine": "Mühərriki söndür", + "Turn on Kiri's in Settings → Kubernetes instead of starting a copy.": "Nüsxə başlatmaq əvəzinə Tənzimləmələr → Kubernetes bölməsindən Kiri-nin öz klasterini açın.", + "Turn on Kubernetes": "Kubernetes-i aç", + "Turn on WSL's Windows components": "WSL-in Windows komponentlərini aktivləşdir", + "Turn security off for local use": "Yerli istifadə üçün təhlükəsizliyi söndür", + "Type": "Növ", + "Type one, or generate it": "Birini yazın və ya yaradın", + "Type to search Docker Hub, or paste a full reference such as {a} or {b} to pull exactly that.": "Docker Hub-da axtarmaq üçün yazın və ya dəqiq həmin imici endirmək üçün {a} yaxud {b} kimi tam istinad yapışdırın.", + "USB": "USB", + "USB device": "USB cihazı", + "USB needs usbipd-win": "USB üçün usbipd-win tələb olunur", + "USB passthrough is in beta.": "USB ötürülməsi beta mərhələsindədir.", + "USB passthrough is new: tell us how it works with your devices": "USB ötürülməsi yenidir: cihazlarınızla necə işlədiyini bizə bildirin", + "Ubuntu is already on this PC, so choosing it downloads nothing.": "Ubuntu artıq bu kompüterdə quraşdırılıb. Onu seçsəniz, heç nə endirmək lazım olmayacaq.", + "Undo": "Geri al", + "Undo brings it back": "“Geri al” seçimi ilə bərpa edə bilərsiniz", + "Undo brings them back": "“Geri al” seçimi ilə bərpa edə bilərsiniz", + "Unknown": "Naməlum", + "Unpack Kiri Linux": "Kiri Linux-u arxivdən çıxar", + "Unpack it into WSL": "Arxivdən çıxarıb WSL-ə yerləşdir", + "Unpin tab": "Vərəqin bərkidilməsini ləğv et", + "Untagged": "Teqsiz", + "Untagged; another tag still uses it": "Teqi silindi; başqa bir teq hələ də ondan istifadə edir", + "Unused": "İstifadə olunmur", + "Up to date": "Ən son versiyadır", + "Up {time}": "{time} müddətdir işləyir", + "Up {time} (Paused)": "{time} müddətdir işləyir (Fasilədədir)", + "Updating": "Yenilənir", + "Updating the vulnerability database (about 200 MB the first time)": "Təhlükəsizlik boşluqları bazası yenilənir (ilk dəfə təxminən 200 MB)", + "Upper and lower case, a digit and a symbol, 8 or more": "Ən azı 8 simvol: böyük və kiçik hərf, rəqəm və xüsusi simvol", + "Use AWS profile": "AWS profilindən istifadə et", + "Use Kiri": "Kiri-dən istifadə et", + "Use Kiri Linux instead": "Əvəzinə Kiri Linux-dan istifadə et", + "Use Kiri's Kubernetes": "Kiri-nin Kubernetes-ini işlət", + "Use Save to Downloads to open it.": "Açmaq üçün “Endirilənlərə saxla” seçimini edin.", + "Use Show in Finder to open it.": "Açmaq üçün “Finder-də göstər” seçimini edin.", + "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Docker Hub şəxsi giriş tokenindən istifadə edin (Account settings → Personal access tokens).", + "Use a GitHub personal access token (classic) with the {scope} scope.": "{scope} icazəsinə malik GitHub şəxsi giriş tokenindən (classic) istifadə edin.", + "Use a personal or deploy token with the {scope} scope.": "{scope} icazəsinə malik şəxsi tokendən və ya yerləşdirmə tokenindən (deploy token) istifadə edin.", + "Use another port": "Başqa port seç", + "Use the Ubuntu already here": "Mövcud Ubuntu-dan istifadə et", + "Use this profile": "Bu profildən istifadə et", + "Use your AWS profile": "AWS profilinizdən istifadə edin", + "Use your password, or a robot account's name and token.": "Şifrənizdən və ya robot hesabının adı və tokenindən istifadə edin.", + "Use {app} for docker?": "docker üçün {app} istifadə edilsin?", + "Use {name} instead": "Əvəzinə {name} seç", + "Used by": "İstifadə edən", + "User": "İstifadəçi", + "Username": "İstifadəçi adı", + "Using the Ubuntu already on this PC: nothing to download.": "Bu kompüterdəki mövcud Ubuntu-dan istifadə olunur: heç nə endirməyə ehtiyac yoxdur.", + "VPNs need no setting: container traffic leaves through macOS.": "VPN-lər üçün tənzimləmə tələb olunmur: konteyner trafiki macOS üzərindən çıxır.", + "Value": "Dəyər", + "Version {version}": "Versiya {version}", + "Versions, macOS, whether the engine runs, how many containers and images": "Versiyalar, macOS, mühərrikin işləyib-işləməməsi, konteyner və imic sayı", + "View": "Görünüş", + "View container": "Konteynerə bax", + "Visitors": "Ziyarətçilər", + "Visitors' browsers see a short Kiri Cloud notice page first, then your app.": "Ziyarətçilərin brauzerlərində əvvəlcə Kiri Cloud-un qısa bildiriş səhifəsi, sonra tətbiqiniz açılır.", + "Volumes": "Həcmlər", + "Vulnerabilities": "Təhlükəsizlik boşluqları", + "Vulnerability": "Təhlükəsizlik boşluğu", + "WSL restarted with the new resources": "WSL yeni resurslarla yenidən başladıldı", + "WSL, downloaded from Microsoft": "WSL, Microsoft-dan endirilir", + "Waiting": "Gözlənilir", + "Waiting for GitHub…": "GitHub gözlənilir…", + "Waiting for Windows' approval": "Windows təsdiqi gözlənilir", + "Waiting for the API server…": "API serveri gözlənilir…", + "Waiting for the first sample…": "İlk nümunə gözlənilir…", + "Waiting for the first visitor…": "İlk ziyarətçi gözlənilir…", + "Waiting for you to approve {code} in the browser…": "Brauzerdə {code} kodunu təsdiqləməyiniz gözlənilir…", + "Waiting for you to sign in in the browser…": "Brauzerdə daxil olmağınız gözlənilir…", + "Warn": "Xəbərdarlıq", + "Warnings": "Xəbərdarlıqlar", + "Warnings and errors": "Xəbərdarlıqlar və xətalar", + "We get the file below, redacted, and you get an ID to quote when you write to us. If you're signed in to Kiri Cloud, it says it's from you, so we can reply.": "Aşağıdakı fayl məxfi məlumatları təmizlənmiş şəkildə bizə çatır, siz isə bizə yazarkən qeyd edə biləcəyiniz bir ID alırsınız. Kiri Cloud-a daxil olmusunuzsa, hesabatın sizdən gəldiyi qeyd olunur ki, cavab verə bilək.", + "Website": "Veb-sayt", + "Welcome to Kiri": "Kiri-yə xoş gəlmisiniz", + "What Kiri's window uses on this {host}, not counting the {vm}:": "Kiri pəncərəsinin bu {host} üzərində istifadə etdiyi resurslar ({vm} nəzərə alınmadan):", + "What is WSL?": "WSL nədir?", + "What to import": "Nə idxal edilməlidir", + "What's new": "Yeniliklər", + "What's new in Kiri {version}": "Kiri {version} versiyasında yeniliklər", + "What's new in {version}": "{version} versiyasında yeniliklər", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Kiri-nin bir hissəsi çökdükdə stek izi (stack trace) və ondan əvvəlki son 200 jurnal sətri Kiri-nin və sistemin versiyaları, kompüterin modeli və bu quraşdırma üçün təsadüfi ID ilə birlikdə Kiri Cloud-a göndərilir. Kiri Cloud hesabınız və konteynerlərinizin daxilindəki heç nə göndərilmir. Ev qovluğunuz, imic və konteyner adları, tokenlər və şifrələr mətndən çıxarılır.", + "When the pod restarts, it gets a new name and the link ends.": "Pod yenidən başladıqda yeni ad alır və keçid işləməyi dayandırır.", + "Where should your containers run?": "Konteynerləriniz harada işləsin?", + "Which steps": "Hansı addımlar", + "Window": "Pəncərə", + "Windows Subsystem for Linux": "Linux üçün Windows Alt Sistemi (WSL)", + "Windows asks for an administrator's approval once.": "Windows bir dəfə administrator təsdiqi istəyir.", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows USB cihazlarını Microsoft-un tövsiyə etdiyi usbipd-win aləti vasitəsilə Kiri konteynerlərinin işlədiyi WSL-ə ötürür.", + "Windows is asking": "Windows soruşur", + "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows açılarkən Virtual Maşın Platformasını aktivləşdirir. Bundan sonra Kiri özü yenidən açılır və 2-ci addımdan davam edir. Əvvəlcə işinizi yadda saxlayın.", + "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "Bu tamamlandıqda Windows-u bir dəfə yenidən başlatmaq lazım olacaq. Kiri yenidən başlatmazdan əvvəl soruşacaq ki, işinizi yadda saxlaya biləsiniz.", + "With a fix": "Düzəlişi olan", + "Working dir": "İş qovluğu", + "Yesterday {time}": "Dünən {time}", + "You already have {engine}. Which should build your images?": "Artıq {engine} mövcuddur. İmiclərinizi hansı qursun?", + "You can change it later in Settings → Appearance.": "Bunu daha sonra Tənzimləmələr → Görünüş bölməsindən dəyişə bilərsiniz.", + "You can change this later in Settings → Domains.": "Bunu daha sonra Tənzimləmələr → Domenlər bölməsindən dəyişə bilərsiniz.", + "You can keep working while they copy.": "Onlar kopyalanarkən işləməyə davam edə bilərsiniz.", + "You can pull it again later.": "Daha sonra yenidən endirə bilərsiniz.", + "You can still pull the name as typed.": "İmici adını yazdığınız kimi göstərərək yenə də endirə bilərsiniz.", + "You can switch any time in Settings → Builds.": "İstədiyiniz vaxt Tənzimləmələr → Qurmalar bölməsindən dəyişə bilərsiniz.", + "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "Sizdə {ref} var ({when}). Yeniləmələri almaq üçün yenidən endirin; yalnız dəyişmiş təbəqələr endirilir.", + "You have {ref}. Pull again to get any updates; only changed layers download.": "Sizdə {ref} var. Yeniləmələri almaq üçün yenidən endirin; yalnız dəyişmiş təbəqələr endirilir.", + "You have {tags}": "Sizdə olanlar: {tags}", + "You have {version}": "Sizdəki: {version}", + "You have {version}.": "Sizdəki: {version}.", + "You sign in on github.com. Kiri gets a token that can only read packages.": "github.com üzərindən daxil olursunuz. Kiri yalnız paketləri oxuya bilən token alır.", + "You're sharing {name}": "Paylaşdığınız: {name}", + "Your AWS sign-in expired": "AWS girişinizin vaxtı bitib", + "Your account can use Kiri": "Hesabınız Kiri-dən istifadə edə bilər", + "Your containers keep running while it downloads.": "Endirilmə zamanı konteynerləriniz işləməyə davam edir.", + "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "Hər hansı məlumat yazılmazdan əvvəl ev qovluğunuzun yolu, tokenlər, şifrələr və digər məxfi məlumatlar mətndən çıxarılır.", + "Your link for {name} is live.": "{name} üçün keçidiniz aktivdir.", + "Your other Docker": "Digər Docker mühərrikiniz", + "Your own registry…": "Öz reyestriniz…", + "Your password and two-step code go to Docker, not Kiri.": "Şifrəniz və ikimərhələli doğrulama kodunuz Kiri-yə deyil, Docker-ə göndərilir.", + "Your password, or an access token if the registry offers them.": "Şifrəniz və ya reyestr dəstəkləyirsə, giriş tokeni.", + "Your plan allows {limit} tunnels at once, and all {limit} are in use: {slots}.": "Planınız eyni anda {limit} tunelə icazə verir və bütün {limit} tunel hazırda istifadədədir: {slots}.", + "Your plan allows {limit} tunnels at once. In use: {slots}.": "Planınız eyni anda {limit} tunelə icazə verir. İstifadədədir: {slots}.", + "Your plan allows {limit} tunnels at once; close one first.": "Planınız eyni anda {limit} tunelə icazə verir; əvvəlcə birini bağlayın.", + "Your plan allows {n} at once": "Planınız eyni anda {n} ədədə icazə verir", + "Your test container said hello. Open a new terminal and try it yourself:": "Test konteyneriniz salam göndərdi. Yeni terminal açın və özünüz yoxlayın:", + "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "{engine} imicləriniz və konteynerləriniz {engine} daxilində qalır. Siz onları köçürənə qədər {app} onları görə bilməz.", + "Your {engine} images stay there. Bring them over any time from Settings → Import.": "{engine} imicləriniz orada qalır. İstədiyiniz vaxt Tənzimləmələr → İdxal bölməsindən onları bura köçürə bilərsiniz.", + "Yours": "Sizinki", + "Zoom In": "Yaxınlaşdır", + "Zoom Out": "Uzaqlaşdır", + "a container": "bir konteyner", + "a free port": "boş bir port", + "a password": "bir şifrə", + "a root password": "bir root şifrəsi", + "a saved token": "saxlanılmış token", + "about {min} min left": "təxminən {min} dəq qaldı", + "about {n} min left": "təxminən {n} dəq qaldı", + "about {n} s left": "təxminən {n} san qaldı", + "about {sec} s left": "təxminən {sec} san qaldı", + "about {time} left": "təxminən {time} qaldı", + "address": "ünvan", + "an admin password": "bir administrator şifrəsi", + "and was stopped. The VM has {mem}.": "və dayandırıldı. VM-də {mem} var.", + "and {n} more…": "və daha {n}…", + "anonymous": "anonim", + "another computer": "başqa bir kompüter", + "answered in {ms} ms": "{ms} ms ərzində cavab verdi", + "approved": "təsdiqləndi", + "auto": "avtomatik", + "back": "geri", + "build ID": "qurma ID-si", + "builds": "qurma", + "cached": "keşdə", + "checked {ago}": "yoxlanıldı: {ago}", + "choose tag": "teq seç", + "close": "bağla", + "compose lines": "compose sətirləri", + "compressed": "sıxılmış", + "computer": "kompüter", + "container ID": "konteyner ID-si", + "containers": "konteyner", + "couldn't pull alpine: {why}": "alpine endirilə bilmədi: {why}", + "created {date}": "yaradıldı: {date}", + "database from {date}": "verilənlər bazası tarixi: {date}", + "digest": "digest", + "disk": "disk", + "disk read {read} · write {write}": "disk oxuma {read} · yazma {write}", + "docker build on Kiri": "Kiri-də docker build", + "docker build runs on Kiri's builder": "docker build Kiri-nin qurucusunda işləyir", + "docker flag": "docker bayrağı", + "docker now uses {app}": "docker artıq {app} ilə işləyir", + "docker run, from any terminal": "istənilən terminaldan docker run", + "docker talks to another engine now": "docker hazırda başqa mühərriklə işləyir", + "docker uses Kiri": "docker Kiri ilə işləyir", + "docker, Compose and Docker-socket tools reach Kiri": "docker, Compose və Docker soket alətləri Kiri-yə qoşulur", + "docker, docker compose and docker build use Kiri in every new terminal. Another Docker was found on this PC; leave this off to keep using it as the default.": "docker, docker compose və docker build hər yeni terminalda Kiri-dən istifadə edir. Bu PC-də başqa Docker tapıldı; onu standart olaraq saxlamaq üçün bunu söndürülmüş vəziyyətdə saxlayın.", + "docker, docker compose and docker build use Kiri in every new terminal. No other Docker was found on this PC.": "docker, docker compose və docker build hər yeni terminalda Kiri-dən istifadə edir. Bu PC-də başqa Docker tapılmadı.", + "doesn't update itself": "özünü yeniləmir", + "done": "bitdi", + "downloading": "endirilir", + "failed": "uğursuz", + "failed builds": "uğursuz qurma", + "failed containers": "uğursuz konteyner", + "for that user": "həmin istifadəçi üçün", + "from any page": "istənilən səhifədən", + "from the container's log": "konteynerin jurnalından", + "from the engine, when it tried to start it": "mühərrikdən, onu başlatmağa çalışarkən", + "from the engine, when it tried to start {name}": "mühərrikdən, {name} başladılmağa çalışılarkən", + "idle": "boşda", + "idle · nobody is visiting": "boşda · ziyarətçi yoxdur", + "image ID": "imic ID-si", + "images": "imic", + "in": "daxil olan", + "in config.json": "config.json daxilində", + "in progress": "davam edir", + "in {time}": "{time} ərzində", + "input events": "giriş hadisələri", + "installed": "quraşdırıldı", + "its build cache": "onun qurma keşi", + "just now": "indicə", + "kept in {v}": "{v} daxilində saxlanılır", + "kernel {version}": "nüvə {version}", + "kiri.service and the engine are in place": "kiri.service və mühərrik yerindədir", + "kubectl context": "kubectl konteksti", + "latest": "ən son", + "layers": "təbəqə", + "line {n}": "sətir {n}", + "links open in this app": "keçidlər bu tətbiqdə açılır", + "live": "aktiv", + "live {time}": "aktiv: {time}", + "macOS will ask for an administrator password next.": "macOS indi administrator şifrəsi istəyəcək.", + "made {ago}": "yaradıldı: {ago}", + "move": "köçür", + "needs privileged mode": "imtiyazlı rejim tələb edir", + "needs {name}": "{name} tələb edir", + "network interface": "şəbəkə interfeysi", + "networks": "şəbəkə", + "no layer: this line only changes the image's settings": "təbəqə yoxdur: bu sətir yalnız imicin tənzimləmələrini dəyişir", + "no monthly cap": "aylıq limit yoxdur", + "no speed limit": "sürət limiti yoxdur", + "none": "yoxdur", + "not in use": "istifadə olunmur", + "not running": "işləmir", + "now": "indi", + "of all {cpus} CPUs · peak {peak}": "/ cəmi {cpus} CPU · pik {peak}", + "of {cap}": "/ {cap}", + "of {limit} · peak {peak}": "/ {limit} · pik {peak}", + "on other computers": "digər kompüterlərdə", + "on {date} at {time}": "{date}, saat {time}", + "or hold {mod} and scroll": "və ya {mod} düyməsini basıb saxlayaraq sürüşdürün", + "out": "çıxan", + "owner/image on {registry}, such as {example}": "{registry} üzərində owner/image, məsələn: {example}", + "peak {rate}": "pik {rate}", + "pinned digest": "sabitlənmiş digest", + "pods": "pod", + "port {port}": "port {port}", + "port {port} is in use": "port {port} istifadədədir", + "pull": "endir", + "pulled {when}": "endirildi: {when}", + "pulling alpine": "alpine endirilir", + "pulls now": "indi endirir", + "raw HID": "xam (raw) HID", + "raw USB": "xam (raw) USB", + "received from visitors": "ziyarətçilərdən alınan", + "reconnected {n}×": "{n}× yenidən qoşuldu", + "report ID": "hesabat ID-si", + "running on other computers on your account": "hesabınızdakı digər kompüterlərdə işləyir", + "running…": "işləyir…", + "same as the user": "istifadəçi ilə eyni", + "saved with {v}": "{v} ilə saxlanıldı", + "sent to visitors": "ziyarətçilərə göndərilən", + "serial port": "ardıcıl (serial) port", + "services": "xidmət", + "sets {var}, for local use only.": "{var} təyin edilir; yalnız lokal istifadə üçün nəzərdə tutulub.", + "sets {var}, so it runs without a login or TLS.": "{var} təyin edilir; beləliklə, giriş və TLS olmadan işləyir.", + "sets {var}; it prints the password once in its log.": "{var} təyin edilir; şifrə jurnala yalnız bir dəfə yazılır.", + "settings": "tənzimləmələr", + "sign in to {host}": "{host} ünvanına daxil olun", + "skipped": "ötürüldü", + "sound card": "səs kartı", + "tag": "teq", + "the image's settings": "imicin tənzimləmələri", + "the last error lines in the container's log": "konteynerin jurnalındakı son xəta sətirləri", + "the last lines in the container's log": "konteynerin jurnalındakı son sətirlər", + "the link didn't open": "keçid açılmadı", + "the only web port": "yeganə veb portu", + "the port the app in it listens on": "daxilindəki tətbiqin dinlədiyi port", + "the saved sign-in": "saxlanılmış giriş", + "the test container did not run": "test konteyneri işləmədi", + "the test container did not run: {why}": "test konteyneri işləmədi: {why}", + "this Mac": "bu Mac", + "this PC": "bu PC", + "this build": "bu qurma", + "this image": "bu imic", + "to do": "ediləcək", + "today at {time}": "bu gün saat {time}", + "total ↓ {rx} · ↑ {tx}": "cəmi ↓ {rx} · ↑ {tx}", + "tunnels in use": "istifadədə olan tunel", + "untagged": "teqsiz", + "untagged images": "teqsiz imic", + "up": "işləmə müddəti", + "up to {size}": "ən çox {size}", + "up {time}": "{time} müddətdir işləyir", + "usbipd-win is installed": "usbipd-win quraşdırılıb", + "used by {names}": "istifadə edən: {names}", + "value": "dəyər", + "video": "video", + "volumes": "həcmlər", + "when the VM's {mem} ran out.": "VM-in {mem} yaddaşı tükəndikdə.", + "yesterday": "dünən", + "yesterday at {time}": "dünən saat {time}", + "you": "siz", + "your account": "hesabınız", + "your other Docker": "digər Docker mühərrikiniz", + "{all} lines": "{all} sətir", + "{app} doesn't update itself: rebuild it with cargo xtask app-dev": "{app} özünü yeniləmir: cargo xtask app-dev ilə yenidən qurun", + "{app} needs a password to start": "{app} başlamaq üçün şifrə tələb edir", + "{app} needs an admin password to start": "{app} başlamaq üçün administrator şifrəsi tələb edir", + "{app}: its own engine, containers and settings": "{app}: öz mühərriki, konteynerləri və tənzimləmələri", + "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "docker hansı mühərriklə işləsə də, {build} və {compose} Kiri-də icra olunur və imiclər Kiri-də saxlanılır.", + "{build} and {compose} run on Kiri, and the images are in Kiri. {engine} won't see them; run them with Kiri.": "{build} və {compose} Kiri-də işləyir və imiclər Kiri-də olur. {engine} onları görməyəcək; onları Kiri ilə işlədin.", + "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "{build} docker hara yönəlibsə orada qurur, ona görə də {engine} qurmaları {engine} daxilində qalır. docker Kiri-dən istifadə etdikdə qurmalar Kiri-də işləyir.", + "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "{build} docker hara yönəlibsə orada qurur. docker Kiri-dən istifadə etdikdə qurmalar Kiri-də işləyir.", + "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} həmişə Kiri-də qurur. Dəyişiklik artıq açıq olan terminallarda da dərhal tətbiq edilir. Docker-ə geri qayıtmaq docker-in qurma tənzimləmələrini Kiri dəyişməzdən əvvəlki vəziyyətinə qaytarır.", + "{docker}, {compose} and your tools run on {app} from now on.": "{docker}, {compose} və alətləriniz bundan sonra {app} üzərində işləyir.", + "{done} of {total}": "{done} / {total}", + "{engine} doesn't see them.": "{engine} onları görmür.", + "{file} ({i} of {n})": "{file} ({i} / {n})", + "{free} free of {total}": "{free} boş / {total}", + "{got} of {total}": "{got} / {total}", + "{got} of {total} MB": "{got} / {total} MB", + "{host} isn't searchable from here, so Kiri pulls the reference as typed.": "Buradan {host} üzərində axtarış aparmaq mümkün deyil. Kiri imici istinadı yazdığınız kimi göstərərək endirir.", + "{host} port {q}{port}{q} is not a port number (1–65535).": "{host} portu {q}{port}{q} düzgün port nömrəsi deyil (1–65535).", + "{host} wants a sign-in for {path}, and {user} can't pull it.": "{host}, {path} üçün giriş tələb edir və {user} onu endirə bilmir.", + "{host} wants a sign-in for {path}.": "{host}, {path} üçün giriş tələb edir.", + "{h} h": "{h} saat", + "{h} h {m} min": "{h} saat {m} dəq", + "{image} is a whole Kubernetes cluster in a container.": "{image} bir konteyner daxilində tam Kubernetes klasteridir.", + "{image} needs {what} to start": "{image} başlamaq üçün {what} tələb edir", + "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s} Kiri-nin Kubernetes klasteridir. Onu silmək Kubernetes-i söndürür. Klasterin məlumatları {k8s} verilənlər həcmində qalır; Tənzimləmələr → Kubernetes bölməsindəki Klasteri sil seçimi hər şeyi silir.", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} Kiri-nin Kubernetes klasteridir. Onu dayandırmaq Kubernetes-i söndürür və yenidən başlayana qədər pod-ları dayanır.", + "{kind} names are off: port {port} is in use. Pick another.": "{kind} adları deaktivdir: {port} portu istifadədədir. Başqa port seçin.", + "{kind} names are paused: a container has port {port}.": "{kind} adları ilə müraciət müvəqqəti dayandırılıb: {port} portu bir konteyner tərəfindən tutulub.", + "{label}, last minute": "{label}, son dəqiqə", + "{list} and {last}": "{list} və {last}", + "{list} are running from this image. Stop them first, then remove the image.": "{list} bu imic əsasında işləyir. Əvvəlcə onları dayandırın, sonra imici silin.", + "{list} is running from this image. Stop it first, then remove the image.": "{list} bu imic əsasında işləyir. Əvvəlcə onu dayandırın, sonra imici silin.", + "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "{list} bu imicdən yaradılıb və onsuz yenidən başlaya bilməz, ona görə də faylları ilə birlikdə silinir. Verilənlər həcmləri qalır.", + "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "{list} bu imicdən yaradılıb və onsuz yenidən başlaya bilməzlər, ona görə də faylları ilə birlikdə silinirlər. Verilənlər həcmləri qalır.", + "{list}, and {last}": "{list} və {last}", + "{live} for {time}": "{live} · {time}", + "{live} live, {starting} starting": "{live} aktivdir, {starting} başladılır", + "{local} names and HTTPS aren't on Linux yet.": "{local} adları və HTTPS hələ Linux-da yoxdur.", + "{ms} average": "orta {ms}", + "{m} min": "{m} dəq", + "{m} of the {n} picked": "seçilmiş {n} elementdən {m} ədədi", + "{m} of the {n} picked can't be deleted and stay.": "Seçilmiş {n} elementdən {m} ədədi silinə bilmir və qalır.", + "{names} on {host}": "{names} · {host}", + "{name} didn't start": "{name} başlamadı", + "{name} has no tag {tag}.": "{name} üçün {tag} teqi yoxdur.", + "{name} has the new environment": "{name} üçün yeni mühit dəyişənləri tətbiq edilib", + "{name} is in Kiri": "{name} Kiri-dədir", + "{name} is in use": "{name} istifadədədir", + "{name} is listening on {ports}": "{name} {ports} portlarını dinləyir", + "{name} is shared": "{name} paylaşılır", + "{name} is shared by {who}": "{name} {who} tərəfindən paylaşılır", + "{name} is still used by the container {container}. Remove the container first.": "{name} hələ də {container} konteyneri tərəfindən istifadə olunur. Əvvəlcə konteyneri silin.", + "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} dəyişdirilmir: imiclər kopyalanır, verilənlər həcmləri isə yalnız oxuma rejimində işləyən müvəqqəti köməkçi vasitəsilə oxunur. Sonra köməkçi silinir. Konteynerlər dayandırılmış vəziyyətdə köçürülür.", + "{name} isn't listening on a port yet, so there's nothing to share. Try again once it's up.": "{name} hələ heç bir portu dinləmir, ona görə də paylaşılacaq heç nə yoxdur. İşə düşdükdən sonra yenidən cəhd edin.", + "{name} isn't running. Start it to import from it; it doesn't need to stay open afterwards.": "{name} işləmir. Ondan idxal etmək üçün başladın; sonradan açıq qalmasına ehtiyac yoxdur.", + "{name} needs {var} to start": "{name} başlamaq üçün {var} tələb edir", + "{name} ran and finished": "{name} işə düşdü və icrasını tamamladı", + "{name} ran out of memory": "{name} üçün yaddaş tükəndi", + "{name} restarted with the new environment": "{name} yeni mühit dəyişənləri ilə yenidən başladıldı", + "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} olduğu kimi qalır: Kiri yalnız kopyalayır. Konteynerlər dayandırılmış vəziyyətdə gəlir.", + "{name} stays: Kubernetes is turned off or deleted in Settings → Kubernetes.": "{name} qalır: Kubernetes, Tənzimləmələr → Kubernetes bölməsindən söndürülür və ya silinir.", + "{name} stopped": "{name} dayandı", + "{name} stopped after {n} s": "{name} {n} san sonra dayandı", + "{name} stopped after {n} second": "{name} {n} saniyə sonra dayandı", + "{name} stopped after {n} seconds": "{name} {n} saniyə sonra dayandı", + "{name} stopped: {why}": "{name} dayandı: {why}", + "{n} CPU": "{n} CPU", + "{n} CPUs": "{n} CPU", + "{n} added": "{n} əlavə edildi", + "{n} cached": "{n} keşdə", + "{n} change": "{n} dəyişiklik", + "{n} changed": "{n} dəyişdirildi", + "{n} changes": "{n} dəyişiklik", + "{n} container": "{n} konteyner", + "{n} containers": "{n} konteyner", + "{n} d ago": "{n} gün əvvəl", + "{n} days ago": "{n} gün əvvəl", + "{n} device": "{n} cihaz", + "{n} devices": "{n} cihaz", + "{n} error": "{n} xəta", + "{n} errors": "{n} xəta", + "{n} external": "{n} xarici", + "{n} failed container": "{n} uğursuz konteyner", + "{n} failed containers": "{n} uğursuz konteyner", + "{n} from {what}": "{n} ədədi {what} mənbəyindən", + "{n} h ago": "{n} saat əvvəl", + "{n} image": "{n} imic", + "{n} image, {size}.": "{n} imic, {size}.", + "{n} image.": "{n} imic.", + "{n} images": "{n} imic", + "{n} images, {size}.": "{n} imic, {size}.", + "{n} images.": "{n} imic.", + "{n} in Kiri": "Kiri-də {n}", + "{n} item isn't in Kiri yet. Pick what to copy over.": "{n} element hələ Kiri-də yoxdur. Kopyalanacaqları seçin.", + "{n} items aren't in Kiri yet. Pick what to copy over.": "{n} element hələ Kiri-də yoxdur. Kopyalanacaqları seçin.", + "{n} layer": "{n} təbəqə", + "{n} layers": "{n} təbəqə", + "{n} line": "{n} sətir", + "{n} lines": "{n} sətir", + "{n} live": "{n} aktiv", + "{n} log line": "{n} jurnal sətri", + "{n} log line from the {parts}": "{parts} mənbəyindən {n} jurnal sətri", + "{n} log lines": "{n} jurnal sətri", + "{n} log lines from the {parts}": "{parts} mənbəyindən {n} jurnal sətri", + "{n} min ago": "{n} dəq əvvəl", + "{n} of this image, newest first": "Bu imicdən {n} ədəd, ən yenisi əvvəl", + "{n} of {limit} tunnels in use": "{n} / {limit} tunel istifadədədir", + "{n} of {total}": "{n} / {total}", + "{n} of {total} running": "{n} / {total} işləyir", + "{n} on {where}": "{where}: {n}", + "{n} optional": "{n} istəyə bağlı", + "{n} processes": "{n} proses", + "{n} removed": "{n} silindi", + "{n} request": "{n} sorğu", + "{n} requests": "{n} sorğu", + "{n} requests · {size} served": "{n} sorğu · {size} ötürüldü", + "{n} result": "{n} nəticə", + "{n} results": "{n} nəticə", + "{n} running container": "{n} işləyən konteyner", + "{n} running containers": "{n} işləyən konteyner", + "{n} selected": "{n} seçildi", + "{n} shared": "{n} paylaşılır", + "{n} shared · {where}": "{n} paylaşılır · {where}", + "{n} shared, on {where}": "{n} paylaşılır · {where}", + "{n} shared, {where}": "{n} paylaşılır · {where}", + "{n} shown": "{n} göstərilir", + "{n} stopped container": "{n} dayandırılmış konteyner", + "{n} stopped containers": "{n} dayandırılmış konteyner", + "{n} total": "cəmi {n}", + "{n} variable": "{n} dəyişən", + "{n} variables": "{n} dəyişən", + "{n} volume": "{n} həcm", + "{n} volumes": "{n} həcm", + "{n} vulnerabilities in {packages} packages": "{packages} paketdə {n} təhlükəsizlik boşluğu", + "{n} vulnerability in {packages} packages": "{packages} paketdə {n} təhlükəsizlik boşluğu", + "{n} with a fix": "{n} ədədinin düzəlişi var", + "{n} {noun}": "{n} {noun}", + "{n}s ago": "{n} san əvvəl", + "{os} settings": "{os} tənzimləmələri", + "{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.": "{os} avtomatik proksi konfiqurasiya (PAC) faylından istifadə edir. Kiri bu konfiqurasiyanı tətbiq edə bilmir. “Fərdi” seçimini edin və proksi məlumatlarını daxil edin.", + "{owner} runs this pod": "Bu pod-u {owner} işlədir", + "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}. İmiclər və ya Verilənlər həcmləri bölməsində göstərilmir: bu, docker build mexanizmidir.", + "{path} comes first on your PATH, so terminals run it instead of this Kiri. If it's an older Kiri, remove it: rm {path}": "PATH dəyişəninizdə {path} birinci gəlir, ona görə də terminallar bu Kiri əvəzinə onu işlədir. Əgər köhnə Kiri versiyasıdırsa, silin: rm {path}", + "{pct}% of this month's cap": "Bu ayın limitinin {pct}%-i", + "{ports} aren't web ports, so they aren't listed.": "{ports} veb portu deyil, ona görə də siyahıda göstərilmir.", + "{ports} isn't a web port, so it isn't listed.": "{ports} veb portu deyil, ona görə də siyahıda göstərilmir.", + "{program} on {host}": "{program} · {host}", + "{q}{name}{q} can't be a name: names have no spaces or {q}={q}.": "{q}{name}{q} ad ola bilməz: adlarda boşluq və ya {q}={q} ola bilməz.", + "{rate} limit": "{rate} limiti", + "{rate}/s limit": "{rate}/san limiti", + "{ready} containers": "{ready} konteyner", + "{running} of {all} running": "{running} / {all} işləyir", + "{running} running · {total}": "{running} işləyir · {total}", + "{showing} of {all} lines": "{showing} / {all} sətir", + "{size} MB in {secs} s": "{secs} san ərzində {size} MB", + "{size} MB · already here": "{size} MB · artıq buradadır", + "{size} is Ubuntu's download today.": "Hazırda Ubuntu-nu endirmək üçün {size} məlumat endirilməlidir.", + "{size} left": "{size} qaldı", + "{size} left this month": "Bu ay {size} qaldı", + "{size} received": "{size} alındı", + "{size} served": "{size} ötürüldü", + "{s} s": "{s} san", + "{text} with an error.": "{text} (xəta ilə).", + "{time} ago": "{time} əvvəl", + "{time} ago, when the VM's {mem} ran out.": "{time} əvvəl, VM-in {mem} yaddaşı tükəndikdə.", + "{used} of {total}": "{used} / {total}", + "{user} can run containers without sudo": "{user} sudo olmadan konteyner işlədə bilər", + "{user}'s sign-in is forgotten on this computer.": "Bu kompüterdə {user} üçün saxlanılmış giriş məlumatları silinir.", + "{var} sets the {kind} port, so it can't be changed here.": "{var} {kind} portunu təyin edir, ona görə də burada dəyişdirilə bilməz.", + "{version} available": "{version} mövcuddur", + "{version} ready": "{version} hazırdır", + "{vm} off": "{vm} söndürülüb", + "{vm} running": "{vm} işləyir", + "{what}?": "{what}?", + "{who} has it. Give {name} another port on this {host}, or stop {holder} first.": "Port {who} tərəfindən tutulub. Bu {host} üzərində {name} üçün başqa port verin və ya əvvəlcə {holder} prosesini dayandırın.", + "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who} dayandı ({when}).{more} Hesabat onu düzəltməyimizə kömək edir: ev qovluğunuz və tokenləriniz təmizlənmiş şəkildə stek izi (stack trace) və ondan əvvəlki son 200 jurnal sətri göndərilir.", + "{who} stopped {when}.{more} Crash reports are sent automatically, so this one goes to Kiri too.": "{who} dayandı ({when}).{more} Çökmə hesabatları avtomatik göndərilir, ona görə də bu hesabat da Kiri-yə gedir.", + "{why}. Give the VM more memory in Settings → Resources": "{why}. Tənzimləmələr → Resurslar bölməsindən VM-ə daha çox yaddaş ayırın", + "{zout} smaller · {zin} bigger · {z0} reset": "{zout} kiçilt · {zin} böyüt · {z0} sıfırla", + "· the newest 500 · up to 15 MB a part is kept": "· ən yeni 500 · hər hissə üçün ən çox 15 MB saxlanılır", + "– About {ratio}× the download of Kiri Linux": "– Kiri Linux-un endirmə həcmindən təxminən {ratio}× böyük", + "– Kiri shares it with your own Linux work": "– Kiri bu Linux mühitini şəxsi Linux işlərinizlə ortaq istifadə edir", + "– Not a Linux to use yourself": "– Birbaşa şəxsi istifadə üçün nəzərdə tutulmuş Linux deyil", + "— the end of the run before the last restart —": "— son yenidən başlatmadan əvvəlki icranın sonu —", + "— the log stream ended —": "— jurnal axını başa çatdı —", + "‹ Back": "‹ Geri", + "★ Star on GitHub": "★ GitHub-da ulduz ver", + "✓ Installed": "✓ Quraşdırıldı", + "Waiting to come back": "Geri qayıtması gözlənilir", + "Stop waiting": "Gözləməyi dayandır", + "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "Cihaz yenidən əlçatan olduqda Kiri onu avtomatik qoşur. Cihazı bu kompüterdə saxlamaq üçün gözləməyi dayandırın.", + "Fit the whole project": "Bütün layihəni sığdır", + "Find a service": "Xidmət axtar", + "docker compose up failed": "docker compose up uğursuz oldu", + "Not applied": "Tətbiq edilməyib", + "Saved, but the file has an error": "Saxlanıldı, lakin faylda xəta var", + "Your edits stay here. Apply waits until the file is back.": "Düzəlişləriniz burada qalır. Tətbiq et fayl qayıdana qədər gözləyir.", + "build": "qurma", + "Queue": "Növbə", + "The file changed outside Kiri since Apply saved it": "Tətbiq et saxladıqdan bəri fayl Kiri-dən kənarda dəyişdirilib", + "Couldn't apply {name}: {error}": "{name} tətbiq edilə bilmədi: {error}", + "Saved, not started yet": "Saxlanıldı, hələ başladılmayıb", + "image": "imic", + "Overwrite their changes": "Həmin dəyişikliklərin üzərinə yaz", + "Recreating…": "Yenidən yaradılır…", + "Service": "Xidmət", + "{n} need it": "{n} xidmətə lazımdır", + "CHANGES": "DƏYİŞİKLİKLƏR", + "Applied {name}": "{name} tətbiq edildi", + "Overwrite": "Üzərinə yaz", + "Restarting": "Yenidən başlayır", + "depends on": "asılılıqlar", + "{svc} stopped after Apply": "Tətbiq edildikdən sonra {svc} dayandı", + "Apply cancelled. {svc} had already changed; the rest were not changed.": "Tətbiq etmə ləğv edildi. {svc} artıq dəyişdirilmişdi; qalanlarına toxunulmadı.", + "Fix the file first.": "Əvvəlcə faylı düzəldin.", + "Open a compose file": "Compose faylı aç", + "Worker": "İşçi", + "Saved {name}, not applied: {error}": "{name} saxlanıldı, tətbiq edilmədi: {error}", + "Show in file": "Faylda göstər", + "needs {n}": "tələb: {n}", + "Apply cancelled. No service was changed.": "Tətbiq etmə ləğv edildi. Heç bir xidmət dəyişdirilmədi.", + "Arrows point at what a service needs; Compose starts those first.": "Oxlar xidmətin nəyə ehtiyacı olduğunu göstərir; Compose əvvəlcə onları başladır.", + "Starts on line {n} · click to jump there": "{n}-ci sətirdən başlayır · keçmək üçün klikləyin", + "Not in the file any more: stopped and removed. Its volumes stay.": "Artıq faylda yoxdur: dayandırıldı və silindi. Həcmləri saxlanılır.", + "the file changed outside Kiri": "fayl Kiri-dən kənarda dəyişdirilib", + "Overwrite their changes?": "Həmin dəyişikliklərin üzərinə yazılsın?", + "No Compose projects yet": "Hələ Compose layihəsi yoxdur", + "Saved, not applied": "Saxlanıldı, tətbiq edilmədi", + "New service, built from its folder.": "Yeni xidmət, öz qovluğundan qurulur.", + "The compose file isn't on this computer: {error}": "Compose faylı bu kompüterdə deyil: {error}", + "Saved, matches what runs": "Saxlanıldı, işləyənlə eynidir", + "Line {n}.": "Sətir {n}.", + "{name} is already being applied. Wait for it to finish, or cancel it.": "{name} artıq tətbiq edilir. Bitməsini gözləyin və ya ləğv edin.", + "{n} recreated": "{n} yenidən yaradıldı", + "Zoom out": "Uzaqlaşdır", + "That project is gone": "Həmin layihə artıq yoxdur", + "Couldn't run docker compose: {error}": "docker compose işə salına bilmədi: {error}", + "No logs yet.": "Hələ jurnal yoxdur.", + "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "{name} adlı layihə artıq {dir} qovluğundan işləyir. Onu açın və ya bu fayla ayrıca name: sətri əlavə edin.", + "{n} needs it": "{n} xidmətə lazımdır", + "File": "Fayl", + "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "{name} gizli olduqda Kiri planı göstərə bilmir. {apply} docker compose up əmrini işə salacaq.", + "REMOVED": "SİLİNDİ", + "The file changed outside Kiri. Apply writes your edits over it, and those changes are lost.": "Fayl Kiri-dən kənarda dəyişdirilib. Tətbiq et düzəlişlərinizi onun üzərinə yazır və həmin dəyişikliklər itir.", + "The other Apply of {name} finished. Your edit isn't applied yet.": "{name} üçün digər tətbiq etmə bitdi. Düzəlişiniz hələ tətbiq edilməyib.", + "The file changed outside Kiri.": "Fayl Kiri-dən kənarda dəyişdirilib.", + "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "{name} gizli olduqda Kiri bu faylı yoxlaya bilmir. Compose onu qəbul edir, ona görə Tətbiq et yenə də işləyir.", + "Compose rejects this file with its real values. Kiri can't show why with secrets hidden.": "Compose bu faylı həqiqi dəyərləri ilə rədd edir. Məxfi məlumatlar gizli olduqda Kiri səbəbi göstərə bilmir.", + "docker compose took longer than {secs} seconds": "docker compose {secs} saniyədən çox çəkdi", + "Discard": "İmtina et", + "Refresh": "Yenilə", + "Names Docker shows may contain secret values.": "Docker-in göstərdiyi adlarda məxfi dəyərlər ola bilər.", + "a newer image": "daha yeni imic", + "docker compose up stopped": "docker compose up dayandı", + "Applying…": "Tətbiq edilir…", + "Cache": "Keş", + "New service from {image}.": "{image} imicindən yeni xidmət.", + "{n} new": "{n} yeni", + "Apply cancelled. {n} services had already changed; the rest were not changed.": "Tətbiq etmə ləğv edildi. {n} xidmət artıq dəyişdirilmişdi; qalanlarına toxunulmadı.", + "Compose rejects this file: YAML error on line {n}": "Compose bu faylı rədd edir: {n}-ci sətirdə YAML xətası", + "Saved, not applied: {error}": "Saxlanıldı, tətbiq edilmədi: {error}", + "Kiri has no state folder": "Kiri-nin vəziyyət qovluğu yoxdur", + "{n} services": "{n} xidmət", + "Reload (lose your edits)": "Yenidən yüklə (düzəlişlər itəcək)", + "Not started": "Başladılmayıb", + "Couldn't open the compose file: {error}": "Compose faylı açıla bilmədi: {error}", + "Projects you start with {cmd} show up here once they have run on Kiri.": "{cmd} ilə başlatdığınız layihələr Kiri-də işlədikdən sonra burada görünür.", + "Saved": "Saxlanıldı", + "a variable it uses changed": "istifadə etdiyi dəyişən dəyişdi", + "Not created": "Yaradılmayıb", + "Saves the file, then runs {cmd}. Unchanged services keep running.": "Faylı saxlayır, sonra {cmd} əmrini işə salır. Dəyişməyən xidmətlər işləməyə davam edir.", + "NEW": "YENİ", + "needs {list}": "tələb: {list}", + "Removing…": "Silinir…", + "Creating…": "Yaradılır…", + "Metrics": "Metrikalar", + "Apply cancelled": "Tətbiq etmə ləğv edildi", + "The compose file is gone from its folder.": "Compose faylı öz qovluğunda yoxdur.", + "Zoom in": "Yaxınlaşdır", + "The image name from {name} isn't valid": "{name} dəyişənindən gələn imic adı yanlışdır", + "Kiri can't show this service's details with its secrets hidden": "Məxfi məlumatlar gizli olduqda Kiri bu xidmətin təfərrüatlarını göstərə bilmir", + "The file changed outside Kiri": "Fayl Kiri-dən kənarda dəyişdirilib", + "Recreate": "Yenidən yarat", + "Applied {name}, but {svc} stopped": "{name} tətbiq edildi, lakin {svc} dayandı", + "Web": "Veb", + "See its logs": "Jurnallarına bax", + "Remove from the list": "Siyahıdan çıxar", + "Compose rejects this file. A required variable may not be set: {name}.": "Compose bu faylı rədd edir. Tələb olunan dəyişən təyin edilməmiş ola bilər: {name}.", + "environment": "mühit", + "Search": "Axtarış", + "Couldn't save the compose file: {error}": "Compose faylı saxlanıla bilmədi: {error}", + "Compose files": "Compose faylları", + "Scheduler": "Planlaşdırıcı", + "Kiri has nothing to put back": "Kiri-nin geri qaytaracağı heç nə yoxdur", + "Put back the file as it was before Apply saved over it": "Faylı Tətbiq et üzərinə yazmazdan əvvəlki vəziyyətinə qaytar", + "Kiri can't check this file's variables, so it manages this project by name. Apply changes from a terminal.": "Kiri bu faylın dəyişənlərini yoxlaya bilmədiyi üçün layihəni adı ilə idarə edir. Dəyişiklikləri terminaldan tətbiq edin.", + "Edited, not applied": "Düzəliş edilib, tətbiq edilməyib", + "This file isn't a compose file: it has no services": "Bu fayl Compose faylı deyil: heç bir xidməti yoxdur", + "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri docker CLI-ni tapa bilmir. Yenidən quraşdırmaq üçün Kiri-ni yenidən başladın.", + "Fit": "Sığdır", + "Compose rejects this file: YAML error in an included file, line {n}": "Compose bu faylı rədd edir: əlavə edilmiş faylda YAML xətası, sətir {n}", + "Open a compose file…": "Compose faylı aç…", + "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "Bu faylın adında {vars} istifadə olunur. Adın içərisinə məxfi dəyər düşməməsi üçün Kiri qovluğun adını ({name}) istifadə edir.", + "Kiri doesn't know that action": "Kiri bu əməliyyatı tanımır", + "Kiri can't find this project's compose file.": "Kiri bu layihənin Compose faylını tapa bilmir.", + "ports": "portlar", + "Newest container created {time}": "Ən yeni konteyner yaradıldı: {time}", + "Compose file": "Compose faylı", + "Not started yet. Apply on the Compose file tab brings every service up.": "Hələ başladılmayıb. Compose faylı vərəqindəki Tətbiq et bütün xidmətləri işə salır.", + "Couldn't change {name}: {error}": "{name} dəyişdirilə bilmədi: {error}", + "{n} unchanged": "{n} dəyişmədi", + "Create": "Yarat", + "Structure": "Struktur", + "YAML files": "YAML faylları", + "{n} service": "{n} xidmət", + "{name} are used in a name or folder path. Docker shows those in plain text.": "{name} adda və ya qovluq yolunda istifadə olunur. Docker bunları açıq mətn kimi göstərir.", + "Its logs, Start, Stop and Remove still work.": "Jurnalları, Başlat, Dayandır və Sil hələ də işləyir.", + "Showing the file as edited, not applied yet.": "Fayl düzəliş edilmiş formada göstərilir, hələ tətbiq edilməyib.", + "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "Hələ heç nə yoxdur: fayl işləyənlə eynidir. Dəyişdirdikdə hər xidmətə nə olacağı burada göstərilir.", + "Kiri can't read the compose file: {error}": "Kiri Compose faylını oxuya bilmir: {error}", + "Pick a .yaml or .yml compose file": ".yaml və ya .yml Compose faylı seçin", + "Applied {name}, but {svcs} stopped": "{name} tətbiq edildi, lakin {svcs} dayandı", + "Compose rejects this file: YAML error in {file}, line {n}": "Compose bu faylı rədd edir: {file} daxilində YAML xətası, sətir {n}", + "What Apply does": "Tətbiq et nə edir", + "Saved, but an included file has an error": "Saxlanıldı, lakin əlavə edilmiş faylda xəta var", + "{name} is used in a name or folder path. Docker shows those in plain text.": "{name} adda və ya qovluq yolunda istifadə olunur. Docker bunları açıq mətn kimi göstərir.", + "Apply": "Tətbiq et", + "Couldn't read env file {file}: it isn't a local regular file": "{file} env faylı oxuna bilmədi: yerli adi fayl deyil", + "Keep editing": "Düzəlişə davam et", + "The compose file is read-only, so Kiri can't save it. Make it writable, then Apply again.": "Compose faylı yalnız oxumaq üçündür, Kiri onu saxlaya bilmir. Yazıla bilən edin, sonra yenidən Tətbiq et düyməsinə basın.", + "There's no Compose project {name} on Kiri": "Kiri-də {name} adlı Compose layihəsi yoxdur", + "The compose file is back, and differs from your edits.": "Compose faylı qayıtdı və düzəlişlərinizdən fərqlənir.", + "{n} more": "+{n} digər", + "Unchanged": "Dəyişmədi", + "Saved, but line {n} has an error": "Saxlanıldı, lakin {n}-ci sətirdə xəta var", + "Actual size": "Faktiki ölçü", + "Show in compose file": "Compose faylında göstər", + "Open project": "Layihəni aç", + "not started": "başladılmayıb", + "Apply the compose file to create it": "Yaratmaq üçün Compose faylını tətbiq edin", + "Hide {name}'s containers": "{name} konteynerlərini gizlət", + "Show {name}'s containers": "{name} konteynerlərini göstər", + "Hide {name}'s pods": "{name} podlarını gizlət", + "Show {name}'s pods": "{name} podlarını göstər", + "{n} more in a Compose project": "Compose layihəsində daha {n}", + "{n} more in Compose projects": "Compose layihələrində daha {n}", + "Your only container is in a Compose project": "Yeganə konteyneriniz Compose layihəsindədir", + "All {n} containers are in Compose projects": "Bütün {n} konteyner Compose layihələrindədir", + "Skipped until Kiri next opens": "Kiri növbəti dəfə açılana qədər ötürüldü", + "Couldn't add the kiri docker context": "kiri docker konteksti əlavə edilə bilmədi", + "The kiri and docker commands": "kiri və docker əmrləri", + "Ready in any new terminal": "İstənilən yeni terminalda hazırdır", + "Couldn't add them to your shell": "Shell-ə əlavə edilə bilmədi", + "Starts at login": "Girişdə başlayır", + "The engine starts when you log in": "Sistemə daxil olduqda mühərrik başlayır", + "The engine runs from the app for now": "Mühərrik hələlik tətbiqdən işləyir", + "Show log": "Jurnalı göstər", + "Continue anyway": "Yenə də davam et", + "One step didn't work. Everything else is ready.": "Bir addım alınmadı. Qalan hər şey hazırdır.", + "Some steps didn't work. Everything else is ready.": "Bəzi addımlar alınmadı. Qalan hər şey hazırdır.", + "No matches": "Uyğunluq yoxdur", + "Disk image size": "Disk imicinin ölçüsü", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Daemon üçün KIRI_CPUS, KIRI_MEMORY_MIB və ya KIRI_DISK_GB təyin edilib və onlar buradakı tənzimləmələrdən üstündür.", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Hazırda {cpus}, ən çox {mem} yaddaş və {disk} disklə işləyir.", + "No other WSL distros installed.": "Başqa WSL distributivi quraşdırılmayıb.", + "WSL integration": "WSL inteqrasiyası", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Bağla: pəncərənin istifadə etdiyi yaddaş boşaldılır. Yenidən açılması bir az çəkir və açıq terminallar bağlanır.", + "Closing the window": "Pəncərə bağlandıqda", + "Hide: the window stays ready and opens again at once.": "Gizlət: pəncərə hazır qalır və dərhal yenidən açılır.", + "Start Kiri at sign-in": "Sistemə girişdə Kiri-ni başlat", + "Start Kiri in the background when you sign in.": "Sistemə daxil olduqda Kiri-ni arxa planda başladır.", + "Stop the engine when Kiri quits": "Kiri-dən çıxdıqda mühərriki dayandır", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-dən çıxmaq işləyən konteynerləri və mühərriki dayandırır. Kiri-ni açmaq onu yenidən başladır.", + "{env} is set, so docker uses another engine instead of {app}": "{env} təyin edilib, ona görə docker {app} əvəzinə başqa mühərrik işlədir", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "{env} təyin edilib, ona görə {docker} {app} əvəzinə başqa mühərrik işlədir. {app} işlətmək üçün onu shell-dən silin.", + "{env} is set": "{env} təyin edilib", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "Bu sessiyada {env} docker kontekstini üstələyir, ona görə konteksti dəyişmək {docker} əmrini {app} üzərinə keçirməyəcək. {cmd} ilə təmizləyin və ya profilinizdən silin.", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} {app} üzərinə yönəlib. Testcontainers, IDE qoşmaları və SDK-lar kimi alətlər ondan birbaşa istifadə edir.", + "another engine": "başqa mühərrik", + "{path} belongs to {engine} and stays so.": "{path} {engine} mühərrikinə məxsusdur və elə də qalır.", + "Tools that ignore docker contexts can use {hint}": "docker kontekstlərini nəzərə almayan alətlər {hint} istifadə edə bilər", + "command": "əmr", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} boşdur. docker kontekstlərini nəzərə almayan alətlərin {app} tapması üçün onu {app} ilə əlaqələndirin.", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} boşdur. Başqa Docker mühərriki işləmədikdə {app} hər işə düşəndə ona xidmət göstərir.", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} boşdur. Başqa Docker mühərriki tutmadıqda Kiri başlayarkən {service} onu əlaqələndirir.", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} boşdur. {app} onu quraşdırılmış Kiri üçün saxlayır.", + "Linking…": "Əlaqələndirilir…", + "Use {app}": "{app} işlət", + "Free": "Boş", + "Docker socket": "Docker soketi", + "The {docker} command uses {app}.": "{docker} əmri {app} ilə işləyir.", + "{env} is set in this session, so {docker} uses another engine.": "Bu sessiyada {env} təyin edilib, ona görə {docker} başqa mühərrik işlədir.", + "The {docker} command uses {engine}.": "{docker} əmri {engine} ilə işləyir.", + "Switching…": "Keçilir…", + "{docker} command": "{docker} əmri", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock indi Kiri-ni göstərir", + "Could not link /var/run/docker.sock: {error}": "/var/run/docker.sock əlaqələndirilə bilmədi: {error}", + "Stopping containers…": "Konteynerlər dayandırılır…", + "Copying data…": "Məlumatlar kopyalanır…", + "Verifying copy…": "Kopya yoxlanılır…", + "Switching storage…": "Saxlama yeri dəyişdirilir…", + "Restarting engine…": "Mühərrik yenidən başladılır…", + "Moving data…": "Məlumatlar köçürülür…", + "Storage location unavailable": "Saxlama yeri əlçatmazdır", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri {path} daxilində öz məlumatlarını tapa bilmədi. Diski qoşub yenidən cəhd edin, başqa qovluq seçin və ya standart yerə sıfırlayın.", + "Change…": "Dəyişdir…", + "Reset to default": "Standarta sıfırla", + "Open storage settings": "Saxlama tənzimləmələrini aç", + "Start Kiri to change its storage location. ({error})": "Saxlama yerini dəyişmək üçün Kiri-ni başladın. ({error})", + "{size} used": "{size} istifadədə", + "{size} free": "{size} boş", + "Default": "Standart", + "Moving Kiri's data to {path}.": "Kiri məlumatları {path} qovluğuna köçürülür.", + "Running containers pause while Kiri copies its data and start again once it's done.": "Kiri məlumatları kopyalayarkən işləyən konteynerlər fasilə verir və bitdikdən sonra yenidən başlayır.", + "Couldn't change storage location": "Saxlama yeri dəyişdirilə bilmədi", + "Old data": "Köhnə məlumatlar", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Əvvəlki məlumatlar hələ də {path} daxilindədir. Yeni yerdə hər şey işlədikdən sonra onu silin.", + "Remove old data": "Köhnə məlumatları sil", + "Storage location": "Saxlama yeri", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} Kiri-nin saxlama yerini təyin edir, ona görə burada dəyişdirilə bilməz.", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "İmiclər, konteynerlər və həcmlər bu qovluqda saxlanılır. Xarici disklər yerli fayl sistemindən istifadə etməlidir (macOS-da APFS, Linux-da ext4/xfs/btrfs, Windows-da NTFS); FAT və exFAT dəstəklənmir.", + "Reset storage location to default?": "Saxlama yeri standarta sıfırlansın?", + "Change storage location?": "Saxlama yeri dəyişdirilsin?", + "Destination: {path} ({free} free).": "Hədəf: {path} ({free} boş).", + "Destination: {path}.": "Hədəf: {path}.", + "Existing Kiri data in this folder will be replaced.": "Bu qovluqdakı mövcud Kiri məlumatları əvəzlənəcək.", + "Migration mode": "Köçürmə rejimi", + "Move existing images, containers, and volumes": "Mövcud imicləri, konteynerləri və həcmləri köçür", + "Stops running containers, copies your data, and starts them again.": "İşləyən konteynerləri dayandırır, məlumatlarınızı kopyalayır və yenidən başladır.", + "Start fresh": "Sıfırdan başla", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Yeni qovluqda boş başlayır. Köhnə qovluğunuz siz silənə qədər qalır.", + "Kiri will switch to this folder and restart the engine.": "Kiri bu qovluğa keçəcək və mühərriki yenidən başladacaq.", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Kiri məlumatlarınızı köçürərkən işləyən konteynerlər dayanacaq və bitdikdən sonra yenidən başlayacaq.", + "Move data": "Məlumatları köçür", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri standart qovluğuna qayıdacaq və mühərriki yenidən başladacaq. Ayrılmış diskdəki məlumatlar silinmir.", + "Remove old data?": "Köhnə məlumatlar silinsin?", + "Everything in {path} will be deleted for good.": "{path} daxilindəki hər şey həmişəlik silinəcək.", + "Choose a storage folder": "Saxlama qovluğu seçin", + "Kiri's data is moving already": "Kiri məlumatları artıq köçürülür", + "Kiri's data moved to {path}": "Kiri məlumatları {path} qovluğuna köçürüldü", + "Storage is available again": "Saxlama sahəsi yenidən əlçatandır", + "Old data removed": "Köhnə məlumatlar silindi", + "A proxy on this computer is reached as {host}.": "Bu kompüterdəki proksiyə {host} kimi müraciət olunur.", + "VPNs need no setting: container traffic leaves through Linux.": "VPN-lər üçün tənzimləmə tələb olunmur: konteyner trafiki Linux üzərindən çıxır.", + "Shared with Linux: containers only use them while busy.": "Linux ilə ortaqdır: konteynerlər yalnız işləyərkən bunlardan istifadə edir.", + "The most containers and the engine may take. Unused memory stays free on Linux.": "Konteynerlərin və mühərrikin ala biləcəyi ən çox yaddaş. İstifadə olunmayan yaddaş Linux-da boş qalır.", + "The engine is off; it starts with these next time.": "Mühərrik sönülüdür; növbəti dəfə bu tənzimləmələrlə başlayacaq.", + "Restart engine to apply": "Tətbiq etmək üçün mühərriki yenidən başlat", + "Windows bind-mount file events": "Windows qoşulmuş qovluq fayl hadisələri", + "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "Canlı yeniləmə üçün Windows disklərindəki ({path} kimi) fayl dəyişikliklərini konteynerlərə ötürür. Boşdaykən CPU işlətmir.", + "One text file, redacted, saved to your Desktop. Read it before you share it.": "Məxfi məlumatları çıxarılmış bir mətn faylı İş masasında saxlanılır. Paylaşmazdan əvvəl onu oxuyun.", + "The 5 newest crash reports for Kiri": "Kiri üçün ən yeni 5 qəza hesabatı", + "Kiri and this PC": "Kiri və bu PC", + "Kiri and this computer": "Kiri və bu kompüter", + "Versions, {os}, whether the engine runs, how many containers and images": "Versiyalar, {os}, mühərrikin işləyib-işləməməsi, konteyner və imic sayı", + "Saved. The engine uses these from its next start": "Saxlanıldı. Mühərrik növbəti işə düşmədən etibarən bunları tətbiq edəcək", + "5 min": "5 dəq", + "10 min": "10 dəq", + "30 min": "30 dəq", + "Never": "Heç vaxt", + "Build cache limit": "Qurma keşi limiti", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "BuildKit keşi bu ölçünü keçdikdə ən köhnə keşlənmiş qatlar avtomatik təmizlənir.", + "Stop builder when idle": "Boşdaykən qurucunu dayandır", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Boşdaykən yaddaş işlətməməsi üçün qurmalar arasında BuildKit-i dayandırır; növbəti qurma onu bir saniyədən tez oyadır.", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Daemon üçün KIRI_BUILD_CACHE_GB və ya KIRI_BUILDER_IDLE_SECS təyin edilib və onlar buradakı tənzimləmələrdən üstündür.", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT: ən sürətli. Cloudflare WARP və ya korporativ təhlükəsizlik divarı konteyner HTTPS trafikini bloklayırsa, Host ötürücüsünə keçin. VM yenidən başladıqda tətbiq olunur.", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Host ötürücüsü: bağlantılar Virtualization.framework NAT əvəzinə macOS-dakı Kiri üzərindən çıxır. VM yenidən başladıqda tətbiq olunur.", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Mühitdə KIRI_SHARED_NAT təyin edilib və üstünlüyə malikdir.", + "Outbound VM traffic": "Çıxan VM trafiki", + "macOS NAT": "macOS NAT", + "Host relay": "Host ötürücüsü", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "VM diskinin böyüyə biləcəyi ən böyük ölçü. {os} üzərində yer yalnız məlumat yazıldıqca tutulur və istifadə olunmayan yer {storage} bölməsindən geri qaytarıla bilər. Yenidən başlatmada tətbiq olunur.", + "Settings → Storage": "Tənzimləmələr → Saxlama sahəsi", + "VM disk space": "VM disk sahəsi", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Yerli Linux birbaşa host fayl sistemindən istifadə edir — silinmiş imiclər və həcmlər yeri dərhal boşaldır.", + "Compact disk…": "Diski sıxlaşdır…", + "Reclaim space": "Yeri geri qaytar", + "Compacting…": "Sıxlaşdırılır…", + "Reclaiming…": "Qaytarılır…", + "Compacting {vhdx} and restarting the engine…": "{vhdx} sıxlaşdırılır və mühərrik yenidən başladılır…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{os} üzərində {host}, VM daxilində {inUse} istifadədə · boş bloklar təmizlənir…", + "Trimming unused blocks inside the VM disk…": "VM diskindəki istifadə olunmayan bloklar təmizlənir…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "Windows üzərində {host} ({vhdx}), {inUse} istifadədə · {freed}.", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{os} üzərində {host}, VM daxilində {inUse} istifadədə · {freed}.", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "Windows üzərində {host} ({vhdx}), {inUse} istifadədə · qaytarılacaq yer yoxdur.", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{os} üzərində {host}, VM daxilində {inUse} istifadədə · qaytarılacaq yer yoxdur.", + "Nothing to reclaim.": "Qaytarılacaq yer yoxdur.", + "{size} can be given back": "{size} geri qaytarıla bilər", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "Windows üzərində {host} ({vhdx}), {inUse} istifadədə · {can}. Sıxlaşdırma mühərriki yenidən başladır.", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{os} üzərində {host}, VM daxilində {inUse} istifadədə · konteynerləri dayandırmadan {can}.", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "Windows üzərində {host} ({vhdx}). Sıxlaşdırma boş yeri qaytarır və mühərriki yenidən başladır.", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{os} üzərində {host}. Yeri qaytarma konteynerləri dayandırmadan VM diskindəki boş blokları təmizləyir.", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "{vhdx} daxilindəki boş yeri Windows-a qaytarır. Sıxlaşdırma mühərriki yenidən başladır.", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Konteynerləri dayandırmadan VM diskindəki boş blokları {os} sisteminə qaytarır.", + "Cleaning up stopped containers, untagged images, and build cache…": "Dayandırılmış konteynerlər, teqsiz imiclər və qurma keşi təmizlənir…", + "{count} ({size})": "{count} ({size})", + "build cache": "qurma keşi", + "No stopped containers, untagged images or build cache · {freed}.": "Dayandırılmış konteyner, teqsiz imic və ya qurma keşi yoxdur · {freed}.", + "No stopped containers, untagged images or build cache.": "Dayandırılmış konteyner, teqsiz imic və ya qurma keşi yoxdur.", + "Cleaning up…": "Təmizlənir…", + "Clean up…": "Təmizlə…", + "Unused Docker data": "İstifadə olunmayan Docker məlumatları", + "Command-line tools in shell": "Shell-də əmr sətri alətləri", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Yeni terminallarda {docker}, {kubectl} və {kiri} işləməsi üçün {zshrc} və {zprofile} fayllarına {bin} əlavə edin.", + "Uninstall Kiri": "Kiri-ni sil", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Mühərriki dayandırır, Kiri-nin arxa plan xidmətini, CLI keçidlərini və shell profil qeydlərini silir və əvvəlki Docker kontekstinizi ({cmd}) bərpa edir.", + "Uninstall Kiri…": "Kiri-ni sil…", + "Couldn't reclaim disk space: {error}": "Disk sahəsi geri qaytarıla bilmədi: {error}", + "Reclaimed {size} on {os}": "{os} üzərində {size} geri qaytarıldı", + "Nothing to reclaim": "Qaytarılacaq yer yoxdur", + "Couldn't clean up unused Docker data: {error}": "İstifadə olunmayan Docker məlumatları təmizlənə bilmədi: {error}", + "Cleaned up {size} of unused Docker data": "{size} istifadə olunmayan Docker məlumatı təmizləndi", + "Cleaned up unused Docker data": "İstifadə olunmayan Docker məlumatları təmizləndi", + "Compact WSL disk?": "WSL diski sıxlaşdırılsın?", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} sıxlaşdırıldıqda boş yer Windows-a qaytarılır və Kiri mühərriki ilə işləyən konteynerlər qısa müddətə yenidən başladılır.", + "Compact disk": "Diski sıxlaşdır", + "Clean up unused Docker data?": "İstifadə olunmayan Docker məlumatları təmizlənsin?", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Dayandırılmış konteynerləri, teqsiz imicləri və BuildKit qurma keşini silir. İşləyən konteynerlər və teqli imiclər saxlanılır.", + "Clean up": "Təmizlə", + "Uninstall Kiri?": "Kiri silinsin?", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Mühərriki dayandırır, Kiri-nin arxa plan xidmətini, CLI keçidlərini və shell profil qeydlərini silir və əvvəlki Docker kontekstinizi bərpa edir. İmicləriniz və həcmləriniz siz silənə qədər Kiri-nin məlumat qovluğunda qalır.", + "Cluster": "Klaster", + "default": "standart", + "k3s version": "k3s versiyası", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Klaster qovşağı üçün imic versiyası ({cmd}). Yenidən yaradıldıqda tətbiq olunur.", + "Extra server flags": "Əlavə server bayraqları", + "Passed to {srv} ({flag}), separated by spaces.": "Boşluqla ayrılaraq {srv} ({flag}) əmrinə ötürülür.", + "Startup manifests": "Başlanğıc manifestləri", + "YAML files in {path} are applied whenever the cluster starts.": "Klaster hər başladıqda {path} daxilindəki YAML faylları tətbiq olunur.", + "Open folder": "Qovluğu aç", + "{n} untagged image": "{n} teqsiz imic", + "{n} untagged images": "{n} teqsiz imic", + "Uninstall Kiri from Windows Settings → Apps": "Kiri-ni Windows Tənzimləmələri → Tətbiqlər bölməsindən silin", + "Builder settings saved": "Qurucu tənzimləmələri saxlanıldı", + "Could not save builder settings: {error}": "Qurucu tənzimləmələri saxlanıla bilmədi: {error}", + "Disk reclaim is already running": "Disk sahəsinin qaytarılması artıq icra olunur", + "Outbound VM traffic setting saved. Restart the VM to apply.": "Çıxan VM trafiki tənzimləməsi saxlanıldı. Tətbiq etmək üçün VM-i yenidən başladın.", + "Could not save VM networking setting: {error}": "VM şəbəkə tənzimləməsi saxlanıla bilmədi: {error}", + "Added Kiri command-line tools to shell profiles": "Kiri əmr sətri alətləri shell profillərinə əlavə edildi", + "Removed Kiri command-line tools from shell profiles": "Kiri əmr sətri alətləri shell profillərindən silindi", + "Could not update shell profiles: {error}": "Shell profilləri yenilənə bilmədi: {error}", + "Uninstalling Kiri…": "Kiri silinir…", + "Could not uninstall Kiri: {error}": "Kiri silinə bilmədi: {error}", + "Uninstall Kiri using your system package manager": "Kiri-ni sistem paket menecerinizlə silin", + "Swap": "Swap", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM-in yaddaşı bitdikdə istifadə edə biləcəyi disk sahəsi — beləliklə konteynerlər dayanmaq əvəzinə yavaşlayır. Yenidən başlatmada tətbiq olunur.", + "Community": "İcma" +} diff --git a/crates/kiri/src/ui/lang/bg.json b/crates/kiri/src/ui/lang/bg.json index 8d4866ad5..8fa324220 100644 --- a/crates/kiri/src/ui/lang/bg.json +++ b/crates/kiri/src/ui/lang/bg.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Неуспешно деинсталиране на Kiri: {error}", "Uninstall Kiri using your system package manager": "Деинсталирайте Kiri чрез пакетния мениджър на системата си", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Дисково пространство, което VM може да използва, когато паметта ѝ свърши, така че контейнерите да се забавят, вместо да бъдат спрени. Прилага се при рестартиране." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Дисково пространство, което VM може да използва, когато паметта ѝ свърши, така че контейнерите да се забавят, вместо да бъдат спрени. Прилага се при рестартиране.", + "Community": "Общност" } diff --git a/crates/kiri/src/ui/lang/bn.json b/crates/kiri/src/ui/lang/bn.json index 596b26e2e..15c593d46 100644 --- a/crates/kiri/src/ui/lang/bn.json +++ b/crates/kiri/src/ui/lang/bn.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri আনইনস্টল করা যায়নি: {error}", "Uninstall Kiri using your system package manager": "আপনার সিস্টেমের প্যাকেজ ম্যানেজার দিয়ে Kiri আনইনস্টল করুন", "Swap": "সোয়াপ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "মেমরি ফুরিয়ে গেলে VM যে ডিস্ক স্পেস ব্যবহার করতে পারে, ফলে কন্টেইনার বন্ধ না হয়ে ধীর হয়ে যায়। রিস্টার্টে প্রযোজ্য হয়।" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "মেমরি ফুরিয়ে গেলে VM যে ডিস্ক স্পেস ব্যবহার করতে পারে, ফলে কন্টেইনার বন্ধ না হয়ে ধীর হয়ে যায়। রিস্টার্টে প্রযোজ্য হয়।", + "Community": "কমিউনিটি" } diff --git a/crates/kiri/src/ui/lang/ca.json b/crates/kiri/src/ui/lang/ca.json index ac4e8adda..1720ba373 100644 --- a/crates/kiri/src/ui/lang/ca.json +++ b/crates/kiri/src/ui/lang/ca.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "No s'ha pogut desinstal·lar Kiri: {error}", "Uninstall Kiri using your system package manager": "Desinstal·la Kiri amb el gestor de paquets del sistema", "Swap": "Intercanvi (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espai de disc que la VM pot fer servir quan se li acaba la memòria, perquè els contenidors s’alenteixin en lloc d’aturar-se. S’aplica en reiniciar." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espai de disc que la VM pot fer servir quan se li acaba la memòria, perquè els contenidors s’alenteixin en lloc d’aturar-se. S’aplica en reiniciar.", + "Community": "Comunitat" } diff --git a/crates/kiri/src/ui/lang/ckb.json b/crates/kiri/src/ui/lang/ckb.json index df0e8f10f..1cc4ee501 100644 --- a/crates/kiri/src/ui/lang/ckb.json +++ b/crates/kiri/src/ui/lang/ckb.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "نەتوانرا Kiri بسڕدرێتەوە: {error}", "Uninstall Kiri using your system package manager": "Kiri بە بەڕێوەبەری پاکێجی سیستەمەکەت بسڕەوە", "Swap": "سواپ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "شوێنی دیسک کە VM دەتوانێت بەکاری بهێنێت کاتێک بیرگەکەی تەواو دەبێت، بۆ ئەوەی کۆنتەینەرەکان خاو ببنەوە لەجیاتی ڕاگیران. لە دەستپێکردنەوەدا جێبەجێ دەبێت." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "شوێنی دیسک کە VM دەتوانێت بەکاری بهێنێت کاتێک بیرگەکەی تەواو دەبێت، بۆ ئەوەی کۆنتەینەرەکان خاو ببنەوە لەجیاتی ڕاگیران. لە دەستپێکردنەوەدا جێبەجێ دەبێت.", + "Community": "کۆمەڵگە" } diff --git a/crates/kiri/src/ui/lang/cs.json b/crates/kiri/src/ui/lang/cs.json index a3d585cb2..61f1baf71 100644 --- a/crates/kiri/src/ui/lang/cs.json +++ b/crates/kiri/src/ui/lang/cs.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri se nepodařilo odinstalovat: {error}", "Uninstall Kiri using your system package manager": "Odinstalujte Kiri pomocí správce balíčků vašeho systému", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Místo na disku, které VM může použít, když jí dojde paměť, takže se kontejnery zpomalí, místo aby byly zastaveny. Projeví se po restartu." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Místo na disku, které VM může použít, když jí dojde paměť, takže se kontejnery zpomalí, místo aby byly zastaveny. Projeví se po restartu.", + "Community": "Komunita" } diff --git a/crates/kiri/src/ui/lang/de.json b/crates/kiri/src/ui/lang/de.json index b7a2e291f..2f318a0e2 100644 --- a/crates/kiri/src/ui/lang/de.json +++ b/crates/kiri/src/ui/lang/de.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri konnte nicht deinstalliert werden: {error}", "Uninstall Kiri using your system package manager": "Deinstalliere Kiri über die Paketverwaltung deines Systems", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Speicherplatz auf der Festplatte, den die VM nutzen darf, wenn ihr Arbeitsspeicher ausgeht. Container werden dann langsamer, statt gestoppt zu werden. Gilt nach einem Neustart." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Speicherplatz auf der Festplatte, den die VM nutzen darf, wenn ihr Arbeitsspeicher ausgeht. Container werden dann langsamer, statt gestoppt zu werden. Gilt nach einem Neustart.", + "Community": "Community" } diff --git a/crates/kiri/src/ui/lang/el.json b/crates/kiri/src/ui/lang/el.json index 638bd6388..c7c446dcd 100644 --- a/crates/kiri/src/ui/lang/el.json +++ b/crates/kiri/src/ui/lang/el.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Δεν ήταν δυνατή η απεγκατάσταση του Kiri: {error}", "Uninstall Kiri using your system package manager": "Απεγκαταστήστε το Kiri μέσω του διαχειριστή πακέτων του συστήματός σας", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Χώρος στον δίσκο που μπορεί να χρησιμοποιήσει η VM όταν εξαντληθεί η μνήμη της, ώστε τα containers να επιβραδύνονται αντί να σταματούν. Εφαρμόζεται κατά την επανεκκίνηση." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Χώρος στον δίσκο που μπορεί να χρησιμοποιήσει η VM όταν εξαντληθεί η μνήμη της, ώστε τα containers να επιβραδύνονται αντί να σταματούν. Εφαρμόζεται κατά την επανεκκίνηση.", + "Community": "Κοινότητα" } diff --git a/crates/kiri/src/ui/lang/es.json b/crates/kiri/src/ui/lang/es.json index 0a9f7e21b..7430c78e7 100644 --- a/crates/kiri/src/ui/lang/es.json +++ b/crates/kiri/src/ui/lang/es.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "No se pudo desinstalar Kiri: {error}", "Uninstall Kiri using your system package manager": "Desinstala Kiri con el gestor de paquetes de tu sistema", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espacio en disco que la VM puede usar cuando se queda sin memoria, para que los contenedores vayan más lentos en lugar de detenerse. Se aplica al reiniciar." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espacio en disco que la VM puede usar cuando se queda sin memoria, para que los contenedores vayan más lentos en lugar de detenerse. Se aplica al reiniciar.", + "Community": "Comunidad" } diff --git a/crates/kiri/src/ui/lang/fa.json b/crates/kiri/src/ui/lang/fa.json index bc054a9cc..4741a9f12 100644 --- a/crates/kiri/src/ui/lang/fa.json +++ b/crates/kiri/src/ui/lang/fa.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "حذف نصب Kiri ممکن نشد: {error}", "Uninstall Kiri using your system package manager": "Kiri را با مدیر بستهٔ سیستم خود حذف نصب کنید", "Swap": "سواپ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "فضای دیسکی که VM هنگام تمام شدن حافظه‌اش می‌تواند استفاده کند تا کانتینرها به‌جای متوقف شدن کند شوند. پس از راه‌اندازی مجدد اعمال می‌شود." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "فضای دیسکی که VM هنگام تمام شدن حافظه‌اش می‌تواند استفاده کند تا کانتینرها به‌جای متوقف شدن کند شوند. پس از راه‌اندازی مجدد اعمال می‌شود.", + "Community": "جامعه" } diff --git a/crates/kiri/src/ui/lang/fi.json b/crates/kiri/src/ui/lang/fi.json index d67b88b13..6517f848c 100644 --- a/crates/kiri/src/ui/lang/fi.json +++ b/crates/kiri/src/ui/lang/fi.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kirin asennusta ei voitu poistaa: {error}", "Uninstall Kiri using your system package manager": "Poista Kirin asennus järjestelmän paketinhallinnalla", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Levytilaa, jota VM voi käyttää, kun sen muisti loppuu, jolloin kontit hidastuvat pysäyttämisen sijaan. Tulee voimaan uudelleenkäynnistyksessä." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Levytilaa, jota VM voi käyttää, kun sen muisti loppuu, jolloin kontit hidastuvat pysäyttämisen sijaan. Tulee voimaan uudelleenkäynnistyksessä.", + "Community": "Yhteisö" } diff --git a/crates/kiri/src/ui/lang/fr.json b/crates/kiri/src/ui/lang/fr.json index bcabeadc8..0775230e6 100644 --- a/crates/kiri/src/ui/lang/fr.json +++ b/crates/kiri/src/ui/lang/fr.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Impossible de désinstaller Kiri : {error}", "Uninstall Kiri using your system package manager": "Désinstallez Kiri avec le gestionnaire de paquets de votre système", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espace disque que la VM peut utiliser quand sa mémoire est épuisée : les conteneurs ralentissent au lieu d’être arrêtés. Appliqué au redémarrage." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espace disque que la VM peut utiliser quand sa mémoire est épuisée : les conteneurs ralentissent au lieu d’être arrêtés. Appliqué au redémarrage.", + "Community": "Communauté" } diff --git a/crates/kiri/src/ui/lang/hi.json b/crates/kiri/src/ui/lang/hi.json index 76cd063d9..01a44d050 100644 --- a/crates/kiri/src/ui/lang/hi.json +++ b/crates/kiri/src/ui/lang/hi.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri अनइंस्टॉल नहीं कर सके: {error}", "Uninstall Kiri using your system package manager": "अपने सिस्टम पैकेज मैनेजर से Kiri अनइंस्टॉल करें", "Swap": "स्वैप", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "डिस्क स्थान जिसे VM अपनी मेमोरी खत्म होने पर उपयोग कर सकता है, ताकि कंटेनर रुकने के बजाय धीमे हो जाएं। रीस्टार्ट पर लागू होता है।" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "डिस्क स्थान जिसे VM अपनी मेमोरी खत्म होने पर उपयोग कर सकता है, ताकि कंटेनर रुकने के बजाय धीमे हो जाएं। रीस्टार्ट पर लागू होता है।", + "Community": "समुदाय" } diff --git a/crates/kiri/src/ui/lang/hu.json b/crates/kiri/src/ui/lang/hu.json index ce78de880..304150206 100644 --- a/crates/kiri/src/ui/lang/hu.json +++ b/crates/kiri/src/ui/lang/hu.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Nem sikerült eltávolítani a Kirit: {error}", "Uninstall Kiri using your system package manager": "Távolítsd el a Kirit a rendszer csomagkezelőjével", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Lemezterület, amelyet a VM akkor használhat, ha elfogy a memóriája, így a konténerek leállítás helyett lelassulnak. Újraindításkor lép életbe." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Lemezterület, amelyet a VM akkor használhat, ha elfogy a memóriája, így a konténerek leállítás helyett lelassulnak. Újraindításkor lép életbe.", + "Community": "Közösség" } diff --git a/crates/kiri/src/ui/lang/hy.json b/crates/kiri/src/ui/lang/hy.json new file mode 100644 index 000000000..422c287e2 --- /dev/null +++ b/crates/kiri/src/ui/lang/hy.json @@ -0,0 +1,2040 @@ +{ + " (current step)": " (ընթացիկ քայլ)", + " (done)": " (արված է)", + " ({port} was in use)": " ({port} պորտը զբաղված էր)", + " That's {count} crashes since Kiri last opened.": " Kiri-ի վերջին բացումից ի վեր խափանումների քանակը՝ {count}։", + " and ": " և ", + " or ": " կամ ", + "(no description)": "(նկարագրություն չկա)", + "(no message)": "(հաղորդագրություն չկա)", + "(read-only)": "(միայն կարդալու)", + "(was {value})": "(նախկինում՝ {value})", + "* Estimates until measured on a clean PC.": "* Գնահատական է, քանի դեռ չափված չէ մաքուր համակարգչի վրա։", + "+ A complete Linux you can open from Start": "+ Լիարժեք Linux, որը կարող եք բացել «Սկիզբ» ընտրացանկից", + "+ Already have Ubuntu? Kiri uses it: nothing to download": "+ Ubuntu արդեն ունե՞ք։ Kiri-ն կօգտագործի այն՝ ներբեռնելու ոչինչ չկա", + "+ No Microsoft Store, no username or password": "+ Առանց Microsoft Store-ի, առանց օգտանվան և գաղտնաբառի", + "+ Removed completely when you remove Kiri": "+ Ամբողջությամբ հեռացվում է Kiri-ն հեռացնելիս", + "+ Uses the Ubuntu you already have: nothing to download": "+ Օգտագործում է ձեր արդեն ունեցած Ubuntu-ն՝ ներբեռնելու ոչինչ չկա", + "+{n} more": "+{n} ևս", + ", ": ", ", + "Build with Kiri. docker build and docker compose build run on Kiri, and the images are in Kiri. {engine} won’t see them. You can switch any time in Settings → Builds.": "Կառուցել Kiri-ով։ docker build և docker compose build հրամանները կատարվում են Kiri-ում, և պատկերները պահվում են Kiri-ում։ {engine} ծրագիրը դրանք չի տեսնի։ Կարող եք ցանկացած պահի փոխել սա՝ «Կարգավորումներ» → «Կառուցումներ»։", + "Keep building with Docker. Nothing changes: docker build builds where it does now, and the images stay in {engine}.": "Շարունակել կառուցել Docker-ով։ Ոչինչ չի փոխվում՝ docker build հրամանը կառուցում է այնտեղ, որտեղ հիմա, և պատկերները մնում են {engine} ծրագրում։", + "Kept: the container itself, its files, image, ports, volumes, network and restart policy.": "Պահպանվում են: բուն կոնտեյները, նրա ֆայլերը, պատկերը, պորտերը, հատորները, ցանցը և վերագործարկման քաղաքականությունը։", + "docker still uses {engine}, so what you run in the terminal won't show up here. Your images can come along.": "docker-ը դեռ աշխատում է {engine} ծրագրի հետ, ուստի այն, ինչ գործարկում եք տերմինալում, այստեղ չի երևա։ Ձեր պատկերները կարելի է տեղափոխել։", + "kindest/node is the node image of kind, a tool that runs Kubernetes in Docker. kind starts it for you, with privileged mode and the settings it needs. Started on its own, it stops at this {mount}.": "kindest/node-ը kind-ի հանգույցի պատկերն է։ kind-ը գործիք է, որը Kubernetes-ը գործարկում է Docker-ում։ kind-ն ինքն է այն գործարկում՝ արտոնյալ ռեժիմով և անհրաժեշտ կարգավորումներով։ Ինքնուրույն գործարկվելիս այն կանգ է առնում այս կետում՝ {mount}։", + "{name} has {list} that aren't in Kiri yet.": "{name} ծրագրում կան {list}, որոնք դեռ Kiri-ում չկան։", + "{name} isn't answering on {addr}, so visitors get an error page. Is the app inside it running?": "{name} կոնտեյները չի պատասխանում {addr} հասցեում, ուստի այցելուները տեսնում են սխալի էջ։ Ներսի հավելվածն աշխատո՞ւմ է։", + "{name} isn't answering, so visitors get an error page. Is the app inside it running?": "{name} կոնտեյները չի պատասխանում, ուստի այցելուները տեսնում են սխալի էջ։ Ներսի հավելվածն աշխատո՞ւմ է։", + "A container that publishes one of these ports gets it; names on that port pause until it lets go.": "Այս պորտերից մեկը հրապարակող կոնտեյները ստանում է այն, իսկ այդ պորտի անունները դադարեցվում են, մինչև կոնտեյները չազատի պորտը։", + "A couple more steps: set them up, or skip.": "Եվս մի քանի քայլ՝ կարգավորեք դրանք կամ բաց թողեք։", + "A deployment (its ReplicaSet)": "Տեղակայում (նրա ReplicaSet-ը)", + "A device in Kiri is gone from Windows until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri-ին միացված սարքն անհասանելի է Windows-ում, մինչև այն չանջատեք։ Կոնտեյներում՝ --device /dev/ttyUSB0 (serial), /dev/input (HID) կամ /dev/bus/usb (raw)։", + "A device in Kiri is gone from the Mac until you detach it. In a container: --device /dev/ttyUSB0 (serial), /dev/input (HID) or /dev/bus/usb (raw).": "Kiri-ին միացված սարքն անհասանելի է Mac-ում, մինչև այն չանջատեք։ Կոնտեյներում՝ --device /dev/ttyUSB0 (serial), /dev/input (HID) կամ /dev/bus/usb (raw)։", + "A few things need fixing before Kiri can run containers.": "Մինչ Kiri-ն կկարողանա կոնտեյներներ գործարկել, պետք է մի քանի բան ուղղել։", + "A kiri command": "kiri հրաման", + "A kiri command crashed": "kiri հրամանը խափանվեց", + "A proxy on this Mac is reached as {host}.": "Այս Mac-ի պրոքսին հասանելի է որպես {host}։", + "A service sends traffic to this pod": "Ծառայությունը տրաֆիկ է ուղարկում այս pod-ին", + "A single-node cluster (k3s) in one container, for kubectl's {context} context. Off stops it and keeps its state.": "Մեկ հանգույցով կլաստեր (k3s) մեկ կոնտեյներում՝ kubectl-ի {context} համատեքստի համար։ Անջատելիս այն կանգնեցվում է, և վիճակը պահպանվում է։", + "A single-node cluster (k3s) in one container. It takes about 20 s, longer the first time, while k3s downloads.": "Մեկ հանգույցով կլաստեր (k3s) մեկ կոնտեյներում։ Գործարկումը տևում է մոտ 20 վ, առաջին անգամ՝ ավելի երկար, քանի որ k3s-ը ներբեռնվում է։", + "A small, fast container runtime.": "Փոքր և արագ կոնտեյներների կատարման միջավայր։", + "A tiny Linux made only for Kiri, built from Alpine. It stays out of sight and leaves with Kiri.": "Փոքրիկ Linux՝ ստեղծված միայն Kiri-ի համար Alpine-ի հիման վրա։ Այն աչքի չի ընկնում և հեռանում է Kiri-ի հետ միասին։", + "API on {addr}": "API՝ {addr}", + "API server": "API սերվեր", + "API server port": "API սերվերի պորտ", + "AWS didn't accept that code. Wait for the next one and try again.": "AWS-ը չընդունեց այդ կոդը։ Սպասեք հաջորդին և նորից փորձեք։", + "AWS profile": "AWS պրոֆիլ", + "About": "Ծրագրի մասին", + "Accent": "Ակցենտային գույն", + "Accept the SQL Server licence": "Ընդունել SQL Server-ի լիցենզիան", + "Access token": "Մուտքի թոքեն", + "Access token or password": "Մուտքի թոքեն կամ գաղտնաբառ", + "Action {op}": "Գործողություն՝ {op}", + "Actions": "Գործողություններ", + "Actual Size": "Իրական չափ", + "Add": "Ավելացնել", + "Add it to WSL": "Ավելացնել այն WSL-ին", + "Add port": "Ավելացնել պորտ", + "Added by this build": "Ավելացվել է այս կառուցմամբ", + "Added in this image": "Ավելացվել է այս պատկերում", + "Additional certificate names": "Սերտիֆիկատի լրացուցիչ անուններ", + "Administrator approval": "Ադմինիստրատորի թույլտվություն", + "After the restart": "Վերագործարկումից հետո", + "Age": "Տարիք", + "All": "Բոլորը", + "All languages · {n}": "Բոլոր լեզուները · {n}", + "All levels": "Բոլոր մակարդակները", + "All statuses": "Բոլոր կարգավիճակները", + "All steps": "Բոլոր քայլերը", + "All {kind}": "Բոլորը՝ {kind}", + "Allow access": "Թույլատրել մուտքը", + "Allow an empty password": "Թույլատրել դատարկ գաղտնաբառ", + "Already there": "Արդեն կա", + "Always send crash reports": "Միշտ ուղարկել խափանումների հաշվետվությունները", + "Amazon ECR takes a token, not a password: the username is {user} and the token comes from {cmd}. It lasts 12 hours.": "Amazon ECR-ն ընդունում է թոքեն, ոչ թե գաղտնաբառ՝ օգտանունը {user} է, իսկ թոքենը տալիս է {cmd} հրամանը։ Այն գործում է 12 ժամ։", + "Anchore, open source": "Anchore, բաց կոդով", + "Another builder has been picked for {build} since ({use}). Choose Kiri again to build on Kiri.": "{build} հրամանի համար այդ պահից ի վեր այլ կառուցիչ է ընտրված ({use})։ Կրկին ընտրեք Kiri-ն՝ Kiri-ում կառուցելու համար։", + "Another program holds 127.0.0.1:53, so Kiri cannot answer for .kiri.local; containers stay at .kiri.localhost": "127.0.0.1:53 հասցեն զբաղեցրել է մեկ այլ ծրագիր, ուստի Kiri-ն չի կարող պատասխանել .kiri.local հասցեի համար, և կոնտեյներները մնում են .kiri.localhost հասցեում", + "Answers on /run/kiri/docker.sock": "Պատասխանում է /run/kiri/docker.sock հասցեում", + "Anyone who can reach the port signs in as root.": "Յուրաքանչյուր ոք, ով կարող է հասնել պորտին, մուտք է գործում որպես root։", + "Anyone with this link can open it while Kiri is running.": "Այս հղումն ունեցող յուրաքանչյուր ոք կարող է բացել այն, քանի դեռ Kiri-ն աշխատում է։", + "Appearance": "Արտաքին տեսք", + "Applies after you log out and back in": "Կկիրառվի համակարգից դուրս գալուց և նորից մուտք գործելուց հետո", + "Apply…": "Կիրառել…", + "Asking {host} for {ref}…": "{host} սերվերից հարցվում է {ref} պատկերը…", + "Asks for your password once": "Ձեր գաղտնաբառը կհարցվի մեկ անգամ", + "Asleep": "Քնած", + "Attach": "Միացնել", + "Attach it to see where it shows up in Linux.": "Միացրեք այն՝ տեսնելու համար, թե որտեղ է այն հայտնվում Linux-ում։", + "Attached": "Միացված է", + "Attaching…": "Միացում…", + "Audio": "Աուդիո", + "Back": "Հետ", + "Back (Esc)": "Հետ (Esc)", + "Back to Share": "Վերադառնալ կիսվելու էջ", + "Back to editing": "Վերադառնալ խմբագրմանը", + "Base image": "Բազային պատկեր", + "Beta": "Բետա", + "Bigger": "Ավելի մեծ", + "Blue": "Կապույտ", + "Bring all my {engine} images to {app}": "Տեղափոխել իմ բոլոր պատկերները {engine} ծրագրից {app} ծրագիր", + "Bring images, volumes and containers over to Kiri.": "Տեղափոխեք պատկերները, հատորները և կոնտեյներները Kiri։", + "Bring your {name} things to Kiri": "Տեղափոխեք ձեր տվյալները {name} ծրագրից Kiri", + "Bringing your images over from {engine}: {done} of {total}.": "Պատկերների տեղափոխում {engine} ծրագրից՝ {done} / {total}։", + "Brought {n} item over from {engine}.": "{engine} ծրագրից տեղափոխվեց {n} տարր։", + "Brought {n} item over from {engine}; {failed} failed (Settings → Import says why).": "{engine} ծրագրից տեղափոխվեց {n} տարր, ձախողվեց՝ {failed} (պատճառը՝ «Կարգավորումներ» → «Ներմուծել» բաժնում)։", + "Brought {n} items over from {engine}.": "{engine} ծրագրից տեղափոխվեց {n} տարր։", + "Brought {n} items over from {engine}; {failed} failed (Settings → Import says why).": "{engine} ծրագրից տեղափոխվեց {n} տարր, ձախողվեց՝ {failed} (պատճառը՝ «Կարգավորումներ» → «Ներմուծել» բաժնում)։", + "Browsers see a short Kiri Cloud notice page first.": "Զննարկիչները նախ տեսնում են Kiri Cloud-ի կարճ ծանուցման էջ։", + "Build cache cleared": "Կառուցման քեշը մաքրվեց", + "Build cache cleared: freed {size}": "Կառուցման քեշը մաքրվեց՝ ազատվեց {size}", + "Build context": "Կառուցման համատեքստ", + "Build record": "Կառուցման գրառում", + "Build with": "Կառուցել", + "Build with Kiri": "Կառուցել Kiri-ով", + "Build with Kiri.": "Կառուցել Kiri-ով։", + "BuildKit starts if it's asleep.": "BuildKit-ը կգործարկվի, եթե քնած է։", + "BuildKit {size}": "BuildKit {size}", + "BuildKit {size} and its build cache": "BuildKit {size} և դրա կառուցման քեշը", + "Building": "Կառուցվում է", + "Builds": "Կառուցումներ", + "Builds you run with docker build show up here, with each step's time, cache and output.": "docker build հրամանով գործարկված կառուցումները հայտնվում են այստեղ՝ յուրաքանչյուր քայլի ժամանակով, քեշով և ելքով։", + "Built from source": "Կառուցված է սկզբնական կոդից", + "Bus {bus} · Device {dev}": "Շինա {bus} · Սարք {dev}", + "By name, no ports.": "Ըստ անվան, առանց պորտերի։", + "By port. Nothing to set up.": "Ըստ պորտի։ Կարգավորելու ոչինչ չկա։", + "Bypass for": "Բացառություններ", + "CLI": "CLI", + "CPU": "Պրոցեսոր", + "CPU is a share of all {n} cores: 100% would be every core busy.": "Պրոցեսորի բեռնվածությունը բոլոր միջուկների ({n}) մասնաբաժինն է՝ 100%-ը նշանակում է, որ բոլոր միջուկները զբաղված են։", + "CPUs": "Պրոցեսորներ", + "Cached": "Քեշից", + "Camera": "Տեսախցիկ", + "Can't be shared": "Հնարավոր չէ կիսվել", + "Can't be shared yet": "Դեռ հնարավոր չէ կիսվել", + "Can't reach Docker Hub right now.": "Այս պահին հնարավոր չէ միանալ Docker Hub-ին։", + "Cancel": "Չեղարկել", + "Cancel download": "Չեղարկել ներբեռնումը", + "Cancel pull": "Չեղարկել ներբեռնումը", + "Canceled": "Չեղարկված է", + "Cancelled": "Չեղարկված է", + "Cancelled. Nothing was added; layers that finished are kept for the next pull.": "Չեղարկված է։ Ոչինչ չավելացվեց, իսկ ավարտված շերտերը պահպանվել են հաջորդ ներբեռնման համար։", + "Change ports": "Փոխել պորտերը", + "Changing it restarts the cluster.": "Փոփոխելիս կլաստերը կվերագործարկվի։", + "Changing this asks Windows for an administrator's approval, since it adds or removes a DNS rule for {local}.": "Սա փոխելու համար Windows-ը կպահանջի ադմինիստրատորի թույլտվություն, քանի որ ավելացվում կամ հեռացվում է DNS կանոն {local} դոմենի համար։", + "Changing this needs admin rights (an administrator password), since it adds or removes {path}.": "Սա փոխելու համար անհրաժեշտ են ադմինիստրատորի իրավունքներ (ադմինիստրատորի գաղտնաբառ), քանի որ ավելացվում կամ հեռացվում է {path} ֆայլը։", + "Check for Updates…": "Ստուգել թարմացումները…", + "Check for updates automatically": "Ավտոմատ ստուգել թարմացումները", + "Check now": "Ստուգել հիմա", + "Check the spelling, or paste a full reference like {ref}.": "Ստուգեք ուղղագրությունը կամ տեղադրեք ամբողջական հղում, օրինակ՝ {ref}։", + "Checked once the engine runs": "Կստուգվի շարժիչի գործարկվելուց հետո", + "Checked once your account can use Kiri": "Կստուգվի, երբ ձեր հաշիվը կկարողանա օգտագործել Kiri-ն", + "Checking the code with AWS…": "Կոդը ստուգվում է AWS-ում…", + "Checking your plan…": "Ձեր սակագնային պլանը ստուգվում է…", + "Checking…": "Ստուգում…", + "Choose a Linux": "Ընտրեք Linux", + "Choose and install": "Ընտրել և տեղադրել", + "Choose what to bring…": "Ընտրել, թե ինչ տեղափոխել…", + "Choose your language": "Ընտրեք ձեր լեզուն", + "Clear": "Մաքրել", + "Clear build cache": "Մաքրել կառուցման քեշը", + "Clear the selection": "Չեղարկել ընտրությունը", + "Clear the selection (Esc)": "Չեղարկել ընտրությունը (Esc)", + "Clear {n} failed": "Մաքրել ձախողվածները ({n})", + "Clearing…": "Մաքրում…", + "Close": "Փակել", + "Close ({keys})": "Փակել ({keys})", + "Close Window": "Փակել պատուհանը", + "Close find": "Փակել որոնումը", + "Close pane": "Փակել վահանակը", + "Close tab": "Փակել ներդիրը", + "Close this scan": "Փակել այս սկանավորումը", + "Close to your plan's speed limit": "Մոտ է ձեր պլանի արագության սահմանին", + "Cluster IP": "Կլաստերի IP", + "Collapse all": "Ծալել բոլորը", + "Command": "Հրաման", + "Command to run in the container": "Կոնտեյներում գործարկվող հրաման", + "Completed": "Ավարտված է", + "Compose project {project} made it: {cmd} puts back what the compose file says, so change it there too.": "Այն ստեղծվել է Compose-ի {project} նախագծով՝ {cmd} հրամանը կվերականգնի compose ֆայլում նշվածը, ուստի փոխեք այն նաև այնտեղ։", + "Compose services answer at {addr}.": "Compose-ի ծառայությունները պատասխանում են {addr} հասցեում։", + "Connect Windows to it": "Միացնել Windows-ը դրան", + "Connecting…": "Միացում…", + "Connection lost.": "Կապը կորավ։", + "Container": "Կոնտեյներ", + "Container files are not on Windows' disk: use Save to Downloads": "Կոնտեյների ֆայլերը Windows-ի սկավառակում չեն՝ օգտագործեք «Պահել Ներբեռնումներում»", + "Container list": "Կոնտեյներների ցանկ", + "Container port {q}{port}{q} is not a port number (1–65535).": "Կոնտեյների պորտի {q}{port}{q} արժեքը պորտի համար չէ (1–65535)։", + "Container traffic leaves through WSL's network.": "Կոնտեյներների տրաֆիկը դուրս է գնում WSL-ի ցանցով։", + "Container, Kubernetes and diagnostics logs.": "Կոնտեյներների, Kubernetes-ի և ախտորոշման մատյաններ։", + "Containers": "Կոնտեյներներ", + "Containers answer at .kiri.localhost": "Կոնտեյներները պատասխանում են .kiri.localhost հասցեով", + "Containers now answer at .kiri.local": "Կոնտեյներներն այժմ պատասխանում են .kiri.local հասցեով", + "Containers run on this computer's own kernel, so they see its USB devices as they are: docker run --device with the path shown.": "Կոնտեյներներն աշխատում են այս համակարգչի սեփական միջուկի վրա, ուստի տեսնում են դրա USB սարքերն այնպես, ինչպես կան՝ docker run --device ցուցադրված ուղով։", + "Containers see it": "Տեսանելի է կոնտեյներներին", + "Containers you start with docker run or Compose show up here, with the {context} context.": "docker run հրամանով կամ Compose-ով գործարկված կոնտեյներները հայտնվում են այստեղ՝ {context} համատեքստով։", + "Continue": "Շարունակել", + "Continue with GitHub": "Շարունակել GitHub-ով", + "Controlled by": "Կառավարվում է", + "Copied": "Պատճենվեց", + "Copied {text}": "Պատճենվեց՝ {text}", + "Copy": "Պատճենել", + "Copy ID": "Պատճենել ID-ն", + "Copy link": "Պատճենել հղումը", + "Copy {what}": "Պատճենել {what}", + "Could not change container names: {error}": "Չհաջողվեց փոխել կոնտեյներների անունները՝ {error}", + "Could not change the certificate's trust: {error}": "Չհաջողվեց փոխել սերտիֆիկատի նկատմամբ վստահությունը՝ {error}", + "Could not change the ports: {error}": "Չհաջողվեց փոխել պորտերը՝ {error}", + "Could not open Terminal: {error}": "Չհաջողվեց բացել Terminal հավելվածը՝ {error}", + "Could not open a terminal: {error}": "Չհաջողվեց բացել տերմինալ՝ {error}", + "Could not restart WSL: {error}": "Չհաջողվեց վերագործարկել WSL-ը՝ {error}", + "Could not restart the VM: {error}": "Չհաջողվեց վերագործարկել վիրտուալ մեքենան՝ {error}", + "Could not restart the engine: {error}": "Չհաջողվեց վերագործարկել շարժիչը՝ {error}", + "Could not save .wslconfig: {error}": "Չհաջողվեց պահպանել .wslconfig ֆայլը՝ {error}", + "Could not save the SBOM: {error}": "Չհաջողվեց պահպանել SBOM-ը՝ {error}", + "Could not save the file: {error}": "Չհաջողվեց պահպանել ֆայլը՝ {error}", + "Could not save the proxy settings: {error}": "Չհաջողվեց պահպանել պրոքսիի կարգավորումները՝ {error}", + "Could not save the registry settings: {error}": "Չհաջողվեց պահպանել ռեեստրի կարգավորումները՝ {error}", + "Could not save the setting to {path}": "Չհաջողվեց պահպանել կարգավորումն այս ֆայլում՝ {path}", + "Could not save the setting to ~/.kiri/ui.json": "Չհաջողվեց պահպանել կարգավորումը ~/.kiri/ui.json ֆայլում", + "Could not save: {error}": "Չհաջողվեց պահպանել՝ {error}", + "Couldn't change which builder docker build uses: {error}": "Չհաջողվեց փոխել docker build-ի օգտագործած կառուցիչը՝ {error}", + "Couldn't check for updates: {error}": "Չհաջողվեց ստուգել թարմացումները՝ {error}", + "Couldn't check: {error}": "Չհաջողվեց ստուգել՝ {error}", + "Couldn't clear the build cache: {error}": "Չհաջողվեց մաքրել կառուցման քեշը՝ {error}", + "Couldn't copy to the clipboard": "Չհաջողվեց պատճենել սեղմատախտակին", + "Couldn't download it: {error}": "Չհաջողվեց ներբեռնել՝ {error}", + "Couldn't list the tags": "Չհաջողվեց ստանալ պիտակների ցանկը", + "Couldn't read the USB devices": "Չհաջողվեց կարդալ USB սարքերը", + "Couldn't read the build history": "Չհաջողվեց կարդալ կառուցումների պատմությունը", + "Couldn't remove the build: {error}": "Չհաջողվեց հեռացնել կառուցումը՝ {error}", + "Couldn't save it: {error}": "Չհաջողվեց պահպանել՝ {error}", + "Couldn't save the report: {error}": "Չհաջողվեց պահպանել հաշվետվությունը՝ {error}", + "Couldn't send it: {error}": "Չհաջողվեց ուղարկել՝ {error}", + "Couldn't send the crash report: {error}": "Չհաջողվեց ուղարկել խափանման հաշվետվությունը՝ {error}", + "Couldn't set up the Docker tools": "Չհաջողվեց կարգավորել Docker-ի գործիքները", + "Couldn't share": "Չհաջողվեց կիսվել", + "Couldn't share service {name}: it's gone": "Չհաջողվեց կիսվել {name} ծառայությամբ, քանի որ այն այլևս չկա", + "Couldn't share {name}": "Չհաջողվեց կիսվել՝ {name}", + "Couldn't share {name}: Kiri couldn't tell which port it listens on. Publish one from its page.": "Չհաջողվեց կիսվել՝ {name}։ Kiri-ն չկարողացավ պարզել, թե որ պորտն է այն լսում։ Հրապարակեք որևէ պորտ դրա էջում։", + "Couldn't share {name}: it stopped": "Չհաջողվեց կիսվել՝ {name}, քանի որ այն կանգնեց", + "Couldn't share {name}: it's gone": "Չհաջողվեց կիսվել՝ {name}, քանի որ այն այլևս չկա", + "Couldn't share {name}: {reason}": "Չհաջողվեց կիսվել՝ {name}։ {reason}", + "Couldn't start {shell}: {error}": "Չհաջողվեց գործարկել {shell} shell-ը՝ {error}", + "Couldn't stop {name}: {error}": "Չհաջողվեց կանգնեցնել՝ {name}։ {error}", + "Couldn't switch docker: {error}": "Չհաջողվեց փոխարկել docker-ը՝ {error}", + "Crash reports": "Խափանման հաշվետվություններ", + "Crashed (139)": "Խափանվեց (139)", + "Create a diagnostics report": "Ստեղծել ախտորոշման հաշվետվություն", + "Create report…": "Ստեղծել հաշվետվություն…", + "Created": "Ստեղծվել է", + "Critical": "Կրիտիկական", + "Custom": "Անհատական", + "Cut": "Կտրել", + "Dark": "Մուգ", + "Database": "Տվյալների բազա", + "Debug": "Վրիպազերծում", + "Delete": "Ջնջել", + "Delete cluster": "Ջնջել կլաստերը", + "Delete pod {name}?": "Ջնջե՞լ {name} pod-ը։", + "Delete the Kubernetes cluster?": "Ջնջե՞լ Kubernetes կլաստերը։", + "Delete {what}?": "Ջնջե՞լ {what}։", + "Deleting": "Ջնջում", + "Deleting Kubernetes": "Kubernetes-ի ջնջում", + "Deleting pod {pod}": "Ջնջվում է {pod} pod-ը", + "Deleting…": "Ջնջվում է…", + "Deployment {name} runs this pod": "Այս pod-ը գործարկում է {name} տեղակայումը", + "Detach": "Անջատել", + "Detaching…": "Անջատվում է…", + "Details": "Մանրամասներ", + "Device": "Սարք", + "Diagnostics": "Ախտորոշում", + "Diagnostics report": "Ախտորոշման հաշվետվություն", + "Did you mean {name}?": "Գուցե նկատի ունեի՞ք {name}։", + "Didn't pull": "Չներբեռնվեց", + "Didn't pull.": "Չներբեռնվեց։", + "Disconnect": "Անջատել", + "Disconnecting…": "Անջատվում է…", + "Dismiss": "Փակել", + "Docker Desktop": "Docker Desktop", + "Docker Hub can't be reached": "Docker Hub-ը հասանելի չէ", + "Docker Hub has no image called {name}.": "Docker Hub-ում {name} անունով պատկեր չկա։", + "Docker Hub images pull through these in order; the first that has the image answers, and Docker Hub itself is the fallback. Other registries are pulled directly.": "Docker Hub-ի պատկերները ներբեռնվում են այս հայելիներով՝ հերթականությամբ. պատասխանում է պատկերն ունեցող առաջին հայելին, իսկ դրա բացակայության դեպքում՝ հենց Docker Hub-ը։ Մյուս ռեեստրները ներբեռնվում են ուղղակիորեն։", + "Docker tools": "Docker-ի գործիքներ", + "Docker tools are ready": "Docker-ի գործիքները պատրաստ են", + "Docker's default engine": "Docker-ի լռելյայն շարժիչը", + "Docker's own page signs you in. Check that it shows this code:": "Մուտքը կատարվում է Docker-ի սեփական էջում։ Համոզվեք, որ այնտեղ ցուցադրվում է այս կոդը:", + "Docs": "Փաստաթղթեր", + "Domains": "Դոմեններ", + "Done": "Պատրաստ է", + "Download": "Ներբեռնել", + "Download Ubuntu": "Ներբեռնել Ubuntu-ն", + "Download WSL": "Ներբեռնել WSL-ը", + "Download the new .deb or .rpm": "Ներբեռնեք նոր .deb կամ .rpm փաթեթը", + "Downloading Grype, the scanner (about 30 MB, once)": "Ներբեռնվում է Grype սկաները (մոտ 30 ՄԲ, մեկ անգամ)", + "Downloading Ubuntu 26.04": "Ներբեռնվում է Ubuntu 26.04-ը", + "Downloading {name} from {source}": "Ներբեռնվում է {name}, աղբյուրը՝ {source}", + "Downloading {version}": "Ներբեռնվում է {version}", + "Downloading…": "Ներբեռնվում է…", + "Drag to resize": "Քաշեք՝ չափը փոխելու համար", + "Drag to resize, double-click to reset": "Քաշեք՝ չափը փոխելու համար, կրկնակի սեղմեք՝ վերակայելու համար", + "Driver": "Դրայվեր", + "Duration": "Տևողություն", + "Edit": "Խմբագրել", + "Ended: pod deleted": "Ավարտվեց՝ pod-ը ջնջվել է", + "Ended: pod restarted · share the service to keep a link": "Ավարտվեց՝ pod-ը վերագործարկվել է · կիսվեք ծառայությամբ, որպեսզի հղումը պահպանվի", + "Ended: service deleted": "Ավարտվեց՝ ծառայությունը ջնջվել է", + "Engine": "Շարժիչ", + "Engine running": "Շարժիչն աշխատում է", + "Engine updated": "Շարժիչը թարմացվեց", + "Enter the port the app in the pod listens on, 1 to 65535": "Մուտքագրեք այն պորտը, որը լսում է pod-ի ներսի հավելվածը՝ 1-ից 65535", + "Enter this code on GitHub": "Մուտքագրեք այս կոդը GitHub-ում", + "Enter your MFA code": "Մուտքագրեք ձեր MFA կոդը", + "Environment": "Միջավայր", + "Error": "Սխալ", + "Errors": "Սխալներ", + "Everything in it goes: its pods, services, volumes and other resources, and the {context} kubectl context. The next start makes a new, empty cluster.": "Ամեն ինչ կջնջվի՝ դրա pod-երը, ծառայությունները, հատորները և այլ ռեսուրսներ, ինչպես նաև {context} kubectl համատեքստը։ Հաջորդ գործարկումը կստեղծի նոր, դատարկ կլաստեր։", + "Everything in the window.": "Պատուհանի ամբողջ բովանդակությունը։", + "Everything is in Kiri.": "Ամեն ինչ արդեն Kiri-ում է։", + "Exit code": "Ելքի կոդ", + "Exited with code {code}, {when}": "Ավարտվեց {code} կոդով, {when}", + "Expand all": "Ծավալել բոլորը", + "Expose services to LAN": "Ծառայությունները հասանելի դարձնել տեղային ցանցում", + "External": "Արտաքին", + "Failed": "Ձախողվեց", + "Failed ({code})": "Ձախողվեց ({code})", + "Failing": "Ձախողվում է", + "Feedback": "Հետադարձ կապ", + "Files": "Ֆայլեր", + "Find": "Գտնել", + "Find ({keys})": "Գտնել ({keys})", + "Find a path, method or status": "Գտնել ուղի, մեթոդ կամ կարգավիճակ", + "Find in logs": "Գտնել մատյաններում", + "Find in the terminal": "Գտնել տերմինալում", + "Finish updating to Kiri {version}": "Ավարտեք թարմացումը Kiri {version} տարբերակին", + "Finished": "Ավարտված", + "Fix all": "Ուղղել բոլորը", + "Fixed in": "Ուղղվել է", + "Fold the sidebar": "Ծալել կողային վահանակը", + "Follow": "Հետևել", + "Follow {os} (now {lang}), or always use one language.": "Հետևել համակարգին՝ {os} (այժմ՝ {lang}), կամ միշտ օգտագործել մեկ լեզու։", + "Follow {os}, or always use the dark or light theme.": "Հետևել համակարգին՝ {os}, կամ միշտ օգտագործել մուգ կամ բաց թեման։", + "Font": "Տառատեսակ", + "For Kubernetes on this {host}, Kiri has its own. It's the switch under Kubernetes in the sidebar.": "Kubernetes-ի համար Kiri-ն ունի իր սեփական կլաստերը այս {host} համակարգչում։ Այն կողային վահանակում Kubernetes-ի տակ գտնվող փոխանջատիչն է։", + "For pulling and pushing images.": "Պատկերներ ներբեռնելու և վերբեռնելու համար։", + "Forward": "Առաջ", + "Found": "Հայտնաբերված", + "Freed {size}": "Ազատվեց՝ {size}", + "Frees {size}": "Կազատի՝ {size}", + "From": "Որտեղից", + "From its base image": "Իր բազային պատկերից", + "From the base image": "Բազային պատկերից", + "From ubuntu.com, through Microsoft's WSL list.": "ubuntu.com-ից՝ Microsoft-ի WSL ցանկի միջոցով։", + "Generate": "Ստեղծել", + "Getting a link…": "Հղումը ստացվում է…", + "GitHub opened in your browser. Approve there and you're signed in straight away.": "GitHub-ը բացվեց ձեր դիտարկիչում։ Հաստատեք այնտեղ, և անմիջապես մուտք կգործեք։", + "GitHub opened in your browser. Approve there and {what} is shared straight away.": "GitHub-ը բացվեց ձեր դիտարկիչում։ Հաստատեք այնտեղ, և {what} անմիջապես հասանելի կդառնա։", + "GitHub's page asks you to let Kiri read your packages. Check that it shows this code:": "GitHub-ի էջը կխնդրի թույլ տալ Kiri-ին կարդալ ձեր փաթեթները։ Համոզվեք, որ այնտեղ ցուցադրվում է այս կոդը:", + "Give it back to this computer": "Վերադարձնել այս համակարգչին", + "Give the VM more memory": "Ավելի շատ հիշողություն տալ վիրտուալ մեքենային", + "Give {name} a public https link": "Ստեղծել հանրային https հղում՝ {name}", + "Given back to Windows": "Վերադարձվել է Windows-ին", + "Given back to the Mac": "Վերադարձվել է Mac-ին", + "Go to Containers": "Անցնել Կոնտեյներներ բաժին", + "Gone from Kiri": "Այլևս չկա Kiri-ում", + "Graphics|process": "Գրաֆիկա", + "Green": "Կանաչ", + "Grype, the open-source scanner from Anchore": "Grype՝ Anchore-ի բաց կոդով սկաները", + "HTTP proxy": "HTTP պրոքսի", + "HTTPS proxy": "HTTPS պրոքսի", + "Hand it to Kiri's containers": "Հանձնել Kiri-ի կոնտեյներներին", + "Has a fix": "Ունի ուղղում", + "Have": "Առկա է", + "Headless: there's no cluster address to share. Share one of its pods.": "Headless: կիսվելու համար կլաստերային հասցե չկա։ Կիսվեք դրա pod-երից մեկով։", + "Health check": "Առողջության ստուգում", + "Helpers|process": "Օժանդակ", + "Hide": "Թաքցնել", + "Hide ({keys})": "Թաքցնել ({keys})", + "Hide password": "Թաքցնել գաղտնաբառը", + "Hide the crash report": "Թաքցնել խափանման հաշվետվությունը", + "Hide the terminal ({keys})": "Թաքցնել տերմինալը ({keys})", + "Hide until Kiri next opens": "Թաքցնել մինչև Kiri-ի հաջորդ բացումը", + "Hide until {name} has more": "Թաքցնել, մինչև այստեղ նորերը հայտնվեն՝ {name}", + "Hide {app}": "Թաքցնել {app}", + "High": "Բարձր", + "Host or network": "Հոսթ կամ ցանց", + "How it runs": "Ինչպես է աշխատում", + "How should you reach your containers?": "Ինչպե՞ս դիմել ձեր կոնտեյներներին։", + "ID": "ID", + "IDs, commands and code.": "ID-ներ, հրամաններ և կոդ։", + "IP addresses or domain names, separated by commas, that the API server's certificate also covers, such as this {host}'s address on your network. Saving restarts the cluster.": "IP հասցեներ կամ դոմենային անուններ՝ ստորակետով բաժանված, որոնք նույնպես ընդգրկում է API սերվերի սերտիֆիկատը, օրինակ՝ այս {host} համակարգչի հասցեն ձեր ցանցում։ Պահպանելիս կլաստերը վերագործարկվում է։", + "If Kiri's useful, a star on GitHub helps others find it.": "Եթե Kiri-ն օգտակար է, GitHub-ում աստղը կօգնի ուրիշներին գտնել այն։", + "If it's private, run {cmd} first.": "Եթե այն մասնավոր է, նախ կատարեք {cmd} հրամանը։", + "If it's private, sign in first:": "Եթե այն մասնավոր է, նախ մուտք գործեք:", + "If it's private, {link} first.": "Եթե այն մասնավոր է, նախ {link}։", + "If it's private, {link}.": "Եթե այն մասնավոր է, {link}։", + "Image": "Պատկեր", + "Image to pull": "Ներբեռնվող պատկեր", + "Images": "Պատկերներ", + "Images you pull or build show up here: docker pull alpine, or search above.": "Ձեր ներբեռնած կամ կառուցած պատկերները հայտնվում են այստեղ՝ docker pull alpine, կամ որոնեք վերևում։", + "Import": "Ներմուծել", + "Import from": "Ներմուծել որտեղից", + "Import {n} item": "Ներմուծել {n} տարր", + "Import {n} items": "Ներմուծել {n} տարր", + "Imported": "Ներմուծված", + "Imported {done}; {failed} failed (hover “Failed” for why).": "Ներմուծվեց՝ {done}, ձախողվեց՝ {failed} (պատճառը տեսնելու համար մկնիկը պահեք «Ձախողվեց» նշման վրա)։", + "Imported {n} item.": "Ներմուծվեց {n} տարր։", + "Imported {n} items.": "Ներմուծվեց {n} տարր։", + "Importing…": "Ներմուծվում է…", + "In Kiri": "Kiri-ում", + "In a container": "Կոնտեյներում", + "In a week": "Մեկ շաբաթից", + "In use": "Օգտագործվում է", + "In use {used}. The VM may take up to {target} right now, and grows as containers need more.": "Օգտագործվում է՝ {used}։ Վիրտուալ մեքենան այս պահին կարող է զբաղեցնել մինչև {target} և մեծանում է, երբ կոնտեյներներին ավելին է պետք։", + "In use: {proxy}, except {hosts}.": "Օգտագործվում է՝ {proxy}, բացառությամբ՝ {hosts}։", + "In use: {proxy}.": "Օգտագործվում է՝ {proxy}։", + "Included": "Ներառված է", + "Info": "Տեղեկություն", + "Info and up": "Տեղեկություն և ավելի բարձր", + "Insecure registries": "Անապահով ռեեստրներ", + "Inside Linux": "Linux-ի ներսում", + "Install Kiri's engine in it": "Տեղադրել Kiri-ի շարժիչը դրանում", + "Install WSL": "Տեղադրել WSL-ը", + "Install usbipd-win": "Տեղադրել usbipd-win", + "Installed": "Տեղադրված է", + "Installing": "Տեղադրում", + "Installing Windows Subsystem for Linux": "Տեղադրվում է Windows-ի ենթահամակարգը Linux-ի համար", + "Installing…": "Տեղադրվում է…", + "Installs when you quit Kiri": "Կտեղադրվի, երբ դուրս գաք Kiri-ից", + "Interface font": "Ինտերֆեյսի տառատեսակ", + "Internal steps": "Ներքին քայլեր", + "It asks to change the Linux VM itself, which Run doesn't allow. If you trust {image}, start it yourself with {cmd}.": "Այն պահանջում է փոխել հենց Linux վիրտուալ մեքենան, ինչը «Գործարկել» գործառույթը թույլ չի տալիս։ Եթե վստահում եք {image} պատկերին, գործարկեք այն ինքներդ՝ {cmd} հրամանով։", + "It has no selector, so it picks no pods.": "Այն սելեկտոր չունի, ուստի ոչ մի pod չի ընտրում։", + "It restarts, so open connections drop.": "Այն կվերագործարկվի, և բաց կապերը կխզվեն։", + "It stays up while Kiri is running.": "Այն աշխատում է, քանի դեռ Kiri-ն աշխատում է։", + "It takes effect when it next starts.": "Կուժի մեջ մտնի հաջորդ գործարկման ժամանակ։", + "It works with serial adapters, Zigbee sticks, mice and keyboards; webcams and audio aren't supported yet.": "Աշխատում է սերիական ադապտերների, Zigbee սարքերի, մկնիկների և ստեղնաշարերի հետ, իսկ վեբ-տեսախցիկներն ու աուդիոն դեռ չեն աջակցվում։", + "It wrote nothing to its log.": "Այն ոչինչ չի գրել իր մատյանում։", + "It's a network interface inside Linux, not a device file.": "Linux-ում սա ցանցային ինտերֆեյս է, ոչ թե սարքի ֆայլ։", + "It's deleted, with its files and unnamed volumes. Named volumes stay.": "Այն կջնջվի իր ֆայլերի և անանուն հատորների հետ միասին։ Անվանված հատորները կմնան։", + "It's stopped and deleted, with its files and unnamed volumes. Named volumes stay.": "Այն կկանգնեցվի և կջնջվի իր ֆայլերի և անանուն հատորների հետ միասին։ Անվանված հատորները կմնան։", + "Its API server stalls or stops answering · {free}": "Դրա API սերվերը կախվում է կամ դադարում է պատասխանել · {free}", + "Its container is stopped and deleted, with their files. Named volumes stay.": "Դրա կոնտեյները կկանգնեցվի և կջնջվի իր ֆայլերով հանդերձ։ Անվանված հատորները կմնան։", + "Its containers stop and their files go.": "Դրա կոնտեյներները կկանգնեն, և դրանց ֆայլերը կջնջվեն։", + "Its data is deleted for good.": "Դրա տվյալները կջնջվեն ընդմիշտ։", + "Its deployment starts a new pod in its place.": "Դրա տեղակայումը նոր pod կգործարկի դրա փոխարեն։", + "Its job may start it again.": "Դրա առաջադրանքը կարող է այն նորից գործարկել։", + "Its last container stopped because {name} wasn't set.": "Դրա վերջին կոնտեյները կանգ առավ, քանի որ {name} փոփոխականը սահմանված չէր։", + "Its node runs, but the API server doesn't answer. A busy or memory-starved VM can do this; Kiri keeps asking.": "Հանգույցն աշխատում է, բայց API սերվերը չի պատասխանում։ Այդպես լինում է, երբ VM-ը ծանրաբեռնված է կամ հիշողությունը չի բավականացնում. Kiri-ն շարունակում է հարցումներ անել։", + "Its node runs, but the API server doesn't answer: {error}. A busy or memory-starved VM can do this; Kiri keeps asking.": "Հանգույցն աշխատում է, բայց API սերվերը չի պատասխանում՝ {error}։ Այդպես լինում է, երբ VM-ը ծանրաբեռնված է կամ հիշողությունը չի բավականացնում. Kiri-ն շարունակում է հարցումներ անել։", + "Its start script stops when {name} isn't set.": "Դրա գործարկման սկրիպտը կանգ է առնում, եթե {name} փոփոխականը սահմանված չէ։", + "Its start script stops without it: “{why}”.": "Առանց դրա գործարկման սկրիպտը կանգ է առնում՝ «{why}»։", + "Its value": "Դրա արժեքը", + "Its {n} containers are stopped and deleted, with their files. Named volumes stay.": "Դրա {n} կոնտեյները կկանգնեցվեն և կջնջվեն իրենց ֆայլերով հանդերձ։ Անվանված հատորները կմնան։", + "Its {owner} starts a new pod in its place.": "Դրա տերը՝ {owner}, նոր pod կգործարկի դրա փոխարեն։", + "KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.": "Դեմոնի համար սահմանված է KIRI_CPUS կամ KIRI_MEMORY_MIB, և այն գերակա է այս կարգավորումների նկատմամբ։", + "Keep": "Պահել", + "Keep building with Docker": "Շարունակել կառուցել Docker-ով", + "Keep building with Docker.": "Շարունակել կառուցել Docker-ով։", + "Keep typing to search Docker Hub.": "Շարունակեք մուտքագրել՝ Docker Hub-ում որոնելու համար։", + "Keep using your PC meanwhile.": "Այդ ընթացքում կարող եք շարունակել օգտագործել համակարգիչը։", + "Kept in Credential Manager": "Պահվում է Credential Manager-ում", + "Kept in the Keychain": "Պահվում է Keychain-ում", + "Kept in {path} with Docker's names, for docker pull, push, login and build. Docker Desktop's file is left alone.": "Պահվում է {path} ֆայլում՝ Docker-ի անուններով՝ docker pull, push, login և build հրամանների համար։ Docker Desktop-ի ֆայլը մնում է անփոփոխ։", + "Kept {name}: {container} couldn't be removed ({error})": "Պահպանվեց՝ {name}. չհաջողվեց հեռացնել {container} կոնտեյները ({error})", + "Kept {name}: {error}": "Պահպանվեց՝ {name}. {error}", + "Key": "Բանալի", + "Keyboard": "Ստեղնաշար", + "Killed (137)": "Բռնի դադարեցվել է (137)", + "Kiri Cloud gives it a public https link through a secure tunnel from this {host}. You sign in with GitHub, so every link traces back to a person. Kiri never sees your password.": "Kiri Cloud-ը դրան տալիս է հանրային https հղում՝ անվտանգ թունելով, որը սկսվում է այս սարքից՝ {host}։ Դուք մուտք եք գործում GitHub-ով, ուստի յուրաքանչյուր հղում կապված է կոնկրետ մարդու հետ։ Kiri-ն երբեք չի տեսնում ձեր գաղտնաբառը։", + "Kiri Setup": "Kiri-ի տեղադրում", + "Kiri and this Mac": "Kiri-ն և այս Mac-ը", + "Kiri can't pass sound or video through yet: containers won't get anything from it.": "Kiri-ն դեռ չի կարող փոխանցել ձայն կամ տեսանյութ, ուստի կոնտեյներները դրանից ոչինչ չեն ստանա։", + "Kiri engine installed": "Kiri-ի շարժիչը տեղադրված է", + "Kiri finds every package in the image (OS packages, language libraries and binaries) and checks each against a vulnerability database. No scans yet: run the first one.": "Kiri-ն գտնում է պատկերի բոլոր փաթեթները (ՕՀ-ի փաթեթներ, լեզուների գրադարաններ և երկուական ֆայլեր) և յուրաքանչյուրը ստուգում խոցելիությունների տվյալների բազայով։ Սկանավորումներ դեռ չկան. գործարկեք առաջինը։", + "Kiri is not running": "Kiri-ն չի աշխատում", + "Kiri is ready": "Kiri-ն պատրաստ է", + "Kiri is set up.": "Kiri-ն կարգավորված է։", + "Kiri quit unexpectedly last time": "Նախորդ անգամ Kiri-ն անսպասելիորեն փակվեց", + "Kiri runs Grype here on your Mac against the image in Kiri's store. The image isn't uploaded anywhere.": "Kiri-ն Grype-ը գործարկում է հենց այստեղ՝ ձեր Mac-ում, Kiri-ի պահոցում գտնվող պատկերի համար։ Պատկերը ոչ մի տեղ չի վերբեռնվում։", + "Kiri runs Linux containers inside WSL, in a Linux of its own. Both choices run the same containers at the same speed; they differ in size and in what else you get.": "Kiri-ն Linux կոնտեյներները գործարկում է WSL-ի ներսում՝ իր սեփական Linux-ում։ Երկու տարբերակներն էլ նույն կոնտեյներները գործարկում են նույն արագությամբ. դրանք տարբերվում են չափով և նրանով, թե ինչ եք ստանում դրանից բացի։", + "Kiri runs Linux containers on Windows without Docker Desktop. It needs Windows Subsystem for Linux (WSL), Microsoft's own way to run Linux, which this PC doesn't have yet.": "Kiri-ն Linux կոնտեյներները գործարկում է Windows-ում՝ առանց Docker Desktop-ի։ Դրա համար անհրաժեշտ է Windows Subsystem for Linux-ը (WSL)՝ Linux գործարկելու Microsoft-ի սեփական եղանակը, որը այս համակարգչում դեռ չկա։", + "Kiri sets itself up for your Windows account only.": "Kiri-ն կարգավորվում է միայն ձեր Windows հաշվի համար։", + "Kiri sets up its builder once its engine is running, and builds go to it from then on.": "Kiri-ն կկարգավորի իր կառուցիչը, երբ շարժիչը գործարկվի, և այդ պահից կառուցումները կկատարվեն դրանում։", + "Kiri signs in to Docker Hub with the docker command, which isn't installed. Install it, then try again.": "Kiri-ն Docker Hub մուտք է գործում docker հրամանով, որը տեղադրված չէ։ Տեղադրեք այն և նորից փորձեք։", + "Kiri signs in to GitHub with the GitHub CLI (gh), which isn't installed. Install it, then try again.": "Kiri-ն GitHub մուտք է գործում GitHub CLI-ով (gh), որը տեղադրված չէ։ Տեղադրեք այն և նորից փորձեք։", + "Kiri started your container.": "Kiri-ն գործարկեց ձեր կոնտեյները։", + "Kiri started {name} in {time}.": "Kiri-ն գործարկեց {name} կոնտեյները. տևողությունը՝ {time}։", + "Kiri started {name}.": "Kiri-ն գործարկեց {name} կոնտեյները։", + "Kiri uses your AWS profile through the AWS CLI, which isn't installed. Public images still pull.": "Kiri-ն ձեր AWS պրոֆիլն օգտագործում է AWS CLI-ի միջոցով, որը տեղադրված չէ։ Հանրային պատկերները դեռ ներբեռնվում են։", + "Kiri will reuse the Ubuntu already installed on this PC. Kiri runs in it, and you keep opening it as your own Linux.": "Kiri-ն կօգտագործի այս համակարգչում արդեն տեղադրված Ubuntu-ն։ Kiri-ն աշխատում է դրանում, իսկ դուք շարունակում եք այն բացել որպես ձեր սեփական Linux։", + "Kiri {version} is a test build: it doesn't update itself": "Kiri {version} տարբերակը փորձնական կառուցում է. այն ինքն իրեն չի թարմացնում", + "Kiri {version} is available": "Հասանելի է Kiri {version} տարբերակը", + "Kiri {version} is downloaded": "Kiri {version} տարբերակը ներբեռնված է", + "Kiri {version} is ready to install": "Kiri {version} տարբերակը պատրաստ է տեղադրման", + "Kiri {version} is the newest version": "Kiri {version} տարբերակը ամենանորն է", + "Kiri's Kubernetes cluster": "Kiri-ի Kubernetes կլաստերը", + "Kiri's builder": "Kiri-ի կառուցիչը", + "Kiri's certificate is no longer trusted": "Kiri-ի սերտիֆիկատն այլևս վստահելի չէ", + "Kiri's certificate is trusted: containers open over HTTPS": "Kiri-ի սերտիֆիկատը վստահելի է. կոնտեյներները բացվում են HTTPS-ով", + "Kiri's containers and engine use {used}, of the {total} this computer has.": "Kiri-ի կոնտեյներներն ու շարժիչը օգտագործում են {used}՝ այս համակարգչի {total} ծավալից։", + "Kiri's containers, engine and agent hold {used} of the {total} WSL has (.wslconfig sets that).": "Kiri-ի կոնտեյներները, շարժիչը և գործակալը զբաղեցնում են {used}՝ WSL-ին հասանելի {total} ծավալից (դա սահմանվում է .wslconfig-ում)։", + "Kiri's log": "Kiri-ի մատյանը", + "Kiri's logs": "Kiri-ի մատյանները", + "Kiri's own, {name}, is on, so another copy isn't needed.": "Kiri-ի սեփականը՝ {name}, միացված է, ուստի ևս մեկ պատճենի կարիք չկա։", + "Kiri: {state}": "Kiri: {state}", + "Kiri’s engine": "Kiri-ի շարժիչը", + "Kubernetes cluster": "Kubernetes կլաստեր", + "Kubernetes deleted, with its state": "Kubernetes-ը ջնջվեց իր վիճակով հանդերձ", + "Kubernetes is busy with another change; try again in a moment": "Kubernetes-ը զբաղված է մեկ այլ փոփոխությամբ. մի պահ անց նորից փորձեք", + "Kubernetes is managed in Settings → Kubernetes": "Kubernetes-ը կառավարվում է «Կարգավորումներ» → «Kubernetes» բաժնում", + "Kubernetes is off": "Kubernetes-ն անջատված է", + "Kubernetes is out of memory": "Kubernetes-ին հիշողությունը չի բավականացնում", + "Kubernetes is running · API on {addr}": "Kubernetes-ն աշխատում է · API՝ {addr}", + "Kubernetes is running.": "Kubernetes-ն աշխատում է։", + "Kubernetes is running: {cmd}": "Kubernetes-ն աշխատում է՝ {cmd}", + "Kubernetes is short of memory.": "Kubernetes-ին հիշողությունը չի բավականացնում։", + "Kubernetes is starting": "Kubernetes-ը գործարկվում է", + "Kubernetes is stopping": "Kubernetes-ը կանգնեցվում է", + "Kubernetes isn't answering": "Kubernetes-ը չի պատասխանում", + "Kubernetes isn't running": "Kubernetes-ը չի աշխատում", + "Kubernetes needs about {need}, and this VM can use {max}, of which {used} is in use.": "Kubernetes-ին անհրաժեշտ է մոտ {need}, իսկ այս VM-ը կարող է օգտագործել {max}, որից զբաղված է {used}։", + "Kubernetes needs about {need}, and this VM can use {max}.": "Kubernetes-ին անհրաժեշտ է մոտ {need}, իսկ այս VM-ը կարող է օգտագործել {max}։", + "Kubernetes settings": "Kubernetes-ի կարգավորումներ", + "Kubernetes settings saved. They apply when it next starts.": "Kubernetes-ի կարգավորումները պահպանվեցին։ Դրանք կկիրառվեն հաջորդ գործարկման ժամանակ։", + "Kubernetes stopped it: it used more memory than it may, or the VM ran out": "Kubernetes-ը կանգնեցրեց այն, քանի որ այն օգտագործեց թույլատրվածից ավելի հիշողություն, կամ VM-ի հիշողությունը սպառվեց", + "Kubernetes stopped. Its state is kept for the next start.": "Kubernetes-ը կանգնեցվեց։ Դրա վիճակը պահպանված է հաջորդ գործարկման համար։", + "Kubernetes: {error}": "Kubernetes: {error}", + "Labels": "Նշիչներ", + "Language": "Լեզու", + "Large": "Մեծ", + "Later": "Ավելի ուշ", + "Later installs it when you quit Kiri.": "«Ավելի ուշ» ընտրելու դեպքում այն կտեղադրվի, երբ դուրս գաք Kiri-ից։", + "Later: Kiri waits in the tray and picks up after your next restart.": "«Ավելի ուշ»՝ Kiri-ն կսպասի ծանուցումների տարածքում և կշարունակի համակարգչի հաջորդ վերագործարկումից հետո։", + "Layer": "Շերտ", + "Layers": "Շերտեր", + "Let it pick a random one": "Թող ընտրի պատահական արժեք", + "Lets {user} run containers without sudo": "Թույլ է տալիս {user} օգտատիրոջը գործարկել կոնտեյներներ առանց sudo-ի", + "Level": "Մակարդակ", + "Light": "Բաց", + "Linux VM": "Linux VM", + "Linux VM: {state}": "Linux VM: {state}", + "Linux account": "Linux հաշիվ", + "Linux for Kiri": "Linux Kiri-ի համար", + "Linux hasn't made a device for it yet.": "Linux-ը դեռ դրա համար սարք չի ստեղծել։", + "Linux stopped a process for memory": "Linux-ը կանգնեցրեց պրոցեսը հիշողության պակասի պատճառով", + "Listening on {ports}": "Լսում է՝ {ports}", + "Live": "Ակտիվ է", + "Live · waiting for the first visitor": "Ակտիվ է · սպասում է առաջին այցելուին", + "Live|stream": "Ուղիղ", + "Loading tags…": "Պիտակները բեռնվում են…", + "Loading the steps…": "Քայլերը բեռնվում են…", + "Loading…": "Բեռնվում է…", + "Local names": "Տեղական անուններ", + "Location": "Տեղադրություն", + "Log lines for this action": "Այս գործողության մատյանի տողերը", + "Log out now": "Դուրս գալ հիմա", + "Log out to finish": "Ավարտելու համար դուրս եկեք համակարգից", + "Log text": "Մատյանի տեքստ", + "Logs": "Մատյաններ", + "Logs: {error}": "Մատյաններ: {error}", + "Looking for Kubernetes…": "Kubernetes-ի որոնում…", + "Looking for OrbStack and Docker Desktop…": "OrbStack-ի և Docker Desktop-ի որոնում…", + "Looking for USB devices…": "USB սարքերի որոնում…", + "Looking for crash reports…": "Խափանումների հաշվետվությունների որոնում…", + "Looking for shells…": "Shell-երի որոնում…", + "Low": "Ցածր", + "MFA code": "MFA կոդ", + "Mac": "Mac", + "Made by": "Հեղինակ", + "Make Kiri the default": "Դարձնել Kiri-ն լռելյայն", + "Make Kiri the default for docker": "Դարձնել Kiri-ն լռելյայն docker-ի համար", + "Make a new one": "Ստեղծել նորը", + "Manufacturer": "Արտադրող", + "MariaDB won't start until you choose how its root account signs in.": "MariaDB-ն չի գործարկվի, քանի դեռ չեք ընտրել, թե ինչպես է մուտք գործում դրա root հաշիվը։", + "Maximise": "Ծավալել", + "Medium": "Միջին", + "Memory": "Հիշողություն", + "Memory full · {mem}": "Հիշողությունը լցված է · {mem}", + "Method": "Մեթոդ", + "Mirror address": "Հայելու հասցե", + "Modified": "Փոփոխվել է", + "Monospace font": "Հավասարալայն տառատեսակ", + "More": "Ավելին", + "More actions for {name}": "Այլ գործողություններ՝ {name}", + "More memory": "Ավելի շատ հիշողություն", + "More settings": "Այլ կարգավորումներ", + "Mounts": "Միացումներ", + "Mouse": "Մկնիկ", + "MySQL won't start until you choose how its root account signs in.": "MySQL-ը չի գործարկվի, քանի դեռ չեք ընտրել, թե ինչպես է մուտք գործում դրա root հաշիվը։", + "Name": "Անուն", + "Named volumes from docker volume create or -v name:/path show up here.": "Այստեղ են հայտնվում docker volume create կամ -v name:/path հրամաններով ստեղծված անվանված հատորները։", + "Names answer on {http} and {https}. Pick other ports when another app needs these; links then carry the port, like {url}.": "Անունները պատասխանում են {http} և {https} պորտերով։ Ընտրեք այլ պորտեր, եթե դրանք պետք են մեկ այլ հավելվածի. այդ դեպքում հղումները կներառեն պորտը, օրինակ՝ {url}։", + "Names, images and status. Not their files, logs or environment.": "Անուններ, պատկերներ և կարգավիճակ։ Առանց դրանց ֆայլերի, մատյանների կամ միջավայրի։", + "Namespace": "Անվանատարածք", + "Namespace · {up} of {all} running": "Անվանատարածք · աշխատում է {up}՝ {all} ընդհանուրից", + "Needs a restart": "Պահանջվում է վերագործարկում", + "Needs an administrator password once.": "Մեկ անգամ կպահանջվի ադմինիստրատորի գաղտնաբառը։", + "Needs upper and lower case, a digit and a symbol, 8 or more": "Անհրաժեշտ են մեծատառ և փոքրատառ, թվանշան և նշան, առնվազն 8 նիշ", + "Negligible": "Աննշան", + "Network": "Ցանց", + "Networks": "Ցանցեր", + "Networks you create with docker network create show up here.": "Այստեղ են հայտնվում docker network create հրամանով ձեր ստեղծած ցանցերը։", + "Network|process": "Ցանց", + "New containers get {http}, {https} and {no}.": "Նոր կոնտեյներները ստանում են {http}, {https} և {no}։", + "New tab": "Նոր ներդիր", + "New tab ({keys})": "Նոր ներդիր ({keys})", + "Next match": "Հաջորդ համընկնումը", + "No Linux username is needed now: Kiri runs inside Ubuntu on its own. Ubuntu asks for one only the first time you open it yourself. * Estimate.": "Linux օգտանունն այժմ պետք չէ. Kiri-ն ինքնուրույն աշխատում է Ubuntu-ի ներսում։ Ubuntu-ն այն կհարցնի միայն, երբ առաջին անգամ ինքներդ բացեք այն։ * Մոտավոր գնահատական։", + "No USB devices": "USB սարքեր չկան", + "No build matches.": "Համապատասխան կառուցումներ չկան։", + "No builds yet": "Կառուցումներ դեռ չկան", + "No changes": "Փոփոխություններ չկան", + "No containers running": "Աշխատող կոնտեյներներ չկան", + "No containers yet": "Կոնտեյներներ դեռ չկան", + "No crashes. Kiri keeps a report here if one of its parts ever stops unexpectedly.": "Խափանումներ չկան։ Եթե Kiri-ի որևէ մաս անսպասելիորեն կանգ առնի, Kiri-ն այստեղ հաշվետվություն կպահի։", + "No fix yet": "Ուղղում դեռ չկա", + "No images yet": "Պատկերներ դեռ չկան", + "No known vulnerabilities in {n} packages": "{n} փաթեթում հայտնի խոցելիություններ չկան", + "No language matches. Try its English name.": "Համապատասխան լեզու չկա։ Փորձեք դրա անգլերեն անվանումը։", + "No languages match": "Համապատասխան լեզուներ չկան", + "No lines match.": "Համապատասխան տողեր չկան։", + "No mirrors yet: Docker Hub images come from Docker Hub itself.": "Հայելիներ դեռ չկան. Docker Hub-ի պատկերները գալիս են անմիջապես Docker Hub-ից։", + "No networks yet": "Ցանցեր դեռ չկան", + "No password, no login and no TLS. Fine on this Mac, not for anything shared.": "Առանց գաղտնաբառի, մուտքի և TLS-ի։ Հարմար է այս Mac-ի համար, բայց ոչ ընդհանուր օգտագործման համար։", + "No password, no login and no TLS. Fine on this PC, not for anything shared.": "Առանց գաղտնաբառի, մուտքի և TLS-ի։ Հարմար է այս համակարգչի համար, բայց ոչ ընդհանուր օգտագործման համար։", + "No password, no login and no TLS. Fine on this computer, not for anything shared.": "Առանց գաղտնաբառի, մուտքի և TLS-ի։ Հարմար է այս համակարգչի համար, բայց ոչ ընդհանուր օգտագործման համար։", + "No pods": "Pod-եր չկան", + "No pods match its selector.": "Դրա ընտրիչին համապատասխանող pod-եր չկան։", + "No ports to share": "Կիսվելու պորտեր չկան", + "No proxy is in use.": "Պրոքսի չի օգտագործվում։", + "No requests match.": "Համապատասխան հարցումներ չկան։", + "No requests yet": "Հարցումներ դեռ չկան", + "No results": "Արդյունքներ չկան", + "No service points at it, so the link goes straight to the pod.": "Ոչ մի ծառայություն չի ուղղված դրան, ուստի հղումը տանում է անմիջապես pod-ին։", + "No services": "Ծառայություններ չկան", + "No steps here.": "Այստեղ քայլեր չկան։", + "No visitors in the last 2 minutes": "Վերջին 2 րոպեում այցելուներ չեն եղել", + "No volumes yet": "Հատորներ դեռ չկան", + "No {label}": "{label} չկան", + "Node": "Հանգույց", + "None": "Ոչ մեկը", + "None (headless)": "Ոչ մեկը (headless)", + "None found": "Ոչինչ չի գտնվել", + "None match these filters.": "Այս զտիչներին ոչինչ չի համապատասխանում։", + "None: every registry is checked over HTTPS.": "Չկա. յուրաքանչյուր ռեեստր ստուգվում է HTTPS-ով։", + "Not a web port, so it isn't shared": "Վեբ պորտ չէ, ուստի հնարավոր չէ կիսվել", + "Not an image name: {reference}": "Պատկերի անուն չէ՝ {reference}", + "Not answering · visitors get an error": "Չի պատասխանում · այցելուները սխալ են ստանում", + "Not created yet": "Դեռ ստեղծված չէ", + "Not found.": "Չի գտնվել։", + "Not in use: no container was made from it": "Չի օգտագործվում՝ դրանից ոչ մի կոնտեյներ չի ստեղծվել", + "Not now": "Ոչ հիմա", + "Not now: ask again in a week": "Ոչ հիմա՝ կրկին հարցնել մեկ շաբաթից", + "Not running": "Չի աշխատում", + "Not sent": "Չի ուղարկվել", + "Not set up yet. It's made on your first build, which downloads BuildKit (about 110 MB) once.": "Դեռ կարգավորված չէ։ Այն կստեղծվի ձեր առաջին կառուցման ժամանակ, որը մեկ անգամ կներբեռնի BuildKit-ը (մոտ 110 ՄԲ)։", + "Not signed in": "Մուտք գործված չէ", + "Not signed in to any registry": "Ոչ մի ռեեստր մուտք գործված չէ", + "Nothing called “{q}” on Docker Hub": "Docker Hub-ում «{q}» անունով ոչինչ չկա", + "Nothing changes: {build} builds where it does now, and the images stay in {engine}.": "Ոչինչ չի փոխվում՝ {build} հրամանը կառուցում է նույն տեղում, ինչ հիմա, իսկ պատկերները մնում են {engine} շարժիչում։", + "Nothing here.": "Այստեղ ոչինչ չկա։", + "Nothing is deleted. You can switch back any time from the status bar.": "Ոչինչ չի ջնջվում։ Կարող եք ցանկացած պահի վերադառնալ կարգավիճակի տողից։", + "Nothing logged yet.": "Մատյանում դեռ ոչինչ չկա։", + "Nothing matches “{q}” in {tab}.": "«{tab}» բաժնում «{q}» հարցմանը ոչինչ չի համապատասխանում։", + "Nothing matches “{q}”.": "«{q}» հարցմանը ոչինչ չի համապատասխանում։", + "Nothing restarts it either: when the pod is deleted or restarts, the link ends.": "Այն վերագործարկող էլ չկա՝ երբ pod-ը ջնջվում կամ վերագործարկվում է, հղումը դադարում է աշխատել։", + "Nothing shared yet": "Դեռ ոչնով չեք կիսվել", + "Nothing shared. Press the globe beside a running container to give it a public link.": "Ոչնով չեք կիսվել։ Սեղմեք աշխատող կոնտեյների կողքի գլոբուսը՝ դրան հանրային հղում տալու համար։", + "Nothing starts it again: no deployment or other controller owns it.": "Այն նորից գործարկող չկա՝ այն չի պատկանում ոչ մի տեղակայման կամ այլ կարգավարի։", + "Nothing to download": "Ներբեռնելու ոչինչ չկա", + "Nothing to download: it came inside Kiri.": "Ներբեռնելու ոչինչ չկա՝ այն ներառված է Kiri-ում։", + "Nothing to import from: OrbStack and Docker Desktop aren't on this {host}.": "Ներմուծելու տեղ չկա՝ այս {host} սարքում OrbStack և Docker Desktop չկան։", + "Nothing to pass to a container yet.": "Կոնտեյներին փոխանցելու դեռ ոչինչ չկա։", + "Nothing to type: it uses the AWS sign-in already on this computer.": "Ոչինչ մուտքագրել պետք չէ՝ օգտագործվում է այս համակարգչում արդեն առկա AWS մուտքը։", + "Now": "Հիմա", + "OK": "Լավ", + "Off": "Անջատված", + "Off: Kiri checks only when you click Check now.": "Անջատված: Kiri-ն ստուգում է միայն, երբ սեղմում եք «Ստուգել հիմա»։", + "Off: containers answer at <name>.kiri.localhost, which needs no setup.": "Անջատված: կոնտեյներները հասանելի են <name>.kiri.localhost հասցեով, որը կարգավորում չի պահանջում։", + "Off: press Start engine to run containers. It stays off after a restart until you start it.": "Անջատված: սեղմեք «Գործարկել շարժիչը»՝ կոնտեյներներ աշխատեցնելու համար։ Վերագործարկումից հետո այն անջատված է մնում, մինչև չգործարկեք։", + "Off: the API server and LoadBalancer services answer on this {host} only (127.0.0.1).": "Անջատված: API սերվերը և LoadBalancer ծառայությունները պատասխանում են միայն այս {host} սարքում (127.0.0.1)։", + "Official": "Պաշտոնական", + "On": "Միացված", + "On disk": "Սկավառակին", + "On this Mac": "Այս Mac-ում", + "On this PC": "Այս համակարգչում", + "On {registry} an image is named owner/image, such as {example}. Type one to choose its tag, or paste a full reference.": "{registry} ռեեստրում պատկերի անունն ունի owner/image տեսքը, օրինակ՝ {example}։ Մուտքագրեք անունը՝ պիտակն ընտրելու համար, կամ տեղադրեք ամբողջական հղումը։", + "On {targets}": "Հասցեներ՝ {targets}", + "On: Kiri checks each time it opens. It never updates without asking.": "Միացված: Kiri-ն ստուգում է ամեն անգամ բացվելիս։ Այն երբեք չի թարմացվում առանց հարցնելու։", + "On: containers open at https:// with Kiri's own certificate, which only vouches for .kiri.local and .kiri.localhost names.": "Միացված: կոնտեյներները բացվում են https:// արձանագրությամբ՝ Kiri-ի սեփական սերտիֆիկատով, որը երաշխավորում է միայն .kiri.local և .kiri.localhost անունները։", + "On: running containers answer at <name>.kiri.local.": "Միացված: աշխատող կոնտեյներները հասանելի են <name>.kiri.local հասցեով։", + "On: the API server and LoadBalancer services answer on every network interface, so other devices on your network can reach them.": "Միացված: API սերվերը և LoadBalancer ծառայությունները պատասխանում են բոլոր ցանցային միջերեսներում, ուստի ձեր ցանցի մյուս սարքերը կարող են միանալ դրանց։", + "One more step: log out and back in.": "Եվս մեկ քայլ՝ դուրս եկեք համակարգից և նորից մուտք գործեք։", + "One more step: set it up, or skip.": "Եվս մեկ քայլ՝ կարգավորեք այն կամ բաց թողեք։", + "One restart to finish WSL": "Մեկ վերագործարկում՝ WSL-ի տեղադրումն ավարտելու համար", + "One text file, redacted, saved to your Desktop and shown in Finder. Read it before you share it.": "Մեկ տեքստային ֆայլ՝ անձնական տվյալները հեռացված, պահվում է ձեր Աշխատասեղանին և ցուցադրվում Finder-ում։ Կարդացեք այն, նախքան որևէ մեկի հետ կիսվելը։", + "Only from {what}": "Միայն՝ {what}", + "Only {size} left this month. When it runs out, the link stops until next month.": "Այս ամիս մնացել է միայն {size}։ Երբ այն սպառվի, հղումը կդադարի աշխատել մինչև հաջորդ ամիս։", + "Open": "Բացել", + "Open Kiri": "Բացել Kiri-ն", + "Open Pods": "Բացել Pod-երը", + "Open Share": "Բացել Կիսվելը", + "Open in Terminal": "Բացել Տերմինալում", + "Open logs folder": "Բացել մատյանների թղթապանակը", + "Open the page again": "Կրկին բացել էջը", + "Open {addr}": "Բացել՝ {addr}", + "Open {name}": "Բացել՝ {name}", + "Open {site}": "Բացել՝ {site}", + "Open {url}": "Բացել՝ {url}", + "OpenSearch won't start without a strong admin password.": "OpenSearch-ը չի գործարկվի առանց ադմինիստրատորի ուժեղ գաղտնաբառի։", + "Opening the scan…": "Սկանավորումը բացվում է…", + "Optional": "Ոչ պարտադիր", + "Or allow an empty password": "Կամ թույլատրել դատարկ գաղտնաբառ", + "Or let it pick a random password": "Կամ թույլ տալ ընտրել պատահական գաղտնաբառ", + "Or set {names} instead.": "Կամ դրա փոխարեն սահմանեք {names}։", + "Or turn security off for local use": "Կամ անջատել պաշտպանությունը տեղային օգտագործման համար", + "Orange": "Նարնջագույն", + "OrbStack": "OrbStack", + "Out of memory": "Հիշողությունը սպառվել է", + "Overview": "Ընդհանուր տեսք", + "PC": "Համակարգիչ", + "Package": "Փաթեթ", + "Packages": "Փաթեթներ", + "Page|process": "Էջ", + "Pane restored": "Վահանակը վերականգնվեց", + "Pane zoomed": "Վահանակը ծավալվեց", + "Part": "Բաղադրիչ", + "Part of Kiri": "Kiri-ի մաս", + "Part of the cluster itself (kube-system). Not shared.": "Կլաստերի մասն է (kube-system)։ Հնարավոր չէ կիսվել։", + "Pass to containers": "Փոխանցել կոնտեյներներին", + "Paste": "Տեղադրել", + "Paste NAME=value lines, or a .env file, into a name.": "Տեղադրեք NAME=value տողեր կամ .env ֆայլ անվան դաշտում։", + "Paste {n} lines? Each line runs as a command.": "Տեղադրե՞լ {n} տող։ Յուրաքանչյուր տող կկատարվի որպես հրաման։", + "Path": "Ուղի", + "Pause": "Դադարեցնել", + "Paused": "Դադարեցված", + "Paused · nobody can open the link": "Դադարեցված · ոչ ոք չի կարող բացել հղումը", + "Paused: nobody can open the link until you resume.": "Դադարեցված: ոչ ոք չի կարող բացել հղումը, մինչև չվերսկսեք։", + "Peak {rate}": "Գագաթնակետ՝ {rate}", + "Pin tab": "Ամրացնել ներդիրը", + "Pink": "Վարդագույն", + "Pinned": "Ամրացված", + "Pinned: right-click to unpin": "Ամրացված: աջ սեղմեք՝ ապաամրացնելու համար", + "Pinned: unpin the tab to close it": "Ամրացված: ապաամրացրեք ներդիրը՝ այն փակելու համար", + "Plug one in: a serial adapter, a Zigbee stick, a microcontroller. It shows up here.": "Միացրեք որևէ սարք՝ հաջորդական ադապտեր, Zigbee ստիկ, միկրոկարգավորիչ։ Այն կհայտնվի այստեղ։", + "Pod IP": "Pod-ի IP", + "Pod in {ns}": "Pod՝ {ns} անվանատարածքում", + "Pod in {ns} · on {node}": "Pod՝ {ns} անվանատարածքում · {node} հանգույցում", + "Pods": "Pod-եր", + "Pods you create with kubectl show up here, grouped by namespace.": "kubectl հրամանով ձեր ստեղծած pod-երը հայտնվում են այստեղ՝ խմբավորված ըստ անվանատարածքի։", + "Port": "Պորտ", + "Port in the container": "Պորտ կոնտեյներում", + "Port on your {host}": "Պորտ ձեր {host} սարքում", + "Port on your {host} (localhost) → port inside the container. Leave the {host} side empty to pick a free one.": "Պորտ ձեր {host} սարքում (localhost) → պորտ կոնտեյների ներսում։ Թողեք {host} կողմը դատարկ՝ ազատ պորտ ընտրելու համար։", + "Port {port} is already in use on this {host}": "{port} պորտն արդեն զբաղված է այս {host} սարքում", + "Port {port}. The link keeps working when pods restart.": "Պորտ {port}։ Հղումը շարունակում է աշխատել pod-երի վերագործարկման ժամանակ։", + "Ports": "Պորտեր", + "Ports changed": "Պորտերը փոխվեցին", + "Ports for {name}": "Պորտեր՝ {name}", + "Ports removed": "Պորտերը հեռացվեցին", + "Ports saved: {ports}": "Պորտերը պահպանվեցին՝ {ports}", + "Ports…": "Պորտեր…", + "Postgres won't start without a superuser password.": "Postgres-ը չի գործարկվի առանց սուպերօգտատիրոջ գաղտնաբառի։", + "Powered by": "Հիմնված է", + "Press Share on a running container to give it a public https link anyone can open.": "Սեղմեք Կիսվել աշխատող կոնտեյների վրա՝ դրան հանրային https հղում տալու համար, որը կարող է բացել ցանկացած մեկը։", + "Press to see it, or disconnect it.": "Սեղմեք՝ դիտելու կամ անջատելու համար։", + "Press to try again": "Սեղմեք՝ նորից փորձելու համար", + "Previous match": "Նախորդ համընկնումը", + "Previous run": "Նախորդ գործարկումը", + "Printed once in the container's log.": "Մեկ անգամ տպվում է կոնտեյների մատյանում։", + "Private images won't pull until you sign in again.": "Մասնավոր պատկերները չեն ներբեռնվի, մինչև նորից մուտք չգործեք։", + "Processes": "Գործընթացներ", + "Progress": "Ընթացք", + "Protocol": "Արձանագրություն", + "Proxy": "Պրոքսի", + "Proxy settings saved": "Պրոքսիի կարգավորումները պահպանվեցին", + "Public images need no sign-in": "Հանրային պատկերների համար մուտք պետք չէ", + "Public images on public.ecr.aws need nothing. For your own account's registry, Kiri runs {cmd} with this profile.": "public.ecr.aws-ի հանրային պատկերների համար ոչինչ պետք չէ։ Ձեր հաշվի ռեեստրի համար Kiri-ն այս պրոֆիլով կատարում է {cmd} հրամանը։", + "Public images pull without signing in.": "Հանրային պատկերները ներբեռնվում են առանց մուտքի։", + "Publish": "Հրապարակել", + "Publish on {targets}": "Հրապարակել՝ {targets}", + "Publish the port {name} listens on, and give it a public https link": "Հրապարակել այն պորտը, որը լսում է {name} կոնտեյները, և դրան տալ հանրային https հղում", + "Pull": "Ներբեռնել", + "Pull again": "Կրկին ներբեռնել", + "Pull an image": "Ներբեռնել պատկեր", + "Pull an image ({key})": "Ներբեռնել պատկեր ({key})", + "Pull exactly this": "Ներբեռնել հենց սա", + "Pull from": "Ներբեռնել՝ որտեղից", + "Pull image": "Ներբեռնել պատկերը", + "Pull {tag}": "Ներբեռնել՝ {tag}", + "Pulled": "Ներբեռնված", + "Pulled {name}": "Ներբեռնվեց՝ {name}", + "Pulled {name} in {time}.": "Ներբեռնվեց՝ {name} (ժամանակը՝ {time})։", + "Pulled {when}": "Ներբեռնվել է՝ {when}", + "Pulling": "Ներբեռնվում է", + "Pulling {n}": "Ներբեռնվում է՝ {n}", + "Purple": "Մանուշակագույն", + "Quit": "Դուրս գալ", + "Quit Kiri": "Դուրս գալ Kiri-ից", + "Quit {app}": "Դուրս գալ՝ {app}", + "Quote {id} if you write to us about this crash.": "Նշեք {id} նույնացուցիչը, եթե այս խափանման մասին գրեք մեզ։", + "Radio": "Ռադիո", + "Ran": "Կատարված", + "Reachable at {addr}": "Հասանելի է՝ {addr}", + "Reachable at {url}": "Հասանելի է՝ {url}", + "Read more on runkiri.com ↗": "Մանրամասն՝ runkiri.com ↗", + "Reading build history…": "Կառուցումների պատմությունը կարդացվում է…", + "Reading the image…": "Պատկերը կարդացվում է…", + "Reading the log…": "Մատյանը կարդացվում է…", + "Reading the scans…": "Սկանավորումները կարդացվում են…", + "Reading what {name} has…": "Տվյալները կարդացվում են՝ {name}…", + "Ready": "Պատրաստ է", + "Recent crashes": "Վերջին խափանումները", + "Recent logs, crash reports and versions in one redacted file, for when something goes wrong.": "Վերջին մատյանները, խափանումների հաշվետվությունները և տարբերակները մեկ ֆայլում՝ անձնական տվյալները հեռացված, այն դեպքի համար, երբ ինչ-որ բան սխալ է ընթանում։", + "Recent pulls": "Վերջին ներբեռնումները", + "Recommended": "Խորհուրդ է տրվում", + "Reconnecting": "Վերամիացում", + "Reconnecting {name}…": "Վերամիացում՝ {name}…", + "Reconnecting · {reason}": "Վերամիացում · {reason}", + "Reconnecting…": "Վերամիացում…", + "Redo": "Կրկնել", + "Registries": "Ռեեստրներ", + "Registries reached without a verified certificate (self-signed, or plain HTTP). Kiri tries HTTPS without checking the certificate, then HTTP. Only the hosts and networks listed; every other registry is checked as usual.": "Առանց հաստատված հավաստագրի հասանելի ռեեստրներ (ինքնաստորագրված կամ պարզ HTTP)։ Kiri-ն նախ փորձում է HTTPS՝ առանց հավաստագիրը ստուգելու, ապա՝ HTTP։ Միայն նշված հոսթերն ու ցանցերը. մնացած բոլոր ռեեստրները ստուգվում են սովորականի պես։", + "Registry": "Ռեեստր", + "Registry mirrors": "Ռեեստրի հայելիներ", + "Registry settings saved": "Ռեեստրի կարգավորումները պահպանվեցին", + "Reload": "Վերաբեռնել", + "Remove": "Հեռացնել", + "Remove Kubernetes' container?": "Հեռացնե՞լ Kubernetes-ի կոնտեյները։", + "Remove all": "Հեռացնել բոլորը", + "Remove both": "Հեռացնել երկուսն էլ", + "Remove network {name}?": "Հեռացնե՞լ {name} ցանցը։", + "Remove project": "Հեռացնել նախագիծը", + "Remove this build from the history?": "Հեռացնե՞լ այս կառուցումը պատմությունից։", + "Remove this port": "Հեռացնել այս պորտը", + "Remove volume {name}?": "Հեռացնե՞լ {name} հատորը։", + "Remove {name} and {image}?": "Հեռացնե՞լ {name} կոնտեյները և {image} պատկերը։", + "Remove {name}?": "Հեռացնե՞լ {name}։", + "Remove {n} containers and {image}?": "Հեռացնե՞լ {n} կոնտեյներ և {image} պատկերը։", + "Remove {n} untagged": "Հեռացնել անպիտակները ({n})", + "Removed {gone} of {n} {what}": "Հեռացվեց {gone} {what}՝ {n} հատից", + "Removed {name}": "Հեռացվեց՝ {name}", + "Removed {n} {what}": "Հեռացվեց՝ {n} {what}", + "Removes the cluster's container, everything in it (the {volume} volume) and the {context} kubectl context, as {cmd} does.": "Հեռացնում է կլաստերի կոնտեյները, դրա ողջ պարունակությունը ({volume} հատորը) և {context} kubectl կոնտեքստը, ինչպես դա անում է {cmd} հրամանը։", + "Removes the {n} container that exited with an error, with their files. Named volumes stay.": "Հեռացնում է սխալով ավարտված {n} կոնտեյները՝ իր ֆայլերով։ Անվանված հատորները մնում են։", + "Removes the {n} containers that exited with an error, with their files. Named volumes stay.": "Հեռացնում է սխալով ավարտված {n} կոնտեյները՝ իրենց ֆայլերով։ Անվանված հատորները մնում են։", + "Removes the {n} failed build from the history.": "Պատմությունից հեռացնում է {n} ձախողված կառուցումը։", + "Removes the {n} failed builds from the history.": "Պատմությունից հեռացնում է {n} ձախողված կառուցումը։", + "Removes the {n} untagged image rebuilds left behind. Nothing uses them. Frees {size}.": "Հեռացնում է վերակառուցումներից մնացած {n} անպիտակ պատկերը։ Այն ոչ մի տեղ չի օգտագործվում։ Կազատի {size}։", + "Removes the {n} untagged images rebuilds left behind. Nothing uses them. Frees {size}.": "Հեռացնում է վերակառուցումներից մնացած {n} անպիտակ պատկերը։ Դրանք ոչ մի տեղ չեն օգտագործվում։ Կազատի {size}։", + "Removing {gone} of {n}…": "Հեռացում՝ {gone} / {n}…", + "Report ID": "Հաշվետվության ID", + "Report sent": "Հաշվետվությունն ուղարկվեց", + "Repository": "Պահոց", + "Requests to {name}": "Հարցումներ դեպի {name}", + "Resources": "Ռեսուրսներ", + "Restart": "Վերագործարկել", + "Restart Kiri to finish. Running containers stop, and those with a restart policy start again.": "Ավարտելու համար վերագործարկեք Kiri-ն։ Աշխատող կոնտեյներները կկանգնեն, իսկ վերագործարկման քաղաքականություն ունեցողները նորից կգործարկվեն։", + "Restart VM to apply": "Վերագործարկել VM-ը՝ կիրառելու համար", + "Restart all": "Վերագործարկել բոլորը", + "Restart engine": "Վերագործարկել շարժիչը", + "Restart engine to finish": "Ավարտելու համար վերագործարկեք շարժիչը", + "Restart later": "Վերագործարկել ավելի ուշ", + "Restart now": "Վերագործարկել հիմա", + "Restart to update": "Վերագործարկել՝ թարմացնելու համար", + "Restart {name} with the new environment?": "Վերագործարկե՞լ {name} կոնտեյները նոր միջավայրով։", + "Restarting stops the running containers; start them again afterwards.": "Վերագործարկումը կկանգնեցնի աշխատող կոնտեյներները, որից հետո նորից գործարկեք դրանք։", + "Restarting…": "Վերագործարկվում է…", + "Restarts": "Վերագործարկումներ", + "Restore": "Վերականգնել", + "Resume": "Վերսկսել", + "Retry": "Կրկնել", + "Retry starts it again; the layers already here are kept.": "«Կրկնել» կոճակը նորից կսկսի այն, իսկ արդեն ներբեռնված շերտերը կպահպանվեն։", + "Review": "Դիտել", + "Run": "Գործարկել", + "Run a test container": "Գործարկել փորձնական կոնտեյներ", + "Run {cmd}, then Retry.": "Կատարեք {cmd} հրամանը, ապա սեղմեք «Կրկնել»։", + "Running": "Աշխատում է", + "Running Kiri {version} · back in {time}": "Աշխատում է Kiri {version} · կվերադառնա {time} հետո", + "Running containers answer at <name>.kiri.localhost, which needs no setup.": "Աշխատող կոնտեյներները հասանելի են <name>.kiri.localhost հասցեով, և դա կարգավորում չի պահանջում։", + "Running now with {cpus} and up to {mem}.": "Այժմ աշխատում է՝ {cpus} և մինչև {mem} հիշողություն։", + "Running, not ready": "Աշխատում է, պատրաստ չէ", + "Running: it rests by itself when nothing runs and wakes when you use it.": "Աշխատում է: ինքն իրեն քնում է, երբ ոչինչ չի աշխատում, և արթնանում է, երբ այն օգտագործում եք։", + "Running: {cmd}": "Աշխատում է: {cmd}", + "Runs": "Կատարում է", + "Runs each command with {sh} in {name}; {cd} carries over. ↑ and ↓ go through earlier commands.": "Յուրաքանչյուր հրաման կատարվում է {sh} միջոցով {name} կոնտեյներում, իսկ {cd} հրամանի արդյունքը պահպանվում է։ ↑ և ↓ ստեղներով անցեք նախորդ հրամաններին։", + "Runs here on your Mac against Kiri's copy of the image; nothing is uploaded.": "Կատարվում է այստեղ՝ ձեր Mac-ում, պատկերի Kiri-ի պատճենի վրա։ Ոչինչ չի վերբեռնվում։", + "Runs your containers": "Գործարկում է ձեր կոնտեյներները", + "SQL Server won't start without a strong password for its sa account, and its licence accepted.": "SQL Server-ը չի գործարկվի առանց sa հաշվի ուժեղ գաղտնաբառի և ընդունված լիցենզիայի։", + "Same as the window ({font})": "Ինչպես պատուհանում ({font})", + "Same as {os}": "Ինչպես համակարգում՝ {os}", + "Save": "Պահպանել", + "Save SBOM": "Պահպանել SBOM-ը", + "Save and start": "Պահպանել և գործարկել", + "Save to Desktop": "Պահպանել Աշխատասեղանին", + "Save to Downloads": "Պահպանել Ներբեռնումներում", + "Save {name}'s new environment?": "Պահպանե՞լ {name} կոնտեյների նոր միջավայրը։", + "Saved in .wslconfig. WSL uses these from its next start": "Պահպանված է .wslconfig-ում։ WSL-ը դրանք կկիրառի հաջորդ գործարկումից", + "Saved in the container's environment. Kiri doesn't keep a copy.": "Պահպանված է կոնտեյների միջավայրում։ Kiri-ն պատճեն չի պահում։", + "Saved in this container's environment. Kiri doesn't keep a copy.": "Պահպանված է այս կոնտեյների միջավայրում։ Kiri-ն պատճեն չի պահում։", + "Saved the SBOM to Downloads as {file}": "SBOM-ը պահպանվեց Ներբեռնումներում՝ {file} անունով", + "Saved the report to {path}": "Հաշվետվությունը պահպանվեց այստեղ՝ {path}", + "Saved to Downloads as {file}": "Պահպանվեց Ներբեռնումներում՝ {file} անունով", + "Saved. The VM uses these from its next start": "Պահպանված է։ VM-ը դրանք կկիրառի հաջորդ գործարկումից", + "Saving…": "Պահպանվում է…", + "Scan again": "Նորից սկանավորել", + "Scan image": "Սկանավորել պատկերը", + "Scan of {when}": "Սկանավորում՝ {when}", + "Scan with": "Սկանավորել՝ օգտագործելով", + "Scan {image}": "Սկանավորել {image} պատկերը", + "Scan {image} for known vulnerabilities": "Ստուգել {image} պատկերը հայտնի խոցելիությունների համար", + "Scanned": "Սկանավորված", + "Scanning the image's packages": "Պատկերի փաթեթները սկանավորվում են", + "Scans": "Սկանավորումներ", + "Search Docker Hub, or paste an image reference": "Որոնեք Docker Hub-ում կամ տեղադրեք պատկերի հղումը", + "Search Kiri": "Որոնել Kiri-ում", + "Search Kiri…": "Որոնել Kiri-ում…", + "Search containers, images…": "Որոնել կոնտեյներներ, պատկերներ…", + "Search languages": "Որոնել լեզուներ", + "Search {view}…": "Որոնել՝ {view}…", + "Searching Docker Hub": "Որոնում Docker Hub-ում", + "Security": "Անվտանգություն", + "See it ↗": "Դիտել ↗", + "See its tags": "Դիտել պիտակները", + "See what it looks like ↗": "Ինչ տեսք ունի ↗", + "See why": "Ինչու՞", + "Select": "Ընտրել", + "Select All": "Ընտրել բոլորը", + "Select all": "Ընտրել բոլորը", + "Select all {n}": "Ընտրել բոլորը ({n})", + "Select none": "Չեղարկել ընտրությունը", + "Select {name}": "Ընտրել՝ {name}", + "Selected {what}": "Ընտրված՝ {what}", + "Selection, focus rings and primary buttons.": "Ընտրություն, ֆոկուսի շրջանակներ և հիմնական կոճակներ։", + "Selector": "Ընտրիչ", + "Send": "Ուղարկել", + "Send a report to Kiri": "Ուղարկել հաշվետվություն Kiri-ին", + "Send an idea or report a bug on GitHub": "Առաջարկել գաղափար կամ հայտնել սխալի մասին GitHub-ում", + "Send crash reports automatically": "Ավտոմատ ուղարկել խափանումների հաշվետվությունները", + "Send report": "Ուղարկել հաշվետվությունը", + "Send to Kiri": "Ուղարկել Kiri-ին", + "Sending…": "Ուղարկվում է…", + "Sent": "Ուղարկված է", + "Sent as {id}": "Ուղարկվեց՝ {id}", + "Sent. Quote {id} if you write to us.": "Ուղարկվեց։ Մեզ գրելիս նշեք {id} համարը։", + "Serial": "Հաջորդական պորտ", + "Serial number": "Սերիական համար", + "Services": "Ծառայություններ", + "Services you create with kubectl expose show up here. LoadBalancer services answer on localhost.": "kubectl expose հրամանով ստեղծված ծառայությունները հայտնվում են այստեղ։ LoadBalancer ծառայությունները պատասխանում են localhost հասցեով։", + "Session": "Սեանս", + "Set it and start": "Նշել և գործարկել", + "Set up": "Կարգավորել", + "Set up Kiri": "Կարգավորել Kiri-ն", + "Set up Kiri's builder so docker build runs here. Nothing downloads until your first build": "Կարգավորեք Kiri-ի կառուցիչը, որպեսզի docker build-ն աշխատի այստեղ։ Մինչև առաջին կառուցումը ոչինչ չի ներբեռնվում", + "Set up with Kiri Linux": "Կարգավորել Kiri Linux-ով", + "Set up with Ubuntu": "Կարգավորել Ubuntu-ով", + "Set {what}": "Նշել՝ {what}", + "Sets ACCEPT_EULA=Y, as Microsoft's image asks.": "Նշում է ACCEPT_EULA=Y, ինչպես պահանջում է Microsoft-ի պատկերը։", + "Setting up": "Կարգավորում", + "Setting up Docker tools…": "Docker-ի գործիքները կարգավորվում են…", + "Setting up Docker tools… {pct}%": "Docker-ի գործիքները կարգավորվում են… {pct}%", + "Setting up Kiri Linux": "Kiri Linux-ը կարգավորվում է", + "Setting up Ubuntu 26.04": "Ubuntu 26.04-ը կարգավորվում է", + "Setting up the Docker tools": "Docker-ի գործիքները կարգավորվում են", + "Settings": "Կարգավորումներ", + "Settings…": "Կարգավորումներ…", + "Setup log": "Տեղադրման մատյան", + "Setup steps": "Տեղադրման քայլեր", + "Setup time": "Տեղադրման ժամանակը", + "Severity": "Կարևորություն", + "Share": "Կիսվել", + "Share again": "Նորից կիսվել", + "Share gives a container or a Kubernetes service a public https link through a secure tunnel to Kiri Cloud.": "«Կիսվել» գործառույթը կոնտեյներին կամ Kubernetes ծառայությանը տալիս է հանրային https հղում՝ Kiri Cloud-ի հետ անվտանգ թունելի միջոցով։", + "Share pod {name}?": "Կիսվե՞լ {name} pod-ով։", + "Share service {name}": "Կիսվել {name} ծառայությամբ", + "Share this pod on a port…": "Կիսվել այս pod-ով որևէ պորտում…", + "Share this pod's port {port}": "Կիսվել այս pod-ի {port} պորտով", + "Share which port?": "Ո՞ր պորտով կիսվել։", + "Share {name}": "Կիսվել՝ {name}", + "Shared": "Կիսված է", + "Shared by {who}": "Կիսվել է՝ {who}", + "Shared now": "Այժմ կիսված", + "Shared with {os}: the VM only uses them while containers are busy.": "Ընդհանուր են {os} համակարգի հետ՝ VM-ը դրանք օգտագործում է միայն այն ժամանակ, երբ կոնտեյներները զբաղված են։", + "Shared · {url}": "Կիսված է · {url}", + "Shares": "Կիսումներ", + "Sharing…": "Կիսվում է…", + "Short of memory, its API server slows down or stops answering.": "Հիշողության պակասի դեպքում դրա API սերվերը դանդաղում է կամ դադարում է պատասխանել։", + "Show": "Ցույց տալ", + "Show Images": "Ցույց տալ պատկերները", + "Show all actions": "Ցույց տալ բոլոր գործողությունները", + "Show containers": "Ցույց տալ կոնտեյներները", + "Show full log": "Ցույց տալ ամբողջական մատյանը", + "Show in Diagnostics": "Ցույց տալ Ախտորոշումում", + "Show in Finder": "Ցույց տալ Finder-ում", + "Show its requests": "Ցույց տալ դրա հարցումները", + "Show password": "Ցույց տալ գաղտնաբառը", + "Show shares": "Ցույց տալ կիսումները", + "Show the crash report": "Ցույց տալ խափանման հաշվետվությունը", + "Show the pulls in Images": "Ցույց տալ ներբեռնումները «Պատկերներ» բաժնում", + "Show the sidebar": "Ցույց տալ կողային վահանակը", + "Show the terminal ({keys})": "Ցույց տալ տերմինալը ({keys})", + "Show the update": "Ցույց տալ թարմացումը", + "Sign in": "Մուտք գործել", + "Sign in and pull": "Մուտք գործել և ներբեռնել", + "Sign in to a registry": "Մուտք գործել ռեեստր", + "Sign in to a registry…": "Մուտք գործել ռեեստր…", + "Sign in to see your plan": "Մուտք գործեք՝ ձեր սակագինը տեսնելու համար", + "Sign in to share {what}": "Մուտք գործեք, որպեսզի կիսվեք՝ {what}", + "Sign in to {registry}": "Մուտք գործել՝ {registry}", + "Sign in with AWS": "Մուտք գործել AWS-ով", + "Sign in with GitHub": "Մուտք գործել GitHub-ով", + "Sign out": "Դուրս գալ", + "Sign out of {registry}": "Դուրս գալ՝ {registry}", + "Sign out of {registry}?": "Դուրս գա՞լ՝ {registry}։", + "Sign-in failed: {error}": "Մուտքը ձախողվեց: {error}", + "Sign-in needed.": "Անհրաժեշտ է մուտք գործել։", + "Signed in": "Մուտք եք գործել", + "Signed in as {name}": "Մուտք եք գործել որպես {name}", + "Signed in as {name}.": "Մուտք եք գործել որպես {name}։", + "Signed in to Kiri Cloud with GitHub as {login}": "Մուտք եք գործել Kiri Cloud GitHub-ով՝ որպես {login}", + "Signed in to a registry, Kiri pulls its private images, and docker uses the same sign-in.": "Ռեեստր մուտք գործելուց հետո Kiri-ն ներբեռնում է դրա մասնավոր պատկերները, իսկ docker-ն օգտագործում է նույն մուտքը։", + "Signed in with GitHub": "Մուտք եք գործել GitHub-ով", + "Signing in again uses your AWS profile.": "Կրկին մուտք գործելու համար օգտագործվում է ձեր AWS պրոֆիլը։", + "Signing in…": "Մուտք…", + "Signing out…": "Ելք…", + "Size": "Չափ", + "Skip": "Բաց թողնել", + "Skip this version": "Բաց թողնել այս տարբերակը", + "Skipped: docker build builds where docker points": "Բաց է թողնված՝ docker build-ը կառուցում է այնտեղ, ուր ցույց է տալիս docker-ը", + "Skipped: docker keeps using the engine it has now": "Բաց է թողնված՝ docker-ը շարունակում է օգտագործել իր ներկայիս շարժիչը", + "Skipped: {problem}": "Բաց թողնվեց՝ {problem}", + "Slow because the VM is out of memory": "Դանդաղ է, քանի որ VM-ի հիշողությունը սպառվել է", + "Small": "Փոքր", + "Smaller": "Ավելի փոքր", + "Snooze ▾": "Հետաձգել ▾", + "Something else on this {host} has it. Give {name} another port.": "Այն զբաղեցրել է այս {host} համակարգչի մեկ այլ ծրագիր։ Նշեք այլ պորտ՝ {name}։", + "Something went wrong": "Ինչ-որ բան այն չգնաց", + "Soon": "Շուտով", + "Speed": "Արագություն", + "Split down": "Բաժանել ներքև", + "Split down ({keys})": "Բաժանել ներքև ({keys})", + "Split right": "Բաժանել աջ", + "Split right ({keys})": "Բաժանել աջ ({keys})", + "Start": "Գործարկել", + "Start Kiri": "Գործարկել Kiri-ն", + "Start Kiri to change its network settings. ({error})": "Գործարկեք Kiri-ն՝ դրա ցանցային կարգավորումները փոխելու համար։ ({error})", + "Start Kiri to change its registry settings. ({error})": "Գործարկեք Kiri-ն՝ ռեեստրի կարգավորումները փոխելու համար։ ({error})", + "Start Kiri to change its resources. ({error})": "Գործարկեք Kiri-ն՝ դրա ռեսուրսները փոխելու համար։ ({error})", + "Start Kiri to change the ports names answer on.": "Գործարկեք Kiri-ն՝ փոխելու այն պորտերը, որոնցով պատասխանում են անունները։", + "Start Kiri when I sign in (in the tray)": "Գործարկել Kiri-ն համակարգ մուտք գործելիս (ծանուցումների տարածքում)", + "Start Kubernetes": "Գործարկել Kubernetes-ը", + "Start Linux VM": "Գործարկել Linux VM-ը", + "Start a single-node cluster (k3s) in one Kiri container. Its API is on {api} (or the next free port), and kubectl gets the {context} context, as with kiri k8s start.": "Գործարկել մեկ հանգույցով կլաստեր (k3s) Kiri-ի մեկ կոնտեյներում։ Դրա API-ն կլինի {api} հասցեում (կամ հաջորդ ազատ պորտում), իսկ kubectl-ը կստանա {context} կոնտեքստը, ինչպես kiri k8s start հրամանի դեպքում։", + "Start again": "Նորից գործարկել", + "Start all": "Գործարկել բոլորը", + "Start engine": "Գործարկել շարժիչը", + "Start it": "Գործարկել", + "Start it to restart it": "Գործարկեք՝ վերագործարկելու համար", + "Start it to run containers. It starts in a fraction of a second and sleeps when idle.": "Գործարկեք այն՝ կոնտեյներներ աշխատեցնելու համար։ Այն գործարկվում է վայրկյանի մի մասում և քնում է պարապ ժամանակ։", + "Start it to share it": "Գործարկեք՝ կիսվելու համար", + "Start scan": "Սկսել սկանավորումը", + "Start the container to run commands in it.": "Գործարկեք կոնտեյները՝ դրանում հրամաններ կատարելու համար։", + "Start the engine": "Գործարկել շարժիչը", + "Start {engine} to bring its images over now, or later from Settings → Import.": "Գործարկեք {engine} շարժիչը՝ դրա պատկերներն անմիջապես տեղափոխելու համար, կամ արեք դա ավելի ուշ՝ Կարգավորումներ → Ներմուծել։", + "Started": "Գործարկված", + "Started with {name} set": "Գործարկվեց {name} փոփոխականով", + "Started {name}": "Գործարկվեց՝ {name}", + "Started {name} on {ports}": "Գործարկվեց՝ {name}, պորտեր՝ {ports}", + "Starting": "Գործարկվում է", + "Starting Kiri’s engine": "Kiri-ի շարժիչը գործարկվում է", + "Starting Kubernetes…": "Kubernetes-ը գործարկվում է…", + "Starting the scan": "Սկանավորումը սկսվում է", + "Starting…": "Գործարկվում է…", + "State": "Վիճակ", + "Status": "Կարգավիճակ", + "Step 1 of 5": "Քայլ 1՝ 5-ից", + "Step 2 of 5": "Քայլ 2՝ 5-ից", + "Step 2 of 5. Nothing else on this PC changes: Kiri sets itself up for your Windows account only.": "Քայլ 2՝ 5-ից։ Այս համակարգչում ուրիշ ոչինչ չի փոխվում՝ Kiri-ն կարգավորվում է միայն ձեր Windows հաշվի համար։", + "Step 3 of 5": "Քայլ 3՝ 5-ից", + "Step 4 of 5": "Քայլ 4՝ 5-ից", + "Steps": "Քայլեր", + "Stop": "Կանգնեցնել", + "Stop Kubernetes?": "Կանգնեցնե՞լ Kubernetes-ը։", + "Stop Linux VM": "Կանգնեցնել Linux VM-ը", + "Stop all": "Կանգնեցնել բոլորը", + "Stop on {host}": "Կանգնեցնել {host} համակարգչում", + "Stop sharing": "Դադարեցնել կիսումը", + "Stop signal": "Կանգնեցման ազդանշան", + "Stop {name}": "Կանգնեցնել՝ {name}", + "Stop {name} on {host}?": "Կանգնեցնե՞լ {name} կիսումը {host} համակարգչում։", + "Stopped": "Կանգնեցված", + "Stopped {when}": "Կանգնեցվել է {when}", + "Stopped {when}, when the {vm} stopped. Start it again whenever you like.": "Կանգնեցվել է {when}՝ «{vm}» բաղադրիչի հետ միասին։ Նորից գործարկեք այն, երբ ցանկանաք։", + "Stopped {when}: its memory ran out": "Կանգնեցվել է {when}՝ հիշողությունը սպառվել է", + "Stopped {when}: its memory ran out (the VM has {mem})": "Կանգնեցվել է {when}՝ հիշողությունը սպառվեց (VM-ի հիշողությունը՝ {mem})", + "Stopped: out of memory": "Կանգնեցվել է՝ հիշողությունը սպառվեց", + "Stopping": "Կանգնեցվում է", + "Stopping…": "Կանգնեցվում է…", + "Stop…": "Կանգնեցնել…", + "Storage": "Կրիչ", + "Strong enough": "Բավականաչափ հուսալի է", + "Subnet": "Ենթացանց", + "Suggested": "Առաջարկվող", + "Switch and import": "Փոխարկել և ներմուծել", + "Switch and import {n} item": "Փոխարկել և ներմուծել {n} տարր", + "Switch and import {n} items": "Փոխարկել և ներմուծել {n} տարր", + "Switch back": "Հետ փոխարկել", + "Switch to the dark theme": "Անցնել մուգ թեմային", + "Switch to the light theme": "Անցնել բաց թեմային", + "Switch to {app}": "Անցնել {app} հավելվածին", + "System": "Համակարգային", + "System Mono|font": "Համակարգային հավասարալայն", + "System|font": "Համակարգային", + "Tab pinned": "Ներդիրն ամրացվեց", + "Tab unpinned": "Ներդիրն ապամրացվեց", + "Tables, the sidebar and headings.": "Աղյուսակներ, կողագոտի և վերնագրեր։", + "Tag": "Պիտակ", + "Teal": "Կապտականաչ", + "Tell us how it goes": "Պատմեք, թե ինչպես է աշխատում", + "Terminal": "Տերմինալ", + "Terminal ({keys})": "Տերմինալ ({keys})", + "Terminated": "Ավարտվել է", + "Test build": "Փորձնական կառուցում", + "Text size": "Տեքստի չափ", + "Text size {n} px": "Տեքստի չափը՝ {n} px", + "That's a lot to copy and can take a long time; choosing what you need is quicker.": "Սա պատճենելու մեծ ծավալ է և կարող է երկար տևել։ Ավելի արագ է ընտրել միայն անհրաժեշտը։", + "The 5 newest, and macOS's own crash reports for Kiri from the last 30 days": "5 ամենանորերը, ինչպես նաև Kiri-ի խափանումների մասին macOS-ի սեփական հաշվետվությունները վերջին 30 օրվա ընթացքում", + "The API server port must be a number from 1024 to 65535": "API սերվերի պորտը պետք է լինի 1024-ից 65535 միջակայքի թիվ", + "The AWS CLI has no profiles yet. Set one up with {cmd}.": "AWS CLI-ում դեռ պրոֆիլներ չկան։ Ստեղծեք պրոֆիլ այս հրամանով՝ {cmd}։", + "The GitHub CLI stays signed in.": "GitHub CLI-ն մուտք գործած կմնա։", + "The Kubernetes API server. It's never shared: anyone with the link could try to control the cluster.": "Kubernetes-ի API սերվերը։ Այն երբեք հանրային չի դարձվում՝ հղումն ունեցող ցանկացած ոք կարող էր փորձել կառավարել կլաստերը։", + "The Linux VM restarted with the new resources": "Linux վիրտուալ մեքենան վերագործարկվեց նոր ռեսուրսներով", + "The VM has {mem}; {free}.": "Վիրտուալ մեքենան ունի {mem}, {free}։", + "The VM is asleep; it starts with these next time.": "Վիրտուալ մեքենան քնած է, հաջորդ անգամ այն կգործարկվի այս կարգավորումներով։", + "The VM's memory is nearly full: {used} of {max}.": "Վիրտուալ մեքենայի հիշողությունը գրեթե լցված է՝ {used} / {max}։", + "The app on {host} keeps running, and {program} there shows the share as stopped from another computer.": "{host} համակարգչի հավելվածը շարունակում է աշխատել, իսկ այնտեղի {program} ծրագիրը ցույց կտա, որ կիսումը կանգնեցվել է մեկ այլ համակարգչից։", + "The build failed": "Կառուցումը ձախողվեց", + "The build was canceled": "Կառուցումը չեղարկվեց", + "The code goes straight to the AWS CLI; Kiri doesn't keep it.": "Կոդն ուղիղ փոխանցվում է AWS CLI-ին, Kiri-ն այն չի պահում։", + "The container keeps running.": "Կոնտեյները շարունակում է աշխատել։", + "The docker command is signed out too.": "docker հրամանը նույնպես դուրս կգա հաշվից։", + "The docker command uses {app}": "docker հրամանն օգտագործում է {app}", + "The docker command uses {engine}. Switch it to {app}": "docker հրամանն օգտագործում է {engine}։ Փոխարկել այն {app} հավելվածին", + "The engine": "Շարժիչը", + "The engine is running but not answering": "Շարժիչն աշխատում է, բայց չի պատասխանում", + "The engine is stopped": "Շարժիչը կանգնեցված է", + "The engine isn't here: reinstall the kiri package": "Շարժիչը չի գտնվել՝ վերատեղադրեք kiri փաթեթը", + "The engine still runs Kiri {version}": "Շարժիչը դեռ աշխատում է Kiri {version} տարբերակով", + "The engine still runs {version}. Restarting it stops running containers, and those with a restart policy start again.": "Շարժիչը դեռ աշխատում է {version} տարբերակով։ Վերագործարկումը կկանգնեցնի աշխատող կոնտեյներները, իսկ վերագործարկման քաղաքականություն ունեցողները նորից կգործարկվեն։", + "The first scan downloads Grype and its database, about 230 MB (3 GB unpacked).": "Առաջին ստուգումը ներբեռնում է Grype-ը և դրա տվյալների բազան՝ մոտ 230 ՄԲ (3 ԳԲ՝ բացված վիճակում)։", + "The full Ubuntu from Microsoft's WSL list. Kiri runs in it, and you can open it as your own Linux too.": "Ամբողջական Ubuntu-ն Microsoft-ի WSL ցանկից։ Kiri-ն աշխատում է դրանում, և դուք նույնպես կարող եք բացել այն որպես ձեր սեփական Linux-ը։", + "The image's own way to start without it.": "Պատկերի սեփական եղանակը՝ գործարկվելու առանց դրա։", + "The kiri share there stops.": "Այնտեղ kiri share հրամանը կկանգնի։", + "The last 300 lines from the window, the engine and kiri commands, and the engine's own output": "Պատուհանի, շարժիչի և kiri հրամանների վերջին 300 տողերը, ինչպես նաև շարժիչի սեփական ելքը", + "The last {n} seconds": "Վերջին {n} վայրկյանը", + "The link ends when the pod does.": "Հղումը կդադարի աշխատել pod-ի հետ միասին։", + "The most the VM may take. It uses memory only as containers need it and gives the rest back to {os}.": "Առավելագույնը, որքան կարող է զբաղեցնել վիրտուալ մեքենան։ Այն հիշողություն է օգտագործում միայն այնքան, որքան պետք է կոնտեյներներին, իսկ մնացածը վերադարձնում է {os} համակարգին։", + "The name comes from the Igbo word ntakịrị, “small”.": "Անունը ծագում է իգբո լեզվի ntakịrị բառից, որը նշանակում է «փոքր»։", + "The part that runs your containers, inside {linux}.": "Մասը, որը գործարկում է ձեր կոնտեյներները, {linux} համակարգի ներսում։", + "The port on this {host} for the API server, from 1024 to 65535 (6443 by default). If it's in use when the cluster starts, the next free one is taken. Saving restarts the cluster and updates the {context} context.": "API սերվերի պորտը այս {host} համակարգչում՝ 1024-ից 65535 (լռելյայն՝ 6443)։ Եթե կլաստերի գործարկման պահին այն զբաղված է, վերցվում է հաջորդ ազատը։ Պահպանելիս կլաստերը վերագործարկվում է, և {context} կոնտեքստը թարմացվում է։", + "The profile {profile} asks for a code from your MFA device {device}.": "{profile} պրոֆիլը կոդ է պահանջում ձեր MFA սարքից՝ {device}։", + "The profile {profile} asks for a code from your MFA device.": "{profile} պրոֆիլը կոդ է պահանջում ձեր MFA սարքից։", + "The profile {profile} signs in through AWS IAM Identity Center. Kiri runs {cmd}, which opens AWS's page.": "{profile} պրոֆիլը մուտք է գործում AWS IAM Identity Center-ի միջոցով։ Kiri-ն գործարկում է {cmd} հրամանը, որը բացում է AWS-ի էջը։", + "The run before the container's last restart": "Կոնտեյների վերջին վերագործարկումից առաջվա աշխատանքը", + "The same docker commands you know, talking to Kiri. Each file is checked against its pinned SHA-256.": "Ձեզ ծանոթ նույն docker հրամանները, որոնք աշխատում են Kiri-ի հետ։ Յուրաքանչյուր ֆայլ ստուգվում է իր ամրագրված SHA-256 հեշով։", + "The window": "Պատուհանը", + "The {n} packages as CycloneDX JSON, saved to Downloads": "{n} փաթեթ CycloneDX JSON ձևաչափով՝ պահված «Ներբեռնումներ» թղթապանակում", + "The {vm} is asleep: it holds no memory": "{vm}՝ քնած է և հիշողություն չի զբաղեցնում", + "Theme": "Թեմա", + "They appear in Images as they arrive.": "Դրանք հայտնվում են «Պատկերներ» բաժնում՝ ներբեռնվելուն պես։", + "This action left no log lines.": "Այս գործողությունը մատյանում տողեր չի թողել։", + "This build made no image to scan: it failed before exporting, or its output was the cache only.": "Այս կառուցումը ստուգելու համար պատկեր չի ստեղծել՝ այն ձախողվել է արտահանումից առաջ, կամ դրա արդյունքը միայն քեշն էր։", + "This build made no image: it failed before exporting, or its output was the cache only.": "Այս կառուցումը պատկեր չի ստեղծել՝ այն ձախողվել է արտահանումից առաջ, կամ դրա արդյունքը միայն քեշն էր։", + "This build's image isn't in Kiri, so there's nothing here to scan. It was pushed or exported elsewhere, or removed since. Build it with --load to scan it here.": "Այս կառուցման պատկերը Kiri-ում չէ, ուստի այստեղ ստուգելու բան չկա։ Այն վերբեռնվել կամ արտահանվել է այլ տեղ, կամ այդ ընթացքում ջնջվել է։ Կառուցեք այն --load դրոշակով՝ այստեղ ստուգելու համար։", + "This can't be undone.": "Սա հնարավոր չէ հետարկել։", + "This closes that tunnel on {host}, from here. The link stops working for everyone.": "Սա այստեղից կփակի {host} համակարգչի թունելը։ Հղումը կդադարի աշխատել բոլորի համար։", + "This computer can't use it while it's in Kiri: detach it to get it back.": "Այս համակարգիչը չի կարող այն օգտագործել, քանի դեռ այն Kiri-ում է։ Անջատեք այն՝ հետ ստանալու համար։", + "This file is binary or larger than 256 KB.": "Այս ֆայլը երկուական է կամ 256 ԿԲ-ից մեծ։", + "This folder is empty.": "Այս թղթապանակը դատարկ է։", + "This image": "Այս պատկերը", + "This image needs privileged mode": "Այս պատկերին անհրաժեշտ է արտոնյալ ռեժիմ", + "This is Kubernetes. Kiri runs it for you": "Սա Kubernetes-ն է։ Kiri-ն այն գործարկում է ձեր փոխարեն", + "This lists every link on your account, on any computer.": "Այստեղ նշված են ձեր հաշվի բոլոր հղումները՝ բոլոր համակարգիչներից։", + "This month": "Այս ամիս", + "This pod's name changes when it restarts, and the link would end.": "Այս pod-ի անունը փոխվում է վերագործարկվելիս, և հղումը կդադարի աշխատել։", + "This sign-in's ID: a hash of its token, safe to quote when asking for help": "Այս մուտքի ID-ն՝ դրա տոկենի հեշը, որը կարելի է անվտանգ նշել օգնություն խնդրելիս", + "This system applies your new access when you sign in again. Kiri opens ready after that.": "Համակարգը ձեր նոր մուտքի իրավունքները կկիրառի, երբ նորից մուտք գործեք։ Դրանից հետո Kiri-ն կբացվի աշխատանքի պատրաստ։", + "Time": "Ժամանակ", + "To make names like {name} work, Kiri adds one small settings file to your Mac ({path}), and changing system settings always needs an administrator. Kiri uses the password only for that, once. It never sees the password: macOS handles it.": "Որպեսզի {name} տիպի անունները աշխատեն, Kiri-ն ձեր Mac-ում ավելացնում է կարգավորումների մեկ փոքր ֆայլ ({path}), իսկ համակարգային կարգավորումները փոխելու համար միշտ ադմինիստրատոր է պետք։ Kiri-ն գաղտնաբառն օգտագործում է միայն դրա համար և միայն մեկ անգամ։ Այն երբեք չի տեսնում գաղտնաբառը՝ դրանով զբաղվում է macOS-ը։", + "Today {time}": "Այսօր՝ {time}", + "Token": "Տոկեն", + "Token or password": "Տոկեն կամ գաղտնաբառ", + "Tomorrow": "Վաղը", + "Took": "Տևողություն", + "Traffic over the last two minutes": "Տրաֆիկը վերջին երկու րոպեում", + "Traffic served": "Սպասարկված տրաֆիկ", + "Trust Kiri's certificate so {url} works. macOS asks for your password. The certificate can only vouch for Kiri's own names.": "Վստահեք Kiri-ի սերտիֆիկատին, որպեսզի {url} հասցեն աշխատի։ macOS-ը կպահանջի ձեր գաղտնաբառը։ Սերտիֆիկատը կարող է երաշխավորել միայն Kiri-ի սեփական անունները։", + "Try again": "Կրկին փորձել", + "Turn off engine": "Անջատել շարժիչը", + "Turn on Kiri's in Settings → Kubernetes instead of starting a copy.": "Պատճեն գործարկելու փոխարեն միացրեք Kiri-ի կլաստերը՝ «Կարգավորումներ» → «Kubernetes» բաժնում։", + "Turn on Kubernetes": "Միացնել Kubernetes-ը", + "Turn on WSL's Windows components": "Միացնել WSL-ի Windows բաղադրիչները", + "Turn security off for local use": "Անջատել պաշտպանությունը տեղային օգտագործման համար", + "Type": "Տեսակ", + "Type one, or generate it": "Մուտքագրեք կամ ստեղծեք այն", + "Type to search Docker Hub, or paste a full reference such as {a} or {b} to pull exactly that.": "Մուտքագրեք՝ Docker Hub-ում որոնելու համար, կամ տեղադրեք ամբողջական հղում, օրինակ՝ {a} կամ {b}, որպեսզի ներբեռնեք հենց այն։", + "USB": "USB", + "USB device": "USB սարք", + "USB needs usbipd-win": "USB-ի համար անհրաժեշտ է usbipd-win", + "USB passthrough is in beta.": "USB փոխանցումը բետա փուլում է։", + "USB passthrough is new: tell us how it works with your devices": "USB փոխանցումը նոր է՝ պատմեք մեզ, թե ինչպես է այն աշխատում ձեր սարքերի հետ", + "Ubuntu is already on this PC, so choosing it downloads nothing.": "Ubuntu-ն արդեն կա այս համակարգչում, ուստի այն ընտրելիս ոչինչ չի ներբեռնվի։", + "Undo": "Հետարկել", + "Undo brings it back": "«Հետարկել» կոճակը այն կվերադարձնի", + "Undo brings them back": "«Հետարկել» կոճակը դրանք կվերադարձնի", + "Unknown": "Անհայտ", + "Unpack Kiri Linux": "Ապափաթեթավորել Kiri Linux-ը", + "Unpack it into WSL": "Ապափաթեթավորել այն WSL-ում", + "Unpin tab": "Ապամրացնել ներդիրը", + "Untagged": "Առանց պիտակի", + "Untagged; another tag still uses it": "Պիտակը հանվեց, պատկերը դեռ օգտագործվում է մեկ այլ պիտակով", + "Unused": "Չօգտագործվող", + "Up to date": "Վերջին տարբերակն է", + "Up {time}": "Աշխատում է {time}", + "Up {time} (Paused)": "Աշխատում է {time} (դադարեցված)", + "Updating": "Թարմացվում է", + "Updating the vulnerability database (about 200 MB the first time)": "Խոցելիությունների բազայի թարմացում (առաջին անգամ՝ մոտ 200 ՄԲ)", + "Upper and lower case, a digit and a symbol, 8 or more": "Մեծատառ և փոքրատառ, թվանշան և նշան, առնվազն 8 նիշ", + "Use AWS profile": "Օգտագործել AWS պրոֆիլ", + "Use Kiri": "Օգտագործել Kiri-ն", + "Use Kiri Linux instead": "Փոխարենը օգտագործել Kiri Linux-ը", + "Use Kiri's Kubernetes": "Օգտագործել Kiri-ի Kubernetes-ը", + "Use Save to Downloads to open it.": "Բացելու համար սեղմեք «Պահպանել Ներբեռնումներում»։", + "Use Show in Finder to open it.": "Բացելու համար սեղմեք «Ցույց տալ Finder-ում»։", + "Use a Docker Hub personal access token (Account settings → Personal access tokens).": "Օգտագործեք Docker Hub-ի անձնական մուտքի տոկեն (Account settings → Personal access tokens)։", + "Use a GitHub personal access token (classic) with the {scope} scope.": "Օգտագործեք GitHub-ի անձնական մուտքի տոկեն (classic)՝ {scope} թույլտվությամբ։", + "Use a personal or deploy token with the {scope} scope.": "Օգտագործեք անձնական կամ տեղակայման տոկեն՝ {scope} թույլտվությամբ։", + "Use another port": "Օգտագործել այլ պորտ", + "Use the Ubuntu already here": "Օգտագործել արդեն առկա Ubuntu-ն", + "Use this profile": "Օգտագործել այս պրոֆիլը", + "Use your AWS profile": "Օգտագործել ձեր AWS պրոֆիլը", + "Use your password, or a robot account's name and token.": "Օգտագործեք ձեր գաղտնաբառը կամ ռոբոտ հաշվի անունն ու տոկենը։", + "Use {app} for docker?": "docker-ի համար օգտագործե՞լ {app}։", + "Use {name} instead": "Փոխարենը օգտագործել {name}", + "Used by": "Օգտագործվում է", + "User": "Օգտատեր", + "Username": "Օգտանուն", + "Using the Ubuntu already on this PC: nothing to download.": "Օգտագործվում է այս համակարգչում արդեն առկա Ubuntu-ն՝ ներբեռնելու բան չկա։", + "VPNs need no setting: container traffic leaves through macOS.": "VPN-ները կարգավորում չեն պահանջում՝ կոնտեյներների տրաֆիկը դուրս է գնում macOS-ի միջոցով։", + "Value": "Արժեք", + "Version {version}": "Տարբերակ {version}", + "Versions, macOS, whether the engine runs, how many containers and images": "Տարբերակները, macOS-ը, աշխատում է արդյոք շարժիչը, քանի կոնտեյներ և պատկեր կա", + "View": "Տեսք", + "View container": "Դիտել կոնտեյները", + "Visitors": "Այցելուներ", + "Visitors' browsers see a short Kiri Cloud notice page first, then your app.": "Այցելուների դիտարկիչները նախ ցույց են տալիս կարճ Kiri Cloud ծանուցման էջ, ապա՝ ձեր հավելվածը։", + "Volumes": "Հատորներ", + "Vulnerabilities": "Խոցելիություններ", + "Vulnerability": "Խոցելիություն", + "WSL restarted with the new resources": "WSL-ը վերագործարկվեց նոր ռեսուրսներով", + "WSL, downloaded from Microsoft": "WSL՝ ներբեռնված Microsoft-ից", + "Waiting": "Սպասում", + "Waiting for GitHub…": "Սպասում ենք GitHub-ին…", + "Waiting for Windows' approval": "Սպասում ենք Windows-ի թույլտվությանը", + "Waiting for the API server…": "Սպասում ենք API սերվերին…", + "Waiting for the first sample…": "Սպասում ենք առաջին չափմանը…", + "Waiting for the first visitor…": "Սպասում ենք առաջին այցելուին…", + "Waiting for you to approve {code} in the browser…": "Սպասում ենք, որ զննարկիչում հաստատեք {code} կոդը…", + "Waiting for you to sign in in the browser…": "Սպասում ենք, որ մուտք գործեք զննարկիչում…", + "Warn": "Զգուշացում", + "Warnings": "Զգուշացումներ", + "Warnings and errors": "Զգուշացումներ և սխալներ", + "We get the file below, redacted, and you get an ID to quote when you write to us. If you're signed in to Kiri Cloud, it says it's from you, so we can reply.": "Մենք կստանանք ստորև նշված ֆայլը՝ անձնական տվյալները հեռացված, իսկ դուք կստանաք ID, որը պետք է նշեք մեզ գրելիս։ Եթե մուտք եք գործել Kiri Cloud, ֆայլում նշված կլինի, որ այն ձեզանից է, որպեսզի կարողանանք պատասխանել։", + "Website": "Կայք", + "Welcome to Kiri": "Բարի գալուստ Kiri", + "What Kiri's window uses on this {host}, not counting the {vm}:": "Որքան է օգտագործում Kiri-ի պատուհանն այս սարքում ({host})՝ առանց հաշվի առնելու «{vm}» բաղադրիչը:", + "What is WSL?": "Ի՞նչ է WSL-ը։", + "What to import": "Ինչ ներմուծել", + "What's new": "Ինչ նոր կա", + "What's new in Kiri {version}": "Kiri {version} տարբերակի նորույթները", + "What's new in {version}": "{version} տարբերակի նորույթները", + "When part of Kiri crashes, the stack trace and the last 200 log lines before it go to Kiri Cloud, with Kiri's and the system's versions, the computer's model and a random ID for this install. Never your Kiri Cloud account, and nothing from inside your containers. Your home folder, image and container names, tokens and passwords are taken out.": "Երբ Kiri-ի որևէ մաս խափանվում է, ստեկի հետագիծը և դրանից առաջ մատյանի վերջին 200 տողը ուղարկվում են Kiri Cloud՝ Kiri-ի և համակարգի տարբերակների, համակարգչի մոդելի և այս տեղադրման պատահական ID-ի հետ միասին։ Ձեր Kiri Cloud հաշիվը երբեք չի ուղարկվում, ինչպես նաև ոչինչ ձեր կոնտեյներների ներսից։ Ձեր տնային թղթապանակը, պատկերների և կոնտեյներների անունները, տոկեններն ու գաղտնաբառերը հեռացվում են։", + "When the pod restarts, it gets a new name and the link ends.": "Երբ pod-ը վերագործարկվում է, այն ստանում է նոր անուն, և հղումն այլևս չի աշխատում։", + "Where should your containers run?": "Որտե՞ղ աշխատեն ձեր կոնտեյներները։", + "Which steps": "Որ քայլերը", + "Window": "Պատուհան", + "Windows Subsystem for Linux": "Windows-ի ենթահամակարգ Linux-ի համար", + "Windows asks for an administrator's approval once.": "Windows-ը մեկ անգամ կխնդրի ադմինիստրատորի թույլտվություն։", + "Windows hands USB devices to WSL, where Kiri's containers run, through usbipd-win, Microsoft's recommended tool.": "Windows-ը USB սարքերը փոխանցում է WSL-ին, որտեղ աշխատում են Kiri-ի կոնտեյներները, usbipd-win-ի միջոցով, որը Microsoft-ի առաջարկած գործիքն է։", + "Windows is asking": "Windows-ը հարցնում է", + "Windows turns on Virtual Machine Platform while it starts up. Kiri opens again by itself afterwards and carries on from step 2. Save your work first.": "Windows-ը բեռնման ընթացքում կմիացնի վիրտուալ մեքենաների հարթակը (Virtual Machine Platform)։ Դրանից հետո Kiri-ն ինքը նորից կբացվի և կշարունակի 2-րդ քայլից։ Նախ պահպանեք ձեր աշխատանքը։", + "Windows will need one restart when this finishes. Kiri will ask before restarting, so you can save your work first.": "Երբ սա ավարտվի, Windows-ը պետք է մեկ անգամ վերագործարկվի։ Kiri-ն կհարցնի վերագործարկելուց առաջ, որպեսզի նախ պահպանեք ձեր աշխատանքը։", + "With a fix": "Ուղղումով", + "Working dir": "Աշխատանքային թղթապանակ", + "Yesterday {time}": "Երեկ {time}", + "You already have {engine}. Which should build your images?": "Դուք արդեն ունեք {engine}։ Ո՞րը կառուցի ձեր պատկերները։", + "You can change it later in Settings → Appearance.": "Սա կարող եք փոխել ավելի ուշ՝ Կարգավորումներ → Արտաքին տեսք։", + "You can change this later in Settings → Domains.": "Սա կարող եք փոխել ավելի ուշ՝ Կարգավորումներ → Դոմեններ։", + "You can keep working while they copy.": "Պատճենման ընթացքում կարող եք շարունակել աշխատել։", + "You can pull it again later.": "Ավելի ուշ կարող եք այն նորից ներբեռնել։", + "You can still pull the name as typed.": "Այնուամենայնիվ, կարող եք ներբեռնել անունն այնպես, ինչպես մուտքագրել եք։", + "You can switch any time in Settings → Builds.": "Կարող եք փոխել ցանկացած պահի՝ Կարգավորումներ → Կառուցումներ։", + "You have {ref}, {when}. Pull again to get any updates; only changed layers download.": "Դուք ունեք {ref}, {when}։ Նորից ներբեռնեք՝ թարմացումները ստանալու համար։ Ներբեռնվում են միայն փոփոխված շերտերը։", + "You have {ref}. Pull again to get any updates; only changed layers download.": "Դուք ունեք {ref}։ Նորից ներբեռնեք՝ թարմացումները ստանալու համար։ Ներբեռնվում են միայն փոփոխված շերտերը։", + "You have {tags}": "Դուք ունեք՝ {tags}", + "You have {version}": "Ձեր տարբերակը՝ {version}", + "You have {version}.": "Ձեր տարբերակը՝ {version}։", + "You sign in on github.com. Kiri gets a token that can only read packages.": "Դուք մուտք եք գործում github.com կայքում։ Kiri-ն ստանում է տոկեն, որը կարող է միայն կարդալ փաթեթները։", + "You're sharing {name}": "Կիսվում եք՝ {name}", + "Your AWS sign-in expired": "Ձեր AWS մուտքի ժամկետը լրացել է", + "Your account can use Kiri": "Ձեր հաշիվը կարող է օգտագործել Kiri-ն", + "Your containers keep running while it downloads.": "Ներբեռնման ընթացքում ձեր կոնտեյներները շարունակում են աշխատել։", + "Your home folder's path, tokens, passwords and other secrets are blanked before anything is written.": "Ձեր տնային թղթապանակի ուղին, տոկենները, գաղտնաբառերը և այլ գաղտնիքները ջնջվում են՝ նախքան որևէ բան գրանցելը։", + "Your link for {name} is live.": "Հղումն ակտիվ է՝ {name}։", + "Your other Docker": "Ձեր մյուս Docker-ը", + "Your own registry…": "Ձեր սեփական ռեեստրը…", + "Your password and two-step code go to Docker, not Kiri.": "Ձեր գաղտնաբառը և երկքայլ ստուգման կոդը ստանում է Docker-ը, ոչ թե Kiri-ն։", + "Your password, or an access token if the registry offers them.": "Ձեր գաղտնաբառը կամ մուտքի տոկեն, եթե ռեեստրը դրանք տրամադրում է։", + "Your plan allows {limit} tunnels at once, and all {limit} are in use: {slots}.": "Ձեր պլանը թույլ է տալիս միաժամանակ {limit} թունել, և բոլոր {limit} թունելն էլ զբաղված են՝ {slots}։", + "Your plan allows {limit} tunnels at once. In use: {slots}.": "Ձեր պլանը թույլ է տալիս միաժամանակ {limit} թունել։ Զբաղված են՝ {slots}։", + "Your plan allows {limit} tunnels at once; close one first.": "Ձեր պլանը թույլ է տալիս միաժամանակ {limit} թունել։ Նախ փակեք դրանցից մեկը։", + "Your plan allows {n} at once": "Ձեր պլանով միաժամանակ թույլատրվում է մինչև {n}", + "Your test container said hello. Open a new terminal and try it yourself:": "Ձեր փորձնական կոնտեյները ողջունեց ձեզ։ Բացեք նոր տերմինալ և փորձեք ինքներդ:", + "Your {engine} images and containers stay in {engine}. {app} can't see them until you bring them over.": "Ձեր {engine} պատկերներն ու կոնտեյներները մնում են {engine} միջավայրում։ {app} հավելվածը դրանք չի տեսնի, քանի դեռ չեք տեղափոխել։", + "Your {engine} images stay there. Bring them over any time from Settings → Import.": "Ձեր {engine} պատկերները մնում են այնտեղ։ Կարող եք դրանք տեղափոխել ցանկացած պահի՝ Կարգավորումներ → Ներմուծել։", + "Yours": "Ձերը", + "Zoom In": "Մեծացնել", + "Zoom Out": "Փոքրացնել", + "a container": "կոնտեյները", + "a free port": "ազատ պորտ", + "a password": "գաղտնաբառ", + "a root password": "root գաղտնաբառ", + "a saved token": "պահպանված տոկեն", + "about {min} min left": "մնաց մոտ {min} րոպե", + "about {n} min left": "մնաց մոտ {n} րոպե", + "about {n} s left": "մնաց մոտ {n} վ", + "about {sec} s left": "մնաց մոտ {sec} վ", + "about {time} left": "մնաց մոտ {time}", + "address": "հասցե", + "an admin password": "ադմինիստրատորի գաղտնաբառ", + "and was stopped. The VM has {mem}.": "և կանգնեցվեց։ Վիրտուալ մեքենայի հիշողությունը՝ {mem}։", + "and {n} more…": "և ևս {n}…", + "anonymous": "անանուն", + "another computer": "այլ համակարգիչ", + "answered in {ms} ms": "պատասխան՝ {ms} մվ", + "approved": "հաստատված է", + "auto": "ավտո", + "back": "հետ", + "build ID": "կառուցման ID", + "builds": "կառուցումներ", + "cached": "քեշից", + "checked {ago}": "ստուգվել է {ago}", + "choose tag": "ընտրել պիտակ", + "close": "փակել", + "compose lines": "compose տողեր", + "compressed": "սեղմված", + "computer": "համակարգիչ", + "container ID": "կոնտեյների ID", + "containers": "կոնտեյներներ", + "couldn't pull alpine: {why}": "չհաջողվեց ներբեռնել alpine-ը՝ {why}", + "created {date}": "ստեղծվել է {date}", + "database from {date}": "տվյալների բազա՝ {date}", + "digest": "digest", + "disk": "սկավառակ", + "disk read {read} · write {write}": "սկավառակի ընթերցում {read} · գրառում {write}", + "docker build on Kiri": "docker build Kiri-ում", + "docker build runs on Kiri's builder": "docker build-ն աշխատում է Kiri-ի կառուցիչում", + "docker flag": "docker դրոշակ", + "docker now uses {app}": "docker-ն այժմ օգտագործում է {app}", + "docker run, from any terminal": "docker run՝ ցանկացած տերմինալից", + "docker talks to another engine now": "docker-ն այժմ աշխատում է այլ շարժիչի հետ", + "docker uses Kiri": "docker-ն օգտագործում է Kiri-ն", + "docker, Compose and Docker-socket tools reach Kiri": "docker-ը, Compose-ը և Docker սոկետով աշխատող գործիքները միանում են Kiri-ին", + "docker, docker compose and docker build use Kiri in every new terminal. Another Docker was found on this PC; leave this off to keep using it as the default.": "docker-ը, docker compose-ը և docker build-ը յուրաքանչյուր նոր տերմինալում օգտագործում են Kiri-ն։ Այս համակարգչում գտնվել է մեկ այլ Docker։ Թողեք սա անջատված, որպեսզի այն մնա լռելյայնը։", + "docker, docker compose and docker build use Kiri in every new terminal. No other Docker was found on this PC.": "docker-ը, docker compose-ը և docker build-ը յուրաքանչյուր նոր տերմինալում օգտագործում են Kiri-ն։ Այս համակարգչում այլ Docker չի գտնվել։", + "doesn't update itself": "ինքն իրեն չի թարմացնում", + "done": "պատրաստ է", + "downloading": "ներբեռնվում է", + "failed": "ձախողվեց", + "failed builds": "ձախողված կառուցումներ", + "failed containers": "ձախողված կոնտեյներներ", + "for that user": "այդ օգտատիրոջ համար", + "from any page": "ցանկացած էջից", + "from the container's log": "կոնտեյների մատյանից", + "from the engine, when it tried to start it": "շարժիչից, երբ այն փորձեց գործարկել", + "from the engine, when it tried to start {name}": "շարժիչից՝ {name} գործարկելու փորձի ժամանակ", + "idle": "անգործ", + "idle · nobody is visiting": "անգործ · այցելուներ չկան", + "image ID": "պատկերի ID", + "images": "պատկերներ", + "in": "մուտք", + "in config.json": "config.json-ում", + "in progress": "ընթացքում է", + "in {time}": "{time} հետո", + "input events": "մուտքի իրադարձություններ", + "installed": "տեղադրված է", + "its build cache": "դրա կառուցման քեշը", + "just now": "հենց նոր", + "kept in {v}": "պահվում է՝ {v}", + "kernel {version}": "միջուկ {version}", + "kiri.service and the engine are in place": "kiri.service-ը և շարժիչը տեղում են", + "kubectl context": "kubectl համատեքստ", + "latest": "վերջինը", + "layers": "շերտեր", + "line {n}": "տող {n}", + "links open in this app": "բաց հղումներ այս հավելվածում", + "live": "ակտիվ", + "live {time}": "ակտիվ է {time}", + "macOS will ask for an administrator password next.": "Հաջորդիվ macOS-ը կխնդրի ադմինիստրատորի գաղտնաբառը։", + "made {ago}": "ստեղծվել է {ago}", + "move": "շարժվել", + "needs privileged mode": "պահանջում է արտոնյալ ռեժիմ", + "needs {name}": "պահանջում է {name} փոփոխականը", + "network interface": "ցանցային ինտերֆեյս", + "networks": "ցանցեր", + "no layer: this line only changes the image's settings": "առանց շերտի՝ այս տողը փոխում է միայն պատկերի կարգավորումները", + "no monthly cap": "առանց ամսական սահմանաչափի", + "no speed limit": "առանց արագության սահմանափակման", + "none": "չկա", + "not in use": "չի օգտագործվում", + "not running": "չի աշխատում", + "now": "հիմա", + "of all {cpus} CPUs · peak {peak}": "բոլոր {cpus} պրոցեսորից · գագաթնակետ {peak}", + "of {cap}": "/ {cap}", + "of {limit} · peak {peak}": "սահմանաչափ՝ {limit} · գագաթնակետ {peak}", + "on other computers": "այլ համակարգիչներում", + "on {date} at {time}": "{date}, ժամը {time}", + "or hold {mod} and scroll": "կամ սեղմած պահեք {mod} ստեղնը և ոլորեք", + "out": "ելք", + "owner/image on {registry}, such as {example}": "owner/image {registry} ռեեստրում, օրինակ՝ {example}", + "peak {rate}": "գագաթնակետ {rate}", + "pinned digest": "ամրագրված digest", + "pods": "pod-եր", + "port {port}": "պորտ {port}", + "port {port} is in use": "{port} պորտը զբաղված է", + "pull": "ներբեռնել", + "pulled {when}": "ներբեռնվել է {when}", + "pulling alpine": "alpine-ը ներբեռնվում է", + "pulls now": "կներբեռնվի հիմա", + "raw HID": "անմիջական HID", + "raw USB": "անմիջական USB", + "received from visitors": "ստացված այցելուներից", + "reconnected {n}×": "վերամիացումներ՝ {n}×", + "report ID": "հաշվետվության ID", + "running on other computers on your account": "աշխատում են ձեր հաշվի այլ համակարգիչներում", + "running…": "աշխատում է…", + "same as the user": "նույնը, ինչ օգտատիրոջը", + "saved with {v}": "պահպանված է՝ {v}", + "sent to visitors": "ուղարկված այցելուներին", + "serial port": "սերիական պորտ", + "services": "ծառայություններ", + "sets {var}, for local use only.": "սահմանում է {var}, միայն տեղային օգտագործման համար։", + "sets {var}, so it runs without a login or TLS.": "սահմանում է {var}, ուստի այն աշխատում է առանց մուտքի և TLS-ի։", + "sets {var}; it prints the password once in its log.": "սահմանում է {var}։ Այն մեկ անգամ կտպի գաղտնաբառն իր մատյանում։", + "settings": "կարգավորումներ", + "sign in to {host}": "մուտք գործեք՝ {host}", + "skipped": "բաց թողնված", + "sound card": "ձայնային քարտ", + "tag": "պիտակ", + "the image's settings": "պատկերի կարգավորումները", + "the last error lines in the container's log": "կոնտեյների մատյանի սխալներով վերջին տողերը", + "the last lines in the container's log": "կոնտեյների մատյանի վերջին տողերը", + "the link didn't open": "հղումը չբացվեց", + "the only web port": "միակ վեբ պորտը", + "the port the app in it listens on": "պորտը, որին լսում է ներսի հավելվածը", + "the saved sign-in": "պահպանված մուտքը", + "the test container did not run": "փորձնական կոնտեյները չաշխատեց", + "the test container did not run: {why}": "փորձնական կոնտեյները չաշխատեց՝ {why}", + "this Mac": "այս Mac-ը", + "this PC": "այս համակարգիչը", + "this build": "այս կառուցումը", + "this image": "այս պատկերը", + "to do": "սպասում է", + "today at {time}": "այսօր, ժամը {time}", + "total ↓ {rx} · ↑ {tx}": "ընդամենը ↓ {rx} · ↑ {tx}", + "tunnels in use": "զբաղված թունելներ", + "untagged": "առանց պիտակի", + "untagged images": "առանց պիտակի պատկերներ", + "up": "աշխատում է", + "up to {size}": "մինչև {size}", + "up {time}": "աշխատում է {time}", + "usbipd-win is installed": "usbipd-win-ը տեղադրված է", + "used by {names}": "օգտագործում են՝ {names}", + "value": "արժեք", + "video": "տեսասարք", + "volumes": "հատորներ", + "when the VM's {mem} ran out.": "երբ վիրտուալ մեքենայի {mem} հիշողությունը սպառվեց։", + "yesterday": "երեկ", + "yesterday at {time}": "երեկ, ժամը {time}", + "you": "դուք", + "your account": "ձեր հաշիվը", + "your other Docker": "ձեր մյուս Docker-ը", + "{all} lines": "{all} տող", + "{app} doesn't update itself: rebuild it with cargo xtask app-dev": "{app} հավելվածն ինքն իրեն չի թարմացնում՝ վերակառուցեք այն cargo xtask app-dev հրամանով", + "{app} needs a password to start": "Գործարկվելու համար {app} հավելվածին պետք է գաղտնաբառ", + "{app} needs an admin password to start": "Գործարկվելու համար {app} հավելվածին պետք է ադմինիստրատորի գաղտնաբառ", + "{app}: its own engine, containers and settings": "{app}: սեփական շարժիչ, կոնտեյներներ և կարգավորումներ", + "{build} and {compose} run on Kiri, and the images are in Kiri, whichever engine docker uses.": "{build} և {compose} հրամաններն աշխատում են Kiri-ում, և պատկերները Kiri-ում են՝ անկախ նրանից, թե docker-ն ինչ շարժիչ է օգտագործում։", + "{build} and {compose} run on Kiri, and the images are in Kiri. {engine} won't see them; run them with Kiri.": "{build} և {compose} հրամաններն աշխատում են Kiri-ում, և պատկերները Kiri-ում են։ {engine} շարժիչը դրանք չի տեսնի։ Գործարկեք դրանք Kiri-ով։", + "{build} builds wherever docker points, so {engine}'s builds stay in {engine}. When docker uses Kiri, builds run on Kiri.": "{build} հրամանը կառուցում է այնտեղ, ուր ուղղված է docker-ը, ուստի {engine} շարժիչի կառուցումները մնում են {engine} շարժիչում։ Երբ docker-ն օգտագործում է Kiri-ն, կառուցումներն աշխատում են Kiri-ում։", + "{build} builds wherever docker points. When docker uses Kiri, builds run on Kiri.": "{build} հրամանը կառուցում է այնտեղ, ուր ուղղված է docker-ը։ Երբ docker-ն օգտագործում է Kiri-ն, կառուցումներն աշխատում են Kiri-ում։", + "{cmd} always builds on Kiri. A switch applies at once, in terminals already open too. Switching back to Docker puts docker's build settings back as they were before Kiri changed them.": "{cmd} հրամանը միշտ կառուցում է Kiri-ում։ Փոխարկումը գործում է անմիջապես, նաև արդեն բաց տերմինալներում։ Docker-ին վերադառնալիս docker-ի կառուցման կարգավորումները վերականգնվում են այնպես, ինչպես էին մինչև Kiri-ի փոփոխությունները։", + "{docker}, {compose} and your tools run on {app} from now on.": "Այսուհետ {docker}, {compose} հրամանները և ձեր գործիքներն աշխատում են {app} հավելվածով։", + "{done} of {total}": "{done} / {total}", + "{engine} doesn't see them.": "{engine} շարժիչը դրանք չի տեսնում։", + "{file} ({i} of {n})": "{file} ({i} / {n})", + "{free} free of {total}": "ազատ՝ {free} / {total}", + "{got} of {total}": "{got} / {total}", + "{got} of {total} MB": "{got} / {total} ՄԲ", + "{host} isn't searchable from here, so Kiri pulls the reference as typed.": "Այստեղից հնարավոր չէ որոնել {host} ռեեստրում, ուստի Kiri-ն ներբեռնում է պատկերի հղումն այնպես, ինչպես մուտքագրված է։", + "{host} port {q}{port}{q} is not a port number (1–65535).": "{host} համակարգչի {q}{port}{q} պորտը վավեր պորտի համար չէ (1–65535)։", + "{host} wants a sign-in for {path}, and {user} can't pull it.": "{host} ռեեստրը մուտք է պահանջում {path} պահոցի համար, իսկ {user} օգտատերը չի կարող այն ներբեռնել։", + "{host} wants a sign-in for {path}.": "{host} ռեեստրը մուտք է պահանջում {path} պահոցի համար։", + "{h} h": "{h} ժ", + "{h} h {m} min": "{h} ժ {m} ր", + "{image} is a whole Kubernetes cluster in a container.": "{image} պատկերը մեկ կոնտեյների մեջ տեղավորված ամբողջական Kubernetes կլաստեր է։", + "{image} needs {what} to start": "{image} պատկերը գործարկելու համար անհրաժեշտ է՝ {what}", + "{k8s} is Kiri's Kubernetes cluster. Removing it turns Kubernetes off. The cluster's data stays in the {k8s} volume; Delete cluster in Settings → Kubernetes removes everything.": "{k8s} կոնտեյները Kiri-ի Kubernetes կլաստերն է։ Այն հեռացնելիս Kubernetes-ն անջատվում է։ Կլաստերի տվյալները մնում են {k8s} հատորում։ Ամեն ինչ հեռացնում է «Ջնջել կլաստերը» կոճակը՝ Կարգավորումներ → Kubernetes բաժնում։", + "{k8s} is Kiri's Kubernetes cluster. Stopping it turns Kubernetes off, and its pods stop until it starts again.": "{k8s} կոնտեյները Kiri-ի Kubernetes կլաստերն է։ Այն կանգնեցնելիս Kubernetes-ն անջատվում է, և նրա pod-երը կանգ են առնում, մինչև այն նորից գործարկվի։", + "{kind} names are off: port {port} is in use. Pick another.": "{kind} անուններն անջատված են՝ {port} պորտը զբաղված է։ Ընտրեք մեկ այլ պորտ։", + "{kind} names are paused: a container has port {port}.": "{kind} անունները դադարեցված են՝ {port} պորտը զբաղեցրել է կոնտեյներներից մեկը։", + "{label}, last minute": "{label}, վերջին րոպե", + "{list} and {last}": "{list} և {last}", + "{list} are running from this image. Stop them first, then remove the image.": "Այս պատկերից աշխատում են՝ {list}։ Նախ կանգնեցրեք դրանք, ապա հեռացրեք պատկերը։", + "{list} is running from this image. Stop it first, then remove the image.": "Այս պատկերից աշխատում է՝ {list}։ Նախ կանգնեցրեք այն, ապա հեռացրեք պատկերը։", + "{list} was made from this image and can't start again without it, so it goes too, with its files. Volumes stay.": "{list} կոնտեյները ստեղծվել է այս պատկերից և առանց դրա չի կարող նորից գործարկվել, ուստի այն նույնպես կհեռացվի իր ֆայլերով։ Հատորները կմնան։", + "{list} were made from this image and can't start again without it, so they go too, with their files. Volumes stay.": "{list} կոնտեյներները ստեղծվել են այս պատկերից և առանց դրա չեն կարող նորից գործարկվել, ուստի դրանք նույնպես կհեռացվեն իրենց ֆայլերով։ Հատորները կմնան։", + "{list}, and {last}": "{list} և {last}", + "{live} for {time}": "{live}՝ {time}", + "{live} live, {starting} starting": "ակտիվ՝ {live}, գործարկվում է՝ {starting}", + "{local} names and HTTPS aren't on Linux yet.": "{local} անուններն ու HTTPS-ը Linux-ում դեռ հասանելի չեն։", + "{ms} average": "միջինը՝ {ms}", + "{m} min": "{m} ր", + "{m} of the {n} picked": "ընտրված {n} տարրից՝ {m}", + "{m} of the {n} picked can't be deleted and stay.": "Ընտրված {n} տարրից {m} տարր հնարավոր չէ ջնջել, և դրանք կմնան։", + "{names} on {host}": "{names}՝ {host}", + "{name} didn't start": "{name} չգործարկվեց", + "{name} has no tag {tag}.": "{name} պատկերը {tag} պիտակ չունի։", + "{name} has the new environment": "{name} կոնտեյներն այժմ նոր միջավայրով է", + "{name} is in Kiri": "{name} սարքը Kiri-ում է", + "{name} is in use": "{name} օգտագործվում է", + "{name} is listening on {ports}": "{name} լսում է՝ {ports}", + "{name} is shared": "{name} հասանելի է հղումով", + "{name} is shared by {who}": "{name} հասանելի է հղումով, կիսել է՝ {who}", + "{name} is still used by the container {container}. Remove the container first.": "{name} դեռ օգտագործվում է {container} կոնտեյների կողմից։ Նախ հեռացրեք կոնտեյները։", + "{name} isn't changed: images are copied, and volumes are read through a temporary read-only helper that's removed after. Containers arrive stopped.": "{name} չի փոփոխվում՝ պատկերները պատճենվում են, իսկ հատորները կարդացվում են ժամանակավոր, միայն կարդալու համար նախատեսված օգնական կոնտեյների միջոցով, որը հետո հեռացվում է։ Կոնտեյներները տեղափոխվում են կանգնեցված վիճակում։", + "{name} isn't listening on a port yet, so there's nothing to share. Try again once it's up.": "{name} դեռ ոչ մի պորտ չի լսում, ուստի կիսվելու բան չկա։ Կրկին փորձեք, երբ այն գործարկվի։", + "{name} isn't running. Start it to import from it; it doesn't need to stay open afterwards.": "{name} չի աշխատում։ Գործարկեք այն՝ դրանից ներմուծելու համար։ Դրանից հետո այն բաց պահելու կարիք չկա։", + "{name} needs {var} to start": "{name} կոնտեյները գործարկելու համար անհրաժեշտ է {var} փոփոխականը", + "{name} ran and finished": "{name} աշխատեց և ավարտվեց", + "{name} ran out of memory": "{name}՝ հիշողությունը սպառվեց", + "{name} restarted with the new environment": "{name} վերագործարկվեց նոր միջավայրով", + "{name} stays as it is: Kiri only copies. Containers arrive stopped.": "{name} մնում է անփոփոխ՝ Kiri-ն միայն պատճենում է։ Կոնտեյներները տեղափոխվում են կանգնեցված վիճակում։", + "{name} stays: Kubernetes is turned off or deleted in Settings → Kubernetes.": "{name} մնում է՝ Kubernetes-ն անջատվում կամ ջնջվում է Կարգավորումներ → Kubernetes բաժնում։", + "{name} stopped": "{name} կանգ առավ", + "{name} stopped after {n} s": "{name} կանգ առավ {n} վ անց", + "{name} stopped after {n} second": "{name} կանգ առավ {n} վայրկյան անց", + "{name} stopped after {n} seconds": "{name} կանգ առավ {n} վայրկյան անց", + "{name} stopped: {why}": "{name} կանգ առավ՝ {why}", + "{n} CPU": "{n} պրոցեսոր", + "{n} CPUs": "{n} պրոցեսոր", + "{n} added": "ավելացվել է՝ {n}", + "{n} cached": "քեշից՝ {n}", + "{n} change": "{n} փոփոխություն", + "{n} changed": "փոփոխվել է՝ {n}", + "{n} changes": "{n} փոփոխություն", + "{n} container": "{n} կոնտեյներ", + "{n} containers": "{n} կոնտեյներ", + "{n} d ago": "{n} օր առաջ", + "{n} days ago": "{n} օր առաջ", + "{n} device": "{n} սարք", + "{n} devices": "{n} սարք", + "{n} error": "{n} սխալ", + "{n} errors": "{n} սխալ", + "{n} external": "արտաքին՝ {n}", + "{n} failed container": "{n} ձախողված կոնտեյներ", + "{n} failed containers": "{n} ձախողված կոնտեյներ", + "{n} from {what}": "{what}: {n}", + "{n} h ago": "{n} ժ առաջ", + "{n} image": "{n} պատկեր", + "{n} image, {size}.": "{n} պատկեր, {size}։", + "{n} image.": "{n} պատկեր։", + "{n} images": "{n} պատկեր", + "{n} images, {size}.": "{n} պատկեր, {size}։", + "{n} images.": "{n} պատկեր։", + "{n} in Kiri": "Kiri-ում՝ {n}", + "{n} item isn't in Kiri yet. Pick what to copy over.": "Kiri-ում դեռ չկա {n} տարր։ Ընտրեք, թե ինչը տեղափոխել։", + "{n} items aren't in Kiri yet. Pick what to copy over.": "Kiri-ում դեռ չկա {n} տարր։ Ընտրեք, թե ինչը տեղափոխել։", + "{n} layer": "{n} շերտ", + "{n} layers": "{n} շերտ", + "{n} line": "{n} տող", + "{n} lines": "{n} տող", + "{n} live": "ակտիվ՝ {n}", + "{n} log line": "մատյանի {n} տող", + "{n} log line from the {parts}": "մատյանի {n} տող ({parts})", + "{n} log lines": "մատյանի {n} տող", + "{n} log lines from the {parts}": "մատյանի {n} տող ({parts})", + "{n} min ago": "{n} ր առաջ", + "{n} of this image, newest first": "այս պատկերի {n} սկանավորում, նորերը՝ սկզբում", + "{n} of {limit} tunnels in use": "օգտագործվում է {n} / {limit} թունել", + "{n} of {total}": "{n} / {total}", + "{n} of {total} running": "աշխատում է՝ {n} / {total}", + "{n} on {where}": "{where}: {n}", + "{n} optional": "ոչ պարտադիր՝ {n}", + "{n} processes": "{n} պրոցես", + "{n} removed": "հեռացվել է՝ {n}", + "{n} request": "{n} հարցում", + "{n} requests": "{n} հարցում", + "{n} requests · {size} served": "{n} հարցում · փոխանցվել է {size}", + "{n} result": "{n} արդյունք", + "{n} results": "{n} արդյունք", + "{n} running container": "{n} աշխատող կոնտեյներ", + "{n} running containers": "{n} աշխատող կոնտեյներ", + "{n} selected": "ընտրված է՝ {n}", + "{n} shared": "կիսված՝ {n}", + "{n} shared · {where}": "կիսված՝ {n} · {where}", + "{n} shared, on {where}": "կիսված՝ {n}, {where}", + "{n} shared, {where}": "կիսված՝ {n}, {where}", + "{n} shown": "ցուցադրված է՝ {n}", + "{n} stopped container": "{n} կանգնեցված կոնտեյներ", + "{n} stopped containers": "{n} կանգնեցված կոնտեյներ", + "{n} total": "ընդամենը՝ {n}", + "{n} variable": "{n} փոփոխական", + "{n} variables": "{n} փոփոխական", + "{n} volume": "{n} հատոր", + "{n} volumes": "{n} հատոր", + "{n} vulnerabilities in {packages} packages": "{n} խոցելիություն {packages} փաթեթում", + "{n} vulnerability in {packages} packages": "{n} խոցելիություն {packages} փաթեթում", + "{n} with a fix": "շտկումով՝ {n}", + "{n} {noun}": "{n} {noun}", + "{n}s ago": "{n} վ առաջ", + "{os} settings": "{os} կարգավորումներ", + "{os} uses an automatic proxy configuration (PAC) file, which Kiri can't follow. Choose Custom and enter the proxy.": "{os} համակարգն օգտագործում է պրոքսիի ավտոմատ կարգավորման (PAC) ֆայլ, որը Kiri-ն չի կարող կիրառել։ Ընտրեք «Անհատական» և նշեք պրոքսին։", + "{owner} runs this pod": "Այս pod-ը գործարկում է՝ {owner}", + "{parts}. Not listed in Images or Volumes: it's docker build's machinery.": "{parts}։ Չի ցուցադրվում «Պատկերներ» և «Հատորներ» բաժիններում՝ դա docker build-ի ներքին մեխանիզմն է։", + "{path} comes first on your PATH, so terminals run it instead of this Kiri. If it's an older Kiri, remove it: rm {path}": "{path} ֆայլը ձեր PATH-ում առաջինն է, ուստի տերմինալները գործարկում են այն՝ այս Kiri-ի փոխարեն։ Եթե դա Kiri-ի հին տարբերակ է, հեռացրեք այն՝ rm {path}", + "{pct}% of this month's cap": "ամսական սահմանաչափի {pct}%", + "{ports} aren't web ports, so they aren't listed.": "{ports} պորտերը վեբ պորտեր չեն, ուստի ցուցակում չեն։", + "{ports} isn't a web port, so it isn't listed.": "{ports} պորտը վեբ պորտ չէ, ուստի ցուցակում չէ։", + "{program} on {host}": "{program}՝ {host}", + "{q}{name}{q} can't be a name: names have no spaces or {q}={q}.": "{q}{name}{q} չի կարող անուն լինել՝ անունները չեն կարող պարունակել բացատներ կամ {q}={q}։", + "{rate} limit": "սահմանաչափ՝ {rate}", + "{rate}/s limit": "սահմանաչափ՝ {rate}/վ", + "{ready} containers": "{ready} կոնտեյներ", + "{running} of {all} running": "աշխատում է՝ {running} / {all}", + "{running} running · {total}": "աշխատում է՝ {running} · {total}", + "{showing} of {all} lines": "{showing} / {all} տող", + "{size} MB in {secs} s": "{size} ՄԲ՝ {secs} վայրկյանում", + "{size} MB · already here": "{size} ՄԲ · արդեն առկա է", + "{size} is Ubuntu's download today.": "Ubuntu-ի ներբեռնման չափն այսօր {size} է։", + "{size} left": "մնացել է՝ {size}", + "{size} left this month": "այս ամիս մնացել է՝ {size}", + "{size} received": "ստացվել է՝ {size}", + "{size} served": "փոխանցվել է՝ {size}", + "{s} s": "{s} վ", + "{text} with an error.": "{text}՝ սխալով։", + "{time} ago": "{time} առաջ", + "{time} ago, when the VM's {mem} ran out.": "{time} առաջ, երբ սպառվեց վիրտուալ մեքենայի {mem} հիշողությունը։", + "{used} of {total}": "{used} / {total}", + "{user} can run containers without sudo": "{user} օգտատերը կարող է կոնտեյներներ գործարկել առանց sudo-ի", + "{user}'s sign-in is forgotten on this computer.": "{user} հաշվի մուտքի տվյալներն այս համակարգչում մոռացվել են։", + "{var} sets the {kind} port, so it can't be changed here.": "{var} փոփոխականը սահմանում է {kind} պորտը, ուստի այն այստեղ հնարավոր չէ փոխել։", + "{version} available": "Հասանելի է {version} տարբերակը", + "{version} ready": "{version} տարբերակը պատրաստ է", + "{vm} off": "{vm}: անջատված", + "{vm} running": "{vm}: աշխատում է", + "{what}?": "Հաստատե՞լ՝ {what}", + "{who} has it. Give {name} another port on this {host}, or stop {holder} first.": "Պորտը զբաղեցրել է՝ {who}։ Ընտրեք այլ պորտ {name} կոնտեյների համար այս {host} համակարգչում կամ նախ կանգնեցրեք՝ {holder}։", + "{who} stopped {when}.{more} A report helps us fix it: the stack trace and the last 200 log lines before it, with your home folder and tokens blanked.": "{who}՝ խափանվեց {when}։{more} Հաշվետվությունը կօգնի մեզ շտկել այն՝ կանչերի ստեկը և դրանից առաջ մատյանի վերջին 200 տողը, առանց ձեր տնային թղթապանակի ուղու և թոքենների։", + "{who} stopped {when}.{more} Crash reports are sent automatically, so this one goes to Kiri too.": "{who}՝ խափանվեց {when}։{more} Խափանումների հաշվետվություններն ուղարկվում են ավտոմատ, ուստի այս մեկը նույնպես կուղարկվի Kiri-ին։", + "{why}. Give the VM more memory in Settings → Resources": "{why}։ Վիրտուալ մեքենային ավելի շատ հիշողություն տրամադրեք Կարգավորումներ → Ռեսուրսներ բաժնում", + "{zout} smaller · {zin} bigger · {z0} reset": "{zout} փոքրացնել · {zin} մեծացնել · {z0} վերակայել", + "· the newest 500 · up to 15 MB a part is kept": "· պահվում են վերջին 500-ը · յուրաքանչյուր մասից մինչև 15 ՄԲ", + "– About {ratio}× the download of Kiri Linux": "– Ներբեռնումը մոտ {ratio}× ավելի մեծ է, քան Kiri Linux-ինը", + "– Kiri shares it with your own Linux work": "– Kiri-ն այն կիսում է ձեր սեփական Linux աշխատանքի հետ", + "– Not a Linux to use yourself": "– Սա Linux չէ անձնական օգտագործման համար", + "— the end of the run before the last restart —": "— վերջին վերագործարկումից առաջվա աշխատանքի ավարտը —", + "— the log stream ended —": "— մատյանի հոսքն ավարտվեց —", + "‹ Back": "‹ Հետ", + "★ Star on GitHub": "★ Աստղ տալ GitHub-ում", + "✓ Installed": "✓ Տեղադրված է", + "Waiting to come back": "Սպասում է վերադարձին", + "Stop waiting": "Դադարեցնել սպասումը", + "Kiri attaches it again when it's back. Stop waiting to leave it on this computer.": "Kiri-ն նորից կմիացնի այն, երբ այն վերադառնա։ Սեղմեք «Դադարեցնել սպասումը»՝ այն այս համակարգչում թողնելու համար։", + "Fit the whole project": "Տեղավորել ամբողջ նախագիծը", + "Find a service": "Գտնել ծառայություն", + "docker compose up failed": "docker compose up հրամանը ձախողվեց", + "Not applied": "Կիրառված չէ", + "Saved, but the file has an error": "Պահպանված է, բայց ֆայլում սխալ կա", + "Your edits stay here. Apply waits until the file is back.": "Ձեր խմբագրումները մնում են այստեղ։ Կիրառումը սպասում է ֆայլի վերադարձին։", + "build": "կառուցում", + "Queue": "Հերթ", + "The file changed outside Kiri since Apply saved it": "Ֆայլը փոփոխվել է Kiri-ից դուրս՝ պահպանվելուց հետո", + "Couldn't apply {name}: {error}": "Չհաջողվեց կիրառել՝ {name}։ {error}", + "Saved, not started yet": "Պահպանված է, դեռ գործարկված չէ", + "image": "պատկեր", + "Overwrite their changes": "Վերագրանցել այդ փոփոխությունները", + "Recreating…": "Վերաստեղծվում է…", + "Service": "Ծառայություն", + "{n} need it": "անհրաժեշտ է {n} ծառայության", + "CHANGES": "ՓՈՓՈԽՎԱԾ", + "Applied {name}": "Կիրառվեց՝ {name}", + "Overwrite": "Վերագրանցել", + "Restarting": "Վերագործարկվում է", + "depends on": "կախված է", + "{svc} stopped after Apply": "Կիրառումից հետո կանգ առավ՝ {svc}", + "Apply cancelled. {svc} had already changed; the rest were not changed.": "Կիրառումը չեղարկվեց։ Արդեն փոփոխվել էր՝ {svc}, իսկ մնացածը մնացին անփոփոխ։", + "Fix the file first.": "Նախ ուղղեք ֆայլը։", + "Open a compose file": "Բացել Compose ֆայլ", + "Worker": "Աշխատող", + "Saved {name}, not applied: {error}": "Պահպանվեց՝ {name}, բայց չկիրառվեց՝ {error}", + "Show in file": "Ցույց տալ ֆայլում", + "needs {n}": "պահանջում է՝ {n}", + "Apply cancelled. No service was changed.": "Կիրառումը չեղարկվեց։ Ոչ մի ծառայություն չի փոփոխվել։", + "Arrows point at what a service needs; Compose starts those first.": "Սլաքները ցույց են տալիս, թե ինչ է պետք ծառայությանը. Compose-ը նախ գործարկում է դրանք։", + "Starts on line {n} · click to jump there": "Սկսվում է տող {n}-ից · սեղմեք՝ անցնելու համար", + "Not in the file any more: stopped and removed. Its volumes stay.": "Այլևս ֆայլում չկա. կանգնեցվել և հեռացվել է։ Դրա հատորները մնում են։", + "the file changed outside Kiri": "ֆայլը փոփոխվել է Kiri-ից դուրս", + "Overwrite their changes?": "Վերագրանցե՞լ այդ փոփոխությունները։", + "No Compose projects yet": "Compose նախագծեր դեռ չկան", + "Saved, not applied": "Պահպանված է, չի կիրառվել", + "New service, built from its folder.": "Նոր ծառայություն՝ կառուցված իր թղթապանակից։", + "The compose file isn't on this computer: {error}": "Compose ֆայլն այս համակարգչում չէ՝ {error}", + "Saved, matches what runs": "Պահպանված է, համընկնում է աշխատողի հետ", + "Line {n}.": "Տող {n}։", + "{name} is already being applied. Wait for it to finish, or cancel it.": "Արդեն կիրառվում է՝ {name}։ Սպասեք ավարտին կամ չեղարկեք այն։", + "{n} recreated": "վերաստեղծվել է՝ {n}", + "Zoom out": "Փոքրացնել", + "That project is gone": "Այդ նախագիծն այլևս չկա", + "Couldn't run docker compose: {error}": "Չհաջողվեց գործարկել docker compose-ը՝ {error}", + "No logs yet.": "Մատյաններ դեռ չկան։", + "A project named {name} already runs from {dir}. Open that one, or give this file its own name: line.": "{name} անունով նախագիծն արդեն աշխատում է {dir} թղթապանակից։ Բացեք այն կամ այս ֆայլին տվեք սեփական name: տողը։", + "{n} needs it": "անհրաժեշտ է {n} ծառայության", + "File": "Ֆայլ", + "Kiri can't show the plan with {name} hidden. {apply} will run docker compose up.": "Kiri-ն չի կարող ցույց տալ պլանը, երբ թաքցված է՝ {name}։ «{apply}» կոճակը կգործարկի docker compose up։", + "REMOVED": "ՀԵՌԱՑՎԱԾ", + "The file changed outside Kiri. Apply writes your edits over it, and those changes are lost.": "Ֆայլը փոփոխվել է Kiri-ից դուրս։ Կիրառումը կգրի ձեր խմբագրումները դրա վրա, և այդ փոփոխությունները կկորչեն։", + "The other Apply of {name} finished. Your edit isn't applied yet.": "Մյուս կիրառումն ավարտվեց ({name})։ Ձեր խմբագրումը դեռ կիրառված չէ։", + "The file changed outside Kiri.": "Ֆայլը փոփոխվել է Kiri-ից դուրս։", + "Kiri can't check this file with {name} hidden. Compose accepts it, so Apply still works.": "Kiri-ն չի կարող ստուգել այս ֆայլը, երբ թաքցված է՝ {name}։ Compose-ն ընդունում է այն, ուստի «Կիրառել»-ը գործում է։", + "Compose rejects this file with its real values. Kiri can't show why with secrets hidden.": "Compose-ը մերժում է այս ֆայլը իրական արժեքներով։ Kiri-ն չի կարող ցույց տալ պատճառը, քանի դեռ գաղտնիքները թաքցված են։", + "docker compose took longer than {secs} seconds": "docker compose-ը տևեց ավելի քան {secs} վայրկյան", + "Discard": "Չեղարկել", + "Refresh": "Թարմացնել", + "Names Docker shows may contain secret values.": "Docker-ի ցուցադրած անունները կարող են պարունակել գաղտնի արժեքներ։", + "a newer image": "ավելի նոր պատկեր", + "docker compose up stopped": "docker compose up-ը կանգ առավ", + "Applying…": "Կիրառվում է…", + "Cache": "Քեշ", + "New service from {image}.": "Նոր ծառայություն՝ {image} պատկերից։", + "{n} new": "նոր՝ {n}", + "Apply cancelled. {n} services had already changed; the rest were not changed.": "Կիրառումը չեղարկվեց։ {n} ծառայություն արդեն փոփոխվել էր, իսկ մնացածը մնացին անփոփոխ։", + "Compose rejects this file: YAML error on line {n}": "Compose-ը մերժում է այս ֆայլը. YAML սխալ՝ տող {n}", + "Saved, not applied: {error}": "Պահպանված է, չի կիրառվել՝ {error}", + "Kiri has no state folder": "Kiri-ն չունի վիճակի թղթապանակ", + "{n} services": "{n} ծառայություն", + "Reload (lose your edits)": "Վերաբեռնել (կորցնել խմբագրումները)", + "Not started": "Չի գործարկվել", + "Couldn't open the compose file: {error}": "Չհաջողվեց բացել Compose ֆայլը՝ {error}", + "Projects you start with {cmd} show up here once they have run on Kiri.": "{cmd} հրամանով գործարկված նախագծերը հայտնվում են այստեղ Kiri-ում աշխատելուց հետո։", + "Saved": "Պահպանված է", + "a variable it uses changed": "օգտագործվող փոփոխականը փոխվել է", + "Not created": "Ստեղծված չէ", + "Saves the file, then runs {cmd}. Unchanged services keep running.": "Պահպանում է ֆայլը, ապա գործարկում {cmd}։ Անփոփոխ ծառայությունները շարունակում են աշխատել։", + "NEW": "ՆՈՐ", + "needs {list}": "պահանջում է՝ {list}", + "Removing…": "Հեռացվում է…", + "Creating…": "Ստեղծվում է…", + "Metrics": "Չափանիշներ", + "Apply cancelled": "Կիրառումը չեղարկվեց", + "The compose file is gone from its folder.": "Compose ֆայլն այլևս իր թղթապանակում չէ։", + "Zoom in": "Մեծացնել", + "The image name from {name} isn't valid": "{name} փոփոխականի պատկերի անունը վավեր չէ", + "Kiri can't show this service's details with its secrets hidden": "Kiri-ն չի կարող ցույց տալ այս ծառայության մանրամասները, քանի դեռ գաղտնիքները թաքցված են", + "The file changed outside Kiri": "Ֆայլը փոփոխվել է Kiri-ից դուրս", + "Recreate": "Վերաստեղծել", + "Applied {name}, but {svc} stopped": "Կիրառվեց՝ {name}, բայց կանգ առավ՝ {svc}", + "Web": "Վեբ", + "See its logs": "Դիտել մատյանները", + "Remove from the list": "Հեռացնել ցանկից", + "Compose rejects this file. A required variable may not be set: {name}.": "Compose-ը մերժում է այս ֆայլը։ Պարտադիր փոփոխականը կարող է սահմանված չլինել՝ {name}։", + "environment": "միջավայր", + "Search": "Որոնում", + "Couldn't save the compose file: {error}": "Չհաջողվեց պահպանել Compose ֆայլը՝ {error}", + "Compose files": "Compose ֆայլեր", + "Scheduler": "Պլանավորիչ", + "Kiri has nothing to put back": "Kiri-ն վերականգնելու ոչինչ չունի", + "Put back the file as it was before Apply saved over it": "Վերականգնել ֆայլը նախքան «Կիրառել»-ի պահպանումը եղած տեսքով", + "Kiri can't check this file's variables, so it manages this project by name. Apply changes from a terminal.": "Kiri-ն չի կարող ստուգել այս ֆայլի փոփոխականները, ուստի կառավարում է նախագիծն ըստ անվան։ Կիրառեք փոփոխությունները տերմինալից։", + "Edited, not applied": "Խմբագրված է, չի կիրառվել", + "This file isn't a compose file: it has no services": "Սա Compose ֆայլ չէ. ծառայություններ չունի", + "Kiri can't find the docker CLI. Restart Kiri to set it up again.": "Kiri-ն չի գտնում docker CLI-ն։ Վերագործարկեք Kiri-ն՝ այն նորից կարգավորելու համար։", + "Fit": "Տեղավորել", + "Compose rejects this file: YAML error in an included file, line {n}": "Compose-ը մերժում է այս ֆայլը. YAML սխալ ներառված ֆայլում՝ տող {n}", + "Open a compose file…": "Բացել Compose ֆայլ…", + "This file's name uses {vars}. Kiri uses the folder's name, {name}, so it never puts a secret in a name.": "Այս ֆայլի անունն օգտագործում է՝ {vars}։ Kiri-ն օգտագործում է թղթապանակի անունը ({name}), որպեսզի գաղտնիքը երբեք անվան մեջ չհայտնվի։", + "Kiri doesn't know that action": "Kiri-ին անծանոթ գործողություն է", + "Kiri can't find this project's compose file.": "Kiri-ն չի գտնում այս նախագծի Compose ֆայլը։", + "ports": "պորտեր", + "Newest container created {time}": "Ամենանոր կոնտեյները ստեղծվել է՝ {time}", + "Compose file": "Compose ֆայլ", + "Not started yet. Apply on the Compose file tab brings every service up.": "Դեռ գործարկված չէ։ «Compose ֆայլ» ներդիրի «Կիրառել» կոճակը կգործարկի բոլոր ծառայությունները։", + "Couldn't change {name}: {error}": "Չհաջողվեց փոխել՝ {name}։ {error}", + "{n} unchanged": "անփոփոխ՝ {n}", + "Create": "Ստեղծել", + "Structure": "Կառուցվածք", + "YAML files": "YAML ֆայլեր", + "{n} service": "{n} ծառայություն", + "{name} are used in a name or folder path. Docker shows those in plain text.": "{name} օգտագործվում են անվան կամ թղթապանակի ուղու մեջ։ Docker-ը դրանք ցուցադրում է բաց տեքստով։", + "Its logs, Start, Stop and Remove still work.": "Մատյանները, «Գործարկել», «Կանգնեցնել» և «Հեռացնել» գործողությունները շարունակում են աշխատել։", + "Showing the file as edited, not applied yet.": "Ցուցադրվում է խմբագրված ֆայլը, որը դեռ կիրառված չէ։", + "Nothing yet: the file matches what's running. Change it and this lists what happens to each service.": "Դեռ ոչինչ չկա. ֆայլը համընկնում է աշխատողի հետ։ Փոփոխեք այն, և այստեղ կցուցադրվի, թե ինչ կպատահի յուրաքանչյուր ծառայության հետ։", + "Kiri can't read the compose file: {error}": "Kiri-ն չի կարող կարդալ Compose ֆայլը՝ {error}", + "Pick a .yaml or .yml compose file": "Ընտրեք .yaml կամ .yml Compose ֆայլ", + "Applied {name}, but {svcs} stopped": "Կիրառվեց՝ {name}, բայց կանգ առան՝ {svcs}", + "Compose rejects this file: YAML error in {file}, line {n}": "Compose-ը մերժում է այս ֆայլը. YAML սխալ {file} ֆայլում՝ տող {n}", + "What Apply does": "Ինչ է անում «Կիրառել»-ը", + "Saved, but an included file has an error": "Պահպանված է, բայց ներառված ֆայլում սխալ կա", + "{name} is used in a name or folder path. Docker shows those in plain text.": "{name} օգտագործվում է անվան կամ թղթապանակի ուղու մեջ։ Docker-ը դրանք ցուցադրում է բաց տեքստով։", + "Apply": "Կիրառել", + "Couldn't read env file {file}: it isn't a local regular file": "Չհաջողվեց կարդալ env ֆայլը ({file}). այն տեղային սովորական ֆայլ չէ", + "Keep editing": "Շարունակել խմբագրել", + "The compose file is read-only, so Kiri can't save it. Make it writable, then Apply again.": "Compose ֆայլը միայն ընթերցման համար է, ուստի Kiri-ն չի կարող պահպանել այն։ Դարձրեք այն գրառելի, ապա նորից սեղմեք «Կիրառել»։", + "There's no Compose project {name} on Kiri": "Kiri-ում չկա Compose նախագիծ՝ {name}", + "The compose file is back, and differs from your edits.": "Compose ֆայլը վերադարձել է և տարբերվում է ձեր խմբագրումներից։", + "{n} more": "+{n} ևս", + "Unchanged": "Անփոփոխ", + "Saved, but line {n} has an error": "Պահպանված է, բայց տող {n}-ում սխալ կա", + "Actual size": "Իրական չափ", + "Show in compose file": "Ցույց տալ Compose ֆայլում", + "Open project": "Բացել նախագիծը", + "not started": "չի գործարկվել", + "Apply the compose file to create it": "Ստեղծելու համար կիրառեք Compose ֆայլը", + "Hide {name}'s containers": "Թաքցնել կոնտեյներները՝ {name}", + "Show {name}'s containers": "Ցույց տալ կոնտեյներները՝ {name}", + "Hide {name}'s pods": "Թաքցնել pod-երը՝ {name}", + "Show {name}'s pods": "Ցույց տալ pod-երը՝ {name}", + "{n} more in a Compose project": "Եվս {n}՝ Compose նախագծում", + "{n} more in Compose projects": "Եվս {n}՝ Compose նախագծերում", + "Your only container is in a Compose project": "Ձեր միակ կոնտեյները Compose նախագծում է", + "All {n} containers are in Compose projects": "Բոլոր {n} կոնտեյներները Compose նախագծերում են", + "Skipped until Kiri next opens": "Բաց է թողնված մինչև Kiri-ի հաջորդ բացումը", + "Couldn't add the kiri docker context": "Չհաջողվեց ավելացնել kiri docker համատեքստը", + "The kiri and docker commands": "kiri և docker հրամանները", + "Ready in any new terminal": "Պատրաստ է ցանկացած նոր տերմինալում", + "Couldn't add them to your shell": "Չհաջողվեց ավելացնել դրանք ձեր shell-ում", + "Starts at login": "Գործարկվում է մուտք գործելիս", + "The engine starts when you log in": "Շարժիչը գործարկվում է համակարգ մուտք գործելիս", + "The engine runs from the app for now": "Առայժմ շարժիչն աշխատում է հավելվածից", + "Show log": "Ցույց տալ մատյանը", + "Continue anyway": "Այնուամենայնիվ շարունակել", + "One step didn't work. Everything else is ready.": "Մեկ քայլ չաշխատեց։ Մնացած ամեն ինչ պատրաստ է։", + "Some steps didn't work. Everything else is ready.": "Որոշ քայլեր չաշխատեցին։ Մնացած ամեն ինչ պատրաստ է։", + "No matches": "Համընկնումներ չկան", + "Disk image size": "Սկավառակի պատկերի չափը", + "KIRI_CPUS, KIRI_MEMORY_MIB or KIRI_DISK_GB is set for the daemon, and it takes precedence over these.": "Դեմոնի համար սահմանված է KIRI_CPUS, KIRI_MEMORY_MIB կամ KIRI_DISK_GB, և այն գերակա է այս կարգավորումների նկատմամբ։", + "Running now with {cpus}, up to {mem}, and a {disk} disk.": "Այժմ աշխատում է՝ {cpus}, մինչև {mem} հիշողություն և {disk} սկավառակ։", + "No other WSL distros installed.": "Այլ WSL բաշխումներ տեղադրված չեն։", + "WSL integration": "WSL ինտեգրում", + "Close: the memory the window uses is freed. It takes a moment to open again, and open terminals end.": "Փակել. պատուհանի զբաղեցրած հիշողությունն ազատվում է։ Վերաբացումը մի պահ է տևում, իսկ բաց տերմինալները փակվում են։", + "Closing the window": "Պատուհանը փակելիս", + "Hide: the window stays ready and opens again at once.": "Թաքցնել. պատուհանը մնում է պատրաստ և անմիջապես նորից բացվում է։", + "Start Kiri at sign-in": "Գործարկել Kiri-ն մուտք գործելիս", + "Start Kiri in the background when you sign in.": "Համակարգ մուտք գործելիս գործարկում է Kiri-ն ֆոնային ռեժիմում։", + "Stop the engine when Kiri quits": "Կանգնեցնել շարժիչը Kiri-ից դուրս գալիս", + "Quitting Kiri stops running containers and the engine. Opening Kiri starts it again.": "Kiri-ից դուրս գալը կանգնեցնում է աշխատող կոնտեյներներն ու շարժիչը։ Kiri-ն բացելիս այն նորից գործարկվում է։", + "{env} is set, so docker uses another engine instead of {app}": "Սահմանված է {env}, ուստի docker-ն օգտագործում է այլ շարժիչ՝ {app} հավելվածի փոխարեն", + "{env} is set, so {docker} uses another engine instead of {app}. Unset it in your shell to use {app}.": "Սահմանված է {env}, ուստի {docker} հրամանն օգտագործում է այլ շարժիչ՝ {app} հավելվածի փոխարեն։ Հեռացրեք այն shell-ից՝ {app} օգտագործելու համար։", + "{env} is set": "{env} սահմանված է", + "{env} overrides docker's context in this session, so switching context won't move {docker} to {app}. Clear it with {cmd} or remove it from your profile.": "Այս սեսիայում {env} փոփոխականը գերակայում է docker-ի համատեքստին, ուստի համատեքստը փոխելը չի ուղղի {docker} հրամանը դեպի {app}։ Մաքրեք այն {cmd} հրամանով կամ հեռացրեք պրոֆիլից։", + "{path} leads to {app}. Tools like Testcontainers, IDE plugins and SDKs use it directly.": "{path} ուղին տանում է դեպի {app}։ Testcontainers-ը, IDE հավելումները և SDK-ներն օգտագործում են այն ուղղակիորեն։", + "another engine": "այլ շարժիչ", + "{path} belongs to {engine} and stays so.": "{path} ուղին պատկանում է այլ շարժիչի ({engine}) և մնում է անփոփոխ։", + "Tools that ignore docker contexts can use {hint}": "docker համատեքստերն անտեսող գործիքները կարող են օգտագործել՝ {hint}", + "command": "հրաման", + "{path} is free. Link it to {app} so tools that ignore docker contexts find {app} there.": "{path} ուղին ազատ է։ Կապեք այն {app} հավելվածին, որպեսզի docker համատեքստերն անտեսող գործիքներն այնտեղ գտնեն {app}։", + "{path} is free. {app} serves it whenever it runs and no other Docker engine does.": "{path} ուղին ազատ է։ Երբ այլ Docker շարժիչ չի աշխատում, այն սպասարկում է {app} հավելվածը։", + "{path} is free. {service} links it when Kiri starts while no other Docker engine has it.": "{path} ուղին ազատ է։ Երբ այլ Docker շարժիչ այն չի զբաղեցրել, Kiri-ի գործարկման ժամանակ այն կապում է {service} ծառայությունը։", + "{path} is free. {app} leaves it for the installed Kiri.": "{path} ուղին ազատ է։ {app} հավելվածն այն թողնում է տեղադրված Kiri-ին։", + "Linking…": "Կապվում է…", + "Use {app}": "Օգտագործել {app}", + "Free": "Ազատ է", + "Docker socket": "Docker սոկետ", + "The {docker} command uses {app}.": "{docker} հրամանն օգտագործում է {app}։", + "{env} is set in this session, so {docker} uses another engine.": "Այս սեսիայում սահմանված է {env}, ուստի {docker} հրամանն օգտագործում է այլ շարժիչ։", + "The {docker} command uses {engine}.": "{docker} հրամանն օգտագործում է՝ {engine}։", + "Switching…": "Փոխարկվում է…", + "{docker} command": "{docker} հրաման", + "/var/run/docker.sock now points to Kiri": "/var/run/docker.sock-ն այժմ ուղղված է Kiri-ին", + "Could not link /var/run/docker.sock: {error}": "Չհաջողվեց կապել /var/run/docker.sock-ը՝ {error}", + "Stopping containers…": "Կոնտեյներները կանգնեցվում են…", + "Copying data…": "Տվյալները պատճենվում են…", + "Verifying copy…": "Պատճենը ստուգվում է…", + "Switching storage…": "Պահոցը փոխարկվում է…", + "Restarting engine…": "Շարժիչը վերագործարկվում է…", + "Moving data…": "Տվյալները տեղափոխվում են…", + "Storage location unavailable": "Պահոցի տեղադրությունն անհասանելի է", + "Kiri couldn't find its data in {path}. Connect its drive and retry, choose another folder, or reset to the default location.": "Kiri-ն չգտավ իր տվյալները {path} թղթապանակում։ Միացրեք կրիչն ու կրկին փորձեք, ընտրեք այլ թղթապանակ կամ վերականգնեք լռելյայն տեղադրությունը։", + "Change…": "Փոխել…", + "Reset to default": "Վերականգնել լռելյայնը", + "Open storage settings": "Բացել պահոցի կարգավորումները", + "Start Kiri to change its storage location. ({error})": "Գործարկեք Kiri-ն՝ պահոցի տեղադրությունը փոխելու համար։ ({error})", + "{size} used": "զբաղված՝ {size}", + "{size} free": "ազատ՝ {size}", + "Default": "Լռելյայն", + "Moving Kiri's data to {path}.": "Kiri-ի տվյալները տեղափոխվում են՝ {path}։", + "Running containers pause while Kiri copies its data and start again once it's done.": "Աշխատող կոնտեյներները դադար են առնում տվյալների պատճենման ընթացքում և ավարտից հետո նորից գործարկվում են։", + "Couldn't change storage location": "Չհաջողվեց փոխել պահոցի տեղադրությունը", + "Old data": "Հին տվյալներ", + "Previous data is still in {path}. Remove it once everything works in the new location.": "Նախկին տվյալները դեռ պահվում են այստեղ՝ {path}։ Հեռացրեք դրանք, երբ նոր տեղադրությունում ամեն ինչ աշխատի։", + "Remove old data": "Հեռացնել հին տվյալները", + "Storage location": "Պահոցի տեղադրություն", + "{var} sets Kiri's storage location, so it can't be changed here.": "{var} փոփոխականը սահմանում է Kiri-ի պահոցի տեղադրությունը, ուստի այն այստեղ հնարավոր չէ փոխել։", + "Images, containers, and volumes live in this folder. External drives must use a native filesystem (APFS on macOS, ext4/xfs/btrfs on Linux, NTFS on Windows); FAT and exFAT drives aren't supported.": "Պատկերները, կոնտեյներները և հատորները պահվում են այս թղթապանակում։ Արտաքին կրիչները պետք է ունենան հարազատ ֆայլային համակարգ (APFS՝ macOS-ում, ext4/xfs/btrfs՝ Linux-ում, NTFS՝ Windows-ում). FAT և exFAT կրիչները չեն աջակցվում։", + "Reset storage location to default?": "Վերականգնե՞լ պահոցի լռելյայն տեղադրությունը։", + "Change storage location?": "Փոխե՞լ պահոցի տեղադրությունը։", + "Destination: {path} ({free} free).": "Նշանակետ՝ {path} (ազատ՝ {free})։", + "Destination: {path}.": "Նշանակետ՝ {path}։", + "Existing Kiri data in this folder will be replaced.": "Այս թղթապանակում առկա Kiri-ի տվյալները կփոխարինվեն։", + "Migration mode": "Տեղափոխման ռեժիմ", + "Move existing images, containers, and volumes": "Տեղափոխել առկա պատկերները, կոնտեյներները և հատորները", + "Stops running containers, copies your data, and starts them again.": "Կանգնեցնում է աշխատող կոնտեյներները, պատճենում ձեր տվյալները և նորից գործարկում դրանք։", + "Start fresh": "Սկսել զրոյից", + "Starts empty in the new folder. Your old folder stays until you remove it.": "Նոր թղթապանակում սկսում է դատարկ վիճակով։ Հին թղթապանակը մնում է, մինչև այն հեռացնեք։", + "Kiri will switch to this folder and restart the engine.": "Kiri-ն կանցնի այս թղթապանակին և կվերագործարկի շարժիչը։", + "Running containers will stop while Kiri moves your data and start again once it's done.": "Աշխատող կոնտեյներները կկանգնեն տվյալների տեղափոխման ընթացքում և ավարտից հետո նորից կգործարկվեն։", + "Move data": "Տեղափոխել տվյալները", + "Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted.": "Kiri-ն կվերադառնա լռելյայն թղթապանակին և կվերագործարկի շարժիչը։ Անջատված կրիչի տվյալները չեն ջնջվում։", + "Remove old data?": "Հեռացնե՞լ հին տվյալները։", + "Everything in {path} will be deleted for good.": "{path} թղթապանակի ամբողջ պարունակությունը կջնջվի ընդմիշտ։", + "Choose a storage folder": "Ընտրեք պահոցի թղթապանակ", + "Kiri's data is moving already": "Kiri-ի տվյալներն արդեն տեղափոխվում են", + "Kiri's data moved to {path}": "Kiri-ի տվյալները տեղափոխվեցին՝ {path}", + "Storage is available again": "Պահոցը կրկին հասանելի է", + "Old data removed": "Հին տվյալները հեռացվեցին", + "A proxy on this computer is reached as {host}.": "Այս համակարգչի պրոքսին հասանելի է որպես {host}։", + "VPNs need no setting: container traffic leaves through Linux.": "VPN-ները կարգավորում չեն պահանջում՝ կոնտեյներների տրաֆիկը դուրս է գնում Linux-ի միջոցով։", + "Shared with Linux: containers only use them while busy.": "Ընդհանուր են Linux-ի հետ՝ կոնտեյներները դրանք օգտագործում են միայն զբաղված լինելիս։", + "The most containers and the engine may take. Unused memory stays free on Linux.": "Առավելագույն հիշողությունը, որը կարող են զբաղեցնել կոնտեյներներն ու շարժիչը։ Չօգտագործված հիշողությունը Linux-ում մնում է ազատ։", + "The engine is off; it starts with these next time.": "Շարժիչն անջատված է. հաջորդ անգամ այն կգործարկվի այս կարգավորումներով։", + "Restart engine to apply": "Վերագործարկել շարժիչը՝ կիրառելու համար", + "Windows bind-mount file events": "Windows-ի կցված թղթապանակների ֆայլային իրադարձություններ", + "Forward file changes on Windows drives (like {path}) into containers for live reload. Uses no CPU when idle.": "Փոխանցում է Windows կրիչների (օրինակ՝ {path}) ֆայլերի փոփոխությունները կոնտեյներներին՝ թարմացման համար։ Պարապուրդի ժամանակ CPU չի օգտագործում։", + "One text file, redacted, saved to your Desktop. Read it before you share it.": "Մեկ տեքստային ֆայլ՝ անձնական տվյալները հեռացված, պահվում է ձեր Աշխատասեղանին։ Կարդացեք այն, նախքան կիսվելը։", + "The 5 newest crash reports for Kiri": "Kiri-ի 5 ամենանոր խափանման հաշվետվությունները", + "Kiri and this PC": "Kiri-ն և այս PC-ն", + "Kiri and this computer": "Kiri-ն և այս համակարգիչը", + "Versions, {os}, whether the engine runs, how many containers and images": "Տարբերակները, {os}, աշխատում է արդյոք շարժիչը, քանի կոնտեյներ և պատկեր կա", + "Saved. The engine uses these from its next start": "Պահպանված է։ Շարժիչը դրանք կկիրառի հաջորդ գործարկումից", + "5 min": "5 ր", + "10 min": "10 ր", + "30 min": "30 ր", + "Never": "Երբեք", + "Build cache limit": "Կառուցման քեշի սահմանաչափ", + "Oldest cached layers are pruned automatically once BuildKit's cache passes this size.": "Ամենահին քեշավորված շերտերն ավտոմատ մաքրվում են, երբ BuildKit-ի քեշը գերազանցում է այս չափը։", + "Stop builder when idle": "Կանգնեցնել կառուցիչը պարապուրդի ժամանակ", + "Stops BuildKit between builds so it uses no memory while idle; the next build wakes it in under a second.": "Կառուցումների միջև կանգնեցնում է BuildKit-ը, որպեսզի պարապուրդի ժամանակ հիշողություն չզբաղեցնի. հաջորդ կառուցումն արթնացնում է այն մեկ վայրկյանից արագ։", + "KIRI_BUILD_CACHE_GB or KIRI_BUILDER_IDLE_SECS is set for the daemon, and it takes precedence over these.": "Դեմոնի համար սահմանված է KIRI_BUILD_CACHE_GB կամ KIRI_BUILDER_IDLE_SECS, և այն գերակա է այս կարգավորումների նկատմամբ։", + "macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.": "macOS NAT՝ ամենաարագը։ Անցեք «Հոսթի վերահաղորդիչ» ռեժիմին, եթե Cloudflare WARP-ը կամ կորպորատիվ firewall-ն արգելափակում է կոնտեյներների HTTPS-ը։ Կիրառվում է VM-ի վերագործարկումից հետո։", + "Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart.": "Հոսթի վերահաղորդիչ. միացումները դուրս են գալիս macOS-ում աշխատող Kiri-ից՝ Virtualization.framework NAT-ի փոխարեն։ Կիրառվում է VM-ի վերագործարկումից հետո։", + "KIRI_SHARED_NAT is set in the environment and takes precedence.": "Միջավայրում սահմանված է KIRI_SHARED_NAT, և այն գերակա է։", + "Outbound VM traffic": "VM-ի ելքային տրաֆիկ", + "macOS NAT": "macOS NAT", + "Host relay": "Հոսթի վերահաղորդիչ", + "The most the VM disk may grow to. Space is used on {os} only as data is written, and unused space can be reclaimed in {storage}. Applies on restart.": "Առավելագույն չափը, մինչև որը կարող է մեծանալ VM-ի սկավառակը։ Տեղը զբաղեցվում է ({os}) միայն տվյալներ գրելիս, իսկ ազատված տեղը կարելի է վերադարձնել «{storage}» բաժնում։ Կիրառվում է վերագործարկումից հետո։", + "Settings → Storage": "Կարգավորումներ → Կրիչ", + "VM disk space": "VM-ի սկավառակի տարածք", + "Native Linux uses your host filesystem directly — deleted images and volumes free space immediately.": "Linux-ն ուղղակիորեն օգտագործում է հոսթի ֆայլային համակարգը՝ ջնջված պատկերներն ու հատորներն անմիջապես ազատում են տարածքը։", + "Compact disk…": "Սեղմել սկավառակը…", + "Reclaim space": "Վերադարձնել տեղը", + "Compacting…": "Սեղմվում է…", + "Reclaiming…": "Վերադարձվում է…", + "Compacting {vhdx} and restarting the engine…": "Սեղմվում է {vhdx} ֆայլը և վերագործարկվում է շարժիչը…", + "{host} on {os}, {inUse} in use inside the VM · trimming unused blocks…": "{host} ({os}), VM-ի ներսում զբաղված է {inUse} · մաքրվում են չօգտագործվող բլոկները…", + "Trimming unused blocks inside the VM disk…": "VM-ի սկավառակի չօգտագործվող բլոկները մաքրվում են…", + "{host} on Windows ({vhdx}), {inUse} in use · {freed}.": "{host} Windows-ում ({vhdx}), զբաղված է {inUse} · {freed}։", + "{host} on {os}, {inUse} in use inside the VM · {freed}.": "{host} ({os}), VM-ի ներսում զբաղված է {inUse} · {freed}։", + "{host} on Windows ({vhdx}), {inUse} in use · nothing to reclaim.": "{host} Windows-ում ({vhdx}), զբաղված է {inUse} · վերադարձնելու տեղ չկա։", + "{host} on {os}, {inUse} in use inside the VM · nothing to reclaim.": "{host} ({os}), VM-ի ներսում զբաղված է {inUse} · վերադարձնելու տեղ չկա։", + "Nothing to reclaim.": "Վերադարձնելու տեղ չկա։", + "{size} can be given back": "կարելի է վերադարձնել {size}", + "{host} on Windows ({vhdx}), {inUse} in use · {can}. Compacting restarts the engine.": "{host} Windows-ում ({vhdx}), զբաղված է {inUse} · {can}։ Սեղմումը վերագործարկում է շարժիչը։", + "{host} on {os}, {inUse} in use inside the VM · {can} without stopping containers.": "{host} ({os}), VM-ի ներսում զբաղված է {inUse} · {can}՝ առանց կոնտեյներները կանգնեցնելու։", + "{host} on Windows ({vhdx}). Compacting returns unused space and restarts the engine.": "{host} Windows-ում ({vhdx})։ Սեղմումը վերադարձնում է ազատ տեղը և վերագործարկում շարժիչը։", + "{host} on {os}. Reclaiming trims unused blocks in the VM disk without stopping containers.": "{host} ({os})։ Վերադարձումը մաքրում է VM-ի սկավառակի չօգտագործվող բլոկներն առանց կոնտեյներները կանգնեցնելու։", + "Returns unused space in {vhdx} to Windows. Compacting restarts the engine.": "Վերադարձնում է {vhdx} ֆայլի չօգտագործվող տեղը Windows-ին։ Սեղմումը վերագործարկում է շարժիչը։", + "Returns unused blocks in the VM disk to {os} without stopping containers.": "Վերադարձնում է VM-ի սկավառակի չօգտագործվող բլոկները համակարգին ({os})՝ առանց կոնտեյներները կանգնեցնելու։", + "Cleaning up stopped containers, untagged images, and build cache…": "Մաքրվում են կանգնեցված կոնտեյներները, առանց պիտակի պատկերները և կառուցման քեշը…", + "{count} ({size})": "{count} ({size})", + "build cache": "կառուցման քեշ", + "No stopped containers, untagged images or build cache · {freed}.": "Կանգնեցված կոնտեյներներ, առանց պիտակի պատկերներ կամ կառուցման քեշ չկան · {freed}։", + "No stopped containers, untagged images or build cache.": "Կանգնեցված կոնտեյներներ, առանց պիտակի պատկերներ կամ կառուցման քեշ չկան։", + "Cleaning up…": "Մաքրվում է…", + "Clean up…": "Մաքրել…", + "Unused Docker data": "Չօգտագործվող Docker տվյալներ", + "Command-line tools in shell": "Հրամանային տողի գործիքները shell-ում", + "Add {bin} to {zshrc} and {zprofile} so {docker}, {kubectl} and {kiri} work in new terminals.": "Ավելացնել {bin} ուղին {zshrc} և {zprofile} ֆայլերում, որպեսզի {docker}, {kubectl} և {kiri} հրամաններն աշխատեն նոր տերմինալներում։", + "Uninstall Kiri": "Հեռացնել Kiri-ն", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context ({cmd}).": "Կանգնեցնում է շարժիչը, հեռացնում Kiri-ի ֆոնային ծառայությունը, CLI հղումներն ու shell պրոֆիլի գրառումները և վերականգնում նախորդ Docker համատեքստը ({cmd})։", + "Uninstall Kiri…": "Հեռացնել Kiri-ն…", + "Couldn't reclaim disk space: {error}": "Չհաջողվեց վերադարձնել սկավառակի տարածքը՝ {error}", + "Reclaimed {size} on {os}": "Վերադարձվեց {size} ({os})", + "Nothing to reclaim": "Վերադարձնելու տեղ չկա", + "Couldn't clean up unused Docker data: {error}": "Չհաջողվեց մաքրել չօգտագործվող Docker տվյալները՝ {error}", + "Cleaned up {size} of unused Docker data": "Մաքրվեց {size} չօգտագործվող Docker տվյալ", + "Cleaned up unused Docker data": "Չօգտագործվող Docker տվյալները մաքրվեցին", + "Compact WSL disk?": "Սեղմե՞լ WSL սկավառակը։", + "Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.": "{vhdx} ֆայլի սեղմումը վերադարձնում է չօգտագործվող տեղը Windows-ին և կարճ ժամանակով վերագործարկում Kiri-ի շարժիչն ու աշխատող կոնտեյներները։", + "Compact disk": "Սեղմել սկավառակը", + "Clean up unused Docker data?": "Մաքրե՞լ չօգտագործվող Docker տվյալները։", + "Removes stopped containers, untagged images, and BuildKit's build cache. Running containers and tagged images are kept.": "Հեռացնում է կանգնեցված կոնտեյներները, առանց պիտակի պատկերները և BuildKit-ի կառուցման քեշը։ Աշխատող կոնտեյներները և պիտակավորված պատկերները պահպանվում են։", + "Clean up": "Մաքրել", + "Uninstall Kiri?": "Հեռացնե՞լ Kiri-ն։", + "Stops the engine, removes Kiri's background service, CLI links and shell profile entries, and restores your previous Docker context. Your images and volumes stay in Kiri's data folder until you delete it.": "Կանգնեցնում է շարժիչը, հեռացնում Kiri-ի ֆոնային ծառայությունը, CLI հղումներն ու shell պրոֆիլի գրառումները և վերականգնում նախորդ Docker համատեքստը։ Ձեր պատկերներն ու հատորները մնում են Kiri-ի տվյալների թղթապանակում, մինչև այն ջնջեք։", + "Cluster": "Կլաստեր", + "default": "լռելյայն", + "k3s version": "k3s տարբերակ", + "Image version for the cluster node ({cmd}). Applies when recreated.": "Կլաստերի հանգույցի պատկերի տարբերակը ({cmd})։ Կիրառվում է վերաստեղծելիս։", + "Extra server flags": "Սերվերի լրացուցիչ դրոշներ", + "Passed to {srv} ({flag}), separated by spaces.": "Փոխանցվում են {srv} հրամանին ({flag})՝ բացատներով բաժանված։", + "Startup manifests": "Մեկնարկային մանիֆեստներ", + "YAML files in {path} are applied whenever the cluster starts.": "{path} թղթապանակի YAML ֆայլերը կիրառվում են կլաստերի յուրաքանչյուր գործարկման ժամանակ։", + "Open folder": "Բացել թղթապանակը", + "{n} untagged image": "{n} առանց պիտակի պատկեր", + "{n} untagged images": "{n} առանց պիտակի պատկեր", + "Uninstall Kiri from Windows Settings → Apps": "Հեռացրեք Kiri-ն Windows-ի Կարգավորումներ → Հավելվածներ բաժնից", + "Builder settings saved": "Կառուցիչի կարգավորումները պահպանվեցին", + "Could not save builder settings: {error}": "Չհաջողվեց պահպանել կառուցիչի կարգավորումները՝ {error}", + "Disk reclaim is already running": "Սկավառակի տարածքի վերադարձն արդեն կատարվում է", + "Outbound VM traffic setting saved. Restart the VM to apply.": "VM-ի ելքային տրաֆիկի կարգավորումը պահպանվեց։ Կիրառելու համար վերագործարկեք VM-ը։", + "Could not save VM networking setting: {error}": "Չհաջողվեց պահպանել VM-ի ցանցային կարգավորումը՝ {error}", + "Added Kiri command-line tools to shell profiles": "Kiri-ի հրամանային տողի գործիքներն ավելացվեցին shell պրոֆիլներում", + "Removed Kiri command-line tools from shell profiles": "Kiri-ի հրամանային տողի գործիքները հեռացվեցին shell պրոֆիլներից", + "Could not update shell profiles: {error}": "Չհաջողվեց թարմացնել shell պրոֆիլները՝ {error}", + "Uninstalling Kiri…": "Kiri-ն հեռացվում է…", + "Could not uninstall Kiri: {error}": "Չհաջողվեց հեռացնել Kiri-ն՝ {error}", + "Uninstall Kiri using your system package manager": "Հեռացրեք Kiri-ն ձեր համակարգի փաթեթների կառավարչի միջոցով", + "Swap": "Փոխանակում (swap)", + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Սկավառակի տարածք, որը VM-ը կարող է օգտագործել հիշողությունը սպառվելիս, որպեսզի կոնտեյներները կանգնելու փոխարեն դանդաղեն։ Կիրառվում է վերագործարկումից հետո։", + "Community": "Համայնք" +} diff --git a/crates/kiri/src/ui/lang/id.json b/crates/kiri/src/ui/lang/id.json index 437c72e63..e4728f1fe 100644 --- a/crates/kiri/src/ui/lang/id.json +++ b/crates/kiri/src/ui/lang/id.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Tidak bisa menghapus instalasi Kiri: {error}", "Uninstall Kiri using your system package manager": "Hapus instalasi Kiri menggunakan manajer paket sistem Anda", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Ruang disk yang boleh dipakai VM saat memorinya habis, sehingga kontainer melambat alih-alih dihentikan. Berlaku saat dimulai ulang." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Ruang disk yang boleh dipakai VM saat memorinya habis, sehingga kontainer melambat alih-alih dihentikan. Berlaku saat dimulai ulang.", + "Community": "Komunitas" } diff --git a/crates/kiri/src/ui/lang/it.json b/crates/kiri/src/ui/lang/it.json index 516c01c4a..6ef3e56fe 100644 --- a/crates/kiri/src/ui/lang/it.json +++ b/crates/kiri/src/ui/lang/it.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Impossibile disinstallare Kiri: {error}", "Uninstall Kiri using your system package manager": "Disinstalla Kiri usando il gestore di pacchetti del sistema", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spazio su disco che la VM può usare quando esaurisce la memoria, così i container rallentano invece di essere fermati. Si applica al riavvio." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spazio su disco che la VM può usare quando esaurisce la memoria, così i container rallentano invece di essere fermati. Si applica al riavvio.", + "Community": "Comunità" } diff --git a/crates/kiri/src/ui/lang/ja.json b/crates/kiri/src/ui/lang/ja.json index c1e9bd038..9d0ea804b 100644 --- a/crates/kiri/src/ui/lang/ja.json +++ b/crates/kiri/src/ui/lang/ja.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri をアンインストールできませんでした:{error}", "Uninstall Kiri using your system package manager": "システムのパッケージマネージャーで Kiri をアンインストールしてください", "Swap": "スワップ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM のメモリが足りなくなったときに使えるディスク領域です。コンテナは停止されずに遅くなるだけで済みます。再起動時に適用されます。" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM のメモリが足りなくなったときに使えるディスク領域です。コンテナは停止されずに遅くなるだけで済みます。再起動時に適用されます。", + "Community": "コミュニティ" } diff --git a/crates/kiri/src/ui/lang/kk.json b/crates/kiri/src/ui/lang/kk.json index 9e374ff11..e8f427ae2 100644 --- a/crates/kiri/src/ui/lang/kk.json +++ b/crates/kiri/src/ui/lang/kk.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri-ді өшіру мүмкін болмады: {error}", "Uninstall Kiri using your system package manager": "Kiri-ді жүйенің пакет менеджері арқылы өшіріңіз", "Swap": "Своп", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM жадысы таусылғанда пайдалана алатын диск кеңістігі: контейнерлер тоқтатылмай, баяулайды. Қайта іске қосқанда қолданылады." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM жадысы таусылғанда пайдалана алатын диск кеңістігі: контейнерлер тоқтатылмай, баяулайды. Қайта іске қосқанда қолданылады.", + "Community": "Қауымдастық" } diff --git a/crates/kiri/src/ui/lang/ko.json b/crates/kiri/src/ui/lang/ko.json index 86c2dd7a8..3c68b5a2e 100644 --- a/crates/kiri/src/ui/lang/ko.json +++ b/crates/kiri/src/ui/lang/ko.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri를 제거할 수 없습니다: {error}", "Uninstall Kiri using your system package manager": "시스템 패키지 관리자로 Kiri를 제거하세요", "Swap": "스왑", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM의 메모리가 부족할 때 사용할 수 있는 디스크 공간입니다. 컨테이너가 중지되지 않고 느려지기만 합니다. 다시 시작하면 적용됩니다." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM의 메모리가 부족할 때 사용할 수 있는 디스크 공간입니다. 컨테이너가 중지되지 않고 느려지기만 합니다. 다시 시작하면 적용됩니다.", + "Community": "커뮤니티" } diff --git a/crates/kiri/src/ui/lang/lo.json b/crates/kiri/src/ui/lang/lo.json index 4bc17c876..3d7cc31c4 100644 --- a/crates/kiri/src/ui/lang/lo.json +++ b/crates/kiri/src/ui/lang/lo.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "ຖອນການຕິດຕັ້ງ Kiri ບໍ່ໄດ້: {error}", "Uninstall Kiri using your system package manager": "ຖອນການຕິດຕັ້ງ Kiri ໂດຍໃຊ້ຕົວຈັດການແພັກເກັດຂອງລະບົບທ່ານ", "Swap": "ສະວັບ", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "ພື້ນທີ່ດິສກ໌ທີ່ VM ໃຊ້ໄດ້ເມື່ອໜ່ວຍຄວາມຈຳໝົດ ເພື່ອໃຫ້ຄອນເທນເນີຊ້າລົງແທນທີ່ຈະຖືກຢຸດ. ມີຜົນເມື່ອເລີ່ມໃໝ່." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "ພື້ນທີ່ດິສກ໌ທີ່ VM ໃຊ້ໄດ້ເມື່ອໜ່ວຍຄວາມຈຳໝົດ ເພື່ອໃຫ້ຄອນເທນເນີຊ້າລົງແທນທີ່ຈະຖືກຢຸດ. ມີຜົນເມື່ອເລີ່ມໃໝ່.", + "Community": "ຊຸມຊົນ" } diff --git a/crates/kiri/src/ui/lang/lt.json b/crates/kiri/src/ui/lang/lt.json index 8977eb45e..708120e89 100644 --- a/crates/kiri/src/ui/lang/lt.json +++ b/crates/kiri/src/ui/lang/lt.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Nepavyko pašalinti Kiri: {error}", "Uninstall Kiri using your system package manager": "Pašalinkite Kiri naudodami sistemos paketų tvarkyklę", "Swap": "Sukeitimų sritis (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Disko vieta, kurią VM gali naudoti pritrūkusi atminties, kad konteineriai sulėtėtų, o ne būtų sustabdyti. Įsigalioja paleidus iš naujo." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Disko vieta, kurią VM gali naudoti pritrūkusi atminties, kad konteineriai sulėtėtų, o ne būtų sustabdyti. Įsigalioja paleidus iš naujo.", + "Community": "Bendruomenė" } diff --git a/crates/kiri/src/ui/lang/nb.json b/crates/kiri/src/ui/lang/nb.json index 5c6dfebb8..c6a8ac2a7 100644 --- a/crates/kiri/src/ui/lang/nb.json +++ b/crates/kiri/src/ui/lang/nb.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kunne ikke avinstallere Kiri: {error}", "Uninstall Kiri using your system package manager": "Avinstaller Kiri med systemets pakkebehandler", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Diskplass VM-en kan bruke når minnet går tomt, slik at containere går tregere i stedet for å bli stoppet. Brukes ved omstart." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Diskplass VM-en kan bruke når minnet går tomt, slik at containere går tregere i stedet for å bli stoppet. Brukes ved omstart.", + "Community": "Fellesskap" } diff --git a/crates/kiri/src/ui/lang/ne.json b/crates/kiri/src/ui/lang/ne.json index 5a2c2d2d9..9dcf24aa4 100644 --- a/crates/kiri/src/ui/lang/ne.json +++ b/crates/kiri/src/ui/lang/ne.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri अनइन्स्टल गर्न सकिएन: {error}", "Uninstall Kiri using your system package manager": "आफ्नो सिस्टमको प्याकेज म्यानेजरबाट Kiri अनइन्स्टल गर्नुहोस्", "Swap": "स्व्याप", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "मेमोरी सकिएपछि VM ले प्रयोग गर्न सक्ने डिस्क स्पेस, जसले गर्दा कन्टेनर रोकिनुको सट्टा सुस्त हुन्छन्। रिस्टार्ट गर्दा लागू हुन्छ।" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "मेमोरी सकिएपछि VM ले प्रयोग गर्न सक्ने डिस्क स्पेस, जसले गर्दा कन्टेनर रोकिनुको सट्टा सुस्त हुन्छन्। रिस्टार्ट गर्दा लागू हुन्छ।", + "Community": "समुदाय" } diff --git a/crates/kiri/src/ui/lang/pl.json b/crates/kiri/src/ui/lang/pl.json index 67760d94e..61ffc0667 100644 --- a/crates/kiri/src/ui/lang/pl.json +++ b/crates/kiri/src/ui/lang/pl.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Nie udało się odinstalować Kiri: {error}", "Uninstall Kiri using your system package manager": "Odinstaluj Kiri za pomocą systemowego menedżera pakietów", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Miejsce na dysku, którego VM może używać, gdy zabraknie jej pamięci, dzięki czemu kontenery zwalniają zamiast zostać zatrzymane. Obowiązuje po ponownym uruchomieniu." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Miejsce na dysku, którego VM może używać, gdy zabraknie jej pamięci, dzięki czemu kontenery zwalniają zamiast zostać zatrzymane. Obowiązuje po ponownym uruchomieniu.", + "Community": "Społeczność" } diff --git a/crates/kiri/src/ui/lang/pt-BR.json b/crates/kiri/src/ui/lang/pt-BR.json index cf4286886..ad0942b66 100644 --- a/crates/kiri/src/ui/lang/pt-BR.json +++ b/crates/kiri/src/ui/lang/pt-BR.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Não foi possível desinstalar o Kiri: {error}", "Uninstall Kiri using your system package manager": "Desinstale o Kiri usando o gerenciador de pacotes do sistema", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espaço em disco que a VM pode usar quando a memória acaba, para que os contêineres fiquem mais lentos em vez de serem parados. Aplicado ao reiniciar." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Espaço em disco que a VM pode usar quando a memória acaba, para que os contêineres fiquem mais lentos em vez de serem parados. Aplicado ao reiniciar.", + "Community": "Comunidade" } diff --git a/crates/kiri/src/ui/lang/ro.json b/crates/kiri/src/ui/lang/ro.json index e2e36c58c..de5f31e22 100644 --- a/crates/kiri/src/ui/lang/ro.json +++ b/crates/kiri/src/ui/lang/ro.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Nu s-a putut dezinstala Kiri: {error}", "Uninstall Kiri using your system package manager": "Dezinstalează Kiri folosind gestionarul de pachete al sistemului", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spațiu pe disc pe care VM îl poate folosi când îi rămâne fără memorie, astfel încât containerele încetinesc în loc să fie oprite. Se aplică la repornire." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Spațiu pe disc pe care VM îl poate folosi când îi rămâne fără memorie, astfel încât containerele încetinesc în loc să fie oprite. Se aplică la repornire.", + "Community": "Comunitate" } diff --git a/crates/kiri/src/ui/lang/ru.json b/crates/kiri/src/ui/lang/ru.json index 9da5fc966..f35788c79 100644 --- a/crates/kiri/src/ui/lang/ru.json +++ b/crates/kiri/src/ui/lang/ru.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Не удалось удалить Kiri: {error}", "Uninstall Kiri using your system package manager": "Удалите Kiri с помощью системного пакетного менеджера", "Swap": "Подкачка (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Место на диске, которое VM может использовать, когда заканчивается память: контейнеры замедляются, а не останавливаются. Применяется после перезапуска." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Место на диске, которое VM может использовать, когда заканчивается память: контейнеры замедляются, а не останавливаются. Применяется после перезапуска.", + "Community": "Сообщество" } diff --git a/crates/kiri/src/ui/lang/sl.json b/crates/kiri/src/ui/lang/sl.json index 8b83987d0..ae3998e93 100644 --- a/crates/kiri/src/ui/lang/sl.json +++ b/crates/kiri/src/ui/lang/sl.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kirija ni bilo mogoče odstraniti: {error}", "Uninstall Kiri using your system package manager": "Odstranite Kiri z upraviteljem paketov svojega sistema", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Prostor na disku, ki ga VM lahko uporabi, ko ji zmanjka pomnilnika, da se vsebniki upočasnijo, namesto da bi se ustavili. Velja po ponovnem zagonu." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Prostor na disku, ki ga VM lahko uporabi, ko ji zmanjka pomnilnika, da se vsebniki upočasnijo, namesto da bi se ustavili. Velja po ponovnem zagonu.", + "Community": "Skupnost" } diff --git a/crates/kiri/src/ui/lang/sq.json b/crates/kiri/src/ui/lang/sq.json index bb245507c..9206b961d 100644 --- a/crates/kiri/src/ui/lang/sq.json +++ b/crates/kiri/src/ui/lang/sq.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri nuk u çinstalua dot: {error}", "Uninstall Kiri using your system package manager": "Çinstaloni Kiri duke përdorur menaxherin e paketave të sistemit", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Hapësirë në disk që VM mund ta përdorë kur i mbaron memoria, që kontejnerët të ngadalësohen në vend që të ndalen. Zbatohet pas rinisjes." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Hapësirë në disk që VM mund ta përdorë kur i mbaron memoria, që kontejnerët të ngadalësohen në vend që të ndalen. Zbatohet pas rinisjes.", + "Community": "Komuniteti" } diff --git a/crates/kiri/src/ui/lang/ta.json b/crates/kiri/src/ui/lang/ta.json index 20aa2bb37..47051dd6e 100644 --- a/crates/kiri/src/ui/lang/ta.json +++ b/crates/kiri/src/ui/lang/ta.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri-ஐ நிறுவல் நீக்க முடியவில்லை: {error}", "Uninstall Kiri using your system package manager": "உங்கள் கணினி தொகுப்பு மேலாளரைப் பயன்படுத்தி Kiri-ஐ நிறுவல் நீக்கவும்", "Swap": "ஸ்வாப்", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "நினைவகம் தீர்ந்தால் VM பயன்படுத்தக்கூடிய வட்டு இடம்; இதனால் கண்டெய்னர்கள் நிறுத்தப்படாமல் மெதுவாகும். மறுதொடக்கத்தில் பொருந்தும்." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "நினைவகம் தீர்ந்தால் VM பயன்படுத்தக்கூடிய வட்டு இடம்; இதனால் கண்டெய்னர்கள் நிறுத்தப்படாமல் மெதுவாகும். மறுதொடக்கத்தில் பொருந்தும்.", + "Community": "சமூகம்" } diff --git a/crates/kiri/src/ui/lang/te.json b/crates/kiri/src/ui/lang/te.json index 469fbba3e..0a0411c0f 100644 --- a/crates/kiri/src/ui/lang/te.json +++ b/crates/kiri/src/ui/lang/te.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiriని అన్‌ఇన్‌స్టాల్ చేయలేకపోయాం: {error}", "Uninstall Kiri using your system package manager": "మీ సిస్టమ్ ప్యాకేజీ మేనేజర్‌తో Kiriని అన్‌ఇన్‌స్టాల్ చేయండి", "Swap": "స్వాప్", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "మెమరీ అయిపోయినప్పుడు VM ఉపయోగించగల డిస్క్ స్థలం, దీని వల్ల కంటైనర్లు ఆపబడకుండా నెమ్మదిస్తాయి. రీస్టార్ట్‌లో వర్తిస్తుంది." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "మెమరీ అయిపోయినప్పుడు VM ఉపయోగించగల డిస్క్ స్థలం, దీని వల్ల కంటైనర్లు ఆపబడకుండా నెమ్మదిస్తాయి. రీస్టార్ట్‌లో వర్తిస్తుంది.", + "Community": "సముదాయం" } diff --git a/crates/kiri/src/ui/lang/th.json b/crates/kiri/src/ui/lang/th.json index df8e13079..076ae229f 100644 --- a/crates/kiri/src/ui/lang/th.json +++ b/crates/kiri/src/ui/lang/th.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "ถอนการติดตั้ง Kiri ไม่ได้: {error}", "Uninstall Kiri using your system package manager": "ถอนการติดตั้ง Kiri ด้วยตัวจัดการแพ็กเกจของระบบ", "Swap": "สวอป", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "พื้นที่ดิสก์ที่ VM ใช้ได้เมื่อหน่วยความจำหมด เพื่อให้คอนเทนเนอร์ทำงานช้าลงแทนที่จะถูกหยุด มีผลเมื่อเริ่มใหม่" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "พื้นที่ดิสก์ที่ VM ใช้ได้เมื่อหน่วยความจำหมด เพื่อให้คอนเทนเนอร์ทำงานช้าลงแทนที่จะถูกหยุด มีผลเมื่อเริ่มใหม่", + "Community": "ชุมชน" } diff --git a/crates/kiri/src/ui/lang/tr.json b/crates/kiri/src/ui/lang/tr.json index f85057fdf..7f53265c2 100644 --- a/crates/kiri/src/ui/lang/tr.json +++ b/crates/kiri/src/ui/lang/tr.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kiri kaldırılamadı: {error}", "Uninstall Kiri using your system package manager": "Kiri'yi sistem paket yöneticinizi kullanarak kaldırın", "Swap": "Takas (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM'nin belleği tükendiğinde kullanabileceği disk alanı; böylece konteynerler durdurulmak yerine yavaşlar. Yeniden başlatınca uygulanır." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM'nin belleği tükendiğinde kullanabileceği disk alanı; böylece konteynerler durdurulmak yerine yavaşlar. Yeniden başlatınca uygulanır.", + "Community": "Topluluk" } diff --git a/crates/kiri/src/ui/lang/uk.json b/crates/kiri/src/ui/lang/uk.json index 17488b7de..20353436d 100644 --- a/crates/kiri/src/ui/lang/uk.json +++ b/crates/kiri/src/ui/lang/uk.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Не вдалося видалити Kiri: {error}", "Uninstall Kiri using your system package manager": "Видаліть Kiri за допомогою системного менеджера пакунків", "Swap": "Підкачка (swap)", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Місце на диску, яке VM може використовувати, коли закінчується пам'ять: контейнери сповільнюються, а не зупиняються. Застосовується після перезапуску." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Місце на диску, яке VM може використовувати, коли закінчується пам'ять: контейнери сповільнюються, а не зупиняються. Застосовується після перезапуску.", + "Community": "Спільнота" } diff --git a/crates/kiri/src/ui/lang/uz.json b/crates/kiri/src/ui/lang/uz.json index 9bf2c95fa..339e32fca 100644 --- a/crates/kiri/src/ui/lang/uz.json +++ b/crates/kiri/src/ui/lang/uz.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Kirini oʻchirib tashlab boʻlmadi: {error}", "Uninstall Kiri using your system package manager": "Kirini tizimingiz paket menejeri orqali oʻchirib tashlang", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM xotirasi tugaganda ishlatishi mumkin boʻlgan disk joyi — shunda konteynerlar toʻxtab qolish oʻrniga sekinlashadi. Qayta ishga tushganda qoʻllanadi." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "VM xotirasi tugaganda ishlatishi mumkin boʻlgan disk joyi — shunda konteynerlar toʻxtab qolish oʻrniga sekinlashadi. Qayta ishga tushganda qoʻllanadi.", + "Community": "Hamjamiyat" } diff --git a/crates/kiri/src/ui/lang/vi.json b/crates/kiri/src/ui/lang/vi.json index 1b7282d25..c728e7188 100644 --- a/crates/kiri/src/ui/lang/vi.json +++ b/crates/kiri/src/ui/lang/vi.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "Không thể gỡ cài đặt Kiri: {error}", "Uninstall Kiri using your system package manager": "Hãy gỡ cài đặt Kiri bằng trình quản lý gói của hệ thống", "Swap": "Swap", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Dung lượng đĩa mà VM có thể dùng khi hết bộ nhớ, để container chạy chậm lại thay vì bị dừng. Áp dụng khi khởi động lại." + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "Dung lượng đĩa mà VM có thể dùng khi hết bộ nhớ, để container chạy chậm lại thay vì bị dừng. Áp dụng khi khởi động lại.", + "Community": "Cộng đồng" } diff --git a/crates/kiri/src/ui/lang/zh-Hans.json b/crates/kiri/src/ui/lang/zh-Hans.json index 6383854ea..f8f9c356f 100644 --- a/crates/kiri/src/ui/lang/zh-Hans.json +++ b/crates/kiri/src/ui/lang/zh-Hans.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "无法卸载 Kiri:{error}", "Uninstall Kiri using your system package manager": "请使用系统包管理器卸载 Kiri", "Swap": "交换空间", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虚拟机内存用尽时可使用的磁盘空间,容器会变慢而不是被停止。重启后生效。" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虚拟机内存用尽时可使用的磁盘空间,容器会变慢而不是被停止。重启后生效。", + "Community": "社区" } diff --git a/crates/kiri/src/ui/lang/zh-Hant.json b/crates/kiri/src/ui/lang/zh-Hant.json index 40baefcde..228013856 100644 --- a/crates/kiri/src/ui/lang/zh-Hant.json +++ b/crates/kiri/src/ui/lang/zh-Hant.json @@ -2035,5 +2035,6 @@ "Could not uninstall Kiri: {error}": "無法解除安裝 Kiri:{error}", "Uninstall Kiri using your system package manager": "請使用系統套件管理員解除安裝 Kiri", "Swap": "交換空間", - "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虛擬機記憶體用盡時可使用的磁碟空間,容器會變慢而不是被停止。重新啟動後生效。" + "Disk space the VM may use when its memory runs out, so containers slow down instead of being stopped. Applies on restart.": "虛擬機記憶體用盡時可使用的磁碟空間,容器會變慢而不是被停止。重新啟動後生效。", + "Community": "社群" } diff --git a/crates/kiri/src/ui/langstep.js b/crates/kiri/src/ui/langstep.js index e5373f1ab..401c607b3 100644 --- a/crates/kiri/src/ui/langstep.js +++ b/crates/kiri/src/ui/langstep.js @@ -6,21 +6,22 @@ langFor() and saving; this file has the tables, the search and the keys. */ /* Each language in its own name, by script: the Latin alphabet (A to Z by that - name), Greek, Cyrillic, the Arabic script, Ethiopic, the Indian scripts, - Thai and Lao, then Japanese, Korean and Chinese. */ -const LANGS = [["en", "English"], ["id", "Bahasa Indonesia"], ["ca", "Català"], ["cs", "Čeština"], ["de", "Deutsch"], ["es", "Español"], ["fr", "Français"], ["it", "Italiano"], ["lt", "Lietuvių"], ["hu", "Magyar"], ["nb", "Norsk bokmål"], ["uz", "Oʻzbekcha"], ["pl", "Polski"], ["pt-BR", "Português (Brasil)"], ["ro", "Română"], ["sq", "Shqip"], ["sl", "Slovenščina"], ["fi", "Suomi"], ["vi", "Tiếng Việt"], ["tr", "Türkçe"], ["el", "Ελληνικά"], ["bg", "Български"], ["ru", "Русский"], ["uk", "Українська"], ["kk", "Қазақша"], ["ar", "العربية"], ["fa", "فارسی"], ["ckb", "کوردیی ناوەندی"], ["am", "አማርኛ"], ["hi", "हिन्दी"], ["ne", "नेपाली"], ["bn", "বাংলা"], ["ta", "தமிழ்"], ["te", "తెలుగు"], ["th", "ไทย"], ["lo", "ລາວ"], ["ja", "日本語"], ["ko", "한국어"], ["zh-Hans", "简体中文"], ["zh-Hant", "繁體中文"]]; + name), Greek, Cyrillic, Armenian, the Arabic script, Ethiopic, the Indian + scripts, Thai and Lao, then Japanese, Korean and Chinese. */ +const LANGS = [["en", "English"], ["az", "Azərbaycanca"], ["id", "Bahasa Indonesia"], ["ca", "Català"], ["cs", "Čeština"], ["de", "Deutsch"], ["es", "Español"], ["fr", "Français"], ["it", "Italiano"], ["lt", "Lietuvių"], ["hu", "Magyar"], ["nb", "Norsk bokmål"], ["uz", "Oʻzbekcha"], ["pl", "Polski"], ["pt-BR", "Português (Brasil)"], ["ro", "Română"], ["sq", "Shqip"], ["sl", "Slovenščina"], ["fi", "Suomi"], ["vi", "Tiếng Việt"], ["tr", "Türkçe"], ["el", "Ελληνικά"], ["bg", "Български"], ["ru", "Русский"], ["uk", "Українська"], ["kk", "Қазақша"], ["hy", "Հայերեն"], ["ar", "العربية"], ["fa", "فارسی"], ["ckb", "کوردیی ناوەندی"], ["am", "አማርኛ"], ["hi", "हिन्दी"], ["ne", "नेपाली"], ["bn", "বাংলা"], ["ta", "தமிழ்"], ["te", "తెలుగు"], ["th", "ไทย"], ["lo", "ລາວ"], ["ja", "日本語"], ["ko", "한국어"], ["zh-Hans", "简体中文"], ["zh-Hant", "繁體中文"]]; /* Each language's English name: the language step shows it beside the own name and finds a language by it ("German" for Deutsch). One for each in LANGS; one missing shows and sorts by its own name (langEn). */ -const LANG_EN = { en: "English", id: "Indonesian", ca: "Catalan", cs: "Czech", de: "German", es: "Spanish", fr: "French", it: "Italian", lt: "Lithuanian", hu: "Hungarian", nb: "Norwegian Bokmål", uz: "Uzbek", pl: "Polish", "pt-BR": "Portuguese (Brazil)", ro: "Romanian", sq: "Albanian", sl: "Slovenian", fi: "Finnish", vi: "Vietnamese", tr: "Turkish", el: "Greek", bg: "Bulgarian", ru: "Russian", uk: "Ukrainian", kk: "Kazakh", ar: "Arabic", fa: "Persian", ckb: "Kurdish (Sorani)", am: "Amharic", hi: "Hindi", ne: "Nepali", bn: "Bengali", ta: "Tamil", te: "Telugu", th: "Thai", lo: "Lao", ja: "Japanese", ko: "Korean", "zh-Hans": "Chinese (Simplified)", "zh-Hant": "Chinese (Traditional)" }; +const LANG_EN = { en: "English", az: "Azerbaijani", id: "Indonesian", ca: "Catalan", cs: "Czech", de: "German", es: "Spanish", fr: "French", it: "Italian", lt: "Lithuanian", hu: "Hungarian", nb: "Norwegian Bokmål", uz: "Uzbek", pl: "Polish", "pt-BR": "Portuguese (Brazil)", ro: "Romanian", sq: "Albanian", sl: "Slovenian", fi: "Finnish", vi: "Vietnamese", tr: "Turkish", el: "Greek", bg: "Bulgarian", ru: "Russian", uk: "Ukrainian", kk: "Kazakh", hy: "Armenian", ar: "Arabic", fa: "Persian", ckb: "Kurdish (Sorani)", am: "Amharic", hi: "Hindi", ne: "Nepali", bn: "Bengali", ta: "Tamil", te: "Telugu", th: "Thai", lo: "Lao", ja: "Japanese", ko: "Korean", "zh-Hans": "Chinese (Simplified)", "zh-Hant": "Chinese (Traditional)" }; /* Hello in each, in its own script. */ -const HELLO = { en: "Hello", id: "Halo", ca: "Hola", cs: "Ahoj", de: "Hallo", es: "Hola", fr: "Bonjour", it: "Ciao", lt: "Labas", hu: "Szia", nb: "Hei", uz: "Salom", pl: "Cześć", "pt-BR": "Olá", ro: "Salut", sq: "Përshëndetje", sl: "Živjo", fi: "Hei", vi: "Xin chào", tr: "Merhaba", el: "Γεια σου", bg: "Здравей", ru: "Привет", uk: "Привіт", kk: "Сәлем", ar: "مرحبًا", fa: "سلام", ckb: "سڵاو", am: "ሰላም", hi: "नमस्ते", ne: "नमस्ते", bn: "নমস্কার", ta: "வணக்கம்", te: "నమస్కారం", th: "สวัสดี", lo: "ສະບາຍດີ", ja: "こんにちは", ko: "안녕하세요", "zh-Hans": "你好", "zh-Hant": "你好" }; +const HELLO = { en: "Hello", az: "Salam", id: "Halo", ca: "Hola", cs: "Ahoj", de: "Hallo", es: "Hola", fr: "Bonjour", it: "Ciao", lt: "Labas", hu: "Szia", nb: "Hei", uz: "Salom", pl: "Cześć", "pt-BR": "Olá", ro: "Salut", sq: "Përshëndetje", sl: "Živjo", fi: "Hei", vi: "Xin chào", tr: "Merhaba", el: "Γεια σου", bg: "Здравей", ru: "Привет", uk: "Привіт", kk: "Сәлем", hy: "Բարև", ar: "مرحبًا", fa: "سلام", ckb: "سڵاو", am: "ሰላም", hi: "नमस्ते", ne: "नमस्ते", bn: "নমস্কার", ta: "வணக்கம்", te: "నమస్కారం", th: "สวัสดี", lo: "ສະບາຍດີ", ja: "こんにちは", ko: "안녕하세요", "zh-Hans": "你好", "zh-Hant": "你好" }; /* Other names people search by: what a language is also called in English ("Farsi"), in itself ("Castellano") or spelled another way (हिंदी, Uzbek in other Latin spellings or Cyrillic). */ const LANG_ALIAS = { farsi: ["fa"], mandarin: ["zh-Hans", "zh-Hant"], chinese: ["zh-Hans", "zh-Hant"], putonghua: ["zh-Hans"], cantonese: ["zh-Hant"], castellano: ["es"], castilian: ["es"], "हिंदी": ["hi"], bangla: ["bn"], brazilian: ["pt-BR"], norwegian: ["nb"], sorani: ["ckb"], bahasa: ["id"], - "o'zbekcha": ["uz"], "oʻzbekcha": ["uz"], "o‘zbekcha": ["uz"], ozbekcha: ["uz"], "ōzbekça": ["uz"], "ўзбекча": ["uz"] }; + "o'zbekcha": ["uz"], "oʻzbekcha": ["uz"], "o‘zbekcha": ["uz"], ozbekcha: ["uz"], "ōzbekça": ["uz"], "ўзбекча": ["uz"], + azeri: ["az"], azerbaycanca: ["az"], hayeren: ["hy"] }; const langEn = (id, own) => LANG_EN[id] || own; const langOwn = (id) => (LANGS.find(([l]) => l === id) || [id, id])[1]; /* Languages offered after the system's own, until Suggested holds five. */ diff --git a/tests/ui/langmenu-search.js b/tests/ui/langmenu-search.js index 3acc2cf0f..2bbfe4053 100644 --- a/tests/ui/langmenu-search.js +++ b/tests/ui/langmenu-search.js @@ -2,7 +2,7 @@ // window: 760x480 // Settings › Appearance › Language: a button showing the choice that opens a // short searchable list (the language step's search, other names and keys), -// not a 39-row menu. The hidden stays the choice. { const R = []; const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; diff --git a/tests/ui/langpick.js b/tests/ui/langpick.js index e26b49d2f..0c81f6463 100644 --- a/tests/ui/langpick.js +++ b/tests/ui/langpick.js @@ -13,10 +13,10 @@ const saved = (name) => sent.filter((m) => m.type === "setpref" && m.name === na const rail = () => document.querySelector("nav [data-view=containers] .lbl").textContent; kiri.on({ type: "langpick" }); -t("a langpick event opens the language step with a row for each of the 40 languages", () => { +t("a langpick event opens the language step with a row for each of the 42 languages", () => { if (!dlg()) throw new Error("no dialog"); const ids = tilesNow().map((b) => b.dataset.lang).sort().join(" "); - if (ids !== LANGS.map(([id]) => id).sort().join(" ") || tilesNow().length !== 40) throw new Error("rows: " + ids); + if (ids !== LANGS.map(([id]) => id).sort().join(" ") || tilesNow().length !== 42) throw new Error("rows: " + ids); }); t("one column, a line each", () => { const lefts = new Set(tilesNow().map((b) => Math.round(b.getBoundingClientRect().left))); @@ -26,7 +26,7 @@ t("one column, a line each", () => { t("each row is in its own language, with its own Hello", () => { if (pickTile("de").querySelector(".ln").getAttribute("lang") !== "de" || !pickTile("de").textContent.includes("Deutsch") || !pickTile("de").textContent.includes("Hallo")) throw new Error(pickTile("de").textContent); if (!pickTile("zh-Hans").textContent.includes("简体中文") || !pickTile("zh-Hans").textContent.includes("你好")) throw new Error(pickTile("zh-Hans").textContent); - for (const [id, name, hello] of [["ja", "日本語", "こんにちは"], ["ko", "한국어", "안녕하세요"], ["zh-Hant", "繁體中文", "你好"], ["ru", "Русский", "Привет"], ["uk", "Українська", "Привіт"], ["hi", "हिन्दी", "नमस्ते"], ["ne", "नेपाली", "नमस्ते"], ["fa", "فارسی", "سلام"], ["ckb", "کوردیی ناوەندی", "سڵاو"], ["el", "Ελληνικά", "Γεια σου"], ["kk", "Қазақша", "Сәлем"], ["te", "తెలుగు", "నమస్కారం"], ["am", "አማርኛ", "ሰላም"], ["th", "ไทย", "สวัสดี"], ["lo", "ລາວ", "ສະບາຍດີ"], ["nb", "Norsk bokmål", "Hei"], ["uz", "Oʻzbekcha", "Salom"], ["bn", "বাংলা", "নমস্কার"], ["ta", "தமிழ்", "வணக்கம்"], ["ar", "العربية", "مرحبًا"], ["vi", "Tiếng Việt", "Xin chào"], ["id", "Bahasa Indonesia", "Halo"]]) + for (const [id, name, hello] of [["ja", "日本語", "こんにちは"], ["ko", "한국어", "안녕하세요"], ["zh-Hant", "繁體中文", "你好"], ["ru", "Русский", "Привет"], ["uk", "Українська", "Привіт"], ["hi", "हिन्दी", "नमस्ते"], ["ne", "नेपाली", "नमस्ते"], ["fa", "فارسی", "سلام"], ["ckb", "کوردیی ناوەندی", "سڵاو"], ["el", "Ελληνικά", "Γεια σου"], ["kk", "Қазақша", "Сәлем"], ["hy", "Հայերեն", "Բարև"], ["te", "తెలుగు", "నమస్కారం"], ["am", "አማርኛ", "ሰላም"], ["th", "ไทย", "สวัสดี"], ["lo", "ລາວ", "ສະບາຍດີ"], ["nb", "Norsk bokmål", "Hei"], ["uz", "Oʻzbekcha", "Salom"], ["az", "Azərbaycanca", "Salam"], ["bn", "বাংলা", "নমস্কার"], ["ta", "தமிழ்", "வணக்கம்"], ["ar", "العربية", "مرحبًا"], ["vi", "Tiếng Việt", "Xin chào"], ["id", "Bahasa Indonesia", "Halo"]]) if (pickTile(id).querySelector(".ln").getAttribute("lang") !== id || !pickTile(id).textContent.includes(name) || !pickTile(id).textContent.includes(hello)) throw new Error(pickTile(id).textContent); }); t("the system's language is marked and picked", () => { diff --git a/tests/ui/langstep.js b/tests/ui/langstep.js index 23d7dfe0b..9333c2e7b 100644 --- a/tests/ui/langstep.js +++ b/tests/ui/langstep.js @@ -41,12 +41,12 @@ t("Suggested: the system's language first, its other languages, then up to five" if (sug?.querySelector(".lsect")?.textContent !== "Suggested") throw new Error("first section: " + sug?.querySelector(".lsect")?.textContent); const got = ids(`#${sug.id}`).join(" "); if (got !== "en de pt-BR es fr") throw new Error("suggested: " + got); - if (all?.querySelector(".lsect")?.textContent !== "All languages · 40") throw new Error("second section: " + all?.querySelector(".lsect")?.textContent); + if (all?.querySelector(".lsect")?.textContent !== "All languages · 42") throw new Error("second section: " + all?.querySelector(".lsect")?.textContent); }); t("All languages: every one, by its English name", () => { const all = groups()[1]; const got = rows(`#${all.id}`); - if (got.length !== 40 || new Set(got.map((r) => r.dataset.lang)).size !== 40) throw new Error(got.length + " rows"); + if (got.length !== 42 || new Set(got.map((r) => r.dataset.lang)).size !== 42) throw new Error(got.length + " rows"); const names = got.map((r) => (r.querySelector(".le") || r.querySelector(".ln")).textContent); const sorted = [...names].sort((a, b) => a.localeCompare(b, "en")); if (names.join() !== sorted.join()) throw new Error("not sorted: " + names.join(", ")); @@ -100,7 +100,7 @@ t("nothing found says so", () => { }); t("clearing the search brings the sections back", () => { type(""); - if (groups().length !== 2 || rows().length !== 45) throw new Error(`${groups().length} sections, ${rows().length} rows`); + if (groups().length !== 2 || rows().length !== 47) throw new Error(`${groups().length} sections, ${rows().length} rows`); }); t("Up and Down move through the rows, from the one picked", () => { @@ -329,8 +329,8 @@ t("Page Down, Page Up, Home and End move the highlight", () => { type(""); }); -t("other names: farsi, mandarin, chinese, castellano, हिंदी, Uzbek spellings, नेपाली", () => { - for (const [s, want] of [["farsi", "fa"], ["Farsi", "fa"], ["mandarin", "zh-Hans zh-Hant"], ["chinese", "zh-Hans zh-Hant"], ["castellano", "es"], ["हिंदी", "hi"], ["हिन्दी", "hi"], ["ozbek", "uz"], ["o'zbek", "uz"], ["oʻzbekcha", "uz"], ["ōzbekça", "uz"], ["ўзбекча", "uz"], ["uz", "uz"], ["नेपाली", "ne"], ["nepali", "ne"]]) { +t("other names: farsi, mandarin, chinese, castellano, हिंदी, Uzbek spellings, नेपाली, Azərbaycanca, Հայերեն", () => { + for (const [s, want] of [["farsi", "fa"], ["Farsi", "fa"], ["mandarin", "zh-Hans zh-Hant"], ["chinese", "zh-Hans zh-Hant"], ["castellano", "es"], ["हिंदी", "hi"], ["हिन्दी", "hi"], ["ozbek", "uz"], ["o'zbek", "uz"], ["oʻzbekcha", "uz"], ["ōzbekça", "uz"], ["ўзбекча", "uz"], ["uz", "uz"], ["नेपाली", "ne"], ["nepali", "ne"], ["azeri", "az"], ["azerbaycan", "az"], ["azərbaycanca", "az"], ["hayeren", "hy"], ["հայերեն", "hy"]]) { type(s); const got = ids().slice(0, want.split(" ").length).join(" "); if (got !== want) throw new Error(`"${s}" found ${ids().join(" ")}`); @@ -364,7 +364,7 @@ t("a language without an English name or a hello still shows, by its own name", if (!opened) throw new Error("the step didn't open"); const xx = list().querySelector('#lg-a [data-lang="xx"]'); if (!xx || xx.querySelector(".ln").textContent !== "Xxish" || xx.querySelector(".le")) throw new Error(xx?.outerHTML || "no row"); - if (list().querySelector("#lg-a .lsect").textContent !== "All languages · 41") throw new Error(list().querySelector("#lg-a .lsect").textContent); + if (list().querySelector("#lg-a .lsect").textContent !== "All languages · 43") throw new Error(list().querySelector("#lg-a .lsect").textContent); type("xxi"); if (ids().join() !== "xx") throw new Error("found " + ids()); type(""); diff --git a/tests/ui/langswitch.js b/tests/ui/langswitch.js index 3b36ea73f..85e09c1bf 100644 --- a/tests/ui/langswitch.js +++ b/tests/ui/langswitch.js @@ -62,7 +62,7 @@ t("every language comes from the host when picked, and shows", () => { if (document.documentElement.dir !== (rtlLang ? "rtl" : "ltr")) throw new Error(`${id}: dir is ${document.documentElement.dir}`); if (getComputedStyle(document.documentElement).getPropertyValue("--ui-font").includes("Geeza Pro") !== rtlLang) throw new Error(`${id}: Arabic script's fonts`); const font = getComputedStyle(document.documentElement).getPropertyValue("--ui-font"); - const want = { ja: "Hiragino Sans", ko: "Malgun Gothic", "zh-Hant": "PingFang TC", "zh-Hans": "PingFang SC", hi: "Kohinoor Devanagari", ne: "Kohinoor Devanagari", bn: "Kohinoor Bangla", ta: "Tamil Sangam MN", am: "Kefa", te: "Kohinoor Telugu", th: "Thonburi", lo: "Lao Sangam MN" }[id] || "PingFang SC"; + const want = { ja: "Hiragino Sans", ko: "Malgun Gothic", "zh-Hant": "PingFang TC", "zh-Hans": "PingFang SC", hy: "Mshtakan", hi: "Kohinoor Devanagari", ne: "Kohinoor Devanagari", bn: "Kohinoor Bangla", ta: "Tamil Sangam MN", am: "Kefa", te: "Kohinoor Telugu", th: "Thonburi", lo: "Lao Sangam MN" }[id] || "PingFang SC"; // Hindi, Nepali, Bengali and Tamil each with their own script's fonts, and only them. if (/^(hi|ne|bn|ta|te)$/.test(id) && !font.includes("Nirmala UI")) throw new Error(`${id}: no Nirmala UI in ${font}`); if (!/^(hi|ne|bn|ta|te)$/.test(id) && font.includes("Nirmala UI")) throw new Error(`${id}: Indian fonts in ${font}`); @@ -83,7 +83,7 @@ t("an answer for a language no longer picked changes nothing", () => { }); t("tags map to the languages Kiri has, as lang.rs maps them", () => { const want = { zh: "zh-Hans", "zh-CN": "zh-Hans", "zh-SG": "zh-Hans", "zh-Hans-HK": "zh-Hans", zh_TW: "zh-Hant", "zh-TW": "zh-Hant", "zh-HK": "zh-Hant", "zh-MO": "zh-Hant", "zh-Hant": "zh-Hant", "zh-Hant-CN": "zh-Hant", - zhx: "", in: "id", "in-ID": "id", "id-ID": "id", iw: "", "iw-IL": "", "ja-JP": "ja", "ko-KR": "ko", "ru-RU": "ru", uk: "uk", "uk-UA": "uk", uk_UA: "uk", hi: "hi", "hi-IN": "hi", ne: "ne", "ne-NP": "ne", ne_NP: "ne", "bn-IN": "bn", "bn-BD": "bn", "ta-IN": "ta", "ta-LK": "ta", "te-IN": "te", am: "am", "am-ET": "am", "th-TH": "th", "lo-LA": "lo", "ca-ES": "ca", "cs-CZ": "cs", "lt-LT": "lt", "hu-HU": "hu", "nb-NO": "nb", no: "nb", "nn-NO": "nb", "ro-RO": "ro", "sq-AL": "sq", "sl-SI": "sl", "fi-FI": "fi", "el-GR": "el", "bg-BG": "bg", "kk-KZ": "kk", uz: "uz", "uz-UZ": "uz", "uz-Latn-UZ": "uz", uz_UZ: "uz", "fa-IR": "fa", ckb: "ckb", "ku-Arab-IQ": "ckb", ku: "", "pl-PL": "pl", "tr-TR": "tr", "vi-VN": "vi", "it-CH": "it", "pt-PT": "pt-BR", "fr-CA": "fr", "en-GB": "en", nl: "", ar: "ar", "ar-SA": "ar", "ar-EG": "ar", ar_AE: "ar", arz: "", he: "" }; + zhx: "", in: "id", "in-ID": "id", "id-ID": "id", iw: "", "iw-IL": "", "ja-JP": "ja", "ko-KR": "ko", "ru-RU": "ru", uk: "uk", "uk-UA": "uk", uk_UA: "uk", hi: "hi", "hi-IN": "hi", ne: "ne", "ne-NP": "ne", ne_NP: "ne", "bn-IN": "bn", "bn-BD": "bn", "ta-IN": "ta", "ta-LK": "ta", "te-IN": "te", am: "am", "am-ET": "am", "th-TH": "th", "lo-LA": "lo", "ca-ES": "ca", "cs-CZ": "cs", "lt-LT": "lt", "hu-HU": "hu", "nb-NO": "nb", no: "nb", "nn-NO": "nb", "ro-RO": "ro", "sq-AL": "sq", "sl-SI": "sl", "fi-FI": "fi", "el-GR": "el", "bg-BG": "bg", "kk-KZ": "kk", uz: "uz", "uz-UZ": "uz", "uz-Latn-UZ": "uz", uz_UZ: "uz", az: "az", "az-AZ": "az", "az-Latn-AZ": "az", az_AZ: "az", hy: "hy", "hy-AM": "hy", hy_AM: "hy", "fa-IR": "fa", ckb: "ckb", "ku-Arab-IQ": "ckb", ku: "", "pl-PL": "pl", "tr-TR": "tr", "vi-VN": "vi", "it-CH": "it", "pt-PT": "pt-BR", "fr-CA": "fr", "en-GB": "en", nl: "", ar: "ar", "ar-SA": "ar", "ar-EG": "ar", ar_AE: "ar", arz: "", he: "" }; const bad = Object.entries(want).filter(([tag, id]) => langFor(tag) !== id).map(([tag, id]) => `${tag} → ${langFor(tag)}, not ${id}`); if (bad.length) throw new Error(bad.join("; ")); }); diff --git a/tests/ui/nav-beta-tag.js b/tests/ui/nav-beta-tag.js index 68b0e12f0..1e32b412c 100644 --- a/tests/ui/nav-beta-tag.js +++ b/tests/ui/nav-beta-tag.js @@ -1,5 +1,5 @@ // parity: macos windows linux -// The sidebar's Compose and USB entries, each with a two-digit count, in each of the 40 languages: both carry +// The sidebar's Compose and USB entries, each with a two-digit count, in each of the 42 languages: both carry // the plain outlined Beta tag in the language's word; the name is never cut by it; the tag is whole or hidden, // never clipped; no New tag is left. const R = []; diff --git a/tests/ui/routerports.js b/tests/ui/routerports.js index 619f3eddb..8cca9db8f 100644 --- a/tests/ui/routerports.js +++ b/tests/ui/routerports.js @@ -64,6 +64,22 @@ t("a router that couldn't start says its port is in use", () => { const n = document.querySelector("#content .rp-notes").textContent; if (!/off: port 80 is in use/.test(n) || /paused/.test(n)) throw new Error(n); }); +t("localUrl hides dead domain links when the router is off or paused, keeping published host ports", () => { + const ctr = { Id: "c1", Names: ["/web"], Image: "nginx:alpine", State: "running", Status: "Up 1m", Created: 1, + Ports: [{ IP: "0.0.0.0", PublicPort: 62720, PrivatePort: 80, Type: "tcp" }], Labels: {} }; + kiri.on({ type: "lists", containers: [ctr], images: [], volumes: [], networks: [] }); + show("containers"); + for (const state of [{ running: false, serving: false }, { running: true, serving: false }]) { + kiri.on(rpEvent(80, 443, { http: state })); + if (localUrl(ctr, "web") !== "") throw new Error("expected empty localUrl, got " + localUrl(ctr, "web")); + if (document.querySelector(".sub-addr") || document.querySelector('[data-open*="kiri.local"]')) throw new Error("dead domain link rendered"); + if (!document.querySelector("#content").textContent.includes("62720")) throw new Error("published host port missing"); + } + kiri.on(rpEvent(80, 443, { http: { running: true, serving: true } })); + if (!localUrl(ctr, "web").endsWith("web.kiri.localhost")) throw new Error("restored localUrl: " + localUrl(ctr, "web")); + if (!document.querySelector(".sub-addr")) throw new Error("domain link not restored"); + kiri.on({ type: "lists", containers: [], images: [], volumes: [], networks: [] }); +}); t("with no engine, the row says to start Kiri", () => { kiri.on({ type: "routerports", error: "connection refused" }); domains(); diff --git a/tests/ui/setup-langstep.js b/tests/ui/setup-langstep.js index b2e715140..1e23edcbc 100644 --- a/tests/ui/setup-langstep.js +++ b/tests/ui/setup-langstep.js @@ -41,13 +41,13 @@ t("the setup window asks with a search field, focused, and one list, not tiles", if (main().querySelector(".lhello").textContent !== "Hello!") throw new Error("hello: " + main().querySelector(".lhello").textContent); if (!(box(q()).bottom <= box(list()).top && box(list()).bottom <= box(document.getElementById("lang-go")).top)) throw new Error("not search, list, Continue"); }); -t("Suggested, then All languages · 40 by English name, as in the main window", () => { +t("Suggested, then All languages · 42 by English name, as in the main window", () => { const [sug, all] = groups(); if (sug?.querySelector(".lsect").textContent !== "Suggested") throw new Error(sug?.textContent.slice(0, 40)); if (ids(`#${sug.id}`).join(" ") !== "en de pt-BR es fr") throw new Error("suggested: " + ids(`#${sug.id}`).join(" ")); - if (all?.querySelector(".lsect").textContent !== "All languages · 40") throw new Error(all?.querySelector(".lsect").textContent); + if (all?.querySelector(".lsect").textContent !== "All languages · 42") throw new Error(all?.querySelector(".lsect").textContent); const got = rows(`#${all.id}`), names = got.map((r) => (r.querySelector(".le") || r.querySelector(".ln")).textContent); - if (got.length !== 40 || names.join() !== [...names].sort((a, b) => a.localeCompare(b, "en")).join()) throw new Error(names.join(", ")); + if (got.length !== 42 || names.join() !== [...names].sort((a, b) => a.localeCompare(b, "en")).join()) throw new Error(names.join(", ")); const de = list().querySelector('[data-lang="de"]'); if (de.querySelector(".ln").textContent !== "Deutsch" || de.querySelector(".le").textContent !== "German" || de.querySelector(".lh").textContent !== "Hallo") throw new Error(de.textContent); if (picked().join() !== "en") throw new Error("picked " + picked()); From 31cca962b2c8c42758b7922a7bd39b1736262d4f Mon Sep 17 00:00:00 2001 From: Precious Okwu <32944039+libracoder@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:23:21 +0100 Subject: [PATCH 156/157] Engine & CLI: restore missing unpacked layers, fix macOS k8s idle CPU (#989), and add kiri engine (#983) (#996) * Start: evict stale VmLink::layers cache and re-send missing unpacked layers * 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 | 307 ++++++++-- crates/kiri/src/daemon/vmlink.rs | 28 + 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 | 18 + tests/regressions.tsv | 4 + 14 files changed, 1241 insertions(+), 100 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 2e858e732..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(e) => crate::diag::warn!("Kubernetes service port not published", port = format!("{port}/{proto}"), error = e), + 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(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()?; @@ -4296,17 +4363,19 @@ 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")); - 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); @@ -4340,11 +4409,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 +10775,121 @@ 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")); + } + + /// 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 +/// `/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/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 ca598cdfa..fbf7863ae 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -13,6 +13,24 @@ 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 +- 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 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 From 14522dfc60ca9d9f56b49865885c107568aab77f Mon Sep 17 00:00:00 2001 From: Amir Husayn Panahifar Date: Fri, 27 Nov 2026 15:24:26 +0330 Subject: [PATCH 157/157] fix(linux): enforce enable_icc=false by isolating bridge ports com.docker.network.bridge.enable_icc=false was accepted and shown in inspect but never applied, so containers on the network still reached each other. Each container's host-side veth on such a network is now an isolated bridge port (IFLA_BRPORT_ISOLATED), set in the same netlink request that creates it, at start and on network connect. The gateway, embedded DNS, published ports and egress keep working. A value that is not a boolean is refused at network create, as Docker does. Refs #213 --- crates/kiri-init/src/linux/net.rs | 17 ++++++---- crates/kiri-init/src/linux/netlink.rs | 42 ++++++++++++++++++++++-- crates/kiri-proto/src/lib.rs | 4 +++ crates/kiri/src/daemon/engine.rs | 6 ++++ crates/kiri/src/daemon/network.rs | 46 ++++++++++++++++++++++++++- docs/fix-registry.md | 6 ++++ tests/e2e.sh | 13 ++++++++ tests/regressions.tsv | 2 ++ 8 files changed, 127 insertions(+), 9 deletions(-) diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index ecf418291..a090a7bc8 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -139,12 +139,17 @@ pub struct Plug { pub internal: bool, /// IPv6-only: no IPv4 address on the container or the bridge. pub no_ipv4: bool, + /// `com.docker.network.bridge.enable_icc=false`: the container's veth + /// is an isolated bridge port, so it reaches no other container on the + /// network, only the gateway and beyond. + pub no_icc: bool, } impl Plug { pub fn from_opts(opts: kiri_proto::StrList<'_>) -> Plug { use kiri_proto::net_opts as k; - Plug { internal: k::values(opts, k::INTERNAL).next().is_some(), no_ipv4: k::values(opts, k::NO_IPV4).next().is_some() } + let has = |key| k::values(opts, key).next().is_some(); + Plug { internal: has(k::INTERNAL), no_ipv4: has(k::NO_IPV4), no_icc: has(k::NO_ICC) } } } @@ -1408,7 +1413,7 @@ fn attach_with_ns( v6: Option, plug: Plug, ) -> io::Result<()> { - let Plug { internal, no_ipv4 } = plug; + let Plug { internal, no_ipv4, no_icc } = plug; let mac = Some(mac.unwrap_or_else(|| mac_for(ip))); let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?; let opened_ns; @@ -1424,7 +1429,7 @@ fn attach_with_ns( let host = bridges.route_nl()?; // A stopped container's veth may still hold this address and MAC. delete_retired(host); - netlink::create_veth(host, host_ifname, bridge_index, netns, CONTAINER_MTU, &ifname, mac)?; + netlink::create_veth(host, host_ifname, bridge_index, netns, CONTAINER_MTU, &ifname, mac, no_icc)?; } // Enter the container's network namespace once to resolve the peer index, // disable IPv6 link-local when IPv6 is off, and open the inner route socket. @@ -1581,10 +1586,10 @@ mod tests { #[test] fn internal_networks_are_no_uplink() { let v6 = Some(Ip6 { ip: [0xfd; 16], prefix: 64, gateway: [0xfd; 16] }); - assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, no_ipv4: false }), None); + assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, ..Plug::default() }), None); let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], None, Plug::default()).unwrap(); assert_eq!((u.ifname.as_str(), u.v4, u.v6), ("eth1", Some([10, 0, 0, 1]), None)); - let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { internal: false, no_ipv4: true }).unwrap(); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { no_ipv4: true, ..Plug::default() }).unwrap(); assert_eq!((u.v4, u.v6), (None, Some([0xfd; 16]))); } @@ -1604,7 +1609,7 @@ mod tests { let mut ups = Vec::new(); ups.extend(Uplink::of("kva0", "eth0", gw_a, None, Plug::default())); // An internal network attached in between produces no uplink. - ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, no_ipv4: false })); + ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, ..Plug::default() })); ups.extend(Uplink::of("kxz2", "eth2", gw_zeta, None, Plug::default())); ups.extend(Uplink::of("kxb3", "eth3", gw_beta, None, Plug::default())); diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 91736467f..663787a34 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -28,6 +28,9 @@ const IFLA_LINKINFO: u16 = 18; const IFLA_NET_NS_FD: u16 = 28; const IFLA_INFO_KIND: u16 = 1; const IFLA_INFO_DATA: u16 = 2; +const IFLA_INFO_SLAVE_KIND: u16 = 4; +const IFLA_INFO_SLAVE_DATA: u16 = 5; +const IFLA_BRPORT_ISOLATED: u16 = 33; const VETH_INFO_PEER: u16 = 1; const IFA_ADDRESS: u16 = 1; const IFA_LOCAL: u16 = 2; @@ -290,7 +293,10 @@ fn random_bytes() -> [u8; 6] { /// peer is created straight inside `netns` as `peer`. The kernel picks the /// peer's interface index: a new namespace is not always only lo (with ipip /// or gre loaded it has tunl0, gre0 … too), so it is looked up by name. -pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std::fs::File, mtu: u32, peer: &str, peer_mac: Option<[u8; 6]>) -> io::Result<()> { +/// With `isolated` the host side becomes an isolated bridge port in the same +/// request, before the container runs. +#[allow(clippy::too_many_arguments)] +pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std::fs::File, mtu: u32, peer: &str, peer_mac: Option<[u8; 6]>, isolated: bool) -> io::Result<()> { let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); m.raw(&ifinfo(0, libc::IFF_UP as u32, libc::IFF_UP as u32)).attr_str(IFLA_IFNAME, host).attr_u32(IFLA_MASTER, bridge_index as u32); m.attr_u32(IFLA_MTU, mtu); @@ -301,7 +307,24 @@ pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std: m.attr(IFLA_ADDRESS, &mac); } m.end().end().end(); - nl.request(&mut [m]) + if isolated { + nl.request(&mut [m, isolate_port_msg(host)]) + } else { + nl.request(&mut [m]) + } +} + +/// `ip link set dev type bridge_slave isolated on`: the bridge port +/// forwards nothing to another isolated port, so containers on the same +/// network cannot reach each other (Docker's `enable_icc=false`), while the +/// bridge itself (the gateway, DNS, published ports, egress) still can. +fn isolate_port_msg(name: &str) -> Msg { + let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); + m.raw(&ifinfo(0, 0, 0)).attr_str(IFLA_IFNAME, name); + m.nest(IFLA_LINKINFO).attr_str(IFLA_INFO_SLAVE_KIND, "bridge"); + m.nest(IFLA_INFO_SLAVE_DATA).attr(IFLA_BRPORT_ISOLATED, &[1]); + m.end().end(); + m } pub fn delete_link(nl: &mut Netlink, name: &str) -> io::Result<()> { @@ -1733,6 +1756,21 @@ mod tests { u32::from_be_bytes(d.try_into().unwrap()) } + /// `enable_icc=false` (#213): the host-side veth, found by name, gets + /// the bridge's port attribute `isolated` set, as + /// `ip link set dev kv1 type bridge_slave isolated on` sends it. + #[test] + fn isolate_port_marks_the_veth_an_isolated_bridge_port() { + let m = isolate_port_msg("kv1"); + assert_eq!(u16::from_ne_bytes([m.buf[4], m.buf[5]]), RTM_NEWLINK); + // nlmsghdr (16) + ifinfomsg (16), then the attributes. + let top = attrs(&m.buf[32..]); + assert_eq!(get(&top, IFLA_IFNAME), b"kv1\0"); + let info = attrs(get(&top, IFLA_LINKINFO)); + assert_eq!(get(&info, IFLA_INFO_SLAVE_KIND), b"bridge\0"); + assert_eq!(attrs(get(&info, IFLA_INFO_SLAVE_DATA)), vec![(IFLA_BRPORT_ISOLATED, &[1u8][..])]); + } + /// The embedded DNS's redirect in a container's namespace: its own /// table (an engine inside the container replaces `kiri`), one output /// nat chain emptied first, and UDP/TCP rules that send 127.0.0.11:53 to diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index c49234412..359d79d31 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -561,6 +561,10 @@ pub mod net_opts { /// only the name the guest keeps it by: neither it nor the bridge gets /// one, and DNS has no A record for it. pub const NO_IPV4: &str = "noipv4"; + /// `noicc=1`: the network has `com.docker.network.bridge.enable_icc=false`: + /// the container's bridge port is isolated, so it reaches no other + /// container on that network (#213). + pub const NO_ICC: &str = "noicc"; /// `dnsbridge=kiri3`, one per network: a user network the container /// joins once it runs (`NetAttach`). Its embedded DNS answers that /// network's names from the start, as Docker's does with every network diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 2c693bb95..31cfa286e 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -4281,6 +4281,9 @@ impl Engine { if n.no_ipv4 { net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if n.icc_disabled() { + net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_ICC)); + } net6_opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, n.name)); } Err(e) => { @@ -5288,6 +5291,9 @@ impl Engine { if net.no_ipv4 { opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if net.icc_disabled() { + opts.push(format!("{}=1", kiri_proto::net_opts::NO_ICC)); + } opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, net.name)); if let Err(e) = vm.net_attach(id, n, &net.bridge, ip, net.prefix, net.gateway, &names, &opts) { self.release_attached_ips(&net.name, Some(ip), ip6); diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index 216666d01..703b6d8a7 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -180,6 +180,12 @@ impl Network { matches!(self.name.as_str(), "bridge" | "host" | "none") } + /// `--opt com.docker.network.bridge.enable_icc=false`: containers on + /// this network cannot reach each other (#213). + pub fn icc_disabled(&self) -> bool { + self.options.get(ENABLE_ICC_OPT).and_then(|v| v.as_str()).and_then(parse_go_bool) == Some(false) + } + /// Docker's `"172.17.0.0/16"`. pub fn subnet_str(&self) -> String { format!("{}/{}", ip_str(self.subnet), self.prefix) @@ -371,10 +377,31 @@ fn builtin(name: &str, driver: &str, bridge: &str, subnet: [u8; 4], gateway: [u8 /// than reported and not applied. pub const BRIDGE_NAME_OPT: &str = "com.docker.network.bridge.name"; +/// `--opt com.docker.network.bridge.enable_icc=false`: no traffic between +/// the network's containers, enforced by isolating each one's bridge port. +pub const ENABLE_ICC_OPT: &str = "com.docker.network.bridge.enable_icc"; + +/// A boolean as Go's `strconv.ParseBool` reads it, as Docker reads bridge +/// options. +fn parse_go_bool(s: &str) -> Option { + match s { + "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true), + "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false), + _ => None, + } +} + /// The options a network keeps, or why one of them cannot be applied. An -/// empty bridge name is Docker's "unset" and is dropped. +/// empty bridge name is Docker's "unset" and is dropped. An `enable_icc` +/// that is not a boolean is refused, as Docker does, rather than left to +/// mean the containers may reach each other. fn checked_options(options: serde_json::Value) -> Result { let serde_json::Value::Object(mut map) = options else { return Ok(serde_json::json!({})) }; + if let Some(v) = map.get(ENABLE_ICC_OPT) + && v.as_str().and_then(parse_go_bool).is_none() + { + return Err(format!("invalid value {v} for the network option {ENABLE_ICC_OPT}: expected true or false")); + } match map.get(BRIDGE_NAME_OPT).map(|v| v.as_str().unwrap_or("?")) { None => {} Some("") => { @@ -1379,6 +1406,23 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// `enable_icc` reads as Docker reads it: false in any of Go's + /// spellings turns container-to-container traffic off, and a value + /// that is no boolean is refused instead of leaving it on (#213). + #[test] + fn enable_icc_false_is_read_and_a_bad_value_refused() { + let (mut n, dir) = nets(); + let opts = |v: &str| Settings { options: serde_json::json!({ENABLE_ICC_OPT: v}), ..Default::default() }; + assert!(n.create("iccoff", opts("false")).unwrap().icc_disabled()); + assert!(n.create("iccoff0", opts("0")).unwrap().icc_disabled()); + assert!(!n.create("iccon", opts("true")).unwrap().icc_disabled()); + assert!(!n.create("plain", Settings::default()).unwrap().icc_disabled()); + let e = n.create("iccbad", opts("no")).unwrap_err(); + assert!(e.contains("invalid value \"no\" for the network option com.docker.network.bridge.enable_icc"), "{e}"); + assert!(n.find("iccbad").is_none(), "nothing made"); + let _ = std::fs::remove_dir_all(dir); + } + fn v6(ipam6: Option) -> Settings { Settings { labels: serde_json::json!({}), ipv6: true, ipam6, ..Default::default() } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index fbf7863ae..ee9d57774 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 +### Networks: enforce `com.docker.network.bridge.enable_icc=false` by isolating each container's bridge port (unreleased) +- Fixes: #213 `enable_icc=false` was accepted but not enforced: containers on the same user-defined network still reached each other +- Caused: none known +- Caused by: - +- Check: `icc-off-no-peer`, `icc-off-connect-no-peer`, `crates/kiri/src/daemon/network.rs`, `crates/kiri-init/src/linux/netlink.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/tests/e2e.sh b/tests/e2e.sh index fa69170a2..0cc8b772b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -775,6 +775,19 @@ t ipam-bad-gateway "no matching subnet for gateway" $D network create --subnet 1 t bridge-name-refused "does not support the network option com.docker.network.bridge.name" $D network create -o com.docker.network.bridge.name=cp-isolated --subnet 10.234.0.0/24 bridgename code bridge-name-nothing-made 1 $D network inspect bridgename t bridge-name-empty "map[]" bash -c "$D network create -o com.docker.network.bridge.name= bridgename >/dev/null && $D network inspect -f '{{.Options}}' bridgename; $D network rm bridgename >/dev/null" +# enable_icc=false: the network's containers don't reach each other, joined +# at start or by network connect (each is an isolated bridge port), while the +# gateway's DNS still names them. A value that is no boolean is refused (#213). +$D network create -o com.docker.network.bridge.enable_icc=false noicc >/dev/null +$D run -d --name noiccweb --network noicc nginx:alpine >/dev/null +nginx_up noiccweb +t icc-off-no-peer "blocked" $D run --rm --network noicc alpine sh -c 'wget -qO- -T 3 http://noiccweb >/dev/null 2>&1 && echo reached || echo blocked' +t icc-off-names "$(ipon noiccweb noicc)" $D run --rm --network noicc alpine sh -c 'getent hosts noiccweb | cut -d" " -f1' +$D run -d --name noiccjoin alpine sleep 300 >/dev/null +$D network connect noicc noiccjoin +t icc-off-connect-no-peer "blocked" $D exec noiccjoin sh -c "wget -qO- -T 3 http://$(ipon noiccweb noicc) >/dev/null 2>&1 && echo reached || echo blocked" +t icc-off-bad-value "invalid value \"no\" for the network option com.docker.network.bridge.enable_icc" $D network create -o com.docker.network.bridge.enable_icc=no noiccbad +$D rm -f noiccweb noiccjoin >/dev/null; $D network rm noicc >/dev/null # Fixed addresses (--ip, Compose ipv4_address) and MAC addresses. $D run -d --name fixed --network ipamnet --ip 10.231.0.10 --mac-address 02:42:0a:e7:00:0a nginx:alpine >/dev/null t static-ip "10.231.0.10" $D inspect -f '{{.NetworkSettings.Networks.ipamnet.IPAddress}}' fixed diff --git a/tests/regressions.tsv b/tests/regressions.tsv index d67e3c667..0b39a8846 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -376,3 +376,5 @@ 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 +icc-off-no-peer #213 com.docker.network.bridge.enable_icc=false was accepted but not enforced: containers on the network still reached each other +icc-off-connect-no-peer #213 a container joined by network connect to an enable_icc=false network still reached the others on it