[tests] Ports and Caddy: test ports come from outside the ephemeral range, and a Caddy start that does not come up is retried
This commit is contained in:
@@ -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::<u16>().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<Vec<u16>> = 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;
|
||||
|
||||
Reference in New Issue
Block a user