iroh_dns_server/
server.rs

1//! The main server which combines the DNS and HTTP(S) servers.
2use std::sync::Arc;
3
4use iroh_metrics::service::start_metrics_server;
5use n0_error::{Result, StdResultExt};
6use tracing::info;
7
8use crate::{
9    config::Config,
10    dns::{DnsHandler, DnsServer},
11    http::HttpServer,
12    metrics::Metrics,
13    state::AppState,
14    store::ZoneStore,
15};
16
17/// Spawn the server and run until the `Ctrl-C` signal is received, then shutdown.
18pub async fn run_with_config_until_ctrl_c(config: Config) -> Result<()> {
19    let metrics = Arc::new(Metrics::default());
20    let zone_store_options = config.zone_store.clone().unwrap_or_default();
21    let mut store = ZoneStore::persistent(
22        Config::signed_packet_store_path()?,
23        zone_store_options.into(),
24        metrics.clone(),
25    )?;
26    if let Some(bootstrap) = config.mainline_enabled() {
27        info!("mainline fallback enabled");
28        store = store.with_mainline_fallback(bootstrap);
29    };
30    let server = Server::spawn(config, store, metrics).await?;
31    tokio::signal::ctrl_c().await.anyerr()?;
32    info!("shutdown");
33    server.shutdown().await?;
34    Ok(())
35}
36
37/// The iroh-dns server.
38pub struct Server {
39    http_server: HttpServer,
40    dns_server: DnsServer,
41    metrics_task: tokio::task::JoinHandle<Result<()>>,
42}
43
44impl Server {
45    /// Spawn the server.
46    ///
47    /// This will spawn several background tasks:
48    /// * A DNS server task
49    /// * A HTTP server task, if `config.http` is not empty
50    /// * A HTTPS server task, if `config.https` is not empty
51    pub async fn spawn(config: Config, store: ZoneStore, metrics: Arc<Metrics>) -> Result<Self> {
52        let dns_handler = DnsHandler::new(store.clone(), &config.dns, metrics.clone())?;
53
54        let state = AppState {
55            store,
56            dns_handler,
57            metrics: metrics.clone(),
58        };
59
60        let metrics_addr = config.metrics_addr();
61        let metrics_task = tokio::task::spawn(async move {
62            if let Some(addr) = metrics_addr {
63                let mut registry = iroh_metrics::Registry::default();
64                registry.register(metrics);
65                start_metrics_server(addr, Arc::new(registry))
66                    .await
67                    .anyerr()?;
68            }
69            Ok(())
70        });
71        let http_server = HttpServer::spawn(
72            config.http,
73            config.https,
74            config.pkarr_put_rate_limit,
75            state.clone(),
76        )
77        .await?;
78        let dns_server = DnsServer::spawn(config.dns, state.dns_handler.clone()).await?;
79        Ok(Self {
80            http_server,
81            dns_server,
82            metrics_task,
83        })
84    }
85
86    /// Cancel the server tasks and wait for all tasks to complete.
87    pub async fn shutdown(self) -> Result<()> {
88        self.metrics_task.abort();
89        let (res1, res2) = tokio::join!(self.dns_server.shutdown(), self.http_server.shutdown(),);
90        res1?;
91        res2?;
92        Ok(())
93    }
94
95    /// Wait for all tasks to complete.
96    ///
97    /// This will run forever unless all tasks close with an error, or `Self::cancel` is called.
98    pub async fn run_until_error(self) -> Result<()> {
99        tokio::select! {
100            res = self.dns_server.run_until_done() => res?,
101            res = self.http_server.run_until_done() => res?,
102        }
103        self.metrics_task.abort();
104        Ok(())
105    }
106
107    /// Spawn a server suitable for testing.
108    ///
109    /// This will run the DNS and HTTP servers, but not the HTTPS server.
110    ///
111    /// It returns the server handle, the [`SocketAddr`] of the DNS server and the [`Url`] of the
112    /// HTTP server.
113    #[cfg(test)]
114    pub async fn spawn_for_tests() -> Result<(Self, std::net::SocketAddr, url::Url)> {
115        Self::spawn_for_tests_with_options(None, None).await
116    }
117
118    /// Spawn a server suitable for testing, while optionally enabling mainline with custom
119    /// bootstrap addresses.
120    #[cfg(test)]
121    pub async fn spawn_for_tests_with_options(
122        mainline: Option<crate::config::BootstrapOption>,
123        options: Option<crate::store::ZoneStoreOptions>,
124    ) -> Result<(Self, std::net::SocketAddr, url::Url)> {
125        use std::net::{IpAddr, Ipv4Addr};
126
127        use crate::config::MetricsConfig;
128
129        let mut config = Config::default();
130        config.dns.port = 0;
131        config.dns.bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
132        config.http.as_mut().unwrap().port = 0;
133        config.http.as_mut().unwrap().bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
134        config.https = None;
135        config.metrics = Some(MetricsConfig::disabled());
136
137        let mut store = ZoneStore::in_memory(options.unwrap_or_default(), Default::default())?;
138        if let Some(bootstrap) = mainline {
139            info!("mainline fallback enabled");
140            store = store.with_mainline_fallback(bootstrap);
141        }
142        let server = Self::spawn(config, store, Default::default()).await?;
143        let dns_addr = server.dns_server.local_addr();
144        let http_addr = server.http_server.http_addr().expect("http is set");
145        let http_url = format!("http://{http_addr}").parse::<url::Url>().anyerr()?;
146        Ok((server, dns_addr, http_url))
147    }
148}