Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6bb350f016 | |||
| 374b126446 | |||
| 76c04633b5 | |||
| 1e0510be81 | |||
| 9a2df906ea | |||
| 6d6beb207d | |||
| 7a68da01f5 | |||
| 5be67fed64 | |||
| cac836601b | |||
| bd22ce265b | |||
| bbc8b7b1cb | |||
| 5dd8cadef3 | |||
| fefe30ec51 | |||
| fb40cce748 | |||
| eaa057b284 | |||
| f23a1b5cec | |||
| 3f98f68b51 | |||
| 3d38a7a984 |
6
Cargo.lock
generated
6
Cargo.lock
generated
@@ -279,7 +279,7 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
|
||||
|
||||
[[package]]
|
||||
name = "cm-dashboard"
|
||||
version = "0.1.172"
|
||||
version = "0.1.187"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@@ -301,7 +301,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cm-dashboard-agent"
|
||||
version = "0.1.172"
|
||||
version = "0.1.187"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -324,7 +324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cm-dashboard-shared"
|
||||
version = "0.1.172"
|
||||
version = "0.1.187"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"serde",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cm-dashboard-agent"
|
||||
version = "0.1.172"
|
||||
version = "0.1.188"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -112,9 +112,12 @@ impl DiskCollector {
|
||||
|
||||
/// Get block devices and their mount points using lsblk
|
||||
async fn get_mount_devices(&self) -> Result<HashMap<String, String>, CollectorError> {
|
||||
let output = Command::new("lsblk")
|
||||
.args(&["-rn", "-o", "NAME,MOUNTPOINT"])
|
||||
.output()
|
||||
use super::run_command_with_timeout;
|
||||
|
||||
let mut cmd = Command::new("lsblk");
|
||||
cmd.args(&["-rn", "-o", "NAME,MOUNTPOINT"]);
|
||||
|
||||
let output = run_command_with_timeout(cmd, 2).await
|
||||
.map_err(|e| CollectorError::SystemRead {
|
||||
path: "block devices".to_string(),
|
||||
error: e.to_string(),
|
||||
@@ -186,8 +189,8 @@ impl DiskCollector {
|
||||
|
||||
/// Get filesystem info for a single mount point
|
||||
fn get_filesystem_info(&self, mount_point: &str) -> Result<(u64, u64), CollectorError> {
|
||||
let output = Command::new("df")
|
||||
.args(&["--block-size=1", mount_point])
|
||||
let output = std::process::Command::new("timeout")
|
||||
.args(&["2", "df", "--block-size=1", mount_point])
|
||||
.output()
|
||||
.map_err(|e| CollectorError::SystemRead {
|
||||
path: format!("df {}", mount_point),
|
||||
@@ -386,7 +389,7 @@ impl DiskCollector {
|
||||
/// Get SMART data for drives
|
||||
async fn get_smart_data_for_drives(&self, physical_drives: &[PhysicalDrive], mergerfs_pools: &[MergerfsPool]) -> HashMap<String, SmartData> {
|
||||
let mut smart_data = HashMap::new();
|
||||
|
||||
|
||||
// Collect all drive names
|
||||
let mut all_drives = std::collections::HashSet::new();
|
||||
for drive in physical_drives {
|
||||
@@ -413,23 +416,26 @@ impl DiskCollector {
|
||||
|
||||
/// Get SMART data for a single drive
|
||||
async fn get_smart_data(&self, drive_name: &str) -> Result<SmartData, CollectorError> {
|
||||
let output = Command::new("sudo")
|
||||
.args(&["smartctl", "-a", &format!("/dev/{}", drive_name)])
|
||||
.output()
|
||||
use super::run_command_with_timeout;
|
||||
|
||||
// Use direct smartctl (no sudo) - service has CAP_SYS_RAWIO and CAP_SYS_ADMIN capabilities
|
||||
// For NVMe drives, specify device type explicitly
|
||||
let mut cmd = Command::new("smartctl");
|
||||
if drive_name.starts_with("nvme") {
|
||||
cmd.args(&["-d", "nvme", "-a", &format!("/dev/{}", drive_name)]);
|
||||
} else {
|
||||
cmd.args(&["-a", &format!("/dev/{}", drive_name)]);
|
||||
}
|
||||
|
||||
let output = run_command_with_timeout(cmd, 3).await
|
||||
.map_err(|e| CollectorError::SystemRead {
|
||||
path: format!("SMART data for {}", drive_name),
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
|
||||
let output_str = String::from_utf8_lossy(&output.stdout);
|
||||
let error_str = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
// Debug logging for SMART command results
|
||||
debug!("SMART output for {}: status={}, stdout_len={}, stderr={}",
|
||||
drive_name, output.status, output_str.len(), error_str);
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
debug!("SMART command failed for {}: {}", drive_name, error_str);
|
||||
// Return unknown data rather than failing completely
|
||||
return Ok(SmartData {
|
||||
health: "UNKNOWN".to_string(),
|
||||
@@ -756,9 +762,9 @@ impl DiskCollector {
|
||||
|
||||
/// Get drive information for a mount path
|
||||
fn get_drive_info_for_path(&self, path: &str) -> anyhow::Result<PoolDrive> {
|
||||
// Use lsblk to find the backing device
|
||||
let output = Command::new("lsblk")
|
||||
.args(&["-rn", "-o", "NAME,MOUNTPOINT"])
|
||||
// Use lsblk to find the backing device with timeout
|
||||
let output = Command::new("timeout")
|
||||
.args(&["2", "lsblk", "-rn", "-o", "NAME,MOUNTPOINT"])
|
||||
.output()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to run lsblk: {}", e))?;
|
||||
|
||||
|
||||
@@ -105,12 +105,12 @@ impl MemoryCollector {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Get usage data for all tmpfs mounts at once using df
|
||||
let mut df_args = vec!["df", "--output=target,size,used", "--block-size=1"];
|
||||
// Get usage data for all tmpfs mounts at once using df (with 2 second timeout)
|
||||
let mut df_args = vec!["2", "df", "--output=target,size,used", "--block-size=1"];
|
||||
df_args.extend(tmpfs_mounts.iter().map(|s| s.as_str()));
|
||||
|
||||
let df_output = std::process::Command::new(df_args[0])
|
||||
.args(&df_args[1..])
|
||||
let df_output = std::process::Command::new("timeout")
|
||||
.args(&df_args[..])
|
||||
.output()
|
||||
.map_err(|e| CollectorError::SystemRead {
|
||||
path: "tmpfs mounts".to_string(),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use async_trait::async_trait;
|
||||
use cm_dashboard_shared::{AgentData};
|
||||
|
||||
use std::process::{Command, Output};
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
pub mod backup;
|
||||
pub mod cpu;
|
||||
@@ -13,6 +15,20 @@ pub mod systemd;
|
||||
|
||||
pub use error::CollectorError;
|
||||
|
||||
/// Run a command with a timeout to prevent blocking
|
||||
pub async fn run_command_with_timeout(mut cmd: Command, timeout_secs: u64) -> std::io::Result<Output> {
|
||||
let timeout_duration = Duration::from_secs(timeout_secs);
|
||||
|
||||
match timeout(timeout_duration, tokio::task::spawn_blocking(move || cmd.output())).await {
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(e)) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
|
||||
Err(_) => Err(std::io::Error::new(
|
||||
std::io::ErrorKind::TimedOut,
|
||||
format!("Command timed out after {} seconds", timeout_secs)
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Base trait for all collectors with direct structured data output
|
||||
#[async_trait]
|
||||
|
||||
@@ -51,7 +51,7 @@ impl NetworkCollector {
|
||||
|
||||
/// Get the primary physical interface (the one with default route)
|
||||
fn get_primary_physical_interface() -> Option<String> {
|
||||
match Command::new("ip").args(["route", "show", "default"]).output() {
|
||||
match Command::new("timeout").args(["2", "ip", "route", "show", "default"]).output() {
|
||||
Ok(output) if output.status.success() => {
|
||||
let output_str = String::from_utf8_lossy(&output.stdout);
|
||||
// Parse: "default via 192.168.1.1 dev eno1 ..."
|
||||
@@ -110,7 +110,7 @@ impl NetworkCollector {
|
||||
// Parse VLAN configuration
|
||||
let vlan_map = Self::parse_vlan_config();
|
||||
|
||||
match Command::new("ip").args(["-j", "addr"]).output() {
|
||||
match Command::new("timeout").args(["2", "ip", "-j", "addr"]).output() {
|
||||
Ok(output) if output.status.success() => {
|
||||
let json_str = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
|
||||
@@ -43,8 +43,8 @@ impl NixOSCollector {
|
||||
match fs::read_to_string("/etc/hostname") {
|
||||
Ok(hostname) => Some(hostname.trim().to_string()),
|
||||
Err(_) => {
|
||||
// Fallback to hostname command
|
||||
match Command::new("hostname").output() {
|
||||
// Fallback to hostname command (with 2 second timeout)
|
||||
match Command::new("timeout").args(["2", "hostname"]).output() {
|
||||
Ok(output) => Some(String::from_utf8_lossy(&output.stdout).trim().to_string()),
|
||||
Err(_) => None,
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use cm_dashboard_shared::{AgentData, ServiceData, SubServiceData, SubServiceMetr
|
||||
use std::process::Command;
|
||||
use std::sync::RwLock;
|
||||
use std::time::Instant;
|
||||
use tracing::debug;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::{Collector, CollectorError};
|
||||
use crate::config::SystemdConfig;
|
||||
@@ -117,8 +117,37 @@ impl SystemdCollector {
|
||||
}
|
||||
}
|
||||
|
||||
// Docker containers are now collected as top-level services below
|
||||
// Keeping nginx as sub-services for now
|
||||
if service_name.contains("docker") && active_status == "active" {
|
||||
let docker_containers = self.get_docker_containers();
|
||||
for (container_name, container_status) in docker_containers {
|
||||
// For now, docker containers have no additional metrics
|
||||
// Future: could add memory_mb, cpu_percent, restart_count, etc.
|
||||
let metrics = Vec::new();
|
||||
|
||||
sub_services.push(SubServiceData {
|
||||
name: container_name.clone(),
|
||||
service_status: self.calculate_service_status(&container_name, &container_status),
|
||||
metrics,
|
||||
});
|
||||
}
|
||||
|
||||
// Add Docker images
|
||||
let docker_images = self.get_docker_images();
|
||||
for (image_name, image_status, image_size_str, image_size_mb) in docker_images {
|
||||
let mut metrics = Vec::new();
|
||||
metrics.push(SubServiceMetric {
|
||||
label: "size".to_string(),
|
||||
value: image_size_mb,
|
||||
unit: Some("MB".to_string()),
|
||||
});
|
||||
|
||||
sub_services.push(SubServiceData {
|
||||
name: format!("{} ({})", image_name, image_size_str),
|
||||
service_status: self.calculate_service_status(&image_name, &image_status),
|
||||
metrics,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create complete service data
|
||||
let service_data = ServiceData {
|
||||
@@ -140,20 +169,9 @@ impl SystemdCollector {
|
||||
}
|
||||
}
|
||||
|
||||
// Collect Docker containers as top-level services
|
||||
let docker_containers = self.get_docker_containers();
|
||||
for (container_name, container_status) in docker_containers {
|
||||
let service_data = ServiceData {
|
||||
name: container_name.clone(),
|
||||
memory_mb: 0.0, // TODO: Could add container memory via docker stats
|
||||
disk_gb: 0.0, // TODO: Could add container disk usage
|
||||
user_stopped: false,
|
||||
service_status: self.calculate_service_status(&container_name, &container_status),
|
||||
sub_services: Vec::new(),
|
||||
};
|
||||
agent_data.services.push(service_data.clone());
|
||||
complete_service_data.push(service_data);
|
||||
}
|
||||
// Sort services alphabetically by name
|
||||
agent_data.services.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
complete_service_data.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
|
||||
// Update cached state
|
||||
{
|
||||
@@ -233,18 +251,18 @@ impl SystemdCollector {
|
||||
|
||||
/// Auto-discover interesting services to monitor
|
||||
fn discover_services_internal(&self) -> Result<(Vec<String>, std::collections::HashMap<String, ServiceStatusInfo>)> {
|
||||
// First: Get all service unit files
|
||||
let unit_files_output = Command::new("systemctl")
|
||||
.args(&["list-unit-files", "--type=service", "--no-pager", "--plain"])
|
||||
// First: Get all service unit files (with 3 second timeout)
|
||||
let unit_files_output = Command::new("timeout")
|
||||
.args(&["3", "systemctl", "list-unit-files", "--type=service", "--no-pager", "--plain"])
|
||||
.output()?;
|
||||
|
||||
if !unit_files_output.status.success() {
|
||||
return Err(anyhow::anyhow!("systemctl list-unit-files command failed"));
|
||||
}
|
||||
|
||||
// Second: Get runtime status of all units
|
||||
let units_status_output = Command::new("systemctl")
|
||||
.args(&["list-units", "--type=service", "--all", "--no-pager", "--plain"])
|
||||
// Second: Get runtime status of all units (with 3 second timeout)
|
||||
let units_status_output = Command::new("timeout")
|
||||
.args(&["3", "systemctl", "list-units", "--type=service", "--all", "--no-pager", "--plain"])
|
||||
.output()?;
|
||||
|
||||
if !units_status_output.status.success() {
|
||||
@@ -340,16 +358,16 @@ impl SystemdCollector {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to systemctl if not in cache
|
||||
let output = Command::new("systemctl")
|
||||
.args(&["is-active", &format!("{}.service", service)])
|
||||
// Fallback to systemctl if not in cache (with 2 second timeout)
|
||||
let output = Command::new("timeout")
|
||||
.args(&["2", "systemctl", "is-active", &format!("{}.service", service)])
|
||||
.output()?;
|
||||
|
||||
let active_status = String::from_utf8(output.stdout)?.trim().to_string();
|
||||
|
||||
// Get more detailed info
|
||||
let output = Command::new("systemctl")
|
||||
.args(&["show", &format!("{}.service", service), "--property=LoadState,ActiveState,SubState"])
|
||||
// Get more detailed info (with 2 second timeout)
|
||||
let output = Command::new("timeout")
|
||||
.args(&["2", "systemctl", "show", &format!("{}.service", service), "--property=LoadState,ActiveState,SubState"])
|
||||
.output()?;
|
||||
|
||||
let detailed_info = String::from_utf8(output.stdout)?;
|
||||
@@ -401,7 +419,7 @@ impl SystemdCollector {
|
||||
if let Some(dirs) = self.config.service_directories.get(service_name) {
|
||||
// Service has configured paths - use the first accessible one
|
||||
for dir in dirs {
|
||||
if let Some(size) = self.get_directory_size(dir) {
|
||||
if let Some(size) = self.get_directory_size(dir).await {
|
||||
return Ok(size);
|
||||
}
|
||||
}
|
||||
@@ -409,9 +427,9 @@ impl SystemdCollector {
|
||||
return Ok(0.0);
|
||||
}
|
||||
|
||||
// No configured path - try to get WorkingDirectory from systemctl
|
||||
let output = Command::new("systemctl")
|
||||
.args(&["show", &format!("{}.service", service_name), "--property=WorkingDirectory"])
|
||||
// No configured path - try to get WorkingDirectory from systemctl (with 2 second timeout)
|
||||
let output = Command::new("timeout")
|
||||
.args(&["2", "systemctl", "show", &format!("{}.service", service_name), "--property=WorkingDirectory"])
|
||||
.output()
|
||||
.map_err(|e| CollectorError::SystemRead {
|
||||
path: format!("WorkingDirectory for {}", service_name),
|
||||
@@ -423,7 +441,7 @@ impl SystemdCollector {
|
||||
if line.starts_with("WorkingDirectory=") && !line.contains("[not set]") {
|
||||
let dir = line.strip_prefix("WorkingDirectory=").unwrap_or("");
|
||||
if !dir.is_empty() && dir != "/" {
|
||||
return Ok(self.get_directory_size(dir).unwrap_or(0.0));
|
||||
return Ok(self.get_directory_size(dir).await.unwrap_or(0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -431,18 +449,23 @@ impl SystemdCollector {
|
||||
Ok(0.0)
|
||||
}
|
||||
|
||||
/// Get size of a directory in GB
|
||||
fn get_directory_size(&self, path: &str) -> Option<f32> {
|
||||
let output = Command::new("sudo")
|
||||
.args(&["du", "-sb", path])
|
||||
.output()
|
||||
.ok()?;
|
||||
/// Get size of a directory in GB (with 2 second timeout)
|
||||
async fn get_directory_size(&self, path: &str) -> Option<f32> {
|
||||
use super::run_command_with_timeout;
|
||||
|
||||
// Use -s (summary) and --apparent-size for speed, 2 second timeout
|
||||
let mut cmd = Command::new("sudo");
|
||||
cmd.args(&["du", "-s", "--apparent-size", "--block-size=1", path]);
|
||||
|
||||
let output = run_command_with_timeout(cmd, 2).await.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
// Log permission errors for debugging but don't spam logs
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if stderr.contains("Permission denied") {
|
||||
debug!("Permission denied accessing directory: {}", path);
|
||||
} else if stderr.contains("timed out") {
|
||||
warn!("Directory size check timed out for {}", path);
|
||||
} else {
|
||||
debug!("Failed to get size for directory {}: {}", path, stderr);
|
||||
}
|
||||
@@ -759,10 +782,10 @@ impl SystemdCollector {
|
||||
fn get_docker_containers(&self) -> Vec<(String, String)> {
|
||||
let mut containers = Vec::new();
|
||||
|
||||
// Check if docker is available (use sudo for permissions)
|
||||
// Use -a to show ALL containers (running and stopped)
|
||||
let output = Command::new("sudo")
|
||||
.args(&["docker", "ps", "-a", "--format", "{{.Names}},{{.Status}}"])
|
||||
// Check if docker is available (cm-agent user is in docker group)
|
||||
// Use -a to show ALL containers (running and stopped) with 3 second timeout
|
||||
let output = Command::new("timeout")
|
||||
.args(&["3", "docker", "ps", "-a", "--format", "{{.Names}},{{.Status}}"])
|
||||
.output();
|
||||
|
||||
let output = match output {
|
||||
@@ -799,6 +822,87 @@ impl SystemdCollector {
|
||||
|
||||
containers
|
||||
}
|
||||
|
||||
/// Get docker images as sub-services
|
||||
fn get_docker_images(&self) -> Vec<(String, String, String, f32)> {
|
||||
let mut images = Vec::new();
|
||||
// Check if docker is available (cm-agent user is in docker group) with 3 second timeout
|
||||
let output = Command::new("timeout")
|
||||
.args(&["3", "docker", "images", "--format", "{{.Repository}}:{{.Tag}},{{.Size}}"])
|
||||
.output();
|
||||
|
||||
let output = match output {
|
||||
Ok(out) if out.status.success() => out,
|
||||
Ok(_) => {
|
||||
return images;
|
||||
}
|
||||
Err(_) => {
|
||||
return images;
|
||||
}
|
||||
};
|
||||
|
||||
let output_str = match String::from_utf8(output.stdout) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return images,
|
||||
};
|
||||
|
||||
for line in output_str.lines() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let parts: Vec<&str> = line.split(',').collect();
|
||||
if parts.len() >= 2 {
|
||||
let image_name = parts[0].trim();
|
||||
let size_str = parts[1].trim();
|
||||
|
||||
// Skip <none>:<none> images (dangling images)
|
||||
if image_name.contains("<none>") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parse size to MB (sizes come as "142MB", "1.5GB", "512kB", etc.)
|
||||
let size_mb = self.parse_docker_size(size_str);
|
||||
|
||||
images.push((
|
||||
format!("image_{}", image_name),
|
||||
"active".to_string(), // Images are always "active" (present)
|
||||
size_str.to_string(),
|
||||
size_mb
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
images
|
||||
}
|
||||
|
||||
/// Parse Docker size string to MB
|
||||
fn parse_docker_size(&self, size_str: &str) -> f32 {
|
||||
let size_upper = size_str.to_uppercase();
|
||||
|
||||
// Extract numeric part and unit
|
||||
let mut num_str = String::new();
|
||||
let mut unit = String::new();
|
||||
|
||||
for ch in size_upper.chars() {
|
||||
if ch.is_ascii_digit() || ch == '.' {
|
||||
num_str.push(ch);
|
||||
} else if ch.is_alphabetic() {
|
||||
unit.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
let value: f32 = num_str.parse().unwrap_or(0.0);
|
||||
|
||||
// Convert to MB
|
||||
match unit.as_str() {
|
||||
"KB" | "K" => value / 1024.0,
|
||||
"MB" | "M" => value,
|
||||
"GB" | "G" => value * 1024.0,
|
||||
"TB" | "T" => value * 1024.0 * 1024.0,
|
||||
_ => value, // Assume bytes if no unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cm-dashboard"
|
||||
version = "0.1.172"
|
||||
version = "0.1.188"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -215,7 +215,7 @@ impl Dashboard {
|
||||
|
||||
// Update TUI with new metrics (only if not headless)
|
||||
if let Some(ref mut tui_app) = self.tui_app {
|
||||
tui_app.update_metrics(&self.metric_store);
|
||||
tui_app.update_metrics(&mut self.metric_store);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,14 @@ use tracing::{debug, info, warn};
|
||||
|
||||
use super::MetricDataPoint;
|
||||
|
||||
/// ZMQ communication statistics per host
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ZmqStats {
|
||||
pub packets_received: u64,
|
||||
pub last_packet_time: Instant,
|
||||
pub last_packet_age_secs: f64,
|
||||
}
|
||||
|
||||
/// Central metric storage for the dashboard
|
||||
pub struct MetricStore {
|
||||
/// Current structured data: hostname -> AgentData
|
||||
@@ -13,6 +21,8 @@ pub struct MetricStore {
|
||||
historical_metrics: HashMap<String, Vec<MetricDataPoint>>,
|
||||
/// Last heartbeat timestamp per host
|
||||
last_heartbeat: HashMap<String, Instant>,
|
||||
/// ZMQ communication statistics per host
|
||||
zmq_stats: HashMap<String, ZmqStats>,
|
||||
/// Configuration
|
||||
max_metrics_per_host: usize,
|
||||
history_retention: Duration,
|
||||
@@ -24,6 +34,7 @@ impl MetricStore {
|
||||
current_agent_data: HashMap::new(),
|
||||
historical_metrics: HashMap::new(),
|
||||
last_heartbeat: HashMap::new(),
|
||||
zmq_stats: HashMap::new(),
|
||||
max_metrics_per_host,
|
||||
history_retention: Duration::from_secs(history_retention_hours * 3600),
|
||||
}
|
||||
@@ -44,6 +55,16 @@ impl MetricStore {
|
||||
self.last_heartbeat.insert(hostname.clone(), now);
|
||||
debug!("Updated heartbeat for host {}", hostname);
|
||||
|
||||
// Update ZMQ stats
|
||||
let stats = self.zmq_stats.entry(hostname.clone()).or_insert(ZmqStats {
|
||||
packets_received: 0,
|
||||
last_packet_time: now,
|
||||
last_packet_age_secs: 0.0,
|
||||
});
|
||||
stats.packets_received += 1;
|
||||
stats.last_packet_time = now;
|
||||
stats.last_packet_age_secs = 0.0; // Just received
|
||||
|
||||
// Add to history
|
||||
let host_history = self
|
||||
.historical_metrics
|
||||
@@ -65,6 +86,15 @@ impl MetricStore {
|
||||
self.current_agent_data.get(hostname)
|
||||
}
|
||||
|
||||
/// Get ZMQ communication statistics for a host
|
||||
pub fn get_zmq_stats(&mut self, hostname: &str) -> Option<ZmqStats> {
|
||||
let now = Instant::now();
|
||||
self.zmq_stats.get_mut(hostname).map(|stats| {
|
||||
// Update packet age
|
||||
stats.last_packet_age_secs = now.duration_since(stats.last_packet_time).as_secs_f64();
|
||||
stats.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Get connected hosts (hosts with recent heartbeats)
|
||||
pub fn get_connected_hosts(&self, timeout: Duration) -> Vec<String> {
|
||||
|
||||
@@ -100,7 +100,7 @@ impl TuiApp {
|
||||
}
|
||||
|
||||
/// Update widgets with structured data from store (only for current host)
|
||||
pub fn update_metrics(&mut self, metric_store: &MetricStore) {
|
||||
pub fn update_metrics(&mut self, metric_store: &mut MetricStore) {
|
||||
if let Some(hostname) = self.current_host.clone() {
|
||||
// Get structured data for this host
|
||||
if let Some(agent_data) = metric_store.get_agent_data(&hostname) {
|
||||
@@ -110,6 +110,14 @@ impl TuiApp {
|
||||
host_widgets.system_widget.update_from_agent_data(agent_data);
|
||||
host_widgets.services_widget.update_from_agent_data(agent_data);
|
||||
|
||||
// Update ZMQ stats
|
||||
if let Some(zmq_stats) = metric_store.get_zmq_stats(&hostname) {
|
||||
host_widgets.system_widget.update_zmq_stats(
|
||||
zmq_stats.packets_received,
|
||||
zmq_stats.last_packet_age_secs
|
||||
);
|
||||
}
|
||||
|
||||
host_widgets.last_update = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ pub struct SystemWidget {
|
||||
nixos_build: Option<String>,
|
||||
agent_hash: Option<String>,
|
||||
|
||||
// ZMQ communication stats
|
||||
zmq_packets_received: Option<u64>,
|
||||
zmq_last_packet_age: Option<f64>,
|
||||
|
||||
// Network interfaces
|
||||
network_interfaces: Vec<cm_dashboard_shared::NetworkInterfaceData>,
|
||||
|
||||
@@ -92,6 +96,8 @@ impl SystemWidget {
|
||||
Self {
|
||||
nixos_build: None,
|
||||
agent_hash: None,
|
||||
zmq_packets_received: None,
|
||||
zmq_last_packet_age: None,
|
||||
network_interfaces: Vec::new(),
|
||||
cpu_load_1min: None,
|
||||
cpu_load_5min: None,
|
||||
@@ -154,6 +160,12 @@ impl SystemWidget {
|
||||
pub fn _get_agent_hash(&self) -> Option<&String> {
|
||||
self.agent_hash.as_ref()
|
||||
}
|
||||
|
||||
/// Update ZMQ communication statistics
|
||||
pub fn update_zmq_stats(&mut self, packets_received: u64, last_packet_age_secs: f64) {
|
||||
self.zmq_packets_received = Some(packets_received);
|
||||
self.zmq_last_packet_age = Some(last_packet_age_secs);
|
||||
}
|
||||
}
|
||||
|
||||
use super::Widget;
|
||||
@@ -796,6 +808,18 @@ impl SystemWidget {
|
||||
Span::styled(format!("Agent: {}", agent_version_text), Typography::secondary())
|
||||
]));
|
||||
|
||||
// ZMQ communication stats
|
||||
if let (Some(packets), Some(age)) = (self.zmq_packets_received, self.zmq_last_packet_age) {
|
||||
let age_text = if age < 1.0 {
|
||||
format!("{:.0}ms ago", age * 1000.0)
|
||||
} else {
|
||||
format!("{:.1}s ago", age)
|
||||
};
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled(format!("ZMQ: {} pkts, last {}", packets, age_text), Typography::secondary())
|
||||
]));
|
||||
}
|
||||
|
||||
// CPU section
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled("CPU:", Typography::widget_title())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cm-dashboard-shared"
|
||||
version = "0.1.172"
|
||||
version = "0.1.188"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
Reference in New Issue
Block a user