Builds: show steps of a running build with one bounded log reader (#923) (#949)

Co-authored-by: Arekatla Nishanth Chowdary <av.sc.u4aie23002@av.students.amrita.edu>
This commit is contained in:
Precious OkwuandArekatla Nishanth Chowdary authored and GitHub committed 2026-11-25 17:28:31 +01:00
1 parent 7a03a6be24
commit 143bc926e7
4 files changed
+123 -7

No files matched your search

+85 -4
View File
@@ -27,7 +27,7 @@ fn kiri_host() -> io::Result<String> {
Ok(format!("npipe://{}", crate::client::pipe().replace('\\', "/")))
}
fn buildx(args: &[&str]) -> io::Result<(String, String)> {
fn buildx_command(args: &[&str]) -> io::Result<Command> {
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<String> {
stderr_for(buildx_command(args)?, limit)
}
fn stderr_for(mut cmd: Command, limit: std::time::Duration) -> io::Result<String> {
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<Value> {
serde_json::Deserializer::from_str(s).into_iter::<Value>().map_while(Result::ok).collect()
@@ -133,8 +192,14 @@ pub fn detail(builder: &str, id: &str) -> io::Result<Value> {
}
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<String> = Vec::new();
let mut steps: HashMap<String, Value> = 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:
+4 -3
View File
@@ -6734,7 +6734,7 @@ const blSpan = (a, b) => (a && b ? Date.parse(b) - Date.parse(a) : a ? Date.now(
// 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 @@ window.kiri = {
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 @@ window.kiri = {
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;
+2
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2 and column 52.
+32
View File
@@ -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);