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