1pub mod cpu;
44pub mod disk;
45pub mod gauges;
46pub mod mem;
47pub mod net;
48pub mod pressure;
49pub mod process;
50mod sampler;
51
52use std::time::Duration;
53
54pub use cpu::CpuReading;
55pub use sampler::spawn;
56
57pub const CATEGORY_NAMES: &[&str] = &[
59 "cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc",
60];
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct Categories {
65 pub cpu: bool,
66 pub io: bool,
67 pub ram: bool,
68 pub rambw: bool,
69 pub storage: bool,
70 pub net: bool,
71 pub pressure: bool,
72 pub proc: bool,
73}
74
75impl Categories {
76 pub const ALL: Categories = Categories {
77 cpu: true,
78 io: true,
79 ram: true,
80 rambw: true,
81 storage: true,
82 net: true,
83 pressure: true,
84 proc: true,
85 };
86
87 pub fn any(&self) -> bool {
88 *self != Categories::default()
89 }
90
91 fn flag(&mut self, name: &str) -> Option<&mut bool> {
93 Some(match name {
94 "cpu" => &mut self.cpu,
95 "io" => &mut self.io,
96 "ram" => &mut self.ram,
97 "rambw" => &mut self.rambw,
98 "storage" => &mut self.storage,
99 "net" => &mut self.net,
100 "pressure" => &mut self.pressure,
101 "proc" => &mut self.proc,
102 _ => return None,
103 })
104 }
105
106 pub fn names(&self) -> String {
108 let mut copy = *self;
109 CATEGORY_NAMES
110 .iter()
111 .filter(|name| copy.flag(name).is_some_and(|on| *on))
112 .copied()
113 .collect::<Vec<_>>()
114 .join(",")
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Selection {
122 Cats(Categories),
125 Any,
128}
129
130pub fn parse_selection(value: &str) -> Result<Selection, String> {
135 let trimmed = value.trim();
136 if trimmed.eq_ignore_ascii_case("any") {
137 return Ok(Selection::Any);
138 }
139 if trimmed
140 .to_ascii_lowercase()
141 .split(',')
142 .any(|t| t.trim() == "any")
143 {
144 return Err("sysmon: `any` stands alone (it means \"every available \
145 subsystem\") — combining it with named categories is \
146 ambiguous. Use `sysmon=any`, or name the categories."
147 .to_string());
148 }
149 parse_categories(trimmed).map(Selection::Cats)
150}
151
152pub fn parse_categories(value: &str) -> Result<Categories, String> {
155 if value.trim().eq_ignore_ascii_case("all") {
156 return Ok(Categories::ALL);
157 }
158 let valid = CATEGORY_NAMES.join(", ");
159 let mut cats = Categories::default();
160 for token in value.split(',') {
161 let name = token.trim().to_ascii_lowercase();
162 if name.is_empty() {
163 continue;
164 }
165 match cats.flag(&name) {
166 Some(flag) => *flag = true,
167 None => {
168 return Err(format!(
169 "sysmon: unknown category '{name}'. Valid: all, any, or a \
170 comma list of {valid}"
171 ));
172 }
173 }
174 }
175 if !cats.any() {
176 return Err(format!(
177 "sysmon: no categories enabled. Use `sysmon=all`, `sysmon=any` or a comma \
178 list of {valid}"
179 ));
180 }
181 Ok(cats)
182}
183
184#[derive(Debug, Clone, PartialEq, Default)]
188pub struct SysmonSample {
189 pub cpu: Option<CpuReading>,
190 pub io: Option<(String, f64)>,
192 pub io_rates: Vec<disk::DiskRate>,
194 pub ram: Option<(f64, f64)>,
196 pub rambw: Option<f64>,
198 pub storage: Option<(String, f64)>,
200 pub net: Vec<net::NetRate>,
202 pub pressure: Option<pressure::PressureReading>,
204 pub procs: Vec<process::ProcReading>,
206}
207
208#[derive(Debug, Clone)]
210pub struct SysmonConfig {
211 pub cats: Categories,
212 pub interval: Duration,
214 pub membw_peak_bytes_per_s: Option<f64>,
217 pub procs: Vec<process::ProcTarget>,
219}
220
221pub const fn platform_supported() -> bool {
223 cfg!(target_os = "linux")
224}
225
226pub const UNSUPPORTED_PLATFORM: &str = "sysmon: the sampler reads /proc and is available on \
228 Linux only; run without `sysmon=` on this host";
229
230pub fn check_rambw_requirements(config: &SysmonConfig) -> Result<(), String> {
234 if !config.cats.rambw {
235 return Ok(());
236 }
237 if mem::read_membw_bytes().is_none() {
238 return Err("\
239sysmon: rambw was requested, but the kernel resctrl interface is not \
240available at /sys/fs/resctrl/mon_data.
241
242To enable memory-bandwidth monitoring:
243 1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
244 check for the `cqm_mbm_total` flag: grep -m1 cqm_mbm_total /proc/cpuinfo
245 2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
246 mainstream distro kernels).
247 3. Mount the interface: sudo mount -t resctrl resctrl /sys/fs/resctrl
248
249If this host cannot support it (most VMs cannot), name the categories \
250without rambw, or use sysmon=any to enable every subsystem this host \
251supports."
252 .to_string());
253 }
254 if config.membw_peak_bytes_per_s.is_none() {
255 return Err("\
256sysmon: rambw needs a peak-bandwidth reference to turn bytes/s into a \
257utilization. Set it with sysmon_membw_gbps=<peak> (the host's rated \
258memory bandwidth in GB/s), name the categories without rambw, or use \
259sysmon=any"
260 .to_string());
261 }
262 Ok(())
263}
264
265pub fn check_pressure_requirements(config: &SysmonConfig) -> Result<(), String> {
267 if !config.cats.pressure || pressure::read_pressure().is_some() {
268 return Ok(());
269 }
270 Err("\
271sysmon: pressure was requested, but the kernel's pressure stall \
272information is not readable at /proc/pressure. It needs a kernel built \
273with CONFIG_PSI (4.20 or later) that was not booted with `psi=0`, and a \
274container must be given the host's /proc/pressure. Name the categories \
275without pressure, or use sysmon=any to enable every subsystem this \
276host supports."
277 .to_string())
278}
279
280pub fn check_requirements(config: &SysmonConfig) -> Result<(), String> {
284 if !platform_supported() {
285 return Err(UNSUPPORTED_PLATFORM.to_string());
286 }
287 if !config.procs.is_empty() && !config.cats.proc {
288 return Err(
289 "sysmon: `sysmon_procs=` names processes to watch, and the `proc` \
290 category is not enabled; add `proc` to `sysmon=`"
291 .to_string(),
292 );
293 }
294 check_rambw_requirements(config)?;
295 check_pressure_requirements(config)
296}
297
298pub fn resolve_any(config: &SysmonConfig) -> (Categories, Vec<String>) {
307 if !platform_supported() {
308 return (
309 Categories::default(),
310 vec![UNSUPPORTED_PLATFORM.to_string()],
311 );
312 }
313 let mut cats = Categories::ALL;
314 let mut skipped = Vec::new();
315 let probe = SysmonConfig {
316 cats,
317 ..config.clone()
318 };
319 let first = |reason: String| reason.lines().next().unwrap_or("unavailable").to_string();
322 if let Err(reason) = check_rambw_requirements(&probe) {
323 cats.rambw = false;
324 skipped.push(format!(
325 "{} (run `sysmon=rambw` for the enable steps)",
326 first(reason)
327 ));
328 }
329 if let Err(reason) = check_pressure_requirements(&probe) {
330 cats.pressure = false;
331 skipped.push(format!(
332 "{} (run `sysmon=pressure` for the details)",
333 first(reason)
334 ));
335 }
336 (cats, skipped)
337}
338
339#[cfg(test)]
340mod tests;