|
| 1 | +use crate::core::{MetricCollector, MetricData, MetricValue}; |
| 2 | +use sysinfo::System; |
| 3 | +use std::collections::HashMap; |
| 4 | + |
| 5 | +pub struct SystemCollector; |
| 6 | + |
| 7 | +impl SystemCollector { |
| 8 | + pub fn new() -> Self { |
| 9 | + SystemCollector |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +impl MetricCollector for SystemCollector { |
| 14 | + fn collect(&self) -> Result<MetricData, Box<dyn std::error::Error>> { |
| 15 | + let mut metrics = HashMap::new(); |
| 16 | + |
| 17 | + if let Some(name) = System::name() { |
| 18 | + metrics.insert("os_name".to_string(), MetricValue::String(name)); |
| 19 | + } |
| 20 | + if let Some(version) = System::os_version() { |
| 21 | + metrics.insert("os_version".to_string(), MetricValue::String(version)); |
| 22 | + } |
| 23 | + if let Some(kernel) = System::kernel_version() { |
| 24 | + metrics.insert("kernel_version".to_string(), MetricValue::String(kernel)); |
| 25 | + } |
| 26 | + if let Some(host) = System::host_name() { |
| 27 | + metrics.insert("hostname".to_string(), MetricValue::String(host)); |
| 28 | + } |
| 29 | + if let Some(arch) = System::cpu_arch() { |
| 30 | + metrics.insert("arch".to_string(), MetricValue::String(arch)); |
| 31 | + } |
| 32 | + |
| 33 | + let uptime_secs = System::uptime(); |
| 34 | + metrics.insert("uptime_seconds".to_string(), MetricValue::Integer(uptime_secs as i64)); |
| 35 | + metrics.insert("uptime_human".to_string(), MetricValue::String(format_uptime(uptime_secs))); |
| 36 | + |
| 37 | + let load = System::load_average(); |
| 38 | + metrics.insert("load_1m".to_string(), MetricValue::Float(load.one)); |
| 39 | + metrics.insert("load_5m".to_string(), MetricValue::Float(load.five)); |
| 40 | + metrics.insert("load_15m".to_string(), MetricValue::Float(load.fifteen)); |
| 41 | + |
| 42 | + Ok(MetricData { |
| 43 | + timestamp: std::time::SystemTime::now(), |
| 44 | + metrics, |
| 45 | + }) |
| 46 | + } |
| 47 | + |
| 48 | + fn name(&self) -> &'static str { |
| 49 | + "system" |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +fn format_uptime(secs: u64) -> String { |
| 54 | + let days = secs / 86400; |
| 55 | + let hours = (secs % 86400) / 3600; |
| 56 | + let minutes = (secs % 3600) / 60; |
| 57 | + |
| 58 | + if days > 0 { |
| 59 | + format!("{}d {}h {}m", days, hours, minutes) |
| 60 | + } else if hours > 0 { |
| 61 | + format!("{}h {}m", hours, minutes) |
| 62 | + } else { |
| 63 | + format!("{}m", minutes) |
| 64 | + } |
| 65 | +} |
0 commit comments