Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to use a provided name server order #1766

Merged
merged 5 commits into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions crates/resolver/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,25 @@ impl Default for LookupIpStrategy {
}
}

/// The strategy for establishing the query order of name servers in a pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde-config", derive(Serialize, Deserialize))]
pub enum ServerOrderingStrategy {
/// Servers are ordered based on collected query statistics. The ordering
/// may vary over time.
Default,
/// The order provided to the resolver is used. The ordering does not vary
/// over time.
Strict,
djc marked this conversation as resolved.
Show resolved Hide resolved
}

impl Default for ServerOrderingStrategy {
/// Returns [`ServerOrderingStrategy::Default`] as the default.
fn default() -> Self {
Self::Default
}
}

/// Configuration for the Resolver
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(
Expand Down Expand Up @@ -797,6 +816,8 @@ pub struct ResolverOpts {
pub preserve_intermediates: bool,
/// Try queries over TCP if they fail over UDP.
pub try_tcp_on_error: bool,
/// The server ordering strategy that the resolver should use.
pub server_ordering_strategy: ServerOrderingStrategy,
}

impl Default for ResolverOpts {
Expand Down Expand Up @@ -825,6 +846,7 @@ impl Default for ResolverOpts {
preserve_intermediates: true,

try_tcp_on_error: false,
server_ordering_strategy: ServerOrderingStrategy::default(),
}
}
}
Expand Down
13 changes: 8 additions & 5 deletions crates/resolver/src/name_server/name_server_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use proto::xfer::{DnsHandle, DnsRequest, DnsResponse, FirstAnswer};
use proto::Time;
use tracing::debug;

use crate::config::{ResolverConfig, ResolverOpts};
use crate::config::{ResolverConfig, ResolverOpts, ServerOrderingStrategy};
use crate::error::{ResolveError, ResolveErrorKind};
#[cfg(feature = "mdns")]
use crate::name_server;
Expand Down Expand Up @@ -180,10 +180,13 @@ where
) -> Result<DnsResponse, ResolveError> {
let mut conns: Vec<NameServer<C, P>> = conns.to_vec();

// select the highest priority connection
// reorder the connections based on current view...
// this reorders the inner set
conns.sort_unstable();
match opts.server_ordering_strategy {
// select the highest priority connection
// reorder the connections based on current view...
// this reorders the inner set
ServerOrderingStrategy::Default => conns.sort_unstable(),
ServerOrderingStrategy::Strict => {}
}
let request_loop = request.clone();

parallel_conn_loop(conns, request_loop, opts).await
Expand Down
84 changes: 80 additions & 4 deletions tests/integration-tests/tests/name_server_pool_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use trust_dns_resolver::config::*;
use trust_dns_resolver::error::ResolveError;
use trust_dns_resolver::name_server::{ConnectionProvider, NameServer, NameServerPool};

const DEFAULT_SERVER_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

#[derive(Clone)]
struct MockConnProvider<O: OnSend> {
on_send: O,
Expand Down Expand Up @@ -54,7 +56,16 @@ fn mock_nameserver(
messages: Vec<Result<DnsResponse, ResolveError>>,
options: ResolverOpts,
) -> MockedNameServer<DefaultOnSend> {
mock_nameserver_on_send_nx(messages, options, DefaultOnSend, false)
mock_nameserver_on_send_nx(messages, options, DefaultOnSend, DEFAULT_SERVER_ADDR, false)
}

#[cfg(test)]
fn mock_nameserver_with_addr(
messages: Vec<Result<DnsResponse, ResolveError>>,
addr: IpAddr,
options: ResolverOpts,
) -> MockedNameServer<DefaultOnSend> {
mock_nameserver_on_send_nx(messages, options, DefaultOnSend, addr, false)
}

#[cfg(test)]
Expand All @@ -63,7 +74,13 @@ fn mock_nameserver_trust_nx(
options: ResolverOpts,
trust_nx_responses: bool,
) -> MockedNameServer<DefaultOnSend> {
mock_nameserver_on_send_nx(messages, options, DefaultOnSend, trust_nx_responses)
mock_nameserver_on_send_nx(
messages,
options,
DefaultOnSend,
DEFAULT_SERVER_ADDR,
trust_nx_responses,
)
}

#[cfg(test)]
Expand All @@ -72,14 +89,15 @@ fn mock_nameserver_on_send<O: OnSend + Unpin>(
options: ResolverOpts,
on_send: O,
) -> MockedNameServer<O> {
mock_nameserver_on_send_nx(messages, options, on_send, false)
mock_nameserver_on_send_nx(messages, options, on_send, DEFAULT_SERVER_ADDR, false)
}

#[cfg(test)]
fn mock_nameserver_on_send_nx<O: OnSend + Unpin>(
messages: Vec<Result<DnsResponse, ResolveError>>,
options: ResolverOpts,
on_send: O,
addr: IpAddr,
trust_nx_responses: bool,
) -> MockedNameServer<O> {
let conn_provider = MockConnProvider {
Expand All @@ -89,7 +107,7 @@ fn mock_nameserver_on_send_nx<O: OnSend + Unpin>(

NameServer::from_conn(
NameServerConfig {
socket_addr: SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 0),
socket_addr: SocketAddr::new(addr, 0),
protocol: Protocol::Udp,
tls_dns_name: None,
trust_nx_responses,
Expand Down Expand Up @@ -435,6 +453,64 @@ fn test_distrust_nx_responses() {
}
}

#[test]
fn test_strict_server_order() {
use trust_dns_proto::rr::Record;

let mut options = ResolverOpts::default();

options.num_concurrent_reqs = 1;
options.server_ordering_strategy = ServerOrderingStrategy::Strict;

let query = Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A);

let preferred_record = v4_record(query.name().clone(), Ipv4Addr::new(127, 0, 0, 1));
let secondary_record = v4_record(query.name().clone(), Ipv4Addr::new(127, 0, 0, 2));

let preferred_server_records = vec![preferred_record; 10];
let secondary_server_records = vec![secondary_record; 10];

let to_dns_response = |records: Vec<Record>| -> Vec<Result<DnsResponse, ResolveError>> {
records
.iter()
.map(|record| Ok(message(query.clone(), vec![record.clone()], vec![], vec![]).into()))
.collect()
};

// Specify different IP addresses for each name server to ensure that they
// are considered separately.
let preferred_nameserver = mock_nameserver_with_addr(
to_dns_response(preferred_server_records.clone()),
Ipv4Addr::new(128, 0, 0, 1).into(),
Default::default(),
);
let secondary_nameserver = mock_nameserver_with_addr(
to_dns_response(secondary_server_records.clone()),
Ipv4Addr::new(129, 0, 0, 1).into(),
Default::default(),
);

let mut pool = mock_nameserver_pool(
vec![preferred_nameserver, secondary_nameserver],
vec![],
None,
options,
);

// The returned records should consistently be from the preferred name
// server until the configured records are exhausted. Subsequently, the
// secondary server should be used.
preferred_server_records.into_iter().chain(secondary_server_records.into_iter()).for_each(
|expected_record| {
let request = message(query.clone(), vec![], vec![], vec![]);
let future = pool.send(request).first_answer();

let response = block_on(future).unwrap();
assert_eq!(response.answers()[0], expected_record);
},
);
}

#[test]
fn test_return_error_from_highest_priority_nameserver() {
use trust_dns_proto::op::ResponseCode;
Expand Down