Apply Clippy recommendations

This commit is contained in:
Nils Andreas Svee committed 2022-10-15 14:58:05 +02:00
1 parent 34b3fc0850
commit cacc5b1a6b
11 files changed
+82 -105

No files matched your search

+5 -5
View File
@@ -4,21 +4,21 @@ pub enum TcaCake {
Pad = 1, Pad = 1,
BaseRate64 = 2, BaseRate64 = 2,
DiffservMode = 3, DiffservMode = 3,
ATM = 4, Atm = 4,
FlowMode = 5, FlowMode = 5,
Overhead = 6, Overhead = 6,
RTT = 7, Rtt = 7,
Target = 8, Target = 8,
Autorate = 9, Autorate = 9,
Memory = 10, Memory = 10,
NAT = 11, Nat = 11,
Raw = 12, Raw = 12,
Wash = 13, Wash = 13,
MPU = 14, Mpu = 14,
Ingress = 15, Ingress = 15,
AckFilter = 16, AckFilter = 16,
SplitGso = 17, SplitGso = 17,
FwMark = 18, FwMark = 18,
FwMarkStore = 19, FwMarkStore = 19,
SCE = 20, Sce = 20,
} }
+17 -23
View File
@@ -33,10 +33,10 @@ where
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub enum MeasurementType { pub enum MeasurementType {
ICMP = 1, Icmp = 1,
ICMPTimestamps, IcmpTimestamps,
NTP, Ntp,
TCPTimestamps, TcpTimestamps,
} }
impl FromStr for MeasurementType { impl FromStr for MeasurementType {
@@ -44,10 +44,10 @@ impl FromStr for MeasurementType {
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
return match s.to_lowercase().as_str() { return match s.to_lowercase().as_str() {
"icmp" => Ok(MeasurementType::ICMP), "icmp" => Ok(MeasurementType::Icmp),
"icmp-timestamps" => Ok(MeasurementType::ICMPTimestamps), "icmp-timestamps" => Ok(MeasurementType::IcmpTimestamps),
"ntp" => Ok(MeasurementType::NTP), "ntp" => Ok(MeasurementType::Ntp),
"tcp-timestamps" => Ok(MeasurementType::TCPTimestamps), "tcp-timestamps" => Ok(MeasurementType::TcpTimestamps),
&_ => Err(ConfigError::InvalidMeasurementType(s.to_string())), &_ => Err(ConfigError::InvalidMeasurementType(s.to_string())),
}; };
} }
@@ -150,7 +150,7 @@ impl Config {
measurement_type: Self::get::<MeasurementType>( measurement_type: Self::get::<MeasurementType>(
"SQMA_MEASUREMENT_TYPE", "SQMA_MEASUREMENT_TYPE",
"sqm-autorate.@advanced_settings[0].measurement_type", "sqm-autorate.@advanced_settings[0].measurement_type",
Some(MeasurementType::ICMPTimestamps), Some(MeasurementType::IcmpTimestamps),
)?, )?,
min_change_interval: Self::get::<f64>( min_change_interval: Self::get::<f64>(
"SQMA_MIN_CHANGE_INTERVAL", "SQMA_MIN_CHANGE_INTERVAL",
@@ -185,25 +185,19 @@ impl Config {
}) })
} }
fn get<T: std::str::FromStr>( fn get<T: FromStr>(env_key: &str, uci_key: &str, default: Option<T>) -> Result<T, ConfigError> {
env_key: &str, match Self::get_value(env_key, uci_key) {
uci_key: &str,
default: Option<T>,
) -> Result<T, ConfigError> {
return match Self::get_value(env_key, uci_key) {
Some(val) => match val.parse::<T>() { Some(val) => match val.parse::<T>() {
Ok(parsed_val) => Ok(parsed_val), Ok(parsed_val) => Ok(parsed_val),
// Ran into an compilation error while trying to return the // Ran into an compilation error while trying to return the
// error as-is, so using my own error type to indicate something went wrong while parsing // error as-is, so using my own error type to indicate something went wrong while parsing
Err(_) => Err(ConfigError::ParseError(env_key.to_string())), Err(_) => Err(ConfigError::ParseError(env_key.to_string())),
}, },
None => { None => match default {
return match default { Some(val) => Ok(val),
Some(val) => Ok(val), None => Err(ConfigError::MissingValue(env_key.to_string())),
None => Err(ConfigError::MissingValue(env_key.to_string())), },
} }
}
};
} }
fn get_value(env_key: &str, uci_key: &str) -> Option<String> { fn get_value(env_key: &str, uci_key: &str) -> Option<String> {
@@ -256,7 +250,7 @@ impl Config {
} }
let line = line?; let line = line?;
let columns: Vec<&str> = line.split(",").collect(); let columns: Vec<&str> = line.split(',').collect();
reflectors.push(IpAddr::from_str(columns[0])?); reflectors.push(IpAddr::from_str(columns[0])?);
} }
+1 -1
View File
@@ -13,7 +13,7 @@ const LOG_DATETIME_FORMAT: &[FormatItem] = format_description!(
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct SimpleLogger { pub struct SimpleLogger {
pub level: log::Level, pub level: Level,
} }
fn time_format<T>(dt: T, format: &(impl Formattable + ?Sized)) -> String fn time_format<T>(dt: T, format: &(impl Formattable + ?Sized)) -> String
+18 -21
View File
@@ -78,15 +78,15 @@ fn main() -> anyhow::Result<()> {
let (reselect_sender, reselect_receiver) = channel(); let (reselect_sender, reselect_receiver) = channel();
let (mut pinger_receiver, mut pinger_sender) = match config.measurement_type { let (mut pinger_receiver, mut pinger_sender) = match config.measurement_type {
MeasurementType::ICMP => ( MeasurementType::Icmp => (
Box::new(PingerICMPEchoListener {}) as Box<dyn PingListener + Send>, Box::new(PingerICMPEchoListener {}) as Box<dyn PingListener + Send>,
Box::new(PingerICMPEchoSender {}) as Box<dyn PingSender + Send>, Box::new(PingerICMPEchoSender {}) as Box<dyn PingSender + Send>,
), ),
MeasurementType::ICMPTimestamps => ( MeasurementType::IcmpTimestamps => (
Box::new(PingerICMPTimestampListener {}) as Box<dyn PingListener + Send>, Box::new(PingerICMPTimestampListener {}) as Box<dyn PingListener + Send>,
Box::new(PingerICMPTimestampSender {}) as Box<dyn PingSender + Send>, Box::new(PingerICMPTimestampSender {}) as Box<dyn PingSender + Send>,
), ),
MeasurementType::NTP | MeasurementType::TCPTimestamps => { MeasurementType::Ntp | MeasurementType::TcpTimestamps => {
todo!() todo!()
} }
}; };
@@ -150,30 +150,27 @@ fn main() -> anyhow::Result<()> {
// Sleep 10 seconds before we start adjusting speeds // Sleep 10 seconds before we start adjusting speeds
sleep(Duration::new(10, 0)); sleep(Duration::new(10, 0));
let dl_direction; let dl_direction = if config.download_interface.starts_with("ifb")
let ul_direction; || config.download_interface.starts_with("veth")
if config.download_interface.starts_with("ifb") || config.download_interface.starts_with("veth")
{ {
dl_direction = StatsDirection::TX; StatsDirection::TX
} else if config.download_interface == "br-lan" {
dl_direction = StatsDirection::RX;
} else { } else {
dl_direction = StatsDirection::RX; StatsDirection::RX
} };
let ul_direction = if config.upload_interface.starts_with("ifb")
if config.upload_interface.starts_with("ifb") || config.upload_interface.starts_with("veth") { || config.upload_interface.starts_with("veth")
ul_direction = StatsDirection::RX; {
StatsDirection::RX
} else { } else {
ul_direction = StatsDirection::TX; StatsDirection::TX
} };
let mut ratecontroller = Ratecontroller::new( let mut ratecontroller = Ratecontroller::new(
config.clone(), config.clone(),
owd_baseline.clone(), owd_baseline,
owd_recent.clone(), owd_recent,
reflector_peers_lock.clone(), reflector_peers_lock,
reselect_sender.clone(), reselect_sender,
)?; )?;
debug!( debug!(
+1 -1
View File
@@ -241,7 +241,7 @@ impl Netlink {
} }
} }
return Err(NetlinkError::NoQdiscFound(ifindex.to_string())); Err(NetlinkError::NoQdiscFound(ifindex.to_string()))
} }
pub fn qdisc_from_ifname(ifname: &str) -> Result<Qdisc, NetlinkError> { pub fn qdisc_from_ifname(ifname: &str) -> Result<Qdisc, NetlinkError> {
+10 -12
View File
@@ -40,12 +40,12 @@ pub struct PingReply {
pub last_receive_time_s: f64, pub last_receive_time_s: f64,
} }
fn open_socket(type_: MeasurementType) -> std::io::Result<Socket> { fn open_socket(type_: MeasurementType) -> io::Result<Socket> {
match type_ { match type_ {
MeasurementType::ICMP | MeasurementType::ICMPTimestamps => { MeasurementType::Icmp | MeasurementType::IcmpTimestamps => {
Socket::new(Domain::IPV4, Type::RAW, Some(Protocol::ICMPV4)) Socket::new(Domain::IPV4, Type::RAW, Some(Protocol::ICMPV4))
} }
MeasurementType::NTP => Socket::new(Domain::IPV4, Type::DGRAM, None), MeasurementType::Ntp => Socket::new(Domain::IPV4, Type::DGRAM, None),
_ => { _ => {
unimplemented!() unimplemented!()
} }
@@ -131,20 +131,18 @@ pub trait PingSender {
drop(reflectors_unlocked); drop(reflectors_unlocked);
for reflector in reflectors.iter() { for reflector in reflectors.iter() {
let addr: SockAddr; let addr: SockAddr = match reflector.is_ipv4() {
match reflector.is_ipv4() {
true => { true => {
let ip4 = Ipv4Addr::from_str(&*reflector.to_string()).unwrap(); let ip4 = Ipv4Addr::from_str(&*reflector.to_string()).unwrap();
let sock4 = SocketAddrV4::new(ip4, 0); let sock4 = SocketAddrV4::new(ip4, 0);
addr = sock4.into(); sock4.into()
} }
false => { false => {
let ip6 = Ipv6Addr::from_str(&*reflector.to_string()).unwrap(); let ip6 = Ipv6Addr::from_str(&*reflector.to_string()).unwrap();
let sock6 = SocketAddrV6::new(ip6, 0, 0, 0); let sock6 = SocketAddrV6::new(ip6, 0, 0, 0);
addr = sock6.into(); sock6.into()
} }
} };
let buf_v = self.craft_packet(id, seq); let buf_v = self.craft_packet(id, seq);
let buf = buf_v.as_slice(); let buf = buf_v.as_slice();
@@ -154,10 +152,10 @@ pub trait PingSender {
thread::sleep(sleep_duration); thread::sleep(sleep_duration);
seq += 1; if seq == u16::MAX {
if seq >= u16::MAX {
seq = 0; seq = 0;
} else {
seq += 1;
} }
} }
} }
+7 -15
View File
@@ -15,7 +15,7 @@ impl PingListener for PingerICMPEchoListener {
// Result: RTT, down time, up time // Result: RTT, down time, up time
fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result<PingReply, PingError> { fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result<PingReply, PingError> {
match SlicedPacket::from_ip(buf) { match SlicedPacket::from_ip(buf) {
Err(err) => return Err(PingError::InvalidPacket(err)), Err(err) => Err(PingError::InvalidPacket(err)),
Ok(value) => match value.transport { Ok(value) => match value.transport {
Some(Icmpv4(icmp)) => match icmp.icmp_type() { Some(Icmpv4(icmp)) => match icmp.icmp_type() {
Icmpv4Type::EchoReply(echo) => { Icmpv4Type::EchoReply(echo) => {
@@ -36,7 +36,7 @@ impl PingListener for PingerICMPEchoListener {
let time_ms = clock.to_milliseconds() as i64; let time_ms = clock.to_milliseconds() as i64;
let rtt: i64 = time_ms - time_sent; let rtt: i64 = time_ms - time_sent;
return Ok(PingReply { Ok(PingReply {
reflector, reflector,
seq: echo.seq, seq: echo.seq,
rtt, rtt,
@@ -48,21 +48,13 @@ impl PingListener for PingerICMPEchoListener {
transmit_timestamp: 0, transmit_timestamp: 0,
last_receive_time_s: clock.get_seconds() as f64 last_receive_time_s: clock.get_seconds() as f64
+ (clock.get_nanoseconds() as f64 / 1e9), + (clock.get_nanoseconds() as f64 / 1e9),
}); })
}
type_ => {
return Err(PingError::InvalidType(format!("{:?}", type_)));
} }
type_ => Err(PingError::InvalidType(format!("{:?}", type_))),
}, },
Some(Icmpv6(slice)) => { Some(Icmpv6(slice)) => Err(PingError::InvalidProtocol(format!("{:?}", slice))),
return Err(PingError::InvalidProtocol(format!("{:?}", slice))); Some(type_) => Err(PingError::InvalidProtocol(format!("{:?}", type_))),
} None => Err(PingError::NoTransport),
Some(type_) => {
return Err(PingError::InvalidProtocol(format!("{:?}", type_)));
}
None => {
return Err(PingError::NoTransport);
}
}, },
} }
} }
+7 -15
View File
@@ -15,7 +15,7 @@ impl PingListener for PingerICMPTimestampListener {
// Result: RTT, down time, up time // Result: RTT, down time, up time
fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result<PingReply, PingError> { fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result<PingReply, PingError> {
match SlicedPacket::from_ip(buf) { match SlicedPacket::from_ip(buf) {
Err(err) => return Err(PingError::InvalidPacket(err)), Err(err) => Err(PingError::InvalidPacket(err)),
Ok(value) => match value.transport { Ok(value) => match value.transport {
Some(Icmpv4(icmp)) => match icmp.icmp_type() { Some(Icmpv4(icmp)) => match icmp.icmp_type() {
Icmpv4Type::TimestampReply(reply) => { Icmpv4Type::TimestampReply(reply) => {
@@ -37,7 +37,7 @@ impl PingListener for PingerICMPTimestampListener {
let dl_time: i64 = time_since_midnight - transmit_timestamp as i64; let dl_time: i64 = time_since_midnight - transmit_timestamp as i64;
let ul_time: i64 = receive_timestamp as i64 - originate_timestamp as i64; let ul_time: i64 = receive_timestamp as i64 - originate_timestamp as i64;
return Ok(PingReply { Ok(PingReply {
reflector, reflector,
seq: reply.seq, seq: reply.seq,
rtt, rtt,
@@ -49,21 +49,13 @@ impl PingListener for PingerICMPTimestampListener {
transmit_timestamp: transmit_timestamp as i64, transmit_timestamp: transmit_timestamp as i64,
last_receive_time_s: time_now.get_seconds() as f64 last_receive_time_s: time_now.get_seconds() as f64
+ (time_now.get_nanoseconds() as f64 / 1e9), + (time_now.get_nanoseconds() as f64 / 1e9),
}); })
}
type_ => {
return Err(PingError::InvalidType(format!("{:?}", type_)));
} }
type_ => Err(PingError::InvalidType(format!("{:?}", type_))),
}, },
Some(Icmpv6(slice)) => { Some(Icmpv6(slice)) => Err(PingError::InvalidType(format!("{:?}", slice))),
return Err(PingError::InvalidType(format!("{:?}", slice))); Some(type_) => Err(PingError::InvalidType(format!("{:?}", type_))),
} None => Err(PingError::NoTransport),
Some(type_) => {
return Err(PingError::InvalidType(format!("{:?}", type_)));
}
None => {
return Err(PingError::NoTransport);
}
}, },
} }
} }
+9 -9
View File
@@ -39,7 +39,7 @@ fn generate_initial_speeds(base_speed: f64, size: u32) -> Vec<f64> {
let mut rates = Vec::new(); let mut rates = Vec::new();
for _ in 0..size { for _ in 0..size {
rates.push((rand::thread_rng().next_u64() as f64 * 0.2 + 0.75) * base_speed); rates.push((thread_rng().next_u64() as f64 * 0.2 + 0.75) * base_speed);
} }
rates rates
@@ -116,7 +116,7 @@ impl Ratecontroller {
debug!("direction: {:?} -> state: {:#?}", direction, state); debug!("direction: {:?} -> state: {:#?}", direction, state);
if state.deltas.len() > 0 { if !state.deltas.is_empty() {
state.next_rate = state.current_rate; state.next_rate = state.current_rate;
if state.deltas.len() < 3 { if state.deltas.len() < 3 {
@@ -148,8 +148,8 @@ impl Ratecontroller {
state.next_rate = state.current_rate state.next_rate = state.current_rate
* (1.0 + 0.1 * (1.0_f64 - state.current_rate / max_rate).max(0.0)) * (1.0 + 0.1 * (1.0_f64 - state.current_rate / max_rate).max(0.0))
+ (base_rate * 0.03); + (base_rate * 0.03);
state.nrate = state.nrate + 1; state.nrate += 1;
state.nrate = state.nrate % self.config.speed_hist_size as usize; state.nrate %= self.config.speed_hist_size as usize;
} }
if state.delta_stat > delay_ms { if state.delta_stat > delay_ms {
@@ -314,7 +314,7 @@ impl Ratecontroller {
.write(true) .write(true)
.open(self.config.speed_hist_file.as_str())?; .open(self.config.speed_hist_file.as_str())?;
speed_hist_fd_inner.write("time,counter,upspeed,downspeed\n".as_bytes())?; speed_hist_fd_inner.write_all("time,counter,upspeed,downspeed\n".as_bytes())?;
speed_hist_fd_inner.flush()?; speed_hist_fd_inner.flush()?;
speed_hist_fd = Some(speed_hist_fd_inner); speed_hist_fd = Some(speed_hist_fd_inner);
@@ -324,7 +324,7 @@ impl Ratecontroller {
.write(true) .write(true)
.open(self.config.stats_file.as_str())?; .open(self.config.stats_file.as_str())?;
stats_fd_inner.write( stats_fd_inner.write_all(
"times,timens,rxload,txload,deltadelaydown,deltadelayup,dlrate,uprate\n".as_bytes(), "times,timens,rxload,txload,deltadelaydown,deltadelayup,dlrate,uprate\n".as_bytes(),
)?; )?;
stats_fd_inner.flush()?; stats_fd_inner.flush()?;
@@ -338,7 +338,7 @@ impl Ratecontroller {
let now = Clock::new(ClockId::Monotonic); let now = Clock::new(ClockId::Monotonic);
let (mut now_s, now_ns) = (now.get_seconds() as f64, now.get_nanoseconds() as f64); let (mut now_s, now_ns) = (now.get_seconds() as f64, now.get_nanoseconds() as f64);
let now_abstime = now_s + now_ns / 1e9; let now_abstime = now_s + now_ns / 1e9;
now_s = now_s - start_s; now_s -= start_s;
let now_t = now_s + now_ns / 1e9; let now_t = now_s + now_ns / 1e9;
if now_t - lastchg_t > self.config.min_change_interval { if now_t - lastchg_t > self.config.min_change_interval {
@@ -416,14 +416,14 @@ impl Ratecontroller {
} }
} }
lastchg_s = lastchg_s - start_s; lastchg_s -= start_s;
lastchg_t = lastchg_s + lastchg_ns / 1e9; lastchg_t = lastchg_s + lastchg_ns / 1e9;
} }
if let Some(ref mut fd) = speed_hist_fd { if let Some(ref mut fd) = speed_hist_fd {
if now_t - lastdump_t > 300.0 { if now_t - lastdump_t > 300.0 {
for i in 0..self.config.speed_hist_size as usize { for i in 0..self.config.speed_hist_size as usize {
if let Err(e) = fd.write( if let Err(e) = fd.write_all(
format!( format!(
"{},{},{},{}\n", "{},{},{},{}\n",
now_t, i, self.state_ul.safe_rates[i], self.state_dl.safe_rates[i] now_t, i, self.state_ul.safe_rates[i], self.state_dl.safe_rates[i]
+2 -2
View File
@@ -99,7 +99,7 @@ impl ReflectorSelector {
candidates.sort_by(|a, b| a.1.cmp(&b.1)); candidates.sort_by(|a, b| a.1.cmp(&b.1));
// Now we will just limit the candidates down to 2 * num_reflectors // Now we will just limit the candidates down to 2 * num_reflectors
let mut num_reflectors = self.config.num_reflectors.clone(); let mut num_reflectors = self.config.num_reflectors;
let candidate_pool_num = (2 * num_reflectors) as usize; let candidate_pool_num = (2 * num_reflectors) as usize;
candidates = candidates[0..candidate_pool_num - 1].to_vec(); candidates = candidates[0..candidate_pool_num - 1].to_vec();
@@ -108,7 +108,7 @@ impl ReflectorSelector {
} }
// Shuffle the deck so we avoid overwhelming good reflectors (Fisher-Yates) // Shuffle the deck so we avoid overwhelming good reflectors (Fisher-Yates)
for i in (1 as usize..candidates.len()).rev() { for i in (1_usize..candidates.len()).rev() {
let j = rng.gen_range(0..(i + 1)); let j = rng.gen_range(0..(i + 1));
candidates.swap(i, j); candidates.swap(i, j);
} }
+5 -1
View File
@@ -2,7 +2,11 @@ pub struct Utils {}
impl Utils { impl Utils {
pub fn a_else_b(a: f64, b: f64) -> f64 { pub fn a_else_b(a: f64, b: f64) -> f64 {
return if a > 0.0 { a } else { b }; if a > 0.0 {
a
} else {
b
}
} }
pub fn ewma_factor(tick: f64, dur: f64) -> f64 { pub fn ewma_factor(tick: f64, dur: f64) -> f64 {
((0.5_f64).ln() / (dur / tick)).exp() ((0.5_f64).ln() / (dur / tick)).exp()