diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index ad29998..debfd83 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -224,8 +224,28 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target { } } -/// Start `caddy run` on a generated Caddy JSON. +/// Start `caddy run` on a generated Caddy JSON; a start that does not come up is retried +/// (twice), since a port can be briefly unavailable right after the previous server on it. pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target { + let mut last = String::new(); + for _ in 0..3 { + match try_start_caddy(env, name, caddy, json) { + Ok(t) => return t, + Err(e) => { + last = e; + std::thread::sleep(Duration::from_millis(500)); + } + } + } + panic!("{last}") +} + +fn try_start_caddy( + env: &Env, + name: &'static str, + caddy: &std::path::Path, + json: &str, +) -> Result { let v: serde_json::Value = serde_json::from_str(json).unwrap(); let servers = &v["apps"]["http"]["servers"]; let https: SocketAddr = servers["ianitor_https"]["listen"][0] @@ -252,18 +272,21 @@ pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: .stderr(Stdio::from(log)) .spawn() .expect("spawn caddy"); - let guard = ChildGuard(child); - if !wait_for_port(https, Duration::from_secs(20)) { + let mut guard = ChildGuard(child); + if !wait_for_port(https, Duration::from_secs(20)) + || !wait_for_port(http, Duration::from_secs(5)) + { + let _ = guard.0.kill(); + let _ = guard.0.wait(); let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default(); - panic!("caddy did not listen on {https}:\n{out}"); + return Err(format!("caddy did not listen on {https} / {http}:\n{out}")); } - assert!(wait_for_port(http, Duration::from_secs(5))); - Target { + Ok(Target { name, http, https, _guard: Guard::Caddy(guard), - } + }) } pub enum Action { diff --git a/tests/support/src/proc.rs b/tests/support/src/proc.rs index ece8f58..1f85fb4 100644 --- a/tests/support/src/proc.rs +++ b/tests/support/src/proc.rs @@ -10,17 +10,52 @@ use std::process::Child; use std::sync::atomic::{AtomicU32, Ordering}; use std::time::{Duration, Instant}; -/// A port on 127.0.0.1 that was free a moment ago, and never handed out before by this -/// process (parallel tests otherwise can get the same port and talk to each other's servers). +/// The kernel's ephemeral port range (ports it hands to `bind(:0)` and outgoing connections). +fn ephemeral_range() -> (u16, u16) { + std::fs::read_to_string("/proc/sys/net/ipv4/ip_local_port_range") + .ok() + .and_then(|s| { + let mut it = s.split_whitespace().filter_map(|x| x.parse::().ok()); + Some((it.next()?, it.next()?)) + }) + .unwrap_or((32768, 60999)) +} + +/// A port on 127.0.0.1 that is free now, never handed out before by this process, and (where +/// possible) outside the ephemeral range, so the kernel does not give it to another socket +/// between this call and the server binding it, or while a server restarts on it. pub fn free_port() -> u16 { static GIVEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let (low, high) = ephemeral_range(); + let (from, to) = if low > 12_000 { + (10_000u32, u32::from(low)) + } else { + (u32::from(high) + 1, 65_000) + }; + let seed = std::process::id().wrapping_mul(2_654_435_761) + ^ std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + let span = to.saturating_sub(from).max(1); + let mut given = GIVEN.lock().unwrap(); + for k in 0..span { + let port = (from + (seed.wrapping_add(k.wrapping_mul(7919))) % span) as u16; + if given.contains(&port) { + continue; + } + if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() { + given.push(port); + return port; + } + } + // Everything outside the ephemeral range is taken: fall back to the kernel's choice. loop { let port = std::net::TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() .unwrap() .port(); - let mut given = GIVEN.lock().unwrap(); if !given.contains(&port) { given.push(port); return port;