|
| 1 | +use async_trait::async_trait; |
| 2 | +use tracing::info; |
| 3 | +use trust_dns_resolver::TokioAsyncResolver; |
| 4 | + |
| 5 | +use super::*; |
| 6 | + |
| 7 | +#[derive(Debug, Clone, Deserialize)] |
| 8 | +pub struct DnsDiscoveryConfig { |
| 9 | + /// The port that monoliths should be listening on for load balancer connections. |
| 10 | + pub monolith_port: u16, |
| 11 | + /// The DNS server to query. Optional. If not provided, the system configuration will be used instead. |
| 12 | + pub dns_server: Option<String>, |
| 13 | + /// The A record to query. If using docker-compose, this should be the service name for the monolith. |
| 14 | + pub query: String, |
| 15 | +} |
| 16 | + |
| 17 | +pub struct DnsMonolithDiscoverer { |
| 18 | + config: DnsDiscoveryConfig, |
| 19 | +} |
| 20 | + |
| 21 | +impl DnsMonolithDiscoverer { |
| 22 | + pub fn new(config: DnsDiscoveryConfig) -> Self { |
| 23 | + info!( |
| 24 | + "Creating DnsMonolithDiscoverer, DNS server: {:?}", |
| 25 | + config.dns_server |
| 26 | + ); |
| 27 | + Self { config } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +#[async_trait] |
| 32 | +impl MonolithDiscoverer for DnsMonolithDiscoverer { |
| 33 | + async fn discover(&mut self) -> anyhow::Result<Vec<MonolithConnectionConfig>> { |
| 34 | + let resolver = |
| 35 | + TokioAsyncResolver::tokio_from_system_conf().expect("failed to create resolver"); |
| 36 | + |
| 37 | + let lookup = resolver.ipv4_lookup(&self.config.query).await?; |
| 38 | + let monoliths = lookup |
| 39 | + .iter() |
| 40 | + .map(|ip| MonolithConnectionConfig { |
| 41 | + host: HostOrIp::Ip(IpAddr::V4(*ip)), |
| 42 | + port: self.config.monolith_port, |
| 43 | + }) |
| 44 | + .collect::<Vec<_>>(); |
| 45 | + |
| 46 | + Ok(monoliths) |
| 47 | + } |
| 48 | + |
| 49 | + fn mode(&self) -> DiscoveryMode { |
| 50 | + DiscoveryMode::Polling(Duration::from_secs(10)) |
| 51 | + } |
| 52 | +} |
0 commit comments