use std::path::PathBuf;
pub const OWN_NAME: &str = "nmbrs";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcSource {
Own,
Pid(u32),
PidFile(PathBuf),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcTarget {
pub name: String,
pub source: ProcSource,
}
pub fn parse_procs(value: &str) -> Result<Vec<ProcTarget>, String> {
let mut targets: Vec<ProcTarget> = Vec::new();
for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
let Some((name, source)) = item.split_once(':') else {
return Err(format!(
"sysmon_procs: '{item}' is not `name:pid` or `name:/path/to/pidfile`"
));
};
let (name, source) = (name.trim(), source.trim());
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(format!(
"sysmon_procs: '{name}' is not a name; a name is letters, digits, `_` and `-`"
));
}
if name == OWN_NAME {
return Err(format!(
"sysmon_procs: `{OWN_NAME}` names nmbrs's own process, which is always watched"
));
}
if targets.iter().any(|t| t.name == name) {
return Err(format!("sysmon_procs: the name '{name}' is given twice"));
}
let source = if source.is_empty() {
return Err(format!("sysmon_procs: '{name}' has no pid or pidfile"));
} else if let Ok(pid) = source.parse::<u32>() {
ProcSource::Pid(pid)
} else if source.starts_with('/') {
ProcSource::PidFile(PathBuf::from(source))
} else {
return Err(format!(
"sysmon_procs: '{source}' (for '{name}') is neither a process id nor an \
absolute path to a pidfile"
));
};
targets.push(ProcTarget {
name: name.to_string(),
source,
});
}
Ok(targets)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ProcCounters {
pub cpu_ticks: u64,
pub threads: u64,
pub rss_pages: u64,
pub io: Option<(u64, u64)>,
}
pub fn parse_stat(text: &str) -> Option<(u64, u64, u64)> {
let after = &text[text.rfind(')')? + 1..];
let fields: Vec<&str> = after.split_whitespace().collect();
let field = |at: usize| -> Option<u64> { fields.get(at)?.parse().ok() };
Some((field(11)? + field(12)?, field(17)?, field(21)?))
}
pub fn parse_io(text: &str) -> Option<(u64, u64)> {
let value = |key: &str| -> Option<u64> {
text.lines()
.find_map(|line| line.strip_prefix(key))?
.trim()
.parse()
.ok()
};
Some((value("read_bytes:")?, value("write_bytes:")?))
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcReading {
pub name: String,
pub cpu_cores: f64,
pub rss_bytes: f64,
pub threads: f64,
pub io_bytes_per_s: Option<(f64, f64)>,
}
pub fn reading(
name: &str,
prev: ProcCounters,
cur: ProcCounters,
dt_s: f64,
ticks_per_s: f64,
page_bytes: f64,
) -> ProcReading {
let per_s = |before: u64, now: u64| -> f64 {
if dt_s <= 0.0 {
0.0
} else {
now.saturating_sub(before) as f64 / dt_s
}
};
ProcReading {
name: name.to_string(),
cpu_cores: per_s(prev.cpu_ticks, cur.cpu_ticks) / ticks_per_s.max(1.0),
rss_bytes: cur.rss_pages as f64 * page_bytes,
threads: cur.threads as f64,
io_bytes_per_s: match (prev.io, cur.io) {
(Some((r0, w0)), Some((r1, w1))) => Some((per_s(r0, r1), per_s(w0, w1))),
_ => None,
},
}
}
pub(super) struct Watched {
pub target: ProcTarget,
last: Option<(u32, ProcCounters)>,
missing_reported: bool,
}
#[cfg(unix)]
fn sysconf(name: libc::c_int, fallback: f64) -> f64 {
let value = unsafe { libc::sysconf(name) };
if value > 0 { value as f64 } else { fallback }
}
pub(super) fn units() -> (f64, f64) {
#[cfg(unix)]
{
(
sysconf(libc::_SC_CLK_TCK, 100.0),
sysconf(libc::_SC_PAGESIZE, 4096.0),
)
}
#[cfg(not(unix))]
{
(100.0, 4096.0)
}
}
impl Watched {
pub fn new(target: ProcTarget) -> Self {
Self {
target,
last: None,
missing_reported: false,
}
}
fn pid(&self) -> Option<u32> {
match &self.target.source {
ProcSource::Own => Some(std::process::id()),
ProcSource::Pid(pid) => Some(*pid),
ProcSource::PidFile(path) => std::fs::read_to_string(path).ok()?.trim().parse().ok(),
}
}
fn counters(pid: u32) -> Option<ProcCounters> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let (cpu_ticks, threads, rss_pages) = parse_stat(&stat)?;
let io = std::fs::read_to_string(format!("/proc/{pid}/io"))
.ok()
.and_then(|text| parse_io(&text));
Some(ProcCounters {
cpu_ticks,
threads,
rss_pages,
io,
})
}
pub fn sample(
&mut self,
dt_s: f64,
units: (f64, f64),
missing: &mut dyn FnMut(&str),
) -> Option<ProcReading> {
let found = self.pid().and_then(|pid| Some((pid, Self::counters(pid)?)));
let Some((pid, cur)) = found else {
if !self.missing_reported {
self.missing_reported = true;
missing(&self.target.name);
}
self.last = None;
return None;
};
self.missing_reported = false;
let prev = self.last.replace((pid, cur));
match prev {
Some((prev_pid, prev)) if prev_pid == pid => Some(reading(
&self.target.name,
prev,
cur,
dt_s,
units.0,
units.1,
)),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn procs_are_names_with_a_pid_or_a_pidfile() {
assert_eq!(
parse_procs("server:1234, db:/run/db.pid").unwrap(),
vec![
ProcTarget {
name: "server".into(),
source: ProcSource::Pid(1234)
},
ProcTarget {
name: "db".into(),
source: ProcSource::PidFile("/run/db.pid".into())
},
]
);
for (value, says) in [
("server", "is not `name:pid`"),
("a b:1", "is not a name"),
("nmbrs:1", "always watched"),
("a:1,a:2", "given twice"),
("a:", "no pid or pidfile"),
("a:run/x.pid", "neither a process id nor an absolute path"),
] {
let err = parse_procs(value).unwrap_err();
assert!(err.contains(says), "{value}: {err}");
}
}
#[test]
fn stat_fields_are_counted_after_the_command_name() {
let stat = "4242 (my (odd) cmd) S 1 4242 4242 0 -1 4194560 100 0 0 0 \
700 300 0 0 20 0 17 0 12345 1000000 2500 18446744073709551615 1 1";
assert_eq!(parse_stat(stat), Some((1000, 17, 2500)));
assert_eq!(parse_stat("no parenthesis"), None);
}
#[test]
fn io_reads_the_storage_byte_counts() {
let io = "rchar: 9\nwchar: 9\nsyscr: 1\nsyscw: 1\nread_bytes: 4096\nwrite_bytes: 8192\ncancelled_write_bytes: 0\n";
assert_eq!(parse_io(io), Some((4096, 8192)));
assert_eq!(parse_io("rchar: 9\n"), None);
}
#[test]
fn a_reading_is_the_difference_over_the_window() {
let prev = ProcCounters {
cpu_ticks: 1000,
threads: 4,
rss_pages: 10,
io: Some((0, 1000)),
};
let cur = ProcCounters {
cpu_ticks: 1200,
threads: 6,
rss_pages: 20,
io: Some((4000, 1000)),
};
assert_eq!(
reading("p", prev, cur, 2.0, 100.0, 4096.0),
ProcReading {
name: "p".into(),
cpu_cores: 1.0,
rss_bytes: 81920.0,
threads: 6.0,
io_bytes_per_s: Some((2000.0, 0.0)),
}
);
}
#[cfg(target_os = "linux")]
#[test]
fn the_own_process_is_read() {
let mut own = Watched::new(ProcTarget {
name: OWN_NAME.into(),
source: ProcSource::Own,
});
let mut missing = |name: &str| panic!("{name} reported missing");
assert!(own.sample(1.0, units(), &mut missing).is_none());
let reading = own.sample(1.0, units(), &mut missing).unwrap();
assert!(reading.rss_bytes > 0.0 && reading.threads >= 1.0);
}
}