diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index ddaa78c..d1c2c2a 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -218,16 +218,35 @@ fn route(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut BufRea match (m, action) { ("GET", "json") => return reply(w, container_inspect(engine, id), 200), ("POST", "start") => { + // An idle BuildKit container that Kiri paused itself counts + // as running: the next build resumes it. + match engine.with(id, |c| (c.status == Status::Running, c.paused && !super::engine::is_builder(c))) { + Ok((_, true)) => return reply(w, Err(Error::Conflict("cannot start a paused container, try unpause instead".into())), 204), + Ok((true, _)) => { + http::respond(w, 304, "", b"")?; + return Ok(Next::KeepAlive); + } + Err(e) => return reply(w, Err(e), 204), + _ => {} + } super::builder::before_start(engine, id); return reply(w, engine.start(id).map(|()| Value::Null), 204); } ("POST", "stop") => { let t = stop_timeout(req, engine, id); - return reply(w, engine.stop(id, t).map(|()| Value::Null), 204); + // The engine decides: a stop that only cancels a pending + // restart still changed something. + return match engine.stop(id, t) { + Ok(false) => { + http::respond(w, 304, "", b"")?; + Ok(Next::KeepAlive) + } + r => reply(w, r.map(|_| Value::Null), 204), + }; } ("POST", "restart") => { let t = stop_timeout(req, engine, id); - let r = engine.stop(id, t).and_then(|()| { + let r = engine.stop(id, t).and_then(|_| { // Wait for the exit to be recorded before starting again. engine.wait(id, "not-running")?; super::builder::before_start(engine, id); diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 86e1d35..f7085e2 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -352,6 +352,8 @@ pub struct Container { /// Set by `stop`/`kill`: no automatic restart until started again. pub stopped_by_user: bool, pub restart_count: u32, + /// Exited, with its restart policy about to start it again. + restart_pending: bool, /// How many times it has exited; `wait?condition=next-exit` waits for this to grow. exits: u64, /// Terminal size asked for before the process existed. @@ -1049,6 +1051,7 @@ impl Engine { vm_stopped: was_running || s.vm_stopped, stopped_by_user: s.stopped_by_user, restart_count: s.restart_count, + restart_pending: false, exits: 0, size: None, ip: None, @@ -1226,6 +1229,7 @@ impl Engine { if wants && !c.spec.auto_remove && !SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst) { let backoff = RESTART_BASE.saturating_mul(1 << c.restart_count.min(10)).min(RESTART_CAP); c.restart_count += 1; + c.restart_pending = true; restart_in = Some(backoff); } c.spec.auto_remove @@ -1266,8 +1270,10 @@ impl Engine { let _ = std::thread::Builder::new().name("kiri-restart".into()).spawn(move || { std::thread::sleep(delay); // Only if nobody stopped or removed it in the meantime. - let still_wanted = - me.lock().containers.get(&id).is_some_and(|c| c.status == Status::Exited && !c.stopped_by_user); + let still_wanted = me.lock().containers.get_mut(&id).is_some_and(|c| { + c.restart_pending = false; + c.status == Status::Exited && !c.stopped_by_user + }); if still_wanted { if let Err(e) = me.start_inner(&id, false) { crate::diag::warn!("container did not restart", id = &id[..12], error = format!("{e:?}")); @@ -1556,6 +1562,7 @@ impl Engine { vm_stopped: false, stopped_by_user: false, restart_count: 0, + restart_pending: false, exits: 0, size: None, ip: None, @@ -1606,6 +1613,7 @@ impl Engine { return Err(Error::BadRequest("no command specified".into())); } c.status = Status::Running; + c.restart_pending = false; c.started = Some(SystemTime::now()); c.finished = None; c.oom_killed = false; @@ -2622,12 +2630,14 @@ impl Engine { self.lock().containers.get(id).is_some_and(|c| c.paused) } - pub fn stop(&self, key: &str, timeout: Duration) -> Result<(), Error> { + /// `docker stop`. False when there was nothing to stop: the container + /// was not running and its restart policy was not about to start it. + pub fn stop(&self, key: &str, timeout: Duration) -> Result { let id = self.resolve(key)?; self.thaw_for_signal(&id); - self.mark_stopped(&id); + let cancelled = self.mark_stopped(&id); if !self.is_running(&id) { - return Ok(()); + return Ok(cancelled); } 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); @@ -2639,14 +2649,27 @@ impl Engine { if left.is_zero() { drop(st); self.vm()?.kill(&id, libc::SIGKILL as u32)?; + // Docker's stop response means the process has exited, even + // with t=0. Wait for its exit (or auto-removal) to be recorded, + // as long as `kill` does: the exit may never be reported. + let killed = std::time::Instant::now() + Duration::from_secs(10); + let mut exited = self.lock(); + while exited.containers.get(&id).is_some_and(|c| c.status == Status::Running) { + let left = killed.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return Err(Error::Io(io::Error::other(format!("cannot stop container: {}: it did not exit after SIGKILL", &id[..12])))); + } + exited = self.changed.wait_timeout(exited, left).unwrap_or_else(|e| e.into_inner()).0; + } + drop(exited); self.emit_container("stop", &id, &[]); - return Ok(()); + return Ok(true); } st = self.changed.wait_timeout(st, left).unwrap_or_else(|e| e.into_inner()).0; } drop(st); self.emit_container("stop", &id, &[]); - Ok(()) + Ok(true) } /// A frozen process cannot handle a signal; Docker thaws it first. @@ -2928,20 +2951,23 @@ impl Engine { self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running) } - fn mark_stopped(&self, id: &str) { - let persist = { + /// 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 { + let (persist, cancelled) = { let mut st = self.lock(); match st.containers.get_mut(id) { Some(c) => { c.stopped_by_user = true; - !c.spec.auto_remove + (!c.spec.auto_remove, std::mem::take(&mut c.restart_pending)) } - None => false, + None => (false, false), } }; if persist { self.save(); } + cancelled } /// Runs `f` over every container, under the lock. @@ -3071,7 +3097,7 @@ fn note_removed(st: &mut State, id: &str, code: i32) { } /// A BuildKit daemon that buildx runs for its docker-container driver. -fn is_builder(c: &Container) -> bool { +pub fn is_builder(c: &Container) -> bool { c.name.starts_with("buildx_buildkit_") } diff --git a/tests/e2e.sh b/tests/e2e.sh index e3f2bee..df1050d 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -93,6 +93,7 @@ t rmi "Untagged" $D rmi alpine:3.21 code rmi-missing 1 $D rmi alpine:3.21 section "run: output and exit codes" +code lifecycle-response-status 0 python3 "$(dirname "$0")/lifecycle-status.py" "$SOCK" alpine t echo "hello" $D run --rm alpine echo hello t args "a b c" $D run --rm alpine echo a b c code exit-0 0 $D run --rm alpine true diff --git a/tests/lifecycle-status.py b/tests/lifecycle-status.py new file mode 100644 index 0000000..6eae36a --- /dev/null +++ b/tests/lifecycle-status.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Check idempotent start/stop and process exit before a zero-timeout stop returns.""" +import http.client +import json +import socket +import sys +import time + + +class Connection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=10) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX) + self.sock.settimeout(self.timeout) + self.sock.connect(self.path) + + +def check(path, image): + owned = [] + + def request(method, target, expected, body=None): + connection = Connection(path) + try: + connection.request(method, "/v1.47" + target, None if body is None else json.dumps(body), + {"Content-Type": "application/json"}) + response = connection.getresponse() + data = response.read() + assert response.status in expected, (method, target, response.status, data) + return response.status, json.loads(data) if data else None + finally: + connection.close() + + try: + _, created = request("POST", "/containers/create", (201,), + {"Image": image, "Cmd": ["sleep", "120"], "HostConfig": {"NetworkMode": "none"}}) + cid = created["Id"] + owned.append(cid) + for _ in range(10): + request("POST", "/containers/" + cid + "/start", (204,)) + request("POST", "/containers/" + cid + "/start", (304,)) + request("POST", "/containers/" + cid + "/stop?t=0", (204,)) + _, state = request("GET", "/containers/" + cid + "/json", (200,)) + assert not state["State"]["Running"], state["State"] + request("POST", "/containers/" + cid + "/stop?t=0", (304,)) + print("PASS ten start/stop cycles and immediate exit inspection", flush=True) + for _ in range(3): + _, created = request("POST", "/containers/create", (201,), + {"Image": image, "Cmd": ["sleep", "120"], "HostConfig": {"AutoRemove": True}}) + cid = created["Id"] + owned.append(cid) + request("POST", "/containers/" + cid + "/start", (204,)) + request("POST", "/containers/" + cid + "/stop?t=0", (204,)) + status, state = request("GET", "/containers/" + cid + "/json", (200, 404)) + assert status == 404 or not state["State"]["Running"], state + print("PASS three stops with automatic removal", flush=True) + + _, created = request("POST", "/containers/create", (201,), + {"Image": image, "Cmd": ["false"], + "HostConfig": {"NetworkMode": "none", "RestartPolicy": {"Name": "always"}}}) + cid = created["Id"] + owned.append(cid) + request("POST", "/containers/" + cid + "/start", (204,)) + # The delay before each restart doubles: after four of them the + # process has exited and the next restart is most of a second away. + deadline = time.monotonic() + 30 + while request("GET", "/containers/" + cid + "/json", (200,))[1]["RestartCount"] < 4: + assert time.monotonic() < deadline, "the container did not keep restarting" + time.sleep(0.05) + request("POST", "/containers/" + cid + "/stop?t=0", (204,)) + _, stopped = request("GET", "/containers/" + cid + "/json", (200,)) + assert not stopped["State"]["Running"] and not stopped["State"]["Restarting"], stopped["State"] + request("POST", "/containers/" + cid + "/stop?t=0", (304,)) + # Long enough for the restart that was pending to have happened. + time.sleep(3) + _, later = request("GET", "/containers/" + cid + "/json", (200,)) + assert not later["State"]["Running"] and not later["State"]["Restarting"], later["State"] + assert later["RestartCount"] == stopped["RestartCount"], (stopped["RestartCount"], later["RestartCount"]) + print("PASS stop cancels a pending restart", flush=True) + + _, created = request("POST", "/containers/create", (201,), + {"Image": image, "Cmd": ["sleep", "120"], "HostConfig": {"NetworkMode": "none"}}) + cid = created["Id"] + owned.append(cid) + request("POST", "/containers/" + cid + "/start", (204,)) + request("POST", "/containers/" + cid + "/pause", (204,)) + _, error = request("POST", "/containers/" + cid + "/start", (409,)) + assert error["message"] == "cannot start a paused container, try unpause instead", error + request("POST", "/containers/" + cid + "/unpause", (204,)) + request("POST", "/containers/" + cid + "/start", (304,)) + request("POST", "/containers/" + cid + "/pause", (204,)) + request("POST", "/containers/" + cid + "/stop?t=0", (204,)) + _, state = request("GET", "/containers/" + cid + "/json", (200,)) + assert not state["State"]["Running"] and not state["State"]["Paused"], state["State"] + print("PASS start and stop of a paused container", flush=True) + finally: + primary_failure = sys.exc_info()[0] is not None + errors = [] + for cid in reversed(owned): + try: + status, _ = request("DELETE", "/containers/" + cid + "?force=true", (204, 404, 409)) + if status == 409: + # AutoRemove can already be deleting this container. + # Wait on the engine's event instead of adding a sleep. + request("POST", "/containers/" + cid + "/wait?condition=removed", (200, 404)) + request("GET", "/containers/" + cid + "/json", (404,)) + except Exception as error: + errors.append(error) + print("Cleanup failed:", repr(error), file=sys.stderr) + if errors and not primary_failure: + raise RuntimeError("Could not remove all lifecycle-test containers") from errors[0] + + +if __name__ == "__main__": + check(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "alpine")