// 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> + Send + Sync; type Answer = Result>, (io::ErrorKind, String)>; type Waiters = HashMap<(String, u16), watch::Receiver>>; type Inflight = Mutex; pub struct Resolver { permits: Arc, inflight: Arc, lookup: Arc, } fn lock(m: &Inflight) -> MutexGuard<'_, Waiters> { 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 = 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> + 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> { if let Ok(ip) = host.parse::() { 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>> { let key = (host.to_ascii_lowercase(), port); let mut map = lock(&self.inflight); if let Some(rx) = map.get(&key) { return Ok(rx.clone()); } let permit: OwnedSemaphorePermit = self.permits.clone().try_acquire_owned().map_err(|_| { io::Error::new( io::ErrorKind::ResourceBusy, format!( "{MAX_LOOKUP_THREADS} name lookups are already waiting on the resolver" ), ) })?; let (tx, rx) = watch::channel(None); map.insert(key.clone(), rx.clone()); drop(map); let lookup = self.lookup.clone(); let inflight = self.inflight.clone(); let spawned = std::thread::Builder::new() .name("ianitor-dns".into()) .spawn({ let key = key.clone(); move || { let answer = lookup(&key.0, key.1) .map(Arc::new) .map_err(|e| (e.kind(), e.to_string())); let _ = tx.send(Some(answer)); lock(&inflight).remove(&key); drop(permit); } }); if let Err(e) = spawned { lock(&self.inflight).remove(&key); return Err(io::Error::other(format!( "cannot start a name lookup thread: {e}" ))); } 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, gate: Arc<(Mutex, 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); } /// QC phase 4 (nit): a lookup thread that panics must not leave its name stuck on a dead /// lookup; the next request for it starts a new one. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_panicking_lookup_does_not_poison_its_name() { let calls = Arc::new(AtomicUsize::new(0)); let c = calls.clone(); let r = Resolver::new(1, move |_, port| { if c.fetch_add(1, Ordering::SeqCst) == 0 { panic!("resolver library bug"); } Ok(vec![SocketAddr::from(([127, 0, 0, 1], port))]) }); assert!(r.resolve("flaky.test", 80, SHORT).await.is_err()); let mut got = None; for _ in 0..50 { match r.resolve("flaky.test", 80, SHORT).await { Ok(a) => { got = Some(a); break; } Err(_) => tokio::time::sleep(Duration::from_millis(20)).await, } } assert_eq!(got.unwrap(), vec![SocketAddr::from(([127, 0, 0, 1], 80))]); assert_eq!(calls.load(Ordering::SeqCst), 2); } #[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")); } }