Skip to content

Commit

Permalink
feat(tui): add dns-ttl flag (#1233)
Browse files Browse the repository at this point in the history
  • Loading branch information
fujiapple852 committed Jul 24, 2024
1 parent f553813 commit 143df5d
Show file tree
Hide file tree
Showing 16 changed files with 52 additions and 12 deletions.
3 changes: 1 addition & 2 deletions crates/trippy-tui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::geoip::GeoIpLookup;
use crate::{frontend, report};
use anyhow::{anyhow, Error};
use std::net::IpAddr;
use std::time::Duration;
use tracing_chrome::{ChromeLayerBuilder, FlushGuard};
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::layer::SubscriberExt;
Expand Down Expand Up @@ -136,7 +135,7 @@ fn start_dns_resolver(cfg: &TrippyConfig) -> anyhow::Result<DnsResolver> {
cfg.dns_resolve_method,
cfg.addr_family,
cfg.dns_timeout,
Duration::from_secs(300),
cfg.dns_ttl,
))?)
}

Expand Down
24 changes: 24 additions & 0 deletions crates/trippy-tui/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ pub struct TrippyConfig {
pub multipath_strategy: MultipathStrategy,
pub port_direction: PortDirection,
pub dns_timeout: Duration,
pub dns_ttl: Duration,
pub dns_resolve_method: ResolveMethod,
pub dns_lookup_as_info: bool,
pub max_samples: usize,
Expand Down Expand Up @@ -546,6 +547,11 @@ impl TrippyConfig {
cfg_file_dns.dns_timeout,
constants::DEFAULT_DNS_TIMEOUT,
);
let dns_ttl = cfg_layer(
args.dns_ttl,
cfg_file_dns.dns_ttl,
constants::DEFAULT_DNS_TTL,
);
let report_cycles = cfg_layer(
args.report_cycles,
cfg_file_report.report_cycles,
Expand Down Expand Up @@ -677,6 +683,7 @@ impl TrippyConfig {
interface,
port_direction,
dns_timeout,
dns_ttl,
dns_resolve_method,
dns_lookup_as_info,
max_samples,
Expand Down Expand Up @@ -729,6 +736,7 @@ impl Default for TrippyConfig {
multipath_strategy: defaults::DEFAULT_STRATEGY_MULTIPATH,
port_direction: PortDirection::None,
dns_timeout: constants::DEFAULT_DNS_TIMEOUT,
dns_ttl: constants::DEFAULT_DNS_TTL,
dns_resolve_method: dns_resolve_method(constants::DEFAULT_DNS_RESOLVE_METHOD),
dns_lookup_as_info: constants::DEFAULT_DNS_LOOKUP_AS_INFO,
max_samples: defaults::DEFAULT_MAX_SAMPLES,
Expand Down Expand Up @@ -1386,6 +1394,13 @@ mod tests {
compare(parse_config(cmd), expected);
}

#[test_case("trip example.com", Ok(cfg().dns_ttl(Duration::from_secs(300)).build()); "default dns ttl")]
#[test_case("trip example.com --dns-ttl 10secs", Ok(cfg().dns_ttl(Duration::from_secs(10)).build()); "custom dns ttl")]
#[test_case("trip example.com --dns-ttl 20", Err(anyhow!("error: invalid value '20' for '--dns-ttl <DNS_TTL>': time unit needed, for example 20sec or 20ms For more information, try '--help'.")); "invalid custom dns ttl")]
fn test_dns_ttl(cmd: &str, expected: anyhow::Result<TrippyConfig>) {
compare(parse_config(cmd), expected);
}

#[test_case("trip example.com", Ok(cfg().dns_resolve_method(ResolveMethod::System).build()); "default resolve method")]
#[test_case("trip example.com --dns-resolve-method system", Ok(cfg().dns_resolve_method(ResolveMethod::System).build()); "custom resolve method system")]
#[test_case("trip example.com -r system", Ok(cfg().dns_resolve_method(ResolveMethod::System).build()); "custom resolve method system short")]
Expand Down Expand Up @@ -1944,6 +1959,15 @@ mod tests {
}
}

pub fn dns_ttl(self, dns_ttl: Duration) -> Self {
Self {
config: TrippyConfig {
dns_ttl,
..self.config
},
}
}

pub fn dns_resolve_method(self, dns_resolve_method: ResolveMethod) -> Self {
Self {
config: TrippyConfig {
Expand Down
4 changes: 4 additions & 0 deletions crates/trippy-tui/src/config/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ pub struct Args {
#[arg(long, value_parser = parse_duration)]
pub dns_timeout: Option<Duration>,

/// The time-to-live (TTL) of DNS entries [default: 300s]
#[arg(long, value_parser = parse_duration)]
pub dns_ttl: Option<Duration>,

/// Lookup autonomous system (AS) information during DNS queries [default: false]
#[arg(long, short = 'z')]
pub dns_lookup_as_info: bool,
Expand Down
3 changes: 3 additions & 0 deletions crates/trippy-tui/src/config/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pub const DEFAULT_DNS_LOOKUP_AS_INFO: bool = false;
/// The default value for `dns-timeout`.
pub const DEFAULT_DNS_TIMEOUT: Duration = Duration::from_millis(5000);

/// The default value for `dns-ttl`.
pub const DEFAULT_DNS_TTL: Duration = Duration::from_secs(300);

/// The default value for `report-cycles`.
pub const DEFAULT_REPORT_CYCLES: usize = 10;

Expand Down
4 changes: 4 additions & 0 deletions crates/trippy-tui/src/config/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ pub struct ConfigDns {
#[serde(default)]
#[serde(deserialize_with = "humantime_deser")]
pub dns_timeout: Option<Duration>,
#[serde(default)]
#[serde(deserialize_with = "humantime_deser")]
pub dns_ttl: Option<Duration>,
}

impl Default for ConfigDns {
Expand All @@ -210,6 +213,7 @@ impl Default for ConfigDns {
dns_resolve_all: Some(super::constants::DEFAULT_DNS_RESOLVE_ALL),
dns_lookup_as_info: Some(super::constants::DEFAULT_DNS_LOOKUP_AS_INFO),
dns_timeout: Some(super::constants::DEFAULT_DNS_TIMEOUT),
dns_ttl: Some(super::constants::DEFAULT_DNS_TTL),
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion crates/trippy-tui/src/frontend/render/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ fn format_dns_settings(app: &TuiApp) -> Vec<SettingsItem> {
"dns-timeout",
format!("{}", format_duration(app.resolver.config().timeout)),
),
SettingsItem::new(
"dns-ttl",
format!("{}", format_duration(app.resolver.config().ttl)),
),
SettingsItem::new(
"dns-resolve-method",
format_dns_method(app.resolver.config().resolve_method),
Expand Down Expand Up @@ -493,7 +497,7 @@ pub const SETTINGS_TAB_COLUMNS: usize = 6;
pub const SETTINGS_TABS: [(&str, usize); 7] = [
("Tui", 8),
("Trace", 17),
("Dns", 4),
("Dns", 5),
("GeoIp", 1),
("Bindings", 36),
("Theme", 31),
Expand Down
2 changes: 1 addition & 1 deletion ...rippy-tui/tests/resources/snapshots/[email protected]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
---
source: crates/trippy-tui/src/config.rs
---
AnetworkdiagnostictoolUsage:trip[OPTIONS][TARGETS]...Arguments:[TARGETS]...AspacedelimitedlistofhostnamesandIPstotraceOptions:-c,--config-file<CONFIG_FILE>Configfile-m,--mode<MODE>Outputmode[default:tui][possiblevalues:tui,stream,pretty,markdown,csv,json,dot,flows,silent]-u,--unprivilegedTracewithoutrequiringelevatedprivilegesonsupportedplatforms[default:false]-p,--protocol<PROTOCOL>Tracingprotocol[default:icmp][possiblevalues:icmp,udp,tcp]--udpTraceusingtheUDPprotocol--tcpTraceusingtheTCPprotocol--icmpTraceusingtheICMPprotocol-F,--addr-family<ADDR_FAMILY>Theaddressfamily[default:Ipv4thenIpv6][possiblevalues:ipv4,ipv6,ipv6-then-ipv4,ipv4-then-ipv6]-4,--ipv4UseIPv4only-6,--ipv6UseIPv6only-P,--target-port<TARGET_PORT>Thetargetport(TCP&UDPonly)[default:80]-S,--source-port<SOURCE_PORT>Thesourceport(TCP&UDPonly)[default:auto]-A,--source-address<SOURCE_ADDRESS>ThesourceIPaddress[default:auto]-I,--interface<INTERFACE>Thenetworkinterface[default:auto]-i,--min-round-duration<MIN_ROUND_DURATION>Theminimumdurationofeveryround[default:1s]-T,--max-round-duration<MAX_ROUND_DURATION>Themaximumdurationofeveryround[default:1s]-g,--grace-duration<GRACE_DURATION>TheperiodoftimetowaitforadditionalICMPresponsesafterthetargethasresponded[default:100ms]--initial-sequence<INITIAL_SEQUENCE>Theinitialsequencenumber[default:33434]-R,--multipath-strategy<MULTIPATH_STRATEGY>TheEqual-costMulti-Pathroutingstrategy(UDPonly)[default:classic][possiblevalues:classic,paris,dublin]-U,--max-inflight<MAX_INFLIGHT>Themaximumnumberofin-flightICMPechorequests[default:24]-f,--first-ttl<FIRST_TTL>TheTTLtostartfrom[default:1]-t,--max-ttl<MAX_TTL>ThemaximumnumberofTTLhops[default:64]--packet-size<PACKET_SIZE>ThesizeofIPpackettosend(IPheader+ICMPheader+payload)[default:84]--payload-pattern<PAYLOAD_PATTERN>TherepeatingpatterninthepayloadoftheICMPpacket[default:0]-Q,--tos<TOS>TheTOS(i.e.DSCP+ECN)IPheadervalue(TCPandUDPonly)[default:0]-e,--icmp-extensionsParseICMPextensions--read-timeout<READ_TIMEOUT>Thesocketreadtimeout[default:10ms]-r,--dns-resolve-method<DNS_RESOLVE_METHOD>HowtoperformDNSqueries[default:system][possiblevalues:system,resolv,google,cloudflare]-y,--dns-resolve-allTracetoallIPsresolvedfromDNSlookup[default:false]--dns-timeout<DNS_TIMEOUT>ThemaximumtimetowaittoperformDNSqueries[default:5s]-z,--dns-lookup-as-infoLookupautonomoussystem(AS)informationduringDNSqueries[default:false]-s,--max-samples<MAX_SAMPLES>Themaximumnumberofsamplestorecordperhop[default:256]--max-flows<MAX_FLOWS>Themaximumnumberofflowstorecord[default:64]-a,--tui-address-mode<TUI_ADDRESS_MODE>Howtorenderaddresses[default:host][possiblevalues:ip,host,both]--tui-as-mode<TUI_AS_MODE>HowtorenderASinformation[default:asn][possiblevalues:asn,prefix,country-code,registry,allocated,name]--tui-custom-columns<TUI_CUSTOM_COLUMNS>CustomcolumnstobedisplayedintheTUIhopstable[default:holsravbwdt]--tui-icmp-extension-mode<TUI_ICMP_EXTENSION_MODE>HowtorenderICMPextensions[default:off][possiblevalues:off,mpls,full,all]--tui-geoip-mode<TUI_GEOIP_MODE>HowtorenderGeoIpinformation[default:short][possiblevalues:off,short,long,location]-M,--tui-max-addrs<TUI_MAX_ADDRS>Themaximumnumberofaddressestoshowperhop[default:auto]--tui-preserve-screenPreservethescreenonexit[default:false]--tui-refresh-rate<TUI_REFRESH_RATE>TheTuirefreshrate[default:100ms]--tui-privacy-max-ttl<TUI_PRIVACY_MAX_TTL>Themaximumttlofhopswhichwillbemaskedforprivacy[default:0]--tui-theme-colors<TUI_THEME_COLORS>TheTUIthemecolors[item=color,item=color,..]--print-tui-theme-itemsPrintallTUIthemeitemsandexit--tui-key-bindings<TUI_KEY_BINDINGS>TheTUIkeybindings[command=key,command=key,..]--print-tui-binding-commandsPrintallTUIcommandsthatcanbeboundandexit-C,--report-cycles<REPORT_CYCLES>Thenumberofreportcyclestorun[default:10]-G,--geoip-mmdb-file<GEOIP_MMDB_FILE>ThesupportedMaxMindorIPinfoGeoIpmmdbfile--generate<GENERATE>Generateshellcompletion[possiblevalues:bash,elvish,fish,powershell,zsh]--generate-manGenerateROFFmanpage--print-config-templatePrintatemplatetomlconfigfileandexit--log-format<LOG_FORMAT>Thedebuglogformat[default:pretty][possiblevalues:compact,pretty,json,chrome]--log-filter<LOG_FILTER>Thedebuglogfilter[default:trippy=debug]--log-span-events<LOG_SPAN_EVENTS>Thedebuglogformat[default:off][possiblevalues:off,active,full]-v,--verboseEnableverbosedebuglogging-h,--helpPrinthelp(seemorewith'--help')-V,--versionPrintversion
AnetworkdiagnostictoolUsage:trip[OPTIONS][TARGETS]...Arguments:[TARGETS]...AspacedelimitedlistofhostnamesandIPstotraceOptions:-c,--config-file<CONFIG_FILE>Configfile-m,--mode<MODE>Outputmode[default:tui][possiblevalues:tui,stream,pretty,markdown,csv,json,dot,flows,silent]-u,--unprivilegedTracewithoutrequiringelevatedprivilegesonsupportedplatforms[default:false]-p,--protocol<PROTOCOL>Tracingprotocol[default:icmp][possiblevalues:icmp,udp,tcp]--udpTraceusingtheUDPprotocol--tcpTraceusingtheTCPprotocol--icmpTraceusingtheICMPprotocol-F,--addr-family<ADDR_FAMILY>Theaddressfamily[default:Ipv4thenIpv6][possiblevalues:ipv4,ipv6,ipv6-then-ipv4,ipv4-then-ipv6]-4,--ipv4UseIPv4only-6,--ipv6UseIPv6only-P,--target-port<TARGET_PORT>Thetargetport(TCP&UDPonly)[default:80]-S,--source-port<SOURCE_PORT>Thesourceport(TCP&UDPonly)[default:auto]-A,--source-address<SOURCE_ADDRESS>ThesourceIPaddress[default:auto]-I,--interface<INTERFACE>Thenetworkinterface[default:auto]-i,--min-round-duration<MIN_ROUND_DURATION>Theminimumdurationofeveryround[default:1s]-T,--max-round-duration<MAX_ROUND_DURATION>Themaximumdurationofeveryround[default:1s]-g,--grace-duration<GRACE_DURATION>TheperiodoftimetowaitforadditionalICMPresponsesafterthetargethasresponded[default:100ms]--initial-sequence<INITIAL_SEQUENCE>Theinitialsequencenumber[default:33434]-R,--multipath-strategy<MULTIPATH_STRATEGY>TheEqual-costMulti-Pathroutingstrategy(UDPonly)[default:classic][possiblevalues:classic,paris,dublin]-U,--max-inflight<MAX_INFLIGHT>Themaximumnumberofin-flightICMPechorequests[default:24]-f,--first-ttl<FIRST_TTL>TheTTLtostartfrom[default:1]-t,--max-ttl<MAX_TTL>ThemaximumnumberofTTLhops[default:64]--packet-size<PACKET_SIZE>ThesizeofIPpackettosend(IPheader+ICMPheader+payload)[default:84]--payload-pattern<PAYLOAD_PATTERN>TherepeatingpatterninthepayloadoftheICMPpacket[default:0]-Q,--tos<TOS>TheTOS(i.e.DSCP+ECN)IPheadervalue(TCPandUDPonly)[default:0]-e,--icmp-extensionsParseICMPextensions--read-timeout<READ_TIMEOUT>Thesocketreadtimeout[default:10ms]-r,--dns-resolve-method<DNS_RESOLVE_METHOD>HowtoperformDNSqueries[default:system][possiblevalues:system,resolv,google,cloudflare]-y,--dns-resolve-allTracetoallIPsresolvedfromDNSlookup[default:false]--dns-timeout<DNS_TIMEOUT>ThemaximumtimetowaittoperformDNSqueries[default:5s]--dns-ttl<DNS_TTL>Thetime-to-live(TTL)ofDNSentries[default:300s]-z,--dns-lookup-as-infoLookupautonomoussystem(AS)informationduringDNSqueries[default:false]-s,--max-samples<MAX_SAMPLES>Themaximumnumberofsamplestorecordperhop[default:256]--max-flows<MAX_FLOWS>Themaximumnumberofflowstorecord[default:64]-a,--tui-address-mode<TUI_ADDRESS_MODE>Howtorenderaddresses[default:host][possiblevalues:ip,host,both]--tui-as-mode<TUI_AS_MODE>HowtorenderASinformation[default:asn][possiblevalues:asn,prefix,country-code,registry,allocated,name]--tui-custom-columns<TUI_CUSTOM_COLUMNS>CustomcolumnstobedisplayedintheTUIhopstable[default:holsravbwdt]--tui-icmp-extension-mode<TUI_ICMP_EXTENSION_MODE>HowtorenderICMPextensions[default:off][possiblevalues:off,mpls,full,all]--tui-geoip-mode<TUI_GEOIP_MODE>HowtorenderGeoIpinformation[default:short][possiblevalues:off,short,long,location]-M,--tui-max-addrs<TUI_MAX_ADDRS>Themaximumnumberofaddressestoshowperhop[default:auto]--tui-preserve-screenPreservethescreenonexit[default:false]--tui-refresh-rate<TUI_REFRESH_RATE>TheTuirefreshrate[default:100ms]--tui-privacy-max-ttl<TUI_PRIVACY_MAX_TTL>Themaximumttlofhopswhichwillbemaskedforprivacy[default:0]--tui-theme-colors<TUI_THEME_COLORS>TheTUIthemecolors[item=color,item=color,..]--print-tui-theme-itemsPrintallTUIthemeitemsandexit--tui-key-bindings<TUI_KEY_BINDINGS>TheTUIkeybindings[command=key,command=key,..]--print-tui-binding-commandsPrintallTUIcommandsthatcanbeboundandexit-C,--report-cycles<REPORT_CYCLES>Thenumberofreportcyclestorun[default:10]-G,--geoip-mmdb-file<GEOIP_MMDB_FILE>ThesupportedMaxMindorIPinfoGeoIpmmdbfile--generate<GENERATE>Generateshellcompletion[possiblevalues:bash,elvish,fish,powershell,zsh]--generate-manGenerateROFFmanpage--print-config-templatePrintatemplatetomlconfigfileandexit--log-format<LOG_FORMAT>Thedebuglogformat[default:pretty][possiblevalues:compact,pretty,json,chrome]--log-filter<LOG_FILTER>Thedebuglogfilter[default:trippy=debug]--log-span-events<LOG_SPAN_EVENTS>Thedebuglogformat[default:off][possiblevalues:off,active,full]-v,--verboseEnableverbosedebuglogging-h,--helpPrinthelp(seemorewith'--help')-V,--versionPrintversion
Loading

0 comments on commit 143df5d

Please sign in to comment.