1use 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#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
31pub struct Pid1Stats {
32 pub cpu_time_kernel: u64,
34 pub cpu_time_user: u64,
36 pub memory_usage_bytes: u64,
38 pub fd_count: u64,
40 pub tasks: u64,
42}
43
44#[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 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 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
75pub 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}