Skip to main content

hyperi_rustlib/metrics/
process.rs

1// Project:   hyperi-rustlib
2// File:      src/metrics/process.rs
3// Purpose:   Process-level metrics collection
4// Language:  Rust
5//
6// License:   FSL-1.1-ALv2
7// Copyright: (c) 2026 HYPERI PTY LIMITED
8
9//! Process-level metrics collection.
10
11use std::sync::Arc;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System};
15
16/// Process metrics collector.
17#[derive(Debug, Clone)]
18pub struct ProcessMetrics {
19    namespace: String,
20    system: Arc<std::sync::Mutex<System>>,
21    pid: sysinfo::Pid,
22    start_time: f64,
23}
24
25impl ProcessMetrics {
26    /// Create a new process metrics collector.
27    #[must_use]
28    pub fn new(namespace: &str) -> Self {
29        let pid = sysinfo::Pid::from_u32(std::process::id());
30        let system = System::new_with_specifics(
31            RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
32        );
33
34        let start_time = SystemTime::now()
35            .duration_since(UNIX_EPOCH)
36            .map(|d| d.as_secs_f64())
37            .unwrap_or(0.0);
38
39        let this = Self {
40            namespace: namespace.to_string(),
41            system: Arc::new(std::sync::Mutex::new(system)),
42            pid,
43            start_time,
44        };
45
46        // Register metric descriptions
47        this.register_metrics();
48        this
49    }
50
51    /// Register metric descriptions.
52    fn register_metrics(&self) {
53        let ns = &self.namespace;
54
55        metrics::describe_gauge!(
56            format!("{ns}_process_cpu_seconds_total"),
57            "Total user and system CPU time spent in seconds".to_string()
58        );
59        metrics::describe_gauge!(
60            format!("{ns}_process_resident_memory_bytes"),
61            "Resident memory size in bytes".to_string()
62        );
63        metrics::describe_gauge!(
64            format!("{ns}_process_virtual_memory_bytes"),
65            "Virtual memory size in bytes".to_string()
66        );
67        metrics::describe_gauge!(
68            format!("{ns}_process_open_fds"),
69            "Number of open file descriptors".to_string()
70        );
71        metrics::describe_gauge!(
72            format!("{ns}_process_start_time_seconds"),
73            "Start time of the process since unix epoch in seconds".to_string()
74        );
75    }
76
77    /// Update process metrics.
78    pub fn update(&self) {
79        let mut system = self.system.lock().expect("lock poisoned");
80        system.refresh_processes_specifics(
81            ProcessesToUpdate::Some(&[self.pid]),
82            true,
83            ProcessRefreshKind::everything(),
84        );
85
86        if let Some(process) = system.process(self.pid) {
87            let ns = &self.namespace;
88
89            // CPU time (approximate - sysinfo gives percentage, not total time)
90            let cpu_usage = f64::from(process.cpu_usage());
91            metrics::gauge!(format!("{ns}_process_cpu_seconds_total")).set(cpu_usage);
92
93            // Memory
94            let rss = process.memory();
95            let virtual_mem = process.virtual_memory();
96            metrics::gauge!(format!("{ns}_process_resident_memory_bytes")).set(rss as f64);
97            metrics::gauge!(format!("{ns}_process_virtual_memory_bytes")).set(virtual_mem as f64);
98
99            // File descriptors (Linux-specific)
100            #[cfg(target_os = "linux")]
101            {
102                if let Ok(fds) = count_open_fds() {
103                    metrics::gauge!(format!("{ns}_process_open_fds")).set(fds as f64);
104                }
105            }
106
107            // Start time
108            metrics::gauge!(format!("{ns}_process_start_time_seconds")).set(self.start_time);
109        }
110    }
111}
112
113/// Count open file descriptors (Linux only).
114#[cfg(target_os = "linux")]
115fn count_open_fds() -> std::io::Result<usize> {
116    let fd_dir = format!("/proc/{}/fd", std::process::id());
117    std::fs::read_dir(fd_dir).map(|entries| entries.count())
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn test_process_metrics_new() {
126        let pm = ProcessMetrics::new("test");
127        assert_eq!(pm.namespace, "test");
128        assert!(pm.start_time > 0.0);
129    }
130
131    #[test]
132    fn test_process_metrics_update() {
133        let pm = ProcessMetrics::new("test");
134        // Should not panic
135        pm.update();
136    }
137}