[edge] Resolver, tests first: hung name lookups pin at most a bounded number of their own threads, concurrent lookups of one name share one, and the rest fail at once (red: one blocking-pool task per request, as before)
This commit is contained in:
@@ -22,6 +22,7 @@ pub mod http_app;
|
|||||||
pub mod logging;
|
pub mod logging;
|
||||||
pub mod pages;
|
pub mod pages;
|
||||||
pub mod proxy;
|
pub mod proxy;
|
||||||
|
pub mod resolver;
|
||||||
pub mod runtime;
|
pub mod runtime;
|
||||||
pub mod secrets;
|
pub mod secrets;
|
||||||
pub mod share;
|
pub mod share;
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Upstream name lookups with a bounded cost.
|
||||||
|
//!
|
||||||
|
//! The system resolver (`getaddrinfo`, which honours nsswitch and /etc/hosts like every other
|
||||||
|
//! program on the machine) blocks a thread, and a lookup cannot be cancelled: when a request
|
||||||
|
//! gives up after [`crate::runtime::RESOLVE_TIMEOUT`], the thread stays busy until glibc gives
|
||||||
|
//! up (by default 5 s × 2 attempts × each name server). Through tokio's blocking pool, a dead
|
||||||
|
//! name server and enough requests would pin every thread of that pool, which the rest of edge
|
||||||
|
//! shares (file reads, the admin socket).
|
||||||
|
//!
|
||||||
|
//! So lookups run on their own threads, at most [`MAX_LOOKUP_THREADS`] at a time, never on
|
||||||
|
//! tokio's pool; concurrent requests for one name share one lookup; and a request that would
|
||||||
|
//! need a thread past the limit fails at once (a 502, like a lookup that timed out) instead of
|
||||||
|
//! queueing. Nothing is cached: like Caddy, every connect resolves again.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::io;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
|
||||||
|
|
||||||
|
/// How many lookups may hold a thread at once.
|
||||||
|
pub const MAX_LOOKUP_THREADS: usize = 8;
|
||||||
|
|
||||||
|
type Lookup = dyn Fn(&str, u16) -> io::Result<Vec<SocketAddr>> + Send + Sync;
|
||||||
|
type Answer = Result<Arc<Vec<SocketAddr>>, (io::ErrorKind, String)>;
|
||||||
|
type Inflight = Mutex<HashMap<(String, u16), watch::Receiver<Option<Answer>>>>;
|
||||||
|
|
||||||
|
pub struct Resolver {
|
||||||
|
permits: Arc<Semaphore>,
|
||||||
|
inflight: Arc<Inflight>,
|
||||||
|
lookup: Arc<Lookup>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(m: &Inflight) -> MutexGuard<'_, HashMap<(String, u16), watch::Receiver<Option<Answer>>>> {
|
||||||
|
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The process-wide resolver over the system's `getaddrinfo`.
|
||||||
|
pub fn system() -> &'static Resolver {
|
||||||
|
static SYSTEM: std::sync::LazyLock<Resolver> = std::sync::LazyLock::new(|| {
|
||||||
|
Resolver::new(MAX_LOOKUP_THREADS, |host, port| {
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
|
(host, port).to_socket_addrs().map(Iterator::collect)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
&SYSTEM
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resolver {
|
||||||
|
pub fn new(
|
||||||
|
threads: usize,
|
||||||
|
lookup: impl Fn(&str, u16) -> io::Result<Vec<SocketAddr>> + Send + Sync + 'static,
|
||||||
|
) -> Resolver {
|
||||||
|
Resolver {
|
||||||
|
permits: Arc::new(Semaphore::new(threads)),
|
||||||
|
inflight: Arc::default(),
|
||||||
|
lookup: Arc::new(lookup),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Addresses for `host:port` in resolver order, within `deadline`. IP literals are not
|
||||||
|
/// looked up. Errors: `TimedOut` (the lookup may go on in the background, holding its
|
||||||
|
/// thread), `ResourceBusy` (every lookup thread is taken), `NotFound` (no address), or the
|
||||||
|
/// resolver's own error.
|
||||||
|
pub async fn resolve(
|
||||||
|
&self,
|
||||||
|
host: &str,
|
||||||
|
port: u16,
|
||||||
|
deadline: Duration,
|
||||||
|
) -> io::Result<Vec<SocketAddr>> {
|
||||||
|
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
||||||
|
return Ok(vec![SocketAddr::new(ip, port)]);
|
||||||
|
}
|
||||||
|
let mut rx = self.start_or_join(host, port)?;
|
||||||
|
let answer = match tokio::time::timeout(deadline, rx.wait_for(Option::is_some)).await {
|
||||||
|
Ok(Ok(v)) => v.clone(),
|
||||||
|
Ok(Err(_)) => {
|
||||||
|
return Err(io::Error::other(
|
||||||
|
"the name lookup thread ended without an answer",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::TimedOut,
|
||||||
|
format!("name lookup took longer than {deadline:?}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match answer {
|
||||||
|
Some(Ok(addrs)) if addrs.is_empty() => Err(io::Error::new(
|
||||||
|
io::ErrorKind::NotFound,
|
||||||
|
"name resolves to no address",
|
||||||
|
)),
|
||||||
|
Some(Ok(addrs)) => Ok(addrs.as_ref().clone()),
|
||||||
|
Some(Err((kind, msg))) => Err(io::Error::new(kind, msg)),
|
||||||
|
None => Err(io::Error::other("no answer")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lookup in flight for this name, or a new one on its own thread.
|
||||||
|
fn start_or_join(&self, host: &str, port: u16) -> io::Result<watch::Receiver<Option<Answer>>> {
|
||||||
|
// Not built yet (the red commit): one blocking-pool task per request, as before.
|
||||||
|
let _ = (&self.permits, &self.inflight);
|
||||||
|
let (tx, rx) = watch::channel(None);
|
||||||
|
let lookup = self.lookup.clone();
|
||||||
|
let host = host.to_owned();
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
let answer = lookup(&host, port)
|
||||||
|
.map(Arc::new)
|
||||||
|
.map_err(|e| (e.kind(), e.to_string()));
|
||||||
|
let _ = tx.send(Some(answer));
|
||||||
|
});
|
||||||
|
Ok(rx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
use std::sync::Condvar;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
/// A resolver whose lookups hang until the gate opens; counts the lookups started.
|
||||||
|
struct Hung {
|
||||||
|
started: Arc<AtomicUsize>,
|
||||||
|
gate: Arc<(Mutex<bool>, Condvar)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hung {
|
||||||
|
fn resolver(threads: usize) -> (Resolver, Hung) {
|
||||||
|
let started = Arc::new(AtomicUsize::new(0));
|
||||||
|
let gate = Arc::new((Mutex::new(false), Condvar::new()));
|
||||||
|
let (s, g) = (started.clone(), gate.clone());
|
||||||
|
let r = Resolver::new(threads, move |_, port| {
|
||||||
|
s.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let (m, cv) = &*g;
|
||||||
|
let mut open = m.lock().unwrap();
|
||||||
|
while !*open {
|
||||||
|
open = cv.wait(open).unwrap();
|
||||||
|
}
|
||||||
|
Ok(vec![SocketAddr::from(([127, 0, 0, 1], port))])
|
||||||
|
});
|
||||||
|
(r, Hung { started, gate })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open(&self) {
|
||||||
|
let (m, cv) = &*self.gate;
|
||||||
|
*m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
|
||||||
|
cv.notify_all();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failed assertion must not leave lookups hung (the runtime waits for them on drop).
|
||||||
|
impl Drop for Hung {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.open();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHORT: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn hung_lookups_pin_at_most_the_limit_and_the_rest_fail_at_once() {
|
||||||
|
let (r, hung) = Hung::resolver(2);
|
||||||
|
for name in ["a.test", "b.test"] {
|
||||||
|
let e = r.resolve(name, 80, SHORT).await.unwrap_err();
|
||||||
|
assert_eq!(e.kind(), io::ErrorKind::TimedOut, "{e}");
|
||||||
|
}
|
||||||
|
// Both threads are still stuck in the resolver: a third name fails without waiting.
|
||||||
|
let t = Instant::now();
|
||||||
|
let e = r
|
||||||
|
.resolve("c.test", 80, Duration::from_secs(5))
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(e.kind(), io::ErrorKind::ResourceBusy, "{e}");
|
||||||
|
assert!(t.elapsed() < Duration::from_secs(1), "{:?}", t.elapsed());
|
||||||
|
// A name already being looked up joins that lookup instead of taking a thread.
|
||||||
|
let e = r.resolve("A.test", 80, SHORT).await.unwrap_err();
|
||||||
|
assert_eq!(e.kind(), io::ErrorKind::TimedOut);
|
||||||
|
assert_eq!(hung.started.load(Ordering::SeqCst), 2);
|
||||||
|
|
||||||
|
// Once the resolver answers, the threads come back.
|
||||||
|
hung.open();
|
||||||
|
let mut ok = None;
|
||||||
|
for _ in 0..100 {
|
||||||
|
match r.resolve("c.test", 81, SHORT).await {
|
||||||
|
Ok(a) => {
|
||||||
|
ok = Some(a);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::ResourceBusy => {
|
||||||
|
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||||
|
}
|
||||||
|
Err(e) => panic!("{e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(ok.unwrap(), vec![SocketAddr::from(([127, 0, 0, 1], 81))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn concurrent_requests_for_one_name_share_one_lookup() {
|
||||||
|
let started = Arc::new(AtomicUsize::new(0));
|
||||||
|
let s = started.clone();
|
||||||
|
let r = Arc::new(Resolver::new(2, move |_, port| {
|
||||||
|
s.fetch_add(1, Ordering::SeqCst);
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
Ok(vec![SocketAddr::from(([192, 0, 2, 1], port))])
|
||||||
|
}));
|
||||||
|
let mut tasks = Vec::new();
|
||||||
|
for _ in 0..20 {
|
||||||
|
let r = r.clone();
|
||||||
|
tasks.push(tokio::spawn(async move {
|
||||||
|
r.resolve("shared.test", 443, Duration::from_secs(5)).await
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
for t in tasks {
|
||||||
|
assert_eq!(
|
||||||
|
t.await.unwrap().unwrap(),
|
||||||
|
vec![SocketAddr::from(([192, 0, 2, 1], 443))]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(started.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn literals_empty_answers_and_errors() {
|
||||||
|
let r = Resolver::new(1, |host, _| match host {
|
||||||
|
"empty.test" => Ok(vec![]),
|
||||||
|
_ => Err(io::Error::new(io::ErrorKind::NotFound, "no such host")),
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
r.resolve("::1", 8080, SHORT).await.unwrap(),
|
||||||
|
vec!["[::1]:8080".parse().unwrap()]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
r.resolve("empty.test", 80, SHORT).await.unwrap_err().kind(),
|
||||||
|
io::ErrorKind::NotFound
|
||||||
|
);
|
||||||
|
let e = r.resolve("gone.test", 80, SHORT).await.unwrap_err();
|
||||||
|
assert_eq!(e.kind(), io::ErrorKind::NotFound);
|
||||||
|
assert!(e.to_string().contains("no such host"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -235,54 +235,15 @@ pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3);
|
|||||||
impl UpstreamRt {
|
impl UpstreamRt {
|
||||||
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
|
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
|
||||||
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
|
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
|
||||||
/// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error.
|
/// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error; lookups run on their
|
||||||
|
/// own bounded threads ([`crate::resolver`]).
|
||||||
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
|
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
|
||||||
resolve_with(
|
crate::resolver::system()
|
||||||
&self.host,
|
.resolve(&self.host, self.port, RESOLVE_TIMEOUT)
|
||||||
self.port,
|
.await
|
||||||
RESOLVE_TIMEOUT,
|
|
||||||
|host, port| async move {
|
|
||||||
tokio::net::lookup_host((host.as_str(), port))
|
|
||||||
.await
|
|
||||||
.map(Iterator::collect)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested.
|
|
||||||
pub async fn resolve_with<F, Fut>(
|
|
||||||
host: &str,
|
|
||||||
port: u16,
|
|
||||||
deadline: Duration,
|
|
||||||
lookup: F,
|
|
||||||
) -> std::io::Result<Vec<SocketAddr>>
|
|
||||||
where
|
|
||||||
F: FnOnce(String, u16) -> Fut,
|
|
||||||
Fut: Future<Output = std::io::Result<Vec<SocketAddr>>>,
|
|
||||||
{
|
|
||||||
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
|
||||||
return Ok(vec![SocketAddr::new(ip, port)]);
|
|
||||||
}
|
|
||||||
let addrs = match tokio::time::timeout(deadline, lookup(host.to_owned(), port)).await {
|
|
||||||
Ok(r) => r?,
|
|
||||||
Err(_) => {
|
|
||||||
return Err(std::io::Error::new(
|
|
||||||
std::io::ErrorKind::TimedOut,
|
|
||||||
format!("name lookup took longer than {deadline:?}"),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if addrs.is_empty() {
|
|
||||||
return Err(std::io::Error::new(
|
|
||||||
std::io::ErrorKind::NotFound,
|
|
||||||
"name resolves to no address",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(addrs)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
||||||
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
@@ -498,46 +459,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod resolve_tests {
|
mod health_tests {
|
||||||
#![allow(clippy::unwrap_used)]
|
#![allow(clippy::unwrap_used)]
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn a_slow_resolver_times_out() {
|
|
||||||
let t = tokio::time::Instant::now();
|
|
||||||
let err = resolve_with("slow.test", 80, RESOLVE_TIMEOUT, |_, _| async {
|
|
||||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
|
||||||
Ok(vec!["127.0.0.1:80".parse().unwrap()])
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap_err();
|
|
||||||
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
|
|
||||||
assert_eq!(t.elapsed(), RESOLVE_TIMEOUT);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn a_prompt_resolver_and_ip_literals_pass() {
|
|
||||||
let a: SocketAddr = "127.0.0.1:80".parse().unwrap();
|
|
||||||
let got = resolve_with(
|
|
||||||
"ok.test",
|
|
||||||
80,
|
|
||||||
RESOLVE_TIMEOUT,
|
|
||||||
|_, _| async move { Ok(vec![a]) },
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(got.unwrap(), vec![a]);
|
|
||||||
let got = resolve_with("::1", 8080, RESOLVE_TIMEOUT, |_, _| async {
|
|
||||||
unreachable!("IP literals are not looked up")
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(got.unwrap(), vec!["[::1]:8080".parse().unwrap()]);
|
|
||||||
let got = resolve_with("empty.test", 80, RESOLVE_TIMEOUT, |_, _| async {
|
|
||||||
Ok(vec![])
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn health_records_keep_the_last_five() {
|
fn health_records_keep_the_last_five() {
|
||||||
let r = HealthRecord::default();
|
let r = HealthRecord::default();
|
||||||
|
|||||||
Reference in New Issue
Block a user