Windows: resume containers with restart policies after WSL engine start (#395) (#845)

This commit is contained in:
Precious Okwu authored and GitHub committed 2026-11-24 05:29:21 +01:00
1 parent f0a87e0349
commit d0e1f8089a
6 files changed
+239 -18

No files matched your search

+4 -2
View File
@@ -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
+82 -2
View File
@@ -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);
+2 -5
View File
@@ -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"))
}
+135 -7
View File
@@ -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<Box<dyn Fn(&str) + Send + Sync>>,
/// 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<StartState>,
cv: Condvar,
}
@@ -324,7 +331,16 @@ struct StartState {
impl Starter {
fn new(socket: PathBuf, start: Box<dyn Fn(Instant) -> 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<Instant> = 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.
+6
View File
@@ -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
+10 -2
View File
@@ -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'