Skip to main content

runtimo_core/
monitor.rs

1//! Health Monitoring Daemon — Background health checks with alerting.
2//!
3//! Monitors system health by capturing periodic snapshots of hardware telemetry
4//! and process state. Alerts on threshold violations:
5//! - Zombie processes > 10
6//! - CPU usage > 90% for 5 consecutive minutes
7//! - Memory monotonic increase (potential leak)
8//!
9//! # Example
10//!
11//! ```rust,ignore
12//! use runtimo_core::HealthMonitor;
13//!
14//! let monitor = HealthMonitor::start()?;
15//! // Monitor runs in background, checking every 60s
16//! // Access latest health state:
17//! let health = monitor.health();
18//! println!("CPU: {:.1}%, RAM: {:.1}%", health.cpu_percent, health.ram_percent);
19//! ```
20
21use crate::processes::ProcessSnapshot;
22use crate::telemetry::Telemetry;
23use serde::{Deserialize, Serialize};
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::{Arc, RwLock};
26use std::thread;
27use std::time::Duration;
28
29/// Alert thresholds for health monitoring.
30const ZOMBIE_THRESHOLD: usize = 10;
31const CPU_THRESHOLD: f32 = 90.0;
32const CPU_ALERT_MINUTES: usize = 5;
33const CHECK_INTERVAL_SECS: u64 = 60;
34
35/// Current health state snapshot.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37#[allow(clippy::exhaustive_structs)]
38pub struct HealthState {
39    /// Unix timestamp of last check.
40    pub timestamp: u64,
41    /// Total CPU usage percentage.
42    pub cpu_percent: f32,
43    /// Total memory usage percentage.
44    pub ram_percent: f32,
45    /// Number of zombie processes.
46    pub zombie_count: usize,
47    /// Total process count.
48    pub process_count: usize,
49    /// Top CPU consuming process name.
50    pub top_cpu_process: Option<String>,
51    /// Top memory consuming process name.
52    pub top_mem_process: Option<String>,
53    /// Number of consecutive minutes CPU exceeded threshold.
54    pub cpu_alert_count: usize,
55    /// Number of consecutive checks with monotonically increasing RAM.
56    pub ram_alert_count: usize,
57    /// Whether memory is monotonically increasing.
58    pub ram_increasing: bool,
59    /// Last RAM usage for monotonicity check.
60    pub last_ram_percent: Option<f32>,
61}
62
63impl Default for HealthState {
64    fn default() -> Self {
65        Self {
66            timestamp: 0,
67            cpu_percent: 0.0,
68            ram_percent: 0.0,
69            zombie_count: 0,
70            process_count: 0,
71            top_cpu_process: None,
72            top_mem_process: None,
73            cpu_alert_count: 0,
74            ram_alert_count: 0,
75            ram_increasing: false,
76            last_ram_percent: None,
77        }
78    }
79}
80
81/// Health alert types.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[allow(clippy::exhaustive_enums)]
84pub enum HealthAlert {
85    /// Zombie process count exceeded threshold.
86    ZombieCount { count: usize, threshold: usize },
87    /// CPU usage exceeded threshold for consecutive minutes.
88    CpuHigh { percent: f32, minutes: usize },
89    /// Memory usage monotonically increasing (potential leak).
90    MemoryLeak { ram_percent: f32 },
91}
92
93impl std::fmt::Display for HealthAlert {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            Self::ZombieCount { count, threshold } => {
97                write!(f, "Zombie processes: {} (threshold: {})", count, threshold)
98            }
99            Self::CpuHigh { percent, minutes } => {
100                write!(f, "CPU usage: {:.1}% for {} minutes", percent, minutes)
101            }
102            Self::MemoryLeak { ram_percent } => {
103                write!(f, "Memory leak detected: {:.1}% RAM", ram_percent)
104            }
105        }
106    }
107}
108
109/// Health monitoring daemon with background thread.
110///
111/// Captures snapshots every 60 seconds and alerts on threshold violations.
112/// Thread-safe state access via RwLock.
113#[allow(clippy::exhaustive_structs)]
114pub struct HealthMonitor {
115    /// Shared health state.
116    state: Arc<RwLock<HealthState>>,
117    /// Stop flag for background thread.
118    stop_flag: Arc<AtomicBool>,
119    /// Background thread handle.
120    _thread: thread::JoinHandle<()>,
121    /// Alert history (last 100 alerts).
122    alerts: Arc<RwLock<Vec<HealthAlert>>>,
123}
124
125impl Drop for HealthMonitor {
126    fn drop(&mut self) {
127        self.stop_flag.store(true, Ordering::Relaxed);
128    }
129}
130
131impl HealthMonitor {
132    /// Starts the health monitoring background thread.
133    ///
134    /// The monitor checks system health every 60 seconds and updates
135    /// the shared health state. Alerts are generated for:
136    /// - Zombie count > 10
137    /// - CPU > 90% for 5+ consecutive minutes
138    /// - Monotonic RAM increase
139    ///
140    /// # Returns
141    ///
142    /// `Ok(HealthMonitor)` on success, or error if thread spawn fails.
143    ///
144    /// # Errors
145    ///
146    /// Returns `Err(String)` if the background monitoring thread fails to spawn.
147    #[allow(clippy::arithmetic_side_effects)] // alert counters are intentional increments
148    pub fn start() -> Result<Self, String> {
149        let state = Arc::new(RwLock::new(HealthState::default()));
150        let alerts = Arc::new(RwLock::new(Vec::new()));
151        let stop_flag = Arc::new(AtomicBool::new(false));
152
153        let state_clone = Arc::clone(&state);
154        let alerts_clone = Arc::clone(&alerts);
155        let stop_flag_clone = Arc::clone(&stop_flag);
156
157        let handle = thread::spawn(move || {
158            while !stop_flag_clone.load(Ordering::Relaxed) {
159                // Capture health snapshot
160                let telemetry = Telemetry::capture();
161                let processes = ProcessSnapshot::capture();
162
163                let mut current_state = state_clone.write().unwrap_or_else(|e| {
164                    eprintln!("[HealthMonitor] State lock poisoned: {}", e);
165                    // Recover from poison by taking the broken lock
166                    e.into_inner()
167                });
168
169                // Update state
170                current_state.timestamp = telemetry.timestamp;
171                current_state.cpu_percent = processes.summary.total_cpu_percent;
172                current_state.ram_percent =
173                    parse_ram_percent(&telemetry.system.ram_total, &telemetry.system.ram_free);
174                current_state.zombie_count = processes.summary.zombie_count;
175                current_state.process_count = processes.summary.total_processes;
176                current_state.top_cpu_process.clone_from(&processes.summary.top_cpu_consumer);
177                current_state.top_mem_process.clone_from(&processes.summary.top_mem_consumer);
178
179                // Check CPU threshold
180                if current_state.cpu_percent > CPU_THRESHOLD {
181                    current_state.cpu_alert_count += 1;
182                    if current_state.cpu_alert_count >= CPU_ALERT_MINUTES {
183                        let alert = HealthAlert::CpuHigh {
184                            percent: current_state.cpu_percent,
185                            minutes: current_state.cpu_alert_count,
186                        };
187                        add_alert(&alerts_clone, alert);
188                    }
189                } else {
190                    current_state.cpu_alert_count = 0;
191                }
192
193                // Check memory monotonicity
194                if let Some(last_ram) = current_state.last_ram_percent {
195                    if current_state.ram_percent > last_ram {
196                        current_state.ram_increasing = true;
197                        current_state.ram_alert_count += 1;
198                        // Alert if RAM increased for 5 consecutive checks
199                        if current_state.ram_alert_count >= 5 {
200                            let alert = HealthAlert::MemoryLeak {
201                                ram_percent: current_state.ram_percent,
202                            };
203                            add_alert(&alerts_clone, alert);
204                        }
205                    } else {
206                        current_state.ram_increasing = false;
207                        current_state.ram_alert_count = 0;
208                    }
209                }
210                current_state.last_ram_percent = Some(current_state.ram_percent);
211
212                // Check zombie threshold
213                if current_state.zombie_count > ZOMBIE_THRESHOLD {
214                    let alert = HealthAlert::ZombieCount {
215                        count: current_state.zombie_count,
216                        threshold: ZOMBIE_THRESHOLD,
217                    };
218                    add_alert(&alerts_clone, alert);
219                }
220
221                // Sleep for check interval
222                for _ in 0..CHECK_INTERVAL_SECS {
223                    if stop_flag_clone.load(Ordering::Relaxed) {
224                        break;
225                    }
226                    thread::sleep(Duration::from_secs(1));
227                }
228            }
229        });
230
231        Ok(Self {
232            state,
233            stop_flag,
234            _thread: handle,
235            alerts,
236        })
237    }
238
239    /// Returns the current health state snapshot.
240    #[must_use] 
241    pub fn health(&self) -> HealthState {
242        self.state.read().unwrap_or_else(|e| e.into_inner()).clone()
243    }
244
245    /// Returns recent health alerts (up to 100).
246    #[must_use] 
247    pub fn alerts(&self) -> Vec<HealthAlert> {
248        self.alerts
249            .read()
250            .unwrap_or_else(|e| e.into_inner())
251            .clone()
252    }
253
254    /// Stops the background monitoring thread.
255    pub fn stop(&self) {
256        self.stop_flag.store(true, Ordering::Relaxed);
257    }
258
259    /// Returns whether the monitor is still running.
260    #[must_use] 
261    pub fn is_running(&self) -> bool {
262        !self.stop_flag.load(Ordering::Relaxed)
263    }
264}
265
266/// Helper to compute RAM usage percentage from total and free values.
267///
268/// Accepts raw telemetry strings like "16Gi" (total) and "13Gi" (free).
269/// Returns used percentage: ((total - free) / total) * 100.
270fn parse_ram_percent(ram_total: &str, ram_free: &str) -> f32 {
271    let total_val = parse_size_value(ram_total.trim());
272    let free_val = parse_size_value(ram_free.trim());
273
274    if total_val > 0.0 {
275        ((total_val - free_val) / total_val) * 100.0
276    } else {
277        0.0
278    }
279}
280
281/// Parses a size string (e.g., "13Gi", "512Mi", "16384MB") into a numeric value in GB.
282fn parse_size_value(size_str: &str) -> f32 {
283    let size_str = size_str.trim();
284    if size_str.ends_with("Gi") {
285        size_str.trim_end_matches("Gi").parse().unwrap_or(0.0)
286    } else if size_str.ends_with("Mi") {
287        #[allow(clippy::map_unwrap_or)] // parse::<f32>().unwrap_or(0.0) is idiomatic for fallback
288        size_str
289            .trim_end_matches("Mi")
290            .parse::<f32>()
291            .map(|v| v / 1024.0)
292            .unwrap_or(0.0)
293    } else if size_str.ends_with("Ki") {
294        size_str
295            .trim_end_matches("Ki")
296            .parse::<f32>()
297            .map_or(0.0, |v| v / (1024.0 * 1024.0))
298    } else if size_str.ends_with("MB") {
299        size_str
300            .trim_end_matches("MB")
301            .parse::<f32>()
302            .map_or(0.0, |v| v / 1000.0)
303    } else if size_str.ends_with("GB") {
304        size_str
305            .trim_end_matches("GB")
306            .parse::<f32>()
307            .unwrap_or(0.0)
308    } else {
309        0.0
310    }
311}
312
313/// Adds an alert to the alert history (max 100 alerts).
314fn add_alert(alerts: &Arc<RwLock<Vec<HealthAlert>>>, alert: HealthAlert) {
315    #[allow(clippy::expect_used)] // lock poisoning is irrecoverable
316    let mut alerts_vec = alerts.write().expect("Alerts lock poisoned");
317    alerts_vec.push(alert);
318    if alerts_vec.len() > 100 {
319        alerts_vec.remove(0);
320    }
321}
322
323#[cfg(test)]
324#[allow(clippy::float_cmp, clippy::use_self)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn test_health_monitor_lifecycle() {
330        let monitor = HealthMonitor::start().expect("Failed to start monitor");
331        assert!(monitor.is_running());
332        // Stop immediately — verifies start/stop without waiting for 60s cycle
333        monitor.stop();
334        // Give thread time to see the flag (sleep loop checks every 1s)
335        thread::sleep(Duration::from_millis(1100));
336        assert!(!monitor.is_running());
337    }
338
339    #[test]
340    fn test_health_state_defaults() {
341        let state = HealthState::default();
342        assert_eq!(state.cpu_alert_count, 0);
343        assert_eq!(state.ram_alert_count, 0);
344        assert!(!state.ram_increasing);
345        assert!(state.last_ram_percent.is_none());
346    }
347
348    #[test]
349    fn test_cpu_alert_after_consecutive_checks() {
350        let mut state = HealthState::default();
351        // Simulate 5 consecutive minutes of high CPU
352        for _ in 0..5 {
353            state.cpu_percent = 95.0;
354            if state.cpu_percent > CPU_THRESHOLD {
355                state.cpu_alert_count += 1;
356            }
357        }
358        assert_eq!(state.cpu_alert_count, 5);
359    }
360
361    #[test]
362    fn test_ram_alert_uses_ram_counter_not_cpu() {
363        let mut state = HealthState {
364            last_ram_percent: Some(50.0),
365            ..Default::default()
366        };
367        // Simulate RAM increasing each check while CPU is normal
368        #[allow(clippy::cast_precision_loss)]
369        for i in 0..5 {
370            state.ram_percent = 50.0 + (i as f32 + 1.0); // 51, 52, 53, 54, 55
371            state.cpu_percent = 10.0; // CPU is fine
372            if state.ram_percent > state.last_ram_percent.unwrap() {
373                state.ram_increasing = true;
374                state.ram_alert_count += 1;
375            } else {
376                state.ram_increasing = false;
377                state.ram_alert_count = 0;
378            }
379            state.last_ram_percent = Some(state.ram_percent);
380        }
381        // RAM alert should fire after 5 consecutive increases (independent of CPU)
382        assert_eq!(state.ram_alert_count, 5);
383        assert!(state.ram_increasing);
384    }
385
386    #[test]
387    fn test_ram_alert_resets_when_ram_decreases() {
388        let mut state = HealthState {
389            last_ram_percent: Some(50.0),
390            ..Default::default()
391        };
392
393        // RAM increases twice
394        state.ram_percent = 55.0;
395        state.ram_alert_count = 2;
396        state.last_ram_percent = Some(55.0);
397
398        // RAM decreases — counter should reset
399        state.ram_percent = 40.0;
400        if state.ram_percent > state.last_ram_percent.unwrap() {
401            state.ram_increasing = true;
402            state.ram_alert_count += 1;
403        } else {
404            state.ram_increasing = false;
405            state.ram_alert_count = 0;
406        }
407        state.last_ram_percent = Some(state.ram_percent);
408
409        assert_eq!(state.ram_alert_count, 0);
410        assert!(!state.ram_increasing);
411    }
412
413    #[test]
414    fn test_parse_size_value() {
415        assert!((parse_size_value("13Gi") - 13.0).abs() < 0.01);
416        assert!((parse_size_value("512Mi") - 0.5).abs() < 0.01);
417        assert_eq!(parse_size_value("invalid"), 0.0);
418    }
419}