Skip to main content

monitord/
pid1.rs

1//! # pid1 module
2//!
3//! `pid1` uses procfs to get some statistics on Linux's more important
4//! process pid1. These metrics can help ensure newer systemds don't regress
5//! or show stange behavior. E.g. more file descriptors without more units.
6
7use std::sync::Arc;
8
9#[cfg(target_os = "linux")]
10use procfs::process::Process;
11use thiserror::Error;
12use tokio::sync::RwLock;
13use tracing::error;
14use tracing::Instrument;
15
16use crate::MachineStats;
17
18#[derive(Error, Debug)]
19pub enum MonitordPid1Error {
20    #[cfg(target_os = "linux")]
21    #[error("Procfs error: {0}")]
22    ProcfsError(#[from] procfs::ProcError),
23    #[error("Integer conversion error: {0}")]
24    IntConversion(#[from] std::num::TryFromIntError),
25}
26
27/// Process-level statistics for PID 1 (systemd) read from procfs.
28/// These metrics help detect regressions or anomalies in the init process itself.
29/// Ref: <https://manpages.debian.org/buster/manpages/procfs.5.en.html>
30#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
31pub struct Pid1Stats {
32    /// CPU time spent in kernel mode by PID 1, in seconds (from /proc/1/stat stime, converted from ticks)
33    pub cpu_time_kernel: u64,
34    /// CPU time spent in user mode by PID 1, in seconds (from /proc/1/stat utime, converted from ticks)
35    pub cpu_time_user: u64,
36    /// Resident set size of PID 1 in bytes (from /proc/1/stat rss, converted from pages)
37    pub memory_usage_bytes: u64,
38    /// Number of open file descriptors held by PID 1 (from /proc/1/fd/)
39    pub fd_count: u64,
40    /// Number of threads/tasks belonging to PID 1 (from /proc/1/task/)
41    pub tasks: u64,
42}
43
44/// Get procfs info on pid 1 - <https://manpages.debian.org/buster/manpages/procfs.5.en.html>
45#[cfg(target_os = "linux")]
46pub fn get_pid_stats(pid: i32) -> Result<Pid1Stats, MonitordPid1Error> {
47    let bytes_per_page = procfs::page_size();
48    let ticks_per_second = procfs::ticks_per_second();
49
50    let pid1_proc = Process::new(pid)?;
51    let stat_file = pid1_proc.stat()?;
52
53    // Living with integer rounding
54    Ok(Pid1Stats {
55        cpu_time_kernel: (stat_file.stime) / (ticks_per_second),
56        cpu_time_user: (stat_file.utime) / (ticks_per_second),
57        memory_usage_bytes: (stat_file.rss) * (bytes_per_page),
58        fd_count: pid1_proc.fd_count()?.try_into()?,
59        // Using 0 as impossible number of tasks
60        tasks: pid1_proc
61            .tasks()?
62            .flatten()
63            .collect::<Vec<_>>()
64            .len()
65            .try_into()?,
66    })
67}
68
69#[cfg(not(target_os = "linux"))]
70pub fn get_pid_stats(_pid: i32) -> Result<Pid1Stats, MonitordPid1Error> {
71    error!("pid1 stats not supported on this OS");
72    Ok(Pid1Stats::default())
73}
74
75/// Async wrapper than can update PID1 stats when passed a locked struct
76///
77/// Split into two spans (blocking procfs read vs. write-lock acquisition) so a
78/// slow run can be attributed to actual work vs. contention on the
79/// `MachineStats` lock shared with every other collector.
80pub async fn update_pid1_stats(
81    pid: i32,
82    locked_machine_stats: Arc<RwLock<MachineStats>>,
83) -> anyhow::Result<()> {
84    let pid1_stats = match tokio::task::spawn_blocking(move || get_pid_stats(pid))
85        .instrument(tracing::debug_span!("pid1_blocking_read"))
86        .await
87    {
88        Ok(p1s) => p1s,
89        Err(err) => return Err(err.into()),
90    };
91
92    let mut machine_stats = locked_machine_stats
93        .write()
94        .instrument(tracing::debug_span!("pid1_acquire_write_lock"))
95        .await;
96    machine_stats.pid1 = match pid1_stats {
97        Ok(s) => Some(s),
98        Err(err) => {
99            error!("Unable to set pid1 stats: {:?}", err);
100            None
101        }
102    };
103
104    Ok(())
105}
106
107#[cfg(target_os = "linux")]
108#[cfg(test)]
109pub mod tests {
110    use super::*;
111
112    #[test]
113    pub fn test_get_stats() -> Result<(), MonitordPid1Error> {
114        let pid1_stats = get_pid_stats(1)?;
115        assert!(pid1_stats.tasks > 0);
116        Ok(())
117    }
118}