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_snafu::{Result, ResultExt};
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.e()?;
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)).await.e()?;
66            }
67            Ok(())
68        });
69        let http_server = HttpServer::spawn(
70            config.http,
71            config.https,
72            config.pkarr_put_rate_limit,
73            state.clone(),
74        )
75        .await?;
76        let dns_server = DnsServer::spawn(config.dns, state.dns_handler.clone()).await?;
77        Ok(Self {
78            http_server,
79            dns_server,
80            metrics_task,
81        })
82    }
83
84    /// Cancel the server tasks and wait for all tasks to complete.
85    pub async fn shutdown(self) -> Result<()> {
86        self.metrics_task.abort();
87        let (res1, res2) = tokio::join!(self.dns_server.shutdown(), self.http_server.shutdown(),);
88        res1?;
89        res2?;
90        Ok(())
91    }
92
93    /// Wait for all tasks to complete.
94    ///
95    /// This will run forever unless all tasks close with an error, or `Self::cancel` is called.
96    pub async fn run_until_error(self) -> Result<()> {
97        tokio::select! {
98            res = self.dns_server.run_until_done() => res?,
99            res = self.http_server.run_until_done() => res?,
100        }
101        self.metrics_task.abort();
102        Ok(())
103    }
104
105    /// Spawn a server suitable for testing.
106    ///
107    /// This will run the DNS and HTTP servers, but not the HTTPS server.
108    ///
109    /// It returns the server handle, the [`SocketAddr`] of the DNS server and the [`Url`] of the
110    /// HTTP server.
111    #[cfg(test)]
112    pub async fn spawn_for_tests() -> Result<(Self, std::net::SocketAddr, url::Url)> {
113        Self::spawn_for_tests_with_options(None, None).await
114    }
115
116    /// Spawn a server suitable for testing, while optionally enabling mainline with custom
117    /// bootstrap addresses.
118    #[cfg(test)]
119    pub async fn spawn_for_tests_with_options(
120        mainline: Option<crate::config::BootstrapOption>,
121        options: Option<crate::store::ZoneStoreOptions>,
122    ) -> Result<(Self, std::net::SocketAddr, url::Url)> {
123        use std::net::{IpAddr, Ipv4Addr};
124
125        use crate::config::MetricsConfig;
126
127        let mut config = Config::default();
128        config.dns.port = 0;
129        config.dns.bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
130        config.http.as_mut().unwrap().port = 0;
131        config.http.as_mut().unwrap().bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
132        config.https = None;
133        config.metrics = Some(MetricsConfig::disabled());
134
135        let mut store = ZoneStore::in_memory(options.unwrap_or_default(), Default::default())?;
136        if let Some(bootstrap) = mainline {
137            info!("mainline fallback enabled");
138            store = store.with_mainline_fallback(bootstrap);
139        }
140        let server = Self::spawn(config, store, Default::default()).await?;
141        let dns_addr = server.dns_server.local_addr();
142        let http_addr = server.http_server.http_addr().expect("http is set");
143        let http_url = format!("http://{http_addr}").parse::<url::Url>().e()?;
144        Ok((server, dns_addr, http_url))
145    }
146}