1use std::path::PathBuf;
14
15pub const OWN_NAME: &str = "nmbrs";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ProcSource {
21 Own,
23 Pid(u32),
25 PidFile(PathBuf),
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct ProcTarget {
33 pub name: String,
34 pub source: ProcSource,
35}
36
37pub fn parse_procs(value: &str) -> Result<Vec<ProcTarget>, String> {
41 let mut targets: Vec<ProcTarget> = Vec::new();
42 for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
43 let Some((name, source)) = item.split_once(':') else {
44 return Err(format!(
45 "sysmon_procs: '{item}' is not `name:pid` or `name:/path/to/pidfile`"
46 ));
47 };
48 let (name, source) = (name.trim(), source.trim());
49 if name.is_empty()
50 || !name
51 .chars()
52 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
53 {
54 return Err(format!(
55 "sysmon_procs: '{name}' is not a name; a name is letters, digits, `_` and `-`"
56 ));
57 }
58 if name == OWN_NAME {
59 return Err(format!(
60 "sysmon_procs: `{OWN_NAME}` names nmbrs's own process, which is always watched"
61 ));
62 }
63 if targets.iter().any(|t| t.name == name) {
64 return Err(format!("sysmon_procs: the name '{name}' is given twice"));
65 }
66 let source = if source.is_empty() {
67 return Err(format!("sysmon_procs: '{name}' has no pid or pidfile"));
68 } else if let Ok(pid) = source.parse::<u32>() {
69 ProcSource::Pid(pid)
70 } else if source.starts_with('/') {
71 ProcSource::PidFile(PathBuf::from(source))
72 } else {
73 return Err(format!(
74 "sysmon_procs: '{source}' (for '{name}') is neither a process id nor an \
75 absolute path to a pidfile"
76 ));
77 };
78 targets.push(ProcTarget {
79 name: name.to_string(),
80 source,
81 });
82 }
83 Ok(targets)
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub struct ProcCounters {
89 pub cpu_ticks: u64,
91 pub threads: u64,
92 pub rss_pages: u64,
94 pub io: Option<(u64, u64)>,
97}
98
99pub fn parse_stat(text: &str) -> Option<(u64, u64, u64)> {
105 let after = &text[text.rfind(')')? + 1..];
106 let fields: Vec<&str> = after.split_whitespace().collect();
107 let field = |at: usize| -> Option<u64> { fields.get(at)?.parse().ok() };
108 Some((field(11)? + field(12)?, field(17)?, field(21)?))
109}
110
111pub fn parse_io(text: &str) -> Option<(u64, u64)> {
113 let value = |key: &str| -> Option<u64> {
114 text.lines()
115 .find_map(|line| line.strip_prefix(key))?
116 .trim()
117 .parse()
118 .ok()
119 };
120 Some((value("read_bytes:")?, value("write_bytes:")?))
121}
122
123#[derive(Debug, Clone, PartialEq)]
125pub struct ProcReading {
126 pub name: String,
127 pub cpu_cores: f64,
129 pub rss_bytes: f64,
130 pub threads: f64,
131 pub io_bytes_per_s: Option<(f64, f64)>,
133}
134
135pub fn reading(
137 name: &str,
138 prev: ProcCounters,
139 cur: ProcCounters,
140 dt_s: f64,
141 ticks_per_s: f64,
142 page_bytes: f64,
143) -> ProcReading {
144 let per_s = |before: u64, now: u64| -> f64 {
145 if dt_s <= 0.0 {
146 0.0
147 } else {
148 now.saturating_sub(before) as f64 / dt_s
149 }
150 };
151 ProcReading {
152 name: name.to_string(),
153 cpu_cores: per_s(prev.cpu_ticks, cur.cpu_ticks) / ticks_per_s.max(1.0),
154 rss_bytes: cur.rss_pages as f64 * page_bytes,
155 threads: cur.threads as f64,
156 io_bytes_per_s: match (prev.io, cur.io) {
157 (Some((r0, w0)), Some((r1, w1))) => Some((per_s(r0, r1), per_s(w0, w1))),
158 _ => None,
159 },
160 }
161}
162
163pub(super) struct Watched {
166 pub target: ProcTarget,
167 last: Option<(u32, ProcCounters)>,
168 missing_reported: bool,
171}
172
173#[cfg(unix)]
175fn sysconf(name: libc::c_int, fallback: f64) -> f64 {
176 let value = unsafe { libc::sysconf(name) };
177 if value > 0 { value as f64 } else { fallback }
178}
179
180pub(super) fn units() -> (f64, f64) {
182 #[cfg(unix)]
183 {
184 (
185 sysconf(libc::_SC_CLK_TCK, 100.0),
186 sysconf(libc::_SC_PAGESIZE, 4096.0),
187 )
188 }
189 #[cfg(not(unix))]
190 {
191 (100.0, 4096.0)
192 }
193}
194
195impl Watched {
196 pub fn new(target: ProcTarget) -> Self {
197 Self {
198 target,
199 last: None,
200 missing_reported: false,
201 }
202 }
203
204 fn pid(&self) -> Option<u32> {
205 match &self.target.source {
206 ProcSource::Own => Some(std::process::id()),
207 ProcSource::Pid(pid) => Some(*pid),
208 ProcSource::PidFile(path) => std::fs::read_to_string(path).ok()?.trim().parse().ok(),
209 }
210 }
211
212 fn counters(pid: u32) -> Option<ProcCounters> {
213 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
214 let (cpu_ticks, threads, rss_pages) = parse_stat(&stat)?;
215 let io = std::fs::read_to_string(format!("/proc/{pid}/io"))
216 .ok()
217 .and_then(|text| parse_io(&text));
218 Some(ProcCounters {
219 cpu_ticks,
220 threads,
221 rss_pages,
222 io,
223 })
224 }
225
226 pub fn sample(
232 &mut self,
233 dt_s: f64,
234 units: (f64, f64),
235 missing: &mut dyn FnMut(&str),
236 ) -> Option<ProcReading> {
237 let found = self.pid().and_then(|pid| Some((pid, Self::counters(pid)?)));
238 let Some((pid, cur)) = found else {
239 if !self.missing_reported {
240 self.missing_reported = true;
241 missing(&self.target.name);
242 }
243 self.last = None;
244 return None;
245 };
246 self.missing_reported = false;
247 let prev = self.last.replace((pid, cur));
248 match prev {
249 Some((prev_pid, prev)) if prev_pid == pid => Some(reading(
251 &self.target.name,
252 prev,
253 cur,
254 dt_s,
255 units.0,
256 units.1,
257 )),
258 _ => None,
259 }
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn procs_are_names_with_a_pid_or_a_pidfile() {
269 assert_eq!(
270 parse_procs("server:1234, db:/run/db.pid").unwrap(),
271 vec![
272 ProcTarget {
273 name: "server".into(),
274 source: ProcSource::Pid(1234)
275 },
276 ProcTarget {
277 name: "db".into(),
278 source: ProcSource::PidFile("/run/db.pid".into())
279 },
280 ]
281 );
282 for (value, says) in [
283 ("server", "is not `name:pid`"),
284 ("a b:1", "is not a name"),
285 ("nmbrs:1", "always watched"),
286 ("a:1,a:2", "given twice"),
287 ("a:", "no pid or pidfile"),
288 ("a:run/x.pid", "neither a process id nor an absolute path"),
289 ] {
290 let err = parse_procs(value).unwrap_err();
291 assert!(err.contains(says), "{value}: {err}");
292 }
293 }
294
295 #[test]
298 fn stat_fields_are_counted_after_the_command_name() {
299 let stat = "4242 (my (odd) cmd) S 1 4242 4242 0 -1 4194560 100 0 0 0 \
300 700 300 0 0 20 0 17 0 12345 1000000 2500 18446744073709551615 1 1";
301 assert_eq!(parse_stat(stat), Some((1000, 17, 2500)));
302 assert_eq!(parse_stat("no parenthesis"), None);
303 }
304
305 #[test]
306 fn io_reads_the_storage_byte_counts() {
307 let io = "rchar: 9\nwchar: 9\nsyscr: 1\nsyscw: 1\nread_bytes: 4096\nwrite_bytes: 8192\ncancelled_write_bytes: 0\n";
308 assert_eq!(parse_io(io), Some((4096, 8192)));
309 assert_eq!(parse_io("rchar: 9\n"), None);
310 }
311
312 #[test]
314 fn a_reading_is_the_difference_over_the_window() {
315 let prev = ProcCounters {
316 cpu_ticks: 1000,
317 threads: 4,
318 rss_pages: 10,
319 io: Some((0, 1000)),
320 };
321 let cur = ProcCounters {
322 cpu_ticks: 1200,
323 threads: 6,
324 rss_pages: 20,
325 io: Some((4000, 1000)),
326 };
327 assert_eq!(
328 reading("p", prev, cur, 2.0, 100.0, 4096.0),
329 ProcReading {
330 name: "p".into(),
331 cpu_cores: 1.0,
332 rss_bytes: 81920.0,
333 threads: 6.0,
334 io_bytes_per_s: Some((2000.0, 0.0)),
335 }
336 );
337 }
338
339 #[cfg(target_os = "linux")]
342 #[test]
343 fn the_own_process_is_read() {
344 let mut own = Watched::new(ProcTarget {
345 name: OWN_NAME.into(),
346 source: ProcSource::Own,
347 });
348 let mut missing = |name: &str| panic!("{name} reported missing");
349 assert!(own.sample(1.0, units(), &mut missing).is_none());
350 let reading = own.sample(1.0, units(), &mut missing).unwrap();
351 assert!(reading.rss_bytes > 0.0 && reading.threads >= 1.0);
352 }
353}