Skip to content

Commit 6ec663b

Browse files
committed
chore: enable more strict clippy warnings
1 parent f7995ce commit 6ec663b

File tree

15 files changed

+303
-68
lines changed

15 files changed

+303
-68
lines changed

Cargo.toml

Lines changed: 223 additions & 0 deletions
Large diffs are not rendered by default.

clippy.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
allow-unwrap-in-tests = true

src/args.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::process::exit;
66
use anyhow::Result;
77

88
/// Args passed into the application.
9-
#[derive(Debug, PartialEq)]
9+
#[derive(Debug, PartialEq, Eq)]
1010
pub struct CliArgs {
1111
/// Optional listen address. By default, listens on `127.0.0.1`
1212
pub listen_address: String,

src/collector.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ use smol::lock::RwLock;
1212

1313
use crate::config::UserConfig;
1414
use crate::metrics::collector::{
15-
CpuStatsCollector, DiskStatsCollector, FilesystemStatsCollector, MemoryStatsCollector, NetworkStatsCollector, NodeInfoCollector, PressureCollector, SystemdUnitStateCollector
15+
CpuStatsCollector, DiskStatsCollector, FilesystemStatsCollector, MemoryStatsCollector,
16+
NetworkStatsCollector, NodeInfoCollector, PressureCollector, SystemdUnitStateCollector,
1617
};
1718
use crate::metrics::Metric;
1819

@@ -50,7 +51,7 @@ impl Collector {
5051

5152
let metrics = &config.metrics;
5253
{
53-
let collector = Box::new(NodeInfoCollector::new().await?);
54+
let collector = Box::new(NodeInfoCollector::new()?);
5455
inner.metrics.push(collector);
5556
}
5657

@@ -75,21 +76,21 @@ impl Collector {
7576
if metrics.systemd_unit_state.enabled {
7677
let units = metrics.systemd_unit_state.units.join(",");
7778
let options = HashMap::from([("units".to_owned(), units)]);
78-
let collector = Box::new(SystemdUnitStateCollector::new(options).await?);
79+
let collector = Box::new(SystemdUnitStateCollector::new(&options).await?);
7980
inner.metrics.push(collector);
8081
}
8182

8283
if metrics.network_throughput.enabled {
8384
let interfaces = metrics.network_throughput.interfaces.join(",");
8485
let options = HashMap::from([("interfaces".to_owned(), interfaces)]);
85-
let collector = Box::new(NetworkStatsCollector::new(options).await?);
86+
let collector = Box::new(NetworkStatsCollector::new(&options)?);
8687
inner.metrics.push(collector);
8788
}
8889

8990
if metrics.disk_usage.enabled {
9091
let mountpoints = metrics.disk_usage.mountpoints.join(",");
9192
let options = HashMap::from([("mountpoints".to_owned(), mountpoints)]);
92-
let collector = Box::new(FilesystemStatsCollector::new(options).await?);
93+
let collector = Box::new(FilesystemStatsCollector::new(&options)?);
9394
inner.metrics.push(collector);
9495
}
9596

@@ -101,7 +102,7 @@ impl Collector {
101102
if metrics.disk_stats.enabled {
102103
let mountpoints = metrics.disk_stats.mountpoints.join(",");
103104
let options = HashMap::from([("mountpoints".to_owned(), mountpoints)]);
104-
let collector = Box::new(DiskStatsCollector::new(options)?);
105+
let collector = Box::new(DiskStatsCollector::new(&options)?);
105106
inner.metrics.push(collector);
106107
}
107108

@@ -129,7 +130,7 @@ impl Collector {
129130
.collect();
130131
let results = futs.join().await;
131132
for res in results {
132-
res.inspect_err(|err| eprintln!("{err:?}"))
133+
res.inspect_err(|err| eprintln!("{err}"))
133134
.context("collecting metrics")?;
134135
}
135136

src/config.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ impl Default for MetricsConfig {
106106

107107
impl UserConfig {
108108
/// Load the configuratin from the `path` specified.
109+
#[allow(clippy::too_many_lines, clippy::shadow_unrelated)]
109110
pub async fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
110111
let docstr = smol::fs::read_to_string(path.as_ref())
111112
.await

src/http.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ async fn serve_request(
3737

3838
match (req.method(), req.uri().path()) {
3939
(&Method::GET, "/metrics") => {
40-
let res = serve_metrics(&collector)
40+
let response = serve_metrics(&collector)
4141
.await
4242
.inspect_err(|err| eprintln!("error serving metrics request: {err}"))
4343
.unwrap_or_else(|_err| internal_server_error());
44-
Ok(res)
44+
Ok(response)
4545
}
4646

4747
(_, _) => Ok(not_found()),

src/main.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//! LiteMon. Lightweight prometheus metrics for Linux.
12
use std::rc::Rc;
23

34
use litemon::args::CliArgs;
@@ -7,6 +8,7 @@ use litemon::http;
78
use tracing_subscriber::layer::SubscriberExt;
89
use tracing_subscriber::util::SubscriberInitExt;
910

11+
/// Global Jemalloc allocator.
1012
#[global_allocator]
1113
static GLOBAL_ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
1214

@@ -27,6 +29,7 @@ fn main() {
2729
}
2830

2931
/// Real, asynchronous entrypoint.
32+
#[allow(clippy::future_not_send)]
3033
async fn async_main(_ex: &Rc<smol::LocalExecutor<'_>>) {
3134
let args = CliArgs::from_env().expect("invalid args");
3235
let config = UserConfig::from_path(&args.config_path)
@@ -54,5 +57,5 @@ async fn async_main(_ex: &Rc<smol::LocalExecutor<'_>>) {
5457

5558
http::listen(collector.clone(), &args.listen_address, args.listen_port)
5659
.await
57-
.unwrap();
60+
.expect("starting http server");
5861
}

src/metrics/collector.rs

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,9 @@ impl Metric for CpuStatsCollector {
125125
.load_avg_enabled
126126
.load(std::sync::atomic::Ordering::Acquire)
127127
{
128-
self.load_avg_1m.set(load_avg.one as f64);
129-
self.load_avg_5m.set(load_avg.five as f64);
130-
self.load_avg_15m.set(load_avg.fifteen as f64);
128+
self.load_avg_1m.set(f64::from(load_avg.one));
129+
self.load_avg_5m.set(f64::from(load_avg.five));
130+
self.load_avg_15m.set(f64::from(load_avg.fifteen));
131131
}
132132

133133
let current_snapshot = CpuUsage::now().await?;
@@ -165,15 +165,16 @@ struct FilesystemLabels {
165165
}
166166

167167
impl FilesystemStatsCollector {
168-
pub async fn new(options: hashbrown::HashMap<String, String>) -> Result<Self> {
169-
let mountpoints = if let Some(mountpoints_str) = options.get("mountpoints") {
170-
mountpoints_str
171-
.split(',')
172-
.map(|s| s.trim().to_string())
173-
.collect()
174-
} else {
175-
vec!["/".to_string()] // Default to root filesystem
176-
};
168+
pub fn new(options: &hashbrown::HashMap<String, String>) -> Result<Self> {
169+
let mountpoints = options.get("mountpoints").map_or_else(
170+
|| vec!["/".to_string()],
171+
|mountpoints_str| {
172+
mountpoints_str
173+
.split(',')
174+
.map(|s| s.trim().to_string())
175+
.collect()
176+
},
177+
);
177178

178179
Ok(Self {
179180
fs_usage_ratio: Default::default(),
@@ -238,16 +239,16 @@ struct NetworkLabels {
238239
}
239240

240241
impl NetworkStatsCollector {
241-
pub async fn new(options: hashbrown::HashMap<String, String>) -> Result<Self> {
242-
let interfaces = if let Some(interfaces_str) = options.get("interfaces") {
243-
interfaces_str
244-
.split(',')
245-
.map(|s| s.trim().to_string())
246-
.collect()
247-
} else {
248-
// Default to common interfaces if none specified
249-
vec!["eth0".to_string()]
250-
};
242+
pub fn new(options: &hashbrown::HashMap<String, String>) -> Result<Self> {
243+
let interfaces = options.get("interfaces").map_or_else(
244+
|| vec!["eth0".to_string()],
245+
|interfaces_str| {
246+
interfaces_str
247+
.split(',')
248+
.map(|s| s.trim().to_string())
249+
.collect()
250+
},
251+
);
251252

252253
Ok(Self {
253254
bytes_received: Default::default(),
@@ -283,6 +284,7 @@ impl Metric for NetworkStatsCollector {
283284
);
284285
}
285286

287+
#[allow(clippy::cast_precision_loss)]
286288
fn collect(&self) -> DynFuture<'_, Result<()>> {
287289
Box::pin(async move {
288290
let interfaces = &self.interfaces;
@@ -336,13 +338,11 @@ struct SystemdUnitLabels {
336338
}
337339

338340
impl SystemdUnitStateCollector {
339-
pub async fn new(options: hashbrown::HashMap<String, String>) -> Result<Self> {
341+
pub async fn new(options: &hashbrown::HashMap<String, String>) -> Result<Self> {
340342
// Parse units from options
341-
let units = if let Some(units_str) = options.get("units") {
343+
let units = options.get("units").map_or_else(Vec::new, |units_str| {
342344
units_str.split(',').map(|s| s.trim().to_string()).collect()
343-
} else {
344-
Vec::new()
345-
};
345+
});
346346

347347
let client = SystemdUnitState::new().await?;
348348

@@ -374,7 +374,7 @@ impl Metric for SystemdUnitStateCollector {
374374
for state_name in ActiveState::all_states() {
375375
let labels = SystemdUnitLabels {
376376
unit: unit_name.clone(),
377-
state: state_name.to_string(),
377+
state: (*state_name).to_string(),
378378
};
379379
self.unit_state.get_or_create(&labels).set(0);
380380
}
@@ -416,7 +416,7 @@ struct NodeInfoLabels {
416416
}
417417

418418
impl NodeInfoCollector {
419-
pub async fn new() -> Result<Self> {
419+
pub fn new() -> Result<Self> {
420420
let info = NodeInfo::new()?;
421421

422422
let labels = NodeInfoLabels {
@@ -437,7 +437,7 @@ impl Metric for NodeInfoCollector {
437437
"litemon_node_info",
438438
"System information about the node",
439439
self.metric.clone(),
440-
)
440+
);
441441
}
442442

443443
fn collect(&self) -> DynFuture<'_, Result<()>> {
@@ -511,15 +511,16 @@ struct DiskStatsLabels {
511511
}
512512

513513
impl DiskStatsCollector {
514-
pub fn new(options: hashbrown::HashMap<String, String>) -> Result<Self> {
515-
let mountpoints = if let Some(mountpoints_str) = options.get("mountpoints") {
516-
mountpoints_str
517-
.split(',')
518-
.map(|s| s.trim().to_string())
519-
.collect()
520-
} else {
521-
vec!["/".to_string()] // Default to root filesystem
522-
};
514+
pub fn new(options: &hashbrown::HashMap<String, String>) -> Result<Self> {
515+
let mountpoints = options.get("mountpoints").map_or_else(
516+
|| vec!["/".to_string()],
517+
|mountpoints_str| {
518+
mountpoints_str
519+
.split(',')
520+
.map(|s| s.trim().to_string())
521+
.collect()
522+
},
523+
);
523524

524525
Ok(Self {
525526
bytes_written: Default::default(),
@@ -545,8 +546,8 @@ impl Metric for DiskStatsCollector {
545546

546547
fn collect(&self) -> DynFuture<'_, Result<()>> {
547548
Box::pin(async move {
548-
let stats = IOMetrics::all().await?;
549-
for (device, stats) in &stats.disks {
549+
let io = IOMetrics::all().await?;
550+
for (device, stats) in &io.disks {
550551
if !self.mountpoints.iter().any(|el| el == &stats.mountpoint) {
551552
continue;
552553
}

src/metrics/cpu.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,21 +52,21 @@ pub struct CpuTime {
5252
}
5353

5454
impl Add for CpuTime {
55-
type Output = CpuTime;
55+
type Output = Self;
5656

5757
fn add(self, rhs: Self) -> Self::Output {
58-
CpuTime {
58+
Self {
5959
idle_ticks: self.idle_ticks + rhs.idle_ticks,
6060
total_ticks: self.total_ticks + rhs.total_ticks,
6161
}
6262
}
6363
}
6464

6565
impl Sub for CpuTime {
66-
type Output = CpuTime;
66+
type Output = Self;
6767

6868
fn sub(self, rhs: Self) -> Self::Output {
69-
CpuTime {
69+
Self {
7070
idle_ticks: self.idle_ticks - rhs.idle_ticks,
7171
total_ticks: self.total_ticks - rhs.total_ticks,
7272
}
@@ -75,7 +75,7 @@ impl Sub for CpuTime {
7575

7676
impl CpuUsage {
7777
/// Retrieve the current CPU usage in ticks from boot.
78-
pub async fn now() -> Result<CpuUsage> {
78+
pub async fn now() -> Result<Self> {
7979
let stat = smol::unblock(|| {
8080
let ret = procfs::KernelStats::current().context("reading /proc/stat")?;
8181
Ok::<procfs::KernelStats, anyhow::Error>(ret)
@@ -115,13 +115,15 @@ impl CpuUsage {
115115
}
116116

117117
/// Calculate the CPU usage between two snapshots taken via [`Self::now()`] for all CPU cores.
118+
#[allow(clippy::cast_precision_loss)]
118119
pub fn percentage_all_cores(&self, prev: &Self) -> f64 {
119120
let diff = self.total_ticks - prev.total_ticks;
120121
(diff.total_ticks - diff.idle_ticks) as f64 / diff.total_ticks as f64
121122
}
122123

123124
/// Calculate the CPU usage between two snapshots taken via [`Self::now()`] for each CPU core
124125
/// separately.
126+
#[allow(clippy::cast_precision_loss)]
125127
pub fn percentage_per_core(&self, prev: &Self) -> Vec<f64> {
126128
self.per_core_ticks
127129
.iter()

src/metrics/disk.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl IOMetrics {
2929
// We try to only collect statistics about disks which are mounted.
3030
let mounts = smol::unblock(|| procfs::mounts().context("reading /proc/mounts")).await?;
3131

32-
let mut ret = IOMetrics {
32+
let mut ret = Self {
3333
disks: HashMap::new(),
3434
};
3535

0 commit comments

Comments
 (0)